Code: telling the brain what to do
A board does nothing until you give it a program: a list of instructions written in a coding language. You write it on a computer in the free Arduino IDE app, then send it to the board through the USB cable. This is called uploading.
Think in "if-then"
Most IoT programs are just smart if-then rules:
- If it is dark, then turn on the light.
- If the soil is dry, then start the pump.
- If someone moves, then sound the buzzer.
Every Arduino program has two parts
setup()runs once when the board starts, like getting ready in the morning.loop()runs again and again forever, like checking your homework over and over.
Your first program: blink a light
Arduino C++
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // get the light ready
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // light ON
delay(1000); // wait 1 second
digitalWrite(LED_BUILTIN, LOW); // light OFF
delay(1000); // wait 1 second
}Text after // is a comment: a note for humans that the board ignores.
A smart night lamp in a few lines
Arduino C++
void setup() {
pinMode(13, OUTPUT); // the lamp LED is on pin 13
}
void loop() {
int light = analogRead(A0); // read the light sensor
if (light < 300) { // if it is dark...
digitalWrite(13, HIGH); // ...turn the lamp on
} else {
digitalWrite(13, LOW); // otherwise, turn it off
}
}