Sending commands to Arduino Using C#

I used this code from one of the sites I was looking at and it supposed to teach you how to read/write a USB device but when I compile it, i get an error as follow:

The type or namespace name 'Drawing' does not exist in the namespace 'System' (are you missing an assembly reference?) (CS0234) - C:\Users\Dourassi\Documents\SharpDevelop Projects\HelloWorld\HelloWorld\Program.cs:6,16

The type or namespace name 'Windows' does not exist in the namespace 'System' (are you missing an assembly reference?) (CS0234) - C:\Users\Dourassi\Documents\SharpDevelop Projects\HelloWorld\HelloWorld\Program.cs:8,16

this is the link for the code:

All efforts are appreciated. I'm trying to basically send (1,2,3) commands to Arduino. then I have the Arduino code checking if input ==1 then it turns LED ON and if input==2 then LED OFF and so on..

You want the Serial libraries in .NET, I'll whip up a quick console app for you... hang on...

Here you go:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;          // Serial stuff in here.

namespace Serial
{
    class Program
    {
        static SerialPort port;
        static void Main(string[] args)
        {
            int baud;
            string name;
            Console.WriteLine("Welcome, enter parameters to begin");
            Console.WriteLine(" ");
            Console.WriteLine("Available ports:");
            if (SerialPort.GetPortNames().Count() >= 0)
            {
                foreach (string p in SerialPort.GetPortNames())
                {
                    Console.WriteLine(p);
                }
            }
            else
            {
                Console.WriteLine("No Ports available, press any key to exit.");
                Console.ReadLine();
                // Quit
                return;
            }
            Console.WriteLine("Port Name:");
            name = Console.ReadLine();
            Console.WriteLine(" ");
            Console.WriteLine("Baud rate:");
            baud = GetBaudRate();

            Console.WriteLine(" ");
            Console.WriteLine("Beging Serial...");
            BeginSerial(baud, name);
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            port.Open();
            Console.WriteLine("Serial Started.");
            Console.WriteLine(" ");
            Console.WriteLine("Ctrl+C to exit program");
                Console.WriteLine("Send:");

            for (; ; )
            {
                Console.WriteLine(" ");
                Console.WriteLine("> ");
                port.WriteLine(Console.ReadLine());
            }
        }

        static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            for (int i = 0; i < (10000 * port.BytesToRead) / port.BaudRate; i++)
                ;       //Delay a bit for the serial to catch up
            Console.Write(port.ReadExisting());
            Console.WriteLine("");
            Console.WriteLine("> ");
        }

        static void BeginSerial(int baud, string name)
        {
            port = new SerialPort(name, baud);
        }

        static int GetBaudRate()
        {
            try
            {
                return int.Parse(Console.ReadLine());
            }
            catch
            {
                Console.WriteLine("Invalid integer.  Please try again:");
                return GetBaudRate();
            }
        }
    }
}

Thank you very much..you are the man..i'm going to try it and hopefully it'll get me a step further.. :slight_smile:

No worries, I intended to make that program soon ish anyway, thanks for giving me the kick up the @rse I needed. :stuck_out_tongue: The only issue I had with that was packet splitting, you may need some sort of delay, or run the connection at a high baud, 115200 worked well. You could expand on it by making an Arduino Coms library of your own, with a Connect(string name, int baud) method and a Send(string message) method. Could be fun playing with enums and setting up event firing, something I have never done... MSDN is your best bet for C# help. Bear in mind this is all serial communication via the System.IO.Ports libraries. The MSDN library will give you detailed info on all the methods, properties and event handelers in every .NET library. That's about as much help as I can give. Good luck, look forward to seeing the finished product in the exhibition. :wink:

GrayMalkin,
I did ran your code and it compiles perfectly. To the best of my knowledge, your code can read and write data to the serial port if i understood it correctly.
I did write a small Arduino code to control an LED based on the input as follow:

/*

  • Hello World!
  • This is the Hello World! for Arduino.
  • It shows how to send data to the computer
    */

int ledPin = 13;
int value;

void setup() // run once, when the sketch starts
{
pinMode(ledPin,OUTPUT);
Serial.begin(115200); // set up Serial library at 9600 bps

}

void loop()
{
int input = Serial.read(); // read serial

switch (input){
case 1: //If C# sent a '1' do case one
if(input == 1)
{
analogWrite(ledPin, 1023);
delay(1000);
analogWrite(ledPin,0);
delay(1000);
}
break;
case 2:
if(input == 2)//If C# sent a '2' do case two
{
analogWrite(ledPin, 500);
delay(1000);
analogWrite(ledPin,0);
delay(1000);
}
break;
case 3:
if(input == 3) //If C# sent a '3' do case three
{
analogWrite(ledPin, 100);
delay(1000);
analogWrite(ledPin,0);
delay(1000);
}
break;
}

}

