简体   繁体   English

Arduino串行通信工作异常

[英]Arduino serial communication working strange

I am writing a C# program that has to communicate with an Arduino. 我正在编写一个必须与Arduino通信的C#程序。 Basically it sends data to it and I should be able to read in the serial monitor. 基本上,它向它发送数据,我应该能够在串行监视器中读取。

C# code: C#代码:

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

Arduino code: Arduino代码:

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 . 选中最后一个复选框时(我的二进制字符串是1和31 0),串行监视器将读取7F FF FF FF而不是80 00 00 00
I have tried using ulong but it doesn't seem to work either, any ideas? 我已经尝试过使用ulong但是似乎也行不通,有什么想法吗?

Why do you want to convert the String to int32 and then back to String?? 为什么要将String转换为int32,然后再转换回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! 即使是Uint32也不能使用32位数字!

And in your arduino code you are using atoi too. 在您的arduino代码中,您也正在使用atoi。 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/ 顺便说一句有关将枚举用于按位运算的示例,请看这里: http : //www.alanzucconi.com/2015/07/26/enum-flags-and-bitwise-operators/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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