green rosh
/
i2c_slave_chaitanya
third commit
Fork of i2c_slave by
Diff: slave.cpp
- Revision:
- 0:ad4485166cfe
- Child:
- 1:37d4026fa600
diff -r 000000000000 -r ad4485166cfe slave.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/slave.cpp Mon Jun 30 11:59:30 2014 +0000 @@ -0,0 +1,93 @@ +#include "slave.h" +void write_to_master(char send) //function to write data to master + { + int acknowledge; + acknowledge = slave.write(send); //sending the byte to master + if(acknowledge==1) + { + pc.printf(" acknowledge %d sent %x \n",acknowledge,send); + } + } + + void split(float data) //function to split data into 4 individual bytes and send to master + { + union convert + { + char byte[4]; //array containing individual bytes + float number; //floating point number to be split into four bytes + }v; + v.number=data; + write_to_master(v.byte[0]); + write_to_master(v.byte[1]); + write_to_master(v.byte[2]); + write_to_master(v.byte[3]); + pc.printf("sent %f\n",v.number); + } + + + +void FUNC_I2C_SLAVE_MAIN() +{ + wait(0.5); + slave.address(0x20); //assigning slave address + int Switch_Variable; + int ReadAddressed=1; + int WriteGeneral=3; + int loopvariable1=1; + int loopvariable2=0; +//initialising dummy sensor data + Sensor.voltage[0]=0.1;Sensor.current[0]=0.0;Sensor.temp[0]=1.0; + Sensor.voltage[1]=0.1;Sensor.current[1]=1.1;Sensor.temp[1]=2.0; + Sensor.voltage[2]=0.2;Sensor.current[2]=2.2;Sensor.temp[2]=2.0; + Sensor.voltage[3]=0.3;Sensor.current[3]=3.3;Sensor.temp[3]=3.0; + Sensor.voltage[4]=0.4;Sensor.current[4]=4.4;Sensor.temp[4]=4.0; + Sensor.voltage[5]=0.5;Sensor.current[5]=5.5;Sensor.temp[5]=5.0; + Sensor.voltage[6]=0.6;Sensor.current[6]=6.6;Sensor.temp[6]=6.0; + Sensor.voltage[7]=0.7;Sensor.current[7]=7.7;Sensor.temp[7]=7.0; + Sensor.voltage[8]=0.8;Sensor.current[8]=8.8;Sensor.temp[8]=8.0; + Sensor.voltage[9]=0.9;Sensor.current[9]=9.9;Sensor.temp[9]=20.5; + while(loopvariable1) + { +//to read data from master + if(slave.receive()==WriteGeneral) //checking if slave is addressed to write + { + Switch_Variable=slave.read(); //receiving data + pc.printf("switch variable=%d\n",Switch_Variable); + slave.stop(); //reset slave to default receiving state + loopvariable1=0; +//to interpret and write data to master + switch(Switch_Variable) + { + + case 1: while(loopvariable2<30) + { + if(slave.receive()==ReadAddressed) //check if slave is addressed to read + { + if(loopvariable2%3==0) + { + pc.printf("\nvoltage%d\n",loopvariable2/3); + split(Sensor.voltage[loopvariable2/3]); + } + else if(loopvariable2%3==1) + { + pc.printf("\ncurrent%d\n",loopvariable2/3); + split(Sensor.current[loopvariable2/3]); + } + else if(loopvariable2%3==2) + { + pc.printf("\ntemp%d\n",loopvariable2/3); + split(Sensor.temp[loopvariable2/3]); + } + loopvariable2++; + slave.stop(); + } + } + break; + case 2 : pc.printf(" telecommand 2\n"); + break; + + }//switch case ends + } +} + pc.printf("done"); +}