GUI with Serial Communication C# - c#

I am new to C# and Visual Studio. I have built a GUI to choose the COM port from a MenuStrip in Visual Studio 2013. What I want to know is how can I connect this with serial port communication.
Should I use a another class for serial communication? Or can I do it in the same class? How can it be programmed?
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.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace exo_new
{
public partial class rehab : Form
{
public rehab()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void conndToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void cOM1ToolStripMenuItem_Click(object sender, EventArgs e)
{
cOM1ToolStripMenuItem.Checked = true;
cOM2ToolStripMenuItem.Checked = false;
cOM3ToolStripMenuItem.Checked = false;
cOM4ToolStripMenuItem.Checked = false;
cOM5ToolStripMenuItem.Checked = false;
cOM6ToolStripMenuItem.Checked = false;
cOM7ToolStripMenuItem.Checked = false;
cOM8ToolStripMenuItem.Checked = false;
cOM9ToolStripMenuItem.Checked = false;
cOM10ToolStripMenuItem.Checked = false;
}
private void cOM2ToolStripMenuItem_Click(object sender, EventArgs e)
{
cOM2ToolStripMenuItem.Checked = true;
cOM1ToolStripMenuItem.Checked = false;
cOM3ToolStripMenuItem.Checked = false;
cOM4ToolStripMenuItem.Checked = false;
cOM5ToolStripMenuItem.Checked = false;
cOM6ToolStripMenuItem.Checked = false;
cOM7ToolStripMenuItem.Checked = false;
cOM8ToolStripMenuItem.Checked = false;
cOM9ToolStripMenuItem.Checked = false;
cOM10ToolStripMenuItem.Checked = false;
}

You can use the System.IO.SerialPort class to program the serial port from a .NET application. (The link is to the MSDN documentation for the class, which includes an example program.) If you want more help than that you'll need to provide some of your code and more of an explanation of what you want to do, and when. (For example, user clicks button X and you want to send message Y...)
UPDATE: Thanks for sharing your code so far. Here is how I would implement a simple solution based on what you've started with:
public partial class rehab : Form
{
private string portName = "COM1";
private const int baudRate = 9600;
public Form1()
{
InitializeComponent();
//TODO: Simplify your UI by dynamically creating the COM port names.
// Get the list of available ports on the computer via the following:
//var portNames = SerialPort.GetPortNames();
// Call this to initially mark 'COM1' as checked.
UpdatePortCheckmarks();
}
private void conndToolStripMenuItem_Click(object sender, EventArgs e)
{
var textToSend = this.textBox1.Text;
// Use a try-catch block to log any exceptions that occur.
try
{
// Use a using block to close and dispose of the serial port
// resource automatically. Also, note that the SerialPort
// constructor takes the port name and baud rate here.
// There are also overloads that let you pass the number of
// data bits, parity, and stop bits, if needed.
using (var serialPort = new SerialPort(portName, baudRate))
{
// Open the port before writing to it.
serialPort.Open();
// Send the content of the textbox (with a newline afterwards).
serialPort.WriteLine(textToSend);
}
}
catch (Exception ex)
{
// You could also use MessageBox.Show. Console.WriteLine will
// display errors in your debugger's output window.
Console.WriteLine("ERROR: " + ex.ToString());
}
}
private void cOM1ToolStripMenuItem_Click(object sender, EventArgs e)
{
portName = "COM1";
UpdatePortCheckmarks();
}
private void cOM2ToolStripMenuItem_Click(object sender, EventArgs e)
{
portName = "COM2";
UpdatePortCheckmarks();
}
// .. and so on for each additional port menu item (COM3 through COM10)
// This method lets you share the code for updating the checkmarks on
// the menu items, so your form code will be cleaner.
private void UpdatePortCheckmarks()
{
cOM1ToolStripMenuItem.Checked = portName == "COM1";
cOM2ToolStripMenuItem.Checked = portName == "COM2";
cOM3ToolStripMenuItem.Checked = portName == "COM3";
cOM4ToolStripMenuItem.Checked = portName == "COM4";
cOM5ToolStripMenuItem.Checked = portName == "COM5";
cOM6ToolStripMenuItem.Checked = portName == "COM6";
cOM7ToolStripMenuItem.Checked = portName == "COM7";
cOM8ToolStripMenuItem.Checked = portName == "COM8";
cOM9ToolStripMenuItem.Checked = portName == "COM9";
cOM10ToolStripMenuItem.Checked = portName == "COM10";
}
}
I've included a 'TODO' comment as a suggestion on how you can further improve your code, but that's optional (and should be a new question if you do have any questions about it).

Related

Receive a single weight from scale Using a button press

I am tasked with creating a Windows form application for the factory i work for.
We will be weighing multiple bags, so every time the button is pressed it must send the weight that is currently on the scale. In other words just capture the current weight and wait for me to press the button again to capture the next bag that will be loaded on the scale. Currently it continuously receives data from the scale once the button is clicked and the result only flashes in my textbox. I want to change so it only receives one weight then stops. Can you please show me how i can accomplish this.
Thank you in advance
Below is my code:
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 Microsoft.Office.Interop.Excel;
namespace ScaleV5
{
public partial class Form1 : Form
{
private SerialPort _serialPort; //<-- declares a SerialPort Variable to be used throughout the form
private const int BaudRate = 9600; //<-- BaudRate Constant. 9600 seems to be the scale-units default value
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] portNames = SerialPort.GetPortNames(); //<-- Reads all available comPorts
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName); //<-- Adds Ports to combobox
}
comboBox1.SelectedIndex = 0; //<-- Selects first entry (convenience purposes)
}
private void button1_Click(object sender, EventArgs e)
{
//<-- This block ensures that no exceptions happen
if (_serialPort != null && _serialPort.IsOpen)
_serialPort.Close();
if (_serialPort != null)
_serialPort.Dispose();
//<-- End of Block
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One); //<-- Creates new SerialPort using the name selected in the combobox
_serialPort.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
_serialPort.Open(); //<-- make the comport listen
textBox1.Multiline = true;
textBox1.Text += $"Listening on " + _serialPort.PortName + $"\r\n";
}
private delegate void Closure();
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired) //<-- Makes sure the function is invoked to work properly in the UI-Thread
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); })); //<-- Function invokes itself
else
{
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
string str = System.Text.Encoding.UTF8.GetString(data);
textBox1.Text = str.ToString();
_serialPort.WriteLine("w");
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
}
private void button3_Click(object sender, EventArgs e)
{
_serialPort.Close();
this.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
}
}
}
put the entire port instantiation and closing/opening code into the SelectedIndexChanged event of the combobox. When the user chooses a port you simply open it and leave it open. Opening and closing ports takes time. So you should keep it to a minimum.
When pressing the button you would only probe the scale via the port for the values. (If you really have 2 modes of operation choose the single measurement)
private void button1_Click(object sender, EventArgs e)
{
// probe device for value
_serialPort.WriteLine("w");
Thread.Sleep(100);
string response = _serialPort.ReadExisting();
// here parse the resonse to extract you value
// stop the device
_serialPort.WriteLine("w");
textBox1.Multiline = true; // <- this code belongs into the constructor
textBox1.Text += extractedStringValue;
}
disclaimer: this code runs synchronously and will block the UI. It depends strongly on your device how long it need to responde to your first request of measurements. To avoid the blocking of the UI you would need to work with async/await.

