Serial communication not working as expected

i have the following sender/transmitter code, when i send the 1st datagram to it (using a program on the PC), it seems to work well, it sends the data to another esp32 and that esp sends back an awnser as an ACK, but then when the PC program sends the 2nd datagram to the esp using the usb/uart serial connection the esp32 doesn't receive anything, anyone has any idea why?

#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <HardwareSerial.h>

#define TAMANHO_MAX_TRAMA 144
#define dataPin 21
#define RX2_PIN 16
#define TX2_PIN 17
#define baudRate 250000
#define RXlink_PIN 9
#define TXlink_PIN 10
#define CHUNK_SIZE 32
HardwareSerial SerialConnect ( 2 );


void sendPacket(byte *data, int length){
  bool running = true;
  while(running){
    byte ack[2];
    SerialConnect.write(data, length);
    SerialConnect.flush();
    
    while(SerialConnect.available() < 2){}
    SerialConnect.read();   
    SerialConnect.readBytes(ack, 2);
    
    if(char(ack[0]) == '1'){
      Serial.write(ack,2);
      Serial.flush();
      running = false;
    }
  }
}


void setup(){
  Serial.begin(baudRate);
  SerialConnect.begin(9600, SERIAL_8N1, 16, 17,true);
  //Serial1.begin(9600);

}



void loop(){
  byte buffer[TAMANHO_MAX_TRAMA];
  int tamanho_trama = 16; //tamanho header + CRC em bytes
  if(Serial.available() >= 12){
    Serial.readBytes(buffer, 12); //espera receber o header do pacote
    
    tamanho_trama += (int)buffer[11];
    
    int remainingBytes = tamanho_trama - 12;
    int bytesRead = 0;
    while (remainingBytes > 0) {
      int chunkSize = min(remainingBytes, CHUNK_SIZE);
      if (Serial.available() > 0){
        int bytesReadThisRound = Serial.readBytes(buffer + 12 + bytesRead, chunkSize);
        bytesRead += bytesReadThisRound;
        remainingBytes -= bytesReadThisRound;
      }
    }
    
    // Ensure that the entire payload + CRC is read before sending
    if (bytesRead == tamanho_trama - 12) {
      // Send the complete message
      sendPacket(buffer, tamanho_trama);
    }
  }
}

what i mean is for example in seria.available() it reads 0

If I understand this correctly, if just 1 character is actually available, you nevertheless attempt to read a bunch of characters in one function call.

For a more cautious and less error-prone approach, I recommend to spend some time studying the Serial Input Basics tutorial.

yeah, i noticed that, fixed it already thanks

but still don't know why it won't receive the second dataframe i send to it after receiving the ACK, it doesn't even pass the "if(Serial.available() >= 12){" condition which is only the header that all my dataframes have

If this were my project, I would rewrite that code rather completely, following the ideas in the tutorial linked above.

1 Like

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