简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM