-2

I am implementing USART communication on an AVR micro-controller. Below is my code. At the moment, I can send a character, send a string and receive a character. I have a method to receive a string.

The method is called char* receive_string() and returns the address of the string that I am receiving. This is the 55 element char array to hold the string, char string[55]. However, for example, when I send the word hello to the micro-controller, this method returns only the first character h. What is it that I am doing wrong?

#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);
}
dda
  • 6,030
  • 2
  • 25
  • 34
Rufusy
  • 11
  • 1
  • 4

1 Answers1

1

strlen(string) in your code does not make sense. How can you get the length of a string that has not been sent yet?

Change that to len = 55 or len = sizeof(string).

In C, strlen counts the number of characters before finding the zero terminator.

dda
  • 6,030
  • 2
  • 25
  • 34
fordp
  • 21
  • 3