Basic Course On Arduino, 2024
Basic Course On Arduino, 2024
Copyright Notes
All trademarks shown belong to their rightful owners; third
party trademarks, product names, trade names, corporate
names and company names mentioned may be trademarks
of their respective owners or registered trademarks of other
companies and have been used for explanatory purposes
only and for the benefit of the owner, without any purpose
of infringement of the Copyright rights in force. What is
reported in this document is the property of Roberto
Francavilla, Italian and European copyright laws are
applicable to it - any texts taken from other sources are also
protected by Copyright and owned by their respective
Owners. All information and content (text, graphics and
images, etc.) reported are, to the best of my knowledge, in
the public domain. If, unintentionally, copyrighted or
infringing material has been posted please notify me by
email at info@bemaker.org and I will promptly remove it.
THE BOOK WAS TRANSLATED FROM ITALIAN INTO YOUR LANGUAGE BY
ARTIFICIAL ITELLIGENCE. THE TRANSLATION IN SOME PLACES MAY NOT
BE ACCURATE ESPECIALLY IN THE SOFTWARE CODE PARTS. FOR THIS
REASON AFTER EACH TUTORIAL THERE IS A LINK FROM WHICH TO
DOWNLOAD THE CORRECT SOFTWARE CODE. IN ADDITION THE BOOK IS
SOLD AT AN EXTREMELY LOW PRICE AND IN THE OFFERS IT IS EVEN
FREE. I HOPE YOU APPRECIATE THIS GESTURE OF MINE IN CHOOSING
MY BOOK ANYWAY, BECAUSE I AM SURE YOU WILL FIND IT, IN SPITE OF
EVERYTHING, VERY INTERESTING.
FOR ANY INFORMATION: info@bemaker.org
Roberto Francavilla
Preparing our Electronics and Robotics Lab.
As the first activity of the Course, we need to prepare our
Laboratory, and to do this we need to take all the materials
from our Starter Kit out of the packaging.
We check that all the materials that will be used in the
various projects are present:
We also need a PC (desktop or notebook is indifferent, but I
suggest with Windows 10 installation):
You also need to have a set of screwdrivers with magnetic
Phillips and flat heads (preferably different sizes):
As you can see from the picture on the web page above,
there are the different versions of the IDE for: Windows,
Mac, Linux,.
What is shown below is the procedure for Windows; for
other systems, the procedure is almost identical.
Clicking on Ports (COM & LPT) shows which COM port the
device is connected to.
At this point we return to the Arduino IDE, go to Tools -- →
COM Ports and select the port to which our device is
connected.
So we have finished the most boring part, don't worry from
now on there will be lots of new things to learn and have
fun.
Well begun is half done
Our ambitious goal is to become Makers !
That is, implementers of our electronic and robotic projects,
and I am sure we will succeed.
The following lessons, based on practical projects, are set
up in such a way that theoretical topics are explained
several times, even on different practical projects. In this
way, even if a topic might at first be unclear or particularly
difficult to understand, don't worry.... GO AHEAD!!!
In fact you will surely find the same topic in another
application, perhaps easier to learn.... And so you will find
yourself saying.... ahh!...so that's how it works...that thing I
didn't understand at project # .......
Also I want to remind you that through the email you will
have the opportunity to get in touch with me, indeed I
would be happy to, so don't delay when you need
clarification, or even give me suggestions (which will always
be welcome) and also to elaborate on some topic that
needs clearer explanations....
Finally, since I do not want to bore you with all these
premises, the last message is about the methodology of
explaining the lectures; it is my intention to avoid using
technical terms except those that are strictly necessary and
to try to explain their meaning. Even for the theoretical
parts, I will try to avoid going into details of physics and
chemistry and will keep a suitable and congruous level of
explanation with school bases for children 12 years old and
up.
At this point we begin to learn about the tools we will use in
our Maker training.
What is Arduino
Arduino is a kind of small PC, it has a processor (a
microcontroller to be exact), memory (like the RAM and
Hard Disk of a PC), a motherboard, and connectors for
signal inputs and outputs that go to external peripherals
which can be sensors, actuator modules such as electric
motors, etc. There are different types of boards, depending
on certain features, for example, there are boards that
already have WiFi module built in, those that have GPS,
etc.. among the most popular is the Arduino UNO R.3, a
basic development board that can be integrated with any
type of module. Because the Arduino project is open source,
many other manufacturers have made their own UNO R.3
board:
Ohm's law.
At this point, we can already identify one of the earliest
laws of electrical engineering, namely: for the same voltage
(thus the jump in the waterfall's elevation), the higher the
resistance (i.e., the more rocks and impediments to water
flow), the lower the electric current (i.e., there is less water
flow). This law of electrical engineering is called Ohm's law
and is represented as follows:
The inverse formulas are:
and
What is an LED.
Pay attention!
The 220 Ohm resistor is identified by the colored rings,
specifically if the resistor has 5 colored rings, it must have
the rings colored as follows: red-red-black-brown. If the
resistor has 4 colored rings, then the colors of the rings
must be: red-red-brown and then a silver or gold colored
ring. In the next lesson we will learn how to read the values
of resistors through the use of the color chart.
Breadboard
is a board made of insulating material with many small
holes. There are commercially available of different sizes,
the most common one being the 400-hole one. The various
small holes are electrically connected to each other in a
special way that I will show you later. Basically, in these
small holes the terminals of the various electronic
components are inserted and without soldering, thus saving
considerable time and especially reuse of components, it
allows the connection between the various electronic
components.
In fact, the Breadboard is used to experiment with the
functionality of the circuits that makers develop with the
possibility of reusing components and the speed of
modifying and trying out different circuit solutions. As can
be seen from the photo, metal strips arranged horizontally
and vertically allow connections between holes in the same
horizontal and vertical row.
Breadboard columns are identified by numbers, rows by
uppercase letters.
The only rows whose holes are all electrically connected to
each other are those identified with "+" and " -." The holes
in the other rows (A, B, C, D, E, F, G, H, J), as can be seen
from the picture above and from the lines in the figure, are
not connected to each other horizontally, but they are
connected vertically, that is, in columns. This means that
inserting a pin in column 6 to any line in the group between
A and E, is the same thing. The Breadboard, as you can
always see from the figure, is divided into two parts that are
isolated from each other.
Project 3 - Hello World
void loop()
{
digitalWrite(4, HIGH); //Put PIN 4 in high state = at 5V i.e. on
digitalWrite(6, LOW); //Put PIN 6 in low state = at 0V i.e., off
delay(1000); // we wait for 1000 milliseconds i.e. 1 second
digitalWrite(4, LOW); //Put PIN 4 in low state = at 0V i.e., off
digitalWrite(6, HIGH); //Put PIN 6 in high state = at 5V i.e. on
delay(1000); // we wait for 1000 milliseconds i.e. 1 second
}
Once you have written the code launch the verification
precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load:
As a result, the two red and blue LEDs will alternately turn
on and off after every second.
If you place the police car, previously printed and cut out, in
such a way that the two LEDs protrude from the car's upper
beacon, drilling two holes at appropriate distances for how
the LEDs are positioned, you will achieve a nice effect.
[For the video related to the project click here].
[For the sketch related to the project click here].
(print and cut out)
LESSON 2 - Insights into Electrical Resistance
less resistance
to water than a riverbed made up of irregular rocks;
likewise, there are materials that have properties such that
electric current will flow through them better than others.
For example, gold is an excellent electrical conductor, as are
silver, copper, aluminum... (all metals are good conductors),
while there are materials that hinder the passage of electric
current to such an extent that they are called "insulators"
such as plastic, rubber,...
Another way to visualize electrical resistance in order to
fully understand its physical principle is as depicted in the
figure below:
The amount of water in the two reservoirs is initially the
same, and the water level represents the electrical
potential, that is, the force by which the water is pushed out
of the pipe. The narrower the outlet pipe is, the more
difficulty the water will have in exiting.
Taking this to an extreme, if we were to have such a small
pipe (imagine a hair's width), it is intuitable that water will
have great difficulty escaping. The tube representing the
electrical conductor, in the case of it being a hair, will
obviously almost totally prevent water from escaping, in
which case the material constituting the conductor is called
an insulator and therefore the current flowing through that
conductor is practically zero.
The first circle is red, so 2, the second circle is still red and
so another 2, the third circle is black, so the third digit is 0
and finally the fourth circle is black, so the multiplier is for 1.
So the R = 220 x 1 that is 220 Ohms.
Trivia: What is a Physical Magnitude
and Uncertainty in Measurements
A physical quantity is a property of a body (or phenomenon)
that can be measured. To specify the physical quantity
requires a number (which indicates its value) and a unit of
measurement. The unit of measurement is a reference
quantity of a quantity, which is assigned a value of 1.
void loop()
{
digitalWrite(4, HIGH); //Red lit.
digitalWrite(5, LOW); //Yellow off
digitalWrite(6, LOW); //Green off
delay(6000); // 6 sec wait.
digitalWrite(4, LOW); //Red off
digitalWrite(5, LOW); //Yellow off
digitalWrite(6, HIGH); //Green on
delay(4000); // 4 sec wait.
digitalWrite(4, LOW); //Red off
digitalWrite(5, HIGH); //Yellow on
digitalWrite(6, HIGH); //Green on
delay(2000); // Waiting for 2 sec.
}
The result will be: the red LED turns on and stays on for 6
sec, after which the red LED turns off and the green LED
turns on. After another 4 sec, the yellow LED also turns on
and stays on for 2 sec. After that, the yellow and green LEDs
are turned off and the red LED is turned on again.
If you place the card with the traffic light, previously printed
and cut out, it will surely give you a nice effect.
[For the video related to the project click here].
[For the sketch related to the project click here].
Introduction to Coding
The time has come to enter the world of Coding, and the
first thing I would like to introduce is sketching. But first
let's take a little step back to understand what we mean by
Coding.
The term Coding has been around for a very few years and
as the name suggests comes from "coding" or generating
codes, which in turn, in computer terms, refers to
Programming Computers (or more generally: electronic
devices) using a particular programming language.
So, summarizing, the term coding refers to computer
programming and thus to the design and
development of software.
Saying that...you'll tell me, bravo you
copied the definition from the first-year high school book of
computer science....
.... but really: what does it mean to Program a
Computer or Electronic Device????
void setup()
{
pinMode (3, OUTPUT); // we set digital PIN 3 as the "output"
pinMode (1, INPUT); // we set digital PIN 1 as the "input"
}
void loop()
{
val = digitalRead (1); // reads the value taken on digital PIN 1
if (val == LOW ) // check if val has assumed the low state (button NOT pressed)
{
digitalWrite(3,LOW); // if the button is NOT pressed then digital PIN 3 is set to
LOW
} // the LED is kept off.
else
{
digitalWrite(3,HIGH); // if the button is pressed then digital PIN 3 is set to HIGH
} // the LED is turned on
}
Once you have written the code launch the verification
precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load.
Once you start the sketch, whenever you press the button,
Arduino commands the LED to turn on. Position the printed
card so that the yellow LED comes out of the star and you
have become a Stellier !
From this project onward, in order to learn the programming
language for making skatches, we also begin to do sketch
analysis of the projects we will gradually make.
[For the video related to the project click here].
[For the sketch related to the project click here].
Analysis of the sketch: The Stelliere
Analyzing the sketch, we can observe several interesting
things, first of all the usefulness of inserting comments.
Comments (which will be ignored by Arduino) can be
entered in two different ways. The first is with the use of the
split "/" and the asterisk " * " , specifically they are put at
the beginning and end of anything that Arduino should
ignore as a comment:
/* [comment] */ . This method is used when the comment
occupies multiple lines.
The second method is to put the double divided "//", this
way everything to the right of the // and for the entire line is
ignored by Arduino and not executed because it is seen as a
comment. This mode is used when the comment is on the
same line as an instruction to describe what the specific
instruction does.
Another interesting thing I want to point out to you about
the sketch is the definition of the digital PINs in the void
setup() , we said that the digital PINs can take two values:
HIGH and LOW (or even 0 and 1) and we said that the
Arduino digital PINs ranging from No. 0 to No. 13 can be
INPUT and OUTPUT PINs. In this project digital PIN 1 is of
INPUT, in fact when the button is pressed it carries voltage
to the PIN, so it receives a signal that we read with the
digitalRead instruction. Digital PIN 3, on the other hand,
provides a LOW or HIGH signal with the digitalWrite
instruction, so it is an OUTPUT PIN. This functionality of
digital PINs in the sketch, whether of INPUT or OUTPUT must
be declared in the void setup().
Arduino Analog PINs
void setup() {
Serial.begin(9600); //serial port initialization
}
void loop() {
int read=analogRead(A0); //read the value from pin A0
// I apply Proportion:
// x : reading = 5 : 1023 -> x = (5*reading)/1023
float Vout=(reading*5)/1023.0; //With the proportion I calculate the voltage
float current=(5-Vout)/1000; //Apply Ohm law and calculate current
float ResIncognita=Vout/current; //calculate the unknown resistance
Serial.print("Voltage output: "); //print on the screen the sentence between ""
Serial.print(Vout); //print the Vout value on the screen
//println means it then goes to head
//to the next line
Serial.print(" Resistance value: "); //print on the screen the sentence between
""
Serial.println(ResIncognita); //print the resistance value on the screen
if (ResIncognita>10000) {
digitalWrite(2,HIGH); //puts PIN 2 in high state [5 V].
}
else {
digitalWrite(2,LOW); //puts PIN 2 in a low state [0 V].
}
delay(1000); //waits one second before starting again
}
void loop() {
int read=analogRead(A0); //reads the PIN A0
float Vout=(reading*5)/1024.0; //determines the Vout on the base
//of the value read at PIN A0
float Rnota=1000.0; //value of the known Resistance i.e. 1000 Ohm
float current=(5-Vout)/Rote; //calculates current
float ResIncognita=Vout/current; //calculates the resistance of the photoresistor
Serial.print(" Photoresistor value [kOhm]: "); //print on the screen the sentence
between ""
Serial.print(ResIncognita); //print the value of the resistance
Serial.print (" Value Illuminance [lux]: "); //print on the screen the sentence
between ""
if (ResIncognita<=2000) {
Serial.println (" over 100 lux ");
digitalWrite(2,LOW); //puts PIN 2 in a low state [0 V].
}
else {
if (ResIncognita>2000 && ResIncognita<3500) {
Serial.println (" about 80 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=3500 && ResIncognita<4500) {
Serial.println (" about 40 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=4500 && ResIncognita<5500) {
Serial.println (" about 30 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=5500 && ResIncognita<9500) {
Serial.println (" about 20 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=9500 && ResIncognita<29500) {
Serial.println (" about 5 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=29500) {
Serial.println (" about 1 lux ");
digitalWrite(2,HIGH); //puts PIN 2 in high state [5 V].
}
}}}}}}
delay(1000); //waits one second before starting again
}
In the
second case, 5 V is maintained for 25 percent of the cycle
time, that is, 25 percent of 5V, so the voltage at the digital
PIN output has an average value of 1.25 V.
In the
third case, 5V is maintained for 50% of the cycle time, that
is, 50% of 5V, so the voltage at the digital PIN output has an
average value of 2.5 V.
In the
fourth case, 5V is maintained for 75% of the cycle time, that
is, 75% of 5V, so the voltage at the digital PIN output has an
average value of 3.75 V.
In the
fifth case, 5V is maintained for 100% of the cycle time, that
is, 100% of 5V, so the voltage at the digital PIN output has
an average value of 5V.
A PWM digital PIN can be given values between 0 and 255
(where 0 indicates 0 V and 255 indicates 5 V-essentially 256
values).
The instruction, with its syntax, for assigning a PWM signal
to a digital PIN is as follows:
void loop() {
int read=analogRead(A0); //reads the PIN A0
int valuepwm=reading/4; //converts the reading into the PWM signal
float Vout=(reading*5)/1024.0; //determines the Vout on the base
//of the value read at PIN A0
float Rnota=1000.0; //value of the known Resistance i.e. 1000 Ohm
float current=(5-Vout)/Rote; //calculates current
float ResIncognita=Vout/current; //calculates unknown resistance
void setup()
{
//configure PWM PINs at the output
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}
void loop()
{
analogWrite(9, 255);
//cycle of for with i decreasing to make
//gradual switching off of the LED
for (int i = 255; i >= 0; i--) {
analogWrite(10, i);
delay(delay2);
}
delay(delay);
analogWrite(6, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(9, i);
delay(delay2);
}
delay(delay);
analogWrite(5, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(6, i);
delay(delay2);
}
delay(delay);
analogWrite(3, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(5, i);
delay(delay2);
}
delay(delay);
analogWrite(5, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(3, i);
delay(delay2);
}
delay(delay);
analogWrite(6, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(5, i);
delay(delay2);
}
delay(delay);
analogWrite(9, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(6, i);
delay(delay2);
}
delay(delay);
analogWrite(10, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(9, i);
delay(delay2);
}
delay(delay);
}
int delay1=100;
int delay2=1;
int myLED[] = {3,5,6,9,10};
int count=0;
void setup()
{
//configure output PWM PINs with for loop
for (count=0; count<6; count++) {
pinMode(myLED[count], OUTPUT);
}
}
void loop()
{
for (count=0; count<5; count++) {
analogWrite(myLED[count], 255);
if (count>0) {
for (int i = 255; i >= 0; i--) {
analogWrite(myLED[count-1], i);
delay(delay2);
}
}
delay(delay1);
}
for (count=4; count>0; count--) {
if (count>0) {
analogWrite(myLED[count-1], 255);
}
for (int i = 255; i >= 0; i--) {
analogWrite(myLED[count], i);
delay(delay2);
}
delay(delay1);
}
}
Load the sketch and you get a nice effect of a peering
robotic eye, especially if you cut out the cardboard and
create the slit in which to insert the LEDs.... The famous
KITT car from Supercar also had a similar effect...
The RGB LED can look different: as a regular 5-mm LED with
four terminals, or in strips of the SMD type (with four wires),
or even mounted on a board (RGB module) with four PINs.
Potentiometer 1
KOhm
int redRGB = 11; //select the pin for the red LED of RGB
int bluRGB =9; // select the pin for the blue LED of RGB
int greenRGB =10; // select the pin for the green LED of RGB
int pinBut=4; // select pin for digital input from button
int val; //variable intensity for RGB color
int color; //1=red, 2=blue, 3=green
int pushbutton; //variable that tells me if button pressed
void setup() {
Serial.begin(9600);
pinMode(redRGB, OUTPUT);
pinMode(bluRGB, OUTPUT);
pinMode(greenRGB, OUTPUT);
pinMode(pinBut, INPUT_PULLUP);
color=1;
analogWrite(redRGB, 255);
analogWrite(bluRGB, 255);
analogWrite(greenRGB, 255);
}
void loop(){
pushbutton=digitalRead(pinBut);
if(pushbutton==0){
color=color;
}
else {
color++;
if (color>3){
color=1;
}
}
intensity_color(color);
}
Once you start the sketch and open the serial monitor, you
can see on the screen which color of the RGB LED is active
and its intensity value, at which point acting on the
potentiometer will change the color of the RGB LED because
you are changing the intensity of the active color.
To change the active color and thus the color to be changed,
you can press the button, again on the screen you will be
shown the new active color and so on.
In this way you can mix the three RGB colors at will and get
the desired color by simulating the color change of the
stars.
int redRGB = 11; //select the pin for the red LED of RGB
int bluRGB =9; // select the pin for the blue LED of RGB
int greenRGB =10; // select the pin for the green LED of RGB
int redLED = 7; //select the pin for the red LED
int bluLED =5; // select the pin for the blue LED
int greenLED =6; // select the pin for the green LED
int pinBut=4; // select pin for digital input from button
int val; //variable intensity for RGB color
int color; //0=red, 1=blue, 2=green
int pushbutton; //variable that tells me if button pressed
void setup() {
Serial.begin(9600);
pinMode(redRGB, OUTPUT);
pinMode(bluRGB, OUTPUT);
pinMode(greenRGB, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(bluLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(pinBut, INPUT_PULLUP);
color=1;
analogWrite(redRGB, 255);
analogWrite(bluRGB, 255);
analogWrite(greenRGB, 255);
}
void loop(){
pushbutton=digitalRead(pinBut);
if(pushbutton==0){
color=color;
}
else {
color++;
if (color>3){
color=1;
}
}
choice_color(color);
intensity_color(color);
delay(200);
}
void loop() {
switch_state = digitalRead(SWITCH_PIN);
Serial.println(switch_state);
if (switch_state == 0){
delay(1000); //after one sec.
digitalWrite(13,0);
digitalWrite(8,1);
delay(1000);
digitalWrite(12,0);
digitalWrite(9,1);
delay(1000);
digitalWrite(11,0);
digitalWrite(10,1);
}
if (switch_state == 1){
delay(1000);
digitalWrite(8,0);
digitalWrite(13,1);
delay(1000);
digitalWrite(9,0);
digitalWrite(12,1);
delay(1000);
digitalWrite(10,0);
digitalWrite(11,1);
}
}
Once the sketch is loaded, Arduino will check the status of
the Tilt Sensor, and will appropriately orient the "sand in the
hourglass," that is, it will turn on the appropriate LEDs, of
course once this step is completed, that is, the LEDs are all
on one side, then to restart the hourglass, it will be
necessary to flip the tilt sensor to start the hourglass in
reverse.
void setup ()
{
pinMode (buzzerPin, OUTPUT); //declare in OUTPUT the PIN 8
}
void loop ()
{
digitalWrite(buzzerPin, HIGH); //enable PIN 8 to 5 V
delay (500); //leaving PIN 8 powered for half a second
digitalWrite(buzzerPin, LOW); ///put out PIN 8
//She builds a vector (variable containing multiple values) with the Notes:
unsigned int melody[] = {
NOTE_C5, NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5,
NOTE_C6};
void setup() {
pinMode(BUZZER_PIN, OUTPUT); //Let's output PIN 9
}
void loop() {
for (int thisNote = 0; thisNote < 8; thisNote++) {
tone(BUZZER_PIN, melody[thisNote], duration); //see more
delay(1000);//It changes note after one second
}
delay(2000);//After two seconds the cycle starts again
}
You can also try this tune I found on the Internet (just copy-
paste):
/*
Be Maker STEM - Project 17a_Buzzer Passive
*/
#define NOTE_B0 31
#define NOTES_C1 33
#define NOTES_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTES_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTES_B3 247
#define NOTES_C4 262
#define NOTES_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTES_B4 494
#define NOTE_C5 523
#define NOTES_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
#define REST 0
int tempo=114; // change this to make the song slower or faster
int buzzer = 9;// change this to whichever pin you want to use
// notes of the moledy followed by the duration.
// a 4 means a quarter note, 8 an eighteenth , 16 sixteenth, so on
// !!negative numbers are used to represent dotted notes,
// so -4 means a dotted quarter note, that is, a quarter Plus an eighteenth!!!
int melody[] = {
NOTE_E4,4, NOTE_E4,4, NOTE_F4,4, NOTE_G4,4,//1
NOTE_G4,4, NOTE_F4,4, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_C4,4, NOTE_D4,4, NOTE_E4,4,
NOTE_E4,-4, NOTE_D4,8, NOTE_D4,2,
NOTE_E4,4, NOTE_E4,4, NOTE_F4,4, NOTE_G4,4,//4
NOTE_G4,4, NOTE_F4,4, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_C4,4, NOTE_D4,4, NOTE_E4,4,
NOTE_D4,-4, NOTE_C4,8, NOTE_C4,2,
NOTE_D4,4, NOTE_D4,4, NOTE_E4,4, NOTE_C4,4,//8
NOTE_D4,4, NOTE_E4,8, NOTE_F4,8, NOTE_E4,4, NOTE_C4,4,
NOTE_D4,4, NOTE_E4,8, NOTE_F4,8, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_D4,4, NOTE_G3,2,
NOTE_E4,4, NOTE_E4,4, NOTE_F4,4, NOTE_G4,4,//12
NOTE_G4,4, NOTE_F4,4, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_C4,4, NOTE_D4,4, NOTE_E4,4,
NOTE_D4,-4, NOTE_C4,8, NOTE_C4,2
};
// sizeof gives the number of bytes, each int value is composed of two bytes (16
bits)
// there are two values per note (pitch and duration), so for each note there are
four bytes
int notes=sizeof(melody)/sizeof(melody[0])/2;
// this calculates the duration of a whole note in ms (60s/time)*4 beats
int wholenote = (60000 * 4) / time;
int divider = 0, noteDuration = 0;
void setup() {
// iterate over the notes of the melody.
// Remember, the array is twice the number of notes (notes + durations)
for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {
// calculates the duration of each note
divider = melody[thisNote + 1];
if (divider > 0) {
noteDuration = (wholenote) / divider; // regular note, just proceed
} else if (divider < 0) {
// dotted notes are represented with negative durations!!!
noteDuration = (wholenote) / abs(divider);
noteDuration *= 1.5; // increases the duration in half for dotted notes
}
// we only play the note for 90% of the duration, leaving 10% as a pause
tone(buzzer, melody[thisNote], noteDuration*0.9);
// Wait for the specief duration before playing the next note.
delay(noteDuration);
noTone(buzzer); // stop the waveform generation before the next note.
}
}
void loop() {
// if you want to repeat the song forever, paste the setup code here .
}
void loop ()
{
digitalValue = digitalRead(digitalPin); //read the value at PIN 9
if (digitalValue > 0) {
digitalWrite (ledPIN, HIGH);
delay(3000); //keeps the LED active for 3 sec.
}
else {
digitalWrite (ledPIN, LOW);
}
}
HC-SR04
void setup() {
pinMode(PortaTrig, OUTPUT);
pinMode(PortaEcho, INPUT);
Serial.begin(9600);
Serial.print( "Ultrasonic Sensor: ");
}
void loop() {
digitalWrite ( PortaTrig, LOW ); //sets the trigger output to a low value
digitalWrite ( PortaTrig, HIGH ); //sets the trigger output to a high value, i.e.,
sends a pulse
delayMicroseconds ( 10 ); // the high value is held for 10 microseconds
digitalWrite( PortaTrig, LOW ); //makes the pulse end i.e. puts the trigger output
at LOW
long duration = pulseIn( PortaEcho, HIGH ); //measures time
long distance = 0.0343 * duration / 2; //calculates the distance in cm
Serial.print("distance: ");
Serial.print(distance);
Serial.println(" cm ");
delay(100); //Wait 100 milliseconds before starting again
}
The servo motor we will use in the next project is the SG-90,
which can be powered directly from Arduino and is used for
moving light objects. As shown in the figure below, the
colored cable has three poles: one pole is connected to
Arduino's 5V Vcc voltage, another to ground (GND), and the
third pole is to be connected to an Arduino digital PIN and is
used for control.
For "heavier" applications we can use servomotors with the
commercial designation MG996R or the TD-8120MG, but in
this case, especially if they are more than one servomotor,
power must be supplied by an external power supply.
Project 20 - Controlling a Servo Motor SG-90
void setup() {
Serial.begin(9600);
ServoMotor.attach(9); //We declare that the ServoMotor is attached to PIN 9
Serial.print("SERVO MOTOR - ROTATION - ");
}
void loop() {
// Let's rotate the Servo Motor by an angle ranging from 10° to 160°.
for(int i=10;i<=160;i++) {
ServoMotor.write(i);
Serial.print("Angle: ");
Serial.print(i); //print the value of the angle
Serial.println(" °"); //print the unit of measurement, i.e. degrees
delay(30);
}
// Let's rotate the Servo Motor by an angle ranging from 160° to 10°.
for(int i=160;i>=10;i--) {
ServoMotor.write(i);
Serial.print("Angle: ");
Serial.print(i); //print the value of the angle
Serial.println(" °"); //print the unit of measurement, i.e. degrees
delay(30);
}
}
After checking the sketch let's upload it to Arduino in the
usual way and open the serial monitor, we will see the
moving part of the motor (called the rotor) rotate from 10°
to 160° and then back again, and the rotation in degrees is
shown on the monitor.
1
) + =
2 + =
)
The wiring diagram is as follows:
//ULTRASOUND MODULE
int triggerPort = 11; //PIN to which the Trigger signal is connected
int echoPort = 10; //PIN to which the Echo signal is connected
//long s=0.0;
//long d=0.0;
void setup() {
Serial.begin(9600);
ServoMotor.attach(6); //The ServoMotor is declared to be attached to PIN 6
pinMode( triggerPort, OUTPUT );
pinMode( echoPort, INPUT );
Serial.print("MOTOR SERVO - ROTATION - ");
}
void loop() {
// Let's rotate the Servo Motor by an angle ranging from 10° to 160°.
for(int i=10;i<=160;i++) {
ServoMotor.write(i);
digitalWrite( triggerPort, LOW ); //ports the trigger output to a low value
digitalWrite( triggerPort, HIGH ); //enable trigger
delayMicroseconds( 10 ); //holds trigger active for 10 microsec (generates
pulse)
digitalWrite( triggerPort, LOW ); //deactivate the trigger
long d = pulseIn( echoPort, HIGH ); //calculates the duration of the bounce
time
long s = 0.0343 * d / 2; //calculates the distance
if (s<100){
for (int t=1;t<s;t++){
Serial.print(".");
}
for (int j=s;j<100;j++){
Serial.print("X");
}
Serial.print (" Obstacle to: ");
Serial.print(s);
Serial.print(" cm ");
Serial.print("Angle: ");
Serial.print(i);
Serial.println(" °");
}
else {
for (int t=1;t<100;t++){
Serial.print(".");
}
Serial.println(" °");
}
}
// Let's rotate the Servo Motor by an angle ranging from 160° to 10°.
for(int i=160;i>=10;i--) {
ServoMotor.write(i);
digitalWrite( triggerPort, LOW ); //ports the trigger output to a low value
digitalWrite( triggerPort, HIGH ); //enable trigger
delayMicroseconds( 10 ); //holds trigger active for 10 microsec (generates
pulse)
digitalWrite( triggerPort, LOW ); //deactivate the trigger
long d = pulseIn( echoPort, HIGH ); //calculates the duration of the bounce
time
long s = 0.0343 * d / 2; //calculates the distance
if (s<100){
for (int t=1;t<s;t++){
Serial.print(".");
}
for (int j=s;j<100;j++){
Serial.print("X");
}
Serial.print (" Obstacle to: ");
Serial.print(s);
Serial.print(" cm ");
Serial.print("Angle: ");
Serial.print(i);
Serial.println(" °");
}
else {
for (int t=1;t<100;t++){
Serial.print(".");
}
Serial.println(" ");
}
}
}
Component
If we connect several bipoles together in such a way that
the incoming terminal of one connects to the outgoing
terminal of the other, we have a Series Connection.
Series Connection
In series connection, all components are passed through by
the same "I" current.
If we connect multiple bipoles by joining the "+" and "-"
terminals together, we have Parallel Connection.
Parallel Connection
In parallel connection, all components are subjected to the
same "V" voltage.
example of Trimmer
Project 23 - The Use and Connection of the
Potentiometer
LM35
void setup() {
Serial.begin(9600); //We set the port speed to 9600
}
void loop() {
int reading = analogRead(sensorPin); // Get a reading from the temperature
sensor
float voltage = reading * (5000 / 1024.0); // Convert the reading into voltage
float temperature = voltage / 10; // Convert the voltage into the temperature in
degree Celsius
Serial.print(temperature); // Print the temperature in the Serial Monitor
Serial.println(" °C");
delay(1000); // wait a second between readings
}
void setup() {
pinMode(scottaPin, OUTPUT);
pinMode(hotPin, OUTPUT);
pinMode(environmentPin, OUTPUT);
pinMode(coldPin, OUTPUT);
Serial.begin(9600); //We set the port speed to 9600
}
void loop() {
int reading = analogRead(sensorPin); // Get a reading from the temperature
sensor
float voltage = reading * (5000 / 1024.0); // Convert the reading into voltage
float temperature = voltage / 10; // Convert the voltage into the temperature in
degree Celsius
Serial.print(temperature); // Print the temperature in the Serial Monitor
Serial.println(" °C");
delay(1000); // wait a second between readings
if (temperature<=10){lightingLED=0;}
if (temperature>10 && temperature<=27){lightingLED=1;}
if (temperature>27 && temperature<=36){lightingLED=2;}
if (temperature>36){lightingLED=3;}
switch (ignitionLED) {
case 0:
digitalWrite(scottaPin, LOW);
digitalWrite(hotPin, LOW);
digitalWrite(environmentPin, LOW);
digitalWrite(coldPin, HIGH);
break;
case 1:
digitalWrite(scottaPin, LOW);
digitalWrite (hotPin, LOW);
digitalWrite(environmentPin, HIGH);
digitalWrite(coldPin, LOW);
break;
case 2:
digitalWrite(scottaPin, LOW);
digitalWrite(hotPin, HIGH);
digitalWrite(environmentPin, LOW);
digitalWrite(coldPin, LOW);
break;
case 3:
digitalWrite(scottaPin, HIGH);
digitalWrite(hotPin, LOW);
digitalWrite(environmentPin, LOW);
digitalWrite(coldPin, LOW);
break;
}
}
At this point we load the sketch on Arduino and with the tip
of the sensor touch the different bodies to measure their
temperature. Depending on the measured temperature
range, a particular colored Led will light up: Blue Led = cold,
Green Led = room temperature, Yellow Led = hot, or Red
Led = hot. We can enrich the design by also putting a card
with holes for the LED head and on the card write the
measured temperature range.
Analysis of the Sketch: Project 25 -
Luminous Thermometer.
Also used for this sketch was the control structure switch(..)
..... case ... ; which we review as being a very important
structure.
This way of having the processor make decisions is used
especially when there are many cases to examine and
decide on which actions to take. The use of the
switch...case... simplifies the structure, in fact it is enough
to define for each case what to do and then we have the
switch function do the case selection directly. The general
syntax of the control structure according to the Arduino
Reference Book is:
switch (var) {
case label1:
// statements
break;
case label2:
// statements
break;
default:
// statements
break;
}
Where var is a variable of type int or char and indicates the
number of the "case" you want to process, and label1 is the
label, also a variable of type int or char. In the syntax
example there are only three cases of which one is the
default. The last case, the default case is selected when you
have none of the previous cases. The structure can also
have more than the represented number of cases.
[For the video related to the project click here].
[For the sketch related to the project click here].
The DHT11 Environmental
Temperature and Humidity Sensing
Sensor.
As you can see, the Module has the third pin from the left
that has no function and therefore should not be connected
to anything.
A 4.7 kOhm resistor is normally connected between the Vcc
pins and Data:
void setup() {
Serial.begin(9600);
Serial.println(F("DHT11 Start"));
dht.begin();
}
void loop() {
delay(2000); // Wait a few seconds between measurements.
float h = dht.readHumidity();
float t = dht.readTemperature(); // Read temperature as Celsius (the default)
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
}
void setup()
{
pinMode(Led, OUTPUT); //set the LED as the OUTPUT
pinMode(sensor, INPUT); //set sensor PIN as INPUT
}
void loop()
{
val = digitalRead(sensor); //The sensor output is read.
if(val == LOW) //If the value of the sensor signal is "LOW"
//then the magnetic field is present and the LED
//on Arduino is turned on
{
digitalWrite(Led, HIGH);
}
else
{
digitalWrite(Led, LOW);
}
}
void setup () {
Serial.begin (9600);
}
void loop () {
sensorValue = analogRead(sensorPin);
delay(sensorValue);
Serial.println (sensorValue, DEC); // you can graph the results using the serial
plotter
}
For this project we will use neither sensor module KY003 nor
KY035, but sensor module KY024, which is the Linear
Magnetic Hall Sensor. This module differs from the first two
because it has both functionalities, that is, it has an analog
output and a digital output:
The PIN labeled A0 is the analog output, the PIN labeled D0,
on the other hand, is the digital output, while the PIN
labeled G stands for Ground and the PIN labeled "+" stands
for the power supply (at 5 V).
The module also has a trimmer that can be adjusted to
adjust the sensitivity of the sensor and thus the threshold
value for turning on the LED. There are two LEDs on the
module, one is lit when the module is powered and the
other when there is the presence of a magnetic field.
For this project we need:
void setup ()
{
pinMode (ledPin, OUTPUT);
pinMode (buzPin, OUTPUT);
pinMode (digitalPin, INPUT);
pinMode(analogPin, INPUT);
Serial.begin(9600);
}
void loop ()
{
digitalWrite (ledPin, LOW); //holds off the LED at PIN 13 on Arduino
digitalWrite(buzPin, LOW); //keeps the buzzer off
digitalVal = digitalRead(digitalPin) ; // Reads the digital interface
if(digitalVal == HIGH) //If the value of the sensor signal is "HIGH"
//then the magnetic field is present and the LED
//on the Arduino is turned on and the Active Buzzer is
powered
//then the value of A0 is read and printed
{
digitalWrite(ledPin, HIGH);
digitalWrite (buzPin, HIGH);
analogVal = analogRead(analogPin);
Serial.println (analogVal, DEC);
delay (analogVal);
}
else
{
digitalWrite(ledPin, LOW);
digitalWrite(buzPin, LOW);
analogVal = 0;
Serial.println (analogVal, DEC);
delay (300);
}
}
void setup()
{
// Set all PINs to OUTPUT
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);
pinMode(segDP, OUTPUT);
pinMode(digit1, OUTPUT);
pinMode(digit2, OUTPUT);
pinMode(digit3, OUTPUT);
pinMode(digit4, OUTPUT);
// All digits set to off
digitalWrite(digit1, DIGIT_OFF);
digitalWrite(digit2, DIGIT_OFF);
digitalWrite(digit3, DIGIT_OFF);
digitalWrite(digit4, DIGIT_OFF);
}
void loop()
{
displayNumber(millis()/1000);
}
ShowNumber(toDisplay % 10);
delayMicroseconds(DISPLAY_BRIGHTNESS);
ShowNumber(OFF);
toDisplay /= 10;
digitalWrite(digit1, DIGIT_OFF);
digitalWrite(digit2, DIGIT_OFF);
digitalWrite(digit3, DIGIT_OFF);
digitalWrite(digit4, DIGIT_OFF);
}
}
case 0:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_OFF);
break;
case 1:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
case 2:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;
case 3:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;
case 4:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 5:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 6:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 7:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
case 8:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 9:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 10:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
}
}
Once the sketch is started the display will show the seconds
elapsed since you started the sketch on Arduino.
[For the video related to the project click here].
[For the sketch related to the project click here].
Project 32 - Counter of seconds and tenths of a
second.
#include "SevSeg.h"
SevSeg sevseg; //Instantiate a seven segment controller object
void setup() {
byte numDigits = 4;
byte digitPins[] = {4, 3, 2, 1};
byte segmentPins[] = {10, 9, 6, 7, 8, 11, 12,5};
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_CATHODE; // See README.md for options
bool updateWithDelays = false; // Default 'false' is Recommended
bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or
isn't connected
void loop() {
static unsigned long timer = millis();
static int deciSeconds = 0;
Load the sketch on Arduino you will see that when the
loading is complete the display will start counting the time
elapsed since the program was launched on Arduino
(seconds and tenths of a second will be indicated)
Analysis of the sketch: Project 32 -
Chronometer with use of the Library.
There are many interesting things in this sketch, let's look at
the most interesting ones. First of all you can see that the
use of the SevSeg Library drastically reduces the code
instructions to be written since special functions are used to
handle the 4-digit seven-segment LED Display.
Among these instructions we find:
byte hardwareConfig = COMMON_CATHODE;
which tells Arduino what type of display we are using
whether common cathode or common anode (in which case
we would write COMMON_ANODE) .
With instructions:
byte digitPins[] = {4, 3, 2, 1};
byte segmentPins[] = {10, 9, 6, 7, 8, 11, 12,5};
we tell Arduino how our display is connected to its pins. In
our particular case: Diital pins D1=4, D2=3, D3=2, D4=1
Segment pins A=10, B=9, C=6, D=7, E=8, F=11, G=12 and
dp=5 .
With education:
bool leadingZeros = false;
we tell Arduino whether there should be zeros in front of the
digit we want to show on the display (in which case we
needed to write "true" or not).
With education:
bool disableDecPoint = false;
we tell Arduino that we plan to use the decimal point of the
display (otherwise we would have written "true")
With education:
sevseg.setNumber(deciSeconds, 1);
we tell Arduino that the numbers it needs to show on the
display, are numbers with only one decimal place.
Let's look at the millis() function instead: when it is called it
returns the elapsed time, in milliseconds, since the sketch
started running on the Arduino. Since we want tenths of a
second, and after ten tenths of a second must trigger the
second, the form to get this is:
if (millis() - timer >= 100) {
timer += 100;
deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
if (deciSeconds == 10000) { // Reset to 0 after counting for
1000 seconds.
deciSeconds=0;
}
Also after 999.9 seconds, it resets the counter to zero and
restarts from zero. Please note, the Arduino Reference
Book says that the type of value returned by the millis()
function is "unsigned long", also to make the variable fixed
for the millis() function call, which is updated from time to
time, it must also be defined as "static" type.
So the correct form is:
static unsigned long timer = millis();
For more details on the use of the library and instructions
in C++ you can refer to the Readme file that accompanies
the library, and for other instructions, to the Arduino
Reference Book [Refence Book click here], while for the
mills() function there is a project, also in this lesson, for
further discussion.
void setup() {
byte numDigits = 4;
byte digitPins[] = {4, 3, 2, 1};
byte segmentPins[] = {10, 9, 6, 7, 8, 11, 12,5};
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_CATHODE; // See README.md for options
bool updateWithDelays = false; // Default 'false' is Recommended
bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or
isn't connected
void loop() {
int val = analogRead(pot);
int scale = map(val, 0, 1023, 0, 10000); //potentiometer from 10K
if (scale > 9999 || scale < 1) { // if value > 9999 or < 0 then value to 0
scale = 0;
}
sevseg.setNumber(scale);
sevseg.refreshDisplay(); // Must run repeatedly
}
void loop() {
if(millis() > time_1 + INTERVAL_1){
time_1 = millis();
print_time(time_1);
Serial.println("I am");
}
#define r8 0
#define r7 1
#define r6 2
#define r5 3
#define r4 4
#define r3 5
#define r2 6
#define r1 7
#define c1 8
#define c2 9
#define c3 10
#define c4 11
#define c5 12
#define c6 13
#define c7 19
#define c8 18
int vRows[8]={r1,r2,r3,r4,r5,r6,r7,r8};
int vCols[8]={c1,c2,c3,c4,c5,c6,c7,c8};
void resetRows(){
for(int i=0;i<8;i++)
digitalWrite(vRows[i],initr);
}
void resetCols(){
for(int i=0;i<8;i++)
digitalWrite(vCols[i],initc);
}
void setup() {
pinMode(r1,OUTPUT);
pinMode(r2,OUTPUT);
pinMode(r3,OUTPUT);
pinMode(r4,OUTPUT);
pinMode(r5,OUTPUT);
pinMode(r6,OUTPUT);
pinMode(r7,OUTPUT);
pinMode(r8,OUTPUT);
pinMode(c1,OUTPUT);
pinMode(c2,OUTPUT);
pinMode(c3,OUTPUT);
pinMode(c4,OUTPUT);
pinMode(c5,OUTPUT);
pinMode(c6,OUTPUT);
pinMode(c7,OUTPUT);
pinMode(c8,OUTPUT);
resetRows();
resetCols();
void lightRows(){
for(int i=0;i<8;i++)
digitalWrite(vRows[i],!initr);
}
void lightCols(){
for(int i=0;i<8;i++)
digitalWrite(vCols[i],!initc);
}
void counter1(){
for(int i=0;i<8;i++){
resetCols();
resetRows();
digitalWrite(vCols[i],HIGH);
delay(pause);
for(int j=0;j<8;j++){
resetRows();
digitalWrite(vRows[j],LOW);
delay(pause);
}
}
void counter2(){
for(int i=0;i<8;i++){
resetCols();
resetRows();
digitalWrite(vRows[i],LOW);
delay(pause);
for(int j=0;j<8;j++){
resetCols();
digitalWrite(vCols[j],HIGH);
delay(pause);
}
}
}
void blinking(){
for(int i=0;i<3;i++){
lightCols();
lightRows();
delay(pause*10);
resetRows();
resetCols();
delay(pause*10);
}
}
}
}
}
void loop() {
counter1();
counter2();
blinking();
String a="HELLO WORLD!"
writeLetter(a);
}
In this way you can dial what you want and assign it a
variable name. Alternatively, it is possible to activate
individual LEDs, again in the sketch you can observe the
functions "counter1()", "counter2()" and "blinking()" which
thanks to "for" cycles drive the individual LEDs in the matrix
by acting directly in the variables vCols and vRows.
Returning to the representation on the LED array of the
phrase "Hello World", we can observe the function
writeLetter(...) that for each letter of the string we enter to
it, thanks to the switch... case... structure, calls the variable
of the single letter that makes up the word Hello Word and
represents it on the LED array.
#include <LiquidCrystal.h>
void setup() {
lcd.begin(16, 2); //set the display as a 2-line, 16-character display
lcd.print("hello, world!"); //let me play the inscription only once
}
int foo = 0; //set a variable that will act as my seconds counter
void loop() {
lcd.setCursor(0, 1); //position the cursor on the first line down to the position
lcd.print(foo); //print the seconds counter
delay(1000);
foo++;
}
Main
Features
Ultrasonic Module Infrared Module
(Sound) (Light)
Frequencies above Frequency on the
20 kHz (20 kilo-hertz, order of THz
or 20 thousand hetz). (tera-hertz, or
Spectrum Ultrasound is at the trillion hertz).
high end of the Infrared is at the
sound spectrum. lower end of the
light spectrum.
Propagation Compared with solid The maximum
bodies, sound in air propagation speed
propagates at a of light is in
slower speed and vacuum: 300,000
does not propagate km/s (300,000
in a vacuum. In air, kilometers per
the speed of sound is second).
about 340 m/s (340
meters per second)
Ability of the Optimal for solid At the same angle
reflected wave surfaces that are to the sound, with
to return in perpendicular to the light there is a
the same direction of the very good
direction as sound wave, as these reflection in the
the generator. surfaces tilt, relative direction of the
to the direction of generator--even
the wave, the for very inclined
dispersion of surfaces.
reflected sound Light is not
increases. For reflected from
particular very dark-colored
inclinations, the bodies (in which
sound wave does not case light is
return in the absorbed) and in
direction of the the case of
generator, so the transparent
reflection causes the materials (where
sound to scatter. light passes
through the
material).
IR module KY032
with jumper
inserted on EN
void setup() {
pinMode(ObstaclePin, INPUT); //setting PIN 8 as INPUT
Serial.begin(9600); //setting the serial port
}
void loop() {
Obstacle = digitalRead(ObstaclePin); //read the status of PIN 8
if (Obstacle == 0) {
Serial.println(" Obstruction eye!!!"); //if PIN 8 status is low
//then the obstacle is present
}
else {
Serial.println (" Street Free"); //otherwise, the street is free
}
delay(50); //cycle repeats after 300 msec.
}
Once the sketch is loaded and the serial monitor is
activated, pass your hand in front of the sensor module at
different distances and verify the detection by the LED on
board the module lighting up and the writing appearing on
the serial monitor. The switching point of the sensor can be
adjusted using the trimmers located on the module.
IR module KY032
with jumper
removed on EN
The scheme to be carried out is as follows:
void setup() {
pinMode(ObstaclePin, INPUT); //setting PIN 8 as INPUT
pinMode(EnPin, OUTPUT); //setting PIN 7 as OUTPUT
Serial.begin(9600); //setting the serial port
}
void loop() {
digitalWrite(EnPin, HIGH); //enable module operation
Obstacle = digitalRead(ObstaclePin); //read the status of PIN 8
if (Obstacle == LOW) {
Serial.println("Obstruction eye!!!"); //If the status of PIN 8 is low then the
obstacle is present
}
else {
Serial.println ("Street Clear"); //otherwise, the street is clear
}
delay(30); //cycle repeats after 300 msec.
}
IR Module KY033
Line Tracking
void setup () {
pinMode (ledPin, OUTPUT);
Serial.begin (9600);
}
void loop () {
sensorValue = analogRead(sensorPin);
if (sensorValue > 500) {
digitalWrite(ledPin,HIGH); //PIN on Arduino turned on
Serial.println ("ON LINE");
}
else {
digitalWrite(ledPin,LOW); //PIN on Arduino off
Serial.println ("OUT OF LINE");
}
delay (200);
}
#include <IRremote.h>
void setup()
{
Serial.begin(9600); //set the serial port
receiver.enableIRIn(); //enables reception
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (receiver.decode(&results))
{
digitalWrite(ledPin, HIGH); //turns on the LED when it receives the signal
Serial.println(results.value);
delay(1000);
digitalWrite(ledPin, LOW); //shuts down the LED after decoding
receiver.resume(); //ready to receive the next signal
}
}
int pinIRremote = 5;
int pinLEDgreen = 9;
int pinLEDyellow = 10;
int pinLEDred = 11;
int pinLEDblu = 12;
IRrecv receiver(pinIRremote);
decode_results results;
void setup()
{
pinMode(pinLEDgreen, OUTPUT);
pinMode(pinLEDyellow, OUTPUT);
pinMode(pinLEDred, OUTPUT);
pinMode(pinLEDblu, OUTPUT);
Serial.begin(9600);
receiver.enableIRIn();
digitalWrite(pinLEDyellow,LOW);
digitalWrite(pinLEDred,LOW);
digitalWrite(pinLEDblu,LOW);
}
void loop()
{
if (receiver.decode(&results))
{
digitalWrite(pinLEDgreen,HIGH);
Serial.println(results.value);
if(results.value==16582903){digitalWrite(pinLEDyellow,HIGH);}
if(results.value==16615543){digitalWrite(pinLEDred,HIGH);}
if(results.value==16599223){digitalWrite(pinLEDblu,HIGH);}
if(results.value==16580863){
digitalWrite(pinLEDyellow,LOW);
digitalWrite(pinLEDred,LOW);
digitalWrite(pinLEDblu,LOW);
}
delay(1000);
digitalWrite(pinLEDgreen,LOW);
receiver.resume();
}
}