1

I want to convert my String variable to a value that I can use as a pin number in

digitalwrite(pindata, boolean);

Please note that this is a NodeMCU board and its pin names are like D0, D1 etc. Not like Arduino numbers. My String might contain values like "D3", "D4", "D5" etc.

Code:

void post() {
  String data = server.arg("msg");
  Serial.println(data);
  pinPulse(data,1000); // <<-- what here wola it's a String
  server.send(200, "text/plain", "Got this data " + data);
}

void pinPulse(char pin, int pulsetime) {
  pinMode(pin, OUTPUT);
  digitalWrite(pin, 1);
  delay(pulsetime);
  digitalWrite(pin, 0);
}
1
  • That function accepts a char not a String. And why is the pin number a char and not an integer?
    – gre_gor
    Jul 24, 2018 at 13:47

1 Answer 1

3

Mapping from pin name to pin number is defined in pins_arduino.h.
Since the names are sequential, you can define the pin numbers in an array and them access them with an index.
e.g. D5 with the index 5 which has the value 14.

To convert "D5" into 5, you need first to get rid of the 'D' with .substring(1) and then convert the rest ("5") into an integer with .toInt().

static const uint8_t NAME2PIN[] = {D0, D1, D2, D3, D4, D5, D6, D7, D8, D9, D10};
//                                 16   5   4   0   2  14  12  13  15   3   1

void post() {
    String data = server.arg("msg");
    Serial.println(data);
    if (data.length() >= 2 && data[0] == 'D') { //check if it's a valid pin name
        uint8_t pin = NAME2PIN[data.substring(1).toInt()]; //skip the first character (D) and convert it to an integer
        pinPulse(pin, 1000);
        server.send(200, "text/plain", "Got this data " + data);
    }
}

void pinPulse(uint8_t pin, int pulsetime) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, 1);
    delay(pulsetime);
    digitalWrite(pin, 0);
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.