You could read the serial port information with the ReadLine()
, but you would need to create a Listener so that every time they had data available at the port, they were read.
The suggestion is that you use the event DataReceived
, which will be called when data is to be read*.
For testing, you can upload the program SerialEvent
arduino:
And with the following example code, you can send and receive data through the serial port:
using System;
using System.IO.Ports;
namespace ArduinoSerial
{
class ArduinoSerial
{
private static SerialPort portaSerial = new SerialPort("COM3",
9600, Parity.None, 8, StopBits.One);
static void Main(string[] args)
{
// quando há dados na porta, chamamos dadosRecebidos
portaSerial.DataReceived += new SerialDataReceivedEventHandler(dadosRecebidos);
// criar a conexão
portaSerial.Open();
// mantendo o programa rodando
while (portaSerial.IsOpen)
{
// o que escrevermos no console, vai pra porta serial
portaSerial.WriteLine(Console.ReadLine());
}
}
// dadosRecebidos imprime a informação de volta no console
static void dadosRecebidos(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string dados = sp.ReadLine();
Console.WriteLine(dados);
}
}
}
Upshot:
In the program SerialEvent
Arduino, you will see that to send data
for serial port, is used Serial.println(inputString);
. Modifying
the program, and replacing inputString
for whatever you want, you
can send different data to your program in C#.
*In the documentation the indicated is actually to use BytesToRead
to see if data is being read.
Sources:
How to Read and Write from the Serial Port
Server Client send/receive simple text
C# Serial Port Listener
Did you manage to solve your problem? I was thinking of modifying my answer, but it would be nice to have one feedback yours, before.
– Daniel
young man, give continuity to your topics please, in another, I answered what could help you and you erased the question
– Rovann Linhalis