c#串口奇数值?

标签 c# c++ arduino

我正在构建一个飞行模拟器,其中我有一个名为 fsuipc 的程序,它允许您连接到 Microsoft 飞行模拟器 x,并且您可以在 C# 中读取和写入数据 - 非常方便!

我已经构建了一个垂直速度计,它只是一个带有针的伺服系统。它连接到运行 c++ 修改版本的 arduino。我希望 c# 将当前的垂直速度发送到 arduino,但遇到了问题并且在过去的 2 天里尝试过。

问题是 arduino 发回的大部分是 -1,当它应该发回 1566(每分钟英尺)之类的东西时会抛出奇数 49。

帮助!

这里是处理垂直速度的 c# 代码部分(忽略有效的空速)。显示当前空速的值工作正常但发送然后接收是完全错误的

private void timer1_Tick(object sender, EventArgs e)
{
    // Process the default group
    try
    {

        FSUIPCConnection.Process();


        // IAS - Simple integer returned so just divide as per the 
        // FSUIPC documentation for this offset and display the result.
        double airpeedKnots = ((double)airspeed.Value / 128d);
        this.txtIAS.Text = airpeedKnots.ToString("f1");

        double verticalspeedfpm = ((double)verticalspeed.Value * 60 * 3.28084 / 256); //gets vertical speed in meters per sec and converts it to feeet per min.
        this.txtvsi.Text = verticalspeedfpm.ToString("f1"); //outputs it to a test box so i can see what the vertical speed is.

        serialPort1.Open(); //opens serial port (com 4) - arduino
        serialPort1.WriteLine(verticalspeedfpm.ToString("f1")); //sends the vertical speed data
        read = (serialPort1.ReadLine()); // reads what the arduino sent back
        serialPort1.Close();//closes the serial port
        txtrecieved.Clear();//cleares the text box
        this.txtrecieved.Text = read;//writes what was recieved 
        // Avionics Master Switch
        this.chkAvionics.Checked = (avionics.Value > 0);  // 0 = Off, 1 = On.

这里是 arduino 代码,可以简单地 ping 回消息:

int vsint;
String vsstring;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  vsstring = Serial.read();
  delay(10);
  Serial.println(vsstring);
}

the windows form - the call back box should be equal to the vs box.

最佳答案

void loop() {
  // put your main code here, to run repeatedly:
  vsstring = Serial.read();
  delay(10);
  Serial.println(vsstring);
}

在您的循环中,您正在从串行读取,而没有首先检查是否有任何可读取的内容 (available())。当您调用 Serial.read() 并且接收缓冲区中没有任何内容时,它会返回 -1。这就是 -1 的来源。

至于 49,您得到它是因为您将数字作为 ascii 文本发送。查看 ascii 表,看看你得到的数字是否突然变得很有意义。您正在从 Serial 读取一个字符串而不是一个字符。 read() 返回一个整数。 String 允许在 = 的 RHS 上使用 int。当它看到一个时,它会将 int 转换为 ascii。所以你得到了 ascii 码的 ascii 表示。

关于c#串口奇数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631256/

相关文章:

c++ - 2个int变体之间的管道运算符是什么意思?

c++ - Arduino IDE 无法检测到 ZumoMotor.H(PIXY PET)

c++ - 如何测量 Arduino 函数的执行速度?

c# - 将具有依赖项 v1 的项目添加到具有依赖项 v1.1 的项目

c# - ImageSharp 在 Core 2.2 中的图像上绘制形状

c++ - 如何返回私有(private)指针成员变量

C++ 将数组写入注册表中的二进制条目

c# - 从资源或站点获取 XML

c# - 从序列末尾获取元素的linq扩展方法

c - arduino上的PWM褪色LED