gpt4 book ai didi

c - AVR、UART、Proteus仿真,虚拟终端显示的不是所有数据

转载 作者:太空宇宙 更新时间:2023-11-04 03:44:32 27 4
gpt4 key购买 nike

我正在为 MCU 编写代码,直到它将通过 UART (RS232) 传输数据。[ATmega8A]

目前,我正在 Proteus 中测试我的代码:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdlib.h>
#include <compat/twi.h>

#define FOSC 16000000 //Clock Speed
#define BAUD 9600 //Baud rate set to 9600
#define MYBRR FOSC/16/BAUD-1

void USART_Init (void)
{
UBRRH = (MYBRR >> 8); //Code for setting
UBRRL = MYBRR; //the baud rate
UCSRB = (1 << RXEN) | (1 << TXEN); //Enable receiver and transmitter
UCSRC = (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); //Frame format setting: 8 Data, 2 Stop bit
}

/* USART transmit function */
void USART_Transmit(unsigned char data)
{
while(!(UCSRA & (1 << UDRE))); //Wait until transmit buffer is empty

UDR = data;
}

/* USART receive function */
unsigned char USART_Receive(void)
{
while(!(UCSRA & (1 << RXC))); //Wait until data is received

return UDR; //Get the data from buffer and return it
}

和main中的测试代码:

 int main(void)
{
unsigned char c;

while(1)
{
a = USART_Receive();
c = 10;
USART_Transmit(c);
_delay(10000);
}
}

在 Proteus 中,虚拟终端显示 0。但是,我希望看到 10。这只是一个例子,通常只有最后一个数字/字符会显示在虚拟终端上。我无法解释这一点。 Proteus 错误或逻辑错误?

感谢您的任何建议。

最佳答案

UART 数据仅以 ascii 格式发送...您必须将整数数据转换为 ascii 格式..使用 itoa() 或执行此操作

int main(void)
{
unsigned char c;
unsigned char b;

while(1)
{
a = USART_Receive();
c = 10;
b=c;
b=c/10;
USART_Transmit(b+48);
b=0;
b=c%10;
USART_Transmit(b+48);
_delay(10000);
}
}

关于c - AVR、UART、Proteus仿真,虚拟终端显示的不是所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com