C# SERIAL PORT TEXTBOX ISSUE - c#

I want to create a form having button,textbox,serialport in Visual c# 2010. My objective is when a button is pressed the data coming from the serial port has to displayed in textbox. I copied the following code from a tutorial. The textbox is not showing anything. Here's is the 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;
namespace ser1
{
public partial class Form1 : Form
{
private string RxString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
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.Text=RxString.Trim();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}'

Related

Receiving data from serial port in windows form application

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 WindowsFormsApp7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getavaialbleports();
}
void getavaialbleports()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void button1_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();
button1.Enabled = false;
}
}
catch(UnauthorizedAccessException)
{
textBox2.Text = "Unauthorised Access";
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
}
private void button3_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
richTextBox1.Text = serialPort1.ReadLine();
}
}
}
I'm able to send data from the above code but for reception I'm not able to read data from it. There are no build errors. Please help me out to solve this problem.
You can implement "SerialPortDataReceivedEvent" to read data from serial port.
Before opening connection to serial port register with "DataReceivedEvent", Inside
button1_Click event add below code.
serialPort1.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
Then add below event handler
private static void mySerialPort_DataReceived(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
//data received on serial port is asssigned to "indata" string
//Console.WriteLine("Received data:");
//Console.Write(indata);
}
Also, try to configure other properties like Parity, StopBits, DataBits etc. similar to the device on other end (with which you are trying to communicate).
Update data on UI:
what you need is a delegate method that sets the Text property of your text box with a given string. You then call that delegate from within your mySerialPort_DataReceivedhandler via the TextBox.Invoke() method. Something like this:
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
private void Form1_Load(object sender, EventArgs e)
{
//...
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
textbox1.AppendText(myString);
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
textbox1.Invoke(this.myDelegate, new Object[] {indata});
}
Let us know if you need further clarification.
Hope this helps..
In my opinion, first just try test, when initing serial port add
serialPort1.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int bytesToRead = serialPort1.BytesToRead;
System.Diagnostics.Debug.WriteLine(bytesToRead);
}
after that in Output window you will sea is there any data in port or not

Time stamp missing

I'm trying to display the data received on textbox. But I realized that when data were being received on Br#y terminal it look fine (eg. 14:02:33.43 > T 11 22.32) but running on the software the time stamp is missing.
Am I missing out anything which lead to this?
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.Data.OleDb;
using System.IO;
namespace SerialCom
{
public partial class Form1 : Form
{
string RxString; //Variable
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
btnStart.Enabled = false;
btnStop.Enabled = true;
txtData.ReadOnly = false;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnStart.Enabled = true;
btnStop.Enabled = false;
txtData.ReadOnly = true;
}
}
private void txtData_KeyPress(object sender, KeyPressEventArgs e)
{
if (!serialPort1.IsOpen) return; // If the port is closed, don't try to send a character.
char[] buff = new char[8]; // If the port is Open, declare a char[] array with one element.
buff[0] = e.KeyChar; // Load element 0 with the key character.
serialPort1.Write(buff, 0, 1); // Send the one character buffer.
e.Handled = true;// Set the KeyPress event as handled so the character won't
// display locally. If you want it to display, omit the next line.
}
private void DisplayText(object sender, EventArgs e)
{
txtData.AppendText(RxString);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
StreamWriter MyStreamWriter = new StreamWriter(#"c:\testing.txt",true); //True tell SW to append to file instead of overwriting
MyStreamWriter.Write(RxString);
MyStreamWriter.Flush();
MyStreamWriter.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
serialPort1.Close();
}
}
}
Basically, I was wrong by saying that the time stamp is originally included in the data i received.. I need to add in the time stamp on my own.. This was to act as a record of when did i actually received the following data.
As a result, what's missing is this
string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff")
Hope this helps people who are struggling with the problem too.

C# Serial Port Receive and Acknowledge

I'm back again with a little project I am stuck on at the moment, trying to receive and then acknowledge the receipt to get the next set of data from the COM1 device.
Basically the device is a Motorola MC1000 hand held barcode scanning device, the software that is on it, is linked to this program which no longer works but sends the data output via serial, and I have managed to get the data out manually by connecting to the port and then manually sending "%0" to the device to output all the data from memory.
So far, I have coded a program to connect to the com device, open the com port, and receive the buffer information, but I need to send an automatic acknowledgement to get all the data out.
The data is in the format of Barcode Qty.
Here is my code so far:
<!-- language: c# -->
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Add this variable
string RxString;
SerialPort ComPort = new SerialPort();
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
ComPort.PortName = Convert.ToString(cboPorts.Text);
serialPort1.PortName = ComPort.PortName;
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
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);
if (e.KeyChar == (char)13) // enter key
{
serialPort1.Write("%0");
//textBox1.Text = "";
}
else if (e.KeyChar < 32 || e.KeyChar > 126)
{
e.Handled = true; // ignores anything else outside printable ASCII range
}
else
{
serialPort1.Write(e.KeyChar.ToString());
}
// 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() + "\n";
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) ||
(index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
}
private void cboPorts_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
I just somehow need to output this all automatically.

SerialPort Read Doesn't Work in C#

i am develop C# windows app.it's read weight from weigh bridge machine to serial port.but,my code doesn't work.i am trying many examples download from internet doesn't work.my code is below:
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;
using System.IO;
namespace SerialPortTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String a = "";
private void button1_Click(object sender, EventArgs e)
{
serialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
if (serialPort1.IsOpen == false)
{
serialPort1.Open();
}
timer1.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
a = a + serialPort1.ReadExisting();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (a.Length != 0)
{
textBox1.AppendText(a);
a = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
button2.Enabled = false;
button1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
button1.Enabled = false;
button2.Enabled = true;
}
else
{
button1.Enabled = true;
button2.Enabled = false;
}
}
}
}
What i am wrong in my code can any one help me any working code.
Thanks in Advance.
You didn't register the serialPort1_DataReceived for serialPort1.
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
You maybe need to extract the binary data from the stream instead of reading the data as a string?
Here's an example of some code that could be inside the DataReceived event handler...
int nb = serialPort1.BytesToRead;
if (nb > 0)
{
byte[] buffer = new byte[nb];
serialPort1.Read(buffer, 0, nb);
// Depending on the structure of the binary data ...
int number1 = BitConverter.ToInt32(buffer, 0);
int number2 = BitConverter.ToInt32(buffer, 4);
// etc.
}

Visual Studio 2010 C# DataReceived does not seem to trigger

Visual Studio 2010 C# 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;
namespace YamanPonics
{
public partial class Form1 : Form
{
string RxString;
//Default SerialPortStatus equals TRUE when first starting up
Boolean serialPortDisconnected = true;
public Form1()
{
InitializeComponent();
//Add available Serial COM ports to combobox
foreach (string ports in System.IO.Ports.SerialPort.GetPortNames())
{
//MessageBox.Show("Serial port avialible" + " " + ports);
comPortCmbBox.Items.Add(ports);
}
}
private void DisplayText(object sender, EventArgs e)
{
serialMsgViewerRchTxt.AppendText(RxString);
MessageBox.Show("Displayed Serial Text!");
}
private void serialPort1_DataReceived (object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//If SerialPort1 IsOpen
if (serialPort1.IsOpen)
{
//Close SerialPort1 communication
serialPort1.Close();
}
}
private void connectDisconnectBtn_Click(object sender, EventArgs e)
{
//Set arduinoComPort value to COM Port value
string arduinoComPort = comPortCmbBox.Text;
//if SerialPortStatus boolean equals FALSE then
if (serialPortDisconnected && (arduinoComPort != ""))
{
//Set serialPort1 BaudRate value to default value of 38400(required for atlas-scientific sensors)
serialPort1.BaudRate = 38400;
//Set serialPort1 Read and Write timeout values
serialPort1.ReadTimeout = 250;
serialPort1.WriteTimeout = 250;
//Set serialPort1 DataBits value
serialPort1.DataBits = 8;
//Open serialPort1 communication
serialPort1.Open();
//Change connectDisconnectBtn text to Disconnect
connectDisconnectBtn.Text = "Disconnect";
//Set serialPortDisconnected to FALSE
serialPortDisconnected = false;
}
else //if SerialPortStatus bollean equals TRUE
{
//Close SerialPort1 communication
serialPort1.Close();
//Set connectDisconnectBtn text to Connect
connectDisconnectBtn.Text = "Connect";
//Set serialPortDisconnected to TRUE
serialPortDisconnected = true;
}
}
private void SendBtn_Click(object sender, EventArgs e)
{
//if serialPort1 IsOpen then
if (serialPort1.IsOpen)
{
serialPort1.Write("{ph}");
}
}
}
}
That code is a simple Serial connect/disconnect and send/receive application. Connect, Disconnect, and send works properly. When my arduino receives a command it sends a response back. My 2010 C# application is not receiving the response in the richtextbox and do not understand why. I can receive a response when I use another serial terminal program so I do know for sure that data is being sent. What am I not doing to successfully receive a response?
Are you sure the serialPort1.DataReceived event is wired up correctly? I see you have the handler method, but I don't see you subscribing to the event.
You need to have this somewhere:
serialPort1.DataReceived += serialPort1_DataReceived;

Categories

Resources