简体   繁体   中英

Programming atmega328p's UART on arduino

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM