Arduino examples
This is a collection of resources for common examples you may need for an arduino project. In some the examples we are using the LED_BUILTIN as an output to validate the code and wiring is working as expected.
The Arduino IDE also has a lot of great built-in examples. After opening your Arduino IDE you can find them by going to File
> Examples
> ...
To setup your arduino goto Getting started with arduino
Buttons
Push button
int BUTTON = 2; // The pin on which you attach the button
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(BUTTON, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int value = digitalRead(BUTTON);
Serial.println(value);
if(value == HIGH) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
delay(10);
}
Arcade button
If you look closely on the arcade button you can see three labels next the the metal parts, COM, NO and NC.
The COM part should go the the ground (GND) and one of the NO/NC parts should be put in the pin you set in the code.
int BUTTON = 2; // The pin on which you attach the button
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(BUTTON, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int value = digitalRead(BUTTON);
Serial.println(value);
if(value == HIGH) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
delay(10);
}
Lights
LED lights
Simple
int LED = 2; // The pin on which you attach the LED
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println("Turning on LED");
digitalWrite(LED, HIGH);
delay(1000);
Serial.println("Turning off LED");
digitalWrite(LED, LOW);
delay(1000);
}
RGB
ℹ️ make sure that you are using the PWM pins of the Arduino. The PWM pins have a ~
sign with them. Read more here
int LED_RED = 6; // The pin on which you attach the red pin
int LED_GREEN = 5; // The pin on which you attach the green pin
int LED_BLUE = 2; // The pin on which you attach the blue pin
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
RGB_color(255, 0, 0); // Red
delay(1000);
RGB_color(0, 255, 0); // Green
delay(1000);
RGB_color(0, 0, 255); // Blue
delay(1000);
}
void RGB_color(int red, int green, int blue) {
Serial.print(red);
Serial.print(", ");
Serial.print(green);
Serial.print(", ");
Serial.println(blue);
analogWrite(LED_RED, red);
analogWrite(LED_GREEN, green);
analogWrite(LED_BLUE, blue);
}
Light sensor
int LDR = A0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ldrPin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int value = analogRead(LDR);
Serial.println(value);
if (ldrStatus <= 200) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
}
Distance / motion
Distance
// https://create.arduino.cc/projecthub/abdularbi17/ultrasonic-sensor-hc-sr04-with-arduino-tutorial-327ff6
int echoPin = 2; // attach pin D2 Arduino to pin Echo of HC-SR04
int trigPin = 3; //attach pin D3 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
int distance = readDistance();
if(distance > 150) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
}
int readDistance() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
return distance;
}
Rotation
int POTENTIOMETER = A0; // Pin on the board, this needs to be an ANALOG port
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(POTENTIOMETER, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int value = analogRead(POTENTIOMETER);
Serial.println(value);
if(value > 500) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
delay(100);
}
Motors
Servo
ℹ️ Not all servo motors can spin 360° but "just" 180°. Most servo motors will have a label sticked to it which will tell you the range of the motor. The wiring of the motors is the same.
non-continuous servo (180°)
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int SERVO = 9;
int pos = 0; // variable to store the servo position
void setup() {
Serial.begin(9600);
myservo.attach(SERVO); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
Serial.println(pos);
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15 ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
Serial.println(pos);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15 ms for the servo to reach the position
}
}
continuous servo (360°)
#include <Servo.h>
// Create the servo object
Servo myservo;
int SERVO = 9;
// Setup section to run once
void setup() {
Serial.begin(9600);
myservo.attach(SERVO); // attach the servo to our servo object
myservo.write(90);
}
// Loop to keep the motor turning!
void loop() {
Serial.println("Rotate counter clockwise");
myservo.write(45); // rotate the motor counterclockwise
delay(5000); // keep rotating for 5 seconds (5000 milliseconds)
Serial.println("Stop");
myservo.write(90); // stop the motor
delay(5000); // stay stopped
Serial.println("Rotate clockwise");
myservo.write(135); // rotate the motor clockwise
delay(5000); // keep rotating
}
RFID
- Download the
Easy MFR522
by Pablo Sampalo (see picture above) - Wire all pins to match the labels (MISO <---> MISO), expect for the following pins: RST, NSS and IRQ
- Put the RST pin from the RFID reader in pin 22 on the arduino
- Put the NSS pin from the RFID reader in pin 21 on the arduino
- We do not need the IRQ pin
- After downloading the
Easy MFR522
library you can select some examples by goin toFile
>Examples
>Easy MFR522
> ...
Sound
Simple speaker
/*
* Copyright 2018 Code and Make (codeandmake.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* A simple project that demonstrates how to make music using an Arduino.
*
* This code accompanies the following tutorial: https://youtu.be/Z1YvIFUIhLs
*/
// Pin to which an 8 Ohm speaker is connected (use a 150 - 220 Ohm resistor)
#define speakerPin 12
// Tempo (beats per minute)
#define bpm 96
// Gap between notes. This is expressed as percentage of time between 2 beats.
#define noteGapPercentage 10
/*
* 2D array containing the notes to be played
* A note comprises of two values:
* * The first value determines the frequency of the note.
* This is expressed as the number of a key on an 88-key piano (1 - 88)
* A number outside this range can be used (e.g. 0) to create a gap
* * The second value determines the duration:
* * 1 represents a whole note (spans 4 beats)
* * 2 represents a half note (spans 2 beats)
* * 4 represents a quarter note (spans 1 beat)
* * 8 represents an eighth note (spans 0.5 beat)
* etc.
*/
uint8_t notes[][2] = {
{35,4}, {35,4}, {42,4}, {42,4}, {44,4}, {44,4}, {42,2},
{40,4}, {40,4}, {39,4}, {39,4}, {37,4}, {37,4}, {35,2},
{42,4}, {42,4}, {40,4}, {40,4}, {39,4}, {39,4}, {37,2},
{42,4}, {42,4}, {40,4}, {40,4}, {39,4}, {39,4}, {37,2},
{35,4}, {35,4}, {42,4}, {42,4}, {44,4}, {44,4}, {42,2},
{40,4}, {40,4}, {39,4}, {39,4}, {37,4}, {37,4}, {35,2}
};
// Time between two beats in microseconds (equal to length of a quarter note)
#define beatDuration (60.0 / bpm) * 1000000L
// Time of the gap between two notes in microseconds
#define noteGap beatDuration * (noteGapPercentage / 100.0)
void setup() {
// Set the speakerPin as an output
pinMode(speakerPin, OUTPUT);
// Iterate over the notes array
for(int i = 0; i < (sizeof(notes) / sizeof(*notes)); i++) {
// pass the key number and note type
playNote(notes[i][0], notes[i][1]);
}
}
void loop() {
// Not used. Music will play once.
}
/*
* Plays an individual note.
*
* keyNumber - The key number (1 - 88)
* noteType - The note type (1, 2, 4, 8, etc.)
*/
void playNote(uint8_t keyNumber, uint8_t noteType) {
long halfPeriod = getPeriodForKey(keyNumber) / 2;
long noteDuration = beatDuration * (4.0 / noteType);
long elapsed = 0;
// While we have a note to play
while(halfPeriod > 0 && elapsed < (noteDuration - noteGap)) {
// Set speakerPin high for half of the period
digitalWrite(speakerPin, HIGH);
wait(halfPeriod);
// Set speakerPin low for half of the period
digitalWrite(speakerPin, LOW);
wait(halfPeriod);
// Update the amount of time that has elapsed
elapsed += halfPeriod * 2;
}
/*
* Gap between notes. Calculated using 'elapsed' to minimise timing errors
* and ensure that the correct gap occurs whenever getPeriodForKey() returns
* zero.
*/
wait(noteDuration - elapsed);
}
/*
* Returns the period for a key or zero for key numbers outside the range of 1 -
* 88.
*
* keyNumber - The key number (1 - 88)
*/
long getPeriodForKey(uint8_t keyNumber) {
// If the key is between 1 and 88
if(keyNumber >= 1 && keyNumber <= 88) {
// Return the period (one second divided by the frequency of the key)
return 1000000L / (pow(2.0, (keyNumber - 49.0) / 12.0) * 440.0);
}
// Otherwise return zero
return 0;
}
/*
* Delay for a number of microseconds. This is necessary because
* delayMicroseconds() has an upper limit.
*
* us - The delay in microseconds
*/
void wait(long us) {
// First delay for the number of whole milliseconds using delay()
delay(us / 1000);
// Then delay for the remainder of microseconds using delayMicroseconds()
delayMicroseconds(us % 1000);
}