Arduino Tutorial (page 5)

  

 

Page 1 Page 2 Page 3 Page 4 (Examples) Page 5 (Examples)
⚛ Introduction to Arduino ⚛ Ultrasonic Sensors ⚛ Input/Output Port Management Functions (Pins) ⚛ The Flashing LED ⚛ Led Chase Effect
⚛ Supply of necessary components ⚛ Arduino Shields ⚛ Input - Output Functions ⚛ Fade in-Fade out ⚛ Led Chase Effect with potentiometer
⚛ LEDs ⚛ Input/Output Ports (Pins) ⚛ Digital Outputs ⚛ Fade in-Fade out, Blink at peaks ⚛ Effects by detecting light (Led effect + light sensor)
⚛ Buttons ⚛ Power Supply ⚛ Digital Inputs ⚛ Gradual increase and decrease of brightness with a potentiometer ⚛ Using sound (Buzzer)
⚛ Potentiometers ⚛ Arduino (IDE) Installation ⚛ Analog Outputs (PWM pins) ⚛ Using the serial screen ⚛ Sound & Light Sensor
⚛ Piezo Buzzers ⚛ Programming Arduino - Basic Functions ⚛ Analog Inputs ⚛ Playing with colors (RGB Led) ⚛ Moving shafts (Servos)
⚛ Photoresistors (LDR) ⚛ Basic structures and programming functions ⚛ Time Function - delay () ⚛ Making an RGB Led ⚛ Moving Servos with a potentiometer
⚛ Servo Motors ⚛ Type of variables ⚛ Time Function - delayMicroseconds () ⚛ Traffic lights ⚛ Motor Control (DC Motor)
⚛ DC Motors ⚛ Programming Comments ⚛ Time Logging Function - millis () ⚛ Pedestrian traffic lights ⚛ Controlling 2 or more motors
    ⚛ Value Mapping Function - map () ⚛ Pedestrian traffic lights and stop button ⚛ Using ultrasound to measure a distance
    ⚛ The Serial Communication Port (Serial)    
    ⚛ Selection Structure    
    ⚛ Repeat Structure (for)    
    ⚛ Support Libraries    

 

 

Led Chase Effect

In this example, a sufficient number of LEDs will be used, depending on how they are available in your workshop, e.g. 8. You will connect them in your known way to corresponding pins and the goal is to light one after the other, while extinguishing the previous one to make a beautiful effect. When it reaches the last led, the wave will have to go back.

We will need a sufficient number of leds and corresponding resistances. We follow the classic connection for LEDs and resistors, as shown in next picture.

Piezo-Buzzers

For this task, we will need to turn our LEDs on and off in ascending order until the last and vice versa, that is, turn them on and off in descending order. This is done with several commands or, preferably, with a iterative process and a table with values ​​of led numbers, so that we have a more concise and efficient code.

1. Initially use variables for each led and manage them in the known way (initialization, write value with digitalWrite (led, value)).
2. Complete the above code and save it.
3. In a new program (or copy of the previous program), try to use the repeat command to set the LEDs as output, turn them on, turn them off. For example, you could turn on LEDs with commands:

For (i = 0; i <= 7; i ++) {
DigitalWrite (Led [i], HIGH);
Delay (200);
DigitalWrite (Led [i], LOW);
}

4. Try using the same procedure to initialize Leds as output. Notice that the table structure is used to group similar things.

The code without a table:

int lPin1 = 6;
int lPin2 = 7;
int lPin3 = 8;
int lPin4 = 9;
int lPin5 = 10;
int lPin6 = 11;
int lPin7 = 12;
int lPin8 = 13;
void setup() {
pinMode(lPin1, OUTPUT);
pinMode(lPin2, OUTPUT);
pinMode(lPin3, OUTPUT);
pinMode(lPin4, OUTPUT);
pinMode(lPin5, OUTPUT);
pinMode(lPin6, OUTPUT);
pinMode(lPin7, OUTPUT);
pinMode(lPin8, OUTPUT);
}
void loop() {
digitalWrite(lPin1, HIGH);
delay(200);
digitalWrite(lPin1, LOW);
digitalWrite(lPin2, HIGH);
delay(200);
digitalWrite(lPin2, LOW);
digitalWrite(lPin3, HIGH);
delay(200);
digitalWrite(lPin3, LOW);
digitalWrite(lPin4, HIGH);
delay(200);
digitalWrite(lPin4, LOW);
digitalWrite(lPin5, HIGH);
delay(200);
digitalWrite(lPin5, LOW);
digitalWrite(lPin6, HIGH);
delay(200);
digitalWrite(lPin6, LOW);
digitalWrite(lPin7, HIGH);
delay(200);
digitalWrite(lPin7, LOW);
digitalWrite(lPin8, HIGH);
delay(200);
digitalWrite(lPin8, LOW);
}

 

