Subversion Repositories MK3Mag

Rev

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

/*#######################################################################################
MK3Mag 3D-Magnet sensor
!!! THIS IS NOT FREE SOFTWARE !!!
#######################################################################################*/

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Copyright (c) 05.2008 Holger Buss
// + Thanks to Ilja Fähnrich (P_Latzhalter)
// + Nur für den privaten Gebrauch
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
// + mit unserer Zustimmung zulässig
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + 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.
// + AUSNAHME: Ein bei www.mikrokopter.de erworbener vorbestückter MK3Mag darf als Baugruppe auch in kommerziellen Systemen verbaut werden
// + Im Zweifelsfall bitte anfragen bei: info@mikrokopter.de
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + 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 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.
// +   * PORTING this software (or parts of it) to systems (other than hardware from www.mikrokopter.de) is NOT allowed
// +   * 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
// +     Exception: A preassembled MK3Mag, purchased from www.mikrokopter.de may be used as a part of commercial systems
// +     In case of doubt please contact: info@MikroKopter.de
// +   * If sources or documentations are redistributet on other webpages, our webpage (http://www.MikroKopter.de) must be
// +     clearly linked as origin
// +  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 "twislave.h"
#include "uart.h"
#include "main.h"
#include "timer0.h"
#include "led.h"


volatile uint8_t I2C_RxBufferSize = 0, I2C_TxBufferSize = 0;
volatile uint8_t *I2C_TxBuffer = 0, *I2C_RxBuffer = 0;
volatile uint8_t Tx_Idx = 0, Rx_Idx = 0;



struct I2C_Heading_t       I2C_Heading;
struct I2C_WriteAttitude_t I2C_WriteAttitude;
struct I2C_Mag_t           I2C_Mag;
struct I2C_Version_t       I2C_Version;
struct I2C_WriteCal_t      I2C_WriteCal;


