这是我 3 个多月都无法解决的问题。我尝试了各种方法,但无法理解为什么我的代码无法正常工作。
我正在尝试通过 UART
发送值。当我发送这样的值时
(Atmel Studio 7.0,Atmega2560
)
USART_Transmit('O');
USART_Transmit('k');
USART_Transmit('!');
USART_Transmit(0x0d);
USART_Transmit(0x0a);//new line
没有问题。输出如我所料
但是,当我尝试发送名为 text
的 char 数组的第一个元素时,它显示的只是垃圾值。
这是我的完整代码
#define F_CPU 16000000L
#include <avr/io.h>
char Text[6] = "Hello"; // this is
void USART_Init( unsigned int speed)
{
UBRR0H = (unsigned char)(speed>>8); // baudrate setting
UBRR0L = (unsigned char)speed;
UCSR0B=(1<<RXEN0)|( 1<<TXEN0); // rx and tx pins activated
UCSR0C = (0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00); character size 8
}
void USART_Transmit( unsigned char data )
{
// ucsr0a has a bit called UDRE0, is uart data register empty , if yes wait
while ( !( UCSR0A & (1<<UDRE0))) {;}
UDR0 = data;
}
int main(void) {
USART_Init(103); // 103 is UBRR , (16000000/9600)*16 =104 104-1=103
USART_Transmit('O');
USART_Transmit('k');
USART_Transmit('!');
USART_Transmit(0x0d);
USART_Transmit(0x0a);//new line
//SendString(Text);
USART_Transmit(Text[0]); //GARBAGE VALUE, PRINTS 0xFF should be ascii H ...
while (1) {
}
}
最佳答案
我的代码在 proteus 模拟程序上运行。我已经在 atmega2560/328/32 上试过了一切正常。 在船上,当我定义 const 或静态变量(字符串数组)时,它是有效的。但是当 const 或静态数组长度大于 16 时,它不起作用。在模拟上一切正常,但在 Arduino Mega(atmega2560)上没有工作。 (抱歉是英语)。
关于c - Atmel 工作室无法将 char 数组作为字符串发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51478541/