简体   繁体   English

C# 与 arduino 通信(arduino 不断发送数据)

[英]C# communication with arduino (arduino keeps sending data)

I'm working on a project in C#.我正在 C# 中开展一个项目。 The program is a control program for an arduino.该程序是 arduino 的控制程序。 I've written some code to write to the serial of the arduino and have programmed the arduino to respond with a standard message (an acknoledge if you will) in this case "5".我已经编写了一些代码来写入 arduino 的序列号,并已对 arduino 进行了编程,以在这种情况下以标准消息(如果您愿意,可以确认)响应“5”。 After sending information to the arduino, the arduino responds with a "5" but keeps sending a "5".在向 arduino 发送信息后,arduino 以“5”响应,但继续发送“5”。

Any idea as to why this happens?知道为什么会这样吗?

port config:端口配置:

    private void Ports_SelectedIndexChanged(object sender, EventArgs e)
    {
        _serialPort.PortName = ArrayComPortsNames[Ports.SelectedIndex];//Set your board COM
        _serialPort.BaudRate = (int)Baudrate.Items[Baudrate.SelectedIndex];
        _serialPort.Parity = Parity.None;
        _serialPort.DataBits = 8;
        _serialPort.StopBits = StopBits.One;
        if (!_serialPort.IsOpen)
            _serialPort.Open();
        _serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_serialPort);
    }
    private void sp_serialPort(object sender, SerialDataReceivedEventArgs e)
    {
        //Write the serial port data to the console.
        Console.Write(_serialPort.ReadLine());
    }

C# code: C# 代码:

    private void buttonKeyboard_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyData)
        {
            case Keys.Z:
                PortWrite("z");
                break;
            case Keys.Q:
                PortWrite("q");
                break;
            case Keys.S:
                PortWrite("s");
                break;
            case Keys.D:
                PortWrite("d");
                break;

        }
    }

    private void PortWrite(string message)
    {
        _serialPort.WriteLine(message);
    }

arduino code: arduino 代码:

void setup() {
Serial.begin(9600);

}

void loop() {
if(Serial.available()){
//Serial.println(Serial.read());
Serial.println("5");
}
delay(100);
}

The key here was in the arduino code 关键在arduino代码中

a Serial.read() command in the if clause was added and resolved the problem: 在if子句中添加了Serial.read()命令,并解决了该问题:

void loop() {
if(Serial.available()){
Serial.read(); //clear serial buffer
Serial.println("5");
}

you are sending the value 5 to the serial port in an infinite loop wich is void loop() put a condition that specifies when to send the value您正在无限循环中将值 5 发送到串行端口,这是 void loop() 放置一个指定何时发送值的条件

    bool f=true;
    void loop() {
    if(Serial.available()>0) 
    {
     while(f) 
    {
     Serial.println(5);
f=false;
    } 
    }
    }

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

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