Basic Course about ARDUINO - Lesson 3



Regarding the safety aspects, since the projects are based on a very low voltage power supply supplied by the USB port of the PC or by backup batteries or power supplies with a maximum of 9V output, there are no particular risks of an electrical nature. It is however necessary to specify that any short circuits caused during the exercise could cause damage to the PC, to the furniture and in extreme cases even to burns, for this reason every time a circuit is assembled, or modifications are made on it, it will be necessary to do it in power failure and at the end of the exercise it will be necessary to disconnect the circuit by removing both the USB cable for connection to the PC and any batteries from the appropriate compartments or external power connectors. Furthermore, again for safety reasons, it is strongly recommended to carry out the projects on insulating and heat resistant mats that can be purchased in any electronics store or even on specialized websites.

At the end of the exercises it is advisable to wash your hands, as the electronic components could have processing residues that could cause damage if swallowed or if in contact with eyes, mouth, skin, etc. Although the individual projects have been tested and safe, those who decide to follow what is reported in this document assume full responsibility for what could happen in the execution of the exercises provided for in it. For younger children and / or for their first experiences in the field of electronics, it is advisable to perform the exercises with the help and in the presence of an adult.

Roberto Francavilla

Robotics with Arduino

Robot con il cuore e il pollice in alto | Vettore Gratis

With this lesson we begin to explore the world of sensors that we can connect to Arduino and therefore with this we also begin to talk about robotics.

Did you know that with Arduino you can build real robots? Nooo!

But Yeeeeeee !!! It all depends on your imagination.

The word “robot” is presumed to derive from the Czech language which means “slave” and was a word used in ancient Europe to indicate people who did heavy and repetitive work, but the best use of the word Robot is, in my opinion, of the great writer Asimov who also fixed the laws:

First Law: “A robot may not injure a human being or, through inaction, allow a human being to come to harm”.

Second Law: “A robot must obey the orders given it by human beings except where such orders would conflict with the First Law”.

Third Law: “A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws”.

Obviously today with the word robot we mean everything that carries out operations mechanically in an automatic way thanks to an electronic controller, with particular reference to programmable appliances used in some sectors of industry, but also for domestic uses (see for example kitchen robots, robot vacuum cleaners …)

What allows a machine to have reactions and therefore a certain behavior, are the SENSORS, or those electronic devices that detect the values ​​of a physical quantity and transmit the variations.

Sensors are also called TRANSDUCERS which can be classified as active if the transducers generate a signal in current or voltage or passive if the transducers output a variation of an electrical parameter such as resistance, capacitance etc …

Another classification criterion refers to the type of signal produced at the output.

The analog transducers have an output signal that continuously follows the variations of the physical input quantity. Digital transducers output the value of the quantity in numerical terms with discrete values. However do not worry, at the end of the course you will be very good at understanding the functioning of many sensors.

The photoresistor or also called Light Sensor

In this lesson we will talk about the light sensor. In particular we will talk about photoresistors its commercial English name is LDR that is Light Dependent Resistor, that is that electronic component that changes its electrical resistance when the brightness of the environment in which it is positioned changes and therefore, with this variation, we can establish different behaviors from make Arduino do.

The operating principle of an LDR is based on particular characteristics possessed by some substances which, subjected to the action of light (photons), modify their resistivity characteristics. Electrical resistivity, also called specific electrical resistance, is the ability of a material to resist the passage of electrical charges. In the International System, resistivity is measured in Ohms per meter (Ω · m). Resistivity differs from resistance in that it is a specific property of the material in question and mainly depends on the microscopic structure of the medium; on the contrary, the resistance R is a property of the entire conductor under examination (macroscopic property).

The animated figure above shows how some materials when hit by photons (light) absorb energy and are able to conduct more electric current when subjected to an electric voltage (electrons are released from their bond). These materials, therefore, modify their resistivity, lowering it, when they are hit by light. In the absence of light, photoresistors act as materials with high resistivity.

For our projects we will refer to the photoresistor GL 5528:

As we have said, there is a link between the amount of light that hits the photoresistor and the Resistance value that the sensor assumes, this link is expressed through a graph (logarithmic) shown below:

On the x axis (abscissa), there are the Lux (ie the luminous intensity), on the y axis (ordinate) there are the kOhm (ie the Resistance). As can be seen from the graph, the greater the light, the smaller the Resistance.

The gray band represents the uncertainty (tolerance) band of the LDR – GL5528 sensor.

