Can't use String in digitalWrite(String,HIGH)

HI, I am newbie into programming. Trying to learn from examples and forums. This is just an example of what i want. solving this will help me a lot.


define REL1 7

String InputStr="";

void relayOn(String Relay) {

digitalWrite(Relay,LOW); //Relay is used so REL1 will be substituted. delay(3000);

}

void setup() {

pinMode(REL1,OUTPUT); Serial.begin(9600);

}

void loop() {

Serial.println("Which Relay"); delay(10000); InputStr=Serial.readString(); delay(2000); relayOn(InputStr);

}


Thank You

That because a String of "1" isn't the same as the (integer) number 1. (Nor is it the same as a real string of "1" or the char '1'.) Convert it to integer (Google it ;)).

Convert it to integer

Nonsense. Stop trying to use Strings AT ALL. There is no excuse for making a function that needs to operate on an integer value take a String.

void relayOn(int Relay)  {


  digitalWrite(Relay,LOW);  //Relay is used so REL1 will be substituted.
  delay(3000);

}
void loop() {

  Serial.println("Which Relay");
  delay(10000);
  InputStr=Serial.readString();
  delay(2000);
  relayOn(atoi(InputStr.c_str()));

}

Robin2's serial input basics thread shows how to do non blocking serial input with null terminated character arrays (C-strings not Strings).

void relayOn(int Relay)  {


  digitalWrite(Relay,LOW);  //Relay is used so REL1 will be substituted.
  delay(3000);

@boylesg:. No, according to the original code, you'd have to enter '7' to operate the relay.

boylesg: ``` void relayOn(int Relay)  {

  digitalWrite(Relay,LOW);  //Relay is used so REL1 will be substituted.   delay(3000);

} void loop() {

  Serial.println("Which Relay");   delay(10000);   InputStr=Serial.readString();   delay(2000);   relayOn(atoi(InputStr.c_str()));

}

This doesn't return the value REL1 in the relayOn function.

Please see reply #5

GrooveFlotilla:
Please see reply #5

Had to enter 7 as input. And that did. Thanks a lot people :smiley:

While learning, learn not to use String (capital S) on a system that is limited in memory. Learn to use so-called c-strings (null terminated character arrays).