Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <termios.h>
- int open_port(const char *port) {
- int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
- if (fd == -1) {
- perror("open_port: Unable to open port");
- return -1;
- }
- struct termios options;
- tcgetattr(fd, &options);
- cfsetispeed(&options, B9600);
- cfsetospeed(&options, B9600);
- options.c_cflag &= ~PARENB;
- options.c_cflag &= ~CSTOPB;
- options.c_cflag &= ~CSIZE;
- options.c_cflag |= CS8;
- options.c_cflag |= (CLOCAL | CREAD);
- tcsetattr(fd, TCSANOW, &options);
- return fd;
- }
- int main() {
- int fd = open_port("/dev/ttyUSB0");
- if (fd == -1) {
- return -1;
- }
- char write_buffer[] = "Hello Arduino!";
- int bytes_written = write(fd, write_buffer, strlen(write_buffer));
- if (bytes_written < 0) {
- perror("write");
- close(fd);
- return -1;
- }
- char read_buffer[256];
- int bytes_read = read(fd, &read_buffer, sizeof(read_buffer));
- if (bytes_read < 0) {
- perror("read");
- close(fd);
- return -1;
- }
- read_buffer[bytes_read] = '\0';
- printf("Received: %s\n", read_buffer);
- close(fd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement