Here is modified version of Blink example

#define D8  13

String p = "D8";

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(D8, OUTPUT);

// the loop function runs over and over again forever
void loop() {
  byte pin[2];
  p.getBytes(pin, sizeof(pin)); 

  digitalWrite(D8, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(D8, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second

D8 defined above is a byte of length 2. So LED turns on/off if I mention D8 on digitalWrite(D8, HIGH). Similarly I am getting the same byte D8 from String p = "D8", and converting it into byte of length 2, but assigning pin to digitalWrite(pin, HIGH/LOW) doesn't works. Has anyone tried something similar before ? any help would be appreciated :)

  • digitalWrite(pin, value) is expecting an unsigned 8 bit integer for the pin parameter ......... it is actually unclear what you are trying to do ....... also, ` doesn't works` does not describe what actually happens .... if you got an error, then why did you not say anything about it?
    – jsotola
    Jan 10 '19 at 3:13

C and C++ programs get compiled in multiple passes through various programs/steps. One of the first is the C Preprocessor, which handles the #define preprocessor directive.

It's basically a big find/replace function. After the preprocessor is done, anywhere you had D8 outside of a string literal, would have the value 13. It's not a variable or a string -- it's simply the number 13.

But the String p, which has content "D8" doesn't get replaced by the #define directive because it's part of a string, and the preprocessor doesn't modify strings in that way.

Also, p converted to a byte array of length 2 does not have anything like 13 as the value. It has 0x44 and 0x38 (or, in decimal, 68 (ASCII 'D') and 56 (ASCII '8')). Disregarding that digitalWrite() and pinMode() do not accept byte arrays, only bytes, you are passing in a byte that doesn't represent pin 13.

If you want to assign the pin via a string, then you would need to use programming to examine the string and pick the right byte value, and each possible value would have to be explicitly enumerated and checked for.

Your Answer

