Sub topic 2
Formatting numbers: DEC, HEX, BIN, and decimal places
This chapter assumes you can upload a sketch, write setup() and loop(), use analogRead() and if statements, and open the Serial Monitor at a matching baud rate.
Formatting numbers with print and println
Serial.print() sends text without a newline. Serial.println() sends the same text and adds a newline. Both accept an optional second argument. For integers, it selects the number base (DEC, HEX, BIN, or OCT). For floats, it sets the number of decimal places.
void setup() {
Serial.begin(9600);
Serial.println(42); // 42
Serial.println(42, HEX); // 2A
Serial.println(42, BIN); // 101010
Serial.println(3.14159, 2); // 3.14
}
void loop() {
}HEX and BIN output is useful when you check register bits or the state of several pins at once.
Saving RAM with the F() macro
The F() macro keeps a string literal in flash memory, the board's program storage, instead of copying it into SRAM, the working memory. An Uno has 2 KB of SRAM, so long messages can exhaust it. Wrap constant text in F() when you pass it to Serial.print().
// Costs RAM: the string is copied into SRAM
Serial.println("Sensor started");
// Saves RAM: the string stays in flash
Serial.println(F("Sensor started"));Tracing your sketch with debug prints
A debug print shows a variable's value or marks a point the code reached. Wrap these prints in macros so you can switch them off later.
#define DEBUG 1
#if DEBUG
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
int counter = 0;
void setup() {
Serial.begin(9600);
DEBUG_PRINTLN(F("setup started"));
}
void loop() {
counter++;
DEBUG_PRINT(F("loop count: "));
DEBUG_PRINTLN(counter);
delay(1000);
}Displaying sensor readings clearly
Label each value, format the voltage with two decimal places, and use F() for the labels. This example assumes a 5 V board and a sensor on A0.
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(F("raw="));
Serial.print(raw);
Serial.print(F(" volts="));
Serial.println(volts, 2);
delay(500);
}Exercise
Your sketch prints Serial.println(255, HEX);. What appears in the Serial Monitor, and why would you choose HEX over DEC here?
Show answer
It prints FF. HEX matches byte-oriented values such as register bits, where each byte is written as two hex digits.