robot4all io5 exercises and solutions robotics

45
Leading Partner: CCS ROBOT4ALL EXERCISES AND SOLUTIONS - ROBOTICS INTELLECTUAL OUTPUT 5

Upload: others

Post on 16-Oct-2021

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Robot4All IO5 Exercises and Solutions Robotics

#

Leading Partner: CCS

ROBOT4ALLEXERCISES AND SOLUTIONS - ROBOTICS

INTELLECTUAL OUTPUT 5

Page 2: Robot4All IO5 Exercises and Solutions Robotics

1

LEIBNIZ UNIVERSITÄT HANNOVERGermany Coordinator ( )

2 EK PEIRAIA Greece

EMPHASYS CENTRE Cyprus

United Kingdom

CDIMM MARAMURES FOUNDATIONRomania

CIVIC COMPUTING

WOMEN IN DIGITAL INITIATIVES LUXEMBOURG ASBL

SpainI.E.S. MARÍA MOLINER

Luxemburg

CyprusCYPRUS COMPUTER SOCIETY

Institut für Didaktik der Demokratie

Richard Heise

All rights reserved. The content of the publication may be used for educational and other non-commercial

purposes on the condition of using the following name as source in every reproduction: „Erasmus+ Project

Robot4All“.

Mareike Heldt

LAYOUT:

PROJECT MANAGEMENT:

This project has been funded with support from the European Commission. This communication reflects the

views only of the author, and the Commission cannot be held responsible for any use which may be made of the

information contained therein. Project Number: 2017-1-DE02-KA202-004274

Leibniz Universität Hannover

PROJECT LEADERSHIP:

[email protected]

Prof. Dr. Dirk Lange

www.robovet.eu

PROJECTS WEBSITE:

Page 3: Robot4All IO5 Exercises and Solutions Robotics

1

LEIBNIZ UNIVERSITÄT HANNOVERGermany Coordinator ( )

2 EK PEIRAIA Greece

EMPHASYS CENTRE Cyprus

United Kingdom

CDIMM MARAMURES FOUNDATIONRomania

CIVIC COMPUTING

WOMEN IN DIGITAL INITIATIVES LUXEMBOURG ASBL

SpainI.E.S. MARÍA MOLINER

Luxemburg

CyprusCYPRUS COMPUTER SOCIETY

Institut für Didaktik der Demokratie

Richard Heise

All rights reserved. The content of the publication may be used for educational and other non-commercial

purposes on the condition of using the following name as source in every reproduction: „Erasmus+ Project

Robot4All“.

Mareike Heldt

LAYOUT:

PROJECT MANAGEMENT:

This project has been funded with support from the European Commission. This communication reflects the

views only of the author, and the Commission cannot be held responsible for any use which may be made of the

information contained therein. Project Number: 2017-1-DE02-KA202-004274

Leibniz Universität Hannover

PROJECT LEADERSHIP:

[email protected]

Prof. Dr. Dirk Lange

www.robovet.eu

PROJECTS WEBSITE:

Page 4: Robot4All IO5 Exercises and Solutions Robotics

2 3

03

04

05

12

19

38

03Organization .............................................................................................................................................................

Introduction ..............................................................................................................................................................

Lesson 5: Basic Arduino .........................................................................................................................................

Bill of Materials .........................................................................................................................................................

Lesson 6: Advanced Arduino ..................................................................................................................................

Appendix ...................................................................................................................................................................

Lesson 4: Introduction to Arduino and Robotics .................................................................................................

Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino was born

as an easy tool for fast prototyping, aimed at students without a background in electronics and programming. As

soon as it reached a wider community, the Arduino board started changing to adapt to new needs and

challenges, differentiating its offer from simple 8-bit boards to products for IoT applications, 3D printing, and

embedded environments. The software, too, is open-source, and it is growing through the contributions of users

worldwide.

Ÿ �VET students with fewer opportunities.

Nowadays, Robotic skills are essential in most of the industrial and engineering processes of our current way

of life. So, in order to be able to create, control and modify such prototypes we should improve the Robotics

curricula of our students introducing them on this field.

The aim of this course is to create robotic circuits and control them efficiently with the use of programming

instructions over Arduino and Tinkercad platforms.

Target groups:

Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it

into an output - activating a motor, turning on an LED, publishing something online. You can order your board

what to do by sending a set of instructions to the microcontroller on the board. To do so you use the Arduino

programming language and the Arduino Software.

Ÿ �Technical VET trainers interested in Robotics and IT fields.

The exercises are intended as a way to introduce you to different elements that we can use in any robot (diodes,

The exercises are organized in three blocks: lesson 4, lesson 5 and lesson 6. In each of every lesson there are

different examples in increasing complexity order, from the very basic to the very advanced. Most of the

exercises are linked to a online solution in Tinkercad, when you will be able to see the hardware circuit associated

to the solution as well as the code, and you will be able to simulate the circuit operation.

The exercises are intended to be physically assembled using a protoboard and different components, but if you

want you could only simulate them although you will loose the fun and practice of electronics assembling.

INTRODUCTION

ORGANIZATION

Page 5: Robot4All IO5 Exercises and Solutions Robotics

2 3

03

04

05

12

19

38

03Organization .............................................................................................................................................................

Introduction ..............................................................................................................................................................

Lesson 5: Basic Arduino .........................................................................................................................................

Bill of Materials .........................................................................................................................................................

Lesson 6: Advanced Arduino ..................................................................................................................................

Appendix ...................................................................................................................................................................

Lesson 4: Introduction to Arduino and Robotics .................................................................................................

Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino was born

as an easy tool for fast prototyping, aimed at students without a background in electronics and programming. As

soon as it reached a wider community, the Arduino board started changing to adapt to new needs and

challenges, differentiating its offer from simple 8-bit boards to products for IoT applications, 3D printing, and

embedded environments. The software, too, is open-source, and it is growing through the contributions of users

worldwide.

Ÿ �VET students with fewer opportunities.

Nowadays, Robotic skills are essential in most of the industrial and engineering processes of our current way

of life. So, in order to be able to create, control and modify such prototypes we should improve the Robotics

curricula of our students introducing them on this field.

The aim of this course is to create robotic circuits and control them efficiently with the use of programming

instructions over Arduino and Tinkercad platforms.

Target groups:

Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it

into an output - activating a motor, turning on an LED, publishing something online. You can order your board

what to do by sending a set of instructions to the microcontroller on the board. To do so you use the Arduino

programming language and the Arduino Software.

Ÿ �Technical VET trainers interested in Robotics and IT fields.

The exercises are intended as a way to introduce you to different elements that we can use in any robot (diodes,

The exercises are organized in three blocks: lesson 4, lesson 5 and lesson 6. In each of every lesson there are

different examples in increasing complexity order, from the very basic to the very advanced. Most of the

exercises are linked to a online solution in Tinkercad, when you will be able to see the hardware circuit associated

to the solution as well as the code, and you will be able to simulate the circuit operation.

The exercises are intended to be physically assembled using a protoboard and different components, but if you

want you could only simulate them although you will loose the fun and practice of electronics assembling.

INTRODUCTION

ORGANIZATION

Page 6: Robot4All IO5 Exercises and Solutions Robotics

4 5

LESSON 4: INTRODUCTION TO

ARDUINO AND ROBOTICS

Ÿ Find in Tinkercad similar circuits and work in them.

Ÿ Find in Tinkercad similar circuits and work with them.

Ÿ Work on the exercises of lesson 6.

Ÿ Work on the exercises of lesson 4, first through the Tinkercad simulation and then assembling the circuits and

programming the Arduino UNO.

sensors, LCDs, etc) in an easy simulation environment and simultaneously make the transition to an useful

hardware environment. The suggested approach to use this exercises is the following:

Ÿ Work on the exercises of lesson 5, first through Tinkercad and then assembling the circuits.

Ÿ Work on the exercises supplied with the Elegoo Robot Car Kit, assembling the car and using the different

sensors and actuators.

Ÿ � Arduino UNO with ATMEGA328P.

Ÿ � LM35 temperature sensor.

Ÿ � 2x 10K potentiometer.

Ÿ � Breadboard, may be a tiny one like this or better a bigger one like this.

Ÿ � 3 micro push buttons.

Ÿ � L293 motor driver.

Ÿ � Arduino yun or Arduino yun shield for arduino uno.

Ÿ � Parallax ping ultrasound distance sensor. It is an expensive one and it is used because it is modelized in

Tinkercad but it can be replaced with minimal circuit and code changes with the much cheaper HC-SR04.

Ÿ � Leds: red, green and yellow.

Ÿ � 3 x 10K resistor.

Ÿ � Micro-servo.

Ÿ � RGB led strip.

Ÿ � DC micro motor.

Ÿ � RFID tokens.

Ÿ � RMD6300 RFID card reader.

Ÿ � N channel mosfet.

Ÿ � 3x 220 ohm resistor.

Ÿ � Simulate the circuit in Tinkercad.

(select blocks+text and Tinkercad will generate the code)

Ÿ � What is the resistor value and why?

Ÿ � Using blocks (pseudocode) write down a program that makes the led blinks once per second.

Ÿ Using Tinkercad circuits, create a circuit with arduino UNO, a breadboard, and a led connected to Arduino

digital pin 8.

Ÿ � Compare the blocks with the code generated by Tinkercad

Ÿ � Build the corresponding real circuit, program it with arduino IDE and test it.

EXERCISES

Ÿ Traffic light: https://www.tinkercad.com/things/cdgx8jSsFSo

Ÿ Switch on/off a light: https://www.tinkercad.com/things/lTBPtStOWzM

1. Blink

Ÿ � To build basic Tinkercard circuits.

OBJECTIVES

Ÿ � To create elementary Arduino circuits.

Ÿ � To be familiar with Programming using blocks.

Ÿ � To manage electronic elements as resistors, leds, breadboards,…

Ÿ � To follow the sequence of instructions of a basic program and preview the output results.

Ÿ � To read and understand initial C++ programs.

Ÿ � To write short and basic C++ programs using the most elementary structures.

After completing this lesson students should be able:

Ÿ Blink: https://www.tinkercad.com/things/ejt30quxU9d

BILL OF MATERIALS

Page 7: Robot4All IO5 Exercises and Solutions Robotics

4 5

LESSON 4: INTRODUCTION TO

ARDUINO AND ROBOTICS

Ÿ Find in Tinkercad similar circuits and work in them.

Ÿ Find in Tinkercad similar circuits and work with them.

Ÿ Work on the exercises of lesson 6.

Ÿ Work on the exercises of lesson 4, first through the Tinkercad simulation and then assembling the circuits and

programming the Arduino UNO.

sensors, LCDs, etc) in an easy simulation environment and simultaneously make the transition to an useful

hardware environment. The suggested approach to use this exercises is the following:

Ÿ Work on the exercises of lesson 5, first through Tinkercad and then assembling the circuits.

Ÿ Work on the exercises supplied with the Elegoo Robot Car Kit, assembling the car and using the different

sensors and actuators.

Ÿ � Arduino UNO with ATMEGA328P.

Ÿ � LM35 temperature sensor.

Ÿ � 2x 10K potentiometer.

Ÿ � Breadboard, may be a tiny one like this or better a bigger one like this.

Ÿ � 3 micro push buttons.

Ÿ � L293 motor driver.

Ÿ � Arduino yun or Arduino yun shield for arduino uno.

Ÿ � Parallax ping ultrasound distance sensor. It is an expensive one and it is used because it is modelized in

Tinkercad but it can be replaced with minimal circuit and code changes with the much cheaper HC-SR04.

Ÿ � Leds: red, green and yellow.

Ÿ � 3 x 10K resistor.

Ÿ � Micro-servo.

Ÿ � RGB led strip.

Ÿ � DC micro motor.

Ÿ � RFID tokens.

Ÿ � RMD6300 RFID card reader.

Ÿ � N channel mosfet.

Ÿ � 3x 220 ohm resistor.

Ÿ � Simulate the circuit in Tinkercad.

(select blocks+text and Tinkercad will generate the code)

Ÿ � What is the resistor value and why?

Ÿ � Using blocks (pseudocode) write down a program that makes the led blinks once per second.

Ÿ Using Tinkercad circuits, create a circuit with arduino UNO, a breadboard, and a led connected to Arduino

digital pin 8.

Ÿ � Compare the blocks with the code generated by Tinkercad

Ÿ � Build the corresponding real circuit, program it with arduino IDE and test it.

EXERCISES

Ÿ Traffic light: https://www.tinkercad.com/things/cdgx8jSsFSo

Ÿ Switch on/off a light: https://www.tinkercad.com/things/lTBPtStOWzM

1. Blink

Ÿ � To build basic Tinkercard circuits.

OBJECTIVES

Ÿ � To create elementary Arduino circuits.

Ÿ � To be familiar with Programming using blocks.

Ÿ � To manage electronic elements as resistors, leds, breadboards,…

Ÿ � To follow the sequence of instructions of a basic program and preview the output results.

Ÿ � To read and understand initial C++ programs.

Ÿ � To write short and basic C++ programs using the most elementary structures.

After completing this lesson students should be able:

Ÿ Blink: https://www.tinkercad.com/things/ejt30quxU9d

BILL OF MATERIALS

Page 8: Robot4All IO5 Exercises and Solutions Robotics

6 7

CIRCUIT:

Arduino output when high is 5V. The led, when lighting has a Vled near 2V, so Vr=5V-Vled=3V. If we want the led

shines properly we will use a current of 15mA, so R=3V/15mA = 200ohm.

BLOCKS:

}

delay(500); // During 500 milliseconds

p inMode(8, OUTPUT);

CODE:

void loop()

{

digitalWrite(8, LOW); //OFF

{

}

delay(500); // During 500 milliseconds

void setup()

digitalWrite(8, HIGH); //ON

Ÿ Compare the blocks with the code generated by Tinkercad (select blocks+text and Tinkercad will generate

the code).

2. Traffic Light

Ÿ Simulate the circuit in Tinkercad.

https://www.tinkercad.com/things/ejt30quxU9d

Ÿ Using blocks write down a program that creates a semaphore: the green light will be on 20s, then the yellow

light will blink 10 times and then the red light will be on 20s.

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and three leds (red, yellow, green)

connected to pins 2,3,4.

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

CIRCUIT

Page 9: Robot4All IO5 Exercises and Solutions Robotics

6 7

CIRCUIT:

Arduino output when high is 5V. The led, when lighting has a Vled near 2V, so Vr=5V-Vled=3V. If we want the led

shines properly we will use a current of 15mA, so R=3V/15mA = 200ohm.

BLOCKS:

}

delay(500); // During 500 milliseconds

p inMode(8, OUTPUT);

CODE:

void loop()

{

digitalWrite(8, LOW); //OFF

{

}

delay(500); // During 500 milliseconds

void setup()

digitalWrite(8, HIGH); //ON

Ÿ Compare the blocks with the code generated by Tinkercad (select blocks+text and Tinkercad will generate

the code).

2. Traffic Light

Ÿ Simulate the circuit in Tinkercad.

https://www.tinkercad.com/things/ejt30quxU9d

Ÿ Using blocks write down a program that creates a semaphore: the green light will be on 20s, then the yellow

light will blink 10 times and then the red light will be on 20s.

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and three leds (red, yellow, green)

connected to pins 2,3,4.

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

CIRCUIT

Page 10: Robot4All IO5 Exercises and Solutions Robotics

8 9

BLOCKS:

CODE:

void setup()

pinMode(2, OUTPUT);

pinMode(3, OUTPUT);

pinMode(4, OUTPUT);

}

void loop()

{

digitalWrite(2, HIGH); //Green

{

digitalWrite(3, LOW);

digitalWrite(4, LOW);

delay(20000); // during 20s

digitalWrite(2, LOW);

}

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, a led and a push button to switch

on/off.

Ÿ Compare the blocks with the code generated by Tinkercad (select blocks+text and Tinkercad will generate

the code).

digitalWrite(3, LOW);

digitalWrite(4, HIGH);

https://www.tinkercad.com/things/cdgx8jSsFSo

delay(500); // during 500 milliseconds

3. Switch on/off a light

Ÿ Using blocks write down a program that waits the user to push and then changes the state of the led (on/off).

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

CIRCUIT:

for (int counter = 0; counter < 10; ++counter) //blink 10 times

digitalWrite(3, LOW); //yellow OFF

delay(500); // during 500 milliseconds

digitalWrite(3, HIGH); //yellow ON

digitalWrite(2, LOW); //RED

delay(20000); // during 20s

{

}

Ÿ Simulate the circuit in Tinkercad.

Page 11: Robot4All IO5 Exercises and Solutions Robotics

8 9

BLOCKS:

CODE:

void setup()

pinMode(2, OUTPUT);

pinMode(3, OUTPUT);

pinMode(4, OUTPUT);

}

void loop()

{

digitalWrite(2, HIGH); //Green

{

digitalWrite(3, LOW);

digitalWrite(4, LOW);

delay(20000); // during 20s

digitalWrite(2, LOW);

}

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, a led and a push button to switch

on/off.

Ÿ Compare the blocks with the code generated by Tinkercad (select blocks+text and Tinkercad will generate

the code).

digitalWrite(3, LOW);

digitalWrite(4, HIGH);

https://www.tinkercad.com/things/cdgx8jSsFSo

delay(500); // during 500 milliseconds

3. Switch on/off a light

Ÿ Using blocks write down a program that waits the user to push and then changes the state of the led (on/off).

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

CIRCUIT:

for (int counter = 0; counter < 10; ++counter) //blink 10 times

digitalWrite(3, LOW); //yellow OFF

delay(500); // during 500 milliseconds

digitalWrite(3, HIGH); //yellow ON

digitalWrite(2, LOW); //RED

delay(20000); // during 20s

{

}

Ÿ Simulate the circuit in Tinkercad.

Page 12: Robot4All IO5 Exercises and Solutions Robotics

10 11

{

while (digitalRead(2) == 1) { } //wait release

pinMode(2, INPUT);

delay(20); // Wait for 20 milliseconds to avoid rebounds when pressing

BLOCKS:

pinMode(8, OUTPUT);

}

void setup()

{

int state = 0;

CODE:

void loop()

if (digitalRead(2) == 1)

{

delay(20); // Wait for 20 milliseconds to avoid rebounds when releasing

{

digitalWrite(8, LOW);

}

digitalWrite(8, HIGH);

if (state == 1)

state = 0;

} else

{

state = 1;

}

if (state == 0)

{

} else

{

}

}

https://www.tinkercad.com/things/lTBPtStOWzM

Page 13: Robot4All IO5 Exercises and Solutions Robotics

10 11

{

while (digitalRead(2) == 1) { } //wait release

pinMode(2, INPUT);

delay(20); // Wait for 20 milliseconds to avoid rebounds when pressing

BLOCKS:

pinMode(8, OUTPUT);

}

void setup()

{

int state = 0;

CODE:

void loop()

if (digitalRead(2) == 1)

{

delay(20); // Wait for 20 milliseconds to avoid rebounds when releasing

{

digitalWrite(8, LOW);

}

digitalWrite(8, HIGH);

if (state == 1)

state = 0;

} else

{

state = 1;

}

if (state == 0)

{

} else

{

}

}

https://www.tinkercad.com/things/lTBPtStOWzM

Page 14: Robot4All IO5 Exercises and Solutions Robotics

12 13

LESSON 5:

BASIC ARDUINO

Ÿ LCD: https://www.tinkercad.com/things/h6c7oCjkj7L

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and a LCD. Display “Hello world” in

the LCD.

Ÿ Simulate the circuit in Tinkercad.

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

Ÿ ASCII table: https://www.tinkercad.com/things/icWyROFaZr9

Ÿ Measuring distances with Parallax ping sensor: https://www.tinkercad.com/things/kDk54zrw28W

Ÿ � To use a LCD in Arduino to display messages to the user.

Ÿ � To use different types of sensors and actuators (temperature sensors, distance sensors, servomotors).

EXERCISES

OBJECTIVES

Ÿ � To differenciate digital and analog use of inputs and outputs in Arduino.

Ÿ � To write basic Arduino programs using libraries with C++ classes and objects.

After completing this lesson students should be able:

Ÿ Temperature measure: https://www.tinkercad.com/things/8h3Z9DviRtp

Ÿ Servo control: https://www.tinkercad.com/things/9qYj2rVm0jD

1. LCD

Ÿ What is the potentiometer for?

CIRCUIT:

#include <LiquidCrystal.h>

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

lcd.begin(16, 2);

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

// (note: line 1 is the second row, since counting begins with 0):

// print the number of seconds since reset:

CODE:

void setup() {

// set up the LCD's number of columns and rows:

// Print a message to the LCD.

lcd.print("hello, world!");

}

void loop() {

// set the cursor to column 0, line 1

lcd.setCursor(0, 1);

lcd.print(millis() / 1000);

}

https://www.tinkercad.com/things/h6c7oCjkj7L

2. ASCII table

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and a LCD. Display the complete

ASCII table in the LCD.

Ÿ Simulate the circuit in Tinkercad.

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

Page 15: Robot4All IO5 Exercises and Solutions Robotics

12 13

LESSON 5:

BASIC ARDUINO

Ÿ LCD: https://www.tinkercad.com/things/h6c7oCjkj7L

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and a LCD. Display “Hello world” in

the LCD.

Ÿ Simulate the circuit in Tinkercad.

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

Ÿ ASCII table: https://www.tinkercad.com/things/icWyROFaZr9

Ÿ Measuring distances with Parallax ping sensor: https://www.tinkercad.com/things/kDk54zrw28W

Ÿ � To use a LCD in Arduino to display messages to the user.

Ÿ � To use different types of sensors and actuators (temperature sensors, distance sensors, servomotors).

EXERCISES

OBJECTIVES

Ÿ � To differenciate digital and analog use of inputs and outputs in Arduino.

Ÿ � To write basic Arduino programs using libraries with C++ classes and objects.

After completing this lesson students should be able:

Ÿ Temperature measure: https://www.tinkercad.com/things/8h3Z9DviRtp

Ÿ Servo control: https://www.tinkercad.com/things/9qYj2rVm0jD

1. LCD

Ÿ What is the potentiometer for?

CIRCUIT:

#include <LiquidCrystal.h>

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

lcd.begin(16, 2);

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

// (note: line 1 is the second row, since counting begins with 0):

// print the number of seconds since reset:

CODE:

void setup() {

// set up the LCD's number of columns and rows:

// Print a message to the LCD.

lcd.print("hello, world!");

}

void loop() {

// set the cursor to column 0, line 1

lcd.setCursor(0, 1);

lcd.print(millis() / 1000);

}

https://www.tinkercad.com/things/h6c7oCjkj7L

2. ASCII table

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and a LCD. Display the complete

ASCII table in the LCD.

Ÿ Simulate the circuit in Tinkercad.

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

Page 16: Robot4All IO5 Exercises and Solutions Robotics

14 15

CIRCUIT:

CODE:

#include <LiquidCrystal.h>

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()

{

lcd.begin(16, 2);

lcd.print("ASCII table");

sprintf(msg,"Ascii:%i Char:%c",i,i); //prints code and character

void loop()

lcd.setCursor(0, 0);

for(int i=32; i<256; i++) //from blank space to end of ascii table

delay(3000);

}

lcd.clear();

}

char msg[20];

}

{

lcd.print(msg);

{

delay(500);

CIRCUIT:

3. Temperature measure

Using a LM35 sensor you should show the current temperature on the LCD. Consult the documentation about the

LM35 sensor: http://www.ti.com/lit/ds/symlink/lm35.pdf. As you can check the sensor gives a 10mV/ºC

tension.

// set up the LCD's number of columns and rows:

char msg[20];

#include <LiquidCrystal.h>

{

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

{

void setup()

CODE:

lcd.begin(16, 2);

void loop()

lcd.print(msg);

sprintf(msg,"Temp = %d%cC",temp,178); //create the text string to send to the LCD

}

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int temp=analogRead(0)*500/1023; //10mV/ºC -> convert to ºC

}

lcd.setCursor(0, 0);

https://www.tinkercad.com/things/8h3Z9DviRtp

https://www.tinkercad.com/things/icWyROFaZr9

Page 17: Robot4All IO5 Exercises and Solutions Robotics

14 15

CIRCUIT:

CODE:

#include <LiquidCrystal.h>

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()

{

lcd.begin(16, 2);

lcd.print("ASCII table");

sprintf(msg,"Ascii:%i Char:%c",i,i); //prints code and character

void loop()

lcd.setCursor(0, 0);

for(int i=32; i<256; i++) //from blank space to end of ascii table

delay(3000);

}

lcd.clear();

}

char msg[20];

}

