ok so if i input something like "turn on led" and put it into the Arduino uno r3, it turns on an LED. how would i do it?
A great place to start learning how to do that is the Arduino Serial Input Basics tutorial.
Hint: simpler commands make the programming easier, like
LED 1
or
LED 0
to turn on and off the LED, respectively.
Here are several examples on to do it from @Robin2 and others, impplemented as Wokwi simulations:
I would suggest using a library like cmdArduino:
how about
const int ledPin = 13; // Pin for LED
enum { Off = HIGH, On = LOW };
void loop ()
{
if (Serial.available ()) {
char buf [90];
int n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
buf [n] = '\0'; // terminate with nul
if (! strcmp (buf, "turn on led"))
digitalWrite (ledPin, On);
}
}
void setup () {
Serial.begin (9600);
pinMode (ledPin, OUTPUT);
digitalWrite (ledPin, Off);
Serial.println (Off);
}
so now you want a command to turn the led off
const int ledPin = 13; // Pin for LED
enum { Off = HIGH, On = LOW };
void loop ()
{
if (Serial.available ()) {
char buf [90];
int n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
buf [n] = '\0'; // terminate with nul
if (! strcmp (buf, "turn on led")) {
digitalWrite (ledPin, On);
Serial.println (" on");
}
else if (! strcmp (buf, "turn off led")) {
digitalWrite (ledPin, Off);
Serial.println (" off");
}
}
}
void setup () {
Serial.begin (9600);
pinMode (ledPin, OUTPUT);
digitalWrite (ledPin, Off);
Serial.println ("cmds: on and off");
}
that's a lot of typing, and what if there's more than one LED, and what if the pins are not LED. what about a more generic cmd that takes a pin # and on/off
const byte Pins [] = { 13, 12, 11, 10 };
const int Npin = sizeof(Pins);
enum { Off = HIGH, On = LOW };
// -----------------------------------------------------------------------------
void loop ()
{
if (Serial.available ()) {
char buf [90];
int n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
buf [n] = '\0'; // terminate with nul
char cmd [9];
int pin;
sscanf (buf, "%s %d", cmd, &pin);
if (! strcmp (cmd, "on"))
digitalWrite (pin, On);
else if (! strcmp (cmd, "off"))
digitalWrite (pin, Off);
Serial.print (" pin ");
Serial.print (pin);
if (Off == digitalRead (pin))
Serial.println (" off");
else
Serial.println (" on");
}
}
// -----------------------------------------------------------------------------
void setup () {
Serial.begin (9600);
for (int n = 0; n < Npin; n++) {
pinMode (Pins [n], OUTPUT);
digitalWrite (Pins [n], Off);
}
Serial.println ("cmds: cmd #");
}