hispalis robiotics arduino trainer v1

34
Hispalis RobIOTics Arduino Trainer v1.0 User guide January, 2018 Hispalis RobIOTics Arduino Trainer v1.0 Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1 de de 34 34

Upload: others

Post on 11-Apr-2022

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Hispalis RobIOTics Arduino Trainer v1

Hispalis RobIOTics

Arduino Trainer v1.0

User guide

January, 2018

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 11 de de 3434

Page 2: Hispalis RobIOTics Arduino Trainer v1

Indice

IntroductionElementos de Arduino Trainer v1.0Arduino Trainer: Leds integrados ( D3, D5, D6 )Arduino Trainer: Sensor Ultrasónico ( D 2 , D 4 )Arduino Trainer: Salidas para módulo L9110 ( D 7 , D 8, D9, D10 )Arduino Trainer: Conexión de módulo driver de motores L9110Arduino Trainer: Pulsadores ( D12, D13 )Arduino Trainer: Sensor de línea ( A0 A1 A2 A3 )Arduino Trainer: Salida Buzzer ( D11 )Arduino Trainer: Conector Bluetooth ( RX, TX )Arduino Trainer: Conector I 2 CArduino Trainer: Conector de AlimentaciónAlimentando Arduino UNOAnalizando el pin VIN de Arduino Trainer v1.0Alimentando Arduino Trainer v1.0 con Arduino UNO

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 22 de de 3434

Page 3: Hispalis RobIOTics Arduino Trainer v1

Introduction

Arduino Trainer v1.0 is a shield for Arduino UNO. It is the best solution to get to knowcomputer programming and robotics.

A shield is a printed circuit board ( also known as PCB ) plugged in over Arduino UNO. Theshield integrates electronic devices providing new posibilities to the original Arduino board. Sincethe electronic devices are soldered in the PCB and connected directly to Arduino pins, ArduinoTrainer reduces complexity wiring, minimizing errors.

Consider a sample circuit including an ultrasonic sensor, two LEDs ( Light Emitter Diode )and two switches ( this could be an alarm circuit ). We should need from 8 to 12 wires to arrange allthese devices connected in a breadboard. A breadboard is a perfect solution for prototipying simplecircuits, but the more complexity in the circuit we have ( adding new hardware ), the more cableswe add, and finally our breadboard becomes a mess. The risk of any kind of error is allways nearand growes exponentially up. In addition, if you get a problem, it is difficult to diagnose it.

Arduino Trainer integrates a complete set of electronic devices, reducing most of neededcables. The full set of integrated devices is listed below:

• Three LEDS connected to PWM outputs

• Two switches

• HCSR04 ultrasonic sensor

• Two PWM GPIO connector

• Two digital GPIO connector

• Connector for 2 LDRs ( light dependent resistor )

• A four channels analog line sensor

• Buzzer connector

• I2C connector to expand Arduino Trainer

• Bluetooth connector for HC-06 bluetooth module

• 5V Supply / GND Supply connectors

• RESET switch

With all these integrated devices, we can arrange a programming lab covering multipletopics and samples. With Arduino Trainer we focus barely in programming topics, instead ofwasting time checking cables or hardware connections

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 33 de de 3434

Page 4: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer is plugged in over Arduino UNO board, and voltage supply is provided viaArduino and its USB PC connection. However, there are different scenarios for Arduino to beexternal voltage supplied.

With a built in bluetooth connector, ready for a HC-06 bluetooth module, Arduino Trainer iscapable to dive in the IOT ( Internet of Things ) ocean. We may switch a LED on/off, use sliders, oreven control a robot using a mobile using AppInventor. We can even connect to a PC runningProccessing to check/control all Arduino input/outputs.

Finally, TrainerBot is a two wheels DIY robot using Arduino Trainer v1.0. TrainerBot is aline follower, avoiding obstacles, bluetooth controlled robot. The chassis is available inThingiverserBot, ready to be printed using a 3D printer

Hispalis RobIOTics TrainerBot

https://www.thingiverse.com/thing:2695236

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 44 de de 3434

Page 5: Hispalis RobIOTics Arduino Trainer v1

Elementos de Arduino Trainer v1.0

The picture below shows all the hardware devices integrated in Arduino Trainer v1.0

Our web http://www.hispalisrobiotics.com a complete set of sample programs is available.Available in github is the zip file to be downloaded.

You only need to download the file ArduinoTrainerv1.0..zip. This file must be uncompressedin our sketckes folder ( normally is called Arduino ). After restarting Arduino IDE, all the files willbe at your disposal in the menu

File → Proyects → ArduinoTrainerv1.0

You may upload and run all the programs using an Arduino UNO alone, and you don’t needto plug Trainer board in, but you will ( obviously ) need to wire all the hardware devices in abreadbord or similar. You will also need to check the pinout assignment for the involved devices( for instance, integrated LEDs in Arduino Trainer refer to digital gpios – general purposeinput/outputs – numbered 3, 5 and 6 ).

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 55 de de 3434

Page 6: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: LEDs integrados ( D3, D5, D6)

Arduino Trainer integrates three Light Emitter Diodes ( LED ), connected to the following Arduino UNO outputs:

• Red LED : pin 3• Yellow LED: pin 5• Green LED: pin 6

LEDs integrados en Arduino Trainer v1.0

The next sample program flashes all the LEDs secuentially

