在Arduino和C#之间进行串行通信,可以使用C#的SerialPort类来实现。以下是一个基本的示例代码:
在Arduino端,使用Serial.begin()函数来初始化串行通信,并使用Serial.print()函数将数据发送给C#程序:
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.print("Sensor value: ");
Serial.println(sensorValue);
delay(1000);
}
在C#端,可以使用SerialPort类来接收来自Arduino的串行数据。以下是一个简单的示例代码:
using System;
using System.IO.Ports;
class Program
{
static void Main(string[] args)
{
SerialPort port = new SerialPort("COM3", 9600); // 串口和波特率需要与Arduino端保持一致
port.Open();
while (true)
{
string data = port.ReadLine(); // 读取一行数据
Console.WriteLine(data);
}
}
}
在这个示例中,我们使用SerialPort类来打开COM3串口,并设置波特率为9600。然后,在一个无限循环中,使用ReadLine()方法读取一行数据,并将其打印到控制台上。
请注意,这只是一个简单的示例,实际应用中可能需要根据具体需求进行适当的修改和扩展。