SlideShare a Scribd company logo
1 of 38
Download to read offline
ROBOTICA
GAZTEATECH 2016
SVET IVANTCHEV
SETUP
• Arduino: https://www.arduino.cc/en/Main/Software
• Driver CH340 (si es necesario: OSX, Win 7,8. OK en Linux, Win10)
• Soporte para ESP8266:
• Ir a Arduino (o File) -> Preferences
• En “Additional Boards Managers URLs” poner:
http://arduino.esp8266.com/package_esp8266com_index.json
• Ir a Tools -> Board -> Boards Manager …
• Buscar esp8266 e instalar:





























• Seleccionar la placa en:

Tools -> Board -> NodeMCU 1.0 (ESP-12E Module)
BLINK
int ledPin = D0; // pin LED
void setup() {
// nothing happens in setup
}
void loop() {
// fade in from min to max in increments of 5 points:
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
analogWrite(ledPin, fadeValue);
delay(30);
}
// fade out from max to min in increments of 5 points:
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
analogWrite(ledPin, fadeValue);
delay(30);
}
}
FADE
LDR
void setup() {
Serial.begin(9600);
}
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023)
// to a voltage (0 - 3.3V):
float voltage = sensorValue * (3.3 / 1023.0);
Serial.println(voltage);
}
LDR
SERVO
#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup()
{
myservo.attach(D8); // connect the servo to D8
}
void loop()
{
int pos;
for(pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=0; pos-=1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
SERVO
#define TRIGGER 12 // D6
#define ECHO 13 // D7 (with voltage divider!)
void setup() {
Serial.begin (9600);
pinMode(TRIGGER, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(BUILTIN_LED, OUTPUT);
pinMode(D0, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(TRIGGER, LOW); delayMicroseconds(2);
digitalWrite(TRIGGER, HIGH); delayMicroseconds(10);
digitalWrite(TRIGGER, LOW);
duration = pulseIn(ECHO, HIGH);
distance = (duration/2) / 29.1;
Serial.println(distance);
if (distance < 10) digitalWrite(D0, LOW);
else digitalWrite(D0, HIGH);
delay(300);
}
HC-SR04
NEOPIXEL
GND
+3.3V
D8
Dout DoutDin Din
pixel 0 pixel 1 pixel 2
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(3, D8, NEO_GRB + NEO_KHZ800);
void setup() {
pixels.begin();
pixels.show();
}
void loop() {
for(int i=0; i<3; i++) {
pixels.setPixelColor(i, pixels.Color(0, 150, 0));
pixels.show();
delay(300);
}
}
NEOPIXELS I
Nota: Instalar la librería NeoPixel si en necesario desde Sketch -> Include Library -> Manage Libraries …
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(3, D8, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
colorWipe(strip.Color(255, 0, 0), 20); // Red
colorWipe(strip.Color(0, 255, 0), 20); // Green
colorWipe(strip.Color(0, 0, 255), 20); // Blue
}
// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
for(uint16_t i=0; i<strip.numPixels(); i++) {
strip.setPixelColor(i, c);
strip.show();
delay(wait);
}
}
NEOPIXEL II
MQTT
MQTT BROKER
CLIENTE CLIENTE
CLIENTE
CLIENTE CLIENTE
CLIENTE
publish
publish
publish
subscribe
subscribe
“topic” -> “message”
MQTT UI
RED LOCAL ENTRE LOS ROBOTS
WIFI
Nombre de la red WiFi: Pi3-AP
Contraseña: raspberry
IP del broker MQTT: 172.24.1.1
Alternativamente puede considerar algún 

servicio público de MQTT como por ejemplo

el servidor de pruebas de HiveMQ: 

broker.hivemq.com
CLIENTE MQTT PARA CHROME
CLIENTE MQTT PARA ANDROID
CLIENTE MQTT PARA IOS
TOPICS Y REGLAS
r1/ldr 2.1
r2/ldr 1.4
r42/ldr 1.0
r13/ip Hello from …
r1/cmd/led1 on
r42/cmd/led2 off
r42/cmd/led1 on
r1/cmd/motL 800
r1/cmd/motR 800
r13/cmd/rgb 016:200:000
r42/cmd/rgbhex #0FAA00
De cada robot al MQTT:
Del MQTT a los robots:
Posibles suscripciones:
r1/+

+/ldr
r42/#
r13/cmd/+
+/ip
remote_001
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Pi3-AP";
const char* password = "raspberry";
const char* mqtt_server = "172.24.1.1";
char msg[50];
long ldr;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500); Serial.print(".");
}
Serial.println("WiFi connected. IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.publish("r1/ip", "Hello world from R1");
} else {
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) { reconnect(); }
client.loop();
long now = millis();
if (now - lastMsg > 500) {
lastMsg = now;
ldr = analogRead(A0);
snprintf (msg, 75, "%ld", ldr);
client.publish("r1/ldr", msg);
}
}
COMO PUBLICAR EN MQTT
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Pi3-AP";
const char* password = "raspberry";
const char* mqtt_server = "172.24.1.1";
long lastMsg = 0;
char msg[50];
long ldr;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
pinMode(D0, OUTPUT);
pinMode(D1, OUTPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
Serial.begin(9600);
}
void setup_wifi() {
delay(20);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500); Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected. IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String topic_str(topic);
String cmd;
String param;
for (int i = 0; i < length; i++) {
param += (char)payload[i];
}
Serial.print("Message arrived: ");
Serial.print(topic); Serial.print(" ");
Serial.println(param);
// "r1/cmd/abc" -> abc
cmd = topic_str.substring( topic_str.lastIndexOf('/')+1 );
if (cmd == "led1") {
if (param=="on") digitalWrite(D0, LOW);
else digitalWrite(D0, HIGH);
} else if (cmd == "led2") {
if (param=="on") digitalWrite(D1, HIGH);
else digitalWrite(D1, LOW);
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.publish("r1/ip", "Hello world from R1");
client.subscribe("r1/cmd/+");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
la función void loop() es igual que en el ejemplo anterior
PUBLISH Y SUBSCRIBE CON MQTT
HTTPS://PROCESSING.ORG
PROCESSING
void setup() {
size(400,400);
}
void draw() {
ellipse(mouseX, mouseY, 60, 60);
}
MQTT CON PROCESSING
import mqtt.*;
MQTTClient client;
int ldrvalue;
void setup() {
client = new MQTTClient(this);
client.connect("mqtt://172.24.1.1", "proc1");
client.subscribe("r1/ldr");
size(500,500);
}
void draw() {
clear();
ellipse(250, 250, ldrvalue/2, ldrvalue/2);
}
void messageReceived(String topic, byte[] payload) {
String spayload = new String(payload);
ldrvalue = int(spayload);
println("new message: " + topic + " - " + spayload);
}
mqtt_rec
PUBLICAR EN MQTT
import mqtt.*;
MQTTClient client;
void setup() {
client = new MQTTClient(this);
client.connect("mqtt://172.24.1.1", "pc42");
}
void draw() {}
void keyPressed() {
switch(key) {
case 'a':
client.publish("/r42/led1", "on");
break;
case 'z':
client.publish("/r42/led1", "off");
break;
}
}
mqtt_001
!!! VM-NC
cuando esta conectado
al ordenador y a la batería
VM+
-
motor A
motor B
CONEXIONES DE MOTORES DC
CONTROL DE MOTORES DC
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT);
pinMode(D3, OUTPUT);
pinMode(D4, OUTPUT);
digitalWrite(D3, HIGH); // Dirección Motor A
digitalWrite(D4, HIGH); // Dirección Motor B
analogWrite(D1, 800); // Velocidad Motor A
analogWrite(D2, 800); // Velocidad Motor A
En el setup
Control
CONTROL DE ENCHUFES 433MHZ
MQTT Y RC
CÓDIGOS
• Instalar la librería rc-switch de https://github.com/sui77/rc-switch/
• Cargar File -> Examples -> rc-switch -> ReceiveDemo_Advanced
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <RCSwitch.h>
const char* ssid = "Pi3-AP";
const char* password = "raspberry";
const char* mqtt_server = "172.24.1.1";
long lastMsg = 0;
char msg[50];
long ldr;
WiFiClient espClient;
PubSubClient client(espClient);
RCSwitch mySwitch = RCSwitch();
void setup() {
pinMode(D0, OUTPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
mySwitch.enableTransmit(16);
Serial.begin(9600);
}
void setup_wifi() {
delay(20);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500); Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected. IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String topic_str(topic);
String cmd;
String param;
for (int i = 0; i < length; i++) {
param += (char)payload[i];
}
Serial.print("Message arrived: ");
Serial.print(topic); Serial.print(" ");
Serial.println(param);
// "r1/cmd/abc" -> abc
cmd = topic_str.substring( topic_str.lastIndexOf('/')+1 );
if (cmd == "plug1") {
if (param=="on") mySwitch.send("010001000000000000010100");
else mySwitch.send("010001000000000000000000");
} else if (cmd == "plug2") {
if (param=="on") mySwitch.send("010001000100000000010100");
else mySwitch.send("010001000100000000000000");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("svet/office/+");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
la función void loop() es igual que en los ejemplos anteriores
CONTROL CON MQTT

More Related Content

What's hot

システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)Masashi Shibata
 
The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181Mahmoud Samir Fayed
 
Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)Thomas Fuchs
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 
Hypercritical C++ Code Review
Hypercritical C++ Code ReviewHypercritical C++ Code Review
Hypercritical C++ Code ReviewAndrey Karpov
 
