Você está na página 1de 13

Prtica 2

Atividade 1:
Sensor de passagem
Nesta prtica vamos utilizar um emissor e um receptor de luz no infra-vermelho para
detectar a passagem de um corpo entre os dois. O emissor usado o TIL32, um LED
que emite luz em 940 nm. O receptor o TIL78, um foto-transistor que opera no
mesmo comprimento de onda. Ver figuras abaixo para um esquema simplificado de
ambos. Foto-transistores so componentes que funcionam como chaves ativadas por
luz. No esquema da figura abaixo, sem nenhuma luz incidente o TIL78 funciona
como uma chave aberta e na sada mediramos uma tenso de 5V. Com uma
quantidade grande de luz incidente, ele funcionaria como um diodo polarizado
diretamente que deixa passar toda a corrente com uma pequena queda de tenso
atravs dele. Nesse caso, a tenso de sada seria igual a essa pequena queda de tenso,
de 0,2 V para o TIL78.



Imagens reproduzidas de http://dqsoft.blogspot.com.br/2013/01/led-e-
fototransistor-infravermelho.html

Hardware necessrio
Placa Arduino
LED emissor TIL32
Foto-transistor TIL78
LED no visvel
2 resistores de 220
1 resistor de 2,7 k
Breadboard
Circuito
No circuito esquematizado abaixo, o TIL32 deve ser posicionado distante vrios
centmetros do TIL78 apontando diretamente para este. O LED deve acender sempre
que algo bloqueie o caminho entre os TIL32 e TIL78.

220
TIL32 LED
5V
D8
220
Arduino

2,7k
TIL78

A0

GND

Cdigo
int led = 8;

void setup() {
pinMode(led,OUTPUT);
}

void loop() {
if(analogRead(A0)>700) {
digitalWrite(led,HIGH);
delay(100);
digitalWrite(led,LOW);
}
delay(4);
}
Atividade 2:
Instantes de passagem
Utilizaremos agora um programa Processing para adquirir a tenso sobre o receptor
da Atividade 1. O programa plota a tenso em funo do tempo, mostrando
claramente os instantes de passagem de objetos entre o emissor e o receptor. Esses
instantes, contados a partir do incio do programa, so ento registrados em um
arquivo texto para anlise futura.

Hardware necessrio
Mesmo da Atividade 1.

Circuito
Mesmo da Atividade 1.

Cdigo
O cdigo Arduino da Atividade 1 modificado para incluir o envio da tenso sobre o
TIL78 pela porta serial. O cdigo Processing o da Atividade 22 da Prtica 1
modificado para plotar o grfico como uma linha contnua ligando os pontos e para
gravar em um arquivo texto, times.txt, todos os instante em que a luz do emissor
TIL32 impedida de atingir o receptor TIL78. O programa para quando qualquer
tecla do teclado pressionada.

Arduino
int led = 8;

void setup() {
Serial.begin(9600);
pinMode(led,OUTPUT);
}

void loop() {
Serial.println((analogRead(A0)));
if(analogRead(A0)>700) {
digitalWrite(led,HIGH);
delay(100);
digitalWrite(led,LOW);
}
delay(4);
}
Processing
import processing.serial.*;
Serial myPort;
int xPos = 1;
float inByte=height;
float inByte2;
PrintWriter output;

void setup() {
size(400,300);
output = createWriter("times.txt");
myPort = new Serial(this,Serial.list()[5],9600);
myPort.bufferUntil('\n');
background(0);
}

