Help with custom communication

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();
}

I need in real time data from value, for example if is button pushed.

Yes it can be done without using delay(x).

Look at File|Examples|02.Digital|BlinkWithoutDelay to use millis() for timing instead of delay().

https://majenko.co.uk/blog/our-blog-1/the-finite-state-machine-26

Your delay is 10 milliseconds. Is your button press repetition rate really in the range of 100 actuations per second?

i.e. will the user ever be allowed to register a less than 10ms press as a valid press?

You are waiting longer than that only because you structured your program to poll the clients "back to back" without servicing any other code.

The call of the delay() function is needed to synchronize the dataflow between the master and 32 slaves.

don't use the hardcoded delay.
send the askData
start receiving and processing as soon as something is in your RX Buffer (Serial.available)

Furthermore you could store a "requestStarted=millis()" and compare in loop if the slave runs in a timeout.
If so, ask the next slave.

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.