String command; //Define the string variable "command"
void setup() {
// put your setup code here, to run once:
pinMode(5, OUTPUT); //Set pin 5 as MOSFET Gate signal pin
pinMode(13, OUTPUT); //Set pin 13 to use onboard LED as a waiting for command status LED
digitalWrite(5, LOW); //Start with MOSFET off
digitalWrite(13, LOW); //Star with status LED off
Serial.begin(9600); //Start Serial comm for sending commands
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("What's your command?"); //Ask for a command in the Serial Monitor
while (Serial.available()==0) { //Wait for user input stopping the code
digitalWrite(13, HIGH); //Blink the onboard LED indicating that the code is waiting for user input
delay(100);
digitalWrite(13, LOW);
delay(100);
}
command=Serial.readString(); //Save the Serial Monitor String command to the "command" variable as a String
Serial.println("data read"); //Confirm Serial Monitor input
Serial.println(command); //Print the command sent over the Serial Monitor to confirm the data received
if (command=="On") { //Turn the MOSFET on
digitalWrite(5, HIGH);
}
else if (command=="Off") { //Turn the MOSFET off
digitalWrite(5, LOW);
}
else { //Provide feedback for a wrong command
Serial.println("Wrong command!");
}
}
int command; //Define the int variable "command"
void setup() {
// put your setup code here, to run once:
pinMode(5, OUTPUT); //Set pin 5 as MOSFET Gate signal pin
pinMode(13, OUTPUT); //Set pin 13 to use onboard LED as a waiting for command status LED
digitalWrite(5, LOW); //Start with MOSFET off
digitalWrite(13, LOW); //Star with status LED off
Serial.begin(9600); //Start Serial comm for sending commands
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("What's your command?"); //Ask for a command in the Serial Monitor
while (Serial.available()==0) { //Wait for user input stopping the code
digitalWrite(13, HIGH); //Blink the onboard LED indicating that the code is waiting for user input
delay(100);
digitalWrite(13, LOW);
delay(100);
}
command=Serial.parseInt(); //Save the Serial Monitor imput command to the "command" variable as an int
Serial.println("data read"); //Confirm Serial Monitor input
Serial.println(command); //Print the command sent over the Serial Monitor to confirm the data received
if (command==1) { //Turn the MOSFET on
digitalWrite(5, HIGH);
}
if (command==2) { //Turn the MOSFET off
digitalWrite(5, LOW);
}
else { //Provide feedback for a wrong command
Serial.println("Wrong command!");
}
}
And the Serial Monitor output:
What's your command?
data read
1
What's your command?
data read
0
Wrong command!
What's your command?
data read
2
What's your command?
data read
0
Wrong command!
What's your command?
Also, anyone knows how to avoid the multiple Serial Monitor outputs?
I tested this with "String" variables to be able to get this fixed.