ok, I feel like this should be simple, but I am at a loss
Simple code mock up to send 4 bytes(mimicking a float) over I2C from Arduino to rpi. I am trying to create a state machine so that I can request certain "registers" containing 4 bytes each. I send a byte from pi to arduino indicating what "register" I want, then read back 4 bytes. I was attemping to reset the state back to NO_STATE after the end of the switch statement, but it effects the bytes received by the pi, and I dont see how.
#include <Wire.h>
#define SLAVE_ADDRESS 0x04
//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03
byte state = NO_STATE;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
}
void loop() {
delay(100);
}
// callback for received data
void receiveData(int byteCount){
while(Wire.available()) {
state = Wire.read();
}
Serial.print("Got:");
Serial.println(state);
}
// callback for sending data
void sendData(){
Serial.println("Sending...");
byte b[4]={1,1,1,1};
switch (state){
case NO_STATE:
//bad state not sure if can return only byte, may need to return 4 zeros or somthing
Wire.write(0);
Wire.write(0);
Wire.write(0);
Wire.write(0);
break;
case GET_BAT_TEMP:
//send battery temp
Wire.write(3);
Wire.write(3);
Wire.write(3);
Wire.write(3);
break;
default:
Wire.write(9);
Wire.write(9);
Wire.write(9);
Wire.write(9);
//send back error code
}
//reset state to none
state=NO_STATE;
}
with this code I receive [3,0,0,0]
if I comment out the line
//state=NO_STATE;
I then receive back [3,3,3,3]
which is what I would expect. But I do not see how reseting the state "after" all the bytes are sent would cause an issue
output from arduino shows entering that function only once, and sending the 4 bytes
Got:3
Sending...
Sending...
Sending...
Sending...