【问题标题】:How can send bytes for arduino?如何为arduino发送字节?
【发布时间】:2011-11-27 16:07:15
【问题描述】:

我开发了一个应用程序,它通过套接字将字符串/命令发送到另一个 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);
            }
        }
    }
}

【问题讨论】:

  • 是适用于 arduino 的 C! ;)

标签: c# serial-port arduino


【解决方案1】:

您想在 C 中将字符串的值转换为整数。所以使用 atoi 函数。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多