Subversion Repositories FlightCtrl

Rev

Rev 1821 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Copyright (c) 04.2007 Holger Buss
// + Nur für den privaten Gebrauch
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
// + bzgl. der Nutzungsbedingungen aufzunehmen.
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
// + Verkauf von Luftbildaufnahmen, usw.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
// + eindeutig als Ursprung verlinkt werden
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
// + Benutzung auf eigene Gefahr
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
// + mit unserer Zustimmung zulässig
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
// + this list of conditions and the following disclaimer.
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
// +     from this software without specific prior written permission.
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
// +     for non-commercial use (directly or indirectly)
// +     Commercial use (for excample: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
// +     with our written permission
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
// +     clearly linked as origin
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// +  POSSIBILITY OF SUCH DAMAGE.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/twi.h>
#include <util/delay.h>
//#include "eeprom.h"
#include "twimaster.h"
//#include "analog.h"
#include "configuration.h"
#include "printf_P.h"

volatile uint8_t twi_state      = TWI_STATE_MOTOR_TX;
volatile uint8_t dac_channel    = 0;
volatile uint8_t motor_write    = 0;
volatile uint8_t motor_read     = 0;
volatile uint16_t I2CTimeout    = 100;
uint8_t missingMotor  = 0;

MotorData_t Motor[MAX_MOTORS];

volatile uint8_t DACValues[4];
uint8_t DACChannel = 0;

#define SCL_CLOCK  200000L
#define I2C_TIMEOUT 30000

/**************************************************
 * Initialize I2C (TWI)                        
 **************************************************/

void I2C_init(void) {
  uint8_t i;
  uint8_t sreg = SREG;
  cli();
 
  // SDA is INPUT
  DDRC  &= ~(1<<DDC1);
  // SCL is output
  DDRC |= (1<<DDC0);
  // pull up SDA
  PORTC |= (1<<PORTC0)|(1<<PORTC1);
 
  // TWI Status Register
  // prescaler 1 (TWPS1 = 0, TWPS0 = 0)
  TWSR &= ~((1<<TWPS1)|(1<<TWPS0));
 
  // set TWI Bit Rate Register
  TWBR = ((SYSCLK/SCL_CLOCK)-16)/2;
 
  twi_state             = TWI_STATE_MOTOR_TX;
  motor_write           = 0;
  motor_read            = 0;
 
  for(i=0; i < MAX_MOTORS; i++) {
    Motor[i].SetPoint   = 0;
    Motor[i].Present    = 0;
    Motor[i].Error      = 0;
    Motor[i].MaxPWM     = 0;
  }
 
  SREG = sreg;
}

/****************************************
 * Start I2C                          
 ****************************************/

void I2C_Start(uint8_t start_state) {
  twi_state = start_state;
  // TWI Control Register
  // clear TWI interrupt flag (TWINT=1)
  // disable TWI Acknowledge Bit (TWEA = 0)
  // enable TWI START Condition Bit (TWSTA = 1), MASTER
  // disable TWI STOP Condition Bit (TWSTO = 0)
  // disable TWI Write Collision Flag (TWWC = 0)
  // enable i2c (TWEN = 1)
  // enable TWI Interrupt (TWIE = 1)
  TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN) | (1<<TWIE);
}

/****************************************
 * Stop I2C                          
 ****************************************/

void I2C_Stop(uint8_t start_state) {
  twi_state = start_state;
  // TWI Control Register
  // clear TWI interrupt flag (TWINT=1)
  // disable TWI Acknowledge Bit (TWEA = 0)
  // diable TWI START Condition Bit (TWSTA = 1), no MASTER
  // enable TWI STOP Condition Bit (TWSTO = 1)
  // disable TWI Write Collision Flag (TWWC = 0)
  // enable i2c (TWEN = 1)
  // disable TWI Interrupt (TWIE = 0)
  TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN);
}

/****************************************
 *    Write to I2C                      
 ****************************************/

void I2C_WriteByte(int8_t byte) {
  // move byte to send into TWI Data Register
  TWDR = byte;
  // clear interrupt flag (TWINT = 1)
  // enable i2c bus (TWEN = 1)
  // enable interrupt (TWIE = 1)
  TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWIE);
}

/****************************************
 * Receive byte and send ACK        
 ****************************************/

void I2C_ReceiveByte(void) {
  TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWIE) | (1<<TWEA);
}

/****************************************
 * I2C receive last byte and send no ACK
 ****************************************/

void I2C_ReceiveLastByte(void){
  TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWIE);
}

/****************************************
 * Reset I2C                        
 ****************************************/

void I2C_Reset(void) {
  // stop i2c bus
  I2C_Stop(TWI_STATE_MOTOR_TX);
  twi_state             = 0;
  motor_write   = TWDR;
  motor_write   = 0;
  motor_read            = 0;
  TWCR = (1<<TWINT); // reset to original state incl. interrupt flag reset
  TWAMR = 0;
  TWAR = 0;
  TWDR = 0;
  TWSR = 0;
  TWBR = 0;
  I2C_init();
  I2C_Start(TWI_STATE_MOTOR_TX);
}

