Open the same serial port multiple times - c#

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.dll
Additional information: Access to the port 'COM3' is denied.
The error happens when i open the port for the second time (when i open the this form again)
using DI_120_Interface.Class;
using MetroFramework.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DI_120_Interface
{
public partial class frmAddInventoryTransItem3 : MetroForm
{
public frmAddInventoryTrans ReceivingAdd { set; get; }
public frmEditInventoryTrans ReceivingEdit { set; get; }
string inv_type2 = null, action2 = null, document2 = null;
static SerialPort _serialPort;
static INIFile settings = new INIFile("C:\\Lateco\\settings.ini");
private string weight;
public frmAddInventoryTransItem3(object parent, string action, string inv_type, string document)
{
if (inv_type == "Receiving in LAVI" && action == "add")
this.ReceivingAdd = (frmAddInventoryTrans)parent;
else if (inv_type == "Receiving in LAVI" && action == "edit")
this.ReceivingEdit = (frmEditInventoryTrans)parent;
InitializeComponent();
inv_type2 = inv_type;
action2 = action;
document2 = document;
}
private void frmAddInventoryTransItem3_Load(object sender, EventArgs e)
{
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
string portname, baudrate, parity, databits, stopbits, handshake;
portname = settings.Read("SERIAL PORT PROPERTIES", "PORT_NAME");
baudrate = settings.Read("SERIAL PORT PROPERTIES", "BAUD_RATE");
parity = settings.Read("SERIAL PORT PROPERTIES", "PARITY");
databits = settings.Read("SERIAL PORT PROPERTIES", "DATA_BITS");
stopbits = settings.Read("SERIAL PORT PROPERTIES", "STOP_BITS");
handshake = settings.Read("SERIAL PORT PROPERTIES", "HANDSHAKE");
_serialPort = new SerialPort(); //error here
_serialPort.PortName = portname;
_serialPort.BaudRate = int.Parse(baudrate);
_serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity, true);
_serialPort.DataBits = int.Parse(databits);
_serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits, true);
_serialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
_serialPort.Open();
_serialPort.ReadTimeout = 200;
if (_serialPort.IsOpen)
{
weight = "";
txtWeight.Text = "000.000";
}
_serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
weight = _serialPort.ReadExisting();
weight = weight.Substring(0, 7);
try
{
if (this.InvokeRequired)
this.BeginInvoke(new EventHandler(DisplayText));
}
catch (ObjectDisposedException) { }
}
catch (TimeoutException) { }
}
private void txtPLU_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
this.ActiveControl = txtQty;
}
}
private void txtQty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
this.ActiveControl = txtWeight;
}
}
private void txtWeight_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
this.ActiveControl = btnAddItem;
}
}
private void btnAddItem_Click(object sender, EventArgs e)
{
string plu_code = txtPLU.Text;
txtWarning.Text = "";
if (IsNumeric(txtQty.Text) && IsNumeric(txtWeight.Text))
{
if (Convert.ToDecimal(txtQty.Text) == 0 || Convert.ToDecimal(txtWeight.Text) == 0)
{
txtWarning.Text = "***Qty/Weight must not be equal to zero.***";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtQty;
}
else
{
if (Functions.AddInventoryItemTempFromItemMasterUsingPLU(inv_type2, document2, plu_code, Convert.ToDecimal(txtQty.Text), Convert.ToDecimal(txtWeight.Text)))
{
txtPLU.Text = "";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
if (inv_type2 == "Receiving in LAVI" && action2 == "add")
this.ReceivingAdd.UpdateQtyWeightAmount();
else if (inv_type2 == "Receiving in LAVI" && action2 == "edit")
this.ReceivingEdit.UpdateQtyWeightAmount();
//this.Close();
}
else
{
txtWarning.Text = "***PLU not found.***";
txtPLU.Text = "";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
}
}
}
else
{
txtWarning.Text = "***Please enter numeric value/s only.***";
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtQty;
}
}
private bool IsNumeric(string s)
{
float output;
return float.TryParse(s, out output);
}
private void DisplayText(object sender, EventArgs e)
{
txtWeight.Text = weight;
}
class INIFile
{
private string filePath;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
public INIFile(string filePath)
{
this.filePath = filePath;
}
public void Write(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, this.filePath);
}
public string Read(string section, string key)
{
StringBuilder SB = new StringBuilder(255);
int i = GetPrivateProfileString(section, key, "", SB, 255, this.filePath);
return SB.ToString();
}
public string FilePath
{
get { return this.filePath; }
set { this.filePath = value; }
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (_serialPort.IsOpen)
_serialPort.Close();
}
}
}

