It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I need to develop a simple attendance system for a company. I am interested to develop this software in C# because I heard that .NET framework provides Barcode Scanner Libraries which makes this task easier. I have been given barcode scanner of AURORA. I have configured this scanner with my system and it reads when i swipe card before it.
I have no idea how to capture barcode information!! This is a completely new task for me and I don't know the methods which I can use to read barcode.
I know that Scaner usually read data as string, keeps it in clipboard and paste it in
active editbox or whatever it active.
For example, if I open notepad and scan card, in notepad I see the number 00004 (which i think is barcode)...
I have few questions:
1. What is the best way to read barcode value which appears on editbox (My application will have an editbox), I need to control the Scanner Event so that It should not paste barcode value in editbox by iteself, rather than I will use that value...
2. What will be the code which will fire an event when someone swipe card?
Kindly provide some working sample code(C#).Your help will be highly appreciated.
public partial class Form1 : Form
{
SerialPort _serialPort;
// delegate is used to write to a UI control from a non-UI thread
private delegate void SetTextDeleg(string text);
private void Form1_Load(object sender, EventArgs e)
{
// all of the options for a serial device
// can be sent through the constructor of the SerialPort class
// PortName = "COM1", Baud Rate = 19200, Parity = None,
// Data Bits = 8, Stop Bits = One, Handshake = None
_serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
}
private void btnStart_Click(object sender, EventArgs e)
{
// Makes sure serial port is open before trying to write
try
{
if (!_serialPort.IsOpen)
_serialPort.Open();
_serialPort.Write("SI\r\n");
}
catch (Exception ex)
{
MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
string data = _serialPort.ReadLine();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}
private void si_DataReceived(string data)
{
textBox1.Text = data.Trim();
}
private TextBox textBox1;
private Label label1;
private RichTextBox richTextBox1;
private Button button1;
}
Well, usually MSRs (Magnetric Stripe Readers) will dump the output to your STDIN - which means it acts like a keyboard.
You'll have to capture keyboard events in your application in order for it to read the data, start with that.
BTW:
How about your try working out some code before asking for samples?
Related
So, I am trying to read data from the serial port to communicate with an Arduino. Here is the code I am using:
public partial class Form1 : Form
{
SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
public Form1()
{
InitializeComponent();
port.Open();
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(DoUpDate));
}
private void DoUpDate(object s, EventArgs e)
{
textBox1.AppendText(port.ReadLine() + "\r\n");
}
}
But the result I get in the textBox is (check the picture):
The value read should be 975 but I got separated values as well as many empty lines.
Any help is apperciated.
EDIT#1:
Here is the Arduino code:
int sensorPin=A0;
int sensorValue=0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
sensorValue=analogRead(sensorPin);
Serial.print(sensorValue);
Serial.print("\n");
}
And here is the result when I click on the serial reader within arduino IDE (which what C# code should show)
EDIT#2
After thinking more about the problem, I think that the C# code is very fast that it is reading uncomplete data but I don't have a solution for it, do you know anything I can try to solve it?
I'm not fluent in C#, but maybe you should wait for data to be in the Serial buffer before trying to read them. A method for that is to use port.ReadExisting() as it can be seen here!
Hope it helps!
Insert a 20ms delay in your loop()
This question already has an answer here:
Reading from serial port asynchronously using Async await method
(1 answer)
Closed 6 years ago.
I have a program which relies on data being sent through a serial port. I would like to monitor when data is sent through with SerialPort.ReadLine(). My problem is that I use check boxes which freeze when checked because the SerialPort.ReadLine() method blocks until it receives some data. I have also tried using ReadTimeout() but it did not work; perhaps because I did not use it correctly.
I've posted my code for this event below. What I would like this method to do is to monitor my serial port when the checkbox is checked, and then stop monitoring the serial port when I un-check the box. My current situation with my code is that it freezes upon checking the box. All help is appreciated.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
checkBox1.Text = "Listening...";
using (SerialPort arduino = new SerialPort())
{
arduino.BaudRate = 9600;
arduino.PortName = comboBox1.Text;
arduino.Open();
string pipe = arduino.ReadLine(); //loop here
if (pipe == "S")
{
//System.Diagnostics.Process.Start("shutdown", "/f /r /t 0");
System.Windows.Forms.Application.Exit();
}
else
{
checkBox1.Text = "Start";
}
}
}
}
Consider using the SerialPort.DataReceived event instead of blocking.
I have device that can connect to my laptop via blue-tooth as COM5. The device has a Pulse sensor. I want to draw data coming from sensor to graph. However when i connected to COM5 the serialport_Datarecieved event is not triggered. I tried device using matlab. It takes and draws data but i cant get data in c#. I checked the connection status of device and it is ok. I tried to change DtrEnabled and RtsEnapled properties but not worked.
private void Form1_Load(object sender, EventArgs e)
{
cmbPortList.Items.AddRange(SerialPort.GetPortNames());
cmbPortList.Sorted = true;
cmbPortList.SelectedIndex = 0;
this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void btnOpenPort_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = cmbPortList.Text;
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.ReadTimeout = 500;
serialPort1.WriteTimeout = 500;
serialPort1.Handshake = Handshake.None;
if (!serialPort1.IsOpen)
{
btnRun.Enabled = true;
serialPort1.Open();
}
}
catch (Exception ex)
{
serialPort1.Close();
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (serialPort1.BytesToRead > 0)
{
Thread.Sleep(50);
byte[] buffer = new byte[serialPort1.BytesToRead];
serialPort1.Read(buffer, 0, buffer.Length);
}
}
I cant read any data in buffer. There is led is flashing while device is not connected with via blue-tooth. So i am absolutely sure i connected to device.
Is problem about Bluetooth or code? Should i use another library to communicate blue tooth device?
I have read links below.
SerialPort fires DataReceived event after close
SerialPort not receiving any data
This may have less to do with the SerialPort and more to do with the way that Winforms threads are interacting with the serial port's background worker threads. See the solution to this for more info.
I think the designer of the circuit requests data from device with 's'. It must be about its protocol or hex code. I have found that code in matlab sample of circuit % Request Data fprintf(s,'s'); That's why i can read data when i use serialport.Write("Blast"); Also i tried all letters. Only 's' char triggers the event.
Hi I'm trying to program a simple C# WPF that displays time information on a virtual scoreboard in real time from a timing system. I'm fairly new to programming so in depth explanation would be appreciated.
I have created a new thread to handle the incoming data from the COM port and as the app is developed this data will be interpreted. For now I just wanted to display the raw information (in hex) that is coming from the timer into a textbox. This works but not as intended. I am receiving tons of duplicate information, my only explanation is I am reading the data too slowly or its reading the same byte over and over. What I would like to happen is to take out each byte and display them, all controlled by one start/stop button.
Possible solutions include storing the entire buffer in a list or array which I'm not quite sure of yet, I don't want to add so many threads that the program freezes everything up.
Here is my code so far (I'm new to pretty much all the code I have written here, so if anything is bad practice please let me know):
public partial class MainWindow : Window
{
SerialPort comms;
Thread commThread;
bool flag;
string message;
public MainWindow()
{
InitializeComponent();
comms = new SerialPort();
}
private void PortControl_Click(object sender, RoutedEventArgs e)
{
if (!comms.IsOpen)
{
PortControl.Content = "Stop";
comms.PortName = "COM1";
comms.BaudRate = 9600;
comms.DataBits = 8;
comms.StopBits = StopBits.One;
comms.Parity = Parity.Even;
comms.ReadTimeout = 500;
comms.ReceivedBytesThreshold = 1;
commThread = new Thread(new ThreadStart(Handle));
comms.Open();
comms.DataReceived += new SerialDataReceivedEventHandler(ReadIn);
}
else
{
PortControl.Content = "Start";
flag = false;
comms.DataReceived -= ReadIn;
commThread.Join();
comms.Close();
}
}
private void ReadIn(object sender, SerialDataReceivedEventArgs e)
{
if (!commThread.IsAlive)
{
flag = true;
commThread.Start();
}
}
private void Handle()
{
while (flag)
{
if (comms.IsOpen)
{
try
{
message = comms.ReadByte().ToString("X2");
Dispatcher.BeginInvoke((Action)(() =>
{
ConsoleBox.Text += message + " ";
}));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
Here is one solution.
The serial port is receiving the data in its own thread, and you should read the incoming bytes in the data received handler.
I propose to read the data and add it to a thread-safe FIFO list in the data received handler and read the data from the list in the main thread.
See my solution in post Serial port reading + Threads or something better?
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am working on a C# windows form application. How can i edit my code in a way that when more than 2 faces is being detected by my webcam.
More information:
When "FaceDetectedLabel.Text = "Faces Detected : " + cam.facesdetected.ToString();" becomes Face Detected: 2 or more...
How can i do the following:
Minimize all program running except my application.
Here is my code:
namespace PBD
{
public partial class MainPage : Form
{
//declaring global variables
private Capture capture; //takes images from camera as image frames
public MainPage()
{
InitializeComponent();
}
private void ProcessFrame(object sender, EventArgs arg)
{
Wrapper cam = new Wrapper();
//show the image in the EmguCV ImageBox
WebcamPictureBox.Image = cam.start_cam(capture).Resize(390, 243, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC).ToBitmap();
FaceDetectedLabel.Text = "Faces Detected : " + cam.facesdetected.ToString();
}
private void MainPage_Load(object sender, EventArgs e)
{
#region if capture is not created, create it now
if (capture == null)
{
try
{
capture = new Capture();
}
catch (NullReferenceException excpt)
{
MessageBox.Show(excpt.Message);
}
}
#endregion
Application.Idle += ProcessFrame;
}
check this post:
How to programmatically minimize opened window folders
You'll have to enumerate all processes and exclude the current one (yours) instead of getting the "explorer" one. I'd suggest also putting exception handling and some checks in place since not all processes have windows to be minimized
Also this post for the log off part:
Log off user from Win XP programmatically in C#