Read string from textbox - c#

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.

Related

Scoreboard data transfer Serial Port c#

There's some outdated software that's used to control the scoreboard at my local athletics track and I've been tasked with creating a new advanced one. However, I cannot seem to get the scoreboard to do what I ask it to do.
I've installed the original software to the my laptop and it works fine, however, when I run my test software that sends data to the board through the serial port, it isn't doing what I want.
I have the "Scoreboard Data Protocol" supplied by the manufacturer and I've been following this. I will supply the code to my test program that I've been using to see if I can get it to work and I will also supply the Data Protocol.
In the text box, I type 010D0201SPAIN and 003C630 and send it to the board and this doesn't work.
public partial class Form1 : Form
{
private SerialPort m_port;
public Form1()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames()); // Adds ports to combobox
m_port = new SerialPort();
m_port.BaudRate = 9600;
m_port.DataBits = 8;
m_port.Parity = Parity.Even;
m_port.StopBits = StopBits.One;
//m_port.Handshake = Handshake.None;
m_port.Encoding = new ASCIIEncoding();
m_port.RtsEnable = true;
m_port.DtrEnable = true;
m_port.ReceivedBytesThreshold = 1;
m_port.DataReceived += DataReceivedEvent;
}
private void button1_Click(object sender, EventArgs e)
{
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_sendbutton.Enabled = true;
button2.Enabled = true;
}catch(UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void m_sendbutton_Click(object sender, EventArgs e)
{
m_port.Write(m_textbox.Text);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
label1.Text += m_port.ReadLine();
}
private void button2_Click(object sender, EventArgs e)
{
byte[] r_bytes = Encoding.ASCII.GetBytes(m_textbox.Text);
m_port.Write(r_bytes, 0, r_bytes.Length);
}
}
}
Scoreboard Data Protocol
Code: https://hastebin.com/epirobuduv.cs
Here's how to add STX and ETX around your message, in a byte array.
private void button2_Click(object sender, EventArgs e)
{
var msg = Encoding.ASCII.GetBytes(m_textbox.Text).ToList();
msg.Insert(0, 0x02); // STX at the start
msg.Add(0x03); // ETX at the end
m_port.Write(msg.ToArray(), 0, msg.Count);
}

making call and receice data from gsm modem in C#

i want to call a service number like that *21*2# with AT Command using gsm modem but also i want to receive the answer ( because it is a service number ) in RichtextBox , hox to do that ? :(
private void button1_Click(object sender, EventArgs e)
{
SerialPort po = new SerialPort();
po.PortName = "COM3";
po.BaudRate = int.Parse( "9600");
po.DataBits = Convert.ToInt32("8");
po.Parity = Parity.None;
po.StopBits = StopBits.One;
po.ReadTimeout = int.Parse("300");
po.WriteTimeout = int.Parse("300");
po.Encoding = Encoding.GetEncoding("iso-8859-1");
po.Open();
po.DtrEnable = true;
po.RtsEnable = true;
po.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
po.Write("ATD9030665834;");
}
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (e.EventType == SerialData.Chars)
{
}
}

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# Received data from Arduino

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();
}
}

SerialPort.BaseStream.BeginWrite & BeginRead questions

I'm having some issues trying to figure out Async communication on a serialport object and was hoping to get some help. I'm still learning Async stuff so be gentle:)
I basically need to make sure that the buffer isn't full prior to writing to the serial port and also all data has been read before any more data gets written to avoid packet collision. Unfortunately the microcontroller that I am writing to does not have any handshaking or CTSEnabled so I have to mimic it in code.
public partial class Form2 : Form
{
System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
System.Timers.Timer tmrPolling = new System.Timers.Timer(200);
static byte [] inputPacket = new byte[2] { (byte)255, (byte)0 }; // Byte to send to SerialPort when input polling timer is activated.
AsyncCallback callback;
IAsyncResult result;
Form2()
{
InitializeComponent();
port.PortName = "COM9";
port.BaudRate = 38400;
port.DataBits = 8;
port.StopBits = System.IO.Ports.StopBits.One;
port.Parity = System.IO.Ports.Parity.None;
port.ReadTimeout = 1;
port.ReceivedBytesThreshold = 5;
port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
callback = new AsyncCallback(ReadComplete);
port.ReadBufferSize = (byte)60;
port.WriteBufferSize = (byte)60;
port.Open();
tmrPolling.Elapsed += new System.Timers.ElapsedEventHandler(tmrPolling_Elapsed);
}
void WritePacket(byte[] packet)
{
result = port.BaseStream.BeginWrite(packet, 0, packet.Count(), callback, port); // writes the input packet to the SerialPort - needed to read the IO values
}
void ReadComplete(IAsyncResult result)
{
}
void tmrPolling_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
WritePacket(inputPacket); // writes the input packet to the SerialPort - needed to read the IO values
}
void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
port.BaseStream.EndWrite(result);
// Reads the data coming in from the serial port and calls the thread safe delegate to update the values on the form.
byte [] received = new byte[port.BytesToRead];
result = port.BaseStream.BeginRead(received, 0, received.Count(), callback, port);
port.BaseStream.EndRead(result);
}
private void UpdateValues()
{
byte[] b = new byte[] { (byte)255, (byte)6, (byte)hsbPan.Value, (byte)vsbTilt.Value, (byte)0,
(byte)0, (byte)0, (byte)0, (byte)13, (byte)10 };
WritePacket(b);
}
private void chkEnablePolling_CheckedChanged(object sender, EventArgs e)
{
tmrPolling.Enabled = chkEnablePolling.Checked;
test.Enabled = chkEnablePolling.Checked;
vsbInputInterval.Enabled = chkEnablePolling.Checked;
vsbInputInterval.Value = Convert.ToInt32(tmrPolling.Interval);
txtInputInterval.Enabled = chkEnablePolling.Checked;
txtInputInterval.Text = ((float)tmrPolling.Interval / ( float)1000).ToString() + " sec";
}
private void vsbInputInterval_Scroll(object sender, ScrollEventArgs e)
{
// adjusts the tick frequency of the Timer for input polling.
txtInputInterval.Text = ((float)tmrPolling.Interval / (float)1000).ToString() + " sec";
tmrPolling.Interval = vsbInputInterval.Value;
}
private void vsbTilt_Scroll(object sender, ScrollEventArgs e)
{
UpdateValues();
}
private void hsbPan_Scroll(object sender, ScrollEventArgs e)
{
UpdateValues();
}
}

Categories