C# Serial Communication DLL - c#

I'm developing in a DLL a serial communication protocol. I have a class for this matter, in there I have separated in different methods:
Open serial communication.
Write and read data (to a PLC).
Close serial communication.
From the project that uses the DLL I can open and close serial communication, but when I use write, the event handler never activates. I don't understand why. I tried to develop the code to test serial communication in a separeted project (without the DLL), it works fine and I can communicate with the PLC. So I thought it might be that I have to keep alive the DLL, I used some timers but it didn't work.
Serial class in the DLL:
public class Serial
{
SerialPort com = new SerialPort(GlobalData.PLC_ADDRESS, 9600, Parity.None, 8, StopBits.One);
public void Open()
{
// Read event handler
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
// Set the read/write timeouts
com.ReadTimeout = 400;
com.WriteTimeout = 400;
// Open the port for communication.
com.Open();
}
public void Talk2PLC()
{
byte[] cmd = { 17, 3, 0, 64, 0, 100, 71, 101};
com.Write(cmd, 0, cmd.Length);
}
public void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine($"Inside com_DataReceived");
// Buffer and process binary data
while (com.BytesToRead > 0)
PlcBuffer.Add((byte)com.ReadByte());
}
public void Close()
{
// Close the port
com.Close();
}
}
From the project that uses the DLL with this methods, I call first Open(), then Talk2PLC.
I used also "IsOpen" in the DLL to check if port is open or not, I didn't copied here to have a clearer code.
What should I do to do that the code enters in "com_DataReceived(...)"? I wrote a Console.WriteLine(..) to check when it enters.

I tried with Mitsubishi I didn't find any issue, can make com.DtrEnable = true before com.Open()

Related

Reading Data from a Scanner Connected Through Serial Port

I have an AspNetCore app that i am developing, I have to connect a barcode/Qr code scanner to the client computer, and I have to get the data on the server side and use the data for validation and pass the result to the client side.
Right now, I connected the scanner through Serial Port and can read the data from the barcode/Qr codes, but I think this is because the client/server is being run on the same computer now since I'm developing it.
I would like to ask that after I deploy the app, is there is a way to get the data on the server side after the Qr code/barcode have been scanned on the client side?
Below is my current code which i use to access the data through the serial port.
I created an instance of the serial port and leave it open so that qr codes/barcodes can be scanned continuously
static SerialPort _serialPort = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
public ActionResult SelectedPN(String nameobj)
{
pn_No= nameobj;
_serialPort.WriteTimeout = 500;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_Data);
if (!_serialPort.IsOpen)
{
try
{
_serialPort.Open();
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
}
When data is received, the Action method which will process the data is called _serialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_Data);
And below is the function
public void mySerialPort_Data(object sender, SerialDataReceivedEventArgs e)
{
if (_serialPort.ReadExisting() != null)
{
newpageList = _db.Categories1;
string data = _serialPort.ReadExisting();
barcode = data.Split(";");
codeValue = barcode[0].Substring(barcode[0].IndexOf(":") + 1);
GetCurrent();
//SelectedPN(pn_No);
}
//_serialPort.Close();
}
This solution works now in development, but I am concerned about when I publish the app. The client and server won't be on the same computer, so this approach probably won't work.
Any help/suggestion would be greatly appreciated.

How to use a C# serial port in the way it is used in Python

I am trying to send the bytes (b'\x03\r') to a device on COM5. The result will be the micropython board on the other end crashing. The python code results in the board freezing (As intended). The C# code results in no changes on the device's end, and the serial port not working until it is replugged. How can I get the C# code to do the same thing that the python code does?
This python code works:
import serial # this is installed with 'pip install pyserial'
ser = serial.Serial(
port='COM5',
baudrate=115200,
)
ser.write(b'\x03\r')
I tried to make this C# code to do the same thing but it does not work
using System.IO.Ports;
public static class tester {
public static void main(/* String[] args */) {
SerialPort sport = new SerialPort("COM5", 115200);
sport.Open();
sport.Write(new byte[]{0x03, 0xD}, 0, 2);
sport.Close();
}
}
Thanks for trying to help me :)
The solution as #kunif and #Hans Passant said was that I needed to set certain parameters as their defaults are not the same on different implementations of serial port libraries. To use a serial device that works fine with the default settings of PySerial use the following code. You will likely have to change the baud rate based on your specific device.
SerialPort sport = new SerialPort("COM5", 115200);
// I love StackOverflow
sport.Handshake = Handshake.None;
sport.DtrEnable = true;
sport.RtsEnable = true;
sport.StopBits = StopBits.One;
sport.DataBits = 8;
sport.Parity = Parity.None;
sport.Open();

Missing bytes while reading the bytes from C# serial port class

