Search code examples
c#winformsserial-portmodbus

Problem with write serial output via Button Clicked


I'm currently trying to write Wisco protocol (similar to MODBUS ASCII) out to my digital output devices but faced a problem. If I clicked the ON or Off buttons (see the Image WinForm UI) that already have code to send protocol to my digital output it wouldn't do it.

But in another program where I use a textbox and write the protocol myself then I have to press Enter (If I don't press Enter key it will not work) before clicking send button and it works. What seems to be the problem here?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = "COM5";
                serialPort1.BaudRate = 9600;
                serialPort1.DataBits = 8;
                serialPort1.Open();
                progressBar1.Value = 100;
            }

            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
                progressBar1.Value = 0;
            }
        }

        private void btnOn_Click(object sender, EventArgs e)
        {
            serialPort1.Write("#00WDO1,1");
        }

        private void btnOff_Click(object sender, EventArgs e)
        {
            serialPort1.Write("#00WDO1,0");
        }
    }
}            

Solution

  • It turns out I just have to add \r\n to solve this problem.

    private void btnSend_Click(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen)
        {
            serialPort1.Write("#00WDO1,1");
            serialPort1.Write("\r\n");
        }
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        if (serialPort1.IsOpen)
        {
            serialPort1.Write("#00WDO1,0");
            serialPort1.Write("\r\n");
        }
    }