Oficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part II

Preview:

DESCRIPTION

Oficina sobre Arduino - Parte II

Citation preview

1

OutlineOutline

1. Introdução

1.Computação Física

2.Computação Pervasiva

3.Microcontroladores

2. Plataforma Arduino

1.Conceitos Básicos

2.Programação

3.Projetos

2

ArduinoArduino

3

ArduinoArduino

Placa + Microcontrolador + USB + Sockets

Pode ser conectado a uma grande variedade de dispositivos:

Sensores: Luz, temperatura, presença, etc.

Displays: LCD, touchscreen

Motores e servos

GPS

Comunicação sem fio: 802.15.4, Zigbee, Bluetooth

Ethernet

Alimentação: Bateria de 9V ou por meio da USB

4

ArduinoArduino

Da página oficial (www.arduino.org):Arduino is an open-source electronics prototyping platform based on flexible, easy-to-use hardware and software. It’s intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments.

Arduino can sense the environment by receiving input from a variety of sensors and can affect its surroundings by controlling lights, motors, and other actuators. The microcontroller on the board is programmed using the Arduino programming language (based on Wiring) and the Arduino development environment (based on Processing). Arduino projects can be stand-alone or they can communicate with software on running on a computer (e.g. Flash, Processing,MaxMSP). ”

5

ArduinoArduino

Criado na Itália (em 2005) pelo Mássimo Banzi, no Interaction Design Ivrea

Baixo custo de produção e alta aplicabilidade

Computação física e redes de sensores

Permite que os programas (ou sketches) sejam escritos em uma linguagem de alto nível chamada Processing

Processing é um ambiente e linguagem de programação para criar imagens, animação e interação

http://processing.org/

6

Versões do ArduinoVersões do Arduino

Arduino Uno

7

Versões do ArduinoVersões do Arduino

Arduino Nano

8

Versões do ArduinoVersões do Arduino

Arduino Mega

9

Versões do ArduinoVersões do Arduino

Arduino Lilypad

10

ArquiteturaArquitetura

Fonte: Minicurso Arduino – Equipe de Robótica UFES 2012

11

Características do Arduino UnoCaracterísticas do Arduino Uno

Microcontrolador ATmega328P

Tensão Operacional 5 V

Tensão de Alimentação 7-12 V

Pinos de I/O digitais 14 (dos quais 6 podem ser saídas PWM)

Pinos de entrada analógica 6

Corrente contínua por pino de I/O 40 mA

Corrente contínua para o pino de 3.3 V 50 mA

Memória Flash 2KB

EEPROM 1K

Frequência de clock 16 MHz

12

Arduino Diecimila/UnoArduino Diecimila/Uno

13

14

Ok... but first, let's go Ok... but first, let's go shoppingshopping

15

Kit Para InicianteKit Para Iniciante

16

Outros ComponentesOutros Componentes

17

SensoresSensores

18

““Hello World”Hello World”

19

Ambiente de DesenvolvimentoAmbiente de Desenvolvimento

O ambiente de desenvolvimento pode ser baixado em:● http://arduino.cc/en/Main/Software● A última versão é a 1.0.5

O arquivo compactado deve ser extraído em qualquer diretório do sistema

Será criado um diretório arduino-XXXX, onde XXXX é a versão baixado (por exemplo: arduino-0022).

20

Ambiente de DesenvolvimentoAmbiente de Desenvolvimento

Executar o arquivo 'arduino'

21

Ambiente de DesenvolvimentoAmbiente de Desenvolvimento

22

Configurando o AmbienteConfigurando o Ambiente

Linux

Conecte o Arduino ao seu computador, por meio da porta USB e espere alguns segundos até que o sistema recoheça o dispositivo

Para confirmar se o dispositivo foi reconhecido, abra um terminal e execute o comando abaixo:

$ dmesg

Procure, nas últimas linhas, por uma linha mais ou menos parecida com a de baixo:

[56999.967291] usb 5-2: FTDI USB Serial Device converter now attached to ttyUSB0

Essa mensagem indica que o kernel reconheceu um novo dispositivo conectado na porta /dev/ttyUSB0.

O sistema nem sempre reconhece como /dev/ttyUSB0, mas em geral é /dev/tty<alguma_coisa>

23

Configurando o AmbienteConfigurando o Ambiente

Windows:

http://arduino.cc/en/Guide/Windows

Mac OSX:

http://arduino.cc/en/Guide/MacOSX

24

Configurando o AmbienteConfigurando o Ambiente

Configurar o ambiente de desenvolvimento para utilizar a porta detectado pelo sistema:

“Tools” → “Serial Port”

Configurar a placa utilizada:

“Tools” → “Board” e escolher a opção “Arduino Uno”

