Skip to content

Instantly share code, notes, and snippets.

@alepez
Last active December 18, 2015 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alepez/5748972 to your computer and use it in GitHub Desktop.
Save alepez/5748972 to your computer and use it in GitHub Desktop.
stupid c++ (almost c) program to write data to serial port. Input string is hex. serialecho /dev/ttyUSB0 9600 "63 69 61 6f"
/*
* main.cpp
*
* Created on: Jun 10, 2013
* Author: pez
*/
#include <termios.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <cstdlib>
#include <stdio.h>
void parseData(const char* dataStr, unsigned char* data, int* length) {
::memset(data, 0, sizeof(data));
const char* ds = dataStr;
unsigned char* d = data;
char byteStr[3] = { 0 };
while (true) {
if (ds[0] == ' ') {
++ds;
}
if (ds[0] == 0 || ds[1] == 0) {
break;
}
byteStr[0] = ds[0];
byteStr[1] = ds[1];
char* endPtr = 0;
int num = strtoul(byteStr, &endPtr, 16);
printf("%c %c => %i\n", ds[0], ds[1], num);
*d = num;
++(*length);
ds += 2;
++d;
}
}
#define CASE_SPEED(speed) case speed: return B ## speed;
int to_speed_t(int speedInt) {
switch (speedInt) {
CASE_SPEED(0);
CASE_SPEED(50);
CASE_SPEED(75);
CASE_SPEED(150);
CASE_SPEED(200);
CASE_SPEED(300);
CASE_SPEED(600);
CASE_SPEED(1200);
CASE_SPEED(1800);
CASE_SPEED(2400);
CASE_SPEED(4800);
CASE_SPEED(9600);
CASE_SPEED(19200);
CASE_SPEED(38400);
CASE_SPEED(57600);
CASE_SPEED(115200);
CASE_SPEED(230400);
CASE_SPEED(460800);
CASE_SPEED(500000);
CASE_SPEED(576000);
CASE_SPEED(921600);
CASE_SPEED(1000000);
CASE_SPEED(1152000);
CASE_SPEED(1500000);
CASE_SPEED(2000000);
CASE_SPEED(2500000);
CASE_SPEED(3000000);
CASE_SPEED(3500000);
CASE_SPEED(4000000);
default:
return 0;
}
}
int main(int argc, char* argv[]) {
const char* devFilename = argv[1];
const char* speedStr = argv[2];
const char* dataStr = argv[3];
int dev = ::open(devFilename, O_RDWR | O_NONBLOCK);
::tcflush(dev, TCIOFLUSH);
termios tio = { 0 };
::memset(&tio, 0, sizeof(termios));
::tcgetattr(dev, &tio);
tio.c_iflag &= ~(ICRNL | IMAXBEL);
tio.c_iflag |= (BRKINT);
tio.c_oflag &= ~(OPOST | ONLCR);
tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE);
tio.c_cflag |= (CS8 | CLOCAL | CREAD);
tio.c_lflag &= ~(ICANON | ISIG | ECHO);
tio.c_lflag |= (IEXTEN | ECHOK | ECHOCTL | ECHOKE);
tio.c_cc[VTIME] = 0;
tio.c_cc[VMIN] = 0;
int speed = to_speed_t(::atoi(speedStr));
::cfsetispeed(&tio, speed);
::cfsetospeed(&tio, speed);
::tcsetattr(dev, TCSANOW, &tio);
unsigned char data[1024];
int length = 0;
parseData(dataStr, data, &length);
::write(dev, data, length);
::close(dev);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment