Can't read the Fairbank scale weight properly - c#

I tried to connect the scale and retrieve the weight from visual studio 2013, but it's wire that sometimes I can get the exacted weight and sometimes I couldn't. I was not sure what's wrong with the code. Can someone help? My code is listed below
using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows;
using System.Data.SqlClient;
using System.Collections;
using System.Threading;
namespace PortDataReceived
{
class PortData
{
public static void Main(string[] args)
{
try
{
string lineOne = "One";
string lineTwo = "Two";
char CarriageReturn = (char)0x0D;
string final = lineOne + CarriageReturn.ToString() + lineTwo + CarriageReturn.ToString();// define the hexvalues to the printer
SerialPort mySerialPort = new SerialPort("COM3");//initiate the new object and tell that we r using COM1
mySerialPort.BaudRate = 9600;
//mySerialPort.Parity = Parity.Odd;
//mySerialPort.StopBits = StopBits.Two;
//mySerialPort.DataBits = 7;
mySerialPort.Parity = Parity.Odd;
mySerialPort.StopBits = StopBits.Two;
mySerialPort.DataBits = 7;
mySerialPort.Handshake = Handshake.None;
mySerialPort.ReadTimeout = 20;
mySerialPort.WriteTimeout = 50;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
//those r all the setting based on the scale requirement
/*foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
{
Console.WriteLine(port);
}*/
while (true)
{
mySerialPort.Open();
mySerialPort.Write(final);
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
}
//mySerialPort.Close();
}
catch (System.IO.IOException e)
{
if (e.Source != null)
Console.WriteLine("IOException source: {0}", e.Source);
throw;
}
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
Console.ReadKey();
}
}
}

Often with serial communication, you have to read multiple times, and concatenate each read, until you finally detect you've read the part that shows you've received it all. Detecting the end may be based on a specific count of bytes received, or it might be looking for a particular byte or sequence of bytes. But it's up to you to make that determination, and to continue reading until that condition is fulfilled. When you first read, there may be characters waiting, but the device has not sent them all yet, so you will have to read again almost immediately after your first read. You're dealing with a stream. The handler event fires when the stream starts, but it doesn't know how long the stream will flow.
This blog post discusses this and some other common serial port issues:
http://blogs.msdn.com/b/bclteam/archive/2006/10/10/top-5-serialport-tips-_5b00_kim-hamilton_5d00_.aspx

Related

C # Serial.read is reading the characters correctly, even with the wrong BaudRate

I'm creating a software in C # that must read the serial port and when recognizing a String (String already known sent by the arduino with BaudRate 38400) it must inform the baudRate used in the reading.
My problem is that no matter what value I put in C # BaudRate, it still recognizes the data correctly.
I tried to change the baudRate on the Arduino, but the result is always the same.
For example, the arduino sends the word "Hello" to a baudRate of 38400. The C # should read the serial port and when recognizing the word Hello (which should only appear with the correct BaudRate) it should display the used baudRate and end the function . However, even setting the baud rate to 1200, 2400 ... etc, ... C # always reads the word "Hello".
On the arduino serial monitor, when I change the speed, the characters are scrambled when I select a different speed than the one configured (as it should happen in C #).
I need C # to receive the scrambled serial data when the baudRate is incorrect.
Snippet of 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;
using System.IO;
using System.IO.Ports;
namespace Baud
{
public partial class frmSerial : Form
{
public static System.IO.Ports.SerialPort serialPort1;
//private delegate void LineReceivedEvent(string line);
public frmSerial()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
Int32[] lista_bauds = new Int32[] { 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 };
Boolean connected = false;
System.ComponentModel.IContainer components = new System.ComponentModel.Container();
serialPort1 = new System.IO.Ports.SerialPort(components); // Creating the new object.
for (int i = 0; i < lista_bauds.Length & connected == false; i++)
{
Console.WriteLine(lista_bauds[i]);
string ReceivedData = "";
serialPort1.PortName = "COM" + numCom.Value.ToString(); // Setting what port number.
serialPort1.BaudRate = 1200; // Setting baudrate.
serialPort1.ReadTimeout = 4000;
//serialPort1.DtrEnable = true; // Enable the Data Terminal Ready
serialPort1.Open(); // Open the port for use.
try
{
if (serialPort1.IsOpen == true)
{
ReceivedData = serialPort1.ReadExisting();
Console.WriteLine(ReceivedData);
if (ReceivedData.Equals("Hello") == true)
{
txtDatasend.Text = "Conectado com BaudRate de" + lista_bauds[i]; ;
Console.WriteLine(ReceivedData);
connected = true;
btnConnect.Text = "Conectar";
serialPort1.Close();
}
else
{
serialPort1.Close();
}
}
}
catch (Exception)
{
throw;
}
}
numCom.Enabled = false;
}
private void btnSend_Click(object sender, EventArgs e)
{
// Sends the text as a byte.
serialPort1.Write(new byte[] { Convert.ToByte(txtDatasend.Text) }, 0, 1);
}
}
}
Heres the arduino code:
int LED_Pin = 13; // LED connected to digital pin 13
void setup()
{
Serial.begin(38400); // Configure the baudrate and data format for serial transmission
pinMode(LED_Pin,OUTPUT); // Pin13 as Output
digitalWrite(LED_Pin,LOW); // Pin13 LED OFF
}
void loop()
{
Serial.println("Autenticar"); // Send the String,Use Serial.println() because we have used SerialPort.ReadLine() on C# side
// SerialPort.ReadLine() on C# side will return only after receiving '/n' character
Blink_LED(); // Blink LED to indicate transmission
}
//Function to Blink LED 13
void Blink_LED()
{
digitalWrite(LED_Pin,HIGH);
delay(100);
digitalWrite(LED_Pin,LOW);
delay(100);
}

can't read data from serial port (in c#) [duplicate]

This question already has answers here:
SerialPort not receiving any data
(3 answers)
Closed 8 years ago.
I wanna read from my sensors' data from serial ports, and i can read the name of the ports but i can't receive data from them... i'm new in #c and serial port coding, thanks before~
And here's my try:
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
//----------------------------------------------------- GLOBAL PARAMETER ------------------------------------------------------
//---serial port objects
static private List <SerialPort> _serialPort = new List<SerialPort>();
//---serial port read buffer
static private List <byte[]> _buffer = new List<byte[]>();
//---length of the port list
static private int _length;
//--------------------------------------------------- INIT FUNCTIONS ----------------------------------------------------------
//---init main function
static private void initFunction(){
//create the serial port objs
createPortObj();
//create the buffers
createBuffer();
//init a clock
//init the ports' name
return;
}
//---Set the port objs
static private void setPortOption(int i) {
SerialPort tPort = _serialPort[i];
//set options
tPort.BaudRate = 9600;
tPort.Parity = Parity.None;
tPort.StopBits = StopBits.One;
tPort.DataBits = 8;
tPort.Handshake = Handshake.None;
//set the datareceived function
//tPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
tPort.DataReceived += DataReceivedHandler;
tPort.Open();
return;
}
//---Create the port objs
static private void createPortObj(){
// Get a list of serial port names.
string[] _names = SerialPort.GetPortNames();
_length = _names.Length;
//create the objs
for(int i=0; i < _length; i++)
{
Console.WriteLine(_names[i]);
//create the port objects
_serialPort.Add(new SerialPort(_names[i]));
//init the port object
setPortOption(i);
}
return;
}
//---Create the buffer
static private void createBuffer() {
//create buffer for each port obj
for (int i = 0; i < _length; i++){
byte[] bufferOne = new Byte[_serialPort[i].BytesToRead];
_buffer.Add(bufferOne);
}
return;
}
//-------------------------------------------------- FEATURED FUNCTION ----------------------------------------------------
//---Transmit the code
//---Data received handler
static public void DataReceivedHandler(Object sender, SerialDataReceivedEventArgs e){
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
//Receive the data from serial ports
for (int i=0; i<_length; i++){
int temp;
temp = _serialPort[i].Read(_buffer[i], 100, _buffer[i].Length);
Console.WriteLine(temp);
}
return;
}
//-------------------------------------------------- RETRIVE FUNCTION ----------------------------------------------------
//---Retrive the source
static private void retriveFunction(){
//close the serial ports
foreach (SerialPort port in _serialPort){
port.Close();
}
return;
}
//-------------------------------------------------- MAIN -----------------------------------------------------------------
//---main function
static void Main(string[] args){
//init function, and open the
initFunction();
int[] num = new int[_length];
for (int i = 0; i < _length; i++){
num[i] = _serialPort[i].Read(_buffer[i], 0, _buffer[i].Length);
}
//check the result of the read function
Console.Write(num[0]);
//on serial port receiving
//retrive the source
retriveFunction();
Console.ReadLine();
}
}
}
thanks again~
I think your code is not wait for data receive.Before your sensors sends back data,your code is finish,program is end,you should handle data in a new thread or in DataReceived event.

Serial communication trouble C#

I got some trouble with my console application. I'm trying to retrieve data from a serial connection with a barcode scanner.
The problem is that:
- first read is perfect;
- second read results incorrect unless I wait approximately one minute.
Here is the code:
using System;
using System.IO.Ports;
class PortDataReceived
{
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM10");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.RequestToSend;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.WriteLine(indata);
}
}
and here is the result of 2 reads of the same barcode without waiting enough time from the first to the second read:
Press any key to continue...
Data Received:
229000400718
Data Received:
2
Data Received:
2
Data Received:
9
Data Received:
0
Data Received:
0
Data Received:
0
Data Received:
4
Data Received:
0
Data Received:
0
Data Received:
7
Data Received:
1
Data Received:
8
Any suggestions?
Thanks in advance!
It appears that the data of the second read comes in char by char, so I would use a StringBuilder b and append incoming data until a valid barcode was received and is contained in b (ie check validity against a database)
I suggest something like this:
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
StringBuilder b = new StringBuilder();
while(!IsValidBarcode(b.ToString()))
{
b.Append(sp.ReadExisting());
}
Console.WriteLine("Data Received:");
Console.WriteLine(b.ToString());
}
private static Boolean IsValidBarcode(String s)
{
if (String.IsNullOrEmpty(s)) return false;
// (1) Query a database for expected barcodes ...
// (2) Check s for Start-Stop-Characters ...
// (3) Query the device for completed barcode ...
throw new NotImplementedException();
}
or this
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
StringBuilder b = new StringBuilder();
Thread.Sleep(1000); // 1 second delay for testing purposes
b.Append(sp.ReadExisting());
Console.WriteLine("Data Received:");
Console.WriteLine(b.ToString());
}
You need some sort of timer to check if the multiple characters being read are part of a single read or if they are 2 different scans. The time between the event firing for your second scan is probably very short, simply set a timer to start after an event firing, if this expires before the next event then it is the end of the barcode, if not append the read to the previous (use a buffer of some sort).
You need to have an ending character to know when your message is completed. Most people are using a \r\n (13,10) and read from the serial port to the end of the line (i.e. \r\n).
You are getting an event for each character and reading it too quickly.
Luca Pillin, I have just included thread.sleep for 3 seconds and it solves the issue
using System;
using System.Threading;
using System.IO.Ports;
class PortDataReceived
{
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM2");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.RequestToSend;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
//
string indata = string.Empty;
SerialPort sp = (SerialPort)sender;
**Thread.Sleep(3000);**
indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.WriteLine(indata);
}
}

Receive SMS through GSM modem

