用arduino控制伺服系统



我试图控制一个伺服与arduino uno和c#,但伺服不移动

下面是Arduino代码:

#include <Servo.h>
Servo servoT1;
void setup()
{
  Serial.begin(9600);
   servoT1.attach(9); 
}
int i=0;
void loop()
{
   if (Serial.available() > 0)
   {
      i=Serial.read();
      i=map(i, 0, 100, 0, 179);
      servoT1.write(i);
    }
}
下面是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_throttle
{
    public partial class Form1 : Form
    {
        SerialPort uno1 = new SerialPort("COM3", 9600);
        public Form1()
        {
            InitializeComponent();
        }
        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            uno1.Open();
            uno1.Write(HScroll.ToString());
            uno1.Close();
        }
    }
}

我想通过在程序中滚动hScrollBar来设置伺服角度。

串口。Read()方法返回可用的传入串行数据的第一个字节http://arduino.cc/en/Serial/Read但是你发送的是字符串(字符数组)尝试从c#中只发送一个字节或字符要做到这一点,你需要检查最大值是256

和另一个你需要发送滚动条的值(你在发送一个字符串的整个对象)

试试这个

uno1.Write (Convert.ToByte (HScroll.value));

最新更新