/****************************************
 * I2C ISR
 ****************************************/

ISR (TWI_vect) {
  static uint8_t missing_motor  = 0;
  switch (twi_state++) { // First i2c_start from SendMotorData()
    // Master Transmit
  case 0: // TWI_STATE_MOTOR_TX
    // skip motor if not used in mixer
    while((Mixer.Motor[motor_write][MIX_THROTTLE] <= 0) && (motor_write < MAX_MOTORS)) motor_write++;
    if(motor_write >= MAX_MOTORS) { // writing finished, read now
      motor_write = 0;
      twi_state = TWI_STATE_MOTOR_RX;
      I2C_WriteByte(0x53 + (motor_read * 2)); // select slave adress in rx mode
    }
    else I2C_WriteByte(0x52 + (motor_write * 2)); // select slave adress in tx mode
    break;
  case 1: // Send Data to Slave
    I2C_WriteByte(Motor[motor_write].SetPoint); // transmit rotation rate setpoint
    break;
  case 2: // repeat case 0+1 for all motors
    if(TWSR == TW_MT_DATA_NACK) { // Data transmitted, NACK received
      if(!missing_motor) missing_motor = motor_write + 1;
      if(++Motor[motor_write].Error == 0) Motor[motor_write].Error = 255; // increment error counter and handle overflow
    }
    I2C_Stop(TWI_STATE_MOTOR_TX);
    I2CTimeout = 10;
    motor_write++; // next motor
    I2C_Start(TWI_STATE_MOTOR_TX); // Repeated start -> switch slave or switch Master Transmit -> Master Receive
    break;
    // Master Receive Data
  case 3:
    if(TWSR != TW_MR_SLA_ACK) { //  SLA+R transmitted, if not ACK received
      // no response from the addressed slave received
      Motor[motor_read].Present = 0;
      motor_read++; // next motor
      if(motor_read >= MAX_MOTORS) motor_read = 0; // restart reading of first motor if we have reached the last one
      I2C_Stop(TWI_STATE_MOTOR_TX);
    } else {
      Motor[motor_read].Present = ('1' - '-') + motor_read;
      I2C_ReceiveByte(); //Transmit 1st byte
    }
    missingMotor = missing_motor;
    missing_motor = 0;
    break;
  case 4: //Read 1st byte and transmit 2nd Byte
    Motor[motor_read].Current = TWDR;
    I2C_ReceiveLastByte(); // nack
    break;
  case 5:
    //Read 2nd byte
    Motor[motor_read].MaxPWM = TWDR;
    motor_read++; // next motor
    if(motor_read >= MAX_MOTORS) motor_read = 0; // restart reading of first motor if we have reached the last one
    I2C_Stop(TWI_STATE_MOTOR_TX);
    break;
   
    // Writing ADC values.
  case 7:
    I2C_WriteByte(0x98); // Address the DAC
    break;
   
  case 8:
    I2C_WriteByte(0x10 + (DACChannel << 1)); // Select DAC Channel (0x10 = A, 0x12 = B, 0x14 = C)
    break;
   
  case 9:
    I2C_WriteByte(DACValues[DACChannel]);
    break;
 
  case 10:
    I2C_WriteByte(0x80); // 2nd byte for all channels is 0x80
    break;
       
  case 11:
    I2C_Stop(TWI_STATE_MOTOR_TX);
    I2CTimeout = 10;
    // repeat case 7...10 until all DAC Channels are updated
    if(DACChannel < 2) {
      DACChannel ++;    // jump to next channel
      I2C_Start(TWI_STATE_GYRO_OFFSET_TX);              // start transmission for next channel
    } else {
      DACChannel = 0; // reset dac channel counter
    }
    break;
   
  default:
    I2C_Stop(TWI_STATE_MOTOR_TX);
    I2CTimeout = 10;
    motor_write = 0;
    motor_read = 0;
  }
}

extern void twi_diagnostics(void) {
  // Check connected BL-Ctrls
  uint8_t i;
 
  printf("\n\rFound BL-Ctrl: ");
 
  for(i = 0; i < MAX_MOTORS; i++) {
    Motor[i].SetPoint = 0;
  }

  I2C_Start(TWI_STATE_MOTOR_TX);
  _delay_ms(2);
 
  motor_read = 0;  // read the first I2C-Data

  for(i = 0; i < MAX_MOTORS; i++) {
    I2C_Start(TWI_STATE_MOTOR_TX);
    _delay_ms(2);
    if(Motor[i].Present) printf("%d ",i+1);
  }

  for(i = 0; i < MAX_MOTORS; i++) {
    if(!Motor[i].Present && Mixer.Motor[i][MIX_THROTTLE] > 0) printf("\n\r\n\r!! MISSING BL-CTRL: %d !!",i + 1);
    Motor[i].Error = 0;
  }
}