2

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;
}
Ramana
  • 49
  • 4
  • Your termios configuration is problematic and incomplete. Your program with its new fixes might seem to work today, but it is not robust code that will work reliably in other conditions. See [Setting Terminal Modes Properly](http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_12.html#SEC237) and [Serial Programming Guide for POSIX Operating Systems](http://www.cmrr.umn.edu/~strupp/serial.html) – sawdust Jul 14 '20 at 08:18
  • Because you're using nonblocking mode, your program is inefficiently polling a system buffer waiting for data. See https://stackoverflow.com/questions/25996171/linux-blocking-vs-non-blocking-serial-read/26006680#26006680 – sawdust Jul 14 '20 at 08:24

1 Answers1

1

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.

user58697
  • 7,808
  • 1
  • 14
  • 28