Hi,
I have a project for which I want to implement a simple interface. I’m not very experimented when it comes to programming, so I decided on a C# WindowsFormsApp which I use to send commands to the Arduino via serial. After a bit of fumbling around, I made it work and control two LEDs.
String s_command;
String led_var;
String led_status;
int LED0 = 8;
int LED1 = 7;
void setup()
{
Serial.begin(115200);
pinMode(LED0, OUTPUT);
pinMode(LED1, OUTPUT);
}
void loop()
{
if (Serial.available())
{
s_command = Serial.readStringUntil('\n');
led_var = getValue(s_command, ':', 0);
led_status = getValue(s_command, ':', 1);
Serial.print(led_var);
Serial.print(":");
Serial.print(led_status);
Serial.println("");
ledControl(led_var, led_status);
}
}
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void ledControl(String ledNumber, String status)
{
if (ledNumber == "LED0")
{
if (status == "ON")
{
digitalWrite(LED0, HIGH);
}
if (status == "OFF")
{
digitalWrite(LED0, LOW);
}
}
else if (ledNumber == "LED1")
{
if (status == "ON")
{
digitalWrite(LED1, HIGH);
}
if (status == "OFF")
{
digitalWrite(LED1, LOW);
}
}
else
{
Serial.println("LED not recognized!");
}
}
When I use the Serial Monitor, it works OK, but when I use the C# app, I get this short delay (about 1 sec). I assume the delay comes from one of the functions in the Arduino code, however I’m not sure which one (both probably?), or how to improve it.
From what I read, it’d be better to use C/C++ instead of the Arduino functions, but I really don’t know how to go about using those.
So, I’d appreciate some advice on how to go about improving what I cobbled together.
Thanks!