Hello everyone, how can I know if the output buffer is empty on the serial port?
Please explain the situation where you need that. Do you have a code example?
It happens that I want to send data to a 485 port and I need to know at what moment the output buffer has become empty to set the RS485 control pin low. I am using the Serial.flush() function, but I do not want to wait for it to finish but rather check it in another part of the program.
digitalWrite(ctr_485, HIGH);
Serial.println(num_cliente);
Serial.println(num_peso);
Serial.println(num_programa);
Serial.flush();
digitalWrite(ctr_485, LOW);
Serial.availablefForWrite() will return the number of bytes available in the buffer, 63 when completely empty, but there may still be a character left in the hardware buffer, as well as the character currently being sent, so you would need a bit of additional delay.
It should be noted, that there are Arduino platforms on which this function is not defined
Depends on which microcontroller, but they should all have a register that holds a number of UART flags, and one of them is invariably a "TXE" or "TXNE" (empty/not-empty) flag. You can even raise an interrupt associated with it.
Yes, more than a function I would like to be able to use the flag that indicates that the transmission has ended, I am using Arduino nano, could you tell me which flag to check?
In the datasheet for the ATMega328P on page 159 (and onward) you will find the relevant registers for USART. https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
You might use the TXC0 bit/flag (transmit complete) in register UCSR0A for instance. Alternatively, you could use USDRE0 (data register empty). You can enable the associated interrupts in UCSR0B and catch them with your own ISR if so desired, but you could also poll the flags instead.
Keep in mind that following this 'bare metal' approach will break compatibility of your sketch with other hardware platforms. You're leaving the comfy world of Arduino.
Keep also in mind that when using these registers in the way you intend, you may run into inadvertent behavior. For instance, a 'register empty' interrupt may be issued even though a transfer is in progress, as the interrupt occurs before the next byte from the array to be sent is loaded into the hardware buffer. Whether this happens and what to take into account you will have to figure out using the datasheet linked to above. Microchip is generally very complete and consistent in their datasheets, but it takes practice to interpret them. Seemingly insignificant choices in formulation, word order etc. tend to be important.
Okay, I'll check this information out and take your advice into account.
Thank you very much!
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.