#define LED_ROJO 3#define LED_AMARILLO 5#define LED_VERDE 6void setup() { pinMode( LED_ROJO , OUTPUT ); pinMode( LED_AMARILLO , OUTPUT ); pinMode( LED_VERDE , OUTPUT );}void loop() { digitalWrite( LED_ROJO , HIGH ); delay( 1000 ); digitalWrite( LED_ROJO , LOW ); delay( 1000 ); digitalWrite( LED_AMARILLO , HIGH ); delay( 1000 ); digitalWrite( LED_AMARILLO , LOW ); delay( 1000 ); digitalWrite( LED_VERDE , HIGH ); delay( 1000 ); digitalWrite( LED_VERDE , LOW ); delay( 1000 );}

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 66 de de 3434

Page 7: Hispalis RobIOTics Arduino Trainer v1

All the LEDs are connected to PWM ( Pulse Width Modulation ) outputs. This means thatwe can define the brightness of each LED adjusting the amount of time between each LED’s on andoff state. If we want to test PWM, we should need to use a function as

analogWrite( led , value );

choosing value in the range { 0 – 255 }.

The following program is based in the example program “Fade”, available in the menu

Files → Examples → Basics → Fade

/* Fade This example shows how to fade an LED on pin 3 using the analogWrite() function. The analogWrite() function uses PWM, so if you want to change the pin you're using, be sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11. This example code is in the public domain. */

int led = 3; // the PWM pin the LED is attached toint brightness = 0; // how bright the LED isint fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:void setup() { // declare pin 3 to be an output: pinMode(led, OUTPUT);}

// the loop routine runs over and over again forever:void loop() { // set the brightness of pin 9: analogWrite(led, brightness);

// change the brightness for next time through the loop: brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade: if (brightness <= 0 || brightness >= 255) { fadeAmount = -fadeAmount; }

// wait for 30 milliseconds to see the dimming effect delay(30);}

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 77 de de 3434

Page 8: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: Sensor Ultrasónico ( D2, D4 )

Arduino Trainer integrates the popular ultrasonic ranging module HCSR04, a distancesensor including an ultrasonic transmitter and receiver.

Sensor Ultrasónico de distancia HCSR04

The pin assignment for the HC SR04 is listed below:

• HCSR04_TRIGGER: pin 2• HCSR04_ECHO: pin 4

The following program shows all the needed steps to program the HCSR04 ranging sensor.The data are visualized in the Serial Monitor included in Arduino IDE

#define HCSR04_ECHO 4#define HCSR04_TRIGGER 2

void setup() { pinMode(HCSR04_TRIGGER , OUTPUT); pinMode(HCSR04_ECHO , INPUT); Serial.begin( 115200); }

void loop() { int gap; for(;;) { gap = Distance_StandardTest(); Serial.println( "Distancia ... "+ String(gap) + " cm."); delay( 500); }}

/* Funcion: Distance_StandardTest() Devuelve en cm la distancia del sensor HCSR04 al objeto más cercano Funcionamiento: 1) Lanzamos un pulso de señal cuadrado. Para ello el pin TRIGGER a) Lo ponemos a LOW, y esperamos un tiempo a que se estabilice ( por si estaba en nivel HIGH )

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 88 de de 3434

Page 9: Hispalis RobIOTics Arduino Trainer v1

b) Lo ponemos a HIGH, y esperamos un tiempo c) Lo ponemos a LOW again 2) El sensor devuelve un pulso de entrada en el pin ECHO, que es el tiempo de ida y vuelta del sonido 3) Con una formula lo convertimos a cm.*/int Distance_StandardTest(void) { long duracion, distancia; // Pulso en TRIGGER digitalWrite(HCSR04_TRIGGER , LOW); delayMicroseconds(5); digitalWrite(HCSR04_TRIGGER, HIGH); delayMicroseconds(5); digitalWrite(HCSR04_TRIGGER, LOW); // Pulso de ECHO duracion = pulseIn(HCSR04_ECHO , HIGH) ; // Conversion a int. Podemos convertir a float ... distancia = (int) (duracion / 2 / 29.1 ) ; //Serial.println( "Distancia ... "+ String(distancia) + " cm.") ; return distancia;}

You can use external libraries to program the HCSR04 sensor. In adittion, NewPing libraryis a reliable, popular and easy to use library. To install and use it,

• Donload the library NewPing.zip: https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home

• Unzip the file in Arduino/libraries

NewPingExample program is located in

Files → Proyects → ArduinoTrainerv1.0 → Sensors → HCSR04 → NewPingExample// ---------------------------------------------------------------------------// Example NewPing library sketch that does a ping about 20 times per second.// ---------------------------------------------------------------------------#include <NewPing.h>#define TRIGGER_PIN 2 // 3 Hercules , 2 Trainer#define ECHO_PIN 4 // 2 Hercules , 4 Trainer#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() { Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.}void loop() { delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). Serial.print("Ping: "); Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range) Serial.println("cm");}

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 99 de de 3434

Page 10: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: Salidas para módulo L9110 ( D7, D8, D9, D10 )

In Arduino Trainer there is a multiple male conector ( MMC ) grouping the general purpose input/outputs D7, D8, D9 , D10 of Arduino UNO. The four otputs have a different behavior, that is

• Outputs D7 D8 Digital Output• Outputs D9 D10 PWM Output

Conector múltiple macho D7 a D10

The multiple conector has three rows of pins: one for the Arduino outputs , one connected tovoltage supply VIN, and the last one connected to ground signal GND. We can insert easily a servoconnector in Arduino Trainer MMC.

It is important to notice that the central row of pins VIN is not connected to 5V Supply. Wehave to connect VIN to the 5V Supply connector using a female to female wire. We can evenconnect an external 6V supply to VIN, to get a full supply in our devices, as servos.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1010 de de 3434

Page 11: Hispalis RobIOTics Arduino Trainer v1

In “Analizando el pin VIN de Arduino Trainer v1.0” you can see in detail the differentways to externally supply Arduino Trainer

If our desire is to design a robot using Arduino, the simplest robot is a two motor robot. Wemay design our own chassis, or simply search in Thingiverse the many and different chassisavailable. Then Arduino Trainer is a good chance to control it, reducing all the wiring.

Arduino Trainer can drive the two most popular kind of robots nowadays:

• Robots using continuous rotation servos (CRS )• Robots using a motor H bridge driver ( L9110 , L293D … )

Let us see how to connect a L9110 motor driver to Arduino Trainer.

Arduino Trainer: Conexión de módulo driver de motores L9110

The L9110S 2-Channel motor driver module is a compact board that can be used to drivesmall robots. This module has two independent motor driver chips which can each drive up 800mAof continuous current. The boards can be operated from 2.5V to 12V enabling this module to beused with both 3.3V and 5V microcontrollers. A PWM Pulse Width Modulation signal is used tocontrol the speed of a motor and a digital output is used to change its direction.

Driver L9110. Los conectores verdes son salidas de motores

a) L9110 driver inputs

The L9110 has four inputs, named { A-IA , A-IB , B-IA , B-IB } . The two former inputsdrive motor A, whilst the two latter drive motor B. The four inputs are wired to Arduino as follows

• A-IA ( B-IA ) is connected to a PWM output ( D9, D10 )• A-IB ( B-IB ) is connected to a digital output ( D7, D8 )

if we choose this scheme each motor will be driven in the speed range { 0 – 255 }, the same way asthe PWM output in the Fade program seen before. In other words, we can drive both motors at avariable speed from 0 to 255.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1111 de de 3434

Page 12: Hispalis RobIOTics Arduino Trainer v1

b) Connecting L9110 driver to Arduino Trainer v1.0

The following wiring scheme is helpful to connect the L9110 module to Arduino Trainerv1.0 The next pictures show in detail all the connections

Output D7 → Input B-IB ( Grey ) Digital, direction Left Motor Output D9 → Input B-IA ( Magenta) Analog, speed Left Motor Output D8 → Input A-IB ( Black) Digital, direction Right Motor Output D10→ Input A-IA ( White ) Analog, speed Right Motor

It is useful to declare the following macros

#define MOTOR_IZDO_DIR 7 // Low Adelante , HIGH Atras#define MOTOR_IZDO_SPEED 9 // Velocidad { 0 – 255 }#define MOTOR_DCHO_DIR 8#define MOTOR_DCHO_SPEED 10

Driver L9110 conectado a Arduino Trainer v1.0, así como a la alimentación (cables rojo marrón )

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1212 de de 3434

Page 13: Hispalis RobIOTics Arduino Trainer v1

Driver L9110: Cables de conexión a Arduino Trainer v1.0

Arduino Trainer v1.0: Cables de conexión al driver L9110

The following L9110 datasheet table shows electrical parameters

The upper right table shows the ouput of each motor ( OA, OB ) versus the input line levels ( IA, IB ). Notice that

• The motor is stalled when both inputs are high ( H ) or low ( L )• If one input is high and the other low, the motor is driven left or right, since the output

voltage ( OA, OB ) changes its polarity.• No PWM is applied to inputs, so the input levels are only high ( H ) and low ( L )

We can test the L9110 driver loading the next sketch, that drives both motors forward and reverse direction.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1313 de de 3434

Page 14: Hispalis RobIOTics Arduino Trainer v1

#define PARA delay(1000);

#define MOTOR_IZDO_DIR 7 // Low Adelante , HIGH Atras#define MOTOR_IZDO_SPD 9 // Velocidad { 0 – 255 }#define MOTOR_DCHO_DIR 8#define MOTOR_DCHO_SPD 10

void setup(){ pinMode( MOTOR_IZDO_DIR , OUTPUT ); pinMode( MOTOR_IZDO_SPD , OUTPUT ); pinMode( MOTOR_DCHO_DIR , OUTPUT ); pinMode( MOTOR_DCHO_SPD , OUTPUT );}

void loop(){ int vel = 200; // velocidad = { 0 , 255 } Forward_Motor_Left( vel ); Forward_Motor_Right( vel ); PARA; Stop_Motor_Left(); Stop_Motor_Right(); PARA; Reverse_Motor_Left( vel ); Reverse_Motor_Right( vel ); PARA; Stop_Motor_Left(); Stop_Motor_Right(); PARA;}

void Stop_Motor_Left( void ){ digitalWrite( MOTOR_IZDO_DIR , LOW ); digitalWrite( MOTOR_IZDO_SPD , LOW );}

void Stop_Motor_Right( void ){ digitalWrite( MOTOR_DCHO_DIR , LOW ); digitalWrite( MOTOR_DCHO_SPD , LOW );}

void Forward_Motor_Left( int velocidad ){ digitalWrite( MOTOR_IZDO_DIR, HIGH ); analogWrite( MOTOR_IZDO_SPD, 255-velocidad ); }

void Forward_Motor_Right( int velocidad ){ digitalWrite( MOTOR_DCHO_DIR, HIGH ); analogWrite( MOTOR_DCHO_SPD, 255-velocidad ); }

void Reverse_Motor_Left( int velocidad ){ digitalWrite( MOTOR_IZDO_DIR, LOW ); analogWrite( MOTOR_IZDO_SPD, velocidad ); }

void Reverse_Motor_Right( int velocidad ){ digitalWrite( MOTOR_DCHO_DIR, LOW ); analogWrite( MOTOR_DCHO_SPD, velocidad ); }

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1414 de de 3434

Page 15: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: Pulsadores ( D12, D13 )

There are three buttons avalaible in Arduino Trainer. The first one is RESET button. Theother two buttons are switches, connected to digital inputs D12 and D13. These switches may beused in our programs as inputs. The names in the PCB are inverted, so the D12 switch connects toArduino D13 input, and conversely D13 switch on the PCB is connected to D12 Arduino input. Wecan simply avoid this if we assign the following define macros

#define SWITCH_D12 13

#define SWITCH_D13 12

using the previous macros both switches are reassigned properly.

One important thing to be remarked is the fact that both switches are configured as PULL-UP inputs ( INPUT_PULLUP ). This means that the state of the input in Arduino UNO is

• 5V ( HIGH ) Open switch• 0V ( LOW ) Closed switch

Both switches are initialized in setup() function as follows

#define SWITCH_D12 13#define SWITCH_D13 12

void setup() { pinMode( SWITCH_D12 , INPUT_PULLUP ); // Enable internal pull-up resistor pinMode( SWITCH_D13 , INPUT_PULLUP ); // Enable internal pull-up resistor}

The function below returns the state of D12 switch

int Switchd12_is_pressed(void){ return !digitalRead( SWITCH_D12 );}

Since ! operator inverts the state of digitalRead() function, we have

If D12 switch is open, the state in Arduino UNO input returned by digitalRead() will be HIGH,( D12 is configured as PULL_UP input ) and the inverted value will be LOW

When D12 switch is closed we have a LOW state in Arduino D12 input returned by digitalRead()function, and the inverted corresponds to HIGH.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1515 de de 3434

Page 16: Hispalis RobIOTics Arduino Trainer v1

The next program shows all the previous ideas and runs as follows: when we press D12 switch, the red LED is lighted on, and pressing D13 switch the red LED is lighted it off.

#define SWITCH_D12 13#define SWITCH_D13 12#define LED_ROJO 3

void setup() { pinMode( LED_ROJO , OUTPUT ); pinMode( SWITCH_D12 , INPUT_PULLUP ); pinMode( SWITCH_D13 , INPUT_PULLUP ); }

void loop(void){ if( Switchd12_is_pressed() ) digitalWrite( LED_ROJO , HIGH ); else if( Switchd13_is_pressed() ) digitalWrite( LED_ROJO , LOW );}

/* Funcion: Switchd12_is_pressed( void ) Returns HIGH 1 if Switch D12 is being pressed , LOW if open*/int Switchd12_state(void){ return !digitalRead( SWITCH_D12 );}

/* Funcion: Switchd13_is_pressed( void ) Returns HIGH 1 if Switch D13 is being pressed , LOW if open*/int Switchd13_is_pressed(void){ return !digitalRead( SWITCH_D13 );}

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1616 de de 3434

Page 17: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: Sensor de línea ( A0, A1, A2, A3 )

Arduino Trainer integrates a set of four IR sensors, each of them is composed of an infraredemitter LED ( clear case ) and a phototransistor receiver ( black case ). From now on, we will referto the full set of 4 sensors ( 4 emitters and 4 receivers ) as Line Sensor. The Line Sensor is splittedfrom the main PCB easily, due to the premade cut on it. Splitting the line sensor is the perfectsolution to use it at your disposal in the appropiate place in a robot.

The IR sensor works sending an non visible, infrared light. When this light is bounced off byan object, the reflected light is received by the phototransistor, and the output level level is rised.

The line sensor is connected to Arduino Trainer using a 6 female to female connector:

• Four cables connect the individuals sensor outputs named S1 to S4• Two extra cables are connected to 5V Supply/GND Supply in Arduino Trainer PCB

The following pictures show the line sensor, and the wiring scheme to Arduino Trainer v1.0

Sensor de línea ( vista inferior ). Diodos emisores aislados Sensor de línea ( vista superior )

Conexión del Sensor de línea a Arduino Trainer Detalle de conexionado

Each individual sensor provides a HIGH output when lit, whilst the output of the sensor is LOW if no reflected light is received. The output response is improved isolating each emitter LED from their receiver to avoid interferences.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1717 de de 3434

Page 18: Hispalis RobIOTics Arduino Trainer v1

In the previous left upper imagen, the isolation is done safely and simply by means of an inserted black cap through each emitter LED. We can also insert a 5mm wide black strip all along the gap between the emitter LED and the receiver phototransistor rows.

The line sensor connects to analog input A0-A3 of Arduino UNO. Notice a “1” printed onthe board both in Arduino Trainer and the line sensor PCBs. The “1” is close to S1 sensor andshould be connected to A0 Arduino input.

We would like to recall that each analog Arduino inputs are digitalized using a 10 bits A/Dresolution converter. Using 10 bits, the minimun value of an analog input is 0, whilst the maximunvalue of the input maps to 1023 ( 2 10 - 1 ).

Since we have four identical sensors, the line sensor is ideal to be programmed using arrays.In the downloaded ArduinoTrainerv1.0.zip package, the folder

Archivo → Proyectos → ArduinoTrainerv1.0 → Sensors → LineSensor

contains a set of programas illustrating the way to deal with arrays, passing an array to a function, returning an array and many more

The following program tests the line sensor

// Constantes de preprocesador#define PARA delay(500)

void setup() { // No es necesario iniciar las entradas analógicas Serial.begin( 115200 );}

void loop() { int s1 , s2 , s3 , s4; int ind;

for(;;) { s1 = analogRead( A0 ); s2 = analogRead( A1 ); s3 = analogRead( A2 ); s4 = analogRead( A3 ); PARA;

for( ind =0; ind <4 ; ind++) Serial.println("LineSensor -->\tS1:"+String(s1)+" \tS2:"+String(s2)+" \tS3:"+String(s3)+" \tS4:"+String(s4) ); PARA; }}

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1818 de de 3434

Page 19: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: LDRs ( A4, A5 )

Arduino UNO has six different analog inputs, named A0-A5. A0-A3 inputs conform the linesensor. The other two remaining inputs, A4 A5 become available in a single connector named“LDR”, close to the bluetooth connector. The two inputs are connected to pullup 10K resistor, andthese resistors are connected to 5V Supply, as seen in the schematics below.

Arduino Trainer: Entradas analógicas A4, A5 LDRs

The scenario we get when we connect a Light Dependent Resistor ( LDR ) in A4 is depicted below. A resistor divider is built using the LDR and the 10K resistor

From the resistor divider formula we have

a) If LDR << 10K then Vout = 0V

b) If LDR >> 10K then Vout = 5V

Typical values for an LDR are

• LDR when lit: 0 a 1K• LDR no light: 50K to Megaohms

With these two data in mind, if we connect a LDR to A4 input ( one LDR pin to theconnector, the other to GND signal ) and we light it, the response should be a low state in A4Arduino UNO input. Therefore analogRead( A4 ) should return a value close to 0. In the other hand,the expected value when LDR gets dark should be close to 5V. Thus, analogRead( A4 ) now shouldbe near 1023.

The two LDRs may be used in a “light follower” robot . An example showing a light follower robot is shown in the next link

Robot Seguidor de luz

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 1919 de de 3434

5V

R1

10

K

Vout ( A4 , A5 )

LD

R

GND

Vout = ( LDR ) 5 V( R1 + LDR )

Page 20: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: BUZZER ( D11 )

Arduino Trainer v1.0 provides an output named BUZZER, connected to PWM D11 of Arduino UNO. The output is available in a two pin connector. A buzzer or a mini speaker may be plugged in using the buzzer connector.

A buzzer ( also known as beeper ) is an audio signalling device which may be mechanical,electromechanical or piezoelectric. The sound is generated by membrane vibrations.

When we connect a buzzer ( or even a mini speaker ) we can play tones and music usingArduino Trainer. The buzzer generates a square wave (50% duty cicle ) of the desired frecuency tobe played. Only one tone can be generated at a time, so we can not produce chords ( multiple tonessimultaneously ). The quality of the sound is not perfect ( in fact t is, but our used is not used tosquare waves but sinusoidal waves ), but nevertheless it is an interesting practice for newbies incomputer programming.

The main function for Arduino UNO to generate sounds is note(). The syntax is

tone( pin , frecuency , duration );

here is an example,

tone ( 11 , 440 , 1000 );

that generates a “La” note during 1 sg ( 1000 msg ).

There are lots of melodies available in the Web. The following program, extracted from

https://openwebinars.net/blog/tutorial-de-arduino-sonidos-con-arduino/

plays two famous melodies easily recognized by each of us

Buzzer Piezoeléctrico

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2020 de de 3434

Page 21: Hispalis RobIOTics Arduino Trainer v1

/**************************//* popurri para Arduino */ /**************************/

/**************** Antonio Guillermo Pérez Coronilla ***************/

/* declaración de variables */int spk=11; // altavoz a GND y pin 11int c[5]={131,262,523,1046,2093}; // frecuencias 4 octavas de Doint cs[5]={139,277,554,1108,2217}; // Do#int d[5]={147,294,587,1175,2349}; // Reint ds[5]={156,311,622,1244,2489}; // Re#int e[5]={165,330,659,1319,2637}; // Miint f[5]={175,349,698,1397,2794}; // Faint fs[5]={185,370,740,1480,2960}; // Fa#int g[5]={196,392,784,1568,3136}; // Solint gs[5]={208,415,831,1661,3322}; // Sol#int a[5]={220,440,880,1760,3520}; // Laint as[5]={233,466,932,1866,3729}; // La#int b[5]={247,494,988,1976,3951}; // Si

void nota(int a, int b); // declaración de la función auxiliar. Recibe dos números enteros.

void setup(){ /*******************//* STAR WARS *//*******************//**** tema principal ****/nota(d[1],150);noTone(spk);delay(50);nota(d[1],150);noTone(spk);delay(50);nota(d[1],150);noTone(spk);delay(50);nota(g[1],900);noTone(spk);delay(150);nota(d[2],900);noTone(spk);delay(50);nota(c[2],150);noTone(spk);delay(50);nota(b[1],150);noTone(spk);delay(50);nota(a[1],150);noTone(spk);delay(50);nota(g[2],900);noTone(spk);delay(150);nota(d[2],900);noTone(spk);delay(100);nota(c[2],150);noTone(spk);delay(50);nota(b[1],150);noTone(spk);delay(50);nota(a[1],150);noTone(spk);delay(50);nota(g[2],900);noTone(spk);delay(150);nota(d[2],900);noTone(spk);delay(100);nota(c[2],150);noTone(spk);delay(50);nota(b[1],150);noTone(spk);delay(50);nota(c[2],150);noTone(spk);delay(50);nota(a[1],1200);noTone(spk);delay(2000);

/**** marcha del imperio ****/nota(g[2],500);noTone(spk);delay(100);nota(g[2],500);noTone(spk);delay(100);nota(g[2],500);noTone(spk);delay(100);nota(ds[2],500);noTone(spk);delay(1);nota(as[2],125);noTone(spk);delay(25);nota(g[2],500);noTone(spk);delay(100);nota(ds[2],500);noTone(spk);delay(1);nota(as[2],125);noTone(spk);delay(25);nota(g[2],500);noTone(spk);delay(2000);

}

void nota(int frec, int t){ tone(spk,frec); // suena la nota frec recibida delay(t); // para después de un tiempo t}

void loop(){}

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2121 de de 3434

Page 22: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: Conector Bluetooth ( RX, TX )

Arduino UNO provides a serial port, wich allows communication with external hardware ora computer. Uploading a sketch is done using both serial ports in Arduino UNO and the computerusing the USB subsystem. The serial port is also used to open the Serial Monitor in Arduino IDE.Then, Serial.print() function sends all the data to the Serial Monitor, and we may visualize any kindof printed data on the screen.

A cable is needed to connect Arduino UNO to external hardware, but there are differentdevices that make possible to remove it. Some of those devices are

• Bluetooth HC-06 module• WIFI module• RF 2,4 Ghz module• Another microprocessor with a serial port, like ESP8266 , wich supports full WiFi

connectivity ( like Hispalis RobIOTics Hercules shield , avalaible soon in ebay ).

Arduino Trainer v1.0 design choice considers the first option, and thus a four pin socket isavailable for an HC06 bluetooth module to be inserted. Thanks to HC06 module we can connectArduino Trainer v1.0 with another computer, or even with a celular, after connection is stablished( pairing ) between both devices.

HC06 module has two pins for communication, named RX ( reception ) and TX( transmission ). Both terminal are wired to Arduino UNO serial port pins, that is

• Arduino UNO Pin 0 ( RX ) ←→ HC-06 TX Pin• Arduino UNO Pin 1 ( TX ) ←→ HC-06 RX Pin

Using a library called Software Serial we can reassign Arduino UNO RX and TX pins.Nevertheless Arduino Trainer v1.0 does not reassign RX/TX pins.

One disadvantage using RX/TX Arduino UNO pins is the fact that HC06 module must beextracted from the socket when uploading a sketch, since HC06 module may disruptcommunication with Arduino IDE.

HC06 bluetooth module is the bridge to get into Internet of Things ( IOT ), thanks toAppInventor, using a mobile. To make an app, we must program both Arduino UNO and the mobile( using AppInventor ).

Our app in the mobile should include the bluetooth client. The app also should display somebuttons, sliders, etc.. The user input will interact with all the components in the app, and eachcomponent in the app will send a control character ( i.e. ‘A’, ‘B’ and so on ) to Arduino UNO usingthe bluetooth integrated in the mobile. As for Arduino UNO, the sketch should poll periodically theserial port for incoming data sent by the mobile. Depending on the received control characterdifferent tasks should be acomplished ( firing a motor, switching a LED on, etc ). We can providealso a timer for the app. The timer is helpful for the mobile to receive data from Arduino UNO, andthe app runs the timer to check for incoming data from UNO.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2222 de de 3434

Page 23: Hispalis RobIOTics Arduino Trainer v1

The next example turns a LED on/off using a mobile. The app interface includes two buttons( ON and OFF button ). The app should send a ‘A’ character when ON button is pressed, and a ‘B’character when OFF button is pressed. On the other hand, the Arduino sketch polls periodically theserial port. This task is acomplished properly in the following sketch:

#define LED 3

void setup() { pinMode(LED, OUTPUT); digitalWrite(LED, LOW); Serial.begin(9600);}

void loop() { static int bytein; if(Serial.available() > 0) { bytein = Serial.read(); switch (bytein) { case '0': digitalWrite(LED, LOW);break; case '1': digitalWrite(LED, HIGH);break; } }}

Then, in AppInventor we must create an app. The following pictures show the layout design,and the blocks involved, and the the two pictures (LED ON, LED OFF ) used in the layout

Diseño del layout:

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2323 de de 3434

Page 24: Hispalis RobIOTics Arduino Trainer v1

Diseño de Bloques:

Imágenes de LEDs:

Led ON Led OFF

N.B.: This example assumes the reader has appropiate skills using AppInventor. Last but not least,no errors control is done. In addition, the layout design was simplified for educational purposes.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2424 de de 3434

Page 25: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: Conector I2C ( A4, A5 )

There is available an I2C socket in Arduino Trainer v1.0. The I2C socket is helpful to connect external hardware not included in Arduino Trainer v1.0

The I2C bus, originally designed by Philips, is a serial data bus, and becomes one of themain communication subsystems integrated in Arduino UNO ( the other two are the serial bus andthe SPI bus ). It is also known as TWI ( Two Wires Interface ), y represents one way for externalhardware or modules to be connected to Arduino UNO using only two wires, that is:

• SDA: Data transmission wire• SCL: Clock signal wire

The I2C bus is a synchronous bus, and the clock signal is shared between all the connecteddevices. In addition, the bus provides a master slave architecture, where Arduino UNO acts as amaster, and starts allways any communication. Then each slave may either send or receive data tothe master device.

The I2C bus shows an special feature, that is, all data lines make use of 1K to 10K pull-upresistors. The standar resistor value is 4K7.

Arduino Trainer v1.0 provides 10K pull-up resistors, and the I2C lines are shared withanalog inputs A4 ( SDA ) and A5 ( SCL ). These two lines are connected to LDR socket, as seenpreviously.

Nowadays many I2C hardware is available in the different web markets, one of this is theLCD I2C module. To learn more about I2C protocol and specifications, jump to http://www.i2c-bus.org/

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2525 de de 3434

Page 26: Hispalis RobIOTics Arduino Trainer v1

Arduino Trainer: Conector de Alimentación

Arduino Trainer provides a 5V Supply / GND Supply multiple male connector. If ArduinoTrainer is voltage supplied through the USB Arduino UNO cable, the 5V Supply socket is availablefor any external hardware connected to Trainer to be supplied. The current must be below 1 A, dueto Arduino UNO limitations ( a 5V regulator IC in the UNO PCB ). Related to the 5V socket thereare a few additional features to be considered:

First, if our choice is an autonomous Arduino UNO/Arduino Trainer, and we are notsupplying UNO with the USB from a computer, the supply connector is the Arduino Trainer socketto be voltage supplied using a 5V Power Bank or batteries. The Power Bank is a common solutionused for powering mobiles, etc.

If we use a Power Bank, we must merely connect the red and black lines of the USB cable( named in the pictures below VCC and GND ) to the multiple male connector 5V Supply / GNDSupply

Conector USB tipo A

Conectores USB: patillaje

Another different purpose for the supply socket was seen before. The supply socket is at ourdisposal for supplying VIN pin in the MMC D7-D10. We would like to recall that the central row ofpins in the multiple male connector D7-D10 is not connected to 5V Supply. If we want a Servo tobe connected properly, we must wire the VIN row in D7-D10 socket to 5V Supply socket. Then, themicromotor in the servo will be supplied through the 5V Supply / GND socket.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2626 de de 3434

Page 27: Hispalis RobIOTics Arduino Trainer v1

Alimentando Arduino UNO

We can use an external supply for Arduino UNO / Arduino Trainer. First, it is important tounderstand the Arduino UNO R3 schematics, shown in the picture below.

Esquema eléctrico de Arduino UNO R3

The upper right yellow circle shows the external supplying connector. This connector isserial soldered to a diode to avoid reverse supplying damages. The voltage drops 0.7 V through thediode terminals, and consequently, the output in the diode shuld be 0,7 V below voltage supply ( 8Vif external voltage supply is 9V ).

The output of the previous diode corresponds to VIN pin, that is connected to a 5V voltageregulator IC ( MC 33269ST-5.0 in the schematics, in fact it is an AMS 1117-5V, located next to theexternal supplying connector in Arduino UNO PCB ). The IC runs supplying a load up to 800 mA.The 5V output supplies the ATMEGA 328 Arduino UNO microprocessor. This 5V regulated supplyis connected to Arduino Trainer v1.0 multiple male connector 5V Supply / GND supply.

It is time now to remark and understand clearly that we may connect an external 5V sourceto the regulator 5V output through the 5V Supply / GND socket. Using this scheme, the integratedregulator will be isolated ( bypassed ), since it must be polarized either using the external supplyingconnector or VIN pin.

With all this ideas in mind, we have different Arduino UNO R3 supplying schemes:

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2727 de de 3434

Page 28: Hispalis RobIOTics Arduino Trainer v1

9V Supply ( 9V battery ): Connect to external supplying connector, to avoid overheating of theArduino UNO 5V regulator.

7.4V Supply ( Li-Po Battery Pack ): Connect through the external supplying connector. Connectingto VIN should overheat the 5V regulator IC.

6V Supply ( i.e., four 1.5V batteries): Connect using VIN pin.

5V Supply ( Power Bank / USB Battery Pack ): Connect to Arduino UNO 5V pin.

To conclude, Arduino UNO may be voltage supplied using different voltage sources, that is:

• External supply using a 9V battery• 7.4V Li-Po Power Bank• Direct Supplying in 5V Arduino UNO pin. This is the recommended supplying way if we

use an USB 5V Battery Pack.• USB computer connector.• VIN pin. We must check and be careful using the polarity of any voltage source.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2828 de de 3434

Page 29: Hispalis RobIOTics Arduino Trainer v1

Analizando el pin VIN de Arduino Trainer

Arduino Trainer v1.0 applies all the Arduino UNO supplying details seen before, except for the fact that Arduino Trainer VIN pin is not connected. The mentioned VIN pin is only connected inturn to the multiple male connector D7 – D10, originally designed to drive Servos ( D9 D10 ) or digital Inputs/Outputs ( D7 D8 ) as external sensors/driving transistor for relays.

Arduino Trainer v1.0

It is important to remark one more time that VIN is not supplied. As an example, if weconnect a servo to output D9 ( PWM ), the servo will not work at all, since the D9 connector is notvoltage supplied ( VIN ).

This feature allows supplying a Servo with a voltage over 5V. If we design a robot usingCRS ( Continuous Rotation Servo ) we may supply a 6V voltage supply source via VIN.Nevertheless, if we do not need to use this special feature, we must simply connect any of thecentral row pins in the D7 – D10 connector to the 5V Supply socket. This is the correct way tosupply the VIN pins in the MMC.

To finish, we would also like to remark that VIN pin in Arduino Trainer is not connected toArduino UNO. If we would like to provide a voltage supply through VIN to Arduino UNO, we needto solder VIN pin in Arduino Trainer v1.0 face down in the PCB. Then, Arduino Trainer VIN willconnect to Arduino UNO VIN pin.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 2929 de de 3434

Page 30: Hispalis RobIOTics Arduino Trainer v1

Alimentando Arduino Trainer con Arduino UNO

This step in our road is the prefered to robot lovers. Well, I have my own set UNO andTrainer set joined together. When they are ( so do I ! ) connected to my PC, everything worksperfectly. Both motors respond each sent command, and ( ¡ yes ! ) all the hardware and sensors aretuned ! They have explored the ArduinoTrainerv1.0 projects, and now they want to go their ownway.

Then, we decide to explore the outside space, rearranging Trainer & UNO in a chassis withwheels. TrainerBot chassis is more than a picture needs an eye. TrainerBot is a 3D printer chassis,available in thingiverse

In any case, Arduino Trainerv1.0 integrates a multiple 5V input socket, ready to be suppliedby en external source, as an USB PowerBank. And even more, Arduino UNO is supplied also.

Here are some of the scenarios considered to voltage supply Arduino UNO / ArduinoTrainer:

a) Arduino UNO external supply: 7,4V – 9 V

• En este caso, Arduino Trainer v1.0 se alimenta a través de la salida de 5V de UNO. • El conector múltiple macho VIN de los pines D7 a D10 no tienen alimentación, para lo

cual debemos conectar cualquier pin VIN del conector D7 a D10 a 5V Supply.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 3030 de de 3434

Page 31: Hispalis RobIOTics Arduino Trainer v1

b) Alimentación por el conector USB

