简体   繁体   English

在Arduino上编程atmega328p的UART

[英]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). 我正在通过直接对其atmega328p的串行通信寄存器进行编程来尝试在arduino中进行串行传输(我知道arduino中有一个现成的串行通信库,但我想自己尝试对atmega328p进行编程)。

I am trying to send a character 'a' to a serial lcd by using tx pin of arduino. 我正在尝试使用arduino的tx引脚将字符“ a”发送到串行LCD。 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. tx引脚始终为高电平。
  3. When the while(1) is not present, there seems to output at the 'tx pin' but with no output on the lcd display. while(1)不存在时,似乎在“ tx引脚”输出,而LCD显示屏上没有输出。

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. 假设您在Arduino上使用328p,则应该假定引导加载程序已在到达代码之前已写入UART寄存器。 Hence the UCSR0B and UCSR0C registers should be fully assigned rather than just masking in your set bits. 因此,应该完全分配UCSR0B和UCSR0C寄存器,而不仅仅是屏蔽设置的位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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