我正在製作一個WindowsForm應用程序來模擬電錶的當前值。我不知道如何從文本框中獲取值並通過COM端口發送。 這是我得到的那一刻c#發送數據到comport
namespace ValueSim1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
// Get all serial ports name
string[] ports = SerialPort.GetPortNames();
// Clear comboBox list to get latest serial ports in each dropdown.
comboBox1.Items.Clear();
foreach (string port in ports)
{
// Output serial port to dropdown list.
comboBox1.Items.Add(port);
}
}
private static SerialPort serialPort1;
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Text != "")
{
serialPort1.PortName = comboBox1.Text; //comboBox1.Text set to PortName
serialPort1.BaudRate = 19200; //Baudrate is set (fix.)
//if serial port has opened, it must be closed at first.
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
}
//open the serial port after confirmation serial port closed.
if (serialPort1.IsOpen == false)
{
serialPort1.Open();
if (serialPort1.IsOpen == true) //message window shows serial port status.
{
MessageBox.Show("Open Success\n" + serialPort1.PortName.ToString() + " " + serialPort1.BaudRate.ToString());
}
else
{
MessageBox.Show("COM Port error");
}
}
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
因此,我得到了5個參數,如強度,頻率等和一個按鈕,當我按下它時,我想將所有這些參數發送到儀表。如果我將serialPort.write命令放在button_click中,應該這樣做? –
您需要知道儀表需要輸入什麼,並格式化您發送的字符串。儀表是否希望參數以逗號分隔,按照由CRLF分隔的特定順序,固定長度參數 - 只要它期望一個字符串輸入並且您格式正確,那麼它應該可以工作。如果儀表正在等待其他編碼,例如字節值,則其他編寫方法之一可能是適當的。 – PaulF
回到一個問題。如果我嘗試打開一個端口,我得到這個:異常拋出:ValueSim1.exe中的'System.NullReferenceException'對象引用未設置爲對象的實例。「 –