I wrote down some app in C# to read the bytes from (USB-SerialPort) payment terminal.
But I can see the bytes are missing/overridden in my application while I read from the read-Buffer of windows serial port.
I have following piece of code for opening the port and reading the bytes( either from ReadExisting or ReadByteArray) from serial port when the DataReceivedEvent gets triggered.
//Open the port
m_port.Open();
//attach the event handler
m_port.ErrorReceived += OnSerialErrorReceived;
m_port.DataReceived += OnSerialDataReceived;
public void OnSerialDataReceived(object sender ,SerialDataReceivedEventArgs serialDataArgs)
{
//Thread.Sleep(20);
//int numberOfBytesToRead = m_port.BytesToRead;
//byte[] readByteArray = new byte[m_port.BytesToRead];
//m_port.Read(readByteArray, 0, readByteArray.Length);
string readData = m_port.ReadExisting();
ParseWLinkProtocolMsgToHexStringArray(Encoding.UTF8.GetBytes(readData));
}
But when I use the Thread.Sleep(20ms) before read the data in OnSerialDataReceived method , I have no missing bytes in my data.
Also I have not set any other properties on the serial port instance except the following.
BaudRate,StopBits,Parity and DataBits.
Can some one please suggest me any other alternative way with out applying the time delay in my application.

Smart Card Encoder using C# code

I'm new to this device,
I only tried RFID Mifare RC522 and read its serial ID
This time I'm trying to read the serial ID of RFID card using this Smart Card Encoder (LA118-M1) using C# coding in MS Visual Studio.
What class library should I download.
I tried using this code:
SerialPort _serialPort = new SerialPort("COM2");
_serialPort.Open();
bool _check = _serialPort.IsOpen;
string _string = _serialPort.ReadLine();
_serialPort.Close();
Result:
Nothing happens
You are not listening serial port. On your initializing code, open COM port and listen to it (Add DataReceived delegate). It would be something like this:
public void Open()
{
_serialPort = new SerialPort("COM2");
_serialPort.Open();
_serialPort.DataReceived +=port_DataReceived;
}
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string line = ((SerialPort)sender).ReadLine();
}
// Close serial port somewhere
You can learn more about SerialPort here or here

Bytes sent over SerialPort not the same when received on Netduino over Bluetooth

I am working on a project and I am using this website as a reference to get my Netduino to communicate with my PC.
I've purchased this Bluetooth transceiver. It seems to be an updated version of the one used by the original post. 1.06 vs 1.04 on his website.
I set the Bluetooth's TXD to Pin0, RXD to Pin1, and VCC to 5V.
This is my code on the Netduino:
static SerialPort Bluetooth;
public static void Main()
{
Bluetooth = new SerialPort(SerialPorts.COM1, 9600, Parity.None, 8, StopBits.One);
Bluetooth.DataReceived += new SerialDataReceivedEventHandler(Bluetooth_DataReceived);
Bluetooth.Open();
Thread.Sleep(Timeout.Infinite);
}
static void Bluetooth_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] bytes = new byte[1];
while(Bluetooth.BytesToRead > 0)
{
Bluetooth.Read(bytes, 0, bytes.Length);
Debug.Print(bytes[0].ToString());
}
}
This is my code on my laptop: (it is a WPF application)
SerialPort serialBT;
private void Connect()
{
// COM7 is the outgoing port that corresponds to the Bluetooth transceiver
serialBT = new SerialPort("COM7", 9600, Parity.None, 8, StopBits.One);
serialBT.Open();
serialBT.Write(new byte[] { 23, 24, 25, 26 }, 0, 4);
Debug.Print("Values sent");
}
On the Netduino, when I send the byte array of 23, 24, 25, and 26 (just for testing purposes), the DataReceived event fires. However the values it received and prints out in the debug window are 6, 0, 0, and 248 instead of the 23, 24, 25, and 26 that it should be.
Other values I send are also just as mysteriously transformed to completely different ones.
I've tripled checked the proper COM settings for the Bluetooth transceiver and those are the correct settings. I've flipped the TXD and RXD pins since the original Arduino expects TXD to be Pin1 and RXD to be Pin0, but that causes no data to be received on the Netduino.
So.... I finally got it working. No change in the code. The answer seemed so simple but no one ever bothered to actually explain it; I just needed to switch the TXD and RXD pins.
COM1 for the Netduino means that PIN0 is the RX pin and PIN1 is the TX pin. Its expecting to receive data on PIN0 and send it on PIN1. The Bluetooth component will send data on its TX and the Netduino should receive it on the RX; The Bluetooth TX (send data) should be connected to the Netduino's RX (receive data) and the Bluetooth's RX (receive data) should be connected to the Netduino's TX pin (send data).

Categories

Resources