C# 的 Arduino UNO 基础知识

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10420959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:47:07  来源:igfitidea点击:

Arduino UNO basics for C#

c#arduinomicrocontroller

提问by ikathegreat

Hello I am new to controlling hardware with a USB connection. I have an Arduino UNO Microcontroller and was searching for resources to get me started. I program in C# (Visual Studio 2010) and was wondering if there were some basics I could use to setting up/testing my connection. I'm looking for something as simple as a check box in my WinForm toggling the Digital I/O pin on the Arduino between high and low. Haven't been able to find much to start with.

您好,我是通过 USB 连接控制硬件的新手。我有一个 Arduino UNO 微控制器,正在寻找资源来帮助我入门。我用 C# (Visual Studio 2010) 编程,想知道是否有一些基础知识可以用来设置/测试我的连接。我正在寻找一些简单的东西,比如我的 WinForm 中的复选框,在高和低之间切换 Arduino 上的数字 I/O 引脚。一直找不到很多东西可以开始。

Thanks in advance.

提前致谢。

采纳答案by Sandeep Bansal

I'm sure you know that Arduino has a few samples that you can use with C#

我确定您知道 Arduino 有一些可以与 C# 一起使用的示例

Here's their C# page

这是他们的 C# 页面

回答by sbonkosky

Since you're using Visual Studio, you might be interested in this cool Visual Studio plugin for Arduino development. http://www.visualmicro.com

由于您使用的是 Visual Studio,您可能会对这个用于 Arduino 开发的酷炫 Visual Studio 插件感兴趣。http://www.visualmicro.com

回答by Visual Micro

There are many ways to send a command from the pc to an arduino. Sandeep Bansil provides a good example of connecting and reading a serial port.

有很多方法可以将命令从 PC 发送到 arduino。Sandeep Bansil 提供了一个连接和读取串行端口的好例子。

Below is a working example of how to write to a serial port based on the state of a checkbox on a windows form amd how to process the request from the pc on the arduino.

以下是如何根据 Windows 窗体上的复选框状态写入串行端口以及如何处理来自 arduino 上的 PC 的请求的工作示例。

This is a verbose example, there are cleaner solutions but this is clearer.

这是一个冗长的例子,有更清晰的解决方案,但这更清晰。

In the example the arduino waits for either an 'a' or a 'b' from the pc. the pc sends an 'a' when a checkbox is checked and sends a 'b' when a checkbox is unchecked. The example assumes digital pin 4 on the arduino.

在示例中,arduino 等待来自 PC 的“a”或“b”。当复选框被选中时,PC 发送一个“a”,当一个复选框未被选中时发送一个“b”。该示例假定 arduino 上的数字引脚 4。

Arduino code

Arduino代码

#define DIGI_PIN_SOMETHING 4
unit8_t commandIn;
void setup()
{
    //create a serial connection at 57500 baud
    Serial.begin(57600);
}

void loop()
{
    //if we have some incomming serial data then..
    if (Serial.available() > 0)
    {
        //read 1 byte from the data sent by the pc
        commandIn = serial.read();
        //test if the pc sent an 'a' or 'b'
        switch (commandIn)
        {
            case 'a':
            {
                //we got an 'a' from the pc so turn on the digital pin
                digitalWrite(DIGI_PIN_SOMETHING,HIGH);
                break;
            }
            case 'b':
            {
                //we got an 'b' from the pc so turn off the digital pin
                digitalWrite(DIGI_PIN_SOMETHING,LOW);
                break;
            }
        }
    }
}

Windows C#

视窗 C#

This code will reside in your form .cs file. The example assumes that you have attached form events for OnOpenForm, OnCloseForm and the OnClick event to the checkbox. From each of the events you can call the respective methods below....

此代码将驻留在您的表单 .cs 文件中。该示例假定您已将 OnOpenForm、OnCloseForm 和 OnClick 事件的表单事件附加到复选框。您可以从每个事件中调用以下相应的方法....

using System;
using System.IO.Ports;

class fooForm and normal stuff
{
    SerialPort port;

    private myFormClose()
    {
        if (port != null)
        port.close();
    }

    private myFormOpen()
    {
        port = new SerialPort("COM4", 57600);
        try
        {
            //un-comment this line to cause the arduino to re-boot when the serial connects
            //port.DtrEnabled = true;

            port.Open();
        } 
        catch (Exception ex)
        {
            //alert the user that we could not connect to the serial port
        }
    }

    private void myCheckboxClicked()
    {
        if (myCheckbox.checked)
        {
            port.Write("a");
        } 
        else
        {  
            port.Write("b");    
        }
    }
}

Tip:

提示:

If you want to read a message from the arduino then add a timer to your form with an interval of 50or 100milliseconds.

如果您想从 arduino 读取消息,请在您的表单中添加一个计时器,间隔为50100毫秒。

In the OnTickevent of the Timer you should check for data using the following code:

OnTickTimer 事件中,您应该使用以下代码检查数据:

//this test is used to see if the arduino has sent any data
if ( port.BytesToRead > 0 )

//On the arduino you can send data like this 
Serial.println("Hellow World") 

//Then in C# you can use 
String myVar = port.ReadLine();

The result of readLine()will be that myVarcontains Hello World.

readLine()will的结果是myVar包含Hello World.

回答by haoming weng

The basic way to communication between PC and Arduino is create 2 buttons On PC and turn ON/off the light on Arduino. Use portwrite();

PC 和 Arduino 之间通信的基本方法是在 PC 上创建 2 个按钮并打开/关闭 Arduino 上的灯。用portwrite();

Here's the simplest demo: https://www.instructables.com/id/C-Serial-Communication-With-Arduino/That's absolutely what you want!

这是最简单的演示:https: //www.instructables.com/id/C-Serial-Communication-With-Arduino/这绝对是您想要的!

C# Code:

C# 代码:

using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace ledcontrol
{
    public partial class Form1 : Form
    {
        SerialPort port;
        public Form1()
        {
            InitializeComponent();
            this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
            if (port==null)
            {
                port = new SerialPort("COM7", 9600);//Set your board COM
                port.Open();
            }
        }
        void Form1_FormClosed(object sender,FormClosedEventArgs e)
        {
            if(port !=null &&port.IsOpen)
            {
                port.Close();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            PortWrite("1");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PortWrite("0");
        }
        private void PortWrite(string message)
        {
            port.Write(message);
        }
    }
}

Arduino sketch:

Arduino草图:

const int LedPin = 13;  
int ledState = 0;  

void setup()  
{   
  pinMode(LedPin, OUTPUT);  

  Serial.begin(9600);    
}  

void loop()  
{   
    char receiveVal;     

    if(Serial.available() > 0)  
    {          
        receiveVal = Serial.read();  

       if(receiveVal == '1')      
          ledState = 1;     
       else  
          ledState = 0;       
    }     

    digitalWrite(LedPin, ledState);   

    delay(50);      
}