jacksonliam

UART to Arduino Raspberry Pi

Jun 20th, 2012
1,855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <errno.h>
  6. #include <termios.h>
  7.  
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10.  
  11. //Raspberry Pi to Arduino UART
  12. //Takes one argument and sends it over the UART as a string
  13. //Uart /dev/ttyAMA0 is setup and settings are not restored.
  14.  
  15. int main(int argc, char ** argv) {
  16.   if(argc == 2){
  17.     printf("send: %s\n", argv[1]);
  18.   } else {
  19.     perror("wrong number of args");
  20.     return -1;
  21.   }
  22.  
  23.   int fd;
  24.   // Open the Port. We want read/write, no "controlling tty" status, and open it no matter what state DCD is in
  25.   fd = open("/dev/ttyAMA0", O_WRONLY | O_NOCTTY | O_NDELAY | O_NONBLOCK);
  26.   if (fd == -1) {
  27.     perror("open_port: Unable to open /dev/ttyAMA0 - ");
  28.     return(-1);
  29.   }
  30.  
  31.   // Turn off blocking for reads, use (fd, F_SETFL, FNDELAY) if you want that
  32.   //fcntl(fd, F_SETFL, 0);
  33.  
  34.   //Set the baud rate
  35.   struct termios options;
  36.   tcgetattr(fd, &options);
  37.   cfsetispeed(&options, B9600);
  38.   cfsetospeed(&options, B9600);
  39.   //Set flow control and all that
  40.   options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
  41.   options.c_iflag = IGNPAR | ICRNL;
  42.   options.c_oflag = 0;
  43.   //Flush line and set options
  44.   tcflush(fd, TCIFLUSH);
  45.   tcsetattr(fd, TCSANOW, &options);
  46.  
  47.   //set characters
  48.   char* strOut;
  49.   int len = asprintf(&strOut, "%s\n", argv[1]);
  50.  
  51.   // Write to the port
  52.   int n = write(fd, strOut, len);
  53.   if (n < 0) {
  54.     perror("error writing");
  55.     return -1;
  56.   }
  57.  
  58.   // Don't forget to clean up
  59.   close(fd);
  60.   return 0;
  61. }
  62. //END OF FILE
Advertisement
Add Comment
Please, Sign In to add comment