gpt4 book ai didi

c# - 串口+C#数据接收问题

转载 作者:行者123 更新时间:2023-11-30 17:11:58 29 4
gpt4 key购买 nike

我想将出现在 Arduino 中的数据传输到我的 C# 应用程序,但不知道我的代码有什么问题。Arduino 代码来了:

int switchPin = 7;
int ledPin = 13;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean flashLight = LOW;

void setup()
{
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
}

boolean debounce(boolean last)
{
boolean current = digitalRead(switchPin);
if (last != current)
{
delay(5);
current = digitalRead(switchPin);
}
return current;
}

void loop()
{
currentButton = debounce(lastButton);
if (lastButton == LOW && currentButton == HIGH)
{
Serial.print("UP");

digitalWrite(ledPin, HIGH);
}
if (lastButton == HIGH && currentButton == LOW)
{
Serial.print("DOWN");

digitalWrite(ledPin, LOW);
}

lastButton = currentButton;
}

如您所见,这个简单的草图在按下按钮时向端口发送消息。我创建了一个控制台 C# 应用程序来接收数据:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text;
using System.IO.Ports;

namespace ArduinoTestApplication
{
class Program
{
static void Main(string[] args)
{
SerialPort port = new SerialPort("COM3", 9600);
port.Open();
string lane;
while (true)
{
lane = port.ReadLine();

Console.WriteLine(lane);
}

}
}
}

但是当我按下按钮时,控制台仍然是空的。请告诉我哪里出了问题!

最佳答案

一切都很简单。我忘记写了

Serial.begin()

:D 就是这样。现在可以了。

关于c# - 串口+C#数据接收问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066595/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com