Now my question is : when I run the C# code, I declare the port COM4 and Baud 115200 and I send inputs: 1 and then the C# askes for the next input so I put in 2 and so on until I click CTRL+C to exit the program..unfortunately, my serial port is not reading the input to turn the LED on..it maybe something trivial ...maybe I'm not calling a lib or connecting the serial port to the C# correctly

Thank you in advance..I like your idea of exhibit but i think I have a way to go before it happens:)

Laxman,
Were you able to write data to the serial port and control and you just compiled it and were able to detect the existant COM's :-?

@Sammor - I shouldn't bother engaging with laxman - it won't be around much longer.

ok thank you..anybody is aware of what could be wrong with my approach explained above..

Maybe

case '1': //If C# sent a '1' do case one

?

(Not sure what it is you're sending)

Also:

switch (input){
   case 1:  //If C# sent a '1' do case one
     if(input == 1)  // no need to test here - that's what the "case" does.

Ok, there are a few distinctions to be made, the code I wrote sends strings, long arrays of chars, so, if you set the arduino to parse the inputs as an int you will have to look up what the arduino sees, for example a letter one sent over serial via the program will appear as the number 49 to the arduino, so you will need to change it to case 48: and case 49:

There was a sketch I use to check this and it is in the examples I believe, I'll hunt it down.

Are you professor?? if not, maybe you should think about it...a lot of us out there are hoping to have good programmers who can deliver like you do :wink:

I am able to read the feedback from the arduino on the C# screen and also turn the LEd on. Here is why: I have input = serial.read() returning -1 which i basically wrote : Serial.println("C# is reading input: -1"); and then I have case-1: turn LED on. So i can your code is working in terms of communicating between C# and Arduino but the next step is to be able to read the inputs sent from C#. I just wanted to let you know in case this rings a bell. I did try 48,49,50 but no luck. DO you think I should try a string let's say "one","two" etc... :wink:

well, that sounds odd, it should be positive numbers returned by Serial.read(); never the less, here is some code to play with, first - changes to my program, it's now a bit more versitile - so should someone stumble on this thread looking for a serial program it is here - too big for the forum post size now, sorry about that.

Ok, here is a sketch to turn on and off LED 13 when sent ASCII 0 or 1

void setup(){
 Serial.begin(115200);
 pinMode(13, INPUT); 
}

int received = 0;
void loop(){
 if(Serial.available() == 1)
 {
   received = Serial.read();
   switch (received)
   {
    case 48:     // Received ASCII 0
       digitalWrite(13, LOW);
       break;   //Move on
    case 49:     // Received ASCII 1
       digitalWrite(13, HIGH);
       break;   //Move on
   }
 } 
}

and here is some code for testing what an arduino really receives...

int incomingByte = 0;      // for incoming serial data

void setup() {
      Serial.begin(9600);      // opens serial port, sets data rate to 9600 bps
}

void loop() {

      // send data only when you receive data:
      if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);
      }
}

From the tutorial, not my work etc.

Noo, I'm not a professor, one day maybe, I'm 15 atm... :stuck_out_tongue:

Also, I noted the way you were using switch statements, not quite right there, close but no biscuit. What you do is:

switch(input){
case :
// Code...
break; // Don't bother doing anyother comparisons, this is the one that was meant to happen
}

eg:

switch (input){
  case 48:  // 48 is what int input must equal for this to run
     digitalWrite(13, LOW;)  // More stuff like this can follow
     break; //When all associated code has finished you can move on.  It does the same as an IF statement but looks neater.  
  case 49:  // 49 is what int input must equal this time
     digitalWrite(13, HIGH);
     break;
// and so on
} // dont forget this one

Awesome..I will try it first thing in the morning when i get to the lab...it seems like both codes are for the Arduino...i guess the code for C# that you provided me before remains the same..I can run it still!!!??

Thank you very very much

case 48:

As AWOL pointed out earlier, case '1': is much easier to read than case 49:, and has been said many, many times before, you don't need to carry around an ASCII chart in your head.

@greymalkin:

it should be positive numbers returned by Serial.read();

"read" returns -1 when the buffer is empty.
It's mentioned in the documentation.

It works perfectly...God you just made my day:)
I will now try to modify it to shift to a GUI and that is my last stage as far as C# goes...thank God.
How do you know all this at 15? very impressive

Groove, you are right!! i just wanted to see if there is a communication between C# and Arduino an the fact that it returns -1 tells me that C# knows that nothing is in the Arduino. and as far as ASCII goes, you are absolutely right!! i'll make the change accordignly...thank you for the hints

ooh, yes... I forget that chars are just ints in disguise... well then that makes life easier still!

switch (input){
  case '0':
     digitalWrite(13, LOW);
     break;
  case '1':
     digitalWrite(13, HIGH);
     break;
}

Also, apologies to AWOL for posting exactly the opposite of what he put in the first place which was use a char instead of case 1: or case 49: