简体   繁体   English

向/从串口发送和接收int值

[英]Sending and receiving int value to/from serial port

I am developing a window's application that sends and receives data to an Arduino via the serial port. 我正在开发一个窗口的应用程序,该应用程序通过串行端口向Arduino发送和接收数据。

The problem I have is when I try to send an int value to the serial port and pick it up in the Arduino program. 我遇到的问题是当我尝试将int值发送到串行端口并在Arduino程序中将其提取时。 I am using WriteFile() in the window's program to send the int and pick it up in the Arduino using Serial.parseInt() . 我正在窗口程序中使用WriteFile()发送int并使用Serial.parseInt()在Arduino Serial.parseInt() When I send char values I can pick them up with no problems. 当我发送char值时,我可以毫无问题地拾取它们。

If I want to send int values the only time I receive an integer in the arduino is if I send integers 48 to 57 which give me an int value of 0 to 9 which are the ASCII characters for decimal 48 to 57, weird. 如果我只想在arduino中接收一个整数,则要发送int值,如果我发送的整数48至57,则给我一个0至9的int值,它们是十进制48至57的ASCII字符,这很奇怪。 eg 57, The Arduino seems to pick this up as 9 which is the char value for ASCII 57. 例如57,Arduino似乎将其取为9,这是ASCII 57的char值。

below is the code in the windows program and the Arduino 下面是Windows程序和Arduino中的代码

C++ code: C ++代码:

DWORD ComPort::WriteAnalogData(int *buffer)
{
    if (!connected)
        return 0;

    DWORD bytesSent;
    DWORD errors;

    if (!WriteFile(hCom, (void *)buffer, sizeof(buffer), &bytesSent, 0))
    ClearCommError(hCom, &errors, NULL);    // If it fails, clear com errors
    else return bytesSent;      // Return the number of bytes sent
    return 0;                   // Or return 0 on failure
}

the return value(bytesSent) after the int is written is 4 so I think this function is working. 写入int后的返回值(bytesSent)为4,因此我认为此函数有效。 I have a similar function for sending single bytes of data which works and the Arduino picks the data up ok 我有一个类似的功能,可以发送单个字节的数据,并且可以正常工作,Arduino可以将数据拾取好

Arduino Code: Arduino代码:

int scadaAnalogVal;
scadaAnalogVal = Serial.parseInt();
digitalWrite(scadaAnalogVal,HIGH);

can anyone tell me what's going on. 谁能告诉我发生了什么事。 Probably something simple but i can't see what the issue is, thanks. 可能很简单,但是我看不出问题是什么,谢谢。

The Arduino parseInt() method has a long return type (32-bits) in the Arduino architecture. Arduino parseInt()方法在Arduino体系结构中具有返回类型(32位)。 I think you should change your Arduino code to: 我认为您应该将Arduino代码更改为:

long scadaAnalogVal;

ParseInt documentation ParseInt文档

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

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