Guest User

Untitled

a guest
Jul 19th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.45 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <inttypes.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <string.h>
  8. #include <fcntl.h>
  9. #include <errno.h>
  10. #include <termios.h>
  11. #include <sys/ioctl.h>
  12.  
  13. int SerialConnection();
  14. int serial_fd;
  15.  
  16.  
  17.  
  18. int main(int argc, char* argv[])
  19. {
  20. char buffer[255]; /* Input buffer */
  21. char *bufptr; /* Current char in buffer */
  22. int nbytes; /* Number of bytes read */
  23.  
  24. if(argc != 2)
  25. {
  26. printf( "Usage: %s <Serial Port>n",argv[0]);
  27. exit(1);
  28. }
  29.  
  30. serial_fd = SerialConnection(argv[1]);//Open serial port
  31. if(serial_fd < 1)
  32. {
  33. printf( "Serial Port Open Failuren");
  34. exit(1);
  35. }
  36. printf( "Serial Port Open Succesfullyn");
  37.  
  38.  
  39. while(1)
  40. {
  41. memset(buffer, 0, 255); //clear buffer
  42. int ELMInit = 1;
  43. switch(ELMInit)
  44. {
  45. case 1:
  46. printf( "Request ATZ Reset ELM Adaptern");
  47. write(serial_fd, "ATZr", 4);
  48. bufptr = buffer;
  49. while ((nbytes = read(serial_fd, bufptr, buffer + sizeof(buffer) - bufptr - 1)) > 0)
  50. {
  51. printf("current buffer %s n",buffer);
  52. bufptr += nbytes;
  53. if (bufptr[-1] == 'r')
  54. {
  55. printf("carriage return found %s n",buffer);
  56. if(strstr(buffer, "ELM327") != NULL)
  57. {
  58. printf("success %sn",buffer);
  59. }
  60. break;
  61. }
  62. *bufptr = '';
  63. }
  64. break;
  65.  
  66. default:
  67. break;
  68.  
  69.  
  70. }
  71.  
  72. }
  73.  
  74. }
  75.  
  76. int SerialConnection(char *serial_port)
  77. {
  78. int fd;
  79. struct termios options;
  80.  
  81. fd = open(serial_port, O_RDWR | O_NOCTTY | O_NDELAY);
  82. if (fd == -1)
  83. {
  84. return -1;
  85. }
  86. else
  87. {
  88. fcntl(fd, F_SETFL, 0);
  89. tcgetattr(fd, &options);
  90. cfsetispeed(&options, B38400);
  91. cfsetospeed(&options, B38400);
  92. options.c_cflag &= ~PARENB; /* Mask the character size to 8 bits, no parity */
  93. options.c_cflag &= ~CSTOPB; /*1 Stop bit */
  94. options.c_cflag &= ~CSIZE;
  95. options.c_cflag |= CS8; /* Select 8 data bits */
  96. options.c_cflag &= ~CRTSCTS; /* Disable hardware flow control */
  97. //options.c_lflag |= ICANON; /* Canonical mode*/
  98. //options.c_lflag |= ~(ICANON | ECHO | ECHOE); /* Enable data to be processed as Canonical input */
  99. options.c_cflag |= (CLOCAL | CREAD); /* Enable the receiver and set local mode */
  100. tcsetattr(fd, TCSANOW, &options); /* Set the new options for the port */
  101. }
  102. return (fd);
  103. }
Add Comment
Please, Sign In to add comment