Character Array outputs

airpanther

Active member
Good day,

When I run the following code, I'm expecting a two very simple 8-bit outputs '00100000' and '00000100'. Each bit represents the position of a switch. I intend to convert this binary to an integer and use this to control an I2C device. Problem is, when I run the code I get random null characters, AND the low bits are always a combination of both the low bits and the high bits?! Any idea what I'm doing wrong?

Output:
HighBits: 00100000�@Y
LowBits: 0000010000100000�@Y

Any guidance is appreciated. Thank you!
Robert

Code:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void OutputBits (int DeviceNumber)//, int LEDNum)
{
  char LowValues[8];
  char HighValues[8];
  
  HighValues[0] = '0';
  HighValues[1] = '0';
  HighValues[2] = '1';
  HighValues[3] = '0';
  HighValues[4] = '0';
  HighValues[5] = '0';
  HighValues[6] = '0';
  HighValues[7] = '0';

  LowValues[0] = '0'; 
  LowValues[1] = '0'; 
  LowValues[2] = '0'; 
  LowValues[3] = '0';
  LowValues[4] = '0';
  LowValues[5] = '1';
  LowValues[6] = '0';
  LowValues[7] = '0';
  
  Serial.print("HighBits: "); Serial.println(HighValues); 
  Serial.print("LowBits: "); Serial.println(LowValues);

}

void loop() {
  // put your main code here, to run repeatedly:
  OutputBits(1);
  while(1);
}
 
The problem is Serial.print when you pass a char * argument, it expects the array to have a null byte to denote the end of the string. Even though you passed a char array, what is passed is a char pointer (i.e. the array bounds are not passed). If you bump up the size of the arrays, and add an explicit null byte, it should print fine. You can use either '\0' or just 0 to represent a null byte, i.e.:

Code:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void OutputBits (int DeviceNumber)//, int LEDNum)
{
  char LowValues[9];
  char HighValues[9];
  
  HighValues[0] = '0';
  HighValues[1] = '0';
  HighValues[2] = '1';
  HighValues[3] = '0';
  HighValues[4] = '0';
  HighValues[5] = '0';
  HighValues[6] = '0';
  HighValues[7] = '0';
  HighValues[8] = '\0';

  LowValues[0] = '0'; 
  LowValues[1] = '0'; 
  LowValues[2] = '0'; 
  LowValues[3] = '0';
  LowValues[4] = '0';
  LowValues[5] = '1';
  LowValues[6] = '0';
  LowValues[7] = '0';
  LowValues[8] = 0;
  
  Serial.print("HighBits: "); Serial.println(HighValues); 
  Serial.print("LowBits: "); Serial.println(LowValues);

}

void loop() {
  // put your main code here, to run repeatedly:
  OutputBits(1);
  while(1);
}
 
Another option that probably would work as well is to do something like: Serial.write(HighValues, 8);
Which takes an array and writes out the count of bytes specified. Note: this does not output the line ending that println() does.
 
Back
Top