I am using a serial prompter (the message system) on my Arduino but the command (sensor loop) defaults to off if I don't explicitly tell it to turn on and I'm trying to figure out how to default it to on then only if I turn it off will it go off.
Here's the code I tried
String command = "on";
int ledPin = 13;
int sensorPin = 4;
bool val = 0;
int currentValue;
int previousValue;
void sensor(){
val = digitalRead(sensorPin);
if (val < HIGH){
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(ledPin, LOW);
delay(1000);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(sensorPin, INPUT);
Serial.begin(9600);
delay(2000);
Serial.println("Available! Give command ('on' or 'off').");
}
void loop() {
if (Serial.available()){
command = Serial.readString();
command.trim();
command.toLowerCase();
Serial.println(command);
if(command.equals("on")){
sensor();
}
else if(command.equals("off")){
digitalWrite(ledPin, LOW);
}
}
}
Any help would be appreciated!
EDIT: Based on the discussion in the comments, you should implement a "flag" type variable that can control the logic sequence for running sensor()
or not. Instead of initially checking for the command in the loop, and then running sensor()
you can initialize your flag to "true" as the default position.
Here's how I would change your code to achieve this:
I have included a Boolean type variable called state
which will decide whether sensor()
should be run or not. The command received from serial will then change the state of this flag variable.
String command = "";
// Adding a Boolean type variable to become the "state" flag. Initialize as "true".
bool state = true;
int ledPin = 13;
int sensorPin = 4;
bool val = 0;
int currentValue;
int previousValue;
void sensor(){
val = digitalRead(sensorPin);
if (val < HIGH){
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(ledPin, LOW);
delay(1000);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(sensorPin, INPUT);
Serial.begin(9600);
delay(2000);
Serial.println("Available! Give command ('on' or 'off').");
}
void loop() {
if (Serial.available()){
command = Serial.readString();
command.trim();
command.toLowerCase();
Serial.println(command);
if(command.equals("on")){
state = true;
}
else if(command.equals("off")){
state = false;
}
}
if (state){
sensor();
}
else{
digitalWrite(ledPin, LOW);
}
}
Original approach:
If I'm understanding your problem correctly, you want ledPin
to be turned on when you run your sketch, correct?
Looking at your logic in sensor()
it seems that you want ledPin
to turn off when sensorPin
is triggered. In this case it would make sense for you to set ledPin
to HIGH in your setup function.
It can look something like this:
void setup() {
pinMode(ledPin, OUTPUT);
// Setting ledPin to on by default:
digitalWrite(ledPin, HIGH);
pinMode(sensorPin, INPUT);
Serial.begin(9600);
delay(2000);
Serial.println("Available! Give command ('on' or 'off').");
}