• En este caso, Arduino Trainer v1.0 se alimenta a través de la alimentación 5V delconector USB.

• El conector múltiple macho VIN de los pines D7 a D10 no tienen alimentación, para locual debemos conectar cualquier pin VIN del conector D7 a D10 a 5V Supply.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 3131 de de 3434

Page 32: Hispalis RobIOTics Arduino Trainer v1

c) Alimentación de Trainer mediante Battery Pack USB

• En esta configuración, debemos conectar la salida del Battery Pack USB al conector 5VSupply - GND Supply. Arduino Trainer v1.0 alimentará a su vez a Arduino UNO mediantela entrada 5V de Arduino UNO.

• El conector múltiple macho VIN de los pines D7 a D10 no tienen alimentación, para lo cualdebemos conectar cualquier pin VIN del conector D7 a D10 a 5V Supply.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 3232 de de 3434

Page 33: Hispalis RobIOTics Arduino Trainer v1

d) Alimentación por pin VIN ( avanzada )

Esta es la configuración mas compleja, ya que el pin VIN de Trainer v1.0 puede conectarse ono al pin VIN de UNO. Es por esto que esta configuración se recomienda solo a usuariosexpertos, que hayan entendido claramente el esquema de alimentación de Arduino UNO.

Este esquema es solo recomendado si queremos conectar Servos de rotación continua yalimentarlos a 6V, ya que al alimentar Arduino Trainer v1.0 por VIN el conector múltiple machoVIN D7 A D10 SE ALIMENTARÁ A VIN externa. Para el resto de configuraciones, basta conectarcualquier pin VIN del conector D7 a D10 a 5V Supply, como ya hemos repetido anteriormente.

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 3333 de de 3434

Page 34: Hispalis RobIOTics Arduino Trainer v1

Para conseguir que Arduino Trainer v1.0 alimente a Arduino UNO, debemos soldar el pinVIN de Arduino Trainer v1.0 por debajo de la placa, para que entre en el conector VIN de UNO.Por la cara de arriba, soldaremos los cables de alimentación externa VIN. Así, si alimentamos ( porejemplo 6 V mediante con 4 pilas de 1,5 V ) a Trainer, este a su vez alimentará al regulador de 5Vde Arduino. Asimismo, el conector múltiple VIN del conector D7 a D10 se alimentará con la mismaalimentación VIN externa ( los mismos 6 V de la alimentación externa ).

Hispalis RobIOTicsContacto: [email protected]

Hispalis RobIOTics Arduino Trainer v1.0Hispalis RobIOTics Arduino Trainer v1.0 Página Página 3434 de de 3434