Programação completa e perfeira
Programação completa e perfeiraProgramação completa e perfeira
Programação completa e perfeiraMagno Rodrigues
 
API Python Chess: Distribution of Chess Wins based on random moves
API Python Chess: Distribution of Chess Wins based on random movesAPI Python Chess: Distribution of Chess Wins based on random moves
API Python Chess: Distribution of Chess Wins based on random movesYao Yao
 
Reporte de electrónica digital con VHDL: practica 7 memorias
Reporte de electrónica digital con VHDL: practica 7 memorias Reporte de electrónica digital con VHDL: practica 7 memorias
Reporte de electrónica digital con VHDL: practica 7 memorias SANTIAGO PABLO ALBERTO
 
The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88Mahmoud Samir Fayed
 

What's hot (20)

Ee
EeEe
Ee
 
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
システムコールトレーサーの動作原理と実装 (Writing system call tracer for Linux/x86)
 
The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181The Ring programming language version 1.5.2 book - Part 74 of 181
The Ring programming language version 1.5.2 book - Part 74 of 181
 
YCAM Workshop Part 3
YCAM Workshop Part 3YCAM Workshop Part 3
YCAM Workshop Part 3
 
Ssaw08 0624
Ssaw08 0624Ssaw08 0624
Ssaw08 0624
 
Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)Rich and Snappy Apps (No Scaling Required)
Rich and Snappy Apps (No Scaling Required)
 
135
135135
135
 
Aa
AaAa
Aa
 
Chat code
Chat codeChat code
Chat code
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
Debugging TV Frame 0x09
Debugging TV Frame 0x09Debugging TV Frame 0x09
Debugging TV Frame 0x09
 
Hypercritical C++ Code Review
Hypercritical C++ Code ReviewHypercritical C++ Code Review
Hypercritical C++ Code Review
 
Programação completa e perfeira
Programação completa e perfeiraProgramação completa e perfeira
Programação completa e perfeira
 
project3
project3project3
project3
 
Der perfekte 12c trigger
Der perfekte 12c triggerDer perfekte 12c trigger
Der perfekte 12c trigger
 
API Python Chess: Distribution of Chess Wins based on random moves
API Python Chess: Distribution of Chess Wins based on random movesAPI Python Chess: Distribution of Chess Wins based on random moves
API Python Chess: Distribution of Chess Wins based on random moves
 
Reporte de electrónica digital con VHDL: practica 7 memorias
Reporte de electrónica digital con VHDL: practica 7 memorias Reporte de electrónica digital con VHDL: practica 7 memorias
Reporte de electrónica digital con VHDL: practica 7 memorias
 
The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88
 
3 1-1
3 1-13 1-1
3 1-1
 
Lambda expressions in C++
Lambda expressions in C++Lambda expressions in C++
Lambda expressions in C++
 

Similar to Gaztea Tech Robotica 2016

Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)Flor Ian
 
[4] 아두이노와 인터넷
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷Chiwon Song
 
codings related to avr micro controller
codings related to avr micro controllercodings related to avr micro controller
codings related to avr micro controllerSyed Ghufran Hassan
 
The IoT Academy IoT Training Arduino Part 3 programming
The IoT Academy IoT Training Arduino Part 3 programmingThe IoT Academy IoT Training Arduino Part 3 programming
The IoT Academy IoT Training Arduino Part 3 programmingThe IOT Academy
 
selected input/output - sensors and actuators
selected input/output - sensors and actuatorsselected input/output - sensors and actuators
selected input/output - sensors and actuatorsEueung Mulyana
 
robotics presentation for a club you run
robotics presentation for a club you runrobotics presentation for a club you run
robotics presentation for a club you runSunilAcharya37
 
Socket Programming Intro.pptx
Socket  Programming Intro.pptxSocket  Programming Intro.pptx
Socket Programming Intro.pptxssuserc4a497
 
Arduino coding class part ii
Arduino coding class part iiArduino coding class part ii
Arduino coding class part iiJonah Marrs
 
Microcontroladores: programas de CCS Compiler.docx
Microcontroladores: programas de CCS Compiler.docxMicrocontroladores: programas de CCS Compiler.docx
Microcontroladores: programas de CCS Compiler.docxSANTIAGO PABLO ALBERTO
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingDemetrio Siragusa
 
Linux Serial Driver
Linux Serial DriverLinux Serial Driver
Linux Serial Driver艾鍗科技
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to knowRoberto Agostino Vitillo
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfWhat will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfSIGMATAX1
 

Similar to Gaztea Tech Robotica 2016 (20)

Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
 
[4] 아두이노와 인터넷
[4] 아두이노와 인터넷[4] 아두이노와 인터넷
[4] 아두이노와 인터넷
 
codings related to avr micro controller
codings related to avr micro controllercodings related to avr micro controller
codings related to avr micro controller
 
The IoT Academy IoT Training Arduino Part 3 programming
The IoT Academy IoT Training Arduino Part 3 programmingThe IoT Academy IoT Training Arduino Part 3 programming
The IoT Academy IoT Training Arduino Part 3 programming
 
selected input/output - sensors and actuators
selected input/output - sensors and actuatorsselected input/output - sensors and actuators
selected input/output - sensors and actuators
 
robotics presentation for a club you run
robotics presentation for a club you runrobotics presentation for a club you run
robotics presentation for a club you run
 
PIC and LCD
PIC and LCDPIC and LCD
PIC and LCD
 
Arduino Programming
Arduino ProgrammingArduino Programming
Arduino Programming
 
Socket Programming Intro.pptx
Socket  Programming Intro.pptxSocket  Programming Intro.pptx
Socket Programming Intro.pptx
 
Introduction to Node MCU
Introduction to Node MCUIntroduction to Node MCU
Introduction to Node MCU
 
FINISHED_CODE
FINISHED_CODEFINISHED_CODE
FINISHED_CODE
 
Arp
ArpArp
Arp
 
Arduino coding class part ii
Arduino coding class part iiArduino coding class part ii
Arduino coding class part ii
 
Microcontroladores: programas de CCS Compiler.docx
Microcontroladores: programas de CCS Compiler.docxMicrocontroladores: programas de CCS Compiler.docx
Microcontroladores: programas de CCS Compiler.docx
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
 
Solution doc
Solution docSolution doc
Solution doc
 
Linux Serial Driver
Linux Serial DriverLinux Serial Driver
Linux Serial Driver
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to know
 
What will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdfWhat will be quantization step size in numbers and in voltage for th.pdf
What will be quantization step size in numbers and in voltage for th.pdf
 
Php arduino
Php arduinoPhp arduino
Php arduino
 

More from Svet Ivantchev

Machne Learning and Human Learning (2013).
Machne Learning and Human Learning (2013).Machne Learning and Human Learning (2013).
Machne Learning and Human Learning (2013).Svet Ivantchev
 
Big Data: 
Some Questions in its Use in Applied Economics (2017)
Big Data: 
Some Questions in its Use in Applied Economics (2017)Big Data: 
Some Questions in its Use in Applied Economics (2017)
Big Data: 
Some Questions in its Use in Applied Economics (2017)Svet Ivantchev
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 
Gaztea Tech 2015: 4. GT Drawbot Control
Gaztea Tech 2015: 4. GT Drawbot ControlGaztea Tech 2015: 4. GT Drawbot Control
Gaztea Tech 2015: 4. GT Drawbot ControlSvet Ivantchev
 
Gaztea Tech 2015: 3. Processing y Firmata
Gaztea Tech 2015: 3. Processing y FirmataGaztea Tech 2015: 3. Processing y Firmata
Gaztea Tech 2015: 3. Processing y FirmataSvet Ivantchev
 
Gaztea Tech 2015: 2. El GT DrawBot
Gaztea Tech 2015: 2. El GT DrawBotGaztea Tech 2015: 2. El GT DrawBot
Gaztea Tech 2015: 2. El GT DrawBotSvet Ivantchev
 
Gaztea Tech 2015: 1. Introducción al Arduino
Gaztea Tech 2015: 1. Introducción al ArduinoGaztea Tech 2015: 1. Introducción al Arduino
Gaztea Tech 2015: 1. Introducción al ArduinoSvet Ivantchev
 
Learning Analytics and Online Learning: New Oportunities?
Learning Analytics and Online Learning: New Oportunities?Learning Analytics and Online Learning: New Oportunities?
Learning Analytics and Online Learning: New Oportunities?Svet Ivantchev
 
How Machine Learning and Big Data can Help Us with the Human Learning
How Machine Learning and Big Data can Help Us with the Human LearningHow Machine Learning and Big Data can Help Us with the Human Learning
How Machine Learning and Big Data can Help Us with the Human LearningSvet Ivantchev
 
Libros electrónicos IV: ePub 2
Libros electrónicos IV: ePub 2Libros electrónicos IV: ePub 2
Libros electrónicos IV: ePub 2Svet Ivantchev
 
Libros electrónicos III
Libros electrónicos IIILibros electrónicos III
Libros electrónicos IIISvet Ivantchev
 
Libros electrónicos II - ePub
Libros electrónicos II - ePubLibros electrónicos II - ePub
Libros electrónicos II - ePubSvet Ivantchev
 
Libros electrónicos I
Libros electrónicos ILibros electrónicos I
Libros electrónicos ISvet Ivantchev
 
Cloud Computing: Just Do It
Cloud Computing: Just Do ItCloud Computing: Just Do It
Cloud Computing: Just Do ItSvet Ivantchev
 
Cloud Computing: What it is, DOs and DON'Ts
Cloud Computing: What it is, DOs and DON'TsCloud Computing: What it is, DOs and DON'Ts
Cloud Computing: What it is, DOs and DON'TsSvet Ivantchev
 
Los mitos de la innovación
Los mitos de la innovaciónLos mitos de la innovación
Los mitos de la innovaciónSvet Ivantchev
 

More from Svet Ivantchev (20)

Machne Learning and Human Learning (2013).
Machne Learning and Human Learning (2013).Machne Learning and Human Learning (2013).
Machne Learning and Human Learning (2013).
 
Big Data: 
Some Questions in its Use in Applied Economics (2017)
Big Data: 
Some Questions in its Use in Applied Economics (2017)Big Data: 
Some Questions in its Use in Applied Economics (2017)
Big Data: 
Some Questions in its Use in Applied Economics (2017)
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Gaztea Tech 2015: 4. GT Drawbot Control
Gaztea Tech 2015: 4. GT Drawbot ControlGaztea Tech 2015: 4. GT Drawbot Control
Gaztea Tech 2015: 4. GT Drawbot Control
 
Gaztea Tech 2015: 3. Processing y Firmata
Gaztea Tech 2015: 3. Processing y FirmataGaztea Tech 2015: 3. Processing y Firmata
Gaztea Tech 2015: 3. Processing y Firmata
 
Gaztea Tech 2015: 2. El GT DrawBot
Gaztea Tech 2015: 2. El GT DrawBotGaztea Tech 2015: 2. El GT DrawBot
Gaztea Tech 2015: 2. El GT DrawBot
 
Gaztea Tech 2015: 1. Introducción al Arduino
Gaztea Tech 2015: 1. Introducción al ArduinoGaztea Tech 2015: 1. Introducción al Arduino
Gaztea Tech 2015: 1. Introducción al Arduino
 
Learning Analytics and Online Learning: New Oportunities?
Learning Analytics and Online Learning: New Oportunities?Learning Analytics and Online Learning: New Oportunities?
Learning Analytics and Online Learning: New Oportunities?
 
How Machine Learning and Big Data can Help Us with the Human Learning
How Machine Learning and Big Data can Help Us with the Human LearningHow Machine Learning and Big Data can Help Us with the Human Learning
How Machine Learning and Big Data can Help Us with the Human Learning
 
Vienen los Drones!
Vienen los Drones!Vienen los Drones!
Vienen los Drones!
 
Data Science
Data ScienceData Science
Data Science
 
Libros electrónicos IV: ePub 2
Libros electrónicos IV: ePub 2Libros electrónicos IV: ePub 2
Libros electrónicos IV: ePub 2
 
Libros electrónicos III
Libros electrónicos IIILibros electrónicos III
Libros electrónicos III
 
Libros electrónicos II - ePub
Libros electrónicos II - ePubLibros electrónicos II - ePub
Libros electrónicos II - ePub
 
Libros electrónicos I
Libros electrónicos ILibros electrónicos I
Libros electrónicos I
 
Cloud Computing: Just Do It
Cloud Computing: Just Do ItCloud Computing: Just Do It
Cloud Computing: Just Do It
 
Cloud Computing: What it is, DOs and DON'Ts
Cloud Computing: What it is, DOs and DON'TsCloud Computing: What it is, DOs and DON'Ts
Cloud Computing: What it is, DOs and DON'Ts
 
BigData
BigDataBigData
BigData
 
Los mitos de la innovación
Los mitos de la innovaciónLos mitos de la innovación
Los mitos de la innovación
 
eFaber en 5 minutos
eFaber en 5 minutoseFaber en 5 minutos
eFaber en 5 minutos
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Gaztea Tech Robotica 2016

  • 2. SETUP • Arduino: https://www.arduino.cc/en/Main/Software • Driver CH340 (si es necesario: OSX, Win 7,8. OK en Linux, Win10) • Soporte para ESP8266: • Ir a Arduino (o File) -> Preferences • En “Additional Boards Managers URLs” poner: http://arduino.esp8266.com/package_esp8266com_index.json
  • 3.
  • 4. • Ir a Tools -> Board -> Boards Manager …
  • 5. • Buscar esp8266 e instalar:
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  • 6. • Seleccionar la placa en:
 Tools -> Board -> NodeMCU 1.0 (ESP-12E Module)
  • 8.
  • 9.
  • 10.
  • 11. int ledPin = D0; // pin LED void setup() { // nothing happens in setup } void loop() { // fade in from min to max in increments of 5 points: for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) { analogWrite(ledPin, fadeValue); delay(30); } // fade out from max to min in increments of 5 points: for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) { analogWrite(ledPin, fadeValue); delay(30); } } FADE
  • 12. LDR
  • 13. void setup() { Serial.begin(9600); } void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 - 1023) // to a voltage (0 - 3.3V): float voltage = sensorValue * (3.3 / 1023.0); Serial.println(voltage); } LDR
  • 14. SERVO
  • 15. #include <Servo.h> Servo myservo; // create servo object to control a servo void setup() { myservo.attach(D8); // connect the servo to D8 } void loop() { int pos; for(pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos>=0; pos-=1) { // goes from 180 degrees to 0 degrees myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } } SERVO
  • 16. #define TRIGGER 12 // D6 #define ECHO 13 // D7 (with voltage divider!) void setup() { Serial.begin (9600); pinMode(TRIGGER, OUTPUT); pinMode(ECHO, INPUT); pinMode(BUILTIN_LED, OUTPUT); pinMode(D0, OUTPUT); } void loop() { long duration, distance; digitalWrite(TRIGGER, LOW); delayMicroseconds(2); digitalWrite(TRIGGER, HIGH); delayMicroseconds(10); digitalWrite(TRIGGER, LOW); duration = pulseIn(ECHO, HIGH); distance = (duration/2) / 29.1; Serial.println(distance); if (distance < 10) digitalWrite(D0, LOW); else digitalWrite(D0, HIGH); delay(300); } HC-SR04
  • 19. #include <Adafruit_NeoPixel.h> Adafruit_NeoPixel pixels = Adafruit_NeoPixel(3, D8, NEO_GRB + NEO_KHZ800); void setup() { pixels.begin(); pixels.show(); } void loop() { for(int i=0; i<3; i++) { pixels.setPixelColor(i, pixels.Color(0, 150, 0)); pixels.show(); delay(300); } } NEOPIXELS I Nota: Instalar la librería NeoPixel si en necesario desde Sketch -> Include Library -> Manage Libraries …
  • 20. #include <Adafruit_NeoPixel.h> Adafruit_NeoPixel strip = Adafruit_NeoPixel(3, D8, NEO_GRB + NEO_KHZ800); void setup() { strip.begin(); strip.show(); // Initialize all pixels to 'off' } void loop() { colorWipe(strip.Color(255, 0, 0), 20); // Red colorWipe(strip.Color(0, 255, 0), 20); // Green colorWipe(strip.Color(0, 0, 255), 20); // Blue } // Fill the dots one after the other with a color void colorWipe(uint32_t c, uint8_t wait) { for(uint16_t i=0; i<strip.numPixels(); i++) { strip.setPixelColor(i, c); strip.show(); delay(wait); } } NEOPIXEL II
  • 21. MQTT MQTT BROKER CLIENTE CLIENTE CLIENTE CLIENTE CLIENTE CLIENTE publish publish publish subscribe subscribe “topic” -> “message”
  • 23. RED LOCAL ENTRE LOS ROBOTS WIFI Nombre de la red WiFi: Pi3-AP Contraseña: raspberry IP del broker MQTT: 172.24.1.1 Alternativamente puede considerar algún 
 servicio público de MQTT como por ejemplo
 el servidor de pruebas de HiveMQ: 
 broker.hivemq.com
  • 25. CLIENTE MQTT PARA ANDROID
  • 27. TOPICS Y REGLAS r1/ldr 2.1 r2/ldr 1.4 r42/ldr 1.0 r13/ip Hello from … r1/cmd/led1 on r42/cmd/led2 off r42/cmd/led1 on r1/cmd/motL 800 r1/cmd/motR 800 r13/cmd/rgb 016:200:000 r42/cmd/rgbhex #0FAA00 De cada robot al MQTT: Del MQTT a los robots: Posibles suscripciones: r1/+
 +/ldr r42/# r13/cmd/+ +/ip
  • 28. remote_001 #include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "Pi3-AP"; const char* password = "raspberry"; const char* mqtt_server = "172.24.1.1"; char msg[50]; long ldr; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; void setup() { Serial.begin(9600); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("WiFi connected. IP address: "); Serial.println(WiFi.localIP()); client.setServer(mqtt_server, 1883); } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect("ESP8266Client")) { Serial.println("connected"); client.publish("r1/ip", "Hello world from R1"); } else { Serial.println(" try again in 5 seconds"); delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); if (now - lastMsg > 500) { lastMsg = now; ldr = analogRead(A0); snprintf (msg, 75, "%ld", ldr); client.publish("r1/ldr", msg); } } COMO PUBLICAR EN MQTT
  • 29. #include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "Pi3-AP"; const char* password = "raspberry"; const char* mqtt_server = "172.24.1.1"; long lastMsg = 0; char msg[50]; long ldr; WiFiClient espClient; PubSubClient client(espClient); void setup() { pinMode(D0, OUTPUT); pinMode(D1, OUTPUT); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); Serial.begin(9600); } void setup_wifi() { delay(20); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected. IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte* payload, unsigned int length) { String topic_str(topic); String cmd; String param; for (int i = 0; i < length; i++) { param += (char)payload[i]; } Serial.print("Message arrived: "); Serial.print(topic); Serial.print(" "); Serial.println(param); // "r1/cmd/abc" -> abc cmd = topic_str.substring( topic_str.lastIndexOf('/')+1 ); if (cmd == "led1") { if (param=="on") digitalWrite(D0, LOW); else digitalWrite(D0, HIGH); } else if (cmd == "led2") { if (param=="on") digitalWrite(D1, HIGH); else digitalWrite(D1, LOW); } } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect("ESP8266Client")) { Serial.println("connected"); client.publish("r1/ip", "Hello world from R1"); client.subscribe("r1/cmd/+"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } la función void loop() es igual que en el ejemplo anterior PUBLISH Y SUBSCRIBE CON MQTT
  • 31. void setup() { size(400,400); } void draw() { ellipse(mouseX, mouseY, 60, 60); }
  • 32. MQTT CON PROCESSING import mqtt.*; MQTTClient client; int ldrvalue; void setup() { client = new MQTTClient(this); client.connect("mqtt://172.24.1.1", "proc1"); client.subscribe("r1/ldr"); size(500,500); } void draw() { clear(); ellipse(250, 250, ldrvalue/2, ldrvalue/2); } void messageReceived(String topic, byte[] payload) { String spayload = new String(payload); ldrvalue = int(spayload); println("new message: " + topic + " - " + spayload); } mqtt_rec
  • 33. PUBLICAR EN MQTT import mqtt.*; MQTTClient client; void setup() { client = new MQTTClient(this); client.connect("mqtt://172.24.1.1", "pc42"); } void draw() {} void keyPressed() { switch(key) { case 'a': client.publish("/r42/led1", "on"); break; case 'z': client.publish("/r42/led1", "off"); break; } } mqtt_001
  • 34. !!! VM-NC cuando esta conectado al ordenador y a la batería VM+ - motor A motor B CONEXIONES DE MOTORES DC
  • 35. CONTROL DE MOTORES DC pinMode(D1, OUTPUT); pinMode(D2, OUTPUT); pinMode(D3, OUTPUT); pinMode(D4, OUTPUT); digitalWrite(D3, HIGH); // Dirección Motor A digitalWrite(D4, HIGH); // Dirección Motor B analogWrite(D1, 800); // Velocidad Motor A analogWrite(D2, 800); // Velocidad Motor A En el setup Control
  • 36. CONTROL DE ENCHUFES 433MHZ MQTT Y RC
  • 37. CÓDIGOS • Instalar la librería rc-switch de https://github.com/sui77/rc-switch/ • Cargar File -> Examples -> rc-switch -> ReceiveDemo_Advanced
  • 38. #include <ESP8266WiFi.h> #include <PubSubClient.h> #include <RCSwitch.h> const char* ssid = "Pi3-AP"; const char* password = "raspberry"; const char* mqtt_server = "172.24.1.1"; long lastMsg = 0; char msg[50]; long ldr; WiFiClient espClient; PubSubClient client(espClient); RCSwitch mySwitch = RCSwitch(); void setup() { pinMode(D0, OUTPUT); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); mySwitch.enableTransmit(16); Serial.begin(9600); } void setup_wifi() { delay(20); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected. IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte* payload, unsigned int length) { String topic_str(topic); String cmd; String param; for (int i = 0; i < length; i++) { param += (char)payload[i]; } Serial.print("Message arrived: "); Serial.print(topic); Serial.print(" "); Serial.println(param); // "r1/cmd/abc" -> abc cmd = topic_str.substring( topic_str.lastIndexOf('/')+1 ); if (cmd == "plug1") { if (param=="on") mySwitch.send("010001000000000000010100"); else mySwitch.send("010001000000000000000000"); } else if (cmd == "plug2") { if (param=="on") mySwitch.send("010001000100000000010100"); else mySwitch.send("010001000100000000000000"); } } void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect("ESP8266Client")) { Serial.println("connected"); client.subscribe("svet/office/+"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } la función void loop() es igual que en los ejemplos anteriores CONTROL CON MQTT