25

““Hello World”Hello World”

O primeiro projeto será o equivalente “Hello World” para dispositivos embarcados

Como não há um terminal, iremos fazer piscar (blink) um LED.

A placa do Arduino vem com um LED embutido, conectado ao pin digital 13

Esta conexão faz com que o pin 13 seja sempre de saída, mas como o LED usa pouca corrente, ainda é possível conectar outras coisas na saída

26

““Hello World”Hello World”

Código:

int ledPin = 13;

void setup() { // initialize the digital pin as an output. // Pin 13 has an LED connected on most Arduino boards: pinMode(ledPin, OUTPUT); }

void loop() { digitalWrite(ledPin, HIGH); // set the LED on delay(1000); // wait for a second digitalWrite(ledPin, LOW); // set the LED off delay(1000); // wait for a second}

27

““Hello World”Hello World”

Para fazer o upload para a placa, deve-se clicar no botão específico:

28

Explicando o códigoExplicando o código

Um sketch Arduino possui, no mínimo duas funções:

setup():Executada apenas uma vez, durante a inicialização

loop():Função principal

29

Explicando o códigoExplicando o código

setup()

pinMode(ledPin, OUTPUT);

A função pinMode define o modo de operação do pino. Neste caso, definimos que o pino 13 (ledPin) será de saída

30

Explicando o códigoExplicando o código

loop()

digitalWrite(ledPin, HIGH); Permite ligar (5V) ou desligar (0V) um pino digital

Neste código especifico, estamos ligando (constante HIGH) o pino 13 (ledPin)

Por meio da constante LOW, podemos desligar o pino

delay(200)A função delay() faz com que o processado fique X milisegundos em espera

31

Projeto 001:Projeto 001:LED FlasherLED Flasher

32

LED FlasherLED Flasher

Componentes:

33

LED FlasherLED Flasher

Conexão:

34

LED FlasherLED Flasher

35

LED FlasherLED Flasher

Código:int ledPin = 10;

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

void loop() { digitalWrite(ledPin, HIGH); delay(1000); digitalWrite(ledPin, LOW); delay(1000); }

36

Projeto 002:Projeto 002:Temperature SensorTemperature Sensor

37

LM35/LM36 – TPM35/TPM36LM35/LM36 – TPM35/TPM36

Sensor de temperatura analógico

Estado-sólido (não usa mércurio)

A medida que a temperatura muda, a tensão que atravessa um diodo cresce a uma taxa conhecida

Não precisa ser calibrado

Barato e fácil de usar

38

LM35/LM36 – TPM35/TPM36LM35/LM36 – TPM35/TPM36

a) LM35

b) LM36

Fonte: http://www.ladyada.net/learn/sensors/tmp36.html

39

Para converter a tensão em temperatura:

LM35:

Temp in ºC: (V in mV) / 10

LM36:– Temp in ºC: [(V in mV - 500)] / 10

LM35/LM36 – TPM35/TPM36LM35/LM36 – TPM35/TPM36

40

Lendo a TemperaturaLendo a Temperatura

41

Devemos conectar o pino do saída do sensor diretamente em uma porta analógica do Arduino

A tensão de saída do sensor será de 0 a 1.75 (aproximadamente)

O tensão lida pelo Arduino é convertido em um valor binário pelo Conversor Analógico Digital

Assim, para descobrirmos a temperatura, devemos fazer uma conversão:

Lendo a TemperaturaLendo a Temperatura

42

Voltage at pin in milliVolts = (reading from ADC) * (5000/1024)

This formula converts the number 0-1023 from the ADC into 0-5000mV (= 5V)

Voltage at pin in milliVolts = (reading from ADC) * (3300/1024)

This formula converts the number 0-1023 from the ADC into 0-3300mV (= 3.3V)

Para converter a tensão em temperatura, basta utilizarmos a fórmulas definidas anteriormente...

Lendo a TemperaturaLendo a Temperatura

43

int temperaturaPin = 0;int ledPin = 12;float vIn = 5.0; //Tensao de entrada

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

