【发布时间】:2020-03-17 21:59:19
【问题描述】:
我相信我了解如何使用中断在 ATmega328p 的 UART 上接收串行数据,但我不了解如何传输数据的机制。
这是一个基本程序,我想用它来传输字符串“hello”,使用中断来驱动传输。我知道字符 'o' 可能会被传输两次,我可以接受。
#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000UL
#define BAUD 19200
#define DOUBLE_SPEED 1
void initUART(unsigned int baud, unsigned int speed);
volatile uint8_t charIndex = 0;
volatile unsigned char command[5] = "hello";
int main(void)
{
//initialize UART
initUART(BAUD, DOUBLE_SPEED);
sei();
//What do I put here to initiate transmission of character string command?
//Is this even correct?
UDR0 = command[0];
while(1)
{
}
}
ISR(USART_TX_vect)
{
// Transmit complete interrupt triggered
if (charIndex >= 4)
{
//Reach the end of command, end transmission
return;
}
//transmit the first char or byte
UDR0 = command[charIndex];
//Step to the next place of the command
charIndex++;
}
void initUART(unsigned int baud, unsigned int speed)
{
unsigned int ubrr;
if(speed)
{
//double rate mode
ubrr = F_CPU/8/baud-1;
//set double speed mode
UCSR0A = (speed << U2X0);
}
else
{
//normal rate mode
ubrr = F_CPU/16/baud-1;
}
//set the baud rate
UBRR0H = (unsigned char)(ubrr >> 8);
UBRR0L = (unsigned char)(ubrr);
//enable Tx and Rx pins on MCU
UCSR0B = (1 << RXEN0) | (1 << TXEN0);
//enable transmit interrupt
UCSR0B = (1 << TXCIE0);
//set control bits, 8 bit char, 0 stop, no parity
UCSR0C = (1 <<UCSZ00) | (1 <<UCSZ01);
}
我的理解是,如果我将第一个字符写入 UDR0(就像我在 main() 中所做的那样),这将触发传输完成中断,然后下一个字节将通过 ISR 传输。这似乎不起作用。
此处显示的代码使用 gcc 编译。有人可以解释一下吗?
【问题讨论】:
-
当您完成传输后,我相信您必须禁用 USART 的 TX 中断,以免永远卡在其中。同样,您应该只在有数据要发送时才启用中断。但我不确定这是否能解决您当前的问题。你的问题具体是什么?您是否看到在 TX 上传输的任何字节或什么?