SerialPort Read Doesn't Work in C# - 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.
}

Related

save data to .txt file at the same time click "read" button

i want to save received data to .txt file when click "read" button. please help me
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.Threading;
using System.IO.Ports;
namespace Serial
{
public partial class Form1 : Form
{
static SerialPort serialPort1;
public Form1()
{
InitializeComponent();
getAvailablePorts();
serialPort1 = new SerialPort();
}
void getAvailablePorts()
{
string[] Ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(Ports);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
textBox2.Text = "Please select port Setting";
}
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 = "anauthorized Acess";
}
}
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);
textBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
try
{
textBox2.Text = serialPort1.ReadLine();
}
catch(TimeoutException)
{
textBox2.Text = "Timeout Exception";
}
}
}
}
Simply use File.WriteAllText.Sample :
File.WriteAllText("path here","text here")
Just use StreamWriter
using(StreamWriter sw = new StreamWriter("filename.txt")){
sw.WriteLine(textbox.Text);
sw.Close();
}

how to change background of a form on a value returning from serial

I'm new to c#,i have been trying to change the color of form when I receive a value from a serial, I am using event handling method to receive data from serial monitor, yet the output is not coming. I have here by attached the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SerialPort port;
public delegate void UpdateGUI(string str);
public void DisplayReceivedData(string str)
{
string ja = "12";
//listBox1.Items.Add("received");
// if(StringComparison
listBox1.Items.Add(str);
textBox1.Text = ja;
int test = String.Compare(str, ja);
textBox1.Text =Convert.ToString(str);
if (test == 0)
{
ActiveForm.BackColor = System.Drawing.Color.DarkBlue;
}
else
{
ActiveForm.BackColor = System.Drawing.Color.White;
}
}
public void Datareceived(object sender, SerialDataReceivedEventArgs arg)
{
SerialPort sp = (SerialPort)sender;
string str = sp.ReadExisting();
Invoke(new UpdateGUI(DisplayReceivedData),str);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
port = new SerialPort("COM10");
port.BaudRate = 9600;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.DataBits = 8;
port.Handshake = Handshake.None;
port.RtsEnable = true;
port.DataReceived += new SerialDataReceivedEventHandler(Datareceived);
port.Open();
}
private void button1_Click(object sender, EventArgs e)
{
ActiveForm.BackColor = System.Drawing.Color.DarkBlue;
}
private void button2_Click(object sender, EventArgs e)
{
ActiveForm.BackColor = System.Drawing.Color.White;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
As you say in your comments the problem is with the end-of-line chars.
You could simply trim them off using:
str.TrimEnd('\r', '\n');

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.

C# SERIAL PORT TEXTBOX ISSUE

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)
{
}
}
}'

Categories

Resources