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();
}
Related
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);
}
}
I'm new to c#,i have been trying to change the color of form when I receive a value from a serial, I am using event handling method to receive data from serial monitor, yet the output is not coming. I have here by attached the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SerialPort port;
public delegate void UpdateGUI(string str);
public void DisplayReceivedData(string str)
{
string ja = "12";
//listBox1.Items.Add("received");
// if(StringComparison
listBox1.Items.Add(str);
textBox1.Text = ja;
int test = String.Compare(str, ja);
textBox1.Text =Convert.ToString(str);
if (test == 0)
{
ActiveForm.BackColor = System.Drawing.Color.DarkBlue;
}
else
{
ActiveForm.BackColor = System.Drawing.Color.White;
}
}
public void Datareceived(object sender, SerialDataReceivedEventArgs arg)
{
SerialPort sp = (SerialPort)sender;
string str = sp.ReadExisting();
Invoke(new UpdateGUI(DisplayReceivedData),str);
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
port = new SerialPort("COM10");
port.BaudRate = 9600;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.DataBits = 8;
port.Handshake = Handshake.None;
port.RtsEnable = true;
port.DataReceived += new SerialDataReceivedEventHandler(Datareceived);
port.Open();
}
private void button1_Click(object sender, EventArgs e)
{
ActiveForm.BackColor = System.Drawing.Color.DarkBlue;
}
private void button2_Click(object sender, EventArgs e)
{
ActiveForm.BackColor = System.Drawing.Color.White;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
As you say in your comments the problem is with the end-of-line chars.
You could simply trim them off using:
str.TrimEnd('\r', '\n');
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)
{
}
}
}
I want to create a form having button,textbox,serialport in Visual c# 2010. My objective is when a button is pressed the data coming from the serial port has to displayed in textbox. I copied the following code from a tutorial. The textbox is not showing anything. Here's is the code
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;
namespace ser1
{
public partial class Form1 : Form
{
private string RxString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// If the port is closed, don't try to send a character.
if (!serialPort1.IsOpen) return;
// If the port is Open, declare a char[] array with one element.
char[] buff = new char[1];
// Load element 0 with the key character.
buff[0] = e.KeyChar;
// Send the one character buffer.
serialPort1.Write(buff, 0, 1);
// Set the KeyPress event as handled so the character won't
// display locally. If you want it to display, omit the next line.
e.Handled = true;
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.Text=RxString.Trim();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}'
i am develop C# windows app.it's read weight from weigh bridge machine to serial port.but,my code doesn't work.i am trying many examples download from internet doesn't work.my code is below:
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.IO.Ports;
using System.IO;
namespace SerialPortTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String a = "";
private void button1_Click(object sender, EventArgs e)
{
serialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
if (serialPort1.IsOpen == false)
{
serialPort1.Open();
}
timer1.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
a = a + serialPort1.ReadExisting();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (a.Length != 0)
{
textBox1.AppendText(a);
a = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
button2.Enabled = false;
button1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
button1.Enabled = false;
button2.Enabled = true;
}
else
{
button1.Enabled = true;
button2.Enabled = false;
}
}
}
}
What i am wrong in my code can any one help me any working code.
Thanks in Advance.
You didn't register the serialPort1_DataReceived for serialPort1.
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
You maybe need to extract the binary data from the stream instead of reading the data as a string?
Here's an example of some code that could be inside the DataReceived event handler...
int nb = serialPort1.BytesToRead;
if (nb > 0)
{
byte[] buffer = new byte[nb];
serialPort1.Read(buffer, 0, nb);
// Depending on the structure of the binary data ...
int number1 = BitConverter.ToInt32(buffer, 0);
int number2 = BitConverter.ToInt32(buffer, 4);
// etc.
}