-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcanonicalarduinoread.c
74 lines (60 loc) · 1.67 KB
/
canonicalarduinoread.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* www.chrisheydrick.com
June 23 2012
CanonicalArduinoRead write a byte to an Arduino, and then
receives a serially transmitted string in response.
The call/response Arduino sketch is here:
https://gist.github.com/2980344
Arduino sketch details at www.chrisheydrick.com
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>
#define DEBUG 1
int main(int argc, char *argv[])
{
int fd, n, i;
char buf[64] = "temp text";
struct termios toptions;
/* open serial port */
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY);
printf("fd opened as %i\n", fd);
/* wait for the Arduino to reboot */
usleep(3500000);
/* get current serial port settings */
tcgetattr(fd, &toptions);
/* set 9600 baud both ways */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* Canonical mode */
toptions.c_lflag |= ICANON;
/* commit the serial port settings */
tcsetattr(fd, TCSANOW, &toptions);
/* Send byte to trigger Arduino to send string back */
write(fd, "0", 1);
/* Receive string from Arduino */
n = read(fd, buf, 64);
/* insert terminating zero in the string */
buf[n] = 0;
printf("%i bytes read, buffer contains: %s\n", n, buf);
if(DEBUG)
{
printf("Printing individual characters in buf as integers...\n\n");
for(i=0; i<n; i++)
{
printf("Byte %i:%i, ",i+1, (int)buf[i]);
}
printf("\n");
}
return 0;
}