Serial port doesn't read all data - c#

I am reading from a serial port Rs232. I am facing a very strange problem.
The total bytes from incoming information is 37 bytes. In my computer, each time which i have interrupt in my serial port, the information is exactly 37bytes.
example abcdefghijklmnopqrstuvwxyz1234567890! and so on till 3
but in another pc, my imformation is been seperated to 8 bytes
example abcdefgh, in next interrup ijklmnop , in next interrup qrstuvwx and so on
Here is my serial port code:
public static string Rs232Weight = "0";//Αυτό είναι για να παίρνει την τιμή η ζυγαριά
public static readonly object lockWeight = new object();
private static SerialPort mySerialPort;
private void button1_Click(object sender, EventArgs e)
{
try
{
mySerialPort = new SerialPort(textBox1.Text);
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.Open();
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
catch
{
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort sp = (SerialPort)sender;
lock (lockWeight)
{
string tmp = sp.ReadExisting();
ExportFile(Convert.ToString(tmp) + "|" + Convert.ToString(tmp.Length));
}
}
catch //(Exception ex)
{
// Dialogs.SingleMessage(Convert.ToString(ex), "Προειδοποίηση");
}
}

Related

How to read barcodes with a barcode scanner that does not emulate keyboard?

EDIT: Okay, so I've moved on and made a fully working console app:
public static void Main(string[] args)
{
SerialPort mySerialPort = new SerialPort("COM4");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true;
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)
{
Thread.Sleep(100);
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine($"Data Received: {indata}");
indata = "";
}
Now the problem is that when I try to do something similar in the UWP app -
public void InitScanner()
{
SerialPort mySerialPort = new SerialPort("COM4")
{
BaudRate = 9600,
Parity = Parity.None,
StopBits = StopBits.One,
DataBits = 8,
Handshake = Handshake.None,
RtsEnable = true
};
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
tBlock_spState.Text = mySerialPort.IsOpen.ToString();
}
void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
tBlock_test.Text = indata;
}
public MainPage()
{
this.InitializeComponent();
InitScanner();
}
It throws an System.IO.IOException with description "Too many posts on a semaphore" (sorry for the translation, I am using VS with Czech language). Does anyone know the reason why is this happening? Once again, can't find anything anywhere.
So, I've got a task to write a code, which could allow to read data from a barcode scanner that does not act like a keyboard and write it to a textbox. My thought was that it could be possible via System.IO.Ports.SerialPort class, but I have absolutely no idea how to make it work as it should. I am working on this in an UWP. I've tried this so far
SerialPort sp = new SerialPort("COM4", 9600);
void MethodName()
{
string s;
if(!sp.IsOpen)
sp.Open();
while (sp.BytesToRead > 0)
{
s = sp.ReadLine();
tBlock_test.Text = s;
}
sp.Close();
}
And that is where I've ended and don't know what to do next, or even if this is somehow correct. Again, basic question, i know, but i am seriously stuck on this and cannot find solution anywhere. I'd appreciate any kind of help.
I've remade the app in the WPF template and tried the answer from here: SerialPort reading cause error because of not owning thread (Delegate + Invoke method) and it finally worked.

SerialDataReceivedEventHandler not being fired

I have been trying to establish a serial port communication in C#. I see, that the event handler for reading data doesnt get fired. The initial strings are the format in which i need to send the data to a register( for eg 0000 reg gets the value of 1180).
Please let me know if i am missing something here.
PS: Just a beginner.
class Program
{
static SerialPort _serialPort;
public static void Main()
{
string phyad = "17";
string regad = "0000";
string value = "1180";
string readad = phyad + regad + "=" + "/";
string combo = phyad + regad + value + "=" + "/";
_serialPort = new SerialPort();
_serialPort.PortName = "COM4";
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
_serialPort.Open();
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
byte[] data = Encoding.ASCII.GetBytes(combo);
_serialPort.Write(data, 0, data.Length);
_serialPort.DataReceived += new SerialDataReceivedEventHandler(MyDataReceivedHandler);
}
private static void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine(_serialPort.ReadExisting());
}
}

Console does not show the entire answar from serial port

I am working with BC66 modem from Quectel. On my program when I type some AT commands to the modem it can not show the entire response from the modem, but instead the reply of the AT command. see figur below:
Instead using an terminal program and type the AT commands i got the status of my request. See figure below:
This is what I am expecting in my program, but unfortunately not happened.
The code snip:
static void Main(string[] args)
{
if (InitPort() == true)
{
Console.WriteLine("Port initialized");
TestAT();
}
}
private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
Console.WriteLine(Encoding.ASCII.GetString(data));
//Console.WriteLine(serialPort.ReadExisting());
}
private static void TestAT()
{
for (int i = 0; i < 10; i++)
{
serialPort.Write("at");
Thread.Sleep(2000);
serialPort.Write("at+cereg");
Thread.Sleep(2000);
}
}
private static bool InitPort()
{
serialPort.PortName = "COM51";
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DataReceived += SerialPort_DataReceived;
try
{
serialPort.Open();
return true;
}
catch
{
return false;
}
}
Any suggestion on what is wrong?
As you can see here on page 7 you need to finish your commands with <CR><LF>.
The “AT” or “at” prefix must be set at the beginning of each command
line. Entering <CR> will terminate a command line.
in C# the equivalent is \r\n
As #Mong Zhu pointed out, you can achieve that by using
serialPort.WriteLine("at");

access to the port 'com8' is denied. Where's the error in this code?

i'm trying to get data from a serial device, but program is running with this error "access to the port 'com8' is denied". please give a solution.
public void PorttInit(object sender, EventArgs e)
{
SerialPort mySerialPort = new SerialPort("COM8");
try
{
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.Open();
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
catch (Exception ex)
{
mySerialPort.Close();
}
finally
{
//mySerialPort.Close();
}
}
public String data;
public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
String dataInput = sp.ReadExisting();
data = dataInput;
}
If in the IDE your serial report output windows(Serial Monitor) is open, you will face with this error. So close that window and then upload your code

Putty Default Serial Configuration

When using C# I can only read the last 4 characters of the value in COM2.
Putty reads it correctly
I have no control or information over the source that is putting the value on COM2.
My C# settings resemble the basic settings on Putty configuration screen, but C# offers more settings, so Putty must have some underlying settings not being shown.
I checked the documentation on Putty, I can't find the default settings on serial port.
My code:
using System.IO.Ports;
...
SerialPort mySerialPort = null;
mySerialPort = new SerialPort("COM2");
mySerialPort.BaudRate = 19200;
mySerialPort.Parity = System.IO.Ports.Parity.None;
mySerialPort.StopBits = System.IO.Ports.StopBits.One
mySerialPort.DataBits = 8;
mySerialPort.Handshake = System.IO.Ports.Handshake.None;
mySerialPort.DiscardNull = true;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.ReadBufferSize = 2147483647;
...
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string value= sp.ReadExisting(); //I onle get the last four characters
}
So I should be obtaining the value "17159160118A" but I onle get "118A", Putty reads the whole string correctly
So given that I have no information about the signal source, my best bet is to use similar configuration as Putty in my code, do you know what configuration this could be? or what am I doing wrong?
So, I deleted all the code and started again with a clean console application, the source was sending the data in two parts, , I was just only reading the second, I just needed to know what was the string terminator, I found out that it was the null terminator character ('\0') so I used that to concatenate my strings, here's my code:
class Program
{
static void Main(string[] args)
{
using (SerialPort sp = new SerialPort("COM2", 19200, Parity.None, 8, StopBits.One))
{
//sp.DiscardNull = true;
sp.Handshake = Handshake.XOnXOff;
sp.ReadBufferSize = 16384;
sp.Open();
sp.DataReceived += sp_DataReceived;
AppDomain.CurrentDomain.ProcessExit += new EventHandler((x, y) =>
{
sp.Close();
});
Console.ReadKey();
}
}
static string myString = string.Empty;
static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (sender as SerialPort);
if (sp.BytesToRead > 0)
{
myString += sp.ReadExisting().Trim();
if (myString.Last() == '\0')
{
myString = myString.Trim('\0').Trim();
if (!string.IsNullOrWhiteSpace(myString))
{
Console.WriteLine(myString);
}
sp.DiscardInBuffer();
myString = string.Empty;
}
}
}
}
I commented out //sp.DiscardNull = true; as it was removing all the null characters and it worked, so any way thanks for the downvote.

Categories