我正在 AVR 微 Controller 上实现 USART 通信。下面是我的代码。目前,我可以发送一个字符,发送一个字符串并接收一个字符。我有一个接收字符串的方法。
该方法名为 char* receive_string()
并返回我收到的字符串的地址。这是保存字符串 char string[55]
的 55 个元素的字符数组。 。但是,例如,当我发送单词 hello
时对于微 Controller ,此方法仅返回第一个字符 h
。我到底做错了什么?
#include <avr/io.h>
#include <util/delay.h>
#include <string.h>
#include <avr/interrupt.h>
// macro definition
#define bit(n) (1 << n) // bit
#define sbit(v, n) v |= (1 << n) // set bit
#define cbit(v, n) v &= !(1 << n) // clear bit
#ifndef F_CPU
#define F_CPU 16000000
#endif
#define BAUD 9600 // baud rate
#define M_UBRR ((F_CPU/16/BAUD)-1) //contents of UBRRnH and UBRRnL registers
// function prototypes
void usart_init();
void send_char(char);
void send_string(char*);
char receive_char();
char* receive_string();
char string[55];
int main() {
usart_init();
char* msg = receive_string();
sei();
while (1) {
send_string(msg);
_delay_ms(1000);
}
return 0;
}
void usart_init() {
UBRR0H = (M_UBRR >> 8); // setting baud rate
UBRR0L = M_UBRR;
UCSR0B = (1 << TXEN0) | (1 << RXEN0) | (1 << RXCIE0); // enable transmitter and receiver
UCSR0C = (1 << USBS0); // 2 stop bit
UCSR0C = (1 << UCSZ00) | (1 << UCSZ01);
}
void send_char(char byte) {
while (!(UCSR0A & (1 << UDRE0))); // wait until the register is empty
UDR0 = byte; // put a char in the UDR0 register
}
void send_string(char* string) {
int i;
int len = strlen(string);
for (i = 0; i < len; i++) {
send_char(string[i]);
}
}
char receive_char() {
while (!(UCSR0A & (1 << RXC0))); // wait until all data in receive buffer is read
return UDR0;
}
char* receive_string() {
char x;
int len = strlen(string);
int i = 0;
while (i < len) {
x = receive_char();
string[i++] = x;
}
string[len] = '\0';
return (string);
}
最佳答案
代码中的
strlen(string)
没有意义。如何获取尚未发送的字符串的长度?
将其更改为 len = 55
或 len = sizeof(string)
。
在 C 语言中,strlen
在找到零终止符之前计算字符数。
关于c - AVR USART通讯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896716/