Advertisement
Guest User

readdata.c

a guest
Aug 4th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.68 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <termios.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6.  
  7. void main(void)
  8.  {
  9.     int fd;
  10.     fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY); //FileDescriptor fd = ttyUSB0 (CP2102)
  11.  
  12.     if (fd<0) {
  13.         printf("Failed to open ttyUSB0\n");
  14.         close(fd);
  15.         return; //Wenn ttyUSB0 nicht geöffnet werden konnte, return
  16.     }
  17.  
  18.     struct termios SerialPortSettings;
  19.     tcgetattr(fd, &SerialPortSettings);
  20.  
  21.     //Baudrate setzen 9600 bps
  22.     cfsetispeed(&SerialPortSettings, B9600);
  23.     cfsetospeed(&SerialPortSettings, B9600);
  24.  
  25.     SerialPortSettings.c_cflag &= ~PARENB; //No Parity
  26.     SerialPortSettings.c_cflag &= ~CSTOPB; //1 Stopbit
  27.     SerialPortSettings.c_cflag &= ~CSIZE; //Clear Mask
  28.     SerialPortSettings.c_cflag |= CS8; //Databits = 8
  29.     SerialPortSettings.c_cflag &= ~CRTSCTS; //Turn off hardware flow control
  30.     SerialPortSettings.c_cflag |= CREAD | CLOCAL; //Turn on rx
  31.  
  32.     SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY); //Turn off software flow control
  33.     SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG); //Set Non-Cannoncial
  34.  
  35.     SerialPortSettings.c_oflag &= ~OPOST;
  36.  
  37.     SerialPortSettings.c_cc[VTIME] = 100;
  38.  
  39.     if((tcsetattr(fd,TCSANOW,&SerialPortSettings)) != 0) { //Set attributes
  40.         printf("Failed to set attributes!");
  41.         close(fd);
  42.         return;
  43.     }
  44.  
  45.     tcflush(fd, TCIFLUSH);
  46.  
  47.     char read_buffer[64];
  48.     int bytes_read = 0;
  49.     bytes_read = read(fd,&read_buffer,64);
  50.  
  51.     printf("\n\n  Bytes Rxed %d", bytes_read);
  52.     printf("\n\n  ");
  53.  
  54.     int i = 0;
  55.     for(i=0;i<bytes_read;i++)
  56.         printf("%c",read_buffer[i]);
  57.  
  58.     close(fd);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement