I am attempting serial transmission in arduino by programming the Serial communication registers of its atmega328p directly (I know there is a ready made serial communication library in arduino but I want try programming atmega328p myself).
I am trying to send a character 'a' to a serial lcd by using tx pin of arduino. I have referred to several resources online and have arrived at the following code:
#define BAUDRATE(BAUD) (((F_CPU/(BAUD*16UL)))-1)
class serials
{
serials()
{
UBRR0H = BAUDRATE(9600) >> 8;
UBRR0L = BAUDRATE(9600);
UCSR0A &= ~_BV(U2X0);
UCSR0B |= _BV(TXEN0) | _BV(RXEN0);
UCSR0C |= _BV(UCSZ00) | _BV(UCSZ01);
}
void transmit(unsigned char);
};
void serials::transmit(unsigned char data)
{
loop_until_bit_is_clear(UCSR0A,UDRE0);
UDR0 = data;
}
void loop()
{
serials lcdtransmit;
lcdtransmit.transmit(254);
lcdtransmit.transmit(1);
lcdtransmit.transmit(254);
lcdtransmit.transmit(128);
lcdtransmit.transmit('a');
while(1);
}
However, when I run this code,
- There is no output on the lcd display.
- The tx pin is always high.
- When the
while(1)is not present, there seems to output at the 'tx pin' but with no output on the lcd display.
Is there any error in the code written for serial transmission ?
while(1)inloop()is usually not a good idea. One reason is that the chip may have a hardware watchdog, and the Arduino library normally resets it outside ofloop(). If you never return fromloop(), the watchdog is never reset, and thus will cause the chip to reboot. You should ensure this code only runs once by simply using a globalbool.setup()to have some code executed only once at program startup.