Guest User

Untitled

a guest
Dec 17th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <math.h>
  4.  
  5. #include <unistd.h> // for sleep function
  6.  
  7. #include <libserialport.h> // cross platform serial port lib
  8. //#include "protocol.h"
  9.  
  10. //const char* desired_port = "COM8";
  11. const char* desired_port = "/dev/cu.usbmodem14101";
  12. const int desired_baud = 9600;
  13.  
  14. struct sp_port *port;
  15.  
  16. void list_ports() {
  17. int i;
  18. struct sp_port **ports;
  19.  
  20. enum sp_return error = sp_list_ports(&ports);
  21. if (error == SP_OK) {
  22. for (i = 0; ports[i]; i++) {
  23. printf("Found port: '%s'\n", sp_get_port_name(ports[i]));
  24. }
  25. sp_free_port_list(ports);
  26. } else {
  27. printf("No serial devices detected\n");
  28. }
  29. printf("\n");
  30. }
  31.  
  32. void parse_serial(char *byte_buff, int byte_num) {
  33. for(int i = 0; i < byte_num;i++){
  34. printf("%c", byte_buff[i]);
  35. }
  36. printf("\n");
  37. }
  38.  
  39. int main() {
  40. list_ports();
  41.  
  42. printf("Opening port '%s' \n", desired_port);
  43. enum sp_return error = sp_get_port_by_name(desired_port,&port);
  44. if (error == SP_OK) {
  45. error = sp_open(port,SP_MODE_READ);
  46. if (error == SP_OK) {
  47. sp_set_baudrate(port,desired_baud);
  48. for(;;) {
  49.  
  50. sleep(0.5); // can do something else in mean time
  51. int bytes_waiting = sp_input_waiting(port);
  52. if (bytes_waiting > 0) {
  53. printf("Bytes waiting %i\n", bytes_waiting);
  54. char byte_buff[512];
  55. int byte_num = 0;
  56. byte_num = sp_nonblocking_read(port,byte_buff,512);
  57. parse_serial(byte_buff,byte_num);
  58. }
  59. fflush(stdout);
  60. }
  61.  
  62. sp_close(port);
  63. } else {
  64. printf("Error opening serial device\n");
  65. }
  66. } else {
  67. printf("Error finding serial device\n");
  68. }
  69.  
  70.  
  71. return 0;
  72. }
Add Comment
Please, Sign In to add comment