C# display a variable in a Textbox

i am sending Sensor information with a NUCLEOF411RE to my PC. I receive this data on the COM98 with a BaudRate of 115200. Now i want to program a Windows Application that will split my string and put it on my textboxes. until now i display the data with a Button_click event. It puts values on the Textboxes that actually are the real values. But if i move my Sensor and klick the button again there should be a lot more different values, but there are the same values on the textboxes. In addition i want to refresh the textboxes automatically and not with a button click.
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 BNO080
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvailablePorts();
}
public string comport;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
comport = comboBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(comboBox1.Text=="" || textBox6.Text=="")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
textBox5.Text = serial.ReadLine();
/*String[] Stringsizes = A.Split(new char[] {' '});
textBox1.Text = Stringsizes[0];
textBox2.Text = Stringsizes[1];
textBox3.Text = Stringsizes[2];
textBox4.Text = Stringsizes[3];*/
// textBox5.Text = A;
//Array.Clear(Stringsizes, 0, 3);
}
catch (Exception) { }
}
}
}
can someone help me?
Can you give more information why you use the Button_Click Event to read the text? Maybe it is a possible way for you to subscribe for the DataReceived-Event of the COM-port?
It would look something like this:
serial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
string receivedString = serial.ReadExisting();
//Do something here...
}
I'd do a couple things. First subscribe to the DataReceived event on the serial port. This event handler will get called when there is data available on the serial port. Then in the event handler you can read from the serial port and add it to your textbox. You can't add it directly (see the AppendText function) because the event handler is called with a different thread, only the UI thread can update UI components (or you'll get a cross-thread exception).
...
public Form1()
{
InitializeComponent();
getAvailablePorts();
// Subscribe to the DataReceived event. Our function Serial_DataReceived
// will be called whenever there's data available on the serial port.
serial.DataReceived += Serial_DataReceived;
}
// Appends the given text to the given textbox in a way that is cross-thread
// safe. This can be called by any thread, not just the UI thread.
private void AppendText(TextBox textBox, string text)
{
// If Invoke is required, i.e. we're not running on the UI thread, then
// we need to invoke it so that this function gets run again but on the UI
// thread.
if (textBox.InvokeRequired)
{
textBox.BeginInvoke(new Action(() => AppendText(textBox, text)));
}
// We're on the UI thread, we can append the new text.
else
{
textBox.Text += text;
}
}
// Gets called whenever we receive data on the serial port.
private void Serial_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadExisting();
AppendText(textBox5, serialData);
}
Because i want to add an rotating 3D cube i decided to switch to WPF. I heard it is much easier to implement a 3D graphic there. So i copied my code to the new WPF project. But now i got already problems to visualize my values on the Textboxes. It doesnt work. It looks like the Evenhandler did not fire an event while receiving Data from the com port.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Drawing;
namespace cube
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
getAvailablePorts();
serial.DataReceived += Serial_DataReceived;
}
public bool button3clicked = false;
public bool button4clicked = false;
public bool button5clicked = false;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
List<string> Itemlist = new List<string>();
String[] ports = SerialPort.GetPortNames();
Itemlist.AddRange(ports);
comboBox1.ItemsSource = Itemlist;
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || textBox6.Text == "")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click_1(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
textBox1.Text = "test";
}
private void AppendText(string[] text)
{
try
{
textBox1.Text = text[0];
textBox2.Text = text[1];
textBox3.Text = text[2];
textBox4.Text = text[3];
}
catch (Exception) { }
}
private void Safe_Position1(TextBox tBr1, TextBox tBi1, TextBox tBj1, TextBox tBk1, string[] text)
{
if (button3clicked == true)
{
tBr1.Text = text[0];
tBi1.Text = text[1];
tBj1.Text = text[2];
tBk1.Text = text[3];
button3clicked = false;
}
}
private void Safe_Position2(TextBox tBr2, TextBox tBi2, TextBox tBj2, TextBox tBk2, string[] text)
{
if (button4clicked == true)
{
tBr2.Text = text[0];
tBi2.Text = text[1];
tBj2.Text = text[2];
tBk2.Text = text[3];
button4clicked = false;
}
}
private void Safe_Position3(TextBox tBr3, TextBox tBi3, TextBox tBj3, TextBox tBk3, string[] text)
{
if (button5clicked == true)
{
tBr3.Text = text[0];
tBi3.Text = text[1];
tBj3.Text = text[2];
tBk3.Text = text[3];
button5clicked = false;
}
}
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadLine();
String[] text = serialData.Split(new char[] { ' ' });
AppendText(text);
Safe_Position1(textBox5, textBox7, textBox8, textBox9, text);
Safe_Position2(textBox10, textBox11, textBox12, textBox13, text);
Safe_Position3(textBox14, textBox15, textBox16, textBox17, text);
}
private void button3_Click(object sender, EventArgs e)
{
button3clicked = true;
}
private void button4_Click(object sender, EventArgs e)
{
button4clicked = true;
}
private void button5_Click(object sender, EventArgs e)
{
button5clicked = true;
}
}
}

