#include #include #include #include #include #include #include #include using namespace std; struct termios oldterm, newterm; int fd = 0; string strRecvBuf; bool serial_init(int port, int baudrate) { bool result = false; char portname[81] = { 0 }; unsigned int baud_symbol = 0; sprintf(portname, "/dev/ttyAMA%d", port); baud_symbol = B115200; // HARD-CODED FOR THIS TEST fd = open(portname, O_RDWR | O_NOCTTY ); // if we were able to open the serial port if (fd) { // preserve current settings if (tcgetattr(fd, &oldterm) != -1) { bzero(&newterm, sizeof(newterm)); // clear structure newterm.c_cflag = baud_symbol | CS8 | CLOCAL | CREAD; newterm.c_iflag = IGNPAR; // do not want to translate CR to newline newterm.c_oflag = 0; newterm.c_lflag &= ~ICANON; newterm.c_cc[VTIME] = 0; // block for 1 sec for emergencies newterm.c_cc[VMIN] = 1; // no character // flush something and check for error if (tcflush(fd, TCIFLUSH) != -1) { // setup the port for our new settings and check for any errors if (tcsetattr(fd, TCSANOW, &newterm) != -1) { result = true; } } } } return(result); } int serial_tx(unsigned char ch) { return (write(fd, &ch, 1)); } string serial_rx_buf() { string strRes; unsigned char buf[4096]; // size is somewhat arbitrary ssize_t sstBytesRead = read(fd, buf, sizeof(buf)); if (sstBytesRead < 0) { char buf[80]; strerror_r(errno, buf, sizeof(buf)); string strMsg = "serial_rx_buf read got error: "; strMsg += buf; throw runtime_error(strMsg.c_str()); } else if (sstBytesRead > 0) { strRes = string((char *) buf, sstBytesRead); } else { throw runtime_error("Got unexpected EOF!"); } return strRes; } void serial_close() { tcsetattr(fd, TCSANOW, &oldterm) ; close(fd); } ///////////////////////////// int main() { const size_t BOUNDARIES = 1000; size_t stNextBoundary = BOUNDARIES; size_t stBytesRcvd = 0; serial_init(0, 115200); for (;;) { string s = serial_rx_buf(); stBytesRcvd += s.size(); if (stBytesRcvd > stNextBoundary) { printf("%u\n", stBytesRcvd); stNextBoundary += BOUNDARIES; } } serial_close(); return 0; }