2

I need to print 4-bit long numbers, these numbers are Binary numbers frome 0 to 16 (0000, 0001, 0010, ...).

PROBLEMS:

Considering this code:

char array[] = {'0000', '0001', '0010', '0011'};
int i;

void setup() {
  Serial.begin(9600); 
}

void loop() {
  while (i < 4){
    Serial.println(array[i]);
    i++;
  }
}

The serial monitor outputs:

0
1
0
1

My expected output is:

0000
0001
0010
0011

It seems that only the first "character" of each element of the array is read.

QUESTION: How can I print the entirety of each element like in my expected output?

After some reasearch, I found this:

Arduino serial print

which then refers to using PROGMEM but I'm not sure if this is what I need or if there is a simpler solution to my problem.

3
  • 1
    Multi-character constants like e.g. '0000' are implementation-defined in how they work. Please don't use such. If you want multiple characters, use strings instead. Commented Nov 11, 2020 at 16:53
  • 1
    As for one of the problem with such constants, think about that on most systems (Arduino included) char is a single byte. How would you fit four characters into a single byte? Commented Nov 11, 2020 at 16:54
  • do you ignore sketch_nov11b.ino:1:17: warning: character constant too long for its type char array[] = {'0000', '0001', '0010', '0011'};? Commented Nov 11, 2020 at 18:44

1 Answer 1

1

As mentioned in the comments, don't use multi-character constants (the ones you used, with single quotes); they might kill puppies. Single quotes are for character constants, like 'a'.

You can use strings (with double quotes), or real binary numbers without trickery; the latter will print without leading zeros.

This code example does both, so pick what you need:

const char* array1[] = {"0000", "0001", "0010", "0011"}; // strings
uint8_t array2[] = {0b000, 0b0001, 0b0010, 0b0011};      // binary numbers
int arraySize = sizeof(array1) / sizeof(array1[0]);
    
void setup() {
  Serial.begin(9600);
  while (!Serial);
    
  Serial.println("Print the strings:");  
  int i = 0;
  while (i < arraySize){
    Serial.println(array1[i]);
    i++;
  }
      
  Serial.println("\nPrint the binary numbers (note: no leading zeroes):");
  i = 0;
  while (i < arraySize){
    Serial.println(array2[i], BIN);
    i++;
  }
      
}
    
void loop() {
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works, that's exactly what i needed, thank you for your help I didn't know it was possible to create an array of strings like you did

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.