简体   繁体   中英

C# Serial communcation with arduino

I'm trying to send a string from my arduino(leonardo) to a C# program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;

namespace ConsoleApplication2
{
class Program
{

    static void Main(string[] args)
    {
        SerialPort mySerialPort = new SerialPort("COM7");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;


        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
    }
}
}

This is my code wich I copied from the msdn example to try and understand what it does. My arduino code below just sends hello world over te com port with a delay of 1000.

void setup ()
{

 Serial.begin(9600);

 }


void loop(){

 Serial.println("Hello World");
 delay(1000);
}

My arduino is using the COM7 like I defined in the C# program. When I run bot programs, The C# program never comes within the datareceived event handler. So no data is received. I really want tis to work :)

Kind regards

I Switched the code to a windows form application, it still was not working. Then i found a topic about serial communication with C# about arduino leonardo here

I had to do this:

        serial.DtrEnable = true;
        serial.RtsEnable = true;

I consider my problem as solved.

Console applications do not have a message loop so naturally they don't respond to events. You have one thread and it will be stuck blocking at Console.ReadKey() . Either use synchronous reads from the serial port or, if you wish to stick to an event-based model, move this code to a windows-based applications.

For a synchronous example, see this MSDN example :

while (_continue)
{
    try
    {
        string message = _serialPort.ReadLine();
        Console.WriteLine(message);
    }
    catch (TimeoutException) { }
}

The above is only an excerpt - the full example demonstrates setting up the timeout values, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM