Helper functions in Arduino
Small named functions keep loop a one-line policy.
// Helpers keep loop readable; the compiler sees the whole sketch.
const int HEAT_PIN = 4;
float readCelsius() {
int counts = analogRead(A2);
return (counts * (5.0 / 1023.0) - 0.5) * 100.0;
}
void setHeater(bool on) {
digitalWrite(HEAT_PIN, on ? HIGH : LOW);
}
void setup() {
pinMode(HEAT_PIN, OUTPUT);
}
void loop() {
setHeater(readCelsius() < 18.0);
delay(1000);
}
How it works
readCelsiusowns the TMP36 conversion arithmetic.setHeaterwraps the pin write behind a verb.loopreads as the policy: heat when below 18 C.
Keywords and builtins used here
HIGHLOWOUTPUTanalogReadboolconstdelaydigitalWritefloatintlooppinModereadCelsiusreturnsetHeatersetupvoid
The run, in numbers
- Lines
- 20
- Characters to type
- 370
- Tokens
- 88
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 81 seconds.
Step 1 of 3 in Functions & state, step 16 of 27 in Language basics.