I want to make a GUI for my device to show the value of each sensor. My device send data with this format
:1*895*123;
:1*987*145;
* is use to separate data from sensors
; is for the end of data
: is for start of data in next loop
I have variables dot, Rx1 and Ry2 to storing the data and show it on label, but looks like my program didn't works.. here's my 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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
string TestText, Rx1, Ry1, dot;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM7";
serialPort1.BaudRate = 2400;
serialPort1.Open();
if (serialPort1.IsOpen)
{
button1.Enabled = false;
button2.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
button1.Enabled = true;
button2.Enabled = false;
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
TestText = serialPort1.ReadExisting();
string[] nameArray = TestText.Split ('*');
foreach (string name in nameArray)
{
dot = nameArray[0];
Rx1 = nameArray[1];
Ry1 = nameArray[2];
}
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label3.Text = dot;
posY.Text = Ry1;
posX.Text = Rx1;
}
//this.Invoke(new EventHandler(DisplayText));
}
}
I'm still new in c# and not so good with it.. so i need help. thanks before.
Are you sure that you're getting complete packets in the data received method? if not you'll need to buffer them up to be sure it's working properly.
You could try something like this.
// A buffer for the incoming data strings.
string buffer = string.Empty;
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// buffer up the latest data.
buffer += serialPort1.ReadExisting();;
// there could be more than one packet in the data so we have to keep looping.
bool done = false;
while (!done)
{
// check for a complete message.
int start = buffer.IndexOf(":");
int end = buffer.IndexOf(";");
if (start > -1 && end > -1 && start < end)
{
// A complete packet is in the buffer.
string packet = buffer.Substring(start + 1, (end - start) - 1);
// remove the packet from the buffer.
buffer = buffer.Remove(start, (end - start) + 1);
// split the packet up in to it's parameters.
string[] parameters = packet.Split('*');
rx1 = parameters[0];
ry1 = parameters[1];
dot = parameters[2];
}
else
done = true;
}
If you getting just one chunk of data after reading. For example :1*895*123;
TestText = serialPort1.ReadExisting();//:1*895*123;
string[] nameArray = TestText.Split(new []{":", "*", ";"}, StringSplitOptions.RemoveEmptyEntries);
label3.Text = nameArray[0];//1
posY.Text = nameArray[1]; //895
posX.Text = nameArray[2]; //123
and if you receive :1*895*123; :1*987*145;
var chunks = s.Split(new [] { ":", ";", " "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var chunk in chunks)
{
string[] data = chunk.Split(new [] { "*" }, StringSplitOptions.RemoveEmptyEntries);
label3.Text = data[0];
posY.Text = data[1];
posX.Text = data[2];
}
But then in labels you just see latest chunk data, so you need store a list of your data. For example you can create class:
class chunkData
{
public string dot;
public string posX;
public string posY;
}
and use it like this:
private List<chunkData> dataList = new List<chunkData>();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
TestText = serialPort1.ReadExisting();
var chunks = TestText.Split(new [] { ":", ";", " "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var chunk in chunks)
{
string[] data = chunk.Split(new [] { "*" }, StringSplitOptions.RemoveEmptyEntries);
dataList.Add(new chunkData(){dot=data[0], posX=data[1], posY=data[2]})
}
//display dataList to DataGridView or other control
}
EDIT: here is what you can do if you receiving data symbol by symbol:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string temp = serialPort1.ReadExisting();
if(temp == ";") //OK we have end of data lets process it
splitAndDisplay();
else
TestText += temp;
}
private void splitAndDisplay()
{
string[] nameArray = TestText.Split(new []{":", "*"}, StringSplitOptions.RemoveEmptyEntries);
this.Invoke(new Action(() =>
{
label3.Text = nameArray[0];
posY.Text = nameArray[1];
posX.Text = nameArray[2];
}));
TestText = "";
}
Related
I've a gui and I get temperature data from a Uc. I can see the data in the rich text box and save to a text file. But I cannot understand how to sort the saved data in the column format. Right now it is a long row of data. Please advice.
Would it be advisable to replace the rich text box to a normal text box?
I've a button to save data to the text file (button3_Click);
using System;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace Serial_receive
{
public partial class Form1 : Form
{
// All members variables should be placed here
// make it more readable, hopefully!
string t;
SerialPort sp;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
// User can already search for ports when the constructor of the FORM1 is calling
// And let the user search ports again with a click
// Searching for ports function
SearchPorts();
}
//search button
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
SearchPorts();
}
void SearchPorts()
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Catch exception if it will be thrown so the user will see it in a message box
OpenCloseSerial();
}
void OpenCloseSerial()
{
try
{
if (sp == null || sp.IsOpen == false)
{
t = comboBox1.Text.ToString();
sErial(t);
button2.Text = "Close Serial port"; // button text
}
else
{
sp.Close();
button2.Text = "Connect and wait for inputs"; // button text
}
}
catch (Exception err) // catching error message
{
MessageBox.Show(err.Message); // displaying error message
}
}
void sErial(string Port_name)
{
try
{
sp = new SerialPort(Port_name, 115200, Parity.None, 8, StopBits.One); // serial port parameters
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
sp.Open();
}
catch (Exception err)
{
throw (new SystemException(err.Message));
}
}
//
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
// This below line is not need , sp is global (belongs to the class!!)
//SerialPort sp = (SerialPort)sender;
if (e.EventType == SerialData.Chars)
{
if (sp.IsOpen)
{
string w = sp.ReadExisting();
if (w != String.Empty)
{
Invoke(new Action(() => richTextBox1.AppendText(w)));
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (sp == null || sp.IsOpen == false)
{
OpenCloseSerial();
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Serial Channel to FRDM-KW40Z";
}
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\Users\varman\Documents\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string temperature = "Temperature";
string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
sorted = sorted.Substring(sorted.IndexOf(temperature));
File.WriteAllText(saveFileDialog1.FileName, sorted);
Text += "\r\n";
richTextBox1.Text = saveFileDialog1.FileName;
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.ScrollBars = ScrollBars.Both;
}
}
}
I assume you want to sort it only in the output file because you didn't share the code that change richTextBox1.Text.
So you can add a new line for each temperature before writing to the file:
private void button3_Click(object sender, EventArgs e)
{
...
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string temperature = "Temperature";
string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
File.WriteAllText(saveFileDialog1.FileName, sorted);
Text += "\r\n";
richTextBox1.Text = saveFileDialog1.FileName;
}
}
Add this line of code before File.WriteAllText if you want to write the text that starts with "Temperature" (this way you remove the "?????" at the beginning):
sorted = sorted.Substring(sorted.IndexOf(temperature));
EDIT:
Following your last edit - you added the code that updates the RichTextBox. So you can do the sorting by column only in DataReceivedHandler. See below:
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
if (e.EventType != SerialData.Chars || !sp.IsOpen)
{
return;
}
string w = sp.ReadExisting();
if (w != String.Empty)
{
string temperature = "Temperature";
string sorted = w.Replace(temperature, Environment.NewLine + temperature);
Invoke(new Action(() => richTextBox1.AppendText(sorted)));
}
}
Basically what you need to understand is that File.WriteAllText(fileName, input) is where you write input into the file, so you can manipulate input as you wish before that line. If you wish to alter the text before it's dispalyed in the RichTextBox then you need to see where you execute something like richTextBox1.AppendText(input) or richTextBox1.Text = input and do all the changes you want on input before that line.
Im trying to read some data from a csv file and display it in c#
this works fine but i have 2 different rows in my csv file which i'll be adding too.
I want them to be accessible if say someonet types '1' into the ukNumber field it will pull all of their data.
atm no matter what i type it always displays the last line in my csv file.
namespace Appraisal
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ukNumber_TextChanged(object sender, EventArgs e)
{
}
public void search_Click(object sender, EventArgs e)
{
using (var reader = new StreamReader(File.OpenRead("C:\\Users\\hughesa3\\Desktop\\details.csv"),
Encoding.GetEncoding("iso-8859-1")))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
string idStr = values[0];
string firstnameStr = values[0];
string surnameStr = values[0];
string jobroleStr = values[0];
string salaryStr = values[0];
richTextBox1.Text = "Name: " + values[1] + "\nSurname: " + values[2] + "\nJob Role: " + values[3] + "\nSalary: £" + values[4];
}
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void apprasialCode_TextChanged(object sender, EventArgs e)
{
}
private void apprasialBtn_Click(object sender, EventArgs e)
{
}
private void ukNumberLabel_Click(object sender, EventArgs e)
{
}
}
}
There is a CsvHelper available via Nuget
https://www.nuget.org/packages/CsvHelper/
See following question:
using csvhelper (nuGET) with C# MVC to import CSV files
to read data from csv file:
using (var reader = new StreamReader(File.OpenRead("c:/yourfile.csv"),
Encoding.GetEncoding("iso-8859-1")))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';'); // replace ';' by the your separator
string idStr = values[0];
string firstnameStr = values[0];
string surnameStr = values[0];
string jobroleStr = values[0];
string salaryStr = values[0];
//convert string
}
}
I need to plot data from sensors of pH, Temperature and Humidity, the data is sent as a matrix from arduino to PC through the serial port.
I can show the data in a TextBox, but when I try to plot the data, it doesn't work (I don't know how to do it).
I just can plot the data when is not a matrix and it's data from just one sensor.
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.Tasks;
using System.IO.Ports;
using System.Windows.Forms.DataVisualization.Charting;
namespace grafik1
{
public partial class Form1 : Form
{
private SerialPort sensport;
private DateTime datetime;
private string data;
private string data2;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DataSource = SerialPort.GetPortNames();
timer1.Start();
}
double rt = 0;
Boolean i = false;
private void timer1_Tick(object sender, EventArgs e)
{
rt = rt + 0.1;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
sensport.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox2.Text == "")
{
MessageBox.Show("Error");
}
else
{
sensport = new SerialPort();
sensport.BaudRate = int.Parse(comboBox2.Text);
sensport.PortName = comboBox1.Text;
sensport.Parity = Parity.None;
sensport.DataBits = 8;
sensport.StopBits = StopBits.One;
sensport.Handshake = Handshake.None;
sensport.DataReceived += sensport_DataReceived;
try
{
sensport.Open();
textBox1.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
void sensport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (i == false)
{
rt = 0;
i = true;
}
data = sensport.ReadLine();
this.chart1.Series["Data1"].Points.AddXY(rt, data);
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Day + "/" + datetime.Month + "/" + datetime.Year + "\t" + datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
txtData.AppendText(time + "\t" + data + "\n");
}
private void button2_Click(object sender, EventArgs e)
{
string directorio = textBox1.Text;
if (directorio == "")
{
MessageBox.Show("Error");
}
else {
try
{
string kayıtyeri = #"" + directorio + "";
this.chart1.SaveImage(("+kayityeri+"), ChartImageFormat.Png);
MessageBox.Show("Grafica guardada en " + kayıtyeri);
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
sensport.Close();
}
private void button4_Click(object sender, EventArgs e)
{
try
{
string pathfile = #"C:\Users\MARIO GONZALEZ\Google Drive\VisualStudio\Arduino0_1\DATA";
string filename = "arduinoRTPv1.xls";
System.IO.File.WriteAllText(pathfile + filename, txtData.Text);
MessageBox.Show("Data saved");
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void button5_Click(object sender, EventArgs e)
{
}
private void chart1_Click(object sender, EventArgs e)
{
}
}
}
Let's assume you have prepared your chart, maybe like this:
chart1.Series.Clear();
chart1.Series.Add("ph");
chart1.Series.Add("Temp");
chart1.Series.Add("Hum");
chart1.Series["ph"].ChartType = SeriesChartType.Line;
chart1.Series["Temp"].ChartType = SeriesChartType.Line;
chart1.Series["Hum"].ChartType = SeriesChartType.Line;
chart1.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;
chart1.ChartAreas[0].AxisY2.Title = "Temp";
chart1.ChartAreas[0].AxisY2.Maximum = 100;
Now you can add a string that contains some data blocks as shown in the comments..
string data = "7.5 23.8 67 \n8.5 23.1 72 \n7.0 25.8 66 \n";
..like this:
var dataBlocks = data.Split('\n');
foreach (var block in dataBlocks)
{
var numbers = block.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
// rt += someTime; (*)
for (int i = 0; i < numbers.Length; i++)
{
double n = double.NaN;
bool ok = double.TryParse(numbers[i], out n);
if (ok) chart1.Series[i].Points.AddXY(rt, n);
else
{
int p = chart1.Series[i].Points.AddXY(rt, 0);
chart1.Series[i].Points[p].IsEmpty = true;
Console.WriteLine("some error message..");
}
}
}
I have modified the data a little to show the changes a little better..
Note that I left out the counting up of your timer rt, which is why the chart shows the points with indexed x-values. For a real realtime plot do include it maybe here (*) !
If you keep adding data your chart will soon get rather crowded.
You will then either have to remove older data from the beginning or at least set a minimum and maximum x-values to restrict the display to a reasonably number of data points and or turn on zooming!
See here here and here for some examples and discussions of these things!
There is a server and multiple clients. The server accepts the connection requests from multiple clients. The sockets created are stored in an array. There is a list box in my application. On selecting a particular item it refers to the corresponding socket in the array of sockets (eg if I select first item, it will consider first socket in the array). But the problem is - as the clients can connect to the server in random fashion how the server keep tracks of the clients if it has to send data to a particular client.
Here is my code:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
int i=0;
TcpListener listener = new TcpListener(8888);
listener.Start();
while(true)
{
Socket soc = listener.AcceptSocket();
socarray[i] = soc;
i++;
if (i == NUMBEROFCLIENTS)
break;
}
// Thread writetodatabase = new Thread(datawrite);
// writetodatabase.Start();
Application.Run(new Form1());
}
private void button5_Click(object sender, EventArgs e)
{
if (listBox1.Text == "Reader1")
{
reader_flag = 1;
toolStripStatusLabel1.Text = "reader1 selected";
a = toolStripStatusLabel1.Text;
}
if (listBox1.Text == "Reader2")
{
reader_flag = 2;
toolStripStatusLabel1.Text = "reader2 selected";
a = toolStripStatusLabel1.Text;
}
}
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string a;
public static int reader_flag = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Form3 formmm = new Form3();
formmm.Show();
}
private void button4_Click(object sender, EventArgs e)
{
Form2 formm = new Form2();
formm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
byte[] bytesFrom = new Byte[1000];
Program.socarray[0].Receive(bytesFrom);
char[] stuffed = System.Text.Encoding.UTF8.GetString(bytesFrom).ToCharArray();
int i;
char escape='#';
List<char> unstuffed = new List<char>();
for(i=0;i<stuffed.Length;i++)
{
if(stuffed[i]==escape)
{
i++;
unstuffed.Add(stuffed[i]);
}
else
{
unstuffed.Add(stuffed[i]);
}
}
unstuffed.RemoveAt(0);
unstuffed.RemoveAt(unstuffed.Count-1);
char[] final;
final = unstuffed.ToArray();
string foo = new string(final);
textBox1.Text = foo;
System.IO.File.WriteAllText(#"C:\Users\cdac\Desktop\server\server\TextFile2.txt", foo);
}
finally { }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Form4 mm = new Form4();
mm.Show();
}
private void toolStripStatusLabel1_Click(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = a;
}
private void button5_Click(object sender, EventArgs e)
{
if (listBox1.Text == "Reader1")
{
reader_flag = 1;
toolStripStatusLabel1.Text = "reader1 selected";
a = toolStripStatusLabel1.Text;
}
if (listBox1.Text == "Reader2")
{
reader_flag = 2;
toolStripStatusLabel1.Text = "reader2 selected";
a = toolStripStatusLabel1.Text;
}
}
private void button6_Click(object sender, EventArgs e)
{
string MyConString = "server=localhost;" +
"database=cdac;"+
"User Id=root;"
+"password=cdac56;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
connection.Open();
//StreamReader reader = new StreamReader("C:\\tag_log_030610.txt");
StreamReader reader = new StreamReader("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(';');
//command.CommandText = "insert into st_attn(rollno,Th_attn,Name) values('" + parts[0] + "','" + parts[1] + "','" + parts[2] + "')";
command.CommandText = "insert into st_attn(rollno) values('" + parts[0] + "')";
Reader = command.ExecuteReader();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Client-Server apps ALWAYS start with a request from the client to the server. No matter if it's a business app, a game, a website, a webservice or even something to tell the time, the client will always first ask the server.
This means that if you're using sockets, you will always have to let the request come from the client. He will send a request to the server. The server will then keep a record internally of where they can find the client. This is kept in the Endpoint property of the Socket. But normally, you will not have to worry about this unless you're working with push apps.
I have a problem regarding the rs232 communication with a Melfa rv-2aj robot. I am sending to commands in ASCII and when the robot replies via rs232 I get something like this: ??QY?e0?L???0???0???. My first thought was that I am not doing a proper conversion from ASCII when I read from RS232, but if I convert this set of charaters to a unicode output I get some chinesse characters and this should not be right. As the robot sends a reply via rs232, makes me think that my implementation is not wrong , but maybe my approch has some faults in it. I think "?" represent ASCII characters that are not properly displayed.
Below I have attached the source code to my application.
Can somebody give some pointers on what I doing wrong when I am reading from the serial that i get his kind of ouput?
I would really appreciate any kind of help, suggestion or reference.
Thank you very much.
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;
namespace RS232_Communication
{
public partial class Form1 : Form
{
private SerialPort COM_port = new SerialPort();
private byte[] _array = new byte[] {0};
public Form1()
{
InitializeComponent();
BAUDRate.Items.Add("2400");
BAUDRate.Items.Add("4800");
BAUDRate.Items.Add("9600");
BAUDRate.Items.Add("14400");
BAUDRate.Items.Add("19200");
BAUDRate.Items.Add("28800");
BAUDRate.SelectedIndex = 2;
DATAUnit.Items.Add("5");
DATAUnit.Items.Add("6");
DATAUnit.Items.Add("7");
DATAUnit.Items.Add("8");
DATAUnit.Items.Add("9");
DATAUnit.SelectedIndex = 3;
ParityUnit.Items.Add("None");
ParityUnit.Items.Add("Odd");
ParityUnit.Items.Add("Even");
ParityUnit.Items.Add("Mark");
ParityUnit.Items.Add("Space");
ParityUnit.SelectedIndex = 2;
STOPUnit.Items.Add("One");
STOPUnit.Items.Add("Two");
STOPUnit.SelectedIndex = 1;
this.Load += new EventHandler(Form1_Load);
SendText.KeyPress +=new KeyPressEventHandler(SendText_KeyPress);
COM_port.DataReceived +=new SerialDataReceivedEventHandler(COM_port_DataReceived);
}
private string GetString(byte[] bBuffer, int iIndex, int iLen, bool bUni)
{
string sBuffer;
if (bUni) sBuffer = Encoding.Unicode.GetString(bBuffer, iIndex, iLen);
else sBuffer = Encoding.ASCII.GetString(bBuffer, iIndex, iLen);
//return the string
return sBuffer;
}
void COM_port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ReceiveText.Invoke(new EventHandler(delegate
{
byte[] data = new Byte[COM_port.BytesToRead];
COM_port.Read(data, 0, data.Length);
//string read = GetString(data, 0, data.Length, true);
string read = System.Text.Encoding.ASCII.GetString(data);
ReceiveText.AppendText(read);
//ReceiveText.AppendText(COM_port.ReadExisting());
}
)
)
;
}
void Form1_Load(Object sender, EventArgs e)
{
foreach (string COMstr in SerialPort.GetPortNames())
COMPort.Items.Add(COMstr);
if (COMPort.Items.Count > 0)
COMPort.SelectedIndex = 0;
else MessageBox.Show("No COM Ports available");
}
private void ConnectBTN_Click(object sender, EventArgs e)
{
try
{
if (COM_port.IsOpen)
{
COMPort.Enabled = true;
BAUDRate.Enabled = true;
ParityUnit.Enabled = true;
STOPUnit.Enabled = true;
DATAUnit.Enabled = true;
COM_port.DtrEnable = false;
COM_port.RtsEnable = false;
ConnectBTN.Text = "Connect";
COM_port.Close();
}
else
{
COM_port.BaudRate = int.Parse(BAUDRate.Text);
COM_port.Parity = (Parity)Enum.Parse(typeof(Parity), ParityUnit.Text);
COM_port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), STOPUnit.Text);
COM_port.DataBits = int.Parse(DATAUnit.Text);
COM_port.PortName = COMPort.Text;
//COM_port.DtrEnable = true;
//COM_port.RtsEnable = true;
COM_port.Open();
COM_port.ReadTimeout = 2000;
COM_port.WriteTimeout = 2000;
COMPort.Enabled = false;
BAUDRate.Enabled = false;
ParityUnit.Enabled = false;
STOPUnit.Enabled = false;
DATAUnit.Enabled = false;
ConnectBTN.Text = "Disconnect";
}
}
catch
{
MessageBox.Show("Connection Error");
}
}
public void WriteBytes(byte[] array)
{
COM_port.Write(array, 0, array.Length);
}
public void WriteBytes(byte[] array, int index, int length)
{
COM_port.Write(array, index, length);
}
public void WriteLine(String line)
{
//string s="";
//foreach (byte b in StringToBytes(line + "\r\n"))
// s = s + b.ToString();
//COM_port.WriteLine(s);
WriteBytes(StringToBytes(line + "\r\n"));//CR + LF
}
public static byte[] StringToBytes(string input)
{
return Encoding.ASCII.GetBytes(input);
}
private void SendBTN_Click(object sender, EventArgs e)
{
if (SendText.Text != "")
{
WriteLine(SendText.Text);
//COM_port.WriteLine(SendText.Text);
SendText.Text = "";
}
}
void SendText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
WriteLine(SendText.Text);
//COM_port.WriteLine(SendText.Text);
SendText.Text = "";
}
}
}
}
I managed to figure out what was the problem. In the manual for the rv-2aj it is specified that in order to use the rs232 communication the following parameters have to be set: baud rate 9600, parity even, stop bits 2, data bits 8. So I configured my communication this way, and when I sent data to the controller I would receive strange messages as I showed in my previous post. It seems that the configuration for communication on the robot side was different then mine, so I changed the value for parity to none and the stop bits to one and now everything works as expected. I get proper feedback from the robot and the commands work. The code I wrote in c# works fine, no necessary modifications required.