A possible solution to this problem could be to have the serial connection in a separate class and provide an event if you received data. Each window can then add an event handler for this event. In the following code, I tried to maintain only the parts necessary to the serial connection. I couldn't really try it on my machine, so there might be some minor problems. Also the event is very basic. It would be better to define a delegate that meets your specific needs:
public class SerialConnection
{
INIFile settings = new INIFile("C:\\Lateco\\settings.ini");
public SerialPort SerialPort { get; set; }
static SerialConnection connection= null;
public event EventHandler WeightReceived;
public static SerialConnection OpenConnection()
{
if(connection == null)
{
connection = new SerialConnection();
string portname, baudrate, parity, databits, stopbits, handshake;
portname = settings.Read("SERIAL PORT PROPERTIES", "PORT_NAME");
baudrate = settings.Read("SERIAL PORT PROPERTIES", "BAUD_RATE");
parity = settings.Read("SERIAL PORT PROPERTIES", "PARITY");
databits = settings.Read("SERIAL PORT PROPERTIES", "DATA_BITS");
stopbits = settings.Read("SERIAL PORT PROPERTIES", "STOP_BITS");
handshake = settings.Read("SERIAL PORT PROPERTIES", "HANDSHAKE");
connection.SerialPort = new SerialPort(); //error here
connection.SerialPort.PortName = portname;
connection.SerialPort.BaudRate = int.Parse(baudrate);
connection.SerialPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity, true);
connection.SerialPort.DataBits = int.Parse(databits);
connection.SerialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits, true);
connection.SerialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
connection.SerialPort.Open();
connection.SerialPort.ReadTimeout = 200;
connection.SerialPort.DataReceived += new SerialDataReceivedEventHandler(connection.serialPort1_DataReceived);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
weight = SerialPort.ReadExisting();
weight = weight.Substring(0, 7);
WeightReceived?.Invoke(weight, new EventArgs());
}
catch (TimeoutException) { }
}
return connection;
}
public void CloseConnection()
{
if (SerialPort.IsOpen)
SerialPort.Close();
}
~SerialConnection()
{
if (SerialPort.IsOpen)
SerialPort.Close();
}
}
In the Form use it like this:
public partial class frmAddInventoryTransItem3 : MetroForm
{
public frmAddInventoryTrans ReceivingAdd { set; get; }
public frmEditInventoryTrans ReceivingEdit { set; get; }
string inv_type2 = null, action2 = null, document2 = null;
private string weight;
private SerialConnection sc = null;
private void frmAddInventoryTransItem3_Load(object sender, EventArgs e)
{
txtQty.Text = 1.ToString();
txtWeight.Text = 0.ToString("N3");
this.ActiveControl = txtPLU;
sc = SerialConnection.OpenConnection();
sc.WeightReceived += new SerialDataReceivedEventHandler(WeightReceived);
}
private void WeightReceived(object weight, EventArgs e)
{
weight = weight as string;
try
{
if (this.InvokeRequired)
this.BeginInvoke(new EventHandler(DisplayText));
}
catch (ObjectDisposedException) { }
}
private void DisplayText(object sender, EventArgs e)
{
txtWeight.Text = weight;
}
}
}

Related

Display a updating list of items on Windows Form using C#

I read a MAC addresses from serial monitor and then i need to put them in the list. My problem is that only the first incoming address (string) is stored in the list. I also need the same addresses (string) not to be stored in the list more than once. I use listbox to view the items in the list. Thanks.
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 SerialMonitor2
{
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
List<string> MacList = new List<string>();
public int cnt = 0;
public Form1()
{
InitializeComponent();
}
private void stop_btn_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message,"Error");
}
}
private void start_btn_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_dataReceived;
try
{
myport.Open();
data_tb.Text = "";
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void myport_dataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
if (in_data[0] == '&')
{
string[] arr = in_data.Split('#');
string MAC = arr[0];
string temperature = arr[3];
textBox1.Text = MAC;
textBox2.Text = temperature;
MacList.Add(MAC);
listBox1.DataSource = MacList;
}
data_tb.AppendText(in_data + "\n");
}
private void port_name_tb_TextChanged(object sender, EventArgs e)
{
}
}
}
/// Try this
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
List<string> MacList = new List<string>();
public int cnt = 0;
public Form1()
{
InitializeComponent();
}
private void stop_btn_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message,"Error");
}
}
private void start_btn_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 115200;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_dataReceived;
try
{
myport.Open();
data_tb.Text = "";
string[] arr = in_data.Split('#');
string MAC = arr[0];
if !MacList.Contains(MAC))
MacList.Add(MAC);
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void myport_dataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
if (in_data[0] == '&')
{
string[] arr = in_data.Split('#');
string MAC = arr[0];
string temperature = arr[3];
textBox1.Text = MAC;
textBox2.Text = temperature;
// MacList.Add(MAC);
listBox1.DataSource = MacList;
}
data_tb.AppendText(in_data + "\n");
}
}

Perform web searches through C # Windows forms

I'm trying to realize web searches to get the title of websites on a Google search.
I got a code that works well on other sites, but using Google I got duplicated results.
I have tried and tried, but I can't see where is the mistake.
Code simplified:
public partial class Form1 : Form
{
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etiqueta in navegador.Document.All)
{
if (etiqueta.GetAttribute("classname").Contains("LC20lb DKV0Md"))
{
listBox1.Items.Add(etiqueta.InnerText);
}
}
}
catch (Exception exception) { }
}
private void function(object sender, EventArgs e)
{
/// string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate("https://google.com/search?q=water");
/// this.Text = query;
}
}
Result:
I don't know how google works but you can prevent duplicates like this
if(!listBox1.Items.Contains(etiqueta.InnerText))
listBox1.Items.Add(etiqueta.InnerText);
After a couple of days researching and improving the code I decided to change the list for a table.
In addition, now the searches are not duplicated and are positioned in the table as expected
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;
namespace SourceDownloader
{
public partial class Form1 : Form
{
strs valor = new strs();
public Form1()
{
InitializeComponent();
}
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etq in navegador.Document.All)
{
if (etq.GetAttribute("classname").Contains("r")) /// LC20lb DKV0Md
{
foreach (HtmlElement a_et in etq.GetElementsByTagName("a"))
{
valor.link = a_et.GetAttribute("href");
}
foreach (HtmlElement t_et in etq.GetElementsByTagName("h3"))
{
valor.tit = t_et.InnerText;
}
bool exist = dataGridView1.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["link"].Value) == valor.link);
var s1 = valor.link;
bool b = s1.Contains("google.com");
bool a = s1.Contains("googleusercontent");
if (!exist /* && !b && !a*/)
{
dataGridView1.Rows.Insert(0, valor.tit, valor.link);
}
}
if (etq.GetAttribute("classname").Contains("G0iuSb"))
{
valor.next = etq.GetAttribute("href");
}
}
more_ops.Enabled = true;
}
catch (Exception)
{
}
}
private void function(object sender, EventArgs e)
{
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
private void more_ops_Click(object sender, EventArgs e)
{
string query = valor.next;
navegador.Navigate(query);
this.Text = query;
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
var msg = dataGridView1.CurrentCell.Value;
System.Diagnostics.Process.Start(msg.ToString());
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
private void Enter(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
string texto = query_box.Text;
texto = texto.Replace("\n", "");
query_box.Text = texto;
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
}
}
/// global values
class strs
{
private string _link = "N/A";
private string _tit = "N/A";
private string _next = "N/A";
public string tit
{
get
{
return _tit;
}
set
{
_tit = value;
}
}
public string link
{
get
{
return _link;
}
set
{
_link = value;
}
}
public string next
{
get
{
return _next;
}
set
{
_next = value;
}
}
}
}

How append Rx data on textBox?

I trying to do an inteface to monitoring the Serial Port. I am using Visual forms. So, I had created a combobox to select the PortCOM, a TextBox to send the data to Serial Port and a TextBoxReceber to receive the Serial Data. I trying print the data received in the TextBoxReceber, I'm using the AppendText but I haven't sucess. Anybody can help me?
My Form1.cs is:
namespace ConsoleESP
{
public partial class Form1 : Form
{
string RxString = "";
public Form1()
{
InitializeComponent();
timerCOM.Enabled = true;
atualizaCOMs();
}
private void atualizaCOMs()
{
int i = 0;
bool quantDif = false;
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDif = true;
}
}
}
else quantDif = true;
if (quantDif == false) return;
comboBox1.Items.Clear();
foreach(string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
comboBox1.SelectedIndex = 0;
}
private void timerCOM_Tick(object sender, EventArgs e)
{
atualizaCOMs();
}
private void btConnect_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen == false)
{
try
{
serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
serialPort1.Open();
}
catch
{
return;
}
if (serialPort1.IsOpen)
{
btConnect.Text = "Desconectar";
comboBox1.Enabled = false;
}
}
else
{
try
{
serialPort1.Close();
comboBox1.Enabled = true;
btConnect.Text = "Conectar";
}
catch
{
return;
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (serialPort1.IsOpen == true) serialPort1.Close();
}
private void btEnviar_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
serialPort1.Write(textBoxEnviar.Text);
}
private delegate void RefreshTextBox();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(TrataDadoRecebido));
}
private void TrataDadoRecebido(object sender, EventArgs e)
{
textBoxReceber.AppendText(RxString);
}
}
}

Send data via USB using STX ETC LRC framing (SerialPort object)

I am trying to write a simple Forms app to send data over a USB port to a listening terminal device. I have been told that I need to send the data using STX ETX LRC framing but I have no idea what that means. I am a software tester for our company and not familiar with data transmissions via usb. Is there anyone who can help me with this? This is my current forms code:
private void sendRequestButton_Click(object sender, EventArgs e)
{
try
{
_serialPort = new SerialPort
{
PortName = portsDropdown.Text,
BaudRate = 19200,//connectionTypeDropdown.Text.Equals(Usb) ? 115200 : 19200,
DataBits = 8,
Parity = Parity.None,
StopBits = StopBits.One,
};
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
_serialPort.Open();
_serialPort.Write(requestTextbox.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, #"Caught Exception:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
_serialPort.Close();
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
var serialPort = (SerialPort)sender;
_response = serialPort.ReadExisting();
Debug.Print(_response);
}
Here's what I used for connecting through the serial port in C#. This is in WPF so you'll have to make some adjustments.
using System;
using System.IO.Ports;
using System.Windows;
using System.Windows.Input;
namespace SerialTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private SerialPort port = new SerialPort();
int intBaud = 0;
string strComport = "";
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cbCom.ItemsSource = ports;
}
private void StartUp()
{
int intbaud;
if (int.TryParse(cbBaud.SelectionBoxItem.ToString(), out intbaud))
{
intBaud = intbaud;
strComport = cbCom.SelectedItem.ToString();
SerialStart();
}
else
{
MessageBox.Show("Enter a valid Baudrate");
}
}
private void SerialStart()
{
try
{
port.BaudRate = int.Parse(cbBaud.SelectionBoxItem.ToString());
port.DataBits = 8;
port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "One");
port.Parity = (Parity)Enum.Parse(typeof(Parity), "None");
port.PortName = cbCom.SelectedItem.ToString();
port.DataReceived += new SerialDataReceivedEventHandler(SerialReceive);
port.Handshake = Handshake.None;
if (port.IsOpen) port.Close();
port.Open();
}
catch (Exception ex)
{
txtTerm.AppendText(ex.ToString());
}
}
public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
private void Log(LogMsgType msgtype, string msg)
{
try
{
txtTerm.Dispatcher.Invoke(new EventHandler(delegate
{
txtTerm.AppendText(msg);
}));
}
catch (Exception ex)
{
ex.ToString();
}
}
private void SerialReceive(object sender, SerialDataReceivedEventArgs e)
{
if (!port.IsOpen) return;
string data = port.ReadExisting();
this.Dispatcher.Invoke(() =>
{
txtTerm.AppendText(data);
txtTerm.ScrollToEnd();
});
}
private void txtInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return && port.IsOpen)
{
try
{
port.WriteLine(txtInput.Text + "\r\n");
}
catch (Exception ex)
{
this.Dispatcher.Invoke(() =>
{
txtTerm.AppendText(ex.ToString()); ;
});
}
this.Dispatcher.Invoke(() =>
{
txtTerm.AppendText(txtInput.Text + "\n");
txtInput.Text = "";
});
}
}
}
}
Edit
Looks like for STX and ETC you have to also convert the characters to bytes
https://www.codeproject.com/questions/1107562/sending-ascii-control-stx-and-etx-in-csharp

