“Hello, World!” is the most basic “program” developers use to test their understanding of a piece of hardware or programming language. On the Arduino, the “blink” sketch stands as the most basic bit of code that will run with human-readable output.
Let’s get our feet wet with the Arduino platform by assembling a slightly more complex version of “blink” using an external LED.
The Circuit:
Connect a jumper wire from pin 2 to the anode of the LED. The anode is the “+” side of the LED and has a longer leg. The easy way to remember this is that the extra little bit of lead can be clipped off to make a plus sign on the leg.
Connect a 220R resistor to the cathode of the LED. We’re using a 220R resistor because it will allow the most voltage to come through while reducing the overall current. I’ll explain how this works in a future video.
Connect the resistor back to the ground pin of the Arduino with another jumper.
The Sketch:
/*
"Hello World" Blink Sketch
Turns an LED on for one second, then off for one second, repeatedly.
modified 8 May 2014
by Scott Fitzgerald
modified 2 Sep 2016
by Arturo Guadalupi
modified 8 Sep 2016
by Colby Newman
modified 3 Aug 2019
by Matthew Eargle
This example code is in the public domain.
*/
int ledPin = 2; //Define ledPin as integer variable with value of 2
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin ledpin as an output.
pinMode(ledPin, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Can you determine what the Arduino is doing at each line in the code?
What happens if we change the values of some variables?
What happens if we change the time parameter of the delay?
In the previous lesson, we learned how to have an Arduino “talk” to us by blinking an LED. Now, we’re going to send signals to the Arduino by pressing a button. After completing this lesson, you should be able to attach any digital sensor to the Arduino and get some usable result.
To verify that the Arduino is receiving our signals properly, we’re going to use those signals to trigger an LED and a message in the serial monitor.
The Circuit:
Connect a jumper wire from the +5V pin to one side of the tactile switch. The adjacent (unswitched) leg of the switch is connected to the anode (+) of the LED. A 330R resistor provides over-current protection for the LED and is connected from the cathode to ground.
The switched side of the tactile switch connects with a jumper wire to pin 2 on the Arduino.
Connect the resistor back to the ground pin of the Arduino with another jumper.
The Sketch:
/*
Input!
Reads a digital input on pin 2, lights an LED, and prints the result to the Serial Monitor
This example code is in the public domain.
*/
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1); // delay in between reads for stability
}
In the previous lesson, we learned how to use a button to create a simple digital input on the Arduino. We also learned how to use the serial monitor to display the button state. In this lesson, we’re going to use a potentiometer to create an analog input and read it on the serial monitor.
The Circuit:
Connect a jumper wire from the +5V pin to pin 1 (the left pin, input, if you’re looking down the shaft) of a 10k potentiometer. Connect a second jumper wire from pin 2 (the right pin, ground) to the ground pin on the Arduino. Connect a third jumper from pin 3 (center pin, signal) to A0 on the Arduino.
The Sketch:
/*
AnalogReadSerial
Reads an analog input on pin 0, prints the result to the Serial Monitor.
Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}
Now, with just a few more lines of code, you can determine the actual voltage going through the potentiometer and into the Arduino:
/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the Serial Monitor.
Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
So far, in this series, we have learned to read and write digital information with an Arduino. We have also learned to read analog information with the Arduino and a potentiometer. In this video, we will learn how to send pseudo-analog signals from the Arduino to a device by fading the light on an LED.
The Circuit:
Connect a jumper wire from pin 9 on the Arduino (9 is an analog out pin as denoted by the tilde [~] sign) to a 220R resistor. Connect the other end of the resistor to the anode of an LED. Connect the cathode of the LED to the ground pin of the Arduino using another jumper wire.
The Sketch:
/*
Fade
This example shows how to fade an LED on pin 9 using the analogWrite()
function.
The analogWrite() function uses PWM, so if you want to change the pin you're
using, be sure to use another PWM capable pin. On most Arduino, the PWM pins
are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
This example code is in the public domain.
*/
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
What happens if we change the delay attribute?
What happens if we change the value of the fadeAmountvariable?
As a challenge, see if you can figure out how to use a potentiometer to control the fade effect–either through the rate of the fade or the brightness.
Up until this point in the series, we have been using LEDs to manipulate light with the Arduino. For this project, we’re going to incorporate a piezo buzzer to manipulate sound for Maximum Annoyance Value! The piezo is a small element that vibrates in the presence of an electric current or–alternatively–generates an electric current when it vibrates.
The Circuit:
Connect jumper wires from the +5V and GND pins on the Arduino to the bus rails along one side of the breadboard. Connect a jumper from the +5V rail to one side of a tactile switch. Connect the other side of the switch with a jumper to one side of the next switch, and so on, until you have wired all 4 switches in series. Connect a jumper from the last switch terminal to pin A0 on the Arduino.
Connect the 220R, 1KR, and 1MR resistors to the switches as shown in the diagram.
Connect the ground lead of the piezo buzzer to the ground rail and the positive lead to pin 8 on the Arduino via jumper wires.
The Sketch:
/*
Play It Again, Sam
A rudimentary Arduino synthesizer
created 13 Sep 2012
by Scott Fitzgerald
This example code is part of the public domain.
*/
// create an array of notes
// the numbers below correspond to the frequencies of middle C, D, E, and F
int notes[] = {262, 294, 330, 349};
void setup() {
//start serial communication
Serial.begin(9600);
}
void loop() {
// create a local variable to hold the input on pin A0
int keyVal = analogRead(A0);
// send the value from A0 to the Serial Monitor
Serial.println(keyVal);
// play the note corresponding to each value on A0
if (keyVal == 1023) {
// play the first frequency in the array on pin 8
tone(8, notes[0]);
} else if (keyVal >= 990 && keyVal <= 1010) { // play the second frequency in the array on pin 8 tone(8, notes[1]); } else if (keyVal >= 505 && keyVal <= 515) { // play the third frequency in the array on pin 8 tone(8, notes[2]); } else if (keyVal >= 5 && keyVal <= 10) {
// play the fourth frequency in the array on pin 8
tone(8, notes[3]);
} else {
// if the value is out of range, play no tone
noTone(8);
}
}
Elegoo, a manufacturer of Arduino-clone electronics and kits based in Shenzhen, China, approached me to do review their new Arduino-powered Smart Robot Car Kit. It’s a neat little kit–something fun to put together on a weekend and mess around with.
As for the meat-and-potatoes, it’s got a few bugs to work out. The car runs great with the included IR remote control, and can easily be programmed to use various sensors or just traverse pre-programmed missions (a la the classic Big Trak toy from Milton Bradley). The ultrasonic obstacle detection/avoidance mode also works like a champ. However, I couldn’t get the Bluetooth functionality working. It may be that the included Bluetooth module is not compatible with the latest versions of Android (as my cursory research and troubleshooting has led me to believe) due to updates in security protocols with Oreo and Pie. Your mileage may vary, though. Also of note was the line-tracking module which had a faulty LED and would only allow the car to spin in circles.
My contact at Elegoo was polite and provided me with some generic troubleshooting information, but they were unwilling to replace the faulty parts. If they’re not going to do it for the review, I would assume that they would be unwilling to do it for the consumer as well, so please take note. That being said, this is the first time that I have had as much trouble with an Elegoo-branded product, as I have used their Arduino clones and passive components in the past with no issue. I hope that this experience was a fluke, but only time will tell. I do want to emphasize that these sorts of problems can and do happen with any distributor, so it is not a mark against their quality per se.
At the end of the day, I’ll likely use these parts for some other projects (the geared motors and control boards may come in quite handy later), and have no real qualms about purchasing through Amazon as you’re protected by their returns policy (provided you purchase from the listing “fulfilled by Amazon”). So, give it a try. It’s a lot of fun to build, and makes a great transition from static Lego kits to full-fledged electronics hackery!
Building on our last project, we’re going to find a new way to control our piezo buzzer. Rather than using buttons, we’re going to use the variable resistance of a photoresistor to create different tones–a sort of light-activated Theremin. A photoresistor is an element that changes resistance based on the amount of light it detects. The more light, the less resistance. This device will convert those resistance values into various tones for our Theremin.
The Circuit:
Connect a jumper wire from +5V and GND to their respective busses on the breadboard. Connect a jumper from the +5V bus rail to one side of the photoresistor. This part is not polarized, so it doesn’t matter which side. Connect the opposite side of the photoresistor to GND via a 10K resistor and to A0 via another jumper.
Connect D8 to the positive leg of the piezo via a jumper and connect the ground leg of the piezo to GND.The Sketch:
int sensorValue;
// variable to calibrate low value
int sensorLow = 1023;
// variable to calibrate high value
int sensorHigh = 0;
// LED pin
const int ledPin = 13;
void setup() {
// Make the LED pin an output and turn it on
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
// calibrate for the first five seconds after program runs
while (millis() < 5000) { // save the maximum sensor value sensorValue = analogRead(A0); if (sensorValue > sensorHigh) {
sensorHigh = sensorValue;
}
// save the minimum sensor value
if (sensorValue < sensorLow) {
sensorLow = sensorValue;
}
}
//turn the LED off, signaling the end of the calibration
digitalWrite(ledPin, LOW);
}
void loop() {
//read the input from A0 and store it in a variable
sensorValue=analogRead(A0);
// map the sensor values to a wide range of pitches
int pitch=map(sensorValue, sensorLow, sensorHigh, 50, 4000);
// play the tone for 20 ms on pin 8
tone(8, pitch, 20);
// wait for 10ms
delay(10);
}
The Arduino, despite its simplicity, is a very powerful electronics platform and it can do so much more than blink LEDs or make noises with a buzzer. In this project, we’re going to connect a simple character LCD to the Arduino and use it to display some randomly selected custom text.
The Circuit:
Start by connecting +5V and GND to their respective busses on the breadboard. Use a jumpers to connect one side of a tactile switch to +5V and the other side to D8. Also connect a 10KR resistor to GND to act as a pull-down and prevent the pin from floating.
Connect a 10KR rotary potentiometer’s + and – pins to +5V and GND respectively while connecting the drain pin to pin 3 on the LCD. Finally, connect the LCD pins as shown in the schematic below:
The Sketch:
#include
LiquidCrystal lcd(12,11,5,4,3,2); // generates an instance in the lcd
const int switchPin = 6;
int switchState = 0;
int prevSwitchState = 0;
int reply;
void setup() {
lcd.begin(16,2);
pinMode(switchPin, INPUT);
lcd.print("I AM THE GREAT");
lcd.setCursor(0,1); // changes the Cursor to continue writing in the second row
lcd.print("ZOLDUINO");
}
void loop() {
switchState=digitalRead(switchPin);
if (switchState != prevSwitchState) {
if (switchState == LOW) {
reply = random(8);
lcd.clear(); // clears the screen
lcd.setCursor(0,1);
switch(reply){ // the program will enter the case
assigned to the switch
case 0:
lcd.print("Si");
break;
case 1:
lcd.print("It's probable");
break;
case 2:
lcd.print("It is certain");
break;
case 3:
lcd.print("Outlook good");
break;
case 4:
lcd.print("It is unclear");
break;
case 5:
lcd.print("Ask again");
break;
case 6:
lcd.print("I have no idea");
break;
case 7:
lcd.print("No");
break;
}
}
}
Now that we’ve learned the basics of digital and analog signalling on an Arduino, let’s start exploring with different kinds of sensors. The ultrasonic sensor module is a rudimentary SONAR device that emits and detects a particular high-frequency sound pulse. We can use this pulse to determine the location and relative position of objects.
The Circuit:
Using jumpers, connect +5V on the Arduino to VCC on the sensor and GND to GND. Connect the sensor’s Trigger and Echo pins to the Arduino at D2 and D4 respectively.
As we’ve learned throughout this series, a microcontroller like the one on the Arduino is basically a rudimentary computer that can execute instruction sets very quickly because it doesn’t have to load all those pesky applications and operating systems. What better capstone for this basic course than to combine everything that we’ve learned so far and build our own rudimentary mathematical computation device: a simple calculator!
For this calculator, we’re going to use a basic 4×4 matrix keypad and attach it to the Arduino in such a way that we only need to use 8 pins to cover the functions of 16 individual switches!
The Circuit:
Connect the character LCD and potentiometer as we learned in the Liquid Crystal Ball project, using the Arduino pins shown in the diagram. You can use a breadboard to create busses for +5V and GND.
Connect the pins of the keypad to pins D0-D8 on the Arduino as shown.
The Sketch:
#include //Header file for LCD from https://www.arduino.cc/en/Reference/LiquidCrystal
#include //Header file for Keypad from https://github.com/Chris--A/Keypad
const byte ROWS = 4; // Four rows
const byte COLS = 4; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
{'7','8','9','D'},
{'4','5','6','C'},
{'1','2','3','B'},
{'','0','#','A'}
};
byte rowPins[ROWS] = { 0, 1, 2, 3 };// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte colPins[COLS] = { 4, 5, 6, 7 }; // Connect keypad COL0, COL1 and COL2 to these Arduino pins.
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); // Create the Keypad
const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Pins to which LCD is connected
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
long Num1,Num2,Number;
char key,action;
boolean result = false;
void setup() {
lcd.begin(16, 2); //We are using a 162 LCD display
lcd.print("DIY Calculator"); //Display a intro message
lcd.setCursor(0, 1); // set the cursor to column 0, line 1
lcd.print("-CircuitDigest"); //Display a intro message
delay(2000); //Wait for display to show info
lcd.clear(); //Then clean it
}
void loop() {
key = kpd.getKey(); //storing pressed key value in a char
if (key!=NO_KEY)
DetectButtons();
if (result==true)
CalculateResult();
DisplayResult();
}
void DetectButtons()
{
lcd.clear(); //Then clean it
if (key=='') //If cancel Button is pressed
{Serial.println ("Button Cancel"); Number=Num1=Num2=0; result=false;}
if (key == '1') //If Button 1 is pressed
{Serial.println ("Button 1");
if (Number==0)
Number=1;
else
Number = (Number10) + 1; //Pressed twice
}
if (key == '4') //If Button 4 is pressed
{Serial.println ("Button 4");
if (Number==0)
Number=4;
else
Number = (Number10) + 4; //Pressed twice
}
if (key == '7') //If Button 7 is pressed
{Serial.println ("Button 7");
if (Number==0)
Number=7;
else
Number = (Number10) + 7; //Pressed twice
}
if (key == '0')
{Serial.println ("Button 0"); //Button 0 is Pressed
if (Number==0)
Number=0;
else
Number = (Number10) + 0; //Pressed twice
}
if (key == '2') //Button 2 is Pressed
{Serial.println ("Button 2");
if (Number==0)
Number=2;
else
Number = (Number10) + 2; //Pressed twice
}
if (key == '5')
{Serial.println ("Button 5");
if (Number==0)
Number=5;
else
Number = (Number10) + 5; //Pressed twice
}
if (key == '8')
{Serial.println ("Button 8");
if (Number==0)
Number=8;
else
Number = (Number10) + 8; //Pressed twice
}
if (key == '#')
{Serial.println ("Button Equal");
Num2=Number;
result = true;
}
if (key == '3')
{Serial.println ("Button 3");
if (Number==0)
Number=3;
else
Number = (Number10) + 3; //Pressed twice
}
if (key == '6')
{Serial.println ("Button 6");
if (Number==0)
Number=6;
else
Number = (Number10) + 6; //Pressed twice
}
if (key == '9')
{Serial.println ("Button 9");
if (Number==0)
Number=9;
else
Number = (Number10) + 9; //Pressed twice
}
if (key == 'A' || key == 'B' || key == 'C' || key == 'D') //Detecting Buttons on Column 4
{
Num1 = Number;
Number =0;
if (key == 'A')
{Serial.println ("Addition"); action = '+';}
if (key == 'B')
{Serial.println ("Subtraction"); action = '-'; }
if (key == 'C')
{Serial.println ("Multiplication"); action = '';}
if (key == 'D')
{Serial.println ("Devesion"); action = '/';}
delay(100);
}
}
void CalculateResult()
{
if (action=='+')
Number = Num1+Num2;
if (action=='-')
Number = Num1-Num2;
if (action=='')
Number = Num1Num2;
if (action=='/')
Number = Num1/Num2;
}
void DisplayResult()
{
lcd.setCursor(0, 0); // set the cursor to column 0, line 1
lcd.print(Num1); lcd.print(action); lcd.print(Num2);
if (result==true)
{lcd.print(" ="); lcd.print(Number);} //Display the result
lcd.setCursor(0, 1); // set the cursor to column 0, line 1
lcd.print(Number); //Display the result
}
Congratulations!
If you have completed all 9 lessons in this course, then you have completed the Arduino for Kooks basic-level course! You have learned most of the wiring and programming rudiments necessary to go on and build your very own projects with the Arduino platform!
As a reward for your efforts, I have designed a “merit badge” that you can attach to your EDC, patch wall, or a sweet hacker jacket. You’ve worked hard to achieve it, so show off your new skill set!