Ramana
Ramana

Reputation: 49

Cannot read from UART port, Beaglebone Black

I am trying to read data from UART1 of Beaglebone Black.
I have connected TX of UART1 to RX of UART1
I am getting unknown characters printed on the screen.
I was giving input characters from Minicom ttyO1 terminal

My code is this.


#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<termios.h>   // using the termios.h library

int main(){
   int file;
   file = open("/dev/ttyO1", O_RDWR | O_NOCTTY | O_NDELAY);

      struct termios options;               //The termios structure is vital
      tcgetattr(file, &options);            //Sets the parameters associated with file
      options.c_cflag = B9600 | CS8 | CREAD | CLOCAL;
      options.c_iflag = IGNPAR | ICRNL;    //ignore partity errors, CR -> newline
      tcflush(file, TCIFLUSH);             //discard file information not transmitted
      tcsetattr(file, TCSANOW, &options);  //changes occur immmediately

      unsigned char recieve[100];  //the string to send
while(1) {
      read(file, (void*)recieve,100);       //send the string
      sleep(2);
      printf("%s ", recieve);
      fflush(stdout);
      close(file);

}
       return 0;
}

Upvotes: 2

Views: 833

Answers (1)

user58697
user58697

Reputation: 7923

Since you initialize the UART with an O_NDELAY option, read returns immediately, and printf prints the contents of an uninitialized array, that is, garbage.

Reading the serial line is sort of tricky. At least, check the read return value, and 0-terminate what has been read (remember, printf expects the data to be 0-terminated, and read does not add the terminator), along the lines of

    int characters = read(file, (void*)recieve,100);
    if (characters == -1) {
        handle_the_error();
    }
    receive[characters] = 0;
    printf("%s", receive);
    ....

Besides that, you shall not read from the closed file. Take the close(file); out of the loop.

Upvotes: 1

Related Questions