Skip to content

Instantly share code, notes, and snippets.

@epatel
Forked from anonymous/gist:4241153
Created December 8, 2012 21:08
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 epatel/4241968 to your computer and use it in GitHub Desktop.
Save epatel/4241968 to your computer and use it in GitHub Desktop.
/*
* main.cpp
*
* Created on: 08.12.2012
* Author: sk
*/
#include <iostream>
#include <windows.h>
using namespace std;
LPCSTR PORTNAME = "COM3";
const int n = 17-2; // -2 for removing sync0 bytes from struct
struct modeeg_packet
{
#if 0
// These will be searched for in code
uint8_t sync0; // = 0xA5
uint8_t sync1; // = 0x5A
#endif
uint8_t version; // = 2
uint8_t count; // packet counter. Increases by 1 each packet
uint16_t data[6]; // 10-bit sample (= 0 - 1023) in big endian (Motorola) format
uint8_t switches; // State of PD5 to PD2, in bits 3 to 0
};
HANDLE initSerial() {
HANDLE hSerial = CreateFile(PORTNAME, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hSerial == INVALID_HANDLE_VALUE) {
cerr <<
"Failed to read from port" << endl <<
GetLastError() << endl;
}
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
cerr << "Couldn't set COM port state" << endl;
}
dcbSerialParams.BaudRate=CBR_57600; // Firmware states 57600 baud
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams)){
cerr << "Analyzing error" << endl;
}
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
if(!SetCommTimeouts(hSerial, &timeouts)){
cerr << "Setting timeout error" << endl;
}
return hSerial;
}
void closeSerialPort(HANDLE hSerial) {
CloseHandle(hSerial);
}
int main() {
cout << "reading from " << PORTNAME << endl;
HANDLE handler = initSerial();
int i = 0;
while (1) {
char sync0;
char sync1;
struct modeeg_packet msg;
DWORD dwBytesRead = 0;
// Find first 0xa5 marker
do {
if (!ReadFile(handler, &sync0, 1, &dwBytesRead, NULL)) {
cerr << "Reading error" << endl;
}
} while (sync0 != 0xa5);
// Read and check second byte for 0x5a
if (!ReadFile(handler, &sync1, 1, &dwBytesRead, NULL)) {
cerr << "Reading error" << endl;
}
if (sync1 == 0x5a) {
if (!ReadFile(handler, &msg, n, &dwBytesRead, NULL)) {
cerr << "Reading error" << endl;
}
cout << msg.count << endl;
}
}
closeSerialPort(handler);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment