Can't read Serial Input
I have an Arduino hooked up via usb to my computer. From it I try to read the from the COM port.
Can anyone see if theres anything blatantly wrong with this???
void main()
{
int exitStatus;
开发者_如何学编程 unsigned int bytesToRead = 1;
unsigned char *buffer = (unsigned char*) malloc(sizeof(unsigned char) + 1);
Serial *connection = new Serial("COM3");
if(connection->IsConnected()){
exitStatus=connection->ReadData(buffer, bytesToRead);
if( *buffer > 0)
<statement I'm trying to hit>
}
}
Right now it always hits the 'statement I'm trying to hit' even when it's no supposed to. Debugging it always shows that the contents of buffer is a lot of junk. I know what's coming in from the serial input should be right because from what I'm seeing in the serial monitor, it all looks good.
Thoughts?
You are not evaluating the exitStatus
variable, which might indicate it the read was successful.
Also you don't need to malloc memory if you want to read just one byte, you can simply pass the pointer to a local char variable.
And while I'm at it, the type for main is either int main()
or int main(int argc, char** argv)
int main()
{
int exitStatus;
unsigned int bytesToRead = 1;
unsigned char buffer;
Serial *connection = new Serial("COM3");
if(connection->IsConnected()){
exitStatus=connection->ReadData(&buffer, 1);
if((exitStatus == <Insert the value for a correct read status>) && (buffer != '0'))
<statement I'm trying to hit>
}
return 0;
}
update Changed the != 0 check to != '0', since I suspect that there is a '0' character (=0x30) comming from the serial interface.
精彩评论