I am sending one character at a time from the InputBox of the Serial Monitor of UNO with "No line ending" option. The aim is to see that the mix-codes (Arduino Codes + Register Level Codes) work together.
void setup()
{
Serial.begin(9600); //must have enabled TX and TX at Bd=9600, NP, and 1-StopBit.
}
void loop()
{
bool n = bitRead(UCSR0A, RXC0);
if (n == HIGH)
{
byte c = Serial.read();//UDR0;
Serial.println(c, BIN);
}
}
Serial is interrupt driven. So Serial.read() does not read from the HW register, but from the receive buffer. The ISR of Serial reads from the HW registers.
Mixing Serial methods with direct access to HW registers will disturb each other.
If receive-interrupt is disabled, do you think that the arrived data will remain in the RX-register and the execution of byte c = UDR0 will make the data available in the c variable?
If the Receive Complete interrupt flag (RXC0) is set in UCSR0A. You will have to manually reset the flag after reading because the ISR is not being called.
I understand if one wants to know how the UART HW works.
But what is the goal to mix the Serial class with direct access to the HW registers?
If you do not know exactly what happens in the Serial class, it is difficult to foresee the effect of simultaneous direct register accesses.
This will work, but is very poor practice. n is a bool, which only "knows" the values "true" and "false", not "HIGH". And, in fact, because it is a bool, you really don't NEED to compare it to anything. "if(n)" will work just fine.
Serial doesn't allow, as far as I know, access to more subtle things like catching a framing error (i.e. a serial break) or an overrun etc. Do you need to detect these sorts of events or ... ?
The notion of HIGH has come from the fact that RXC0-bit of UCSR0A-register assumes HIGH ("this flag bit is set") "when there are unread data in the receive buffer".
As almost all serial drivers I know, an ISR routine fetches the data from the UART and stores them in a (ring)buffer. Serial.available() does not indicate that data are available at the hardware but in the buffer ... If you want to go deeper just study the HardwareSerial library:
byte n = Serial.available(); //checks number of data bytes available in Serial Buffer.
bool n = bitRead(UCSR0A, RXC0); //offers status if there is a data byte in HW RX-register
Correct. available() is looking at the memory buffer filled by the Serial RX ISR. The other is checking the UART status register to see if a single character is sitting in the hardware data register.
I'm sort of on the fence on this. It may not always be the case where a returned value is zero or non-zero. If you're sure it is then "if( n )" works fine. Not sure if that's considered completely portable code (or if that even matters...)