C# Sending Serial Commands to Arduino

2.5k views Asked by At

I am using an Arduino Mega 2560 board to control a strip of LED's. I am trying to use a short C# console program to send serial commands to my Arduino program. In Arduino, I have a library called SerialCommand where I can read a serial string and use it to execute a function and also pass along arguments like so: "functionName arg1 arg2 arg3". I've tested this by sending serial commands through a terminal and it works great! I've gotten Arduino functions to run by sending serial commands from my C# program also but only if that serial string doesn't include any spaces.

Here is my C# code:

class Program
{
    public static System.IO.Ports.SerialPort serialPort1;

    private void establishConnection()
    {
        serialPort1 = new System.IO.Ports.SerialPort("COM4");
        serialPort1.BaudRate = 115200;

        serialPort1.Open();
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        p.establishConnection();

        string i;
        while (true)
        {
            Console.Write("Enter command:  ");
            i = Console.ReadLine();
            if (i == "exit")
            {
                serialPort1.Close();
                break;
            }
            else if (i == "1")
            {
                // Turn LED's on and pass argument "test"
                serialPort1.Write("ON test\n");
            }
        }
    }
}

I know my connection works and my commands are sending because if I program my ON function in Arduino to work without the argument, it works great. However if I send the "ON" command and include the argument after a space, or use spaces in general, the Arduino doesn't read it properly.

Do you have any idea of why the space is messing with my serial commands in C#? Thanks for any help.

Here is a simple sample of what I'm doing in Arduino:

#include "SerialCommand.h"
#include <Adafruit_NeoPixel.h>

SerialCommand sCmd;

#define PIN7 7
// Strip of LED's
Adafruit_NeoPixel testStrip = Adafruit_NeoPixel(10, PIN7, NEO_GRB + NEO_KHZ800);
uint32_t testStripColor = 0xFFFFFF;

void setup() {
  Serial.begin(115200);

  sCmd.addCommand("ON",  lightsOn);
  sCmd.addCommand("OFF",  lightsOff);

  testStrip.begin();
  testStrip.show();
}

void loop() {
  sCmd.readSerial();
}

void lightsOn() {
  char *lightSet;
  lightSet = sCmd.next();  // Read argument

  if (strcmp(lightSet, "test") == 0) {
    for (int i=0; i < testStrip.numPixels(); i++) 
    {
      testStrip.setPixelColor(i, testStripColor);
    }
    testStrip.show();
  }
}

void lightsOff() {
  char *lightSet;
  lightSet = sCmd.next();  // Read argument

  if (strcmp(lightSet, "test") == 0) {
    testStrip.clear();  
    testStrip.show();
  }
}
1

There are 1 answers

0
Wychoniu On

Please try:

serialPort1.WriteLine("ON test");