Created
June 23, 2012 00:45
-
-
Save anonymous/2976017 to your computer and use it in GitHub Desktop.
Serial call/response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <fcntl.h> | |
#include <termios.h> | |
#include <errno.h> | |
#include <sys/ioctl.h> | |
struct tempduino_data | |
{ | |
int fd; | |
char buf[64]; | |
}; | |
/* readwrite() writes a byte and reads the response */ | |
int readwrite(struct tempduino_data *d) | |
{ | |
/* fill buffer with temporary data */ | |
sprintf(d->buf, "test"); | |
/* write a byte */ | |
write_tempduino_byte(d); | |
/* read the response */ | |
read_tempduino(d); | |
return 1; | |
} | |
/* open the serial port file descriptor */ | |
int init_serial_fd(char *ttyname, struct tempduino_data *d) | |
{ | |
/* open the file descriptor */ | |
d->fd = open(ttyname, O_RDWR | O_NOCTTY); | |
printf("fd opened as %i\n", d->fd); | |
/* wait for the Arduino to reboot */ | |
usleep(3500000); | |
return 1; | |
} | |
/* set the serial options to canonical */ | |
int init_serial_options(int fd) | |
{ | |
struct termios toptions; | |
tcgetattr(fd, &toptions); | |
/* 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_iflag |= ICANON; | |
tcsetattr(fd, TCSANOW, &toptions); | |
return 1; | |
} | |
/* write a byte */ | |
int write_tempduino_byte(struct tempduino_data *d) | |
{ | |
char *str = "1"; | |
int n; | |
n = write(d->fd, str, 1); | |
printf("%i bytes written\n", n); | |
return 1; | |
} | |
/* read what the Arduino sends */ | |
int read_tempduino(struct tempduino_data *d) | |
{ | |
int n; | |
n = read(d->fd, d->buf, 64); | |
/* terminating zero in the string */ | |
d->buf[n] = 0; | |
printf("%i bytes read, buffer contains: %s\n", n, d->buf); | |
return 1; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
struct tempduino_data w; | |
init_serial_fd("/dev/ttyACM0", &w); | |
init_serial_options(w.fd); | |
readwrite(&w); | |
readwrite(&w); | |
readwrite(&w); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment