【问题标题】:AVR USART communicationAVR USART 通信
【发布时间】:2018-04-18 09:57:53
【问题描述】:

我正在 AVR 微控制器上实现 USART 通信。下面是我的代码。目前,我可以发送一个字符,发送一个字符串并接收一个字符。我有一个接收字符串的方法。

该方法称为char* receive_string(),并返回我正在接收的字符串的地址。这是用于保存字符串char string[55] 的 55 个元素的字符数组。但是,例如,当我将单词hello 发送到微控制器时,此方法仅返回第一个字符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);
}

【问题讨论】:

    标签: c arduino avr usart


    【解决方案1】:

    strlen(string) 在您的代码中没有意义。如何获取尚未发送的字符串的长度?

    将其更改为 len = 55len = sizeof(string)

    在 C 中,strlen 在找到零终止符之前计算字符数。

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 2015-11-08
      • 2013-10-29
      • 1970-01-01
      • 2016-06-13
      • 2017-11-26
      相关资源
      最近更新 更多