C# Received data from Arduino - c#

I'm building a weather station and I have a little problem. How do the received data to run at a textbox or rich box? The application connects Arduino, but does not operate to read data.
Thank you,
[enter image description here][1]
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string InputData = String.Empty;
delegate void SetTextCallback(string text);
public Form1()
{
InitializeComponent();
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
public void guzikpolacz_Click(object sender, EventArgs e)
{
serialPort1.PortName = comboBox1.Text; // Ustawiamy numer Portu COM
// Ustawiamy wartość baudrate portu
//Inne ustawienia zdefiniowane na stałe
serialPort1.Parity = Parity.None; // bez parzystości
serialPort1.StopBits = StopBits.One; // jeden bit stopu
serialPort1.DataBits = 8; // osiem bitów danych
serialPort1.Open();
polestatusu.Text = "Port Otwarty";
polestatusu = SerialPort;
panel1.BackColor = Color.Lime;
guzikpolacz.Enabled = false; //blokujemy przycisk Połącz
guzikrozlacz.Enabled = true;
}
private void guzikrozlacz_Click(object sender, EventArgs e)
{
serialPort1.Close(); //Zamykamy SerialPort
panel1.BackColor = Color.Red;
polestatusu.Text = "Port Zamknięty";
guzikpolacz.Enabled = true; //aktywujemy przycisk Połącz
guzikrozlacz.Enabled = false; // deaktywujemy przycisk Rozłącz
}
private delegate void UpdateUiTextDelegate(string text);
}
}

Thank you very much, but unfortunately it did not work :( The application connects to the serialport but nothing happens. The connection to the Arduino program Putty works.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string InputData = String.Empty;
delegate void SetTextCallback(string text);
public Form1()
{
InitializeComponent();
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
;}
public void guzikpolacz_Click(object sender, EventArgs e)
{
serialPort1.PortName = comboBox1.Text; // Ustawiamy numer Portu COM
// Ustawiamy wartość baudrate portu
//Inne ustawienia zdefiniowane na stałe
serialPort1.Parity = Parity.None; // bez parzystości
serialPort1.StopBits = StopBits.One; // jeden bit stopu
serialPort1.DataBits = 8; // osiem bitów danych
serialPort1.Open();
polestatusu.Text = "Port Otwarty";
panel1.BackColor = Color.Lime;
guzikpolacz.Enabled = false; //blokujemy przycisk Połącz
guzikrozlacz.Enabled = true;
}
private void guzikrozlacz_Click(object sender, EventArgs e)
{
serialPort1.Close(); //Zamykamy SerialPort
panel1.BackColor = Color.Red;
polestatusu.Text = "Port Zamknięty";
guzikpolacz.Enabled = true; //aktywujemy przycisk Połącz
guzikrozlacz.Enabled = false; // deaktywujemy przycisk Rozłącz
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => serialPort1_DataReceived(sender, e)));
}
else
{
var sp = sender as SerialPort;
//this assumes you want the data from the arduino as text.
// you may need to decode it here.
textBox1.Text = sp.ReadExisting();
}
}
private delegate void UpdateUiTextDelegate(string text);
public Delegate myDelegate { get; set; }
}
}
enter image description here

try adding this event handler to your serial port
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => serialPort1_DataReceived(sender, e)));
}
else
{
var sp = sender as SerialPort;
//this assumes you want the data from the arduino as text.
// you may need to decode it here.
polestatusu.Text = sp.ReadExisting();
}
}

Related

Read string from textbox

I have the below code in WPF application.
It reads the strings from the serial port and displays in textbox.
I want to execute an operation according to the serial input.
This I'm thinking to do either by reading the string variable (RData) or by reading the textbox.text.
I've tried with if statements in the functions but it doesn't work. Please help.
public partial class MainWindow : Window
{
SerialPort serial = new SerialPort();
string RData;
public MainWindow()
{
InitializeComponent();
getPorts();
}
void getPorts()
{
String[] ports = SerialPort.GetPortNames();
comboBoxPorts.ItemsSource = ports;
}
private void buttonConnect_Click(object sender, RoutedEventArgs e)
{
serial.PortName = comboBoxPorts.Text;
serial.BaudRate = 9600;
serial.DataBits = 8;
serial.Handshake = System.IO.Ports.Handshake.None;
serial.StopBits = StopBits.One;
serial.ReadTimeout = -1;
serial.WriteTimeout = -1;
serial.Open();
if (serial.IsOpen)
{
buttonConnect.IsEnabled = false;
labelConState.Content = "Connected";
labelConState.Foreground = System.Windows.Media.Brushes.Green;
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
}
}
private delegate void UpdateUiTextDelegate(string text);
private void Recieve
(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RData = serial.ReadExisting();
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), RData);
}
private void WriteData(string text)
{
textBoxPrompt.Text += text;
}
}
You should set parity property of SerialPort.

Serial-port Datareceive

I'm having a problem with serial port data. I have designed a form where I have used a datareceived handler event and the whole of data needs to be printed in the RichTextBox placed in the form. The problem is I'm only receiving the last bits of data on the RichTextBox, while the MessageBox that is provided with the code runs the whole of data in part. Please suggest where I'm going wrong.Thanks in advance.
public partial class Form1 : Form
{
char po='\0';
string indata,pi;
string[] buffer;
public Form1()
{
InitializeComponent();
System.ComponentModel.IContainer components = new System.ComponentModel.Container();
serialPort1 = new System.IO.Ports.SerialPort(components);
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort1.Open();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
po = Convert.ToChar(serialPort1.BytesToRead);
indata = sp.ReadExisting();
//return (indata);
//for (int p = 0; p <= 256; p++) ;
//MessageBox.Show(buffer[0]);
//MessageBox.Show(indata);
//richTextBox1.Text += indata;
//richTextBox1.Text = indata;
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.WordWrap = true;
richTextBox1.Text = indata;
}
}
It looks like you should be appending the data each time data is received over the serial port, so perhaps you should change
indata = sp.ReadExisting();
to:
indata += sp.ReadExisting();
To hold all of the contents of the Serial Data, including historical data that was previously sent.
Hope this helps!
Trying This Code....
private string StrValue = "";
private void Port_DataReceived(object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)
{
double DouRWeight = 0;
try
{
DouRWeight = Val.ToDouble(Port.ReadLine());
if (DouRWeight != 0)
{
this.Invoke((System.Windows.Forms.MethodInvoker)delegate()
{
StrValue = Val.Format(DouRWeight.ToString(), "####0.000");
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.WordWrap = true;
richTextBox1.Text = StrValue ;
}
It's Completely Worked...

C# serial connection not working

I am trying to send ASCII caracters to a VideoJet Excel 170i printer, via a RS-232 cable (Serial)
When I am using the test program, i have no problem getting a response from the printer, i can change the status of the printer.
This is the code i've made
public partial class Form1 : Form
{
private SerialPort port = new SerialPort("COM1");
private delegate void SetTextDeleg(string data);
public Form1()
{
InitializeComponent();
}
private void addtoText(string text)
{
this.richTextBox1.Text = this.richTextBox1.Text + "\n" + text;
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
port.BaudRate = 9600;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.DataBits = 8;
port.Handshake = Handshake.None;
port.ReadTimeout = 2000;
port.WriteTimeout = 500;
port.DtrEnable = true;
port.RtsEnable = true;
port.Open();
port.DataReceived += DataReceivedHandler;
addtoText("Port is ready");
}
catch (Exception ex)
{
//Console.WriteLine("Error opening my port: {0}", ex.Message);
addtoText("Error opening my port: {0}" + ex.Message);
}
}
public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
System.Threading.Thread.Sleep(500);
string indata = sp.ReadExisting();
this.BeginInvoke(new SetTextDeleg(DisplayToUI), new object[] { indata });
}
private void DisplayToUI(string displayData)
{
addtoText(displayData);
}
private void button1_Click(object sender, EventArgs e)
{
port.Write(tbxAscii.Text);
}
private void Form1_Leave(object sender, EventArgs e)
{
port.Close();
}
}
I need to sent ASCII caracters to the printer, like
[1B][01][09]
To turn the printer to Print Mode.
The printer is supposed to respond, i get no response, and the printer doesn't change its status.
I have a program made to test the serial connection made by the printer, and i can see that all the settings are OK (Baud rate, Parity... port), and indeed on port COM1.
So i think that my port.write is not sending any info to the printer... or maybe i'm sending corrup info and i'm not reading the response of the printer.
are you sure that you want to send [1B][01][09] or do you want to send that byte sequence 0x1b,0x01,0x09
just to see if this works, send the following in you click handler
private void button1_Click(object sender, EventArgs e)
{
var bytes = new byte[] { 0x1b, 0x01, 0x09 };
port.Write(bytes, 0, bytes.Length);
port.Flush(); // make sure everything is written
}
reading has to be changed, to handle bytes
SerialPort sp = (SerialPort)sender;
System.Threading.Thread.Sleep(500);
var available = sp.BytesToRead; // check how many bytes are ready to be read
if (available < 1)
return;
var buffer = new byte[available];
sp.Read(buffer, 0, available);
var indata = BitConverter.ToString(buffer); // convert bytes to a hex representation
this.BeginInvoke(new SetTextDeleg(DisplayToUI), new object[] { indata });

Reading from SerialPort; Error when I close and then open application

I created application for reading from Serial Port and it works just fine. But the problem occure when I close the application and run it again. Suddenly reading from Serial port stops working. I have to disconnect and connect USB to fix that.
This is my code:
namespace Serial
{
public partial class Main : Form
{
SerialPort mainSerialPort = new SerialPort();
public Main()
{
InitializeComponent();
}
delegate void SetTextCallback(string text);
private void buttonOpen_Click(object sender, EventArgs e)
{
mainSerialPort.PortName = "COM" + numericPort.Value.ToString();
mainSerialPort.BaudRate = 115200;
mainSerialPort.Parity = Parity.None;
mainSerialPort.StopBits = StopBits.One;
mainSerialPort.DataBits = 8;
mainSerialPort.Handshake = Handshake.None;
mainSerialPort.DataReceived += DataReceived_Read;
try{
mainSerialPort.Open();
}catch (Exception ex){
labelStatus.Text = ex.GetType().ToString();
}
if (mainSerialPort.IsOpen == true){
numericPort.BackColor = Color.Green;
labelStatus.Text = "Port je otevřen!";
}else{
numericPort.BackColor = Color.Red;
}
}
private void DataReceived_Read(object sender, SerialDataReceivedEventArgs e)
{
SerialPort mySerial = (SerialPort)sender;
if (this.InvokeRequired){
listBoxRead.Invoke(new MethodInvoker(delegate {
listBoxRead.Items.Add(mySerial.ReadExisting());
listBoxRead.SelectedIndex = listBoxRead.Items.Count - 1;
}));
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
mainSerialPort.DataReceived -= DataReceived_Read;
mainSerialPort.Close();
}
}
}
USB and serial ports are unmanaged ressources. You have to dispose it!. A simple "Close" on FormClosed will not do the same.
I think it has to do with some resources not properly freed up. Try calling Dispose method
mainSerialPort.Close();
mainSerialPort.Dispose();

Error reading serial port with C #

I have a system that makes a loop on all serial ports and send a command 'at' for them.
These ports return 'ok' in Putty, but in the C# the MessageBox is empty.
Why is this happening?
Putty: http://i.imgur.com/AZY7aRY.png /
C#: http://i.imgur.com/wgGyT2x.png
public partial class Form1 : Form
{
List<SerialPort> serialPort = new List<SerialPort>();
private delegate void SetTextDeleg(string text);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var portNames = SerialPort.GetPortNames();
foreach (var port in portNames)
{
SerialPort sp;
sp = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);
sp.Handshake = Handshake.None;
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.ReadTimeout = 500;
sp.WriteTimeout = 500;
serialPort.Add(sp);
listPorts.Items.Add(port);
}
}
private void listPorts_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
foreach (var sp in serialPort)
{
// Open port
try
{
if (!sp.IsOpen)
sp.Open();
sp.Write("at\r\n");
}
catch (Exception ex)
{
MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
SerialPort sp = (SerialPort)sender;
string data = sp.ReadLine();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}
private void si_DataReceived(string data)
{
String retorno = data.Trim();
MessageBox.Show(data);
}
}
Your modem response something like this: \n\rOK\n\r you should read all stream in the buffer or you should read 3 time the serial port buffer with ReadLine() method.

Categories