Guest User

readdata.c - updated

a guest
Aug 4th, 2016
89
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 | O_NDELAY); //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.     if((tcsetattr(fd,TCSANOW,&SerialPortSettings)) != 0) { //Set attributes
  38.         printf("Failed to set attributes!");
  39.         close(fd);
  40.         return;
  41.     }
  42.  
  43.     char write_buffer[2];
  44.     write_buffer[0] = 'C';
  45.     write_buffer[1] = '\n';
  46.     int bytes_written = 0;
  47.  
  48.     bytes_written = write(fd,write_buffer,sizeof(write_buffer));
  49.  
  50.     printf("\n  %s written to ttyUSB0",write_buffer[0],write_buffer[1]);
  51.     printf("\n  %d Bytes written to ttyUSB0", bytes_written);
  52.  
  53.     close(fd);
  54. }
Add Comment
Please, Sign In to add comment