Arduino,Visual C#最佳串行通信

时间:2017-08-19 14:37:40

标签: c# c arduino serial-port port

我是Arduino和串口的新手,我想在Arduino和我的C#程序之间进行最佳沟通。在我的代码中,我希望尽可能快地控制一个或多个伺服电机。这是我的Arduino代码:

#include <Servo.h>

Servo serv;

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(5);
  pinMode(9,OUTPUT);
  serv.attach(9);
}

String msg;
void loop() {
  String val = Serial.readString();
  if(val!=0) {
    if(val.startsWith("U")) {
      val.replace("U","");
      serv.write(val.toInt());
      delay(10);
    }
  }
  if(Serial.available()>0) {
    msg = "U";
    msg = msg+serv.read();
    Serial.println(msg);
  }
}

我的C#程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace arduino_servo {
  public partial class Form1 : Form {
    SerialPort port;
    public Form1() {
      InitializeComponent();
      init();
    }

    private void Form1_Load(object sender, EventArgs e) {
    }

    private void init() {
      port = new SerialPort();
      port.PortName = "COM5";
      port.BaudRate = 115200;
      port.DataReceived += new SerialDataReceivedEventHandler(Primire_date);
      try {
        port.Open();
      }
      catch(Exception ex) {
        MessageBox.Show("Eroare",ex.Message,MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }

    private void trackBar1_Scroll(object sender, EventArgs e) {
      if (port.IsOpen) {
        port.WriteLine("U"+trackBar1.Value.ToString());
      }
    }

    private void Primire_date(object emitator, SerialDataReceivedEventArgs e) {
      string msg = port.ReadLine();
      if (msg.IndexOf("U") > -1) {
        msg = msg.Replace("U", "");
        label1.Text = msg;
      }
    }
  }
}

如果你们能给我一些建议或一些修改,我会非常感激。我的沟通有点滞后。

0 个答案:

没有答案