Skip to content

Instantly share code, notes, and snippets.

Created December 8, 2012 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4241153 to your computer and use it in GitHub Desktop.
Save anonymous/4241153 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;
struct modeeg_packet
{
uint8_t sync0; // = 0xA5
uint8_t sync1; // = 0x5A
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=460800;
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;
for (i = 0 ; i < 9999999 ; i++) {
char szBuff[n + 1] = {0};
DWORD dwBytesRead = 0;
if(!ReadFile(handler, szBuff, n, &dwBytesRead, NULL)){
cerr << "Reading error" << endl;
}
modeeg_packet* msg = (modeeg_packet*)szBuff;
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