Sub topic 5
Formatting Numbers: DEC, HEX, BIN, and Decimal Places
Assume you know the Arduino setup() and loop() functions, can upload a sketch, and understand basic variables and data types. This chapter focuses on how Serial.print() and Serial.println() choose a format for numeric values.
How the print functions format values
Serial.print(value) writes a value without ending the line. Serial.println(value) writes the value and then sends a newline. You can join several calls to create labeled output.
For integer values, the optional second argument selects the number base:
| Format | Meaning | Example output for `42` |
|---|---|---|
| `DEC` | Base 10, the usual format | `42` |
| `HEX` | Base 16, using `0–9` and `A–F` | `2A` |
| `BIN` | Base 2, using `0` and `1` | `101010` |
DEC, HEX, and BIN are Arduino constants. Decimal is the default, so Serial.println(42) and Serial.println(42, DEC) produce the same output.
void setup() {
Serial.begin(9600);
int value = 42;
Serial.println(value); // 42
Serial.println(value, DEC); // 42
Serial.println(value, HEX); // 2A
Serial.println(value, BIN); // 101010
}
void loop() {
}The number base changes how the same stored integer is displayed. It does not change the value in memory.
Formatting floating-point values
For a float, the second argument specifies how many digits appear after the decimal point. This is useful for sensor voltages, temperatures, and other measurements.
void setup() {
Serial.begin(9600);
float voltage = 3.14159;
Serial.println(voltage); // 3.14 on typical Arduino boards
Serial.println(voltage, 1); // 3.1
Serial.println(voltage, 4); // 3.1416
}
void loop() {
}The value is rounded for display. Formatting does not increase the measurement's accuracy. If the sensor only provides limited resolution, printing more decimal places can make the result look more precise than it is.
A common error is assuming the second argument always means decimal places:
Serial.println(42, 2); // Prints 101010, because 2 means base 2 for an integerUse a floating-point value when you want decimal places:
Serial.println(42.0, 2); // Prints 42.00Combining labels and formatted values
Build a readable line by printing a label first, then the value.
const int SENSOR_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(SENSOR_PIN);
float volts = raw * (5.0 / 1023.0);
Serial.print("raw=");
Serial.print(raw, DEC);
Serial.print(" hex=0x");
Serial.print(raw, HEX);
Serial.print(" volts=");
Serial.println(volts, 2);
delay(500);
}Hexadecimal is useful when inspecting bit patterns, register values, or addresses. Binary is useful when checking individual bits. Decimal is usually clearest for sensor readings.
Exercise
What does Serial.println(26, HEX) print, and what does Serial.println(26.0, 2) print?
Show answer
The first prints 1A. The second prints 26.00.