void draw(){

void serialEvent (Serial myPort) {


String inString = myPort.readStringUntil('\n');
if (inString != null){
inString = trim(inString);
inByte2 = inByte;
inByte = float(inString);
inByte = map(inByte,0,1023,0,height);

stroke(255,255,255);
line(xPos,height - inByte2,xPos,height - inByte);

if((inByte-inByte2)>100){
output.println(millis());
}

if (xPos >= width) {


xPos = 0;
background(0);
}
else {
xPos++;
}
}
}
void keyPressed() {
output.flush(); // Writes the remaining data to the file
output.close(); // Finishes the file
exit(); // Stops the program
}

Atividade 3:
(baseado em exemplo disponvel em http://www.instructables.com/id/Simple-IR-
proximity-sensor-with-Arduino/?ALLSTEPS )
Sensor de proximidade no infra-vermelho
Utilizaremos os emissores (TIL32) e receptores (TIL78) das prticas anteriores para
implementar um sensor de proximidade. Para isso, um receptor colocado entre 4
emissores (ver seleo na figura abaixo) e isolado oticamente dos mesmos usando fita
preta para isolamento eltrico. Tanto o receptor quanto os emissores apontam para a
mesma direo. Sem nenhum objeto na frente do conjunto, nenhuma luz dos
emissores atinge o receptor. Por outro lado, caso um objeto fique na frente dos
mesmo, luz dos emissores ser refletida pelo objeto e atingir o receptor, baixando
sua tenso e indicando a presena do objeto. Alm disso, quanto mais prximo o
objeto, maior ser a quantidade de luz espalhada para o receptor e menor ser a
tenso de sado do mesmo. Podemos ento conectar um alto-falante ao circuito
soando com uma frequncia que aumenta com a proximidade do objeto. Com isso,
temos ao final um sensor de proximidade para objetos afastados de no mximo cerca
de 25 cm.

Hardware necessrio
Placa Arduino
1 foto-transistor TIL78
4 emissores LED TIL32
resistor de 100 k
Breadboard
Fita eltrica isolante
Alto-falante
Resistor de 100

Circuito
No circuito abaixo, utilizada uma campainha para indicar a proximidade ao
receptor, com ela no precisando de limitao extra de corrente. No entanto, como
usaremos no lugar alto-falantes de 8 , precisamos inserir um resistor de 100 em
srie para limitar a corrente, como em atividades anteriores.

Cdigo
// Simple Proximity Sensor using Infrared
// Description: Measure the distance to an obstacle using infrared light emitted by IR LED and
// read the value with a IR photodiode. The accuracy is not perfect, but works great
// with minor projects.

int IRpin = A0; // IR photodiode on analog pin A0


int IRemitter = 2; // IR emitter LED on digital pin 2
int ambientIR; // variable to store the IR coming from the ambient
int obstacleIR; // variable to store the IR coming from the object
int value[10]; // variable to store the IR values
int distance; // variable that will tell if there is an obstacle or not

void setup(){
Serial.begin(9600); // initializing Serial monitor
pinMode(IRemitter,OUTPUT); // IR emitter LED on digital pin 2
digitalWrite(IRemitter,LOW);// setup IR LED as off
pinMode(11,OUTPUT); // buzzer in digital pin 11
}

void loop(){
distance = readIR(5); // calling the function that will read the distance and passing the "accuracy" to it
Serial.println(distance); // writing the read value on Serial monitor
buzzer();
}

int readIR(int times){


for(int x=0;x<times;x++){
digitalWrite(IRemitter,LOW); // turning the IR LEDs off to read the IR coming from the ambient
delay(1); // minimum delay necessary to read values
ambientIR = analogRead(IRpin); // storing IR coming from the ambient
digitalWrite(IRemitter,HIGH); // turning the IR LEDs on to read the IR coming from the obstacle
delay(1); // minimum delay necessary to read values
obstacleIR = analogRead(IRpin); // storing IR coming from the obstacle
value[x] = ambientIR-obstacleIR; // calculating changes in IR values and storing it for future average
}

for(int x=0;x<times;x++){ // calculating the average based on the "accuracy"


distance+=value[x];
}
return(distance/times); // return the final value
}

//-- Function to sound a buzzer for audible measurements --//


void buzzer(){
if (distance>1){
if(distance>100){ // continuous sound if the obstacle is too close
digitalWrite(11,HIGH);
}
else{ // beeps faster when an obstacle approaches
digitalWrite(11,HIGH);
delay(150-distance); // adjust this value for your convenience
digitalWrite(11,LOW);
delay(150-distance); // adjust this value for your convenience
}
}
else{ // off if there is no obstacle
digitalWrite(11,LOW);
}
}
Atividade 4:
(material retirado de exemplo no site da Arduino + datasheet do mdulo HC-SR04
disponvel em http://users.ece.utexas.edu/~valvano/Datasheets/HCSR04b.pdf +
exemplo disponvel em http://arduinobasics.blogspot.com.br/2012/11/arduinobasics-
hc-sr04-ultrasonic-sensor.html )
Sensor de distncia por ultrasson
The sensor HC-SR04 is an ultrasonic range finde. It detects the distance of the closest
object in front of the sensor (from 2cm up to 4m) with a resolution of 0.3cm. It works
by sending out a burst of ultrasound and listening for the echo when it bounces off of
an object. The Arduino board sends a short pulse to trigger the detection, then listens
for a pulse using the pulseIn() function. The duration of this second pulse is equal to
the time taken by the ultrasound to travel to the object and back to the sensor. Using
the speed of sound, this time can be converted to distance.
The Timing diagram is shown below. You only need to supply a short 10s
pulse to the trigger input to start the ranging, and then the module will send out an 8
cycle burst of ultrasound at 40 kHz and look for its echo. The Echo is a distance
object with its pulse width and the range in proportion. You can calculate the range
through the time interval between sending the trigger signal and receiving the echo
signal. Formula: uS / 58 = centimeters; or: the range = high level time * velocity
(340M/S) / 2. We suggest to use around 60ms measurement cycle.

Hardware required
Arduino board
Ultrasonic sensor HC-SR04
Breadboard
Circuit

Code
/* /*
1 HC-SR04 Ping distance sensor:
VCC to arduino 5v
2 GND to arduino GND
Echo to Arduino pin 7
3 Trig to Arduino pin 8
*/
4

5 #define echoPin 7 // Echo Pin


#define trigPin 8 // Trigger Pin
6
#define LEDPin 13 // Onboard LED
7
int maximumRange = 200; // Maximum range needed
8 int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
9
1 void setup() {
0 Serial.begin (9600);
1 pinMode(trigPin, OUTPUT);
1 pinMode(echoPin, INPUT);
1 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
2 }
1
3 void loop() {
1 /* The following trigPin/echoPin cycle is used to determine the
4 distance of the nearest object by bouncing soundwaves off of it. */
1 digitalWrite(trigPin, LOW);
5 delayMicroseconds(2);
1
6 digitalWrite(trigPin, HIGH);
1 delayMicroseconds(10);
7
1
digitalWrite(trigPin, LOW);
8
duration = pulseIn(echoPin, HIGH);
1
9
2 //Calculate the distance (in cm) based on the speed of sound.
0 distance = duration/58.2;
2
1 if (distance >= maximumRange || distance <= minimumRange){
2 /* Send a negative number to computer and Turn LED ON
2 to indicate "out of range" */
2 Serial.println("-1");
3 digitalWrite(LEDPin, HIGH);
2 }
4 else {
2 /* Send the distance to the computer using Serial protocol, and
5 turn LED OFF to indicate successful reading. */
2 Serial.println(distance);
6 digitalWrite(LEDPin, LOW);
2 }
7
2 //Delay 50ms before next reading.
8 delay(50);
2
}
4
1
0
Atividade 5:
LiquidCrystal - "Hello World!"
The LiquidCrystal library allows you to control LCD displays that are compatible
with the Hitachi HD44780 driver. There are many of them out there, and you can
usually tell them by the 16-pin interface.
This example sketch prints "Hello World!" to the LCD and shows the time in
seconds since the Arduino was reset.

output of the sketch on a 2x16 LCD


The LCDs have a parallel interface, meaning that the microcontroller has to
manipulate several interface pins at once to control the display. The interface consists
of the following pins:
A register select (RS) pin that controls where in the LCD's memory you're writing
data to. You can select either the data register, which holds what goes on the screen,
or an instruction register, which is where the LCD's controller looks for instructions
on what to do next.
A Read/Write (R/W) pin that selects reading mode or writing mode.
An Enable pin that enables writing to the registers.
8 data pins (D0 -D7). The states of these pins (high or low) are the bits that you're
writing to a register when you write, or the values you're reading when you read.
There's also a display constrast pin (Vo), power supply pins (+5V and Gnd) and
LED Backlight (Bklt+ and BKlt-) pins that you can use to power the LCD, control
the display contrast, and turn on and off the LED backlight, respectively.
The process of controlling the display involves putting the data that form the
image of what you want to display into the data registers, then putting instructions in
the instruction register. The LiquidCrystal Library simplifies this for you so you don't
need to know the low-level instructions.
The Hitachi-compatible LCDs can be controlled in two modes: 4-bit or 8-bit.
The 4-bit mode requires seven I/O pins from the Arduino, while the 8-bit mode
requires 11 pins. For displaying text on the screen, you can do most everything in 4-
bit mode, so example shows how to control a 2x16 LCD in 4-bit mode.
Hardware Required
Arduino Board
LCD Screen (compatible with Hitachi HD44780 driver)
pin headers to solder to the LCD display pins
10k Potentiometer
breadboard
hook-up wire

Circuit
Before wiring the LCD screen to your Arduino we suggest to solder a pin header strip
to the 14 (or 16) pin count connector of the LCD screen, as you can see in the image
above.To wire your LCD screen to your Arduino, connect the following pins:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Additionally, wire a 10K pot to +5V and GND, with it's wiper (output) to LCD
screens VO pin (pin3).

image developed using Fritzing. For more circuit examples, see the Fritzing project page
Code
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with
0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}
Atividade 6:
Sensor de distncia independente do computador
Combine as Atividade 4 e 5 para ler o resultado do sensor ultrassnico de distncia
na tela do visor LCD apenas (desabilite o envio da informao para a porta serial).
Conecte ento uma bateria de 9 volts, atravs de uma chave, entrada de potncia
externa da placa Arduino. Com isso, mostre o funcionamento do sensor de distncias
de forma completamente desacoplada do computador.

Você também pode gostar