Using Windows Form as a serial communicator to Arduino Uno - c#

I'm new to the Arduino and serial communication, and I haven't coded in a while, but I'm trying to do what I think should be fairly simple, and have been having plenty of trouble. What I'd like to do is to create a simple GUI on Windows Forms and control a Arduino. I keep seeming to run into different problems every new session.
What I've been trying to do is to create a simple GUI that can toggle an LED on and off, and then to use NumericUpDown to toggle it blinking. Previously, I could get the numericUpDown to toggle values but nothing happens, now if I try and toggle, it tells me the port is closed. I've been trying different port communication methods. Since the Form is saying my port is closed, I cannot test to see if what I've written works. Please ignore the commented code as I'm still trying different things.
When I try to call the blink function, it hasn't blinked properly inside a if statement compared to if I kept it in the loop. I'm not sure how and where to send the value from the Winform to the Arduino.
Is Winform much different than using serial monitor commands?
EDIT1: I stepped away from my computer and now when I run the Windows Form, it shows no errors but The program has exited with code 0 (0x0). I've had the timer and haven't really messed with it yet but it wasn't telling me this error earlier and was running the form fine.
My Arduino Code:
// Define Function Prototypes that use User Types below here or use a .h file
int dorun;
int Blinks;
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
getBlinks();
}
// the loop function runs over and over again forever
void loop()
{
if (Serial.available() > 0)
/*
{
byte Blinktimes = Serial.readBytes[];
}
*/
{
String serialInput = Serial.readString();
//Toggle LED
if (serialInput == "On")
{
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); //I have this just to see that the LED is staying on and off, and will need to change things.
for (int x = 1; x = Blinks; x++)
{
blink();
}
}
else
{
digitalWrite(LED_BUILTIN, LOW); // turn the LED on (LOW is the voltage level)
}
Serial.flush(); //Clear Serial
}
/*
digitalWrite(LED_BUILTIN, HIGH);
if ((Serial.available()))
{
int dorun = Serial.read();
if (dorun = 1)
{
blink();
}
else
{
digitalWrite(LED_BUILTIN, LOW);
}
}
*/
/*turnon();
if (dorun == 1)
{
blink();
}
else
{
digitalWrite(LED_BUILTIN, LOW);
}
*/
}
void getBlinks()
{
byte message[3];
if (Serial.available())
{
Serial.readBytes(message, 3);
Blinks = message[3];
}
}
void blink()
{
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the
voltage level)
delay(250); // wait for a second
digitalWrite(LED_BUILTIN, LOW); //!digitalRead(LED_BUILTIN); // turn the LED off by making the voltage LOW
delay(1000);
}
void turnon()
{
if (Serial.available()> 0)
{
String run = Serial.readString();
if (run == "Run")
{
dorun == 1;
}
if (run == "Off")
{
dorun == 0;
}
}
}
My Windows Form Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApp9
{
public partial class Form1 : Form
{
SerialPort serial; // create serial port
/*
* public class Port
{
public string Name { get; set; }
public int Value { get; set; }
public Port(string n, int i)
{
Name = n;
Value = i;
}
}
*/
SerialPort port;
string[] availablePorts = SerialPort.GetPortNames();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
port.Open();
port.Write("On");
port.Close();
}
private void button2_Click(object sender, EventArgs e)
{
port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
port.Open();
port.Write("Off");
port.Close();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
UpdateBlink();
}
void UpdateBlink()
{
port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
port.Open();
const byte messageType = 2;
byte Blinkcount = (byte)numericUpDown1.Value;
byte[] serialBlink = { messageType, Blinkcount };
serialPort1.Write(serialBlink, 0, serialBlink.Length);
port.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
}
I've been checking out these links:
Click here How I toggle the LED
Click here How to return an int since NumericUpDown returns a decimal
Click [here] (https://www.instructables.com/id/Arduino-Visual-Studio-Serial-Communication/) Arduino Visual Studio Serial communication timer things
Click [here] (https://www.instructables.com/id/Communication-From-a-WinForms-to-a-TinyDuino/) instructions about Winforms to TinyDuino, They should use similar commands as the Arduino right?
So I decided to do a slight overhaul. Instead of trying to deal with sending multiple different types of inputs(String and int) I have decided to just change everything into a byte array and then send it all at once.
Regarding 1. I was really just wondering if it'd be alright to create a function to return a value rather than just building the code in a void function. So I tried it and it worked, hence the change. From what I understood and saw that your protected override bool ProcessCmdKey, basically you wanted to see if the key was an arrow key. If it was return true. So what I did was basically if it's one of the selected colors, return a value corresponding to the color.
I was just hoping you could either help me understand the Serial and COM port connection or if you had a link for more explanation. Earlier when I was trying to send a string(On/Off) and then send a numeric(byte/int) to set a number of blink times, I couldn't figure out if the COM port is kind of like a singular channel. If I'm sending a string from the Windows Form, could I send out a int/byte in the same channel? Now that everything is of one keyword (byte) I can just create a byte array and figure out the communication between the Windows Form and Arduino. I'm a little confused about the underlying Serial aspect. When I saw your code I started to think a little differently.
In your code, if I'm understanding it properly, it seems that MyVCOM is how to communicate back and forth, just like port.Write. I believe it's singular as it's basically like the old telephone line, if I'm on a call, and you call try to call me, your call is blocked since my line is already being used.
So in your ConnReset, you want to make sure the COM's aren't open so you can set up communication. So your ConReset will clear the line if it's open already. What I'm confused about is the else part. If your port isn't open, open COM+PortNumber, so basically open the channel so you can communicate, but you declared port number to be 8, so shouldn't you just use:
MyVCOM.PortName = "COM8";
Where does the user select which COM? All of the communication is being done on COM8 isn't it? Or does is that part all part of a built in library? I believe all I need to do now is to send my byte array to my Arduino and then work on the Back End to take the data the Windows Form is sending.
public int Colorselection(string label3, int color) //Toggle a pin
{
if (label3 == "Red")
{
color = 6;
}
else if (label3 == "Green")
{
color = 5;
}
else if (label3 == "Blue")
{
color = 3;
}
return color;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
String label4 = LEDColor.SelectedItem.ToString(); //Generate A string of selected Color
int xled = Colorselection(label4, color); //Toggle the string into an int
LEDLabel.Text = xled.ToString(); //Generate a string from the int
}
private void Run_Click(object sender, EventArgs e) //Generate byte to send instead of sending strings and int/byte
{
byte RGBLED = Convert.ToByte(color);
byte BlinkNum = Convert.ToByte(number1.Value);
byte BlinkDur = Convert.ToByte(number2.Value);
byte[] array2 = new byte[] { RGBLED, BlinkNum, BlinkDur };
port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
/*
port.Open();
port.Write(array2, 0, 2);
port.Close();
*/
}

Your WinForms application assumes that your Arduino is connected to COM3. Do you know if that's actually the case, or is that sample code that you just copy and pasted? (Check the Windows Device Manager under COM ports to see what ports are available, then unplug/plug your device to see which port it's being mapped to)
Besides that, have you tried debugging your Arduino code on target to see what, if anything, is actually being received?
From the MS documentation, it's not clear how the SerialPort.Write command works exactly in terms of synchronization, so it may not be a great idea to close the port immediately after sending your command. Unfortunately, since I'm not in possession of an Arduino I can't test your code. But I did create a WinForms GUI to accomplish essentially the same task (and more that you probably don't need) several years ago that I've since posted to github (https://github.com/mbhul/RoboCOM). Let me know if that helps, otherwise please tell us more about your development environment.

Related

C# to arduino communication

Good afternoon everyone,
I'm experimenting with serial communication between c# and arduino.
To understand how the comms work with regards to sending numbers (I know, there's alot being discussed already but bear with me) I want to send the value of a trackbar to the arduino, and then translate this number in movement of a servo.
If I understand correctly, integers can't be sent directly but have to be converted into bytes first.
So for this I would convert the numeric value of the trackbar into a byte array
in C# :
byte[] Numbers;
Numbers = BitConverter.GetBytes(trackBar1.Value);
Via serial communication I would send the value
port.Write(Numbers, 0, 1);
And this is where I'm going wrong I think
The trackbar value goes from 0 to 255, so I guess I'd need to know the bytes that equal 0 to 255 to be able to adjust the last number (in my example '1') to get the correct number after translation in Arduino?
As for Arduino, I would 'translate' the bytes as follows:
int IncomingValue = Serial.parseInt();
And then I'd like to use the IncomingValue for my servo.
My question is what I'm doing incorrectly.
thanks
For those interested in tinkering with c# to arduino serial communication (just desribing the issue I had) and sending a value of a trackbar to use in arduino:
make yourself a form project and name it whatever you like.
Then create a trackbar. I will create a trackbar with a minimum value of 0 and a maximum of 255 as follows:
trackbar1.Minimum = 0;
trackbar1.Maximum = 255;
trackBar1.TickFrequency = 10; // this will set ticks every 10 units.
Now we can setup the actual communication between c# and arduino. I'll start with c#.
Opening a port:
port = new SerialPort("COM5", 9600); //Set your Arduino COM port and baud rate
port.Open();
Now we also need to create an event to close the port when the program shuts:
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (port != null && port.IsOpen)
{
port.Close();
}
}
Now we have set up the port, but we still need data to send. In our example we told we were going to send the value of the trackbar. To do this, click on your trackbar and find the trackBar1_Scroll event and double click it.
This basically creates the event of scrolling the trackbar and now we have to describe in this event what we want to happen.
We want to send the data of the trackbar via serial. The trackbar value is retrieved as follows:
trackbar1.value
Now we know how to retrieve the value, we have to look at the options of sending it, there's 3 options using port.write(), we'll use this later:
-Write(String)
-Write(Byte[], Int32, Int32)
-Write(Char[], Int32, Int32)
but as I'm working with an int, I found that the second one was the one I needed.
As you can see we need a Byte array to be able to send this, so we will cast our trackbar data into a byte array by using BitConverter and declaring a byte array called Numbers:
byte[] Numbers = BitConverter.GetBytes(trackBar1.Value);
Now we have every element we need:
The port which has been opened. We also described when to close it.
The trackbar and its data to send.
The data of the trackbar 'packaged' the correct way to be able to send it.
the only thing we didn't do is describe the scroll event, but now we have the correct data format, we can:
private void trackBar1_Scroll(object sender, EventArgs e)
{
byte[] Numbers = BitConverter.GetBytes(trackBar1.Value);
port.Write(Numbers, 0, 1);
}
so in c# our code will look like this:
public Form1()
{
InitializeComponent();
trackBar1.Minimum = 0;
trackBar1.Maximum = 255;
trackBar1.TickFrequency = 10;
port = new SerialPort("COM5", 9600);//Set your board COM
port.Open();
this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
}
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (port != null && port.IsOpen)
{
port.Close();
}
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
byte[] Numbers = BitConverter.GetBytes(trackBar1.Value);
port.Write(Numbers, 0, 1);
}
As for arduino, all we need to do is:
A] Start our serial
B] Read the incoming data
#include <LiquidCrystal.h> // include the LCD library
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //define the LCD display
int Number; //define the number int (the one we'll store our received trackbar value in)
void setup()
{
Serial.begin(9600); //A] Start our serial
}
void loop()
{
lcd.setCursor(0, 0); // Set the LCD cursor at the top left corner
if (Serial.available() > 0 ) { //B] Read the incoming data
nummer = Serial.read(); //
lcd.print(nummer); //
} //
else {}; //
}
I used an LCD to read the data as I couldn't figure out a way to open the serial monitor with the serial communication between c# and arduino happening.
that's why I included an LCD.
I feel explaining this is beyond the scope of this little issue I had.
I hope this helps other beginners like me in the future.
thanks to those who were helpful!

Arduino with servomotors does not respond to serial input from pySerial in Python

I am a noob looking for help. Here is my problem. I have an Arduino Uno with two servomotors; one attached to pin 10, the other to pin 11. I want the servos to move independently according to instructions sent through a serial port to the Arduino from Python on Windows. As such I need Arduino code and Python code. I have used both Python 2.7 and 3.6 with pySerial installed. So far I have only been able to move the servos when using C# to send the coordinates to the Arduino, or from the Arduino code itself. Here is the code. I do not take credit for the Arduino code or the C# code.
Arduino code (Credit to Michael Reeves)
#include<Servo.h>
Servo serX;
Servo serY;
String serialData;
void setup() {
serX.attach(10);
serY.attach(11);
Serial.begin(9600);
Serial.setTimeout(10);
}
void loop() {
}
void serialEvent() {
serialData = Serial.readString();
serX.write(parseDataX(serialData));
serY.write(parseDataY(serialData));
}
int parseDataX(String data){
data.remove(data.indexOf("Y"));
data.remove(data.indexOf("X"), 1);
return data.toInt();
}
int parseDataY(String data){
data.remove(0, data.indexOf("Y") + 1);
return data.toInt();
}
I know that the Arduino code works because I can write to the servos within it and the servos respond correctly. It is also working with C#.
C# code (Credit to Michael Reeves):
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace LaserControl {
public partial class Form1 : Form {
public Stopwatch watch { get; set; }
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e) {
watch = Stopwatch.StartNew();
port.Open();
}
private void Form1_MouseMove(object sender, MouseEventArgs e) {
writeToPort(new Point(e.X, e.Y));
}
public void writeToPort(Point coordinates) {
if (watch.ElapsedMilliseconds > 15) {
watch = Stopwatch.StartNew();
port.Write(string.Format("X{0}Y{1}", (180 - coordinates.X / (Size.Width / 180)), (coordinates.Y / (Size.Height / 180))));
System.Diagnostics.Debug.WriteLine(string.Format("X{0}Y{1}", (coordinates.X / (Size.Width / 180)), (coordinates.Y / (Size.Height / 180))));
}
}
}
}
This code takes mouse input from a form and sends it to the servos. The data structure is a string that looks like this "X90Y100", where the letters correspond to servos and the numbers are the angle.
It is working and the servos move correctly.
Here is the Python code. It is simply a test of moving the servos.
import serial
port = serial.Serial("COM3", 9600)
port.write(b"X100Y70")
The servos do not move. What is the problem?
Any help would be greatly appreciated.
Thank you.
The answer is on this page: Arduino and Python
It is worth noting that the example above will not work on a Windows
machine; the Arduino serial device takes some time to load, and when a
serial connection is established it resets the Arduino.
Any write() commands issued before the device initialised will be
lost. A robust server side script will read from the serial port until
the Arduino declares itself ready, and then issue write commands.
Alternatively It is possible to work around this issue by simply
placing a 'time.sleep(2)' call between the serial connection and the
write call.
I've tested it and it works with the delay added:
import serial
import time
port = serial.Serial("COM3", 9600)
time.sleep(2)
port.write(b"X100Y70")
You should consider a more robust message format. At the least, it should have a terminator char (like "\n"). Serial.readString(); relies on a timeout to determine when a complete message has been received. This can cause errors. You can change your message format to have a terminator (or a fixed size):
void serialEvent() {
static String serialData;
while (Serial.available()) {
char c = (char)Serial.read();
if (c == '\n') {
// Complete message, call a function to handle it
serX.write(parseDataX(serialData));
serY.write(parseDataY(serialData));
// Reset for next message
serialData = "";
}
else {
// Otherwise keep building the message
serialData += c;
}
}

How to store data through web service when data coming to my serial port will be asynchronous?

I have one device "installed" on a users desk (a desk is nothing but a chair or table on which user will sit), and I will be supporting thousands of desks.
A user will have one "chip" and the user will scan this chip on the device which is installed on their desk.
The device will read the data off the chip and will send it to my laptop which will also have one of the devices installed, except this device is the main device responsible for collecting all user scan chip data.
All the data will be routed to my device via a wifi router and I will listen to this from my Main device and read data from this device from my laptop via serial port connection.
This data sending will happen as each user number scans his/her chip.
I have created a windows form application which will continuously run in the background on my laptop, and will be listening to my serial port on which main device is connected.
This is my code taken from here: Source Code Reference:
public partial class MainUI : Form
{
SerialPortManager _spManager;
public MainUI()
{
InitializeComponent();
UserInitialization();
}
}
private void UserInitialization()
{
_spManager = new SerialPortManager();
_spManager.NewSerialDataRecieved += new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved);
this.FormClosing += new FormClosingEventHandler(MainUI_FormClosing);
}
private void MainUI_Load(object sender, EventArgs e)
{
_spManager.StartListening()
}
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
// Send data to whom ever interested
if (NewSerialDataRecieved != null)
{
NewSerialDataRecieved(this, new SerialDataEventArgs(data));
}
}
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
{
if (this.InvokeRequired)
{
// Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e });
return;
}
//data is converted to text
string str = Encoding.ASCII.GetString(e.Data);
if (!string.IsNullOrEmpty(str))
{
//Here i will store that data in to my database through web service.
//What i should use whether WCF service or Web Api because data will be continuos like at a
//time more than 10 or 100 user can scan data at the same time so this event will be fired continuously.
//I am using entity framework to store data in to my database and how to ansynchornously call web service to store my data
//so that my call doesnt block incoming data to serial port
}
}
My main concern is I will have numerous users who will scan data at the same time and how I will handle when more than 10 or 100 user scan the data at the same time.
How can I mitigate this potential issue?
Ok, if i got the question right you need to do something like this ...
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int dataLength = _serialPort.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = _serialPort.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
// Send data to api
string str = Encoding.ASCII.GetString(e.Data);
if (!string.IsNullOrEmpty(str))
{
var api = new HttpClient();
api.BaseUrl("http://somewhere.com");
api.PostAsJsonAsync("api/Something", str)
}
if (this.InvokeRequired)
{
// Using this.Invoke causes deadlock when closing serial port,
// and BeginInvoke is good practice anyway.
this.BeginInvoke(new EventHandler<SerialDataEventArgs>(
_spManager_NewSerialDataRecieved), new object[] { sender, e
});
return;
}
}
// i think this can go completely ...
void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
That posts the data to webapi but whilst that post is taking place on another thread the serial port can carry on receiving data
close your serial port and load every some-amount-of-time. After that some-amount-of-time open the port and scan all devices, then close it again.
public void MainUI.Load(Object sender, Eventargs e)
{
if (_spmanager != null && !_spManager.IsOpen)
//*write the code here where it opens and starts listening
_spmanager.StartListening();
//*write the code here where it waits a little bit then
_spmanager.Close();
}
Therefore everytime it loads it starts when the port is closed, it opens for a little bit, scans whatever values are true and then closes again.
I am not very sure about this but it is just an idea of how to handle it. The code might not be accurate or currect I just wrote it quickly. Take the idea from this

Read Weight from a Serial Mettler Toledo Digital Scale

I am trying to read weight from digital scale in c# app, found this question
this is exactly what I am trying to do
but for me below function never runs.
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(DoUpdate));
}
I have checked the scale in device manager, its location is set to Port_#0004.Hub_#0003 and appear to be working fine
I was not sure about port number of the scale so I did
var test = SerialPort.GetPortNames();
and only COM1 gets returned
Edit 1: When I do int a = port.ReadByte(); my application hangs and execution never moves forward from this statement.
I faced a problem like this and I solved it changing a COM configuration (Configuration > Comunication > Conections) to SICS in the device. I don't know your scale model but maybe my code can help. [Reading data from Mettler Toledo (IND560) scale device using C#]
Could you try polling instead of using the DataReceived event? Also, I believe the DataReceived event has a threshold before it fires, you might want to look into that too.
Are you able to get the serial number from the balance? This should be the first thing you do when connecting. It will let you verify the connection is established. If you are having trouble connecting through a C# interface try using HyperTerminal first. You can vary a lot of setting really quickly and dial in on the right ones to use. Although the balance should be able to use a wide variety of baud rates and stop bits and such. They are usually pretty adaptable. But do try HyperTerminal.
I'm looking for the pdf but there is a very long list of available commands (depending on your model). The pdf is like 130 pages long. Have you read this?
Please see this post, I used Mike library to connect.
using System;
using System.Linq;
using System.Text;
using HidLibrary;
namespace MagtekCardReader
{
class Program
{
private const int VendorId = 0x0801;
private const int ProductId = 0x0002;
private static HidDevice _device;
static void Main()
{
_device = HidDevices.Enumerate(VendorId, ProductId).FirstOrDefault();
if (_device != null)
{
_device.OpenDevice();
_device.Inserted += DeviceAttachedHandler;
_device.Removed += DeviceRemovedHandler;
_device.MonitorDeviceEvents = true;
_device.ReadReport(OnReport);
Console.WriteLine("Reader found, press any key to exit.");
Console.ReadKey();
_device.CloseDevice();
}
else
{
Console.WriteLine("Could not find reader.");
Console.ReadKey();
}
}
private static void OnReport(HidReport report)
{
if (!_device.IsConnected) { return; }
var cardData = new Data(report.Data);
Console.WriteLine(!cardData.Error ? Encoding.ASCII.GetString(cardData.CardData) : cardData.ErrorMessage);
_device.ReadReport(OnReport);
}
private static void DeviceAttachedHandler()
{
Console.WriteLine("Device attached.");
_device.ReadReport(OnReport);
}
private static void DeviceRemovedHandler()
{
Console.WriteLine("Device removed.");
}
}
}

serialport connection for unknown device

I've coin machine acceptor set and I wanna connect this machine using serialport. My main problem is, I did try almost every setting to connect that machine. The pin numbers are written on the cable as 3th and 7th. So I try
private void Form1_Load(object sender, EventArgs e)
{
// SerialPort paraPort defined at designer's generated code
paraport = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
//I wanna access to windows controls from the thread
System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;
}
private void button2_Click(object sender, EventArgs e)
{
//paraPort is the name of serialport class
paraPort.ReadBufferSize = 1024;
paraPort.WriteBufferSize = 1024;
paraPort.ReadTimeout = 1000;
paraPort.WriteTimeout = 1000;
paraPort.NewLine = "\n";
//Because 7th pin is for RTS which means request 2 send
paraPort.Handshake = Handshake.RequestToSend;
//Data Terminal Ready Enable
paraPort.DtrEnable = true;
paraPort.RtsEnable = true;
paraPort.Open();
//Then Thread check the procedure inside of try - catch block
try{
// Thread money defined at designer's generated code
money = new Thread(new ThreadStart(CheckTheMachineState));
money.Start();
}catch(Exception e){
MessageBox.Show("thread cannot be created"+e.Message);
}
}
private void CheckTheMachineState()
{
richTextBox1.AppendText("Thread is running\n");
//I wanna get the value of IOCTL_SERIAL_WAIT_ON_MASK
//But I still don't know how
}
}
The machine is working well. But when I use paraPort.ReadBufferSize property, it gives me 0 when the coin accept :S. When I use the paraPort.Read method it throws an timeout exception :\
So What can I do for this stuff ? I'm using portmon tools to catch the coin machine signal.
IOCTL_SERIAL_WAIT_ON_MASK value is changed as SUCESS when I put the coin. How can I catch this value ?
After several days of work, I have figured out how to connect a coin acceptor/validator machine to a PC via serial port using VB6, such that every coin inserted in the slot will trigger a signal that will be caught by the PC.

Categories

Resources