Reputation: 53
I have a class that has to read a position continuously I am able to read the position but only once, so how would I send a command continuously and read back its response
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SharpRotor.Lib
{
public class SharpRotorL
{
string PortName;
int BaudRate;
public SharpRotorL(string PortName, int BaudRate)
{
this.PortName = PortName;
this.BaudRate = BaudRate;
}
SerialPort sp = new SerialPort();
public void test()
{
sp.NewLine = "\r\n";
sp.PortName = this.PortName;
sp.BaudRate = this.BaudRate;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;
sp.Handshake = Handshake.None;
sp.DtrEnable = true;
sp.WriteBufferSize = 1024;
string t = "";
int timeout = 10000; //t: response msg
try
{
if (!sp.IsOpen)
sp.Open();
Thread.Sleep(200);
sp.BaseStream.Flush();
sp.WriteLine("C"); //Ex: cmd=C to get Position (+0001)
sp.BaseStream.Flush();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
private void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
}
}
as well as reading asynchronously I would also like to send some commands back while still reading position data
Not sure if this is possible, if it is I would love to know a way.
Upvotes: 1
Views: 4572
Reputation: 2053
Should be able to achieve this using the Timer
class. You're pretty close. Note that you should create your DataReceived
event before opening the port.
SerialPort sp;
Timer tm;
private void init_ports()
{
//Setup our Serial Port
sp = new SerialPort();
sp.NewLine = "\r\n";
sp.PortName = this.PortName;
sp.BaudRate = this.BaudRate;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;
sp.Handshake = Handshake.None;
sp.DtrEnable = true;
sp.WriteBufferSize = 1024;
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
//Setup our Timer
tm = new Timer();
tm.Tick += new EventHandler(tm_Tick);
tm.Interval = 1000; //in ms
tm.Enabled = true; //Start our timer
}
void tm_Tick(object sender, EventArgs e)
{
if (!sp.IsOpen)
sp.Open();
sp.Write("C");
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
You should be able to call init_ports
and once a second it should send the C
command.
Upvotes: 4