Send write commands to serial port with C#?
Thanks in advance for your help. I'm writing a lightweight C# program to write lines to a serial port (sending commands to a PLC) for work, and I'm not a programmer. My problem is that my button won't send the line to the serial port. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using开发者_Python百科 System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
string command = "Turn Motor";
SerialPort COM1 = new SerialPort("COM1");
public Form1() {
InitializeComponent();
COM1.Open();
}
private void button1_MouseClick(object sender, MouseEventArgs e) {
COM1.WriteLine(command);
}
}
What can I do to make the button1 click send the text line to the serial port? The code must be as simple as possible as this is only run on one workstation. I've looked at all the examples, but have been unable to adapt them to my code. I also don't want to blatantly rip off others' code to get it working. Any advice would be appreciated.
EDIT: The code above is not everything, for example I'm initializing the port properly. I have another section of code that properly receives and processes strings, it's just the sender I'm having problems with. I also created the button method using the form designer, so there should be no disconnect there.
It looks like you are not initializing your Com Port. You need to set your BaudRate
, Parity
, DataBits
, StopBits
and Handshake
property's. Look at the above MSDN examples for guidence. You can set the property's individualy or set them in the constructor.
According to MSDN the Default values for the above propertys are:
- BuadRate = 9600
- Parity = Parity.None
- DataBits = 8
- StopBits = StopBits.One
- HandShake = HandShake.None
I would suggest:
Use the
Click
event instead of theMouseClick
event.If you just copied your
button1_MouseClick
method from an example somewhere that method probably isn't subscribed to the click event properly. If you double click the button in Visual Studio designer it will set up a method subscribed to the click event correctly for you automatically. That's where you would put yourCOM1.WriteLine(command);
If both of those suggestions are incorrect, you should probably be getting an Exception thrown somewhere (unless you're opening an incorrect port). In that case, you should describe that error in your question here.
精彩评论