我需要编写一个程序来从指标中读取数据。在电脑的设备管理器中,将指示灯定义为USB-ITN,并创建虚拟串口(COM18)。
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace SerialPort
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//configuring the serial port
serialPort1.PortName = "COM18";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Read all the data waiting in the buffer
string data = serialPort1.ReadExisting();
rtbTerminal.AppendText(data);
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
rtbTerminal.AppendText("Port Closed!\n");
}
else
{
serialPort1.Open();
rtbTerminal.AppendText("Port Open!\n");
}
}
}
}
为什么打开串口后无法接收仪表的数据?