/////////////////////////////////////////////////////////////////////////////////////////
//
// LIN sample for Freescale TWR-S12G128
//
// --------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////////

#include <hidef.h>

/////////////////////////////////////////////////////////////////////////////////////////
// Defines
/////////////////////////////////////////////////////////////////////////////////////////

#define MAX_DATA      1               // Max bytes lin frame data
#define MAX_LIN       6               // Max Lin channels

#define SCI_BAUDRATE  19200           // SCI baud rate
#define SCI_CLOCK     6250000         // Bus clock in Hz 

#define BIT(A,B)      ((A>>B)&0x01)   // A is the variable while 
                                      // B is the bit number
// LIN CHANNEL
#define LIN_0         0
#define LIN_1         1
#define LIN_2         2
#define LIN_3         3
#define LIN_4         4
#define LIN_5         5

// SCI REGISTERS
#define SCIBDH        0x00
#define SCIBDL        0x01
#define SCICR1        0x02
#define SCIASR1       0x00
#define SCIACR1       0x01
#define SCIACR2       0x02
#define SCICR2        0x03
#define SCISR1        0x04
#define SCISR2        0x05
#define SCIDRH        0x06
#define SCIDRL        0x07

enum lin_state { IDLE, _BREAK, SYNCH, PROTECTED_IDENTIFIER, DATA_0, DATA_1, 
                 DATA_2, DATA_3, DATA_4, DATA_5, DATA_6, DATA_7, CHECKSUM };

struct message {
  unsigned char identifier;
  unsigned char data_field[MAX_DATA];
};

struct frame {
  unsigned char protected_id;
  unsigned char data[MAX_DATA];
  unsigned char check;
  enum lin_state state;
  unsigned char error;
};

/////////////////////////////////////////////////////////////////////////////////////////
// Functions
/////////////////////////////////////////////////////////////////////////////////////////

void LINInit(unsigned char lin_num);
Bool LINSendMsg(unsigned char lin_num, Bool master, Bool send_data, struct message msg);
Bool LINGetMsg(unsigned char lin_num, Bool get_data, struct  message *msg);
enum lin_state LINCheckState(unsigned char lin_num);
