【问题标题】:c++ sending ascii 254 through serial communicationc++通过串口通信发送ascii 254
【发布时间】:2013-07-15 12:09:42
【问题描述】:

我正在使用来自 Arduino 网站的 Serial.cpp 代码。

我现在正在做的是使用 R220HPRS 继电器开关。问题是示例代码在 VB 中,而我使用的是 c++。所以,我通读了手册,发现通过发送 ASCII 254 和 ASCII 1 会打开 Relay 1 开关

VB 示例

  MSComm1.Output = Chr$(254) 'Enter Command Mode 
  MSComm1.Output = Chr$(1) 'Turn On Relay 1 

然后我从 Arduino 的网站上找到了 Serial.cpp,并决定尝试使用它。 当我这样做时,我与设备建立了连接(或者当我运行程序时它说它),但我不知道如何发送 ASCII 254 和 ASCII 1

这是代码 来自 Serial.cpp

bool Serial::WriteData(char *buffer, unsigned int nbChar)
{
    DWORD bytesSend;

    //Try to write the buffer on the Serial port
    if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
    {
        //In case it don't work get comm error and return false
        ClearCommError(this->hSerial, &this->errors, &this->status);

        return false;
    }
    else
        return true;
}

主要

 int _tmain(int argc, _TCHAR* argv[])
{
    printf("Welcome to the serial test app!\n\n");

Serial* SP = new Serial("\\\\.\\COM3");    // adjust as needed

if (SP->IsConnected())
    printf("We're connected");

while(SP->IsConnected())
{
    char *chr0 = "254";
    SP->WriteData(chr0, 1); 
    SP->WriteData(chr0, 1);
    Sleep(500);
}
return 0;
}

我知道 chr0 = "254" 不是 ASCII,但我不知道如何发送 ASCII 254 和 ASCII 1。

【问题讨论】:

    标签: c++ serial-port ascii


    【解决方案1】:

    要发送一个值为 245 的 char,您需要将其设为字符:

    char chr0 = 254; 
    
    SP->WriteData(&chr0, 1); 
    

    【讨论】:

    • 为了安全起见,chr0 不应该是unsigned 以避免溢出吗?
    • 可能,但这意味着复制并粘贴所有代码以将所有字符更改为无符号,我懒得这样做 - 这不太可能在 Windows 系统上引起问题 - 并且WreiteFile 是一个 windows 调用...
    【解决方案2】:
    char *chr0, you are pointing to a sting.
    it should be char ch = 254;
    and then send the address of ch.
    

    记住单个字符的单引号!!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多