// Rapsberry Pi: RS232 in C - Versione 0.8 - Luglio 2014 // Copyright (c) 2014, Vincenzo Villa (https://www.vincenzov.net) // Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported. // Creative Commons | Attribution-Share Alike 3.0 Unported // https://www.vincenzov.net/tutorial/RaspberryPi/serial.htm // Compile: gcc serial.c -std=gnu99 -o serial // vv@vvrpi ~ $ ./serial #include #include #include #include #include #include #include #include #include #include #include #include #include #define PORT "/dev/ttyAMA0" // Device name #define SPEED B115200 // I/O speed - B9600 and so on #define DATA_BUFFER_SIZE 100 // RX buffer data size int fd; // Serial handler int open_and_configure_interface (void) {struct termios tty; // Device descriptor fd = open (PORT, O_RDWR); // Open device if (fd < 0) {printf ("Error %d opening %s: %s\n", errno, PORT, strerror (errno)); return (-1); } memset (&tty, 0, sizeof tty); if (tcgetattr (fd, &tty) != 0) {printf("ERROR! %s\n", strerror(errno)); return (-1); } cfsetospeed (&tty, SPEED); // Set output speed cfsetispeed (&tty, SPEED); // Set input speed tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars tty.c_iflag &= ~IGNBRK; // Disable break processing tty.c_lflag = 0; // No signaling chars, no echo, no canonical processing tty.c_oflag = 0; // No remapping, no delays tty.c_cc[VMIN] = 0; // Read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_iflag &= ~(IXON | IXOFF | IXANY); // No xon/xoff ctrl tty.c_cflag |= (CLOCAL | CREAD); // Ignore modem controls, enable reading tty.c_cflag &= ~(PARENB | PARODD); // No parity // tty.c_cflag |= 0; tty.c_cflag &= ~CSTOPB; // Set bit stop tty.c_cflag &= ~CRTSCTS; // No gandshake if (tcsetattr (fd, TCSANOW, &tty) != 0) {printf("ERROR! %s\n", strerror(errno)); return (-2); } return (0); } int main(int argc, char *argv[]) { char buffer [DATA_BUFFER_SIZE]; // Data buffer (Rx) printf("Rapsberry Pi: serial port in C - Versione 0.8 - Luglio 2014\n"); printf("Copyright (c) 2014, Vincenzo Villa (https://www.vincenzov.net)\n"); printf("Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported.\n"); printf("Creative Commons | Attribution-Share Alike 3.0 Unported\n"); printf("https://www.vincenzov.net/tutorial/RaspberryPi/serial.htm\n\n"); if (argc < 2) { printf("Usage: ./serial \n\n"); exit (-1); } printf ("Opening %s\n", PORT); open_and_configure_interface(); sleep(1); // Kernel bug workaround - see text printf("User data [%d bytes]: %s\n", strlen(argv[1]), argv[1]); write (fd, argv[1], strlen(argv[1]) ); // send data sleep(1); // Sleep enough to get reply memset (buffer, 0, sizeof(buffer) ); // Clear data buffer int n = read (fd, buffer, sizeof(buffer)); // Read up to 100 characters if (n < 0) printf("ERROR! %s\n", strerror(errno)); printf("Data from device [%d bytes]: %s\n\n", n, buffer); close (fd); return (0); }