3
Reply

serial port

george

george

16 years ago
6.3k

Hey guys Sorry for my bad English  I have design a microcontroller board that send commands as text  to serial port by pressing some buttons

 

e.g.

 

If I press button1 sends             #B1#pressed

If I press button1 sends             #B2#pressed

If I press button1 sends             #B3#pressed

If I press button1 sends              #B4#pressed

If I press button1 sends              #B5#pressed

 

 

I’m beginner with C#

I have found a code example to read the serial port and works!! But I wand some help to continuously read the serial port as the example!  And to put the each button command to string variable

 

E.g. when the software see that the        #B1#....            received, to store to a string variable,

  The entire command    #B1# pressed             and to stop store characters when sees some new command or sees nothing!

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace SimpleSerial

{

    public partial class Form1 : Form

    {

        // Add this variable

        string RxString;

 

        public Form1()

        {

            InitializeComponent();

            serialPort1.PortName = "COM4";

            serialPort1.BaudRate = 19200;

 

            serialPort1.Open();

        }

 

       

 

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            if (serialPort1.IsOpen) serialPort1.Close();

        }

 

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

        {

            // If the port is closed, don't try to send a character.

            if (!serialPort1.IsOpen) return;

 

            // If the port is Open, declare a char[] array with one element.

            char[] buff = new char[1];

 

            // Load element 0 with the key character.

            buff[0] = e.KeyChar;

 

            // Send the one character buffer.

            serialPort1.Write(buff, 0, 1);

 

            // Set the KeyPress event as handled so the character won't

            // display locally. If you want it to display, omit the next line.

            e.Handled = true;

        }

 

        private void DisplayText(object sender, EventArgs e)

        {

            textBox1.AppendText(RxString);

        }

 

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

        {

            RxString = serialPort1.ReadExisting();

            this.Invoke(new EventHandler(DisplayText));

        }

 

        private void textBox1_TextChanged(object sender, EventArgs e)

        {

 

        }

    }

}


Answers (3)