我想使用串口在arduino和c#程序之间进行通信。我对c#编程很陌生。该程序有多个用户控制表单。每个人都需要访问串口发送数据。我需要做的就是从每个类的主窗体中写入串行端口。访问多个类的串行端口
我明白如何设置和写入串口。这里是我的Form1代码:
partial class Form1 : Form
{
lightsControl u1;
fanControl u2;
public Form1()
{
InitializeComponent();
u1 = new lightsControl();
u2 = new fanControl();
u1.Dock = DockStyle.Fill;
u2.Dock = DockStyle.Fill;
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.Open();
}
private void lightsButton_Click(object sender, EventArgs e)
{
u2.Hide();
u1.Show();
controlPanel.Controls.Add(u1);
}
private void fansButton_Click(object sender, EventArgs e)
{
u1.Hide();
u2.Show();
controlPanel.Controls.Add(u2);
}
private void monitorButton_Click(object sender, EventArgs e)
{
u1.Hide();
u2.Hide();
}
public void sendData(ref string tx1, ref string tx2, ref string tx3)
{
serialPort1.WriteLine(tx1);
serialPort1.WriteLine(tx2);
serialPort1.WriteLine(tx3);
}
}
我只有一个其他类写的到目前为止。我试图在继续其余部分之前获得串行通信设置。我创建了sendData函数希望能够从另一个类访问它,但我似乎无法得到这个工作。我使用Visual Studio 2012.
编辑: 它现在工作。这里是我的Form 1代码:
partial class Form1 : Form
{
lightsControl u1;
fanControl u2;
public Form1()
{
InitializeComponent();
u1 = new lightsControl(serialPort);
u2 = new fanControl();
u1.Dock = DockStyle.Fill;
u2.Dock = DockStyle.Fill;
serialPort.PortName = "COM4";
serialPort.BaudRate = 9600;
serialPort.Open();
}
这里是我的第二个表单代码:
private SerialPort port; //declare port
public lightsControl(SerialPort port)//import serialPort from Form1 to port
{
InitializeComponent();
this.port = port;
hideTimer();
updateTimer.Enabled = true;
stopButton.Enabled = false;
}
public void WriteToPort(string data)
{
this.port.WriteLine(data); //function that writes to serial port
}
private void onButton_Click(object sender, EventArgs e)
{
statusLabel.Text = "Always On";
hideTimer();
switch (light)
{
case 0://Light 1
com = light1Name + "On";
Tx2 = "a";
WriteToPort(Tx2);//This is where I need to write to the port
light1Status = 1;
light1Reset();
break;
串口对象在Form1并其传递到正在使用的其他形式。
任何错误。它到底在做什么? –