void I2C_Init(void)
{

        uint8_t sreg;

        // backup status register
        sreg = SREG;
    // disable global interrupts
        cli();

        // SCK/SCL and  MISO/SDA are at put together on the same connector pin in the schematic

        // set PB4 (SCK) and PB5 (MISO) as input pull up
        DDRB &= ~((1<<DDB4)|(1<<DDB5));
        PORTB |= ((1<<PORTB4)|(1<<PORTB5));

        // set PC4 (SDA) and PC5 (SCL) as input tristate
        DDRC &= ~((1<<DDC4)|(1<<DDC5));
        PORTC &= ~((1<<PORTC4)|(1<<PORTC5));

        I2C_TxBuffer = 0;
        Tx_Idx = 0;
        I2C_TxBufferSize = 0;
        I2C_RxBuffer = 0;
        Rx_Idx = 0;
        I2C_RxBufferSize = 0;



        TWCR &= ~(1<<TWSTA)|(1<<TWSTO);
        TWCR|= (1<<TWEA) | (1<<TWEN)|(1<<TWIE);

        // set own address
        // set own address in the upper 7 bits
    TWAR = I2C_SLAVE_ADDRESS; // set own address only the upper 7 bits are relevant
        // TWI Control Register
        // enable TWI Acknowledge Bit (TWEA = 1)
        // disable TWI START Condition Bit (TWSTA = 0), SLAVE
        // disable TWI  STOP Condition Bit (TWSTO = 0), SLAVE
        // enable TWI (TWEN = 1)
        // enable TWI Interrupt (TWIE = 1)
        TWCR |= (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(1<<TWEA)|(0<<TWSTA)|(1<<TWSTO)|(0<<TWWC);
        // update version info
        I2C_Version.Major = VERSION_MAJOR;
        I2C_Version.Minor = VERSION_MINOR;
        I2C_Version.Compatible = I2C_PROTOCOL_COMP;

        // resore status register
        SREG = sreg;
}

// send ACK after recieving a byte / ACK is expected after transmitting a byte
#define TWCR_ACK TWCR           = (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(1<<TWEA)|(0<<TWSTA)|(0<<TWSTO)|(0<<TWWC)
// send no ACK after recieving a byte / No ACK is expected after transmitting a byte
#define TWCR_NACK TWCR          = (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(0<<TWEA)|(0<<TWSTA)|(0<<TWSTO)|(0<<TWWC)
// switched to the non adressed slave mode
#define TWCR_RESET TWCR         = (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(1<<TWEA)|(0<<TWSTA)|(0<<TWSTO)|(0<<TWWC)
// The bit pattern for TWCR_ACK and TWCR_RESET are equal. This is no errro but used for better understanding.
#define TWCR_CLEARBUS TWCR      = (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(1<<TWEA)|(0<<TWSTA)|(1<<TWSTO)|(0<<TWWC)

ISR (TWI_vect)
{
        uint8_t data;
        static uint8_t crc;
        // check event
        switch (TW_STATUS)
        {
        case TW_SR_SLA_ACK: // slave addressed in receiver mode and ack has been returned
            Rx_Idx = 0xFF;  // reset rx buffer pointer
                        TWCR_ACK;       // trigger receiving of first data byte and send ack afterwards
            return;

        case TW_SR_DATA_ACK: // data has been received and ack has been returned
                data = TWDR;
                        if (Rx_Idx  == 0xFF)
                        {       // if the fisrt byte after slave addressing was received
                                switch(data)
                                {
                                        case I2C_CMD_VERSION:
                                                I2C_TxBuffer = (uint8_t *)&I2C_Version;
                                                I2C_TxBufferSize = sizeof(I2C_Version);
                                                I2C_RxBuffer = 0;
                                                I2C_RxBufferSize = 0;
                                                break;

                                        case I2C_CMD_WRITE_CAL:
                                                I2C_TxBuffer = 0;
                                                I2C_TxBufferSize = 0;
                                                I2C_RxBuffer = (uint8_t *)&I2C_WriteCal;
                                                I2C_RxBufferSize = sizeof(I2C_WriteCal);
                                                break;

                                        case I2C_CMD_READ_MAG:
                                                I2C_TxBuffer = (uint8_t *)&I2C_Mag;
                                                I2C_TxBufferSize = sizeof(I2C_Mag);
                                                I2C_RxBuffer = 0;
                                                I2C_RxBufferSize = 0;

                                                I2C_Mag.MagX = MagnetX;
                                                I2C_Mag.MagY = MagnetY;
                                                I2C_Mag.MagZ = MagnetZ;
                                                break;

                                        case I2C_CMD_READ_HEADING:
                                                I2C_TxBuffer = (uint8_t *)&I2C_Heading;
                                                I2C_TxBufferSize = sizeof(I2C_Heading);
                                                I2C_RxBuffer =  (uint8_t *)&I2C_WriteAttitude;
                                                I2C_RxBufferSize = sizeof(I2C_WriteAttitude);
                                                // update heading from global variable
                                                I2C_Heading.Heading = Heading;
                                                // copy current attitude from I2C rx buffer to uart rx buffer (this is used for the calulation of the heading)
                                                ExternData.Attitude[NICK] = I2C_WriteAttitude.Nick;
                                                ExternData.Attitude[ROLL] = I2C_WriteAttitude.Roll;
                                                break;
                                        default: // unknown command id
                                                I2C_RxBuffer = 0;
                                                I2C_RxBufferSize = 0;
                                                I2C_TxBuffer = 0;
                                                I2C_TxBufferSize = 0;
                                        break;
                                }
                                Rx_Idx = 0; // set rx buffer index to start of the buffer
                                crc = data;
                        }
                        else // Rx_Idx  != 0xFF
                        {
                                // fill receiver buffer with the byte that has been received
                                // if buffer exist and there is still some free space
                                if((I2C_RxBuffer != 0) && (Rx_Idx  < I2C_RxBufferSize))
                                {
                                        I2C_RxBuffer[Rx_Idx] = data;
                                        crc += data;
                                }
                                else if (Rx_Idx == I2C_RxBufferSize) // crc byte was transferred
                                {
                                        if(crc == data)
                                        {
                                                // copy primary rx buffer to target
                                        }
                                }
                                // else ignore data
                                Rx_Idx++;
                        }
                        TWCR_ACK;
            return;

        case TW_ST_SLA_ACK: // slave transmitter selected
                // reset index  to start of tx buffer
            Tx_Idx = 0;
            crc = 0;
            // if tx buffer exist and there is at least one byte to transfer
                        if((I2C_TxBuffer != 0) && (I2C_TxBufferSize > 1))
                        {
                                data = I2C_TxBuffer[Tx_Idx];

                        }
                        else
                        {   // send 0x00 if no tx buffer exist or all bytes of the tx buffer have been transmitted
                                data = 0x00;
                        }
                        crc += data;
                        Tx_Idx++;
                        TWDR = data;
                        TWCR_ACK;
            return;

                case TW_ST_DATA_ACK: // data byte has been transmitted ack has been received
                        // put next byte from tx buffer to the data register
                        if((I2C_TxBuffer != 0) && (Tx_Idx < I2C_TxBufferSize))
                        {
                        data = I2C_TxBuffer[Tx_Idx];
                        crc += data;
                        }
                        else if (Tx_Idx == I2C_TxBufferSize)
                        {   // send crc byte at the end
                                data = crc;
                        }
                        else
                        {
                                data = 0x00;
                        }
                        Tx_Idx++;
                        TWDR = data;
                        TWCR_ACK;
            return;

        case TW_BUS_ERROR:  // Bus-Error
            TWCR_CLEARBUS;      // free bus, reset to nonselected slave
            return;

                case TW_ST_DATA_NACK:   // data transmitted, NACK received
                case TW_ST_LAST_DATA:   // last data byte transmitted, ACK received
                case TW_SR_STOP:                // stop or repeated start condition received while selected
                default:
                        TWCR_RESET; // switch to the not addressed slave mode, own SLA will be recognized
                return;
        }
}