我正在尝试使用ATmega328P处理串行通信的概念。我对此非常陌生,但这是我目前编写的代码。基本上,我们将串行通信中的字符输入到ATmega芯片的RX中,并希望TX传回从串行终端发送的相同字符。我相信这个代码确实接收到了传输,但我不知道为什么它不能传输输入的字符。
int main(void)
{
/* For the microcontroller: set the baud rate to 19200 */
UBRR0 = 25;
/*
** Enable transmission and receiving via UART and also
** enable the Receive Complete Interrupt.
*/
// UCSR0A = (1<<RXC0)|(1<<UDRE0);
UCSR0B = (1<<RXCIE0)|(1<<UDRIE0)|(1<<RXEN0)|(1<<TXEN0);
// Receiving data
// wait for data
while(!(UCSR0A & (1 << RXC0)));
// return data
return UDR0;
//Transmitting data
/* No need to set UCSR0C - we just want the default value */
/* Enable interrupts */
sei();
/* Sit back and let it happen - this will loop forever */
for (;;) {
}
}
/*
* Define the interrupt handler for UART Receive Complete - i.e. a new
* character has arrived in the UART Data Register (UDR).
*/
/*UART Register*/
ISR(USART0_UDRE_vect)
{
/* A character has been received - we will read it. If it is
** lower case, we will convert it to upper case and send it
** back, otherwise we just send it back as is
*/
char input;
/* Extract character from UART Data register and place in input
** variable
*/
UDR0 = input;
}
ISR(USART0_RX_vect) {
char input = UDR0;
printf_P(PSTR("%c"), input);
}发布于 2020-09-14 19:36:25
你的代码中没有任何意义。
1)
int main(void)
{
...
return UDR0;这毫无意义:您将从main返回到...哪里?实际上,当您退出main例程时,程序会因为进入死循环而停止。
2)
ISR(USART0_UDRE_vect)
{
...
char input;
...
UDR0 = input;
}您正在传输变量input的内容。上面声明的仍然是未定义的。您永远不会将任何内容赋给变量。我打赌编译器给了你很多警告。
3)
ISR(USART0_RX_vect) {
char input = UDR0;
printf_P(PSTR("%c"), input);
}你对'printf‘有什么期望?当在MCU上运行时,它应该在哪里打印结果?
事实上,代码可能要简单得多
int main(void)
{
// Sets 19200 only when MCU is running at 8MHz
UBRR0 = 25;
// enable receiver and transmitter
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
for(;;) { // infinite loop
// Receiving data
// wait for data
while(!(UCSR0A & (1 << RXC0)));
// read the data byte from the the receiver buffer
unsigned char data = UDR0;
// Wait for the transmitting buffer to be empty
while(!(UCSR0A & (1 << UDRE0)));
// Send the data
UDR0 = data;
}
}https://stackoverflow.com/questions/63824490
复制相似问题