Button 如何将arduino与visual Studio窗体连接
我有一个游戏在视觉学习windows窗体应用程序 arduino按钮如何与wfa按钮一样工作? 感谢C#提供了一个SerialPort类,可用于与Arduino接口。 您可以按如下方式打开端口:Button 如何将arduino与visual Studio窗体连接,button,Button,我有一个游戏在视觉学习windows窗体应用程序 arduino按钮如何与wfa按钮一样工作? 感谢C#提供了一个SerialPort类,可用于与Arduino接口。 您可以按如下方式打开端口: using System.IO; using System.IO.Ports; private string loadAvailablePorts() { ManagementScope connectionScope = new ManagementScope(); SelectQu
using System.IO;
using System.IO.Ports;
private string loadAvailablePorts()
{
ManagementScope connectionScope = new ManagementScope();
SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);
try
{
foreach (ManagementObject item in searcher.Get())
{
string desc = item["Description"].ToString();
string deviceId = item["DeviceID"].ToString();
if (desc.Contains("Arduino"))
{
return deviceId;
}
}
}
catch (ManagementException ex)
{
Util.Log(ex.Message + "\n" + ex.StackTrace);
}
return null;
}
private bool openSerialPort()
{
try
{
serialPort1 = new SerialPort(loadAvailablePorts());
}
catch (ArgumentNullException ex)
{
Util.Log(ex.Message + "\n" + ex.StackTrace);
return false;
}
if (serialPort1 != null)
{
serialPort1.BaudRate = 9600;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
try
{
serialPort1.Open();
}
catch(UnauthorizedAccessException ex)
{
Util.Log(ex.Message + "\n" + ex.StackTrace);
}
catch(IOException ex)
{
Util.Log(ex.Message + "\n" + ex.StackTrace);
}
}
return true;
}
请注意DataReceived事件处理程序。你可以用它来触发你的按键。在Arduino代码中,您需要将一些输出写入显示您单击按钮的串行端口,然后您可以在C#代码中检测到该按钮。出于我的目的,我只从连接到Arduino的传感器读取数据,因此对我来说,这是一个解析使用Serial.println(…)编写的字符串的问题,但对于您的按钮按下,您可能会使用digitalWrite。我没有使用Arduino按钮的经验,但用C#的方式检测点击应该不难
在C#中,您需要编写一个方法以编程方式单击按钮,这可以在DataReceived事件处理程序中执行
private void dataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string capturedText = string.Empty;
try
{
capturedText = serialPort1.ReadLine();
}
catch (InvalidOperationException ex)
{
Util.Log(ex.Message + "\n" + ex.StackTrace);
}
catch (IOException ex)
{
Util.Log(ex.Message + "\n" + ex.StackTrace);
}
if (capturedText.Contains("1"))
{
myButton.PerformClick();
}
}
您的Arduino代码可能类似以下示例:
我希望这有帮助。这应该足以让您的示例正常运行,或者至少让您走上正确的道路。第一次使用arduino如何将其连接到c#code我需要有关arduino代码的帮助第一次使用它:(对于您的按钮按下,它应该非常简单。下面是来自的示例。
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
Serial.println("1");
} else {
Serial.println("0")
}
}