简体   繁体   中英

Arduino serial communication working strange

I am writing a C# program that has to communicate with an Arduino. Basically it sends data to it and I should be able to read in the serial monitor.

C# code:

if (errCheck[i].IsChecked.GetValueOrDefault() == true)
    err = "1"+err;
else 
    err = "0"+err;
_serialPort.Write("<16,"+ Convert.ToUInt32(err,2) + ">"); 

Arduino code:

void parseData() {      // split the data into its parts

    char * strtokIndx; // this is used by strtok() as an index

    //strtokIndx = strtok(tempChars,",");      // get the first part - the string
    //strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

    strtokIndx = strtok(tempChars, ","); // this continues where the previous call left off
    integerFromPC = atoi(strtokIndx);     // convert this part to an integer


    switch (integerFromPC) {
        //all cases         
        case 16: //managing errors
            delay(10);
            strtokIndx = strtok(NULL, ",");
            uint32_tFromPC = atoi(strtokIndx);     
            errors=uint32_tFromPC;
            Serial.print("errors Updated" );

When the last checkbox is checked (so my binary string is 1 and 31 0's) the serial monitor reads 7F FF FF FF instead of 80 00 00 00 .
I have tried using ulong but it doesn't seem to work either, any ideas?

Why do you want to convert the String to int32 and then back to String?? Simply do this:

if (errCheck[i].IsChecked.GetValueOrDefault() == true)
    err = "1"+err;
else 
    err = "0"+err;
_serialPort.Write("<16,"+ err + ">"); 

Even Uint32 can't take 32 digits!

And in your arduino code you are using atoi too. Handle it as a String. Why do u need it as a integer?

Btw thing about using enums for bitwise operations for examples look here: http://www.alanzucconi.com/2015/07/26/enum-flags-and-bitwise-operators/

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