Arduino串口通讯工作奇怪

时间:2017-11-02 08:21:53

标签: c# arduino serial-port

我正在编写一个必须与Arduino通信的C#程序。基本上它向它发送数据,我应该能够在串行监视器中读取。

C#代码:

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

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" );

当选中最后一个复选框时(因此我的二进制字符串为1和31 0),串行监视器将显示7F FF FF FF而不是80 00 00 00
我尝试过使用ulong,但似乎也没有任何想法?

1 个答案:

答案 0 :(得分:0)

为什么要将String转换为int32然后再转换为String? 只需这样做:

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

即使Uint32也不能取32位数字!

在您的arduino代码中,您也在使用atoi。将其作为字符串处理。为什么你需要它作为整数?

关于为按位运算使用枚举的例子,请看这里: http://www.alanzucconi.com/2015/07/26/enum-flags-and-bitwise-operators/