C# 如何为arduino发送字节?
我开发了一个应用程序,通过套接字将字符串/命令发送到另一台PC应用程序服务器,并通过串行端口将字符串发送到Arduino 问题是:如何向Arduino发送字节? 通过串行端口发送字符串的应用程序服务器的C#:C# 如何为arduino发送字节?,c#,serial-port,arduino,C#,Serial Port,Arduino,我开发了一个应用程序,通过套接字将字符串/命令发送到另一台PC应用程序服务器,并通过串行端口将字符串发送到Arduino 问题是:如何向Arduino发送字节? 通过串行端口发送字符串的应用程序服务器的C#: using System; using System.Windows.Forms; using System.Threading; using System.IO; using System.IO.Ports; public class senddata { private vo
using System;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.IO.Ports;
public class senddata
{
private void Form1_Load(object sender, System.EventArgs e)
{
// Define a Porta Serial
serialPort1.PortName = textBox2.Text;
serialPort1.BaudRate = 9600;
serialPort1.Open();
}
private void button1_Click(object sender, System.EventArgs e)
{
serialPort1.Write("1"); // 1 is a String
}
}
>在ARDUINO上运行的C++代码:< /P>
#include <Servo.h>
Servo servo;
int pos;
void setup()
{
servo.attach(9);
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop()
{
if (Serial.available()) {
int msg = Serial.read();
if (msg > 0) {
servo.write(msg); // 10 = pos 1 10-9 = 1
}
}
}
#包括
伺服;
int pos;
无效设置()
{
伺服。连接(9);
Serial.begin(9600);
pinMode(13,输出);
}
void循环()
{
if(Serial.available()){
int msg=Serial.read();
如果(消息>0){
servo.write(msg);//10=pos 1 10-9=1
}
}
}
为了更好地理解这个问题,我将代码更改为(但是,因为伺服的值从0到180,所以这不起作用):
#包括
伺服;
int pos;
无效设置()
{
伺服。连接(9);
Serial.begin(9600);
pinMode(13,输出);
}
void循环()
{
if(Serial.available()){
int cmd=Serial.read();
如果(cmd>0){
//如果我发送1,指示灯将保持亮起。。。
//但当发送12时,LED不会熄灭。
如果(cmd='1'){
数字写入(13,高);
}
如果(cmd='12'){
数字写入(13,低);
}
}
}
}
您希望将字符串的值转换为C中的整数。因此请使用该函数。您应该能够使用原始的Arduino代码,但将C代码更改为:
// ...
private void button1_Click(object sender, System.EventArgs e)
{
SendByte(1); // Send byte '1' to the Arduino
}
private void SendByte(byte byteToSend) {
byte[] bytes = new byte[] { byteToSend };
serialPort1.Write(bytes, 0, bytes.Length);
}
// ...
是为arduino设计的C!;)
// ...
private void button1_Click(object sender, System.EventArgs e)
{
SendByte(1); // Send byte '1' to the Arduino
}
private void SendByte(byte byteToSend) {
byte[] bytes = new byte[] { byteToSend };
serialPort1.Write(bytes, 0, bytes.Length);
}
// ...