Flavius P. Bogdan Flavius P. Bogdan - 25 days ago 9
C# Question

c# send data to comport

Im making a WindowsForm app to simulate current values to a meter. I dont know how to take the values from the text box and send it trough the COM port.
this is the code i got at the moment

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

}
}
}

Answer

See the documentation for the SerialPort class : https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx

There is a Write(string) method, so

serialPort1.Write(comboBox1.Text);

should work See https://msdn.microsoft.com/en-us/library/y2sxhat8(v=vs.110).aspx