Click here to Skip to main content
14,305,260 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am developing a configuration tool in C#. I am beginner in C#.I am using winforms for my application.
I have a serially connected device which send back respond on specific ascii command. Till now I can create and open port able to get the default response in list box. But I can not able write in serial device in ascii. I tried looking on post " how can I write ascii in serial port" but got more confuse.
Can anyone help in easing the syntax or process.

Example: One of the command is "SMS0" it is a 4 byte command with 0 at end.

Any help will be appreciated.

What I have tried:

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;
using System.IO;

namespace SerialGW
{
    public partial class Form1 : Form
    {
 
        //string command;
        public Form1()
        {
            InitializeComponent();
            getAvailablrPorts();
            

        }
        
        void getAvailablrPorts()
        {

            String[] ports = SerialPort.GetPortNames();
            comboBox1.Items.AddRange(ports);

        }
        private void label1_Click(object sender, EventArgs e)
        {
            
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox1.Text == "" || comboBox2.Text == "")
                {
                    textBox2.Text = "Please select port settings";
                }
                else
                {
                   
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);

                    serialPort1.Open();

                    progressBar1.Value = 100;
                    button1.Enabled = true;
                    button2.Enabled = true;
                    textBox1.Enabled = true;
                    button3.Enabled = false;
                    button4.Enabled = true;

                }
            }

            catch(UnauthorizedAccessException)
            {
                textBox2.Text = "Unauthorised access";
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {

            serialPort1.Close();
            progressBar1.Value = 0;

            button1.Enabled = false;
            button2.Enabled = false;
            button4.Enabled = false;
            button3.Enabled = true;
            textBox1.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            serialPort1.WriteLine(textBox1.Text);
        
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
               
                //textBox2.Text = serialPort1.ReadExisting();
                listBox1.Items.Add(serialPort1.ReadExisting());
                //textBox2.Text = serialPort1.ReadLine();     It hangs when we use ReadLines()


            }
            catch (TimeoutException)
            {
                textBox2.Text = "Timeout Exception";
            }
        }
Posted
Updated 28-Jul-19 23:09pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

Use the Encoding class to convert a string to ASCII bytes: Encoding.GetBytes Method (String) (System.Text)[^].
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

I'd consult with the documentation for whatever device you have and ensure that the command is sent right. Even if SerialPort does write in ASCII by default, you need to make sure any necessary control characters and line endings are sent correctly. As noted in a previous solution, you can use the Encoding class to ensure your encoding is right.
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

using System.IO.Ports;

namespace ArduinoWireless
{
    
    public partial class Form1 : Form
    {
        string dataIN;
        string dataIN2;
        public Form1()
        {
            InitializeComponent();
        }
       private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Start();
            string[] ports = SerialPort.GetPortNames();
            cbCom1.Items.AddRange(ports);
        }
        private void btnWrite2Port_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.WriteLine(tbDataOut1.Text + Environment.NewLine);
                    tbReceiveData1.Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
      private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
                dataIN1 = serialPort1.ReadExisting();
                this.Invoke(new EventHandler(ShowData));
        }
        private void ShowData(object sender, EventArgs e)
        {
            int dataINLength = dataIN1.Length;
            lblDataInLength.Text = string.Format("{0:00}", dataINLength);
            if (cbAlwaysUpdate.Checked)
            {
                tbReceiveData1.Text = "";
                tbReceiveData1.Text = dataIN1;
                string s = serialPort1.ReadExisting();
                if  (s.Contains("1234"))
                {
                    tbReceiveData1.Text = s.ToString();
                }
                if (s.Contains("4321"))
                {
                    tbReceiveData1.Text = s.ToString();
                }
                else
                {

                }
            }
          
        }
        private void tbReceiveData1_TextChanged(object sender, EventArgs e)
        {
            if (tbReceiveData1.Text == "1234\r\n") // incoming data event
            {
                MessageBox.Show("1234 entered port");// replace with what you want your incoming data to do.
            }
            if (tbReceiveData1.Text == "4321\r\n")
            {
                MessageBox.Show("4321 entered port"); // replace with what you want your incoming data to do.
            }

        }
    }
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100