C#: serial com not showing the whole data

Dear experts i am trying to access the serial port programmatically through C#.I have interface a gsm module serially for communication.problem i am facing is if data is small m getting it perfectly but when i am reading the all messages{AT+CMGL="ALL"} i am receiving only half data on contrary in third party application i am receiving the whole data.
so want to know where the problem is coming whether i have to inc the size of input buffer where the Readexisting() function storing data or have to increase the timeout?.Last i checked we can not vary the size of buffer. please help.
my code is as follows:
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 SERIAL_PORT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getavailableports();
}
void getavailableports()
{
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
MessageBox.Show("please select port");
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
progressBar1.Value = 100;
// textBox2.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
textBox1.Enabled = true;
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("no");
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
button6.Enabled = false;
button7.Enabled = false;
textBox1.Enabled = false;
//textBox2.Enabled = false;
}
private void button6_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text + "");
textBox1.Text = "";
}
private void button7_Click(object sender, EventArgs e)
{
richTextBox1.Text = serialPort1.ReadExisting();
}
}
}

How To display Weight on Gridview from weight scale in c#?

I am developing weight scale program by serial port communication
but I have do like this.... example:
use put item on scale when my
app get weight then stop comunicate with scale first get weight set on
gridviewrowcolumn then row change automatically and when user put
second item on scale comunication start and same procedure do..
here is my 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;
using System.IO.Ports;
using System.Threading;
namespace serial
{
public partial class Form1 : Form
{
private SerialPort _serialPort; //<-- declares a SerialPort Variable to be used throughout the form
private const int BaudRate = 9600;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
#region Form Load
try
{
//getRawWeight();
string[] portNames = SerialPort.GetPortNames(); //<-- Reads all available comPorts
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName); //<-- Adds Ports to combobox
}
comboBox1.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
}
private void button1_Click(object sender, EventArgs e)
{
if (_serialPort != null && _serialPort.IsOpen)
_serialPort.Close();
if (_serialPort != null)
_serialPort.Dispose();
//<-- End of Block
_serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One); //<-- Creates new SerialPort using the name selected in the combobox
_serialPort.DataReceived += SerialPortOnDataReceived; //<-- this event happens everytime when new data is received by the ComPort
_serialPort.Open(); //<-- make the comport listen
textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
}
private delegate void Closure();
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired) //<-- Makes sure the function is invoked to work properly in the UI-Thread
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); })); //<-- Function invokes itself
else
{
while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
{
string reading = "";
reading += string.Format("{0:X2} ", _serialPort.ReadByte());
//<-- bytewise adds inbuffer to textbox
//string reading = System.Text.Encoding.UTF8.GetString(_serialPort);
textBox1.Text = reading.Substring(13);
}
}
}
}
}
I would open the serial port once and then leave it open until you close your program. Have you successfully communicated with the scale yet? Also some devices like scales have their own button that will send data across the serial port each time you push it. What is wrong with your code? What does it do as it is written?

