c#将数据发送到comport

时间:2016-11-15 10:39:24

标签: c# visual-studio

我正在制作一个WindowsForm应用程序来模拟当前值到一米。我不知道如何从文本框中取值并通过COM端口发送它。 这是我目前获得的代码

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)
    {

    }
  }
}

2 个答案:

答案 0 :(得分:0)

请参阅SerialPort类的文档:https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx

有一个Write(字符串)方法,所以

serialPort1.Write(comboBox1.Text);

应该有效 见https://msdn.microsoft.com/en-us/library/y2sxhat8(v=vs.110).aspx

答案 1 :(得分:0)

使用             SerialPort1.WriteLine(string); e.g

     SerialPort1.WriteLine(textBox1.Text);

还可以使用Write()WriteLine()方法的其他重载。请确保您正确阅读文档。

here is a link to the microsoft documentation for the serial port class

尝试在编码时阅读。