Not getting response from Lane Control Board - c#

I'm trying to get inputs/outputs from a LCB(lane control board),which in serial. I'm using prolific usb-serial as the interface . I'm new to programming,but i've managed to get send/receive inputs when i shorted pin 2 and 3 of DB9 together . But when i plugged the db9 connector to the LCB , it can send , but not receiving any .
I'm using VS2010 in Windows 10.
Below are my snippets ;
namespace serialPort_wengweng
{
public partial class Form1 : Form
{
byte[] DataReceived = new byte[4096];
byte[] DataTransmitted = new byte[15] { 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15 };
ArrayList ar = new ArrayList();
//------------------------------------LCB input properties here-START------------------------//
String LCBInput;
Boolean i1, i2, i3, i4, i5, i6, i7, i8 = false;
//------------------------------------LCB input properties here-START------------------------//
public Form1()
{
InitializeComponent();
this.serialPort1.DataReceived +=new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void btnConnect_Click(object sender, EventArgs e)
{
Console.Write("Connect button pressed .. ");
//if (serialPort1.IsOpen == true)
//{
//}
//else
// MessageBox.Show("");
if (btnConnect.Text == "Connect")
{
serialPort1.PortName = Convert.ToString(cboPortNames.SelectedItem);
serialPort1.BaudRate = Convert.ToInt32(cboBaudRate.SelectedItem);
serialPort1.DataBits = Convert.ToInt32(cboDataBits.SelectedItem);
serialPort1.DtrEnable = true;
serialPort1.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandshake.SelectedItem.ToString());
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.SelectedItem.ToString());
serialPort1.RtsEnable = true;
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.SelectedItem.ToString());
try
{
if (serialPort1.IsOpen) serialPort1.Close();
serialPort1.Open();
progressBar.Value = 100;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
btnConnect.Text = "Disconnect";
}
else
{
btnConnect.Text = "Connect";
if (serialPort1.IsOpen) serialPort1.Close();
progressBar.Value = 0;
txtTX.Text = String.Empty;
txtRXAll.Text = String.Empty;
txtRXParsing1.Text = String.Empty;
}
Console.WriteLine("Done!");
}
void UpdateTextBox(TextBox objTextBox, String DataParsing)
{
Console.WriteLine("In Update Text Box...");
objTextBox.AppendText(DataParsing);
Console.WriteLine("Done!");
}
void ReceivedData(TextBox objTextBox, String DataParsing)
{
Console.WriteLine("In ReceivedData...");
if (objTextBox.InvokeRequired)
{
this.Invoke(new Action<TextBox, String>(UpdateTextBox), new object[] { objTextBox, DataParsing });
}
Console.WriteLine("Done!");
}
private void PrintValues(ArrayList ar, ComboBox objComboBox)
{
Console.Write("Printing Values... ");
try
{
if (objComboBox.Name == "cboPortNames")
{
foreach (var v in ar)
{
objComboBox.Items.Add("COM" + v);
}
}
else
{
foreach (var v in ar)
{
objComboBox.Items.Add(v);
}
}
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
Console.WriteLine("Print Values T.T");
}
Console.WriteLine("Done!");
}
private void Form1_Load(object sender, EventArgs e)
{
Console.Write("In Form Load()");
GetPortNames();
GetBaudRate();
GetDataBits();
GetParity();
GetStopBits();
GetHandshake();
txtTX.Text = ASCIIEncoding.ASCII.GetString(DataTransmitted);
Console.WriteLine("Done!");
}
void GetPortNames()
{
Console.Write("Getting Port Names..");
ar.Clear();
foreach (String s in SerialPort.GetPortNames())
{
ar.Add(s.Substring(3));
}
ar.Sort();
PrintValues(ar, cboPortNames);
cboPortNames.SelectedIndex = 0;
Console.WriteLine("Done!");
}
void GetBaudRate()
{
Console.Write("Getting BaudRate..");
ar.Clear();
ar.Add(110);
ar.Add(300);
ar.Add(1200);
ar.Add(2400);
ar.Add(4800);
ar.Add(9600);
ar.Add(19200);
ar.Add(38400);
ar.Add(57600);
ar.Add(115200);
ar.Add(230400);
ar.Add(460800);
ar.Add(921600);
PrintValues(ar, cboBaudRate);
cboBaudRate.SelectedIndex = 5;
Console.WriteLine("Done!");
}
void GetDataBits()
{
Console.Write("Getting Data Bits..");
ar.Clear();
for (int i = 5; i <= 8; i++)
{
ar.Add(i);
}
PrintValues(ar, cboDataBits);
cboDataBits.SelectedIndex = 3;
Console.WriteLine("Done!");
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.Write("In Data Received ..");
int i = 0;
string dtString="";
string[] dtArray; // data string saving in here
Thread.Sleep(500); // wait data ready
while (serialPort1.BytesToRead > 0) // if data ready in buffer
{
DataReceived[i] = Convert.ToByte(serialPort1.ReadByte()); // read data serial & saving to array byte
i++; // counter buffer
}
if (i == 15 && DataReceived[14]==15)
{
dtString = ASCIIEncoding.ASCII.GetString(DataReceived); // convert array byte to string
dtArray = dtString.Split((char)44); // parsing string data with separator char(44)
ReceivedData(txtRXAll, dtString); // complete receive data show in here
ReceivedData(txtRXParsing1, dtArray[0]); // data first show in here
}
Console.WriteLine("Done!");
}
private void btnExit_Click(object sender, EventArgs e)
{
Console.Write("Button Exit Pressed..");
if (serialPort1.IsOpen == true)
{
MessageBox.Show("Force quit serial port", "Exit", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Exit();
}
else {
Application.Exit();
Console.WriteLine("Serial port closed,quitting app now.");
Thread.Sleep(1000);
}
Console.WriteLine("Done!");
}
private void btnSend_Click(object sender, EventArgs e)
{
Console.Write("Button Send Pressed..");
if (serialPort1.IsOpen)
{
Console.WriteLine("Shoulda write something.");
var collector = new DataCollector("COM6", ProcessMeasurement);
serialPort1.Write(txtTX.Text);
Thread.Sleep(500);
//Console.WriteLine(serialPort1.Read());
}
else {
MessageBox.Show("Not receiving anything", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Console.WriteLine("Done!");
}
private void ProcessMeasurement(List<byte> bytes)
{
Console.WriteLine("In process measurement...");
}
private void GetHandshake()
{
Console.WriteLine("Get Handshake ...");
try
{
ar.Clear();
foreach (String s in Enum.GetNames(typeof(Handshake)))
{
ar.Add(s);
}
PrintValues(ar, cboHandshake);
cboHandshake.SelectedIndex = 0;
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
}
}
private void GetStopBits()
{
Console.WriteLine("Get StopBits ....");
try
{
ar.Clear();
foreach (String s in Enum.GetNames(typeof(StopBits)))
{
if (s != "None") ar.Add(s);
}
PrintValues(ar, cboStopBits);
cboStopBits.SelectedIndex = 0;
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
}
}
private void GetParity()
{
Console.WriteLine("Get Parity ....");
try
{
ar.Clear();
foreach (String s in Enum.GetNames(typeof(Parity)))
{
ar.Add(s);
}
PrintValues(ar, cboParity);
cboParity.SelectedIndex = 0;
}
catch (NotImplementedException nie)
{
Console.WriteLine(nie);
}
}
}
}
And here is DataCollector class,
namespace serialPort_wengweng
{
class DataCollector
{
private readonly Action<List<byte>> _processMeasurement;
private readonly string _port;
private SerialPort _serialPort;
private const int SizeOfMeasurement = 4;
List<byte> Data = new List<byte>();
public DataCollector(string port, Action<List<byte>> processMeasurement)
{
Console.WriteLine("in Data Collector ..");
_processMeasurement = processMeasurement;
_serialPort = new SerialPort(port);
_serialPort.DataReceived += SerialPortDataReceived;
Console.WriteLine("Done!");
}
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (_serialPort.BytesToRead > 0)
{
var count = _serialPort.BytesToRead;
var bytes = new byte[count];
Console.WriteLine(_serialPort.Read(bytes, 0, count));
AddBytes(bytes);
}
}
private void AddBytes(byte[] bytes)
{
Data.AddRange(bytes);
while (Data.Count > SizeOfMeasurement)
{
var measurementData = Data.GetRange(0, SizeOfMeasurement);
Data.RemoveRange(0, SizeOfMeasurement);
if (_processMeasurement != null) _processMeasurement(measurementData);
}
}
}
}

Related

C# InvaildOperationException Collection was modified

I am having an issue with my C# application, it runs fine or x amount of minutes but hits an error at some point which complains about 'InvaildOperationException Collection was modified'. I am quite new to C# and i am unable to find the solution even after reading other posts.
From what i can tell after reading the posts it is something to do with my for loop, could anyone be so kind as to tell me what i have done wrong.
The error i think is caused by the UpdateGraph function.
The code is designed to connect to a Cisco router and get the cellular data via Serial and show it in a graph and richTextBox which is all working minus the error i get at some point :(
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Cisco_Cellular_Diagnostics
{
public partial class Form1 : Form
{
SerialPort serialPort;
string[] ports;
string rawStrings;
int ComPort_ComboBoxIndex;
bool serialIsOpen = false;
bool autoScroll = false;
readonly String executingFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
TextWriter txtFile;
List<int> bandwidthArray = new List<int>();
List<int> rssiArray = new List<int>();
List<int> rsrpArray = new List<int>();
List<int> rsrqArray = new List<int>();
List<int> snrArray = new List<int>();
List<int> nearbyCellsArray = new List<int>();
private static System.Timers.Timer pollingTimer;
public Form1()
{
InitializeComponent();
ports = SerialPort.GetPortNames();
ToolTip toolTip1 = new ToolTip
{
AutoPopDelay = 5000,
InitialDelay = 500,
ReshowDelay = 500,
ShowAlways = true
};
ComPortComboBox.Items.AddRange(ports);
ComPortComboBox.SelectedIndex = 0;
autoScroll = true;
pollingTimer = new System.Timers.Timer(5000);
pollingTimer.Elapsed += new ElapsedEventHandler(SendCellularCmd);
Console.WriteLine("executingFolder = " + executingFolder);
String fileDate = DateTime.Today.ToString("d").Replace("/", "-");
txtFile = new StreamWriter(executingFolder + "\\Cisco Celluar log " + fileDate + ".txt", true);
LoadChart();
}
private void LoadChart()
{
var chart = chart1.ChartAreas[0];
chart.AxisX.IntervalType = DateTimeIntervalType.Number;
chart.AxisX.LabelStyle.Format = "";
chart.AxisY.LabelStyle.Format = "";
chart.AxisX.LabelStyle.IsEndLabelVisible = true;
chart.AxisX.Minimum = 0;
chart.AxisY.Minimum = -128;
chart.AxisY.Maximum = 128;
chart.AxisX.Interval = 1;
chart.AxisY.Interval = 16;
chart1.Series[0].IsVisibleInLegend = false;
chart.AxisX.Title = "Reading";
chart.AxisY.Title = "dB";
//chart1.Series[0].XValueType = ChartValueType.DateTime;
chart1.Series.Add("Bandwidth");
chart1.Series["Bandwidth"].ChartType = SeriesChartType.Line;
chart1.Series["Bandwidth"].Color = Color.Green;
chart1.Series["Bandwidth"].BorderWidth = 8;
chart1.Series.Add("RSSI");
chart1.Series["RSSI"].ChartType = SeriesChartType.Line;
chart1.Series["RSSI"].Color = Color.Blue;
chart1.Series["RSSI"].BorderWidth = 8;
chart1.Series.Add("RSRP");
chart1.Series["RSRP"].ChartType = SeriesChartType.Line;
chart1.Series["RSRP"].Color = Color.Yellow;
chart1.Series["RSRP"].BorderWidth = 8;
chart1.Series.Add("RSRQ");
chart1.Series["RSRQ"].ChartType = SeriesChartType.Line;
chart1.Series["RSRQ"].Color = Color.Red;
chart1.Series["RSRQ"].BorderWidth = 8;
chart1.Series.Add("SNR");
chart1.Series["SNR"].ChartType = SeriesChartType.Line;
chart1.Series["SNR"].Color = Color.Purple;
chart1.Series["SNR"].BorderWidth = 8;
chart1.Series.Add("Nearby cells");
chart1.Series["Nearby cells"].ChartType = SeriesChartType.Line;
chart1.Series["Nearby cells"].Color = Color.DarkGray;
chart1.Series["Nearby cells"].BorderWidth = 8;
chart1.Series["Bandwidth"].Points.AddXY(0, 0);
chart1.Series["RSSI"].Points.AddXY(0, 0);
chart1.Series["RSRP"].Points.AddXY(0, 0);
chart1.Series["RSRQ"].Points.AddXY(0, 0);
chart1.Series["SNR"].Points.AddXY(0, 0);
chart1.Series["Nearby cells"].Points.AddXY(0, 0);
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
BeginInvoke((MethodInvoker)delegate ()
{
rawStrings += indata;
//txtFile.Write(indata);
//txtFile.WriteLine(DateTime.Now + "\n");
ReceivedDataRichTextBox.AppendText(indata);
if (autoScroll)
ReceivedDataRichTextBox.ScrollToCaret();
});
}
private void OpenSerial_Click(object sender, EventArgs e)
{
ComPort_ComboBoxIndex = ComPortComboBox.SelectedIndex;
if (ComPort_ComboBoxIndex >= 0 && !serialIsOpen)
{
try
{
string selectedCOM = ComPortComboBox.SelectedItem.ToString();
serialPort = new SerialPort(selectedCOM, 9600);
serialPort.ReadTimeout = 3000;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DataBits = 8;
serialPort.Handshake = Handshake.None;
serialIsOpen = true;
serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
OpenSerialOne.Text = "Close Serial";
serialPort.Open();
LogIntoCLI();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else if (serialIsOpen)
{
try
{
serialPort.Write("exit");
serialPort.Close();
txtFile.Close();
pollingTimer.Enabled = false;
serialIsOpen = false;
OpenSerialOne.Text = "Open Serial";
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
else
{
MessageBox.Show("Error, check the baud Rate and COM port is selected and try again.");
}
}
private void LogIntoCLI()
{
if (serialIsOpen)
{
try
{
serialPort.Write("\r");
Thread.Sleep(2000);
serialPort.Write("\r"); // "exit\r"
Thread.Sleep(2000);
serialPort.Write("enable\r");
Thread.Sleep(3000);
serialPort.Write("met0cean\r");
Thread.Sleep(2000);
pollingTimer.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void SendCellularCmd(object sender, ElapsedEventArgs e)
{
ExtractData();
serialPort.Write("show cell 0 radio\r");
Console.WriteLine("sending command...");
}
private void ExtractData()
{
try
{
txtFile.Write(rawStrings);
txtFile.WriteLine(DateTime.Now + "\n");
String[] listOfStrings = rawStrings.Split('\n');
rawStrings = "";
foreach (String value in listOfStrings)
{
String[] strlist = value.Split(' ');
if (value.IndexOf("Bandwidth") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "Bandwidth", ref bandwidthArray);
}
else if (value.IndexOf("RSSI") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSSI", ref rssiArray);
}
else if (value.IndexOf("RSRP") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSRP", ref rsrpArray);
}
else if (value.IndexOf("RSRQ") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "RSRQ", ref rsrqArray);
}
else if (value.IndexOf("SNR") >= 0 && strlist.Length == 5)
{
if (int.TryParse(strlist[3], out int extractedValue))
UpdateGraph(extractedValue, "SNR", ref snrArray);
}
else if (value.IndexOf("nearby cells") >= 0 && strlist.Length == 6)
{
if (int.TryParse(strlist[5], out int extractedValue))
UpdateGraph(extractedValue, "Nearby cells", ref nearbyCellsArray);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void UpdateGraph(int a_value, String a_ID, ref List<int> a_List)
{
try
{
// keep the list count to 20 items
if (a_List.Count == 20)
a_List.RemoveAt(0);
a_List.Add(a_value);
// clear chart and add items
chart1.Series[a_ID].Points.Clear();
for (int i = 0; i < a_List.Count; i++)
{
chart1.Series[a_ID].Points.AddXY(i, a_List[i]);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing Application", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
try
{
txtFile.Close();
serialPort.Write("exit");
serialPort.Close();
pollingTimer.Enabled = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
break;
}
}
private void PollingTimeNumericUpDown_ValueChanged(object sender, EventArgs e)
{
pollingTimer.Interval = Convert.ToDouble(PollingTimeNumericUpDown.Value);
}
private void ClearDataButton_Click(object sender, EventArgs e)
{
ReceivedDataRichTextBox.Clear();
chart1.Series["Bandwidth"].Points.Clear();
chart1.Series["RSSI"].Points.Clear();
chart1.Series["RSRP"].Points.Clear();
chart1.Series["RSRQ"].Points.Clear();
chart1.Series["SNR"].Points.Clear();
chart1.Series["Nearby cells"].Points.Clear();
chart1.Series["Bandwidth"].Points.AddXY(0, 0);
chart1.Series["RSSI"].Points.AddXY(0, 0);
chart1.Series["RSRP"].Points.AddXY(0, 0);
chart1.Series["RSRQ"].Points.AddXY(0, 0);
chart1.Series["SNR"].Points.AddXY(0, 0);
chart1.Series["Nearby cells"].Points.AddXY(0, 0);
}
private void SendManualCmd_Click(object sender, EventArgs e)
{
try
{
serialPort.Write(textBox1.Text + "\r");
textBox1.Clear();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void ReloadComPortsButton_Click(object sender, EventArgs e)
{
ComPortComboBox.Items.Clear();
ports = SerialPort.GetPortNames();
ComPortComboBox.Items.AddRange(ports);
}
private void ComComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// CiscoComPort = ComPortComboBox.SelectedItem.ToString();
}
}
}

Serial Port Unauthorized Exception

I am trying to access RFID Reader through Arduino application which gives me the right output on control monitor.
But when I tried to access it through visual studio C#, it works only once and then gives me access is denied! And also stopped working on Arduino IDE.
//Function to initialize serial port
SerialPort RFIDPort
public SerialPort initializeRFIDPort()
{
try
{
RFIDPort = new SerialPort("COM4",9600,Parity.None,8, StopBits.One);
if (RFIDPort.IsOpen)
RFIDPort.Close();
if(!RFIDPort.IsOpen)
RFIDPort.Open();
}
catch (UnauthorizedAccessException ex) {MessageBox.Show( ex.Message); }
catch (Exception)
{
RFIDPort = null;
}
return RFIDPort;
}
I put the function here:
public products()
{
InitializeComponent();
initializeRFIDPort();
}
There is two scan button the first one for scanning and then add data to the database and the second button is to scan and search for data
private void ScanButton_Click(object sender, EventArgs e)
{
try
{
scanButtonIsClicked = true;
if (RFIDPort.IsOpen)
{
RFIDPort.DataReceived += serialPort1_DataReceived;
textBox1.Text = "";
}
else
MessageBox.Show("RFID Reader is not connected!");
}
catch (System.Exception)
{
MessageBox.Show("Please Try Again");
}
}
private void Searchbutton_Click(object sender, EventArgs e)
{
scansearchbtn = true;
scanButtonIsClicked = false;
try
{
if (RFIDPort.IsOpen)
{
RFIDPort.DataReceived += serialPort1_DataReceived;
textBox2.Text = "";
}
else
{
MessageBox.Show("RFID Reader is not connected!");
}
}
catch (IOException)
{
MessageBox.Show("Please reconnect your device ");
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
string line = RFIDPort.ReadLine();
if (scanButtonIsClicked == true)
this.BeginInvoke(new LineReceivedEvent(LineReceived), line);
else
this.BeginInvoke(new LineReceivedEvent(Line2Received), line);
}
catch (TimeoutException) { }
catch (Exception){ MessageBox.Show("Can't Read from RFID Device.Please try again"); }
}
private delegate void LineReceivedEvent(string line);
private void LineReceived(string line)
{
textBox2.Text = line;
}
private void Line2Received(string line)
{
textBox1.Text = line;
}
And then I closed serial port in Forum-Closing.
Please if anyone can lead me to the right way. I have try many times and it works randomly!
On Aruino side this is my code:
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
MFRC522::MIFARE_Key key;
// Init array that will store new NUID
byte nuidPICC[10];
void setup()
{
Serial.begin(9600);
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
for (byte i = 0; i < 6; i++)
{
key.keyByte[i] = 0xFF;
}
printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
}
void loop()
{
if ( ! rfid.PICC_IsNewCardPresent())
return;
if ( ! rfid.PICC_ReadCardSerial())
return;
// Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
// Serial.println(rfid.PICC_GetTypeName(piccType));
// Check is the PICC of Classic MIFARE type
if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType !=
MFRC522::PICC_TYPE_MIFARE_1K && piccType != MFRC522::PICC_TYPE_MIFARE_4K)
{
Serial.println(F("Your tag is not of type MIFARE Classic."));
return;
}
// Store NUID into nuidPICC array
for (byte i = 0; i < 4; i++)
{
nuidPICC[i] = rfid.uid.uidByte[i];
}
printHex(rfid.uid.uidByte, rfid.uid.size);
Serial.println();
// Halt PICC
rfid.PICC_HaltA();
// Stop encryption on PCD
rfid.PCD_StopCrypto1();
}
void printHex(byte *buffer, byte bufferSize)
{
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}

Real Time Chart with Serial port Data in C#

I want to drawing real time chart in c# with my data that read from serial port Arduino device i didn't know how can i do this with c#.
i want 2d and 3d chart in my program anyone can help me ?
in my program i read data from serial port and time of data has been arrived so my chart be have 2 data one of them is info and another is time.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using port.dbDataSetTableAdapters;
using System.Threading.Tasks;
namespace Factory_Performance
{
public partial class FrmMain : Form
{
int sfs = 0;
string filename;
string line;
string s;
string temp="";
string temp1="";
Series series = new Series();
SerialPort ComPort = new SerialPort();
internal delegate void SerialDataReceivedEventHandlerDelegate(object sender, SerialDataReceivedEventArgs e);
internal delegate void SerialPinChangedEventHandlerDelegate(object sender, SerialPinChangedEventArgs e);
private SerialPinChangedEventHandler SerialPinChangedEventHandler1;
delegate void SetTextCallback(int ReadByte);
int InputData = 0;
private int CountData;
private string StrData;
double[] Values;
public FrmMain()
{
InitializeComponent();
SerialPinChangedEventHandler1 = new SerialPinChangedEventHandler(PinChanged);
ComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
}
private double calculate_input(int s2, int s3)
{
return double.Parse(s2.ToString() + "/" + s3.ToString());
}
private void GetAllIDInDB()
{
tblIDTableAdapter.Fill(dbDataSet.TblID);
CmbID.Items.Clear();
for (int i = 0; i < dbDataSet.TblID.Rows.Count; i++)
CmbID.Items.Add(dbDataSet.TblID.Rows[i]["ID"].ToString());
}
private void GetAllID_DetailsInDB(int ID)
{
tblID_DetailsTableAdapter.FillByID(dbDataSet.TblID_Details, ID);
listreadtxt.Items.Clear();
for (int i = 0; i < dbDataSet.TblID_Details.Rows.Count; i++)
listreadtxt.Items.Add(dbDataSet.TblID_Details.Rows[i]["Value"].ToString());
}
private void GetInfoPorts()
{
try
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
cboPorts.Items.Clear();
cboBaudRate.Items.Clear();
cboStopBits.Items.Clear();
cboParity.Items.Clear();
cboHandShaking.Items.Clear();
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(8);
cboDataBits.Items.Add(7);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
catch
{
MessageBox.Show("خطا در گرفتن اطلاعات پورت");
}
}
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = ComPort.ReadByte();
object firstByte = InputData;
if (ComPort.IsOpen==true)
{
s = Convert.ToString(Convert.ToChar(firstByte));
temp1 += s;
lock (firstByte) {
if (Convert.ToInt32(firstByte) == 13)
{
temp = temp1;
temp1 = "";
ComPort.DiscardInBuffer();
ComPort.DiscardOutBuffer();
LstGetInfo.BeginInvoke(new Action(()=>
{
if (temp !=null)
{
LstGetInfo.Items.Add(temp);
if (LstGetInfo.Items.Count >= 100)
{
LstGetInfo.Items.Clear();
}
FileStream fs = new FileStream(filename, FileMode.Append);
var data = System.Text.Encoding.UTF8.GetBytes(String.Format("{0} {1}", temp, DateTime.Now.ToString("hh mm ss")) +"\r\n");
fs.Write(data, 0, data.Length);
fs.Close();
}
}));
LstGetInfo.BeginInvoke(new Action(() =>
{
LstGetInfo.TopIndex = LstGetInfo.Items.Count - 1;
}));
}
}
}
}
internal void PinChanged(object sender, SerialPinChangedEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = (int)StrData[i];
Array.Reverse(Values);
chart1.Titles.Clear();
chart1.Titles.Add(TxtTitle.Text);
chart1.Series.Clear();
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(TxtTitleSeries.Text + " " + i.ToString(), Values[i]);
chart1.Series.Add(series);
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void CmbPalette_SelectedIndexChanged(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
private void FrmMain_Load(object sender, EventArgs e)
{
chart2.Series.Clear();
// TODO: This line of code loads data into the 'dbDataSet.TblID_Details' table. You can move, or remove it, as needed.
this.tblID_DetailsTableAdapter.Fill(this.dbDataSet.TblID_Details);
// TODO: This line of code loads data into the 'dbDataSet.TblID' table. You can move, or remove it, as needed.
this.tblIDTableAdapter.Fill(this.dbDataSet.TblID);
GetInfoPorts();
CmbPalette.SelectedIndex = 1;
CmbChartType.SelectedIndex = 4;
CountData = 0;
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
GetInfoPorts();
}
private void btnPortState_Click(object sender, EventArgs e)
{
if (sfs == 1) {
try
{
if (btnPortState.Text == "ارتباط با دستگاه")
{
temp1 = "";
temp = "";
btnPortState.Text = "قطع ارتباط با دستگاه";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
LstGetInfo.Items.Clear();
}
else if (btnPortState.Text == "قطع ارتباط با دستگاه")
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
}
}
catch
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
MessageBox.Show("خطا در انجام عملیات");
}
}
else
{
MessageBox.Show("برای ذخیزه فایل محلی را انتخاب کنید");
}
}
private void button1_Click_1(object sender, EventArgs e)
{
savedata();
}
private void savedata()
{
try
{
if (LstGetInfo.Items.Count < 0) return;
int ItemCount = int.Parse(listreadtxt.Items[0].ToString());
int ItemIDCount = 0;
int ItemID = 0;
int ItemValue1 = 0, ItemValue2 = 0;
TblIDTableAdapter tblid = new TblIDTableAdapter();
TblID_DetailsTableAdapter tblid_details = new TblID_DetailsTableAdapter();
tblid.DeleteAllID();
LstGetInfo.Items.RemoveAt(0);
for (int i = 0; i < ItemCount; i++)
{
ItemID = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
tblid.Insert(ItemID);
if (LstGetInfo.Items.Count > 0)
{
ItemIDCount = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
for (int j = 0; j < ItemIDCount; j += 2)
{
ItemValue1 = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
ItemValue2 = int.Parse(LstGetInfo.Items[0].ToString());
LstGetInfo.Items.RemoveAt(0);
tblid_details.Insert(ItemID, calculate_input(ItemValue1, ItemValue2));
}
}
}
}
catch
{
// MessageBox.Show("در ساخت نمودار مشکلی پیش آمده است");
try
{
LstGetInfo.Items.RemoveAt(0);
}
catch
{
}
}
finally
{
GetAllIDInDB();
}
ShowChart();
}
private void CmbID_SelectedIndexChanged(object sender, EventArgs e)
{
GetAllID_DetailsInDB(int.Parse(CmbID.Text));
if (listreadtxt.Items.Count > 0)
ShowChart();
}
private void CmbPalette_SelectedIndexChanged_1(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged_1(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
private void ShowChart()
{
CountData =listreadtxt.Items.Count;
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = double.Parse(listreadtxt.Items[i].ToString());
chart1.Titles.Clear();
chart1.Titles.Add(TxtTitle.Text);
chart1.Series.Clear();
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(TxtTitleSeries.Text + " " + i.ToString(), Values[i]);
chart1.Series.Add(series);
}
private void button3_Click_3(object sender, EventArgs e)
{
GetAllIDInDB();
}
private void button4_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = string.Empty;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) {
listreadtxt.Items.Clear();
Stream fs = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(fs);
while ((line = reader.ReadLine()) != null)
{
listreadtxt.Items.Add(line);
}
reader.Close();
}
}
public void button5_Click(object sender, EventArgs e)
{
dateTimePicker1.BeginInvoke(new Action(() =>
{
DialogResult result1 = saveFileDialog1.ShowDialog();
dateTimePicker1.Format = DateTimePickerFormat.Custom;
string formatvalue =Convert.ToString( dateTimePicker1.Value.Date.ToString(" yyyy-MM-dd"));
filename = saveFileDialog1.FileName + formatvalue + ".csv";
if (result1==DialogResult.OK)
{
sfs = 1;
}
}));
}
private void button6_Click(object sender, EventArgs e)
{
try {
ComPort.Close();
CountData = LstGetInfo.Items.Count;
Values = new double[CountData];
for (int i = 0; i < CountData; i++)
Values[i] = double.Parse(LstGetInfo.Items[i].ToString());
chart2.Titles.Clear();
chart2.Titles.Add(TxtTitle.Text);
series.Points.Clear();
for (int i = 0; i < CountData; i++)
series.Points.AddXY(System.DateTime.Now, Values[i]);
chart2.Series.Add(series);
}
catch
{
LstGetInfo.Items.Remove(0);
}
finally
{
ComPort.Open();
}
}
}
}
The problem is that in line
series.Points.AddXY(System.DateTime.Now, Values[i]);
you are adding points with the same X value set to System.DateTime.Now. In result you have only one point on axis X.
I found solution for my problem
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Threading.Tasks;
using System.Threading;
namespace chart
{
public partial class Form1 : Form
{
string s;
int InputData = 0;
private delegate void CanIJust();
Series series = new Series();
private List<int> _valuelist;
private Thread _thread;
private CanIJust _DoIt;
private Random _ran;
private int _interval;
private List<double> _timelist;
private List<int> _customValueList;
SerialPort ComPort = new SerialPort();
int sfs = 0;
string temp = "";
string temp1 = "";
public Form1()
{
InitializeComponent();
chart1.ChartAreas[0].AxisX.IsStartedFromZero = true;
chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = false;
chart1.Series[0].XValueType = ChartValueType.Time;
chart1.ChartAreas[0].AxisX.ScaleView.SizeType = DateTimeIntervalType.Seconds;
chart1.ChartAreas[0].AxisX.IntervalAutoMode = IntervalAutoMode.FixedCount;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Seconds;
chart1.ChartAreas[0].AxisX.Interval = 0;
_valuelist = new List<int>();
_ran = new Random();
_interval = 500;
tbupdateinterval.Text = "500";
GoBoy();
_timelist = new List<double>();
_customValueList = new List<int>();
}
private void GetInfoPorts()
{
try
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
cboPorts.Items.Clear();
cboBaudRate.Items.Clear();
cboStopBits.Items.Clear();
cboParity.Items.Clear();
cboHandShaking.Items.Clear();
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(8);
cboDataBits.Items.Add(7);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
catch
{
MessageBox.Show("خطا در گرفتن اطلاعات پورت");
}
}
private void GoBoy()
{
_DoIt += new CanIJust(AddData);
DateTime now = DateTime.Now;
chart1.ChartAreas[0].AxisX.Minimum = now.ToOADate();
chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(10).ToOADate();
_thread = new Thread(new ThreadStart(ComeOnYouThread));
_thread.Start();
}
private void ComeOnYouThread()
{
while (true)
try
{
chart1.Invoke(_DoIt);
Thread.Sleep(_interval);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Exception:" + e.ToString());
}
}
private void AddData()
{
DateTime now = DateTime.Now;
InputData = ComPort.ReadByte();
object firstByte = InputData;
if (ComPort.IsOpen == true)
{
s = Convert.ToString(Convert.ToChar(firstByte));
temp1 += s;
lock (firstByte)
{
if (Convert.ToInt32(firstByte) == 13)
{
temp = temp1;
temp1 = "";
ComPort.DiscardInBuffer();
ComPort.DiscardOutBuffer();
_valuelist.Add(Convert.ToInt32(temp));
chart1.ResetAutoValues();
if (chart1.Series[0].Points.Count > 0)
{
while (chart1.Series[0].Points[0].XValue < now.AddSeconds(-5).ToOADate())
{
chart1.Series[0].Points.RemoveAt(0);
chart1.ChartAreas[0].AxisX.Minimum = chart1.Series[0].Points[0].XValue;
chart1.ChartAreas[0].AxisX.Maximum = now.AddSeconds(5).ToOADate();
}
}
chart1.Series[0].Points.AddXY(now.ToOADate(), _valuelist[_valuelist.Count - 1]);
chart1.Invalidate();
}
}
}
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (_thread != null)
_thread.Abort();
}
private void btn_2D_Click_1(object sender, EventArgs e)
{
btn_2D.Enabled = false;
btn_3D.Enabled = true;
chart1.ChartAreas[0].Area3DStyle.Enable3D = false;
}
private void btn_3D_Click_1(object sender, EventArgs e)
{
btn_2D.Enabled = true;
btn_3D.Enabled = false;
chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
}
private void btn_add_Click(object sender, EventArgs e)
{
_customValueList.Add(_ran.Next(0, 100));
_timelist.Add(DateTime.Now.ToOADate());
updatesecondChart();
}
private void updatesecondChart()
{
chart2.Series[0].Points.AddXY(_timelist[_timelist.Count - 1], _customValueList[_customValueList.Count-1]);
chart2.Invalidate();
}
private void btn_serialize_Click(object sender, EventArgs e)
{
}
private void btn_updateInterval_Click(object sender, EventArgs e)
{
int interval = 0;
if (int.TryParse(tbupdateinterval.Text, out interval))
{
if (interval > 0)
_interval = interval;
else
MessageBox.Show("بازه زمانی باید بیشتر از 0 باشند");
}
else
{
MessageBox.Show("I nappropriate Data.");
}
}
private void btnGetSerialPorts_Click(object sender, EventArgs e)
{
GetInfoPorts();
}
private void btnPortState_Click(object sender, EventArgs e)
{
//if (sfs == 1)
//{
try
{
if (btnPortState.Text == "ارتباط با دستگاه")
{
temp1 = "";
temp = "";
btnPortState.Text = "قطع ارتباط با دستگاه";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
AddData();
}
else if (btnPortState.Text == "قطع ارتباط با دستگاه")
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
}
}
catch
{
btnPortState.Text = "ارتباط با دستگاه";
ComPort.Close();
MessageBox.Show("خطا در انجام عملیات");
}
}
//else
//{
// MessageBox.Show("برای ذخیزه فایل محلی را انتخاب کنید");
//}
//}
private void CmbPalette_SelectedIndexChanged_1(object sender, EventArgs e)
{
chart1.Palette = (ChartColorPalette)CmbPalette.SelectedIndex;
}
private void CmbChartType_SelectedIndexChanged(object sender, EventArgs e)
{
series.ChartType = (SeriesChartType)CmbChartType.SelectedIndex;
}
}
}

c# Serial DataReceived very slow

I've trying to communicate with an Arduino Due in C#. The communikation works quite well, but my DataReceived handler needs about 1 second to react. This is my problem because I have to send up to 1 billion (1*10E9) commands.
If I activate a DEBUG Setting in the Arduino, it tells me that it's need 64 Milliseconds for a command. I think the C# the App should get it no later than 80 Milliseconds after sending it.
Here is a Part of the Code:
StopWatch s1 = new StopWatch();
private void Open_Port()
{
string port = null;
int baud = 0;
bool ERR = false;
if ((COM_cb.SelectedItem != null) | (BAUD_cb.SelectedItem != null))
{
port = this.COM_cb.GetItemText(this.COM_cb.SelectedItem);
baud = Convert.ToInt32(this.BAUD_cb.GetItemText(this.BAUD_cb.SelectedItem));
ERR = false;
}
else
{
ERR = true;
System.Windows.Forms.MessageBox.Show("Error Msg");
}
if (ERR == false)
{
serialPort1.PortName = port;
serialPort1.BaudRate = baud;
serialPort1.Open();
}
if (serialPort1.IsOpen)//Kalibrieren der Buttons
{
OPEN_btn.Enabled = false;
CLOSE_btn.Enabled = true;
textBox1.ReadOnly = false;
ERR = true;
}
}
private void Print_Click(object sender, EventArgs e) // start
{
Thread t = new Thread(transmit_pic);
t.Start();
}
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
s1.Stop();
//Till this line it take 1 Second after sending
//string t = "";
int byt = serialPort1.BytesToRead;
byte[] buffer = new byte[1];
for (int i = 0; i < byt; i++)
{
serialPort1.Read(buffer, 0, 1);
if(buffer[0] == '0') {
got_answer = true;
}
//t += (char)buffer[0];
}
//RxString= t;
//this.Invoke(new EventHandler(DisplayText));
}
private void sendAktion(int[,] data)
{
string s = int_to_string(data, false);
Console.Write("Send->");
serialPort1.Write(s);
s1.Start();
got_answer = false;
int i = 0;
while (!got_answer) { i++; } //wait for answer
i = 0;
Console.WriteLine("back again ");
}
private void transmit_pic()
{
stop = false;
Bitmap bm = new Bitmap(img);
if (!serialPort1.IsOpen)
{
MessageBox.Show("Open the Serial Port first!");
}
else
{
int size_X = bm.Width;
int size_Y = bm.Height;
for (int h = 0; h < size_Y; h++)
{
for (int w = 0; w < size_X; w++)
{
if(/*somthing happend*/){
//get data...
sendAktion(data)
}
}
}
Console.WriteLine("DONE");
}
}
Does anyone an Idea why c# needs so long to call the datahandler?
Sincere regards,
Fabian Harmsen
UPDATE
- Added comment to DataHandler (24.02.2016 16:30 Europa/Berlin)
The problem lies in the serialPort1_DataReceived received data handler.
I ran a separate thread with a while(true) loop and serial.ReadLine(), all works perfectly.
Hope someone else doesn't need to spend 3 hours fixing this.
using System.Threading;
public void main()
{
setup();
Thread readThread = new Thread(Read);
readThread.Start();
}
public void Read()
{
while(true)
{
try
{
string message = serialPort1.ReadLine();
}
catch (Exception)
{ }
}

How to add realtime data from OPC client to user control using c#

I created an OPC client to connect to KepServerEX, I got realtime data from KepServerEX and now I want to add realtime data to user control that contains a textbox.
Realtime data will be updated via value_changed event.
I created Windows Form Application and added textbox to Form to display realtime value, I can not post images here.
This is my code:
namespace OPC_Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OPCServer KepServer;
OPCGroups KepGroups;
OPCGroup KepGroup;
OPCItems KepItems;
OPCItem KepItem;
string strHostIP = "";
string strHostName = "";
bool opc_connected = false;
int itmHandleClient = 0;
int itmHandleServer = 0;
private bool CreateGroup()
{
try
{
KepGroups = KepServer.OPCGroups;
KepGroup = KepGroups.Add("OPCDOTNETGROUP");
SetGroupProperty();
KepGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
KepGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete);
KepItems = KepGroup.OPCItems;
}
catch (Exception)
{
return false;
}
return true;
}
private void SetGroupProperty()
{
KepServer.OPCGroups.DefaultGroupIsActive = true;
KepServer.OPCGroups.DefaultGroupDeadband = 0;
KepGroup.UpdateRate = 1000;
KepGroup.IsActive = true;
KepGroup.IsSubscribed = true;
}
private void RecurBrowse(OPCBrowser OPCBrowser)
{
OPCBrowser.ShowBranches();
OPCBrowser.ShowLeafs(true);
listBox1.Items.Clear();
foreach (object turn in OPCBrowser)
{
bool bl = turn.ToString().Contains("System") ;
if (bl == false)
{
if (!Regex.IsMatch(turn.ToString(), #"^(\w+\.\w+\.\w+)$"))
{
}
else
{
listBox1.Items.Add(turn.ToString());
}
}
}
}
private bool ConnectRemoteServer(string remoteServerIP, string remoteServerName)
{
try
{
KepServer.Connect(remoteServerName, remoteServerIP);
}
catch (Exception ex)
{
MessageBox.Show(""+ex);
return false;
}
return true;
}
// Write the TAG value when executed event
void KepGroup_AsyncWriteComplete(int TransactionID, int NumItems, ref Array ClientHandles, ref Array Errors)
{
lblState.Text = "";
for (int i = 1; i <= NumItems; i++)
{
lblState.Text += "Tran:" + TransactionID.ToString() + " CH:" + ClientHandles.GetValue(i).ToString() + "Error:" + Errors.GetValue(i).ToString();
}
}
void KepGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
{
for (int i = 1; i <= NumItems; i++)
{
if (Qualities.GetValue(i).ToString() == "192")
{
// add realtime value to texbox to display
txtTagValue.Text = ItemValues.GetValue(i).ToString();
txtQualities.Text = Qualities.GetValue(i).ToString();
txtTimeStamps.Text = TimeStamps.GetValue(i).ToString();
}
else
{
MessageBox.Show("disconnected to opc server");
txtQualities.Text = Qualities.GetValue(i).ToString();
txtTimeStamps.Text = TimeStamps.GetValue(i).ToString();
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (itmHandleClient != 0)
{
Array Errors;
OPCItem bItem = KepItems.GetOPCItem(itmHandleServer);
int[] temp = new int[2] { 0, bItem.ServerHandle };
Array serverHandle = (Array)temp;
KepItems.Remove(KepItems.Count, ref serverHandle, out Errors);
}
itmHandleClient = 1;
KepItem = KepItems.AddItem(listBox1.SelectedItem.ToString(), itmHandleClient);
itmHandleServer = KepItem.ServerHandle;
}
catch (Exception err)
{
itmHandleClient = 0;
txtTagValue.Text = "Error ox";
txtQualities.Text = "Error ox";
txtTimeStamps.Text = "Error ox";
MessageBox.Show("The reserved for system entry:" + err.Message, "message");
}
}
private void Form1_Load(object sender, EventArgs e)
{
//GetLocalServer();
KepServer = new OPCServer();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!opc_connected)
{
return;
}
if (KepGroup != null)
{
KepGroup.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange);
}
if (KepServer != null)
{
KepServer.Disconnect();
KepServer = null;
}
opc_connected = false;
}
private void btnSetGroupPro_Click(object sender, EventArgs e)
{
SetGroupProperty();
}
private void btnConnLocalServer_Click(object sender, EventArgs e)
{
try
{
if (!ConnectRemoteServer(txtRemoteServerIP.Text.Trim(), "KEPware.KEPServerEx.V5"))
{
return;
}
btnSetGroupPro.Enabled = true;
opc_connected = true;
GetServerInfo();
RecurBrowse(KepServer.CreateBrowser());
if (!CreateGroup())
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void btnWrite_Click(object sender, EventArgs e)
{
OPCItem bItem = KepItems.GetOPCItem(itmHandleServer);
int[] temp = new int[2] { 0, bItem.ServerHandle };
Array serverHandles = (Array)temp;
Object[] valueTemp = new Object[] { "", txtWriteTagValue.Text };
Array values = (Array)valueTemp;
Array Errors;
int cancelID;
KepGroup.AsyncWrite(1, ref serverHandles, ref values, out Errors, 2009, out cancelID);
GC.Collect();
}
}
}
Now I want to create some User Controls to display some tag values.What should I do?
This is a pretty big topic in itself, but I have implemented such a beast a few years back in C#, also using KepServerEx.
Without seeing your code it's a bit difficult for me to understand what you have done so far, but the general idea is that you want to handle the OPCGroup.DataChange event. From there you have to "dispatch" the changed value to the proper TextBox.
Of course, you have to setup your OPCServer, your OPCGroup(s) and so on.
I created a library for this, and it was some extensive work required, so I'm afraid it can't really be answered in one Q&A like here.
If you have a very specific question, please open another one and I'll try to answer more specifically.
Cheers

Categories