00001
00002
00003
00004
00005
00006
00007
00008 #include <avr/io.h>
00009 #include <util/twi.h>
00010 #include "twi.h"
00011 #include "uart_i.h"
00012 #define puts(ARG) puts_i(ARG,0);
00013 #define ERROR() return -1;
00014 #define MCU_CLK 16000000
00015
00016
00017
00018
00019
00020
00021
00022 int8_t TWI_Init_default(){
00023 return TWI_Init(72);
00024 }
00025
00026 int8_t TWI_Init(uint8_t BR){
00027 TWBR = BR;
00028 TWSR = 0;
00029 TWCR=(1<<TWEN);
00030 return 1;
00031 }
00032
00033 int8_t TWIMasterTransmit(int8_t SLA, uint8_t * data, uint8_t count){
00034 uint8_t twst;
00035 int i=0;
00036
00037 TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
00038 while (!(TWCR & (1<<TWINT))){
00039 ;
00040 };
00041 twst=TW_STATUS;
00042 if (twst != TW_START){
00043 TWCR |= (1<<TWINT)|(1<<TWSTO);
00044 TWCR=(1<<TWEN);
00045 return -2;
00046 }
00047
00048 TWDR = (SLA<<1);
00049
00050 TWCR &= ~(1<<TWSTA);
00051 TWCR = (1<<TWINT)|(1<<TWEN);
00052
00053 while (!(TWCR & (1<<TWINT))){
00054 ;
00055 }
00056 twst=TW_STATUS;
00057 if (twst != TW_MT_SLA_ACK){
00058
00059 TWCR |= (1<<TWINT)|(1<<TWSTO);
00060
00061 TWCR =(1<<TWEN);
00062 return -3;
00063 }
00064
00065 twst=TW_MT_DATA_ACK;
00066 for(i=0; i<count &&(twst==TW_MT_DATA_ACK);i++){
00067 TWDR = data[i];
00068 TWCR |= (1<<TWINT);
00069
00070 while (!(TWCR & (1<<TWINT))){
00071 ;
00072 }
00073 twst=TW_STATUS;
00074 }
00075
00076
00077 TWCR |= (1<<TWINT)|(1<<TWSTO);
00078 TWCR = (1<<TWEN);
00079
00080 if(twst==TW_MT_DATA_ACK)
00081 return 0;
00082 else
00083 return i;
00084
00085 }
00086
00087
00088
00089
00090
00091
00092
00093 int8_t TWIMasterReceive(uint8_t SLA, uint8_t * data, uint8_t length){
00094 uint8_t twst;
00095 int i=0;
00096
00097 TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
00098 while (!(TWCR & (1<<TWINT))){
00099 ;
00100 };
00101 twst=TW_STATUS;
00102 if (twst != TW_START){
00103 TWCR |= (1<<TWINT)|(1<<TWSTO);
00104 TWCR=(1<<TWEN);
00105 return -2;
00106 }
00107
00108
00109 TWDR = (SLA<<1)+1;
00110 TWCR &= ~(1<<TWSTA);
00111 TWCR |= (1<<TWINT)|(1<<TWEN);
00112 while (!(TWCR & (1<<TWINT))){
00113 ;
00114 }
00115
00116 twst=TW_STATUS;
00117 if (twst != TW_MR_SLA_ACK){
00118
00119 TWCR |= (1<<TWINT)|(1<<TWSTO);
00120
00121 TWCR =(1<<TWEN);
00122 return -3;
00123 }
00124
00125
00126 for(i=0;(i<length)&&(twst!=TW_MR_ARB_LOST);i++){
00127
00128 if(i<length-1)
00129 TWCR |=(1<<TWEA)|(1<<TWINT);
00130 else{
00131 TWCR &= ~(1<<TWEA);
00132 TWCR |=(1<<TWINT);
00133 }
00134 while (!(TWCR & (1<<TWINT))){
00135 ;
00136 }
00137 data[i]=TWDR;
00138 twst=TW_STATUS;
00139 }
00140 TWCR |= (1<<TWINT)|(1<<TWSTO);
00141 TWCR = (1<<TWEN);
00142
00143 if(i==length)
00144 return 0;
00145 else
00146 return i;
00147
00148
00149 }
00150