The circuit in which a photoresistor is inserted is called a voltage divider and is the same circuit used to measure the unknown resistance in the ohmmeter seen in the previous lesson, i.e. two resistors are put in series, one of which is known, and the voltage value is measured. (Vm) at the junction point of the two resistors. Knowing the voltage applied to the circuit (5 V) it is possible to determine the value of the unknown resistance of the photoresistor and therefore to measure the brightness:

C:\Users\Francavi\Documents\Arduino Corso\Foto\Fotoresistore.png

We make Arduino measure the voltage Vm by bringing the signal to its analog PIN, for example A0, at this point, known the voltage Vm, we know the voltage applied to the known resistance, which is obtained by deduction, that is: 5 V – Vm, consequently we can calculate the electric current “I” which according to Ohm’s law (V = R x I) is equal to (using the inverse formula):

and finally we can calculate the value of the unknown resistance:

If we also have the correspondence table between the degree of brightness (which is measured in lux) and the resistance value, we also know how much light is hitting the photoresistor moment by moment. For example, the manufacturers of photoresistors release what in jargon are called data-sheets (i.e. technical sheets) of the components (an example is the figure below referring to the photoresistor GL5528):

which tells us that with 10-15 lux of brightness, a resistance value of about 10-15 kOhm corresponds.

Since I believe I have reached and passed the attention curve… and therefore I am sure that from this moment on you will no longer receive anything…, let’s move on to practical things and therefore let’s move on to carry out the following project.

Project 8 - Twilight Switch with Photoresistor

For this project we need:

The wiring diagram is:

For assembly, follow the diagram below:

After the connections we move on to write the sketch.

Connect the Arduino to the PC via the USB cable and launch the Arduino IDE application by double clicking on its icon.

Since when you open the IDE it usually loads the last written sketch, we start with a clean sketch so as not to create confusion. To do this, click on “File” and then on “New”:

After creating a new file, let’s recopy the sketch below:

Once the code has been written, 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 for loading and on the lens for the serial monitor:

Once you have started the sketch, do some checks, lowering the brightness of your room and raising it, when the room becomes dark then Arduino commands the lighting of an LED (the reference value you can lower or increase it according to the brightness conditions of your room).

Video-Project 8 - Twilight Switch with Photoresistor

Analysis of the sketch: Twilight Switch with Photoresistor

Analyzing the sketch we see that it is substantially similar to the previous one on the Ohm meter, so there would be nothing to highlight apart from the use of the “if” control structure.

The control structure works like this: if the condition between the round brackets of the if is true, then Arduino will execute the instructions contained in the curly brackets of the if, otherwise it means that the condition is not verified and everything that is enclosed in will be executed the braces of the else.

The syntax is as follows:

if (condition) {
else ) {

Curiosity: What is Light

Until the early 1900s, Light was thought to consist of electromagnetic waves and as such it followed the laws of classical electromagnetism; the waves consisted of two sinusoidal components perpendicular to each other (see animated gif: blue magnetic field and red electric field):

The frequency of these waves, that is the periodicity with which the waves are repeated, if it was in the range between 400 and 700 nanometers of wavelength (it is called spectrum, the range of frequencies), could be visible to the human eye (spectrum of visible light). Each frequency of this spectrum also defines the color of the light and the sum of all the frequencies of visible light form the so-called White Light which is then that emitted by the sun.

At the beginning of 1900, in particular between 1900 and 1905, Max Planck and Albert Einstein with the theories and experiments of quantum neo-physics, introduced the concept of photon, and therefore defined the light composed of photons or particles of zero mass, but made of energy alone.

This particle, the photon, also has the properties of being an electromagnetic wave.

Project 9 - Luxmeter with Arduino

Also in this project with Arduino we will create a measuring instrument, that is the Luxmeter. What is the Luxmeter used for? It is used to measure the light intensity present in a certain environment or how much light is hitting an object … you know the tools that photographers used? well! those were essentially lux meters; once the light was measured, they gave indications on the shutter opening time and on the aperture of the diaphragm.

For this project we need:

The wiring diagram is the following and is identical to the previous one:

For assembly follow the diagram below (like the previous one):

Before moving on to the sketch, a little explanation is needed on how to obtain the lux value of the brightness by measuring the resistance value of the photoresistor, in essence we will use the table already described above, namely:

the table refers to the GL5528, obviously if you were to use another type of photoresistor, the table will be rebuilt in the same way as I did above.

For the association of the values in the table we will use what in computer jargon is called the “nested if” method, this method is generally avoided, but for educational reasons I propose it to you.

At this point, click twice on the Arduino icon on the Desktop and the IDE opens and copy the following sketch, please follow each step indicated:

Once the code has been written, launch the verification precompilation (check mark), it will ask you to save the sketch (you can change the name) and then click on the arrow to load and then on the lens to access the serial monitor.

Started the serial monitor, the result is this:

Video-Project 9 - Luxmeter with Arduino

Sketch analysis: Luxmeter with Arduino

The peculiarity of the sketch of this project is that of having created correspondence ranges of the resistance values to the illuminance values and therefore the most appropriate illuminance value is chosen according to the resistance value, this was done using the nested if, that is, after the else that theoretically establishes the alternative to a condition and closes the check (as happens with the sketch of the previous project), a new condition is immediately re-entered to be checked with a new “if” and this happens 6 times. As I said at the beginning, this programming methodology has only a didactic purpose, generally we try to avoid nested ifs and C ++ also provides other solutions that we will see in other projects.

The PWM signal - Pulse Width Modulation

We know that Arduino has 14 digital PINs, that is, they are able to receive at the input, or give an output signal with only two states, HIGH and LOW.

The Digital PINs are indicated with numbers ranging from 0 to 13, but paying attention some of them also have a wave symbol “᷉” in addition to the number. Those PINs are Digital PINs with the possibility of giving an output voltage of the PWM type, Pulse Width Modulation, that is an electrical voltage with modulated pulse width. The Digital PINs with this functionality are: 3, 5, 6, 9, 10 and 11.

C:\Users\Francavi\Documents\Arduino Corso\Foto\ARDUINO_UNO_A06.png

Let’s see what we can do with these PINs with the ondina (in jargon it is called “tilde”).

The PWM signal is a signal that is always based on the principle of on or off (therefore it maintains the characteristics of the two states HIGH and LOW), but if we consider a period of time (called: cycle) and in this period we are going to modify the duration of holding the high state, rather than the low one, and we repeat it for all the cycles, the average value of the signal that we have at the PIN is no longer 0V or 5V, but will be a value between 0 and 5V.

The next figure explains this concept, but let’s see it even better, with the next figure.

In the first case we have that the value of 5 V is not maintained over the cycle time, so the signal is equal to 0% of the 5 V voltage, i.e. the digital PIN has an average value of 0 V at the output.

In the second case, 5 V is maintained for 25% of the cycle time, i.e. 25% of 5V, so the output digital PIN voltage has an average value of 1.25 V.

In the third case, 5V is maintained for 50% of the cycle time, i.e. 50% of 5V, so the output digital PIN voltage has an average value of 2.5 V.

In the fourth case, 5V is maintained for 75% of the cycle time, i.e. 75% of 5V, therefore the output digital PIN voltage has an average value of 3.75 V.

In the fifth case, the 5V is maintained for 100% of the cycle time, that is, 100% of 5V, therefore the voltage at the output digital PIN has an average value equal to 5 V.

To a PWM digital PIN we can give values between 0 and 255 (where 0 indicates 0 V and 255 indicates 5 V – essentially 256 values).

The instruction, with the related syntax, to assign a PWM signal to a digital PIN is as follows:

Therefore, summarizing the above in a schematic diagram, and assuming to use the PIN n. 11 for a PWM type signal, we have:

Obviously we can also use the intermediate values and not only those indicated.

The next project shows in a practical way an interesting application of the PWM signal to digital PINs. In fact, just think of an Arduino function that allows us to adjust the brightness of an LED (but it could be anything else, for example the lights in our house, the rotation speed of a motor, ….) by acting on the PWM digital PINs , but I will say more, we can adjust this variation to other external phenomena as well.

The following project links the measurement of external brightness detected by a photoresistor to the brightness that we want to give in an environment, but before going into the project, however, I would like to highlight something that will be very useful in many applications.

Relationship between Analog PINs and PWM Digital PINs

As previously explained, an Analog PIN assumes values between 0 and 1023 (where 0 indicates 0V and 1023 indicates 5V – essentially 1024 values), while a PWM digital PIN assumes values between 0 and 255 (where 0 indicates 0V and 255 indicates 5V – essentially 256 values).

At this point, thanks to a simple proportion of our holy mathematics, we are able to write a formula that defines the voltage of a PWM digital PIN as a function of the value detected by the analog PIN (for example: A0). In fact, the proportion is as follows:

256: 1024 = X: reading at PIN A0

(to read: 256 stands for 1024 as the unknown value to be obtained and sent to the PWM digital PIN stands for reading at Pin A0)

When the unknown is in the proportional means, we know that to obtain it, multiply it between the proportional extremes and divide by the known term between the proportional means.


but 256/1024 = 1/4, so to have the corresponding PWM signal value, having an analog signal, just divide this last value by 4.

Project 10 - Night and Day with PWM signal

Free Day and Night Clipart in AI, SVG, EPS or PSD

Suppose we want to keep the light in an environment that is always constant, so as the sun goes down, artificial lighting gradually integrates the sunlight to always maintain the same level of brightness in the environment. Well the project that I present to you allows just this functionality.

For this project we need:

The wiring diagram is the following and is identical to the previous one:

For assembly follow the diagram below (like the previous one):

At this point, click twice on the Arduino icon on the Desktop and the IDE opens and copy the following sketch, please follow each step indicated:

Once the code has been written, launch the verification precompilation (check mark), it will ask you to save the sketch (you can change the name) and then click on the arrow to load and then on the lens to access the serial monitor.

Started the sketch on Arduino, if everything has been done correctly, we have that by shading the photoresistor sensor (even with a pen cover), the brightness of the LED increases, while on the contrary, by making more light reach the sensor, the LED tends to go out, all with a FADE effect, i.e. with a gradual variation.

Video-Project 10 - Night and Day with PWM signal

Sketch analysis: Night and Day with PWM signal

In this sketch there are a lot of interesting things to analyze. Let’s review them all starting from the main things:

  1. You can see how the PWM signal is applied to the digital PIN, in fact the analogWrite instruction is used for a PWM digital PIN instead of the classic digitalWrite instruction. It can be seen in the line where it is: analogWrite (11, pwm value);
  2. We have seen how a value coming from an analog PIN is converted into a corresponding value of a PWM Digital PIN, just divide the reading on the Analog PIN by 4, this can be seen on the line: int valuepwm = reading / 4;
  3. Since at the time of the project it was night and in my room at most I was able to get 50 lux and no more, you understand very well that the LED always started from an on condition. So I used a function called map which basically does nothing but calculate proportions and therefore what was my possible range of values ​​of the PWM signal (unable to run the project in full sunlight) which ranged from a minimum of 200 to a maximum of 255, I remapped it to a new scale from 0 to 255.

The syntax for the map function is:

map (value, fromLow, fromHigh, toLow, toHigh)

you see it applied to the sketch on the staff: valuepwm = map (valuepwm, 200, 255, 0, 255);

where the variable valuepwm is assigned the new remapped value of the value that the same variable had before. Since in the remapping it could happen to have negative values that are considered by the PWM digital PIN as HIGH value, then I also had to insert in control with an if in the line: if (valuepwm <0) {valuepwm = 0;}

Project 11 - Return of the Cylons

I’ve always been passionate about the Battlestar Galactica TV series and the thing that intrigued me was how they managed to give the movement of the light that somehow had to represent the view of the Cylon robots. Good! with the project we are going to develop you too can make a Cylon head and why not, use it for carnival.

For this project we need:

The wiring diagram is as follows:

For assembly follow the diagram below:

Now open a new window for the sketch by double clicking on the Arduino application and write the code below and save the file:

Important: the sketch above was written in that form to take into account the still little knowledge of the programming language for Arduino, but using arrays (i.e. variables that can contain multiple values) the code can be very simplified:

Upload the sketch and you will get a nice robotic eye peering effect, especially if you cut out the cardboard with the Cylon face and create the slot in which to insert the LEDs…. Supercar’s famous KITT car also had a similar effect …

Video-Project 11 - The return of the Cylons

Analysis of the Sketch: Return of the Cylons

Not considering the second transcribed sketch, because the topics covered will be seen later, from the first sketch we can observe that the only new topic introduced is the for loop.

The for loop is used when we need, within the body of the program, to carry out repetitive operations for a certain number of times. In fact, in this case it was used to drive the LED switching off gradually using the variable “i” which, starting from the maximum value of 255, decreased at each cycle and the luminous intensity of the LED consequently also.

The syntax for the for loop is:

for (initialization; condition; increment) {

// statement (s);


In our sketch it was using for example:

for (int i = 255; i> = 0; i–) {

analogWrite (10, i);

delay (delay2);


The integer variable “i” starts from the value of 255 and decreases to zero; as long as this condition is true, the for loop repeats itself and in particular executes what is between the curly brackets, i.e. it writes in the PWM digital PIN a value equal to the variable i (which is being decremented) and then turns off gradually the LED connected to PIN 10.

If you found the lesson interesting, make a donation you will help me realize many others.