如何为arduino发送字节?

时间:2011-11-27 16:07:15

标签: c# serial-port arduino

我开发了一个应用程序,它通过套接字将字符串/命令发送到另一台PC应用服务器,并通过串口将字符串发送到Arduino。

问题是:我如何向Arduino发送字节?

通过串口发送String的应用服务器的C#:

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 ++代码:

#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
    }
  }
}

为了更好地理解这个问题,我将代码改为此(但是,因为伺服的值从0变为180,这不起作用):

#include <Servo.h>

Servo servo;
int pos;

void setup()
{
    servo.attach(9);
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}

void loop()
{
    if (Serial.available()) {
        int cmd = Serial.read();

        if (cmd > 0) {
            // If I send a 1 the LED stays ON...
            // but when a send 12 the LED doesn't stay OFF.
            if (cmd == '1') {
                digitalWrite(13,HIGH);
            }

            if (cmd == '12') {
                digitalWrite(13,LOW);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您希望将字符串的值转换为C中的整数。因此请使用atoi函数。

答案 1 :(得分:1)

您应该能够使用原始的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);
}
// ...