繁体   English   中英

使用C ++通过RS232在PC和arduino之间进行串行通信

[英]Serial communication between pc and arduino via RS232 using c++

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

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

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 << "\n\n";
    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 =低:0V,高5V

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

因此,您需要一个电压转换器(和逆变器),就像David Skogan正确指出的那样。

例子:

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

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

个人评论:我会避免解决方案1 ​​...

暂无
暂无

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

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