Hi, I don’t know much about hardware programming so bear with me
I have some code that is communicating with an external ATMega8. I got this code from another programmer so I don’t understand it all (especially what the high/low does on the pin).
I’m seeing a weird issue (which is hard to reproduce). It seems like the code to read the incoming data is actually reading the data I sent out.
This makes me think of two possible reasons
- It is actually reading the data before it can be flushed
- The RX/TX buffers aren’t cleared after sending. When it starts reading some of the response bytes (I have some code that checks the format), the buffer looks like a complete.
My code basically looks like this:
// Pin on a P1
#define EXPANSION_BOX_PIN A0
void setup(void) {
Serial.begin(115200);
Serial1.begin(19200);
/*RS485 direction pin*/
pinMode(EXPANSION_BOX_PIN, OUTPUT);
/*set RS485 direction pin LOW: receiver*/
digitalWrite(EXPANSION_BOX_PIN, LOW);
}
void loop(void) {
// My timer class that tells things to be re-sent
myTimer.Tick();
if (myTimer.ShouldReset()) {
isWaitingForResponse = false;
}
if (isWaitingForResponse) {
isWaitingForResponse = true;
digitalWrite(EXPANSION_BOX_PIN, HIGH);
Serial1.write(1); // I actually write out a full packet here with a specific format
Serial1.flush();
digitalWrite(EXPANSION_BOX_PIN, LOW);
}
}
void serialEvent1()
{
if (!isWaitingForResponse) {
return;
}
while(Serial1.available()) {
Serial1.read(); // Read the response packet.
}
isWaitingForResponse false;
}
// Including this just in case it matters...
#define SERIA1_BUFFER_SIZE 129
HAL_USB_USART_Config acquireUSBSerial1Buffer()
{
HAL_USB_USART_Config conf = {0};
// The usable buffer size will be 128
static uint8_t usbserial1_rx_buffer[SERIA1_BUFFER_SIZE];
static uint8_t usbserial1_tx_buffer[SERIA1_BUFFER_SIZE];
conf.rx_buffer = usbserial1_rx_buffer;
conf.tx_buffer = usbserial1_tx_buffer;
conf.rx_buffer_size = SERIA1_BUFFER_SIZE;
conf.tx_buffer_size = SERIA1_BUFFER_SIZE;
return conf;
}
What I’m wondering is if I could use halfDuplex
and get rid of all this logic I’ve added to make sure I’m never reading/writing at the same time?