Get Weight From Weigh Bridge Machine Using Serial Port in C#

i am develop application for getting weight from weigh Bridge machine using C#.Net.i am trying lot of ways but,doesn't read correct data format weight from weigh bridge machine.i am getting ouput like ?x???????x?x?x??x???x??x???x???x? continuously get from serial port.i want to get weight from weigh bridge machine my code is listed 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);
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
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;
}
}
}
}
my code is append text from serial port data to textbox but,it's shows only like ?xxx?xxxx?xxxx?
can any one help me how to get weight from serial port using c#
Thanks For Reading My Post!
You are using ReadExisting(), that method tries to convert the bytes received by the port into a string. You'll get a question mark if that conversion fails. The default Encoding is ASCII, a byte value between 128 and 255 is not an ASCII character and thus produces a ?
Several possible reasons, roughly in order of likelihood:
Using the wrong baud rate, in particular guessing too high.
The device might be sending binary data, not strings. Which requires using Read() instead of ReadExisting and decoding the binary data.
Electrical noise picked up by a long cable that isn't shielded well enough. Easy to eliminate as a possible reason by disconnecting the cable at the bridge end. If that stops the data then it isn't likely to be noise.
Be sure to thoroughly read the manual. Contact the vendor of the device if you don't have one or can't make sense of it.
This code will be reading weightbridge continuously in background. Be sure to connect the pc with serial port. Also in design page Form1.cs[Design] you need to add Serial port from the toolbox. This code works for me, I hope it works for you too...
public partial class Form1 : Form
{
//Initialize the port and background Worker
private SerialPort port;
private BackgroundWorker backgroundWorker_Indicator;
public Form1()
{
backgroundWorker_Indicator = new BackgroundWorker();
backgroundWorker_Indicator.WorkerSupportsCancellation = true;
backgroundWorker_Indicator.DoWork += new DoWorkEventHandler(Indicator_DoWork);
//set the port according to your requirement.
port = new SerialPort("COMM2", 2400, Parity.None, 8, StopBits.One);
port.DataReceived += new SerialDataReceivedEventHandler(this.Indicator_DataReceived);
}
//button which starts the method. You can also put the method in Form1_Load()
private void SerialPortButton(object sender, EventArgs e)
{
StartStopIndicator();
}
private void StartStopIndicator()
{
try
{
port.Open();
backgroundWorker_Indicator.RunWorkerAsync();
}catch (Exception ea)
{
MessageBox.Show("13 "+ea.Message);
}
}
// Not a button. Just a methood.
private void Indicator_DoWork(object sender, DoWorkEventArgs e)
{
}
private void Indicator_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string str = StripNonNumeric(port.ReadLine());
UpdateWeightOnUI(str);
}
catch (Exception eb)
{
MessageBox.Show("12"+eb.Message);
}
}
private void UpdateWeightOnUI(string Weight)
{
try
{
// A label named weightLabel from the toolbox. This will keep updating on weight change automatically
if (weightLabel.InvokeRequired)
{
this.Invoke((Delegate)new Form1.SetTextCallBack(this.UpdateWeightOnUI), (object)Weight);
}
else
{
weightLabel.Text = Weight;
}
}
catch (Exception ec)
{
MessageBox.Show("11"+ec.Message);
}
}
// This method will remove all other things except the integers
private string StripNonNumeric(string original)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (char c in original)
{
if (char.IsDigit(c))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
private delegate void SetTextCallBack(string text);

Categories