简体   繁体   中英

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 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.

I would suggest:

  1. Use the Click event instead of the MouseClick event.

  2. 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 your COM1.WriteLine(command);

  3. 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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM