Advertisement
edensheiko

Untitled

Apr 4th, 2023
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | Haiku | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <fcntl.h>
  5. #include <termios.h>
  6. #include <unistd.h>
  7.  
  8. #define BAUDRATE B9600
  9. #define MODEMDEVICE "/dev/ttyUSB0"
  10. #define _POSIX_SOURCE 1 /* POSIX compliant source */
  11.  
  12. int main()
  13. {
  14.     int fd, res;
  15.     struct termios oldtio, newtio;
  16.     char buf[255];
  17.  
  18.     // Open the serial port
  19.     fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY);
  20.     if (fd < 0)
  21.     {
  22.         perror(MODEMDEVICE);
  23.         exit(1);
  24.     }
  25.  
  26.     // Save current port settings
  27.     tcgetattr(fd, &oldtio);
  28.  
  29.     // Set new port settings
  30.     memset(&newtio, 0, sizeof(newtio));
  31.     newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
  32.     newtio.c_iflag = IGNPAR;
  33.     newtio.c_oflag = 0;
  34.  
  35.     // Set input mode to non-canonical
  36.     newtio.c_lflag = 0;
  37.  
  38.     // Set timeouts to 0.1 seconds
  39.     newtio.c_cc[VTIME] = 1;
  40.     newtio.c_cc[VMIN] = 0;
  41.  
  42.     // Apply new settings
  43.     tcflush(fd, TCIFLUSH);
  44.     tcsetattr(fd, TCSANOW, &newtio);
  45.  
  46.     // Send data
  47.     char data[] = "Hey, it's Eden\n";
  48.     write(fd, data, strlen(data));
  49.  
  50.     // Read response
  51.     while (1)
  52.     {
  53.         res = read(fd, buf, sizeof(buf));
  54.         if (res > 0)
  55.         {
  56.             buf[res] = 0;
  57.             printf("Received response: %s", buf);
  58.             break;
  59.         }
  60.     }
  61.  
  62.     // Restore old port settings and close serial port
  63.     tcsetattr(fd, TCSANOW, &oldtio);
  64.     close(fd);
  65.  
  66.     return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement