0

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,

  1. There is no output on the lcd display.
  2. The tx pin is always high.
  3. 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 ?

3
  • 2
    while(1) in loop() 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 of loop(). If you never return from loop(), 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 global bool. Commented Jun 18, 2016 at 16:44
  • 1
    @DarkFalcon Or use setup() to have some code executed only once at program startup. Commented Jun 18, 2016 at 16:46
  • I have even erased the while loop from the code, but even then its not responsive. Commented Jun 18, 2016 at 17:02

1 Answer 1

1

Given that you are using the 328p on an Arduino you should assume the boot-loader have already written to the UART registers before you reach your code. Hence the UCSR0B and UCSR0C registers should be fully assigned rather than just masking in your set bits.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.