How to Manage Communication Process vith Arduino

45 Views Asked by At

in my below code, ı am sending 8 times 1 byte data. After sending, ı am checking the datas via arduino. Whwn i send first byte, it catch if it is true. But not same for others. It can not read other values. When ı sent 8 times 5 from serial port. The result is in below.

byte RxBuffer[10];
byte TxBuffer[10];

bool isFirstByteReceived = false;
bool RX_Data_True_Flag = false;
unsigned int rx_counter=1;

void setup() {
  Serial.begin(9600);
}

void loop() {
 if (if(Serial.available()>0)) {
    byte receivedByte = Serial.read();
    if (!isFirstByteReceived) {
         RxBuffer[0] = receivedByte;
         if(RxBuffer[0] == 0x35)
         {
          isFirstByteReceived = 1;
          Serial.print("first data true");
          }
        }
    else{
        Serial.print("other values");
        RxBuffer[rx_counter] = receivedByte; // Assuming the first byte is already received
        Serial.print("RxBuffer["); Serial.print(rx_counter); 
        Serial.print("]"); Serial.println(RxBuffer[rx_counter]);
        rx_counter++;
        if(rx_counter == 8){
            isFirstByteReceived = 0;
            rx_counter = 1;
            Check_RX_Data_True();
         }
      }
 }
}

void Check_RX_Data_True() {

    if (RxBuffer[7] == 0x35 && RxBuffer[8] == 0x35) {
      Serial.println("all values done");
      RX_Data_True_Flag = true;
    } else {
       Serial.println("failed values");
      RX_Data_True_Flag = false;
    }

}
1

There are 1 best solutions below

1
BerkN On

You need to check for is there any serial data before read. Serial.read() function returns -1 if there is no data. Loop function runs faster than serial data stream, so it returns -1 most of the time.

When you call Serial.read() function it returns the received byte once, you call second time it returns only if there is another data. Call it once for one byte data.

void loop() {
    if(Serial.available()>0){
          byte receivedByte = Serial.read();
          if(rx_counter<RXBUFFER_SIZE){
             RxBuffer[rx_counter] = receivedByte;
             rx_counter++;
             Serial.println(rx_counter);
          }
    }
}