用c++实现pc机与arduino之间的RS232串行通信

Serial communication between pc and arduino via RS232 using c++

本文关键字:RS232 通信 之间 arduino c++ 实现 pc 机与      更新时间:2023-10-16

我正试图通过RS232线与我的arduino duemilanove进行通信。我只是希望能够从桌面应用程序发送一个字节(或字符)到我的arduino。Arduino正在插入我电脑上的USB COM5。我将RS232插入COM1,然后在RS232的另一端分别连接到arduino引脚TX, RX和GND上的引脚2,3和5。

我在以下链接中找到了c++的串行通信类:

http://playground.arduino.cc/Interfacing/CPPWindows

我已经从上面的例子中添加了。h和。cpp文件作为Serial.h和Serial.cpp(我认为这个例子使用了SerialClass.h和SerialClass.cpp,我只是改变了名字)。


在我的arduino上,我有以下代码运行:

// ARDUINO
char incomingByte = 0;
void setup() {
        Serial.begin(9600);
}
void loop() {
        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, HEX);
        }
}

我的c++程序如下:

// C++
#include <iostream>
#include <Windows.h>
#include "Serial.h"
using namespace std;
int main(void)
{
    Serial port("COM1");
    char* msg = "Hello Arduino!";
    int msgLen = strlen(msg);
    bool writeSuccess = port.WriteData(msg, msgLen);
    cout << "nn";
    system("PAUSE");
}

当我使用Arduino的串口查看器来查看打印的内容时,我得到了非常奇怪的值,与我发送的内容不匹配(据我所知)。

当我发送"Hello Arduino!"时,Arduino打印以下内容:

I received: FFFFFFAB
I received: 3A
I received: 3A
I received: A
I received: FFFFFFFA
I received: FFFFFFEB
I received: 6D
I received: 37
I received: 15
I received: 2D
I received: 23
I received: 21
I received: FFFFFFBD
I received: 0

这似乎不是"Hello Arduino!"的正确十六进制,但我不知道为什么它不正确。有人知道我哪里做错了吗?

Arduino使用TTL逻辑进行串行连接。它期望值在0和5V。RS232使用不同的电压-V到+V。你可能需要一个转换器

…不!上拉和下拉不是为了这个原因。

  • TTL = low: 0V, high: 5V

  • RS232 =低:+ 3:+ 15 v,高:3:-15 v

结果. .你需要一个电压转换器(和逆变器),就像David Skogan正确指出的那样。

例子:

  1. 使用离散组件(具有自动回声功能,即在PC上,您将看到您发送的数据):http://project.irone.org/simple-rs232-to-ttl-level-converter.html或http://circuit-diagram.hqew.net/Simple-TTL$2dRS232-Level-Converter-Using-Transistor_2757.html
  2. 带MAX232(或同等)和四个电容的公共电路
  3. 使用USB-RS232转换器,而不是使用USB-UART转换器,例如使用FT232或类似的东西。不需要任何接口

或. .只需使用Arduino上的USB端口,Arduino上已经有FT232接口。

个人评论:i'd avoid solution 1…