Here you can find a post serie about using serial port communications with C/C++ and C#, for Windows, Linux and microcontrollers.
This code can be used (of course) for serial cable communications, USB2Dynamixel and indeed Zigbee:
Header:
[sourcecode language="cpp"]
class SerialPort {
private:
HANDLE serialPortHandle;
public:
SerialPort();
~SerialPort();
int connect ();
int connect (wchar_t *device);
//int connect (char *deviceName, int baudRate, SerialParity parity);
void disconnect(void);
int sendArray(unsigned char *buffer, int len);
int getArray (unsigned char *buffer, int len);
void clear();
};
[/sourcecode]
Body:
[sourcecode language="cpp"]
SerialPort::SerialPort() {
serialPortHandle = INVALID_HANDLE_VALUE;
}
SerialPort::~SerialPort() {
if (serialPortHandle!=INVALID_HANDLE_VALUE)
CloseHandle(serialPortHandle);
serialPortHandle = INVALID_HANDLE_VALUE;
}
int SerialPort::connect() {
return connect(L"COM1");
}
int SerialPort::connect( wchar_t* device) {
int error=0;
DCB dcb;
memset(&dcb,0,sizeof(dcb));
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = 57600;
dcb.Parity = NOPARITY;
dcb.fParity = 0;
dcb.StopBits = ONESTOPBIT;
dcb.ByteSize = 8;
serialPortHandle = CreateFile(device, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, NULL);
if (serialPortHandle != INVALID_HANDLE_VALUE) {
if(!SetCommState(serialPortHandle,&dcb))
error=2;
}
else {
error=1;
}
if (error!=0) {
disconnect();
}
else {
clear();
}
return error;
}
void SerialPort::disconnect(void) {
CloseHandle(serialPortHandle);
serialPortHandle = INVALID_HANDLE_VALUE;
//printf("Port 1 has been CLOSED and %d is the file descriptionn", fileDescriptor);
}
int SerialPort::sendArray(unsigned char *buffer, int len) {
unsigned long result;
if (serialPortHandle!=INVALID_HANDLE_VALUE)
WriteFile(serialPortHandle, buffer, len, &result, NULL);
return result;
}
int SerialPort::getArray (unsigned char *buffer, int len) {
unsigned long read_nbr;
read_nbr = 0;
if (serialPortHandle!=INVALID_HANDLE_VALUE)
{
ReadFile(serialPortHandle, buffer, len, &read_nbr, NULL);
}
return((int) read_nbr);
}
void SerialPort::clear() {
PurgeComm (serialPortHandle, PURGE_RXCLEAR | PURGE_TXCLEAR);
}
[/sourcecode]
Hi there, how would I use this class with the setup PC->USB2Dynamixel->Zig2Serial->Zig100 and Zig110->CM510? I am at ease with C++ but not with communication systems...Cheers and keep up the good work!
ResponderEliminarIt's easy, you always use the communications (by wire or wireless) as if you were using a file, open, read, write, close commands. You should set the proper COM (Win) tty (Linux) port and the baud rate.
ResponderEliminarThanks a lot! Actually it was the baudrate that was messed up, I didn't update my post, my bad.
ResponderEliminarAny update on Bioloid control?
Not soon, sorry, I’m suffering health problems.
ResponderEliminarOh sorry to hear that, take care! Hope everything will go fine :) looking forward to reading from you :D
ResponderEliminarThanks :)
ResponderEliminar