I've made a program to communicate to my Arduino in C#.
A very simple version of this worked as expected using these commands:
port.Write("1"); //(0, 1, 2, 3 etc..)
Now i've expanded on this by being able to send multiple characters to my arduino to construct words using an Array, but for some reason this only works when using the serial monitor and not with my C# program.
Here's the code: (Simply type LED to start controlling digital output 13, then use 0/1 to turn the LED off or on.)
char incByte;
char bufferArray[5];
String LEDfunction;
int index;
int LEDstate;
int blinkRate;
bool blinkState = false;
String aString;
String menuChoice = "X";
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
Serial.print("Setting up\n\n");
}
void byteConstructor(byte b) //Here multiple characters are turned into a string
{
Serial.print("Building Array string");
delay(100);
switch (b)
{
case '\n':
bufferArray[index] = 0;
aString = bufferArray; //Array to string
index = 0;
break;
default:
if(index < 4)
bufferArray[index++] = b;
break;
}
}
void loop()
{
if (Serial.available()>0) {
byteConstructor(Serial.read());
if(aString == "LED") menuChoice = "LED";
if(menuChoice == "LED")
{
LEDfunction = aString;
if(LEDfunction == "0") LEDstate = 0;
if(LEDfunction == "1") LEDstate = 1;
if(LEDfunction == "2") blinkState = false;
if(LEDfunction == "3") blinkState = true;
if(LEDfunction == "EXIT") menuChoice = "X";
}
}
if(blinkState == true)
{
Serial.print("Blinking\n");
delay(500);
digitalWrite(13, 0);
delay(500);
}
if(blinkState == false)
{
delay(500);
}
digitalWrite(13, LEDstate);
Serial.print("Latest input: ");
Serial.println(aString);
Serial.print("end of the loop\n");
}
Again this works as expected through the Arduino serial monitor but not when using my C# program, why is that?