void loop(){ digitalWrite(ledPin, HIGH); //ler o valor do sensor float leitura = analogRead(temperaturaPin); float voltagem = (leitura * vIn) / 1023.0; //Imprimir a tensão Serial.print(voltagem); Serial.println(" volts");

//Converter tensao para temperatura float temperaturaC = voltagem * 100.0; delay(1000); Serial.print(temperaturaC); Serial.println(" graus em C"); Serial.println(" "); digitalWrite(ledPin, LOW); delay(1000); }

Lendo a TemperaturaLendo a Temperatura

44

Problems you may encounter Problems you may encounter with multiple sensors...with multiple sensors...

If, when adding more sensors, you find that the temperature is inconsistant, this indicates that

the sensors are interfering with each other when switching the analog reading circuit from one pin

to the other. You can fix this by doing two delayed readings and tossing out the first one

45

Projeto 003:Projeto 003:Sensing LightSensing Light

46

Sensing LightSensing Light

Uma forma bastante prática de medir a intensidade da luz é usando um LDR

LDR = Light-Dependent Resistor

Podem ser chamados de Photoresistores

Quanto maior a intensidade da luz, menor a resistência

20MΩ = Ambiente “muito escuro”

20KΩ = Ambiente “muito iluminado”

47

Sensing LightSensing Light

48

LDR as a Voltage DividerLDR as a Voltage Divider

A voltage divider is just two resistors in series connected between a voltage supply and ground. If

R1 is connected to the voltage supply and R2 is connected to ground then the voltage at the junction

between the two resistors is:

V =V cc∗R2

R1+R2

49

LDR as a Voltage DividerLDR as a Voltage Divider

A voltage divider is just two resistors in series connected between a voltage supply and ground. If

R1 is connected to the voltage supply and R2 is connected to ground then the voltage at the junction

between the two resistors is:

V =V cc∗R2

R1+R2

50

LDR as a Voltage DividercLDR as a Voltage Dividerc

If R1 is the photoresistor, the voltage will increase with

increasing light intensity. If R2 is the photoresistor, the voltage

will decrease with increasing light intensity.

V =V cc∗R2

R1+R2

51

int ledPin = 13;int sensorPin = 1;int period = 400;

int limit = 1000;

int acesso = 0;

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

void loop(){ int rawValue = analogRead(sensorPin); if (rawValue < limit){ digitalWrite(ledPin, LOW); if (acesso != 1){ acesso = 1; Serial.println("ligado"); } }

else{ digitalWrite(ledPin, HIGH); Serial.println(rawValue); if (acesso != 0){ acesso = 0; Serial.println("apagado"); } }

delay(period);}

Sensing LightSensing Light

52

Projeto 004:Projeto 004:Enviando Informações Enviando Informações

para o Arduino via Serialpara o Arduino via Serial

53

Enviando Informações Via SerialEnviando Informações Via Serial

int ledPin = 13;int tempoEspera = 500;

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

void loop(){ char ch; if (Serial.available()){ ch = Serial.read(); if (ch == '0'){ digitalWrite(ledPin, LOW); }else{ digitalWrite(ledPin, HIGH); } } delay(tempoEspera);}

54

Enviando Informações Via SerialEnviando Informações Via Serial

55

Projeto 005:Projeto 005:PySerialPySerial

56

apt-get install python-serial -y

57

PySerialPySerialfrom serial import Serial

porta = '/dev/ttyACM1'

ser=Serial(porta, 19200, timeout=10)ser.readline() #descartar a primeira leiturainfo=ser.readline()ser.close()print info

58

Função Utilitária: Função Utilitária: Enviar E-MailEnviar E-Mail

import sysimport smtplibfrom email.MIMEText import MIMEText

to = 'marvin.lemos@tce.pi.gov.br'user = 'marvinlemos@gmail.com'password = 'senhaaqui'

def mandar_email(mensagem):msg = MIMEText(mensagem)

msg['Subject'] = 'Teste'msg['From'] = "Marvin Lemos"msg['Reply-to'] = "Marvin Lemos "msg['To'] = to

smtpserver = smtplib.SMTP("smtp.gmail.com",587)smtpserver.ehlo()smtpserver.starttls()smtpserver.ehlosmtpserver.login(user, password)

try:smtpserver.sendmail(user,to,

msg.as_string())print "e-mail encaminhado"

except:print "falha ao transmitir e-mail"print sys.exc_info()smtpserver.close()

59

Alguns Projetos ReaisAlguns Projetos Reais

60

● Parceria Opala (Uespi) / Empraba Meio/Norte● Estudar o problema da “enxameação” das

abelhas

Monitoramento de AbelhasMonitoramento de Abelhas

61

Monitoramento de AbelhasMonitoramento de Abelhas

62

Monitoramento de AbelhasMonitoramento de Abelhas

63

Monitoramento de AbelhasMonitoramento de Abelhas

64

Monitoramento AmbientalMonitoramento Ambiental

65

Automação ResidencialAutomação Residencial

66

● Desenvolvido pelo Labiras (http://labiras.cc)● Visa substituir bengala para cegos

Luva UltrassônicaLuva Ultrassônica

Fonte: http://comradio.com.br/cidadania/?p=701

67

ReferênciasReferênciasArduino Starter Kit Manual: A Complete Beginners Guide To The Arduino

http://www.ladyada.net/learn/arduino/

http://blog.justen.eng.br/

Recommended