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;
using System.IO;
using System.Threading;
namespace wangxl{
public partial class Smart_meter : Form
{
public int begin_year;
public int begin_month;
public int begin_day;
public int finish_year;
public int finish_month;
public int finish_day;
string from_bs_2;
string from_EM;
double[,] power = new double[4, 23];
int chushihua = 0;
int chuqi_changshu = 0;
int n_1 = 0;
int n_2 = 0;
double[,] power_display_f = new double[4, 23];
string path = "C:\\Users\\Public\\data\\data_logging.txt";
string path_m = "C:\\Users\\Public\\data\\energy_monitoring.txt";
// string path = "C:\\energy_moniotring\\data_logging.txt";
public Smart_meter()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
String[] input = SerialPort.GetPortNames();
comboBox1.Items.AddRange(input);
comboBox16.Items.AddRange(input);
}
void button1(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataBits = Convert.ToInt32(comboBox3.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox4.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox5.Text);
serialPort1.Open();
progressBar1.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
progressBar1.Value = 0;
}
}
private void button3_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
string output;
output = textBox2.Text;
serialPort1.Write(output);
textBox2.Text = "";
from_bs_2 = "";
serialPort1.DiscardOutBuffer();
// serialPort1.DiscardOutBuffer();
}
}
void button7_Click(object sender, EventArgs e)
{
try
{
serialPort2.PortName = comboBox16.Text;
serialPort2.BaudRate = Convert.ToInt32(comboBox15.Text);
serialPort2.DataBits = Convert.ToInt32(comboBox13.Text);
serialPort2.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox14.Text);
serialPort2.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox12.Text);
serialPort2.Open();
progressBar2.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button8_Click(object sender, EventArgs e)
{
if (serialPort2.IsOpen)
{
serialPort2.Close();
progressBar2.Value = 0;
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_bs_2 += serialPort1.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata));
Thread.Sleep(1000);
}
private void serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_EM += serialPort2.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata_2));
Thread.Sleep(1000);
// textBox1.Text += "laishujule";
}
I want to design a program which can connect 2 or 3 Arduinos at same time. So, I created a serialPort 1, it works well, I can receive the data from serial 1, but when I use the same way to create serialPort 2, I find the serialPort doesn't work, it can be connected, but it can't get any data from Arduino. I found that the serialPort2_DataReceived function doesn't work, I had add the serialPort 2 into my program from tools. Can you help me?
In your code, you are not specifying the SerialDataReceivedEventHandler for each SerialPort. Try adding the lines in your code before opening the serial:
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort2.DataReceived += new SerialDataReceivedEventHandler(serialPort2_DataReceived);
void button1(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataBits = Convert.ToInt32(comboBox3.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox4.Text);
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox5.Text);
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort1.Open();
progressBar1.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void button7_Click(object sender, EventArgs e)
{
try
{
serialPort2.PortName = comboBox16.Text;
serialPort2.BaudRate = Convert.ToInt32(comboBox15.Text);
serialPort2.DataBits = Convert.ToInt32(comboBox13.Text);
serialPort2.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox14.Text);
serialPort2.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox12.Text);
serialPort2.DataReceived += new SerialDataReceivedEventHandler(serialPort2_DataReceived);
serialPort2.Open();
progressBar2.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Related
I want to connect to the wifi network opened from esp32 via c# program and view the data sent from esp32. I was doing this project before using arduino via serialport, but I need to do it with local wifi network and I couldn't find the necessary codes to connect to wifi network. Can you help me.
I made a small program using the BMP180 sensor. I show data in C# by transferring data via Arduino and C# program. In this program, I want to transfer data by using ESP32 and connecting to the wifi network (The ones shown in the picture are a program I made over serialport using arduino.
public partial class Form1 : Form
{
int line = 1;
int column = 1;
int lineNumber = 1;
public Form1()
{
InitializeComponent();
}
private string data;
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisY.Maximum = 1000;
chart1.ChartAreas[0].AxisY.Interval = 100;
chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
chart2.ChartAreas[0].AxisY.Minimum = 0;
chart2.ChartAreas[0].AxisY.Maximum = 100;
chart2.ChartAreas[0].AxisY.Interval = 10;
chart2.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
chart2.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
data = serialPort1.ReadLine();
this.Invoke(new EventHandler(displaydata));
}
private void displaydata(object sender, EventArgs e)
{
DateTime myDateValue = DateTime.Now;
textBox3.Text = myDateValue.ToString();
string[] value = data.Split(',');
textBox1.Text = value[0];
textBox2.Text = value[1];
string pressure = Convert.ToString(value[0]);
string temperature = Convert.ToString(value[1]);
this.chart1.Series[0].Points.AddXY(myDateValue.ToString("HH:mm:ss"), pressure); //zaman ve basınç değerini eksenlere ata
this.chart2.Series[0].Points.AddXY(myDateValue.ToString("HH:mm:ss"), temperature); //zaman ve sıcaklık değerini eksenlere ata
line = dataGridView1.Rows.Add();
dataGridView1.Rows[line].Cells[0].Value = lineNumber;
dataGridView1.Rows[line].Cells[1].Value = pressure;
dataGridView1.Rows[line].Cells[2].Value = temperature;
dataGridView1.Rows[line].Cells[3].Value = myDateValue.ToShortDateString();
dataGridView1.Rows[line].Cells[4].Value = myDateValue.ToLongTimeString();
line++;
lineNumber++;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = 9600;
serialPort1.Open();
button1.Enabled = false;
button2.Enabled=true;
label1.Text = "Connected.";
label1.ForeColor = Color.Green;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ("Error:"));
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
button1.Enabled = true;
button2.Enabled = false;
label1.Text = "Disconnected";
label1.ForeColor = Color.Red;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ("Error:"));
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Interval = 1000;
}
private void button3_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application uyg = new Microsoft.Office.Interop.Excel.Application();
uyg.Visible = true;
Microsoft.Office.Interop.Excel.Workbook kitap = uyg.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)kitap.Sheets[1];
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[1, i + 1];
myRange.Value2 = dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[j + 2, i + 1];
myRange.Value2 = dataGridView1[i, j].Value;
}
}
}
}
}
I think the best option is to use TCP/IP socket connection.
For the ESP32 there are some libraries like:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/lwip.html
And from C#:
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/using-tcp-services
I am taking serial data from a distance sensor through Arduino to Visual Studio and I have another machine that is controlled by another controller.
Return values from serial data received to another function.
My question is: how to return the values from the function?
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
to a while loop inside the function
private void btnMove_Click(object sender, EventArgs e)
My code is as follows:
using System;
using System.Windows.Forms;
using PokeysLibSR;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace Melexis
{
public partial class Form1 : Form
{
PokeysLib pokeys;
public Form1()
{
InitializeComponent();
serialPort1.BaudRate = 9600;
serialPort1.PortName = "COM3";
}
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Open();
}
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string line = serialPort1.ReadLine();
string yourPortStringFormatted = Regex.Replace(line, #"\t|\n|\r", "");
string yourPortStringFormatted1 = yourPortStringFormatted.Trim();
double portNum = Double.Parse(yourPortStringFormatted1);
string line1 = Convert.ToString(portNum / 100);
this.BeginInvoke(new LineReceivedEvent(LineReceived), line1);
}
catch { }
finally
{
GC.Collect();
}
}
private delegate void LineReceivedEvent(string line1);
private void LineReceived(string line1)
{
textBox1.Text = line1;
}
private void btnMove_Click(object sender, EventArgs e)
{
double[] coords = new double[4] { 0, 0, 0, 0 };
byte axisMask = 0;
if (double.TryParse(tbX.Text, out coords[0])) axisMask = (byte)(axisMask + 1);
if (double.TryParse(tbY.Text, out coords[1])) axisMask = (byte)(axisMask + 2);
if (double.TryParse(tbZ.Text, out coords[2])) axisMask = (byte)(axisMask + 4);
while (true)
{
pokeys.StartMove(false, rbAbsolut.Checked, 1, coords);
Thread.Sleep(5000);
coords[0] = -coords[0];
pokeys.StartMove(false, rbAbsolut.Checked, 4, coords);
coords[2] = coords[2] + 10;
Thread.Sleep(5000);
}
}
}
The following code reads port data and writes the data into a textbox with timestemp once it differs from the previous one. Afterwards I can save the data to a textfile.
Instead of writing it into a textbox and then save it to text file per button, I would like it to auto append to the text file every x seconds (lets say 10). By reading through other questions I got some ideas but was not really able to execute them.
Anyone can help?
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
private string in_data_old = "";
public Form1()
{
InitializeComponent();
}
private void start_btn_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 9600;
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 ex) {
MessageBox.Show(ex.Message, "Error");
}
}
void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
if (in_data != in_data_old)
{
this.Invoke(new EventHandler(displaydata_event));
}
in_data_old = in_data;
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Year+ "." +datetime.Month+ "." + datetime.Day + " " + datetime.Hour+ ":" +datetime.Minute+ ":" +datetime.Second;
data_tb.AppendText(time + "\t\t\t\t\t" + in_data+"\n");
}
private void stop_btn_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void save_btn_Click(object sender, EventArgs e)
{
try
{
string pathfile = #"C:\Users\xy\Desktop\DATA\";
string filename = "light_data.txt";
System.IO.File.AppendAllText(pathfile + filename, data_tb.Text);
MessageBox.Show("Data has been saved to "+pathfile, "Save File");
}
catch(Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
}
Add a Timer , you can find it on the toolbox and you can set it's interval for any timer you would like and add your btn click functionality there example :
private void timer1_Tick(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 9600;
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 ex) {
MessageBox.Show(ex.Message, "Error");
}
}
i want to save received data to .txt file when click "read" button. please help me
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;
namespace Serial
{
public partial class Form1 : Form
{
static SerialPort serialPort1;
public Form1()
{
InitializeComponent();
getAvailablePorts();
serialPort1 = new SerialPort();
}
void getAvailablePorts()
{
string[] Ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(Ports);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
textBox2.Text = "Please select port Setting";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
progressBar1.Value = 100;
button1.Enabled = true;
button2.Enabled = true;
textBox1.Enabled = true;
button3.Enabled = false;
button4.Enabled = true;
}
}
catch (UnauthorizedAccessException)
{
textBox2.Text = "anauthorized Acess";
}
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
button1.Enabled = false;
button2.Enabled = false;
button4.Enabled = false;
button3.Enabled = true;
textBox1.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
try
{
textBox2.Text = serialPort1.ReadLine();
}
catch(TimeoutException)
{
textBox2.Text = "Timeout Exception";
}
}
}
}
Simply use File.WriteAllText.Sample :
File.WriteAllText("path here","text here")
Just use StreamWriter
using(StreamWriter sw = new StreamWriter("filename.txt")){
sw.WriteLine(textbox.Text);
sw.Close();
}
I wrote a C# code that will send functions ( 1-9) to a micro controller and the controller will send back data to my computer via RS232(SERIAL PORT). My only problem is i would like to automate it by sending the functions (1-9) and receiving them from the controller automatically. By doing this, I used a for loop but it is only displaying the data received from the last function sent, function 9 . However, i would like it to display all data receive. How can I display all the data received that the controller is sending back? Any suggestions?
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;
using System.Timers;
using System.IO;
using System.Net;
using System.Threading;
namespace SMCData
{
public partial class Form1 : Form
{
SerialPort _serialPort = new SerialPort();
public Form1()
{
InitializeComponent();
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataRecivedHandler);
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comport.Items.Add(s);
}
}
// settup connection
void setport()
{
//checking if Baud_Rate_txt is blank
string temp1 = Baud_Rate_txt.Text;
if (temp1 == "")
{
_serialPort.BaudRate = 9600;
}
else
{
_serialPort.BaudRate = int.Parse(Baud_Rate_txt.Text);
}
/* if (comport.SelectedIndex == -1)
{
ErrorBox.Text = " Need Com Port name";
return;
} */
_serialPort.PortName = comport.Text;//comport.SelectedItem.ToString();
_serialPort.DataBits = 8;
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.RtsEnable = true;
_serialPort.DtrEnable = true;
switch (HandshakeCB.Text)
{
case "None":
_serialPort.Handshake = Handshake.None;
break;
case "XOnXOff":
_serialPort.DtrEnable = true;
_serialPort.Handshake = Handshake.XOnXOff;
break;
}
switch (Parity_CB.Text)
{
case "None":
_serialPort.Parity = Parity.None;
break;
case "Even":
_serialPort.Parity = Parity.Even;
break;
case "Odd":
_serialPort.Parity = Parity.Odd;
break;
}
// Looks for user input on the desired Stop Bits of Application
switch (StopBitsCB.Text)
{
case "1":
_serialPort.StopBits = StopBits.One;
break;
case "2":
_serialPort.StopBits = StopBits.Two;
break;
case "None":
_serialPort.StopBits = StopBits.None;
break;
}
try
{
_serialPort.Open();
}
catch (UnauthorizedAccessException ex)
{
errorbox.Text = ex.Message + System.Environment.NewLine;
}
}
//Data Receive Fucntion
private void DataRecivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
int temp2;
string data;
int temp =sp.BytesToRead;
byte[] array = new byte[temp];
temp2 = sp.Read(array, 0, temp);
if (this.DataRecived.InvokeRequired)
{
DataRecived.BeginInvoke((Action)(() =>
{
data = Encoding.Default.GetString(array) ;
processdata(data);
DataRecived.Text = DataRecived.Text + data + System.Environment.NewLine;
}));
}
}
private void Dispose(RichTextBox dataRecived)
{
throw new NotImplementedException();
}
private void sendBLN_Click(object sender, EventArgs e)
{
// byte[] array_out = Encoding.ASCII.GetBytes(SendTXT.Text);
//_serialPort.Write(array_out, 0, array_out.Length);
// byte[] array_out2 = new byte[1];
//array_out2[0] = 0xD; //Encoding.ASCII.GetBytes("\r");
// byte[] array_out3 = { 141 };
//_serialPort.Write(array_out2, 0, array_out2.Length);
// _serialPort.Write(array_out3, 0, array_out3.Length);
//automate the process by sending 1,2,3,etc
for (int i = 0; i < 10; i++)
{
string c = Convert.ToString(i);
byte[] array_out = Encoding.ASCII.GetBytes(c); //convert i to the right variable type;
_serialPort.Write(array_out, 0, array_out.Length);
byte[] array_out2 = new byte[1];
array_out2[0] = 0xD;
_serialPort.Write(array_out2, 0, array_out2.Length);
//print what you receive
}
}
private void Refresh_btn_Click(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comport.Items.Remove(s);
}
foreach (string s in SerialPort.GetPortNames())
{
comport.Items.Add(s);
}
}
private void Connectbtn_Click(object sender, EventArgs e)
{
try
{
if (!_serialPort.IsOpen)
errorbox.Text = errorbox.Text + "Connected..." + System.Environment.NewLine;
setport();
}
catch (Exception ex )
{
errorbox.Text = errorbox.Text + ex.Message + System.Environment.NewLine;
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
_serialPort.Close();
errorbox.Text = " Disconnect";
}
private void button2_Click(object sender, EventArgs e)
{
DataRecived.Text = " ";
errorbox.Text = " ";
}
private void DataRecived_TextChanged(object sender, EventArgs e)
{
}
void processdata(string data)
{
if (data.Contains("No Action") == true)
{
return;
}
else if (data.Contains("Array Volt") == true)
{
string[] temp = data.Split('=');
temp[1].Trim('\r');
}
}
private void button3_Click(object sender, EventArgs e)
{
byte[] array_out2 = new byte[1];
array_out2 = Encoding.ASCII.GetBytes("\r");
_serialPort.Write(array_out2, 0, array_out2.Length);
}
private void SendTXT_TextChanged(object sender, EventArgs e)
{
}
private void comport_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}