Polymood
Polymood

Reputation: 461

ARDUINO: Serial.print a multiple-character element

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.

Upvotes: 2

Views: 8065

Answers (1)

ocrdu
ocrdu

Reputation: 2183

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() {
}

Upvotes: 1

Related Questions