Hi I have this code
I ask 32 slaves for data
slave has 10 ms for response delay(10);
can I do this without delay?
const byte START_BYTE = 254;
const byte ASK_CONNECT_BYTE = 252;
const byte ASK_DATA_BYTE = 250;
byte mb[5];
byte received[4];
void setup() {
Serial.begin(115200);
Serial2.begin(9600);
}
void loop() {
for (int i = 1; i <= 32; i++) {
askData(i);
}
}
void askData(int device) {
sendMessage(device, ASK_DATA_BYTE, 0);
delay(10);
readMessage(received);
if (validateReceived(received)) {
if (received[0] == device) {
Serial.println("----------");
Serial.print("device: ");
Serial.println(device);
Serial.print("key: ");
Serial.println(received[1]);
Serial.print("value: ");
Serial.println(received[2]);
Serial.println("----------");
}
}
}
bool validateReceived(byte *received) {
if (received[0] == 0 && received[3] == 0) {
return false;
}
byte receivedChecksum = received[3];
byte calculatedChecksum = START_BYTE + received[0] + received[1] + received[2];
calculatedChecksum = ~calculatedChecksum;
if (receivedChecksum == calculatedChecksum) {
return true;
}
return false;
}
void readMessage(byte *received) {
memset(received, 0, 4);
if (Serial2.available()) {
byte b = Serial2.read();
if (b == START_BYTE) {
Serial2.readBytes(received, 4);
}
}
}
void sendMessage(int device, byte key, byte value) {
memset(mb, 0, 5);
mb[0] = START_BYTE;
mb[1] = device;
mb[2] = key;
mb[3] = value;
byte checksum = mb[0] + mb[1] + mb[2] + mb[3];
mb[4] = ~checksum;
Serial2.write((uint8_t *)&mb, sizeof(mb));
Serial2.flush();
}