Advertisement
dllbridge

Com-port for arduino

May 8th, 2024
1,023
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #include <termios.h>
  7.  
  8. int open_port(const char *port) {
  9.     int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
  10.     if (fd == -1) {
  11.         perror("open_port: Unable to open port");
  12.         return -1;
  13.     }
  14.    
  15.     struct termios options;
  16.     tcgetattr(fd, &options);
  17.     cfsetispeed(&options, B9600);
  18.     cfsetospeed(&options, B9600);
  19.     options.c_cflag &= ~PARENB;
  20.     options.c_cflag &= ~CSTOPB;
  21.     options.c_cflag &= ~CSIZE;
  22.     options.c_cflag |= CS8;
  23.     options.c_cflag |= (CLOCAL | CREAD);
  24.     tcsetattr(fd, TCSANOW, &options);
  25.    
  26.     return fd;
  27. }
  28.  
  29. int main() {
  30.     int fd = open_port("/dev/ttyUSB0");
  31.     if (fd == -1) {
  32.         return -1;
  33.     }
  34.    
  35.     char write_buffer[] = "Hello Arduino!";
  36.     int bytes_written = write(fd, write_buffer, strlen(write_buffer));
  37.     if (bytes_written < 0) {
  38.         perror("write");
  39.         close(fd);
  40.         return -1;
  41.     }
  42.    
  43.     char read_buffer[256];
  44.     int bytes_read = read(fd, &read_buffer, sizeof(read_buffer));
  45.     if (bytes_read < 0) {
  46.         perror("read");
  47.         close(fd);
  48.         return -1;
  49.     }
  50.    
  51.     read_buffer[bytes_read] = '\0';
  52.     printf("Received: %s\n", read_buffer);
  53.  
  54.     close(fd);
  55.    
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement