You could read the serial port information with ReadLine()
, but you would need to create a listener so that every time you had data available on the port, they were read.
The suggestion is that you use the event DataReceived
, which will be called when data is being read *.
For testing, you can upload the program SerialEvent
of Arduino:
Andwiththefollowingexamplecode,youcansendandreceivedatathroughtheserialport:
usingSystem;usingSystem.IO.Ports;namespaceArduinoSerial{classArduinoSerial{privatestaticSerialPortportaSerial=newSerialPort("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);
}
}
}
Result:
IntheSerialEvent
programoftheArduino,youwillseethattosenddata forserialport,Serial.println(inputString);
isused.Modifying theprogram,andreplacinginputString
withwhateveryouwant,you youcansenddifferentdatatoyourC#program.
*Inthedocumentationwhatisactuallyindicatedistouse BytesToRead
to see if there is data to be read.
Sources:
How to Read and Write from the Serial Port
Server Client send / receive simple text
C # Serial Port Listener