{

lcd.print(msg);

{

delay(500);

CIRCUIT:

3. Temperature measure

Using a LM35 sensor you should show the current temperature on the LCD. Consult the documentation about the

LM35 sensor: http://www.ti.com/lit/ds/symlink/lm35.pdf. As you can check the sensor gives a 10mV/ºC

tension.

// set up the LCD's number of columns and rows:

char msg[20];

#include <LiquidCrystal.h>

{

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

{

void setup()

CODE:

lcd.begin(16, 2);

void loop()

lcd.print(msg);

sprintf(msg,"Temp = %d%cC",temp,178); //create the text string to send to the LCD

}

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int temp=analogRead(0)*500/1023; //10mV/ºC -> convert to ºC

}

lcd.setCursor(0, 0);

https://www.tinkercad.com/things/8h3Z9DviRtp

https://www.tinkercad.com/things/icWyROFaZr9

Page 18: Robot4All IO5 Exercises and Solutions Robotics

16 17

const int ping = 2;

CODE:

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

Use the sensor Ping of Paralax to measure a distance and show it in cm on the LCD. Do it in Tinkercad and

simulate it. Build the corresponding circuit and test it. If you do not have the Ping sensor of Parallax you can

modify it using a HC-SR04, but in this case we use a pin for trigger and another one for echo. Sensor

documentation: https://www.parallax.com/product/28015n.

CIRCUIT:

4. Measuring distances with Paralax Ping sensor

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#include <LiquidCrystal.h>

}

void loop()

lcd.begin(16, 2);

{

{

void setup()

lcd.print("Distance: ");

digitalWrite(ping, HIGH);

5. Servo control

Control a servo according to the potentiometer position. You will connect the potentiometer so that it gives a

value between 0 and 5 V at the pin A3. You will also connect the servo to the pin D9 and it will be controlled

generating a PWM signal through the Servo class.

lcd.print(distance);

}

pinMode(ping, INPUT); // set to input for echo

delayMicroseconds(10);

long duration = pulseIn(ping, HIGH);

// Calculating the distance

digitalWrite(ping, LOW);

// Reading the echo duration

lcd.setCursor(0, 1);

int distance= duration/58;

// Trigger pin start low

pinMode(ping, OUTPUT); // Output

digitalWrite(ping, LOW);

delayMicroseconds(2);

// Generation of a 10us HIGH pulse as trigger

https://www.tinkercad.com/things/kDk54zrw28W

Page 19: Robot4All IO5 Exercises and Solutions Robotics

16 17

const int ping = 2;

CODE:

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

Use the sensor Ping of Paralax to measure a distance and show it in cm on the LCD. Do it in Tinkercad and

simulate it. Build the corresponding circuit and test it. If you do not have the Ping sensor of Parallax you can

modify it using a HC-SR04, but in this case we use a pin for trigger and another one for echo. Sensor

documentation: https://www.parallax.com/product/28015n.

CIRCUIT:

4. Measuring distances with Paralax Ping sensor

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#include <LiquidCrystal.h>

}

void loop()

lcd.begin(16, 2);

{

{

void setup()

lcd.print("Distance: ");

digitalWrite(ping, HIGH);

5. Servo control

Control a servo according to the potentiometer position. You will connect the potentiometer so that it gives a

value between 0 and 5 V at the pin A3. You will also connect the servo to the pin D9 and it will be controlled

generating a PWM signal through the Servo class.

lcd.print(distance);

}

pinMode(ping, INPUT); // set to input for echo

delayMicroseconds(10);

long duration = pulseIn(ping, HIGH);

// Calculating the distance

digitalWrite(ping, LOW);

// Reading the echo duration

lcd.setCursor(0, 1);

int distance= duration/58;

// Trigger pin start low

pinMode(ping, OUTPUT); // Output

digitalWrite(ping, LOW);

delayMicroseconds(2);

// Generation of a 10us HIGH pulse as trigger

https://www.tinkercad.com/things/kDk54zrw28W

Page 20: Robot4All IO5 Exercises and Solutions Robotics

18 19

#include <Servo.h>

#define pinPotentiometer A3

void setup()

{

servo.write(position);

}

servo.attach(9);

void loop()

Servo servo;

}

int position=map(potentiometer,0,1023,0,180);

int potentiometer=analogRead(pinPotentiometer);

{

CIRCUIT:

CODE:

https://www.tinkercad.com/things/9qYj2rVm0jD

LESSON 6:

ADVANCED ARDUINO

Ÿ Light effects.

Ÿ To use complex hardware and software combinations in Arduino.

Ÿ To communicate Arduino with other platforms and create mixed software/hardware solutions.

OBJECTIVES

After completing this lesson students should be able:

Ÿ To understand and use complex C++ Arduino structures and use complex classes and objects.

Ÿ To understand schematics and use them as a guide for assembling circuits using Arduino and other different

hardware.

Ÿ To create libraries with C++ functions, classes and objects.

EXERCISES

Ÿ PWM control: https://www.tinkercad.com/things/hm05Kl1ERG5

Ÿ Access control with arduino yun: https://github.com/fperal/AccessControl

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and a LCD, a driver and a DC motor. It

will have three buttons: one will set rotation clockwise, other will set rotation counterclockwise and the other

will stop the motor. It will have a potentiometer which will set the speed

CIRCUIT:

1. PWM control

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

Ÿ Simulate the circuit in Tinkercad.

Page 21: Robot4All IO5 Exercises and Solutions Robotics

18 19

#include <Servo.h>

#define pinPotentiometer A3

void setup()

{

servo.write(position);

}

servo.attach(9);

void loop()

Servo servo;

}

int position=map(potentiometer,0,1023,0,180);

int potentiometer=analogRead(pinPotentiometer);

{

CIRCUIT:

CODE:

https://www.tinkercad.com/things/9qYj2rVm0jD

LESSON 6:

ADVANCED ARDUINO

Ÿ Light effects.

Ÿ To use complex hardware and software combinations in Arduino.

Ÿ To communicate Arduino with other platforms and create mixed software/hardware solutions.

OBJECTIVES

After completing this lesson students should be able:

Ÿ To understand and use complex C++ Arduino structures and use complex classes and objects.

Ÿ To understand schematics and use them as a guide for assembling circuits using Arduino and other different

hardware.

Ÿ To create libraries with C++ functions, classes and objects.

EXERCISES

Ÿ PWM control: https://www.tinkercad.com/things/hm05Kl1ERG5

Ÿ Access control with arduino yun: https://github.com/fperal/AccessControl

Ÿ Using Tinkercad circuits, create a circuit with Arduino UNO, a breadboard, and a LCD, a driver and a DC motor. It

will have three buttons: one will set rotation clockwise, other will set rotation counterclockwise and the other

will stop the motor. It will have a potentiometer which will set the speed

CIRCUIT:

1. PWM control

Ÿ Build the corresponding real circuit, program it with arduino IDE and test it.

Ÿ Simulate the circuit in Tinkercad.

Page 22: Robot4All IO5 Exercises and Solutions Robotics

20 21

CODE:

#include <LiquidCrystal.h>

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

#define clockwise 0

#define counterclockwise 1

#define stop 2

#define enable 3

#define MotorPositive 9

#define MotorNegative 10

#define ButtonCW 15

#define ButtonCCW 16

#define ButtonStop 17

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()

pinMode(ButtonCCW,INPUT);

}

{

pinMode(MotorNegative,OUTPUT);

lcd.begin(16, 2);

void SetMotorSpeed(int percent);

pinMode(enable,OUTPUT);

// set up the LCD's number of columns and rows:

pinMode(MotorPositive,OUTPUT);

void SetMotorDirection(int dir);

pinMode(ButtonCW,INPUT);

pinMode(ButtonStop,INPUT);

SetMotorDirection(clockwise);

{

lcd.setCursor(0, 0);

lcd.setCursor(0, 0);

void loop()

{

if (digitalRead(ButtonCW))

lcd.setCursor(0, 0);

}

if (digitalRead(ButtonCCW))

{

lcd.print("Dir: CW ");

SetMotorDirection(counterclockwise);

lcd.print("Dir: CCW ");

}

if (digitalRead(ButtonStop))

{

SetMotorDirection(stop);

lcd.print("Dir: stop ");

int speed=analogRead(A0)/10;

SetMotorSpeed(speed);

lcd.setCursor(0,1);

lcd.print("Speed: ");

lcd.print(speed);

}

lcd.print(" ");

}

Page 23: Robot4All IO5 Exercises and Solutions Robotics

20 21

CODE:

#include <LiquidCrystal.h>

const int rs = 13, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;

#define clockwise 0

#define counterclockwise 1

#define stop 2

#define enable 3

#define MotorPositive 9

#define MotorNegative 10

#define ButtonCW 15

#define ButtonCCW 16

#define ButtonStop 17

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()

pinMode(ButtonCCW,INPUT);

}

{

pinMode(MotorNegative,OUTPUT);

lcd.begin(16, 2);

void SetMotorSpeed(int percent);

pinMode(enable,OUTPUT);

// set up the LCD's number of columns and rows:

pinMode(MotorPositive,OUTPUT);

void SetMotorDirection(int dir);

pinMode(ButtonCW,INPUT);

pinMode(ButtonStop,INPUT);

SetMotorDirection(clockwise);

{

lcd.setCursor(0, 0);

lcd.setCursor(0, 0);

void loop()

{

if (digitalRead(ButtonCW))

lcd.setCursor(0, 0);

}

if (digitalRead(ButtonCCW))

{

lcd.print("Dir: CW ");

SetMotorDirection(counterclockwise);

lcd.print("Dir: CCW ");

}

if (digitalRead(ButtonStop))

{

SetMotorDirection(stop);

lcd.print("Dir: stop ");

int speed=analogRead(A0)/10;

SetMotorSpeed(speed);

lcd.setCursor(0,1);

lcd.print("Speed: ");

lcd.print(speed);

}

lcd.print(" ");

}

Page 24: Robot4All IO5 Exercises and Solutions Robotics

22 23

{

2. Light effects

Ÿ We are going to use the class FastLED to make some light effects with a color led strip.

digitalWrite(MotorPositive,HIGH);

Ÿ Fastled class

break;

case clockwise:

void SetMotorDirection(int dir)

analogWrite(enable,percent*2.55);

{

break;

digitalWrite(MotorPositive,LOW);

digitalWrite(MotorNegative,HIGH);

{

case counterclockwise:

break;

digitalWrite(MotorNegative,LOW);

void SetMotorSpeed(int percent)

switch(dir)

digitalWrite(MotorNegative,HIGH);

}

digitalWrite(MotorPositive,HIGH);

}

case stop:

}

DOCUMENTATION:

Ÿ Fastled basic usage

Ÿ RGB led strip

CODE:

#include "FastLED.h"

#define NumLeds 30

randomSeed(analogRead(0));

void loop()

//red increasing gradient

}

leds[i] = CRGB::White; FastLED.show(); delay(30);

delay(100);

}

