Arduino, Visual C# best Serial comunication - c#

I'm new to Arduino and serial ports and I want to make the best communication between Arduino and my C# program. In my code I want to control one or more servo motors fast as possible. This is my Arduino code:
#include <Servo.h>
Servo serv;
void setup() {
Serial.begin(115200);
Serial.setTimeout(5);
pinMode(9,OUTPUT);
serv.attach(9);
}
String msg;
void loop() {
String val = Serial.readString();
if(val!=0) {
if(val.startsWith("U")) {
val.replace("U","");
serv.write(val.toInt());
delay(10);
}
}
if(Serial.available()>0) {
msg = "U";
msg = msg+serv.read();
Serial.println(msg);
}
}
And my C# program:
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;
namespace arduino_servo {
public partial class Form1 : Form {
SerialPort port;
public Form1() {
InitializeComponent();
init();
}
private void Form1_Load(object sender, EventArgs e) {
}
private void init() {
port = new SerialPort();
port.PortName = "COM5";
port.BaudRate = 115200;
port.DataReceived += new SerialDataReceivedEventHandler(Primire_date);
try {
port.Open();
}
catch(Exception ex) {
MessageBox.Show("Eroare",ex.Message,MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void trackBar1_Scroll(object sender, EventArgs e) {
if (port.IsOpen) {
port.WriteLine("U"+trackBar1.Value.ToString());
}
}
private void Primire_date(object emitator, SerialDataReceivedEventArgs e) {
string msg = port.ReadLine();
if (msg.IndexOf("U") > -1) {
msg = msg.Replace("U", "");
label1.Text = msg;
}
}
}
}
If you guys could give me some advice or some modifications, I would be very thankful. My communication is a bit laggy.

Related

Why is my client server udp code not sending?

I have been interested in tcp, udp and named pipes lately and am trying to teach myself. I am trying to get a udp connection set up to see how it works. I have a client and server program in windows form app with a richtextBox1 and btStart. I would like to get this setup on the same computer and then try with two computers. I cannot get anything to send. Can anyone show me what I'm doing wrong? I am just trying to learn.
Here is the server 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;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPServer
{
public partial class Form1 : Form
{
delegate void ShowMessageMethod(string msg);
UdpClient _server = null;
IPEndPoint _client = null;
Thread _listenThread = null;
private bool _isServerStarted = false;
public Form1()
{
InitializeComponent();
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
this.btStart.Text = "StartServer";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btStart_Click(object sender, EventArgs e)
{
if (_isServerStarted)
{
Stop();
btStart.Text = "StartServer";
}
else
{
Start();
btStart.Text = "StopServer";
}
}
private void Start()
{
//Create the server.
IPEndPoint serverEnd = new IPEndPoint(IPAddress.Any, 1234);
_server = new UdpClient(serverEnd);
ShowMsg("Waiting for a client...");
//Create the client end.
_client = new IPEndPoint(IPAddress.Any, 0);
//Start listening.
Thread listenThread = new Thread(new ThreadStart(Listening));
listenThread.Start();
//Change state to indicate the server starts.
_isServerStarted = true;
}
private void Stop()
{
try
{
//Stop listening.
listenThread.Join();
ShowMsg("Server stops.");
_server.Close();
//Changet state to indicate the server stops.
_isServerStarted = false;
}
catch (Exception excp)
{ }
}
private void Listening()
{
byte[] data;
//Listening loop.
while (true)
{
//receieve a message form a client.
data = _server.Receive(ref _client);
string receivedMsg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the message.
this.Invoke(new ShowMessageMethod(ShowMsg), new object[] { "Client:" + receivedMsg });
//Send a response message.
data = Encoding.ASCII.GetBytes("Server:" + receivedMsg);
_server.Send(data, data.Length, _client);
//Sleep for UI to work.
Thread.Sleep(500);
}
}
private void ShowMsg(string msg)
{
this.richTextBox1.Text += msg + "\r\n";
}
}
}
Here is the client 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;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace UDPClient
{
public partial class Form1 : Form
{
UdpClient _server = null;
IPEndPoint _client = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
//Get the server.
_server = new UdpClient("127.0.0.1", 16000);
//Create a client.
_client = new IPEndPoint(IPAddress.Any, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
_server.Close();
}
catch (Exception s)
{
}
}
private void btSend_Click(object sender, EventArgs e)
{
try
{
//Send the input message.
string text = this.richTextBox1.Text;
_server.Send(Encoding.ASCII.GetBytes(text), text.Length, _client);
//Receive the response message.
byte[] data = _server.Receive(ref _client);
string msg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the response message.
this.richTextBox1.Text = msg;
}
catch (Exception exp)
{
}
}
}
}
As a general rule, when you want to check connectivity problems or debug what is being send, you can use a proxy like Fiddler or ZAP, so you are going to be able to intercept the traffic, analyze and manipulate it in case you need, and this is going to give you a lot of information.
As possible solution to your question take a look at Microsoft documentation.

C#, need to receive data from microcontroller

Trying to receive data, from mk, using DataReceived and handler event, what i do is -
push a button on a program (code is below) then LED on mk will turn on, then the data should be sent back to program (expecting 1, on byte value, but also tried string value, doesn't work). Sending side is working, but receiving....not
seems like i'm missing something. Any help apreciate it. Thx in Further
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;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) // As i understood, here we configure where i data will be shown,
// trying to get it on TextBox1
{
SerialPort sp = (SerialPort)sender;
richTextBox1.Text += sp.ReadExisting() + "\n";
}
private void button1_Click(object sender, EventArgs e) // There are a main actions, first i receive data then send data by a click.
{
serialPort1.Write("\u0001");
serialPort1.Close();
System.ComponentModel.IContainer components = new System.ComponentModel.Container(); //
serialPort1 = new System.IO.Ports.SerialPort(components);
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
serialPort1.Open();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
}
}
The serial port is on a different thread than the UI. So when you receive a character, as you haven't invoked the UI, you get an exception and the UI is not updated.
Invoke the UI first in your DataReceivedHandler. You could do something like that:
public static class ControlExt
{
public static void InvokeChecked(this Control control, Action method)
{
try
{
if (control.InvokeRequired)
{
control.Invoke(method);
}
else
{
method();
}
}
catch { }
}
}
public partial class Form1 : Form
{
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
this.InvokeChecked(delegate
{
richTextBox1.Text += serialPort1.ReadExisting() + "\n";
richTextBox1.SelectionStart = Text.Length;
richTextBox1.ScrollToCaret();
});
}
}

C# read Arduino

I'm trying to make a app that read the outgoing signals from Arduino, but I can't make it work in C# Windows Forms, only in the console. Is my C# Windows Forms code wrong? I don't get any errors when I debug, but it doesn't mean that I haven't forgot something.
Here is 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;
using System.IO.Ports;
using System.Threading;
namespace CommunicateWithArduino
{
public partial class Form1 : Form
{
public static System.IO.Ports.SerialPort port;
delegate void SetTextCallback(string text);
private BackgroundWorker hardWorker;
private Thread readThread = null;
public Form1()
{
InitializeComponent();
hardWorker = new BackgroundWorker();
sendBtn.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
System.ComponentModel.IContainer components =
new System.ComponentModel.Container();
port = new System.IO.Ports.SerialPort(components);
port.PortName = comPort.SelectedItem.ToString();
port.BaudRate = Int32.Parse(baudRate.SelectedItem.ToString());
port.DtrEnable = true;
port.ReadTimeout = 5000;
port.WriteTimeout = 500;
port.Open();
readThread = new Thread(new ThreadStart(this.Read));
readThread.Start();
this.hardWorker.RunWorkerAsync();
btnConnect.Text = "<Connected>";
btnConnect.Enabled = false;
comPort.Enabled = false;
sendBtn.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comPort.Items.Add(s);
}
if (comPort.Items.Count > 0)
comPort.SelectedIndex = comPort.Items.Count-1;
else
comPort.SelectedIndex = 0;
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.Items.Add("38400");
baudRate.Items.Add("57600");
baudRate.Items.Add("115200");
baudRate.SelectedIndex = 2;
}
private void sendBtn_Click(object sender, EventArgs e)
{
if (port.IsOpen)
{
port.Write(sendText.Text);
}
}
private void SetText(string text)
{
if (this.receiveText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.receiveText.Text += "Text: ";
this.receiveText.Text += text;
this.receiveText.Text += Environment.NewLine;
}
}
public void Read()
{
while (port.IsOpen)
{
try
{
if (port.BytesToRead > 0)
{
string message = port.ReadLine();
this.SetText(message);
}
}
catch (TimeoutException) { }
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
try
{
if(!(readThread == null))
readThread.Abort();
}
catch (NullReferenceException)
{
}
try
{
port.Close();
}
catch (NullReferenceException)
{
}
}
}
}
By default, the ReadLine method will block until a line is received. Is your Arduino program sending a line? Did you close the Arduino serial monitor program while running your program?
I would change to port.ReadChar until you verify that you are receiving characters.

Chilkat Sockets error WSAECONNRESET in C# 4.0

my code is working fine but also I am receiving lot of WSAECONNRESET An existing connection was forcibly closed by the remote host. error.
I have a Chilkat.Socket Listener exe which is executing as a windows service and a test program which is simply sending strings data to this listener service. Listener is working fine but the program which is generatring strings and sending it to the listener is receiving the below mentioned error...please guide.
Error:
ChilkatLog:
SendString:
DllDate: Jan 19 2012
UnlockPrefix: XXXXSocket
Username: XXXXXX
Architecture: Little Endian; 64-bit
Language: .NET 4.0 / x64
fd: 0x510
objectId: 1433
NumChars: 111
Charset: ansi
NumBytes: 111
SocketError: WSAECONNRESET An existing connection was forcibly closed by the remote host.
For more information see this Chilkat Blog post: http://www.cknotes.com/?p=217
Error sending on socket
send_size: 111
Failed.
This is my windows service code running as a listner
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using Chilkat;
using NLog;
using Newtonsoft.Json;
namespace Test.Services.MessageServer
{
public partial class MessageProcessor : ServiceBase
{
private Chilkat.Socket _socket;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public MessageProcessor()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
init();
}
protected override void OnStop()
{
}
private void init()
{
_socket = new Chilkat.Socket();
_logger.Info("Service starting...");
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//_logger.Info("Service started");
var success = _socket.UnlockComponent("XXXXXXSocket_XXXXXXXXX");
try
{
if (success != true)
{
return;
}
success = _socket.BindAndListen(5555, 25);
if (success != true)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
// Get the next incoming connection
// Wait a maximum of 0 seconds (0000 millisec)
Chilkat.Socket connectedSocket = null;
connectedSocket = _socket.AcceptNextConnection(0);
if (connectedSocket == null)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
connectedSocket.MaxReadIdleMs = 1000;
string txt = connectedSocket.ReceiveUntilMatch("-EOM-");
_logger.Info(String.Format("Received Orignal Message: {0}", txt));
if (txt == string.Empty)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
connectedSocket.Close(0);
((BackgroundWorker)sender).ReportProgress(0, txt.Replace("-EOM-", string.Empty).Trim());
}
catch (Exception ex)
{
_logger.Error(String.Format("Error caught: {0}", _socket.LastErrorText));
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState == null) return;
_logger.Info((String.Format("Message Received: {0}", e.UserState.ToString())));
var obj = JsonConvert.DeserializeObject<JsonGeoLocation>(e.UserState.ToString());
_logger.Info((String.Format("Received: JobId: {0}\tDateTime: {1}\tLatitude: {2}\tLongitude: {3}", obj.F0,obj.F1,obj.F2.F0,obj.F2.F1)));
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
}
This is my code which is connecting to the above code and sending the messages
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Chilkat;
using NLog;
using Newtonsoft;
using Newtonsoft.Json;
namespace SocketMessageGenerator
{
public partial class Form1 : Form
{
//private Chilkat.Socket _socket;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public Form1()
{
InitializeComponent();
Init();
}
private void Init()
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
SendMessage();
}
private void SendMessage()
{
var socket = new Socket();
var success = socket.UnlockComponent("XXXXXXSocket_XXXXXXXXX");
try
{
if (success != true)
{
return;
}
success = socket.Connect("191.111.009.256", 5555, false, 0);
if (!success)
{
_logger.Info((String.Format("Error: \nunable to connect to host: {0}", socket.LastErrorText)));
}
var geoLocation = new JsonGeoLocation { F0 = 123, F1 = System.DateTime.Now, F2 = new JsonGeoPosition { F0 = 51.577790260314941, F1 = 0.0993499755859375 } };
var obj = JsonConvert.SerializeObject(geoLocation);
success = socket.SendString(message);
//success = socket.SendString(obj);
if (!success)
{
_logger.Info((String.Format("Error: \nunable to send message: {0}", socket.LastErrorText)));
}
socket.Close(1000);
}
catch (Exception)
{
throw;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
}

UDP datagram code for server client application in C#

When i try to send a message from my client , the server is not able to receive that message and print it. Can anyone tell me the error in the following server client application.
I have created two WinForm projects, one is UDP server and the other is UDP client.
In UDP server project, I created a form which contains a RichTextBox named richTextBox1 to show message and a Button named btStart to start/stop the listening. This is the code snippet:
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.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPServer
{
public partial class Form1 : Form
{
delegate void ShowMessageMethod(string msg);
UdpClient _server = null;
IPEndPoint _client = null;
Thread _listenThread = null;
private bool _isServerStarted = false;
public Form1()
{
InitializeComponent();
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
this.btStart.Text = "StartServer";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btStart_Click(object sender, EventArgs e)
{
if (_isServerStarted)
{
Stop();
btStart.Text = "StartServer";
}
else
{
Start();
btStart.Text = "StopServer";
}
}
private void Start()
{
//Create the server.
IPEndPoint serverEnd = new IPEndPoint(IPAddress.Any, 1234);
_server = new UdpClient(serverEnd);
ShowMsg("Waiting for a client...");
//Create the client end.
_client = new IPEndPoint(IPAddress.Any, 0);
//Start listening.
Thread listenThread = new Thread(new ThreadStart(Listening));
listenThread.Start();
//Change state to indicate the server starts.
_isServerStarted = true;
}
private void Stop()
{
try
{
//Stop listening.
listenThread.Join();
ShowMsg("Server stops.");
_server.Close();
//Changet state to indicate the server stops.
_isServerStarted = false;
}
catch (Exception excp)
{ }
}
private void Listening()
{
byte[] data;
//Listening loop.
while (true)
{
//receieve a message form a client.
data = _server.Receive(ref _client);
string receivedMsg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the message.
this.Invoke(new ShowMessageMethod(ShowMsg), new object[] { "Client:" + receivedMsg });
//Send a response message.
data = Encoding.ASCII.GetBytes("Server:" + receivedMsg);
_server.Send(data, data.Length, _client);
//Sleep for UI to work.
Thread.Sleep(500);
}
}
private void ShowMsg(string msg)
{
this.richTextBox1.Text += msg + "\r\n";
}
}
}
In UDP client project, I also created a form which contains a RichTextBox named richTextBox1 to input or show message and a Button named btSend to send the input message. You can run several instances of this project. The server would cope with all the running clients. This is the code snippet:
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.Net.Sockets;
using System.Net;
using System.Threading;
namespace UDPClient
{
public partial class Form1 : Form
{
UdpClient _server = null;
IPEndPoint _client = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
//Get the server.
_server = new UdpClient("127.0.0.1", 16000);
//Create a client.
_client = new IPEndPoint(IPAddress.Any, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
_server.Close();
}
catch (Exception s)
{
}
}
private void btSend_Click(object sender, EventArgs e)
{
try
{
//Send the input message.
string text = this.richTextBox1.Text;
_server.Send(Encoding.ASCII.GetBytes(text), text.Length);
//Receive the response message.
byte[] data = _server.Receive(ref _client);
string msg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the response message.
this.richTextBox1.Text = msg;
}
catch (Exception exp)
{
}
}
}
}
You are not setting your destination. You need to either use UdpClient.Connect before using UdpClient.Send(Byte[], Int32) or use UdpClient.Send(Byte[], Int32, IPEndPoint).

Categories

Resources