Smart Card Encoder using C# code - c#

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

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();

How to automatically detect the COM port being used by the arduino to pass data? C#

I am using the Arduino Uno to communicate with my program in the C# Console, and I want the consolet automatically detect which COM port is being used to pass data and connect.
I've already managed to list all the COM ports does anyone know how to automatically connect to a COM port in C#?
public static void Main(string[] args)
{
_usbPort = new SerialPort();
foreach (var s in SerialPort.GetPortNames())
{
Console.WriteLine(s, "\n");
}
PortSerial();
}
private static void PortSerial()
{
_usbPort.ReadTimeout = 2000;
_usbPort.WriteTimeout = 2000;
_usbPort.Open();
// Write(1);
// Read(2);
Executar();
}

C# Serial Communication DLL

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()

SerialPort read just first character of string

I create small test app to test connection between app and some device which measure temperature. When I write some command to device it's ok, but when device return me response, a string, for that I use ReadExisting() method. But app reads just first character of the string. If I send command again, it's same situation. I try to test connection with program called Terminal.exe, it's happens the same. But when I change BaudRate at some value and return BaudRate on 9600 ( it's ok rate ), then it's worked fine. Also I try to change BaudRate in my app, but it give me the same, just first character of string. Also I have an app written in LabView which works fine.
Also I tested my app with another PC with Terminal.exe , and it's worked fine.
private void SetUpPort()
{
port = new SerialPort();
port.PortName = port_name;
port.BaudRate = 9600;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.ReadTimeout = 1000;
p.DataReceived += new SerialDataReceivedEventHandler(PortDataReceived);
}
private void PortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
recived_data += port.ReadExisting();
}
I would be very thankful for any help.
That is not how to use the SerialPort component. You need to attach the DataReceived event handler, which is called every time data comes in on the serial port. An example is found on the page I linked.
You need to append data until you know you're done! You can't just call ReadExisting and assume you get all the information. Do something like this:
private string inBuffer = String.Empty;
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
inBuffer += indata;
if (<inBuffer fulfills some criteria that tells you it's a complete message>)
{
ProcessInBuffer(inBuffer);
inBuffer = String.Empty;
}
}
It is your task to determine the criteria to fulfill. This may be that the received data as a certain length (if the records are fixed length), or maybe they end with newline characters or something else.
you will use datareceived event to store all the data in a array or string and after you can use every data of that string indata += sp.ReadExisting();

Categories

Resources