for(int i=0; i<NumLeds; i++)

void setup()

for(int i=0; i<NumLeds; i++)

{

leds[i] = CRGB::Black; FastLED.show(); delay(30);

#define DATA_PIN 6

}

//clearing red

for(int i=0; i<NumLeds; i++)

FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NumLeds);

CRGB leds[NumLeds];

{

//color gradient

{

leds[i].red=i; FastLED.show();

{

//white sweep

https://www.tinkercad.com/things/hm

05Kl1ERG5

Page 25: Robot4All IO5 Exercises and Solutions Robotics

22 23

{

2. Light effects

Ÿ We are going to use the class FastLED to make some light effects with a color led strip.

digitalWrite(MotorPositive,HIGH);

Ÿ Fastled class

break;

case clockwise:

void SetMotorDirection(int dir)

analogWrite(enable,percent*2.55);

{

break;

digitalWrite(MotorPositive,LOW);

digitalWrite(MotorNegative,HIGH);

{

case counterclockwise:

break;

digitalWrite(MotorNegative,LOW);

void SetMotorSpeed(int percent)

switch(dir)

digitalWrite(MotorNegative,HIGH);

}

digitalWrite(MotorPositive,HIGH);

}

case stop:

}

DOCUMENTATION:

Ÿ Fastled basic usage

Ÿ RGB led strip

CODE:

#include "FastLED.h"

#define NumLeds 30

randomSeed(analogRead(0));

void loop()

//red increasing gradient

}

leds[i] = CRGB::White; FastLED.show(); delay(30);

delay(100);

}

for(int i=0; i<NumLeds; i++)

void setup()

for(int i=0; i<NumLeds; i++)

{

leds[i] = CRGB::Black; FastLED.show(); delay(30);

#define DATA_PIN 6

}

//clearing red

for(int i=0; i<NumLeds; i++)

FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NumLeds);

CRGB leds[NumLeds];

{

//color gradient

{

leds[i].red=i; FastLED.show();

{

//white sweep

https://www.tinkercad.com/things/hm

05Kl1ERG5

Page 26: Robot4All IO5 Exercises and Solutions Robotics

24 25

leds[i].red=0; FastLED.show();

{

leds[i].blue=0; FastLED.show();

}

delay(100);

delay(100);

for(int i=0; i<NumLeds; i++)

//clearing gree

{

//gree increasing gradient

{

delay(100);

leds[i].green=0; FastLED.show();

}

leds[i].green=i; FastLED.show();

//blue increasing gradient

for(int i=0; i<NumLeds; i++)

for(int i=0; i<NumLeds; i++)

}

{

leds[i].blue=i; FastLED.show();

delay(100);

}

//clearing blue

for(int i=0; i<NumLeds; i++)

{

delay(100);

}

int time=millis();

do

int red,green,blue,led;

blue=random(255);

leds[led].green=green;

//random colors on each led

{

leds[led].red=red;

FastLED.show();

leds[led].blue=blue;

} while (millis()<(time+5000)); //during 5seconds

red=random(255);

led=random(NumLeds);

}

green=random(255);

3. Access control with Arduino Yun

Ÿ The goal of this exercise is to control access to a place controlling a electric lock using RFID tokes and a RFID

lector RMD6300, using an arduino Yun.

DOCUMENTATION:

Ÿ RFID tokens

Ÿ RMD6300

Ÿ The program will read tokens through RMD6300, that will be connected to a serial port, will check if the token

is authorized and will open the door just in case.

Ÿ The Arduino yun will keep a file with authorized users and tokens and other file with access logs.

Page 27: Robot4All IO5 Exercises and Solutions Robotics

24 25

leds[i].red=0; FastLED.show();

{

leds[i].blue=0; FastLED.show();

}

delay(100);

delay(100);

for(int i=0; i<NumLeds; i++)

//clearing gree

{

//gree increasing gradient

{

delay(100);

leds[i].green=0; FastLED.show();

}

leds[i].green=i; FastLED.show();

//blue increasing gradient

for(int i=0; i<NumLeds; i++)

for(int i=0; i<NumLeds; i++)

}

{

leds[i].blue=i; FastLED.show();

delay(100);

}

//clearing blue

for(int i=0; i<NumLeds; i++)

{

delay(100);

}

int time=millis();

do

int red,green,blue,led;

blue=random(255);

leds[led].green=green;

//random colors on each led

{

leds[led].red=red;

FastLED.show();

leds[led].blue=blue;

} while (millis()<(time+5000)); //during 5seconds

red=random(255);

led=random(NumLeds);

}

green=random(255);

3. Access control with Arduino Yun

Ÿ The goal of this exercise is to control access to a place controlling a electric lock using RFID tokes and a RFID

lector RMD6300, using an arduino Yun.

DOCUMENTATION:

Ÿ RFID tokens

Ÿ RMD6300

Ÿ The program will read tokens through RMD6300, that will be connected to a serial port, will check if the token

is authorized and will open the door just in case.

Ÿ The Arduino yun will keep a file with authorized users and tokens and other file with access logs.

Page 28: Robot4All IO5 Exercises and Solutions Robotics

26 27

CIRCUIT:

////////////////////////////////////////////////////////////////////////////////////////////

//

// RFIDYun

// Arduino program uses RMD6300 to read RFID tokens

//AltSoftSerial work better than softwareserial (better performance)

//it uses a timer

// RFIDid is a 7 digit number

// Linino part stores RFID valid numbers in a file named users

#include <FileIO.h>

#include <Bridge.h>

// line format is RFIDid:username

//DEBUG uses "serial" console. If it is not available it freezes at the beginning of the program

//#define DEBUG

//FILEDEBUG uses access log file to log button apen as well as rfid login

#include <AltSoftSerial.h>

#define FILEDEBUG

//#include <SoftwareSerial.h>

// users format is similar to /etc/passwd: one line for each user

AltSoftSerial RFID; //(RX=13, TX=5)

//SoftwareSerial RFID(2,8); //(RX=2, TX=8)

int TagCheck(unsigned long int code, char *tag);

unsigned long int longCalcCode(char *tag);

String getTimeStamp();

int ReadUser(File&, char *tag, char *username);

unsigned char HexToNum(unsigned char digit);

CODE:

Page 29: Robot4All IO5 Exercises and Solutions Robotics

26 27

CIRCUIT:

////////////////////////////////////////////////////////////////////////////////////////////

//

// RFIDYun

// Arduino program uses RMD6300 to read RFID tokens

//AltSoftSerial work better than softwareserial (better performance)

//it uses a timer

// RFIDid is a 7 digit number

// Linino part stores RFID valid numbers in a file named users

#include <FileIO.h>

#include <Bridge.h>

// line format is RFIDid:username

//DEBUG uses "serial" console. If it is not available it freezes at the beginning of the program

//#define DEBUG

//FILEDEBUG uses access log file to log button apen as well as rfid login

#include <AltSoftSerial.h>

#define FILEDEBUG

//#include <SoftwareSerial.h>

// users format is similar to /etc/passwd: one line for each user

AltSoftSerial RFID; //(RX=13, TX=5)

//SoftwareSerial RFID(2,8); //(RX=2, TX=8)

int TagCheck(unsigned long int code, char *tag);

unsigned long int longCalcCode(char *tag);

String getTimeStamp();

int ReadUser(File&, char *tag, char *username);

unsigned char HexToNum(unsigned char digit);

CODE:

Page 30: Robot4All IO5 Exercises and Solutions Robotics

28 29

//green led pin 8

//red led pin 10

#define GREEN 8

#define RED 10

#define BUTTON 11

{

void setup()

RFID.begin(9600); // start serial to RFID reader

pinMode(GREEN, OUTPUT);

#ifdef DEBUG

FileSystem.open("users",FILE_READ);

pinMode(RED, OUTPUT);

Bridge.begin(); //start communication with linino

while (!Console); //wait until console is ready

Console.println("Arduino starting......");

#endif

/* //initialize comunication with the filesystem in the linino part

Console.begin(); //start communication with ethernet console (300bps)

FileSystem.begin();

*/

}

void loop()

{

char tag[14];

int index = 0;

int i;

//creating log, it will add user to the end of the log file

UsersFile.close(); //finished reading, file closed

File LogFile = FileSystem.open("/root/accesslog", FILE_APPEND);

}

#ifdef DEBUG //printing the code readed to the console terminal

Console.print(" ");

i = RFID.read();

do //making a sweep of the 13 bytes and putting all together in a string

char rfid[10], user[25], userOK[25] = "";

//create objets UsersFile, linked to users in linino, open for reading

File UsersFile = FileSystem.open("/root/users", FILE_READ);

if (RFID.available() > 13) //RFID token is 13 bytes long, so I check if there is at least 13 bytes

{

{

Console.print(i);

} while (i != 3);

tag[index++] = i;

Console.println(" "); //sending LF to the console (if not it does not show)

#endif

int OK = 0;

while (ReadUser(UsersFile, rfid, user) == 0) //we will sweep all users file until user found or EOF

{

{

OK = 1;

#endif

if (TagCheck(atol(rfid), tag)) //convert string to number and check against tag

strcpy(userOK, user);

}

#ifdef DEBUG

Page 31: Robot4All IO5 Exercises and Solutions Robotics

28 29

//green led pin 8

//red led pin 10

#define GREEN 8

#define RED 10

#define BUTTON 11

{

void setup()

RFID.begin(9600); // start serial to RFID reader

pinMode(GREEN, OUTPUT);

#ifdef DEBUG

FileSystem.open("users",FILE_READ);

pinMode(RED, OUTPUT);

Bridge.begin(); //start communication with linino

while (!Console); //wait until console is ready

Console.println("Arduino starting......");

#endif

/* //initialize comunication with the filesystem in the linino part

Console.begin(); //start communication with ethernet console (300bps)

FileSystem.begin();

*/

}

void loop()

{

char tag[14];

int index = 0;

int i;

//creating log, it will add user to the end of the log file

UsersFile.close(); //finished reading, file closed

File LogFile = FileSystem.open("/root/accesslog", FILE_APPEND);

}

#ifdef DEBUG //printing the code readed to the console terminal

Console.print(" ");

i = RFID.read();

do //making a sweep of the 13 bytes and putting all together in a string

char rfid[10], user[25], userOK[25] = "";

//create objets UsersFile, linked to users in linino, open for reading

File UsersFile = FileSystem.open("/root/users", FILE_READ);

if (RFID.available() > 13) //RFID token is 13 bytes long, so I check if there is at least 13 bytes

{

{

Console.print(i);

} while (i != 3);

tag[index++] = i;

Console.println(" "); //sending LF to the console (if not it does not show)

#endif

int OK = 0;

while (ReadUser(UsersFile, rfid, user) == 0) //we will sweep all users file until user found or EOF

{

{

OK = 1;

#endif

if (TagCheck(atol(rfid), tag)) //convert string to number and check against tag

strcpy(userOK, user);

}

#ifdef DEBUG

Page 32: Robot4All IO5 Exercises and Solutions Robotics

30 31

//without this, it reads 6 times each RFID.

digitalWrite(RED, HIGH);

delay(2000);

RFID.flush();

}

delay(3000);

while (RFID.available())RFID.read(); //flush seem not to work well, so I read all data from RFID to empty it

LogFile.close();

digitalWrite(RED, LOW);

#ifdef DEBUG

LogFile.print(userOK); //log access to file

#endif

Console.print("Hello ");

Console.println(userOK);

if (OK)

{

Console.println("OK");

digitalWrite(GREEN, HIGH);

delay(2000);

digitalWrite(GREEN, LOW);

}

LogFile.print(" access at "); LogFile.println(getTimeStamp());

else

{

#ifdef DEBUG

Console.println("ERROR");

#endif

String line=CalendarFile.readStringUntil('\n');

{

}

{

{

if (line.substring(6,7)=="O") OpenTheDoor=1;

if (line.length()==7 && line.substring(0,1)!="#")

unsigned long int LineSeconds=3600*(line.substring(0,2)).toInt()+60*(line.substring(3,5)).toInt();

if (line.substring(6,7)=="C") OpenTheDoor=0;

}

//tranlating HH:MM to seconds from midnight

if (seconds>LineSeconds)

}

String sMinutes=sDate.substring(14,16);

String sSeconds=sDate.substring(17,19);

String sHours=sDate.substring(11,13);

//getting date in seconds from midnight

String sDate=getTimeStamp();

// calendar file /root/calendar

if (sDay.toInt()<6) //from monday to friday

{

String sDay=sDate.substring(0,1);

}

unsigned long int seconds=3600*sHours.toInt()+60*sMinutes.toInt()+sSeconds.toInt();

int OpenTheDoor=0;

//and HH:MM/C for close the door

//format HH:MM/O for open the door

File CalendarFile = FileSystem.open("/root/calendar", FILE_READ);

//Reading lines from the file. The lines are marked with the time in wich we open or close the door

while(CalendarFile.available()>0)

Page 33: Robot4All IO5 Exercises and Solutions Robotics

30 31

//without this, it reads 6 times each RFID.

digitalWrite(RED, HIGH);

delay(2000);

RFID.flush();

}

delay(3000);

while (RFID.available())RFID.read(); //flush seem not to work well, so I read all data from RFID to empty it

LogFile.close();

digitalWrite(RED, LOW);

#ifdef DEBUG

LogFile.print(userOK); //log access to file

#endif

Console.print("Hello ");

Console.println(userOK);

if (OK)

{

Console.println("OK");

digitalWrite(GREEN, HIGH);

delay(2000);

digitalWrite(GREEN, LOW);

}

LogFile.print(" access at "); LogFile.println(getTimeStamp());

else

{

#ifdef DEBUG

Console.println("ERROR");

#endif

String line=CalendarFile.readStringUntil('\n');

{

}

{

{

if (line.substring(6,7)=="O") OpenTheDoor=1;

if (line.length()==7 && line.substring(0,1)!="#")

unsigned long int LineSeconds=3600*(line.substring(0,2)).toInt()+60*(line.substring(3,5)).toInt();

if (line.substring(6,7)=="C") OpenTheDoor=0;

}

//tranlating HH:MM to seconds from midnight

if (seconds>LineSeconds)

}

String sMinutes=sDate.substring(14,16);

String sSeconds=sDate.substring(17,19);

String sHours=sDate.substring(11,13);

//getting date in seconds from midnight

String sDate=getTimeStamp();

// calendar file /root/calendar

if (sDay.toInt()<6) //from monday to friday

{

String sDay=sDate.substring(0,1);

}

unsigned long int seconds=3600*sHours.toInt()+60*sMinutes.toInt()+sSeconds.toInt();

int OpenTheDoor=0;

//and HH:MM/C for close the door

//format HH:MM/O for open the door

File CalendarFile = FileSystem.open("/root/calendar", FILE_READ);

//Reading lines from the file. The lines are marked with the time in wich we open or close the door

while(CalendarFile.available()>0)

Page 34: Robot4All IO5 Exercises and Solutions Robotics

32 33

CalendarFile.close();

}

if(!digitalRead(BUTTON)) //user request to open the door (pull-up)

{

if(OpenTheDoor) //if the schedule says the door should be opened now

{

else

File LogFile = FileSystem.open("/root/accesslog", FILE_APPEND);

delay(1000);

/*

}

}

#ifdef FILEDEBUG

delay(1000);

#ifdef DEBUG

digitalWrite(GREEN, HIGH); //it will blink open

}

#endif

#endif

Console.println(" / Open / ");

LogFile.print("BUTTON access at "); LogFile.println(getTimeStamp());

digitalWrite(GREEN, LOW);

{

digitalWrite(GREEN, LOW);

digitalWrite(RED, LOW);

digitalWrite(RED,HIGH);

if(OpenTheDoor) //if the schedule says the door should be opened now

{

#ifdef DEBUG

Console.println(" / Open / ");

#endif

digitalWrite(GREEN, HIGH); //it will blink open 1s every 10s

delay(1000);

digitalWrite(GREEN, LOW);

delay(9000);

}

else

{

#ifdef DEBUG

delay(10000);

}

{

if ( (digit >= '0') && (digit <= '9') ) return digit - 48;

*/

Console.println(" / close / ");

#endif

///////////////////////////////////////////////////////

// HexToNum

//

// C onvert a HEX digit in ASCII format to a number with its value

//

unsigned char HexToNum(unsigned char digit)

if ( (digit >= 'a') && (digit <= 'f') ) return digit - 87;

}

}

if ( (digit >= 'A') && (digit <= 'F') ) return digit - 55;

////////////////////////////////////////////////////////

// TagCheck

//

Page 35: Robot4All IO5 Exercises and Solutions Robotics

32 33

CalendarFile.close();

}

if(!digitalRead(BUTTON)) //user request to open the door (pull-up)

{

if(OpenTheDoor) //if the schedule says the door should be opened now

{

else

File LogFile = FileSystem.open("/root/accesslog", FILE_APPEND);

delay(1000);

/*

}

}

#ifdef FILEDEBUG

delay(1000);

#ifdef DEBUG

digitalWrite(GREEN, HIGH); //it will blink open

}

#endif

#endif

Console.println(" / Open / ");

LogFile.print("BUTTON access at "); LogFile.println(getTimeStamp());

digitalWrite(GREEN, LOW);

{

digitalWrite(GREEN, LOW);

digitalWrite(RED, LOW);

digitalWrite(RED,HIGH);

if(OpenTheDoor) //if the schedule says the door should be opened now

{

#ifdef DEBUG

Console.println(" / Open / ");

#endif

digitalWrite(GREEN, HIGH); //it will blink open 1s every 10s

delay(1000);

digitalWrite(GREEN, LOW);

delay(9000);

}

else

{

#ifdef DEBUG

delay(10000);

}

{

if ( (digit >= '0') && (digit <= '9') ) return digit - 48;

*/

Console.println(" / close / ");

#endif

///////////////////////////////////////////////////////

// HexToNum

//

// C onvert a HEX digit in ASCII format to a number with its value

//

unsigned char HexToNum(unsigned char digit)

if ( (digit >= 'a') && (digit <= 'f') ) return digit - 87;

}

}

if ( (digit >= 'A') && (digit <= 'F') ) return digit - 55;

////////////////////////////////////////////////////////

// TagCheck

//

Page 36: Robot4All IO5 Exercises and Solutions Robotics

34 35

// Check decimal number printed on tag against tag readed

//

// by RFID sensor in HEX format

// code -> decimal code printed on tag

// tag[] -> character array containig tag in HEX format

{

int TagCheck(unsigned long int code, char *tag)

unsigned char HexData[4];

//

for (int i = 3, index = 0; i < 11; i = i + 2, index++) HexData[index] = (HexToNum(tag[i]) << 4) + HexToNum(tag[i +

1]);

int i = 0;

int checksum = 0x0A;

unsigned long int CalcCode = HexData[0];

checksum = checksum ̂ HexData[i];

while (i < 4)

{

return code == CalcCode;

}

}

//

// longCalcCode

////////////////////////////////////////////////////////

// as printed in tags

CalcCode = (CalcCode << 8) + HexData[i++]; //generate the code using hex digits weights

//

// code -> decimal code printed on tag

// Convert RFID sensor in HEX format to numeric format

unsigned long int longCalcCode(char *tag)

checksum = checksum ̂ HexData[i];

unsigned long int CalcCode = HexData[0];

unsigned char HexData[4];

// tag[] -> character array containig tag in HEX format

//

int i = 0;

for (int i = 3, index = 0; i < 11; i = i + 2, index++) HexData[index] = (HexToNum(tag[i]) << 4) + HexToNum(tag[i +

1]);

int checksum = 0x0A;

while (i < 4)

{

CalcCode = (CalcCode << 8) + HexData[i++]; //generate the code using hex digits weights

}

return CalcCode;

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////

// ReadUser

//

// Reads linino file for the next tag id

// Returns tagID in string format at tag and username also in string format at username

// Returns 0 if everything went OK and >0 if there is some error:

int ReadUser(File& UsersFile, char *tag, char *username)

{

if (UsersFile == 0) return 1;

// 1 -> Error reading file /root/users

// 2 -> Error: /root/users may be empty?

Page 37: Robot4All IO5 Exercises and Solutions Robotics

34 35

// Check decimal number printed on tag against tag readed

//

// by RFID sensor in HEX format

// code -> decimal code printed on tag

// tag[] -> character array containig tag in HEX format

{

int TagCheck(unsigned long int code, char *tag)

unsigned char HexData[4];

//

for (int i = 3, index = 0; i < 11; i = i + 2, index++) HexData[index] = (HexToNum(tag[i]) << 4) + HexToNum(tag[i +

1]);

int i = 0;

int checksum = 0x0A;

unsigned long int CalcCode = HexData[0];

checksum = checksum ̂ HexData[i];

while (i < 4)

{

return code == CalcCode;

}

}

//

// longCalcCode

////////////////////////////////////////////////////////

// as printed in tags

CalcCode = (CalcCode << 8) + HexData[i++]; //generate the code using hex digits weights

//

// code -> decimal code printed on tag

// Convert RFID sensor in HEX format to numeric format

unsigned long int longCalcCode(char *tag)

checksum = checksum ̂ HexData[i];

unsigned long int CalcCode = HexData[0];

unsigned char HexData[4];

// tag[] -> character array containig tag in HEX format

//

int i = 0;

for (int i = 3, index = 0; i < 11; i = i + 2, index++) HexData[index] = (HexToNum(tag[i]) << 4) + HexToNum(tag[i +

1]);

int checksum = 0x0A;

while (i < 4)

{

CalcCode = (CalcCode << 8) + HexData[i++]; //generate the code using hex digits weights

}

return CalcCode;

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////

// ReadUser

//

// Reads linino file for the next tag id

// Returns tagID in string format at tag and username also in string format at username

// Returns 0 if everything went OK and >0 if there is some error:

int ReadUser(File& UsersFile, char *tag, char *username)

{

if (UsersFile == 0) return 1;

// 1 -> Error reading file /root/users

// 2 -> Error: /root/users may be empty?

Page 38: Robot4All IO5 Exercises and Solutions Robotics

36 37

if (UsersFile.available() == 0) return 2; //no data found. Maybe EOF?

{

tag[i] = data[i];

int n = 0;

// This function return a string with the time stamp

// getTimeStamp()

//////////////////////////////////////////////////////////////////////////////////////////////////////////

} while (data[++i] != '\n');

char data[25] = "xx";

tag[i++] = '\0'; //add string terminator

}

//

{

return 0; //all went OK

if (data[i] != '\n') i++; //next char until LF found

while (UsersFile.available() > 0 && data[i] != '\n') //read file until EOF or LF found

do //read username, until LF found

{

int i = 0;

}

i = 0;

data[i] = UsersFile.read();

do //read tag, until : found

} while (data[++i] != ':');

username[n++] = data[i];

username[n] = '\0'; //add end of string

//

//

// From https://www.arduino.cc/en/Tutorial/YunDatalogger

// T for the time hh:mm:ss

Process time;

String getTimeStamp()

{

String result;

// date is a command line utility to get the date and the time

// in different formats depending on the additional parameter

time.begin("date");

time.addParameter("+%u %D %T"); // parameters: D for the complete date mm/dd/yy

// u for week day number (1 is monday)

// read the output of the command

while (time.available() > 0) {

char c = time.read();

if (c != '\n') {

result += c;

time.run(); // run the command

}

}

return result;

}

https://github.com/fperal/AccessControl

Page 39: Robot4All IO5 Exercises and Solutions Robotics

36 37

if (UsersFile.available() == 0) return 2; //no data found. Maybe EOF?

{

tag[i] = data[i];

int n = 0;

// This function return a string with the time stamp

// getTimeStamp()

//////////////////////////////////////////////////////////////////////////////////////////////////////////

} while (data[++i] != '\n');

char data[25] = "xx";

tag[i++] = '\0'; //add string terminator

}

//

{

return 0; //all went OK

if (data[i] != '\n') i++; //next char until LF found

while (UsersFile.available() > 0 && data[i] != '\n') //read file until EOF or LF found

do //read username, until LF found

{

int i = 0;

}

i = 0;

data[i] = UsersFile.read();

do //read tag, until : found

} while (data[++i] != ':');

username[n++] = data[i];

username[n] = '\0'; //add end of string

//

//

// From https://www.arduino.cc/en/Tutorial/YunDatalogger

// T for the time hh:mm:ss

Process time;

String getTimeStamp()

{

String result;

// date is a command line utility to get the date and the time

// in different formats depending on the additional parameter

time.begin("date");

time.addParameter("+%u %D %T"); // parameters: D for the complete date mm/dd/yy

// u for week day number (1 is monday)

// read the output of the command

while (time.available() > 0) {

char c = time.read();

if (c != '\n') {

result += c;

time.run(); // run the command

}

}

return result;

}

https://github.com/fperal/AccessControl

Page 40: Robot4All IO5 Exercises and Solutions Robotics

38 39

LED

A Light Emmiting Diode is a optoelectronics device wich emmits colored light when directly polarized. It must be

used with a resistor to limit intensity. Typically it has a direct voltage drop near 2V. More information at Wikipedia:

https://en.wikipedia.org/wiki/Light-emitting_diode

BREADBOARD

A breadboard is used to quickly assemble circuits without soldering. The holes are connected as can be seen

in this image. More information in Wikipedia: https://en.wikipedia.org/wiki/Breadboard

A resistor is a device that implements electrical resistance to the current flow. There is a color code to identify

the resistance. More information at Wikipedia: https://en.wikipedia.org/wiki/Resistor

POTENTIOMETER

Is a variable resistor device with three terminals. It can be used as a variable resistor or as a voltage divider. More

information at Wikipedia. https://en.wikipedia.org/wiki/Potentiometer

Is a device like any other switch. It closes a circuit.

MICRO PUSH BUTTONS.

RESISTOR

APPENDIX

Page 41: Robot4All IO5 Exercises and Solutions Robotics

38 39

LED

A Light Emmiting Diode is a optoelectronics device wich emmits colored light when directly polarized. It must be

used with a resistor to limit intensity. Typically it has a direct voltage drop near 2V. More information at Wikipedia:

https://en.wikipedia.org/wiki/Light-emitting_diode

BREADBOARD

A breadboard is used to quickly assemble circuits without soldering. The holes are connected as can be seen

in this image. More information in Wikipedia: https://en.wikipedia.org/wiki/Breadboard

A resistor is a device that implements electrical resistance to the current flow. There is a color code to identify

the resistance. More information at Wikipedia: https://en.wikipedia.org/wiki/Resistor

POTENTIOMETER

Is a variable resistor device with three terminals. It can be used as a variable resistor or as a voltage divider. More

information at Wikipedia. https://en.wikipedia.org/wiki/Potentiometer

Is a device like any other switch. It closes a circuit.

MICRO PUSH BUTTONS.

RESISTOR

APPENDIX

Page 42: Robot4All IO5 Exercises and Solutions Robotics

40 41

It is a ultrasound distance sensor. It emmits ultrasound pulses at 40Khz and measure the time between the it

emits the pulses and it receives the reflected pulses, and generates a 5V pulse with variable duration

proportional to the measured distance. More information at parallax: https://www.parallax.com/product/28015.

Lm35

The LM35 is a integrated circuit temperature sensor. It has 3 terminals: power and output. The output is

10mV/ºC. More information at texas instrument webpage: www.ti.com/product/lm35

MICRO-SERVO

PARALLAX PING

A micro servo is a little servomotor. A servo is a special type of motor controlled by a control board which set the

motor to a fixed position. It is possible to adjust the position with few grade accuracy. The servo position is

controlled by the duty cycle of a PWM signal with a typical 50Hz frequency. More information at Wikipedia:

https://en.wikipedia.org/wiki/Servo_control

L293

It is a motor driver integrated circuit to implement a H bridge. It provides full control of a motor, including

bidirectional control and braking. More information at Wikipedia: https://en.wikipedia.org/wiki/H_bridge

DC MICRO MOTOR

A micro motor is a little DC motor suitable to move a little robot. It must be operated through a driver (like L293 or

L298) as it needs currents exceeding 100mA to work. A DC micromotor usually rotates at some thousands rpms,

so, to lower rpm count and increase torque, it is usually equipped with a gear, like the one in the image. More

information at Wikipedia: https://en.wikipedia.org/wiki/DC_motor

N CHANNEL MOSFET

A MOSFET is a power transistor controlled by gate voltage usually used as a voltage controlled switch. More

information: https://www.electronics-tutorials.ws/transistor/tran_6.html

Page 43: Robot4All IO5 Exercises and Solutions Robotics

40 41

It is a ultrasound distance sensor. It emmits ultrasound pulses at 40Khz and measure the time between the it

emits the pulses and it receives the reflected pulses, and generates a 5V pulse with variable duration

proportional to the measured distance. More information at parallax: https://www.parallax.com/product/28015.

Lm35

The LM35 is a integrated circuit temperature sensor. It has 3 terminals: power and output. The output is

10mV/ºC. More information at texas instrument webpage: www.ti.com/product/lm35

MICRO-SERVO

PARALLAX PING

A micro servo is a little servomotor. A servo is a special type of motor controlled by a control board which set the

motor to a fixed position. It is possible to adjust the position with few grade accuracy. The servo position is

controlled by the duty cycle of a PWM signal with a typical 50Hz frequency. More information at Wikipedia:

https://en.wikipedia.org/wiki/Servo_control

L293

It is a motor driver integrated circuit to implement a H bridge. It provides full control of a motor, including

bidirectional control and braking. More information at Wikipedia: https://en.wikipedia.org/wiki/H_bridge

DC MICRO MOTOR

A micro motor is a little DC motor suitable to move a little robot. It must be operated through a driver (like L293 or

L298) as it needs currents exceeding 100mA to work. A DC micromotor usually rotates at some thousands rpms,

so, to lower rpm count and increase torque, it is usually equipped with a gear, like the one in the image. More

information at Wikipedia: https://en.wikipedia.org/wiki/DC_motor

N CHANNEL MOSFET

A MOSFET is a power transistor controlled by gate voltage usually used as a voltage controlled switch. More

information: https://www.electronics-tutorials.ws/transistor/tran_6.html

Page 44: Robot4All IO5 Exercises and Solutions Robotics

42 43

RGB LED STRIP

It is a strip of color leds. Each of the leds of the strip may be controlled individually setting the intensity of

one of each three color components. The strip used is a NeoPixel strip. The leds are joined in a shift register

and one can set the color of each LED's red, green and blue component with 8-bit PWM precision (so 24-bit

color per pixel). More information at adafruit: https://www.adafruit.com/product/1376?length=1

RDM6300 125KHz card reader mini-module is designed for reading code from 125KHz card compatible read-

only tags and read/write card. More information at Itead wiki: https://www.itead.cc/wiki/RDM6300

RMD6300 RFID CARD READER AND RFID TOKENS

ARDUINO YUN

The Arduino Yún is a microcontroller board based on the ATmega32u4 and the Atheros AR9331. The Atheros

processor supports a Linux distribution based on OpenWrt named Linino OS. The board has built-in Ethernet and

WiFi support, a USB-A port, micro-SD card slot, 20 digital input/output pins (7 of them can be used as PWM

outputs and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP header, and 3

reset buttons.

More information:

Ÿ https://en.wikipedia.org/wiki/OpenWrt

Ÿ https://store.arduino.cc/arduino-yun

Page 45: Robot4All IO5 Exercises and Solutions Robotics

42 43

RGB LED STRIP

It is a strip of color leds. Each of the leds of the strip may be controlled individually setting the intensity of

one of each three color components. The strip used is a NeoPixel strip. The leds are joined in a shift register

and one can set the color of each LED's red, green and blue component with 8-bit PWM precision (so 24-bit

color per pixel). More information at adafruit: https://www.adafruit.com/product/1376?length=1

RDM6300 125KHz card reader mini-module is designed for reading code from 125KHz card compatible read-

only tags and read/write card. More information at Itead wiki: https://www.itead.cc/wiki/RDM6300

RMD6300 RFID CARD READER AND RFID TOKENS

ARDUINO YUN

The Arduino Yún is a microcontroller board based on the ATmega32u4 and the Atheros AR9331. The Atheros

processor supports a Linux distribution based on OpenWrt named Linino OS. The board has built-in Ethernet and

WiFi support, a USB-A port, micro-SD card slot, 20 digital input/output pins (7 of them can be used as PWM

outputs and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP header, and 3

reset buttons.

More information:

Ÿ https://en.wikipedia.org/wiki/OpenWrt

Ÿ https://store.arduino.cc/arduino-yun