I saw that similar topics were posted on this forum, but I simply don't understand how to send AT commands and receive a response. (I started to program in C# several months ago. I'm still an n00b, but I'm working hard to learn it...).
I need to create application which would only receive SMS message through GSM USB dongle. So far I managed to create app that will recognize and connect modem through COM ports that is available. Now I need to push AT commands for receiving messages and displaying them into a textBox. I was wondering if anyone can spare few minutes to explain the process to me, and modify my code with comments so I can finally learn and understand how to use serialPort for communication. What I need to know, when SMS is sent, does this message is received and stored by GSM modem (and it is stored until I send some requests to read them or do I need to send some event that would trigger GSM modem to collect message from ISP)? how to push AT commands and receive their response (I only know that is done by using serialPort object, but doesn't have clue how to do it...)
This is my method for receiving (which I'm stuck BTW... :))
private void receiveMessage()
{
//commclass is only a class for getting COM port, baud rate and timeout
CommClass cc = new CommClass();
cc.setParameters();
serialPort1.PortName = cc.getPort();
serialPort1.BaudRate = cc.getBaud();
serialPort1.ReadTimeout = cc.getTimeout();
serialPort1.Open();
if (!serialPort1.IsOpen)
{
//MessageBox is written in Croatian language, it is only an alert to check the configuration because port is not opened...
MessageBox.Show("Modem nije spojen, molimo provjerite konfiguraciju...!");
//timer1.Stop();
}
else
{
//this.label2.Text = serialPort1.PortName;
//this.label2.Visible = true;
//this.label3.Visible = true;
//this is where I need to place a code for receiving all SMS messages
this.serialPort1.Write("AT+CMGL=\"REC UNREAD\"");
}
serialPort1.Close();
}
If anyone willing to help, I would appreciate that, if not I would have to deal with it by my self (probably spent few hours/days until I figure it out...)
In both cases, thank you anyway... Cheers.
Sorry for waiting for my reply, been busy lately.
In short this is my code for getting message from GSM USB dongle. I hope that it will be useful to someone...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace SMSget
{
public partial class SMSLogPanel : UserControl
{
SerialPort sp;
int datab = 0;
bool dtr = false;
bool encod;
Handshake h;
Parity p;
int wtimeout = 0;
StopBits s;
#region default constructor
public SMSLogPanel()
{
InitializeComponent();
this.sp = serialPort1 = new SerialPort();
this.datab = serialPort1.DataBits = 8;
this.dtr = serialPort1.DtrEnable = true;
this.encod = serialPort1.Encoding.Equals("iso-8859-1");
this.h = serialPort1.Handshake = Handshake.RequestToSend;
this.p = serialPort1.Parity = Parity.None;
this.wtimeout = serialPort1.WriteTimeout = 300;
this.s = serialPort1.StopBits = StopBits.One;
checkLink();
}
#endregion
#region checking communication and setting user controls...
private void checkLink()
{
GetValues value = new GetValues();
string com = value.getPort();
int baud = value.getBaud();
int timeot = value.getTimeout();
serialPort1.PortName = com;
serialPort1.BaudRate = baud;
serialPort1.ReadTimeout = timeot;
serialPort1.Open();
if (serialPort1.IsOpen)
{
label1.Visible = true;
}
else
{
MessageBox.Show("Komunikacija sa modemom se ne može uspostaviti, molimo postavite novu konfiguraciju...!");
this.Controls.Clear();
SMSConfigPanel cfg = new SMSConfigPanel();
cfg.Show();
this.Controls.Add(cfg);
}
serialPort1.Close();
}
#endregion
#region panel load method
private void SMSLogPanel_Load(object sender, EventArgs e)
{
setGSM();
}
#endregion
#region execute serialport handler
public void getMessage()
{
if (serialPort1.IsOpen)
{
serialPort1.DataReceived += new SerialDataReceivedEventHandler(getResponse);
}
else
{
MessageBox.Show("Nije moguće zaprimiti poruku, komunikacijski port nije otvoren...1");
return;
}
}
#endregion
#region get response from modem
public void getResponse(object sender, SerialDataReceivedEventArgs e)
{
SerialPort serPort = (SerialPort)sender;
string input = serPort.ReadExisting();
if (input.Contains("+CMT:"))
{
if (input.Contains("AT+CMGF=1"))
{
string[] message = input.Split(Environment.NewLine.ToCharArray()).Skip(7).ToArray();
textBox1.Text = string.Join(Environment.NewLine, message);
}
this.Invoke((MethodInvoker)delegate
{
textBox1.Text = input;
});
}
else
{
return;
}
}
#endregion
#region initialize GSM
private void setGSM()
{
serialPort1.Open();
if (!serialPort1.IsOpen)
{
MessageBox.Show("Problem u komunikaciji sa modemom, port nije otvoren...!");
}
serialPort1.Write("AT+CMGF=1" + (char)(13));
serialPort1.Write("AT+CNMI=1,2,0,0,0" + (char)(13));
}
#endregion
#region setiranje timer-a...
private void timer1_Tick_1(object sender, EventArgs e)
{
timer1.Stop();
getMessage();
timer1.Start();
}
#endregion
}
}
This was only code for testing so it works but there is lot to fix and improve. Basically it will be a nice start for all that are searching something like this...
cheers.

Dial mobile phone via C# program

I m trying to Dial mobile phone via C# program. Below Show my Program. In this, When i Click my Dial Button it dial the number(Destination number) which i given in my program. But after one or two seconds it is disappeared & its not connect to the that destination number. Below Shows my C# code. Pls help me to solve this problem. Thank you.......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SerialPort sp = new SerialPort();
sp.PortName = "COM10";
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;
sp.Handshake = Handshake.XOnXOff;
sp.DtrEnable = true;
sp.RtsEnable = true;
sp.Open();
if (!sp.IsOpen)
{
MessageBox.Show("Serial port is not opened");
return;
}
sp.WriteLine("AT" + Environment.NewLine);
sp.WriteLine("ATD=\"" + "Destination Number" + "\"" + Environment.NewLine);
}
}
}
Finally i found the solution. We should add the semi-colon to end of the destination number. then its worked.
sp.WriteLine("ATD=\"" + "Destination Number;" + "\"" + Environment.NewLine);
Increase your BaudRate to max and use this AT Command:
ATD = DestinationNumber;
This will not work with out ; as the system will think you are taking a data call and not a voice call.
Try moving the decleration of the 'sp' outside the method, like so:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
private SerialPort sp;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
sp = new SerialPort();
}
private void button1_Click(object sender, EventArgs e)
{
if (sp.IsOpen)
{
sp.Close();
}
sp.PortName = "COM10";
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;
sp.Handshake = Handshake.XOnXOff;
sp.DtrEnable = true;
sp.RtsEnable = true;
sp.Open();
if (!sp.IsOpen)
{
MessageBox.Show("Serial port is not opened");
return;
}
sp.WriteLine("AT" + Environment.NewLine);
sp.WriteLine("ATD=\"" + "Destination Number" + "\"" + Environment.NewLine);
}
}
}
Here is my working dialing cord it rings the phone
Don't knows that how to get the voice input and out put from port I'm using huwavi E173 dongle.Here is my working cord C#
SerialPort port = new SerialPort();
port.Open();
string t = port.ReadExisting();
Thread.Sleep(100);
string cmd = "ATD";
Thread.Sleep(100);
string phoneNumber = "071********";
Thread.Sleep(100);
port.WriteLine(cmd + phoneNumber + ";\r");
port.Close();

Categories

Resources