Read string over Serial from Arduino

I have an Arduino connected to an interface I made. Everything is working fine, however the Arduino is sending a string to the interface. The program is reading the data, and storing it in a variable.
The problem I am having is that the variable stores the data, but doesn't update it when new data is coming in from the Arduino .
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 WindowsFormsApp3
{
public partial class Form1 : Form
{
public SerialPort myport;
int irisvalue;
string myString;
string s = "";
//String s2;
public Form1()
{
InitializeComponent();
//Load += new EventHandler(Form1_Load);
connectbtn.Text = "Connect";
disconnect.Text = "Disconnect";
this.connectbtn.Click += new EventHandler(connectbtn_Click);
this.disconnect.Click += new EventHandler(disconnect_Click);
this.iris1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.iris1_MouseDown);
this.iris1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.iris1_MouseUp);
this.iris2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.iris2_MouseDown);
this.iris2.MouseUp += new System.Windows.Forms.MouseEventHandler(this.iris2_MouseUp);
this.focus1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.focus1_MouseDown);
this.focus1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.focus1_MouseUp);
this.focus2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.focus2_MouseDown);
this.focus2.MouseUp += new System.Windows.Forms.MouseEventHandler(this.focus2_MouseUp);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void connect()
{
myport = new SerialPort();
myport.BaudRate = 9600;
myport.PortName = "COM3";
myport.Open();
}
void read()
{
s = myport.ReadLine();
//Form1_Load();
}
void discon()
{
myport.Close();
}
private void disconnect_Click(object sender, System.EventArgs e)
{
discon();
if (myport.IsOpen)
{
}
else
{
connectbtn.Text = "Connect";
disconnect.BackColor = default(Color);
connectbtn.BackColor = default(Color);
}
}
private void connectbtn_Click(object sender, System.EventArgs e)
{
connect();
if (myport.IsOpen)
{
connectbtn.Text = "Connected";
connectbtn.BackColor = Color.Green;
//Load += new EventHandler(Form1_Load);
Form1_Load();
disconnect.BackColor = Color.Red;
disconnect.Text = "Disconnect";
read();
//s = myport.ReadLine();
}
else
{
connectbtn.Text = "Error";
connectbtn.BackColor = Color.Red;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void iris1_MouseDown(object sender, MouseEventArgs e)
{
//Console.WriteLine("Hello");
irisvalue = 1;
myString = irisvalue.ToString();
Form1_Load();
}
private void iris1_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
private void iris2_MouseDown(object sender, MouseEventArgs e)
{
irisvalue = 2;
myString = irisvalue.ToString();
Form1_Load();
}
private void iris2_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus1_MouseDown(object sender, MouseEventArgs e)
{
irisvalue = 3;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus1_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus2_MouseDown(object sender, MouseEventArgs e)
{
irisvalue = 4;
myString = irisvalue.ToString();
Form1_Load();
}
private void focus2_MouseUp(object sender, MouseEventArgs e)
{
irisvalue = 0;
myString = irisvalue.ToString();
Form1_Load();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void Form1_Load()
{
textBox1.Text = s;
Console.WriteLine(s);
myport.WriteLine(myString);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
To receive updates you should subscribe on serial port events. Try this code:
myport.DataReceived += (sender, e) =>
{
if (e.EventType == SerialData.Chars)
s = myport.ReadLine();
};

Categories