The Code using table:

int ledPin[8]; // create 8 positions table
int i;
void setup() {
for (i=0;i<8;i++) {
ledPin[i] = i+6; // put values at Pins from 6 to 13
pinMode(ledPin[i], OUTPUT);
}
}
void loop() {
for (i=0;i<=7;i++) {
digitalWrite(ledPin[i], HIGH);
delay(200);
digitalWrite(ledPin[i], LOW);
}
}

 

 

Led Chase Effect with potentiometer

In this example, we will adjust the circuit and the program of the previous worksheet so that the speed that is transmitted to our effect is not constant. In the previous example we gave a delay (500) so that each LED stays on for half a second before it goes out and proceeds to the next one. Now we will use a potentiometer so that on the basis of this (the value it gives us) we will increase or decrease the propagation velocity of the effect, ie the delay time.

For this work we will need that in the previous example, leds and resistors, as well as a potentiometer. The potentiometer has been used again in a previous example, so the reader is familiar with it. It is linked to an analog input from which we read its values. The connection is simple, as shown in Figure 32. We need a source (5V), ground (GND) and the middle foot connected to an analog input. The prices that will come from there will range from 0 to 1023, so we will do the corresponding conversion to give them time-lag. The potentiometer is also placed directly on the breadboard if it has the appropriate edges.

Piezo-Buzzers

We need to adapt the code we made in the previous example to give the delay according to the value we read from the potentiometer. Note that a large value in the potentiometer will mean high switching speed, so short time in delay. The price to be given should be inversely proportional to the price we read!

There is, of course, the possibility of connecting our potentiometer to the ground first and then the source - in this case as we turn our control more, so we reduce the value we read. In this case it is sufficient to use a similar size with the potentiometer value in the delay we give. So experiment and record your observations!

The Code:

int ledPin[8]; // create 8 position table
int potPin = A4; // pin of potentiometer
int interval = 200; // starting value of 200 at the change
int i;
void setup() {
for (i=0;i<8;i++) {
ledPin[i] = i+6; // put as values the pin from 6 to 13
pinMode(ledPin[i], OUTPUT);
};
pinMode(potPin, INPUT);
}
void loop() {
for (i=0;i<=7;i++) {
interval = analogRead(potPin);
digitalWrite(ledPin[i], HIGH);
delay(interval);
digitalWrite(ledPin[i], LOW);
}
}

 

 

Effects by detecting light (Led effect + light sensor)

In this example we will create a device that reacts to visual stimuli. It will consist of a led which will vary its intensity depending on how much light it is in a photosensitive resistance.

For this task we will need a led and a resistance connected to our Arduino. To recognize the brightness we use a photoresistor, which increases or decreases its size depending on the brightness of the area in which we are. This resistor will be placed in series along with a normal resistor (about 1MΩ), and so we have a three-array arrangement: one at the source, one (which connects the two resistors) to an analog input and one to the ground. The device simulates a potentiometer (remember the corresponding example) where the role of the potentiometer switch (voltage variation we read) plays the photosensitive resistance.

Piezo-Buzzers

The programming of this circuit is totally similar to that of the potentiometer sheet. We read a value from the analog input and we adjust this value properly to give it as an analog output to the pin that we connected to our led. Remember to properly adjust your input (values ​​0-1023) to the output to led (values ​​0-255). To do this, you can do some division (eg entry value with 4) or use the map function that does exactly that!

Experiment 1: Experiment with photosensitive resistance. First connect one foot to the source and foot of the simple earthing resistor. Run your schedule. Next, connect the light-sensitive resistor foot to the ground and the simple stand at the source. What do you notice happening?

Experiment 2: Connect the legs of light-sensitive resistor with long wires to move around with it, and so detect the brightness changes!

The Code:

int ledPin = 10;
int resPin = A1;
int resVal = 0; // Here we read the value of the resistance

int ledVal = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(resPin, INPUT);
}
void loop() {
resVal = analogRead(resPin);
ledVal = map(resVal, 0, 1023, 0, 255);
analogWrite(ledPin, ledVal);
// If we did not use the map, we would write analogWrite (ledPin, resVal / 4);

delay(50);
}

 

 

Using sound (Buzzer)

In this example we will use a simple layout with sound. There are components that, when received, generate sounds and are in different types. In this exercise we will connect such a loudspeaker and by playing with the stream we will try to produce various sounds.

For this task we will need a speaker. These speakers work with direct current (source - ground), so we have a device where one end is connected to the source (5V) and the other to the ground (GND). This would give a steady stream of current and thus a steady sound. In figure below, instead of the source, we use an Arduino (PWM) port to allow us to vary the current intensity and thus the sound produced.

Piezo-Buzzers

This circuit is quite simple. It is enough to initialize the Arduino pin and then give the appropriate commands to create different sound levels.

1. Make the appropriate initializations.
2. In a repetitive process, give gradual values ​​to the pin to listen to a range of sounds. Start at 0 and gradually increase the volume up to 255, giving you an appropriate time (eg 500msec) to listen to each sound.
3. You can also create the reverse process, that is to gradually reduce the volume until it reaches 0.

The Code:

int sndPin = 10;
int i;
void setup() {
pinMode(sndPin, OUTPUT);
}
void loop() {
for (i=0;i<=255;i=i+5) {
analogWrite(sndPin, i);
delay(50);
}
}

 

 

Sound & Light Sensor

In this example we will create a device that reacts to visual stimuli. It consists of a loudspeaker that changes its sound depending on how much light it is on a photosensitive resistor. The example is similar to what you did with the photosensitive resistance and led.

For this task we will need a speaker connected to a pin. To recognize the brightness we will use a photoresistor. This resistance will be placed in series along with a normal resistor (about 1MΩ), so we will have a three-array arrangement: one at the source, one (which connects the two resistors) to an analog input of Arduino (e.g. A1) and one on the ground. You can see the layout in Figure below. Note that the device simulates a potentiometer (remember the corresponding example), where the role of the potentiometer switch to change the voltage we are reading will play the resistance that changes its characteristics with light.

Piezo-Buzzers

The programming of this circuit is totally similar to that of the worksheet 13, as well as the potentiometer. We read a value from the analog input and this value is given as an analog output in our led. Accurately adjust your input (values ​​0-1023) to the output to the led (values ​​0-255), using the corresponding function.

Experiment 1: Experiment with photosensitive resistance. First connect one foot to the source and foot of the simple earthing resistor. Run your schedule. Next, connect the light-sensitive resistor foot to the ground and the simple stand at the source. What do you notice happening?

Experiment 2: Connect the legs of light-sensitive resistor with long wires to move around with it, and so detect the brightness changes!

The Code:

int sndPin = 10;
int resPin = A1;
int resVal = 0; // Here we read the value of the resistance

int ledVal = 0;
void setup() {
pinMode(sndPin, OUTPUT);
pinMode(resPin, INPUT);
}
void loop() {
resVal = analogRead(resPin);
ledVal = map(resVal, 0, 1023, 0, 255);
analogWrite(sndPin, ledVal);
//
If we did not use the map, we would write analogWrite(sndPin, resVal / 4);
delay(50);
}

 

 


Moving shafts (Servos)

A very useful mechanism that we can connect and control is the servo, a device that can move a shaft in a 180 degree range. In this exercise we will see the basic connection and planning of a Serb.

For this work we will need a Serb. The servo consists of three cables: one for the source (5V), one for grounding and one for servicing the servo via an Arduino pin. Colors will guide us on the connection. At the TowerPro SG90 we have three cables - one (orange) connected to the source (5V), one (brown) to the ground (GND) and one (yellow) to the control pin. You can see the circuit and the wiring in Figure below.

Piezo-Buzzers

In order to be able to use a servo, we need to include the library in our program. We also need to use specific functions from this library. Look for similar information online.

1. Declare a variable for the pin connected to the servo
2. Include in your program the appropriate library for the Serbian.
3. Declare a servo variable to gain access to its mechanism.
4. Make the appropriate initialization for the port you are using for the servo. For this port, we do not declare that the setup () function is output but that we commit using the attach (pin) command.
5. Using the write () command, give the appropriate commands to your servo so that:
• Start at 90 degrees
• Turn 180 degrees
• return to 90 degrees
• Turn to 0 degrees,
Also taking into account the times that will be needed for turns.

The Code:

#include
int sPin = 10;
Servo s;
void setup() {
s.attach(sPin);
}
void loop() {
s.write(90);
delay(50);
s.write(179);
delay(50);
s.write(90);
delay(50);
s.write(0);
delay(50);
}

 

 

Moving Servos with a potentiometer

In this example we will extend the circuit of the previous worksheet with a potentiometer. The device we use for this is similar to what we used for the potentiometer in previous examples. Our device will work as follows: Turning the potentiometer knob will turn our servos accordingly.

For this task we will need a potentiometer and a servo. The connection for both of these has been analyzed in previous examples, so the reader can refer to them for details. In figure you can see the connection. The potentiometer is also placed directly on the breadboard if it has the appropriate edges.

Piezo-Buzzers

For this work, we will need to make all the statements of variables and initializations we saw for the potentiometer and the servo. In particular:

1. Declare variables and the necessary library we need for the servomotor, as well as make any necessary initializations.
2. In iterations you will read the potentiometer value and, using this value, you will give the servo the appropriate command to move. Caution: The value we get from the potentiometer is from 0 to 1023 and we have to adapt it appropriately for the servomotor.
3. Give adequate time to advance the servo.

The Code:

#include
int sPin = 10;
int potPin = A1; // the pin of potentiometer
Servo s;
int potVal = 0; // the value of potentiometer
int sVal = 0;
void setup() {
s.attach(sPin);
pinMode(potPin, INPUT);
}
void loop() {
potVal = analogRead(potPin);
sVal = map(potVal, 0, 1023, 0, 180);
s.write(sVal);
delay(50);
}

 

 

Motor Control (DC Motor)

In this example we will see basic DC motor control and test. In this example we will connect a motor and in our program we will activate it gradually, giving analogous values ​​to the pin to which we have connected it. This gradual activation can be compared to speed increase.

For this work we will need a motor. Motor polarity is not important at this stage - depending on how legs are connected, we will have a clockwise or left-handed axle. You can see the connection in picture.

Piezo-Buzzers

The programming of this circuit is quite simple at this point.

1. Activate the pin that you connected your motor to as you know it as output.
2. Set voltage at your output (motor pin) using the appropriate function.
3. Give analog outputs (motor pin) incrementally increasing values ​​(0 - 255), using the appropriate function.
4. Use a reasonable time delay between commands so you can sense the difference in rotation speed.

The Code:

int mtrPin = 10;
int i;
void setup() {
pinMode(mtrPin, OUTPUT);
}
void loop() {
digitalWrite(mtrPin, HIGH);
delay(3000);
digitalWrite(mtrPin, LOW);
for (i=0; i<=255; i=i+5) {
analogWrite(mtrPin, i);
delay(100);
}
}

 

 

Controlling 2 or more motors

To test two or more engines at the same time, we usually use an H-bridge. A classic chip that we can use to control two motors is the L298N. In this example we will use two engines that will be controlled by this chip. The two engines can conveniently drive a car or a two-wheeler *.

Refer to the corresponding paragraph of the L298N connection theory. We have to pay attention to the polarities of the engines, because if they are connected upside-down they will turn in the opposite direction we want.

After connecting the motors and the bridge in the way described above, start writing a program that will implement basic route operations. Specifically:

1. Create the appropriate variables and initializations for your pins.
2. Write the code that will make your engines move forward.
3. Write the code that will make your engines stop completely.
4. Write the code that will make your engines move backwards.
5. Write the code that will make your vehicle turn right. To do this, the right engine should move forward while the left is stationary.
6. Write the code that will make your vehicle turn left. To do this, the left engine should move forward while the right one remains stationary.
7. With the help of your teacher, try to create new functions with the functions you just made to call them when you want.
8. How can you build a library with them? What else should your library contain?

* There are four L293D motors available for 4 motors, but they are low in power and are not recommended unless there is a special reason to use them.

The Code:

//motor A
int dir1PinA = 7;
int dir2PinA = 5;
int speedPinA = 6;
//motor B
int dir1PinB = 4;
int dir2PinB = 2;
int speedPinB = 3;
int speed = 255;
int time = 5000;
void setup() {
pinMode (dir1PinA, OUTPUT);
pinMode (dir2PinA, OUTPUT);
pinMode (speedPinA, OUTPUT);
pinMode (dir1PinB, OUTPUT);
pinMode (dir2PinB, OUTPUT);
pinMode (speedPinB, OUTPUT);
}
void loop() {
// all motors run forward
analogWrite (speedPinA, speed);
analogWrite (speedPinB, speed);
digitalWrite (dir1PinA , HIGH);
digitalWrite (dir2PinA, LOW);
digitalWrite (dir1PinB, HIGH);
digitalWrite (dir2PinB, LOW);
delay(time);

// all motors run backward
analogWrite (speedPinA, speed);
analogWrite (speedPinB, speed);
digitalWrite (dir1PinA, LOW);
digitalWrite (dir2PinA, HIGH);
digitalWrite (dir1PinB, LOW);
digitalWrite (dir2PinB, HIGH);
delay(time);

// stop all motors
digitalWrite (speedPinA, LOW);
digitalWrite (speedPinB, LOW);
digitalWrite (dir1PinA , LOW);
digitalWrite (dir2PinA, LOW);
digitalWrite (dir1PinB, LOW);
digitalWrite (dir2PinB, LOW);
delay(time);

// run the right motor
analogWrite (speedPinA, speed);
analogWrite (speedPinB, LOW);
digitalWrite (dir1PinA , HIGH);
digitalWrite (dir2PinA, LOW);
digitalWrite (dir1PinB, HIGH);
digitalWrite (dir2PinB, LOW);
delay(time);

// run the left motor
analogWrite (speedPinA, LOW);
analogWrite (speedPinB, speed);
digitalWrite (dir1PinA , HIGH);
digitalWrite (dir2PinA, LOW);
digitalWrite (dir1PinB, HIGH);
digitalWrite (dir2PinB, LOW);
delay(time);
// stop all motors
digitalWrite (speedPinA, 255);
digitalWrite (speedPinB, 255);
digitalWrite (dir1PinA , LOW);
digitalWrite (dir2PinA, LOW);
digitalWrite (dir1PinB, LOW);
digitalWrite (dir2PinB, LOW);
delay(time);
}

 

 


Using ultrasound to measure a distance

In this example we will use an ultrasound device, measuring the distance with its help. For this reason we will use the HC-SR04, which was presented in the corresponding chapter of the theory.

The layout has four connection points. We connect the source (5V), ground (GND) and two pin, one for the trigger and one for the echo.

Piezo-Buzzers

Connect the terminals appropriately. For programming, we will need to send a signal and wait a little while to read it back.

1. Set the pins as input or output appropriately.
2. Activate the serial screen at 9600 rpm.
3. Set two values ​​for the distance you are reading (in cm), e.g. 0 and 200 to check that you are reading values ​​from 0 to 2 meters.
4. Reset the pulse to the trigger to make sure you are not sending anything first by using the digitalWrite () function and waiting for 2μs.
5. Send a pulse to the trigger and wait 10 μs.
6. Reset the pulse, and read the echo pulse duration using the pulseIn (echoPin, HIGH) function;
7. Calculate the distance in front of you the obstacle according to the type we mentioned (distance = duration / 58.2?)
8. Check whether the distance is within the limits you have set.
9. Send the distance to the serial screen so you can experiment.
10. Put a 50 ms delay before restarting your program.

The code:

int echoPin = 12; // Echo Pin
int trigPin = 13; // Trigger Pin
int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
/* we send waves of sound and take them back, trying to measure the distance from their speed */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
// distance estimation (in cm) based on the speed of sound
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
/* Out of limit */
Serial.println("Out of limit");
delay(100);
}
 else {
/* successful reading */
Serial.println(distance);
delay(50);
};
// delay 50ms before next reading
delay(50);
}