Controle de Servo Web com Arduino UNO e Shield PHPoC WiFi
Componentes e Materiais
| Arduino UNO | × | 1 |
| PHPoC WiFi Shield para Arduino | × | 1 |
| Servo Motor Seeed | × | 1 |
| Fios Jumpers | × | 1 |
Sobre este Projeto
Introdução
Se você é iniciante, recomendo ler sobre Arduino - Servo Motor e Arduino - WiFi.
Para conectar o Arduino à internet, precisamos usar algum tipo de shield de internet, como Ethernet shield, WiFi shield, PHPoC shield ou PHPoC WiFi shield.
A característica marcante do PHPoC shield é que ele não apenas fornece conexão à Internet como os shields Ethernet e WiFi, mas também fornece um servidor web que permite controlar e monitorar o Arduino a partir de um navegador web. Ele também suporta WebSocket, portanto, podemos controlar e monitorar o Arduino em tempo real sem recarregar a página.
O PHPoC Shield tem alguns aplicativos web integrados. Consulte este link para mais detalhes.
Neste projeto, alterei a UI (Interface do Usuário) do aplicativo web Web Remote Control/Slide e escrevi o código Arduino para rotacionar o ângulo do servo motor de acordo com o ângulo recebido do navegador web.
Fiação
- Encaixe o shield PHPoC no Arduino
- Conecte os pinos GND, VCC e sinal do servo motor ao GND, 5V e pino 9 do Arduino, respectivamente.
Fluxo de Dados
Navegador web → PHPoC Shield → Arduino
O aplicativo web calculará o ângulo baseado em evento de toque ou mouse, enviará para o PHPoC shield via websocket. Ao receber estes dados, o PHPoC shield os passa para o Arduino. O Arduino rotaciona o servo motor de acordo com o ângulo.
O que Precisamos Fazer
- Configurar informações WiFi para o shield PHPoC (SSID e senha)
- Carregar nova UI para o shield PHPoC
- Escrever código Arduino
Configurando Informações WiFi para o Shield PHPoC
Veja esta instrução: https://www.phpoc.com/support/manual/p4s-347_user_manual/contents.php?id=network_first_setup
Carregar Nova UI para o Shield PHPoC
- Baixe o código-fonte PHPoC remote_rotate.php (na seção de código)
- Carregue-o no shield PHPoC usando o PHPoC debugger de acordo com esta instrução
Escrever Código Arduino
- Instale a biblioteca para Arduino na Arduino IDE (veja a instrução) e reinicie a Arduino IDE.
- Na Arduino IDE, vá em Arquivo → Exemplos → Phpoc → WebRemoteSlide e Arquivo → Exemplos → Servo → sweep.
- Combine os dois exemplos em um, temos o código para controlar o servo motor via página web (veja o código-fonte na seção de código).
Testando
- Clique no botão serial na Arduino IDE para ver o endereço IP
- Abra o navegador web, digite https://substitua_endereço_ip/remote_rotate.php
- Clique no botão conectar e teste
O Melhor Kit Inicial Arduino para Iniciantes
Se você está procurando um kit Arduino, veja The Best Arduino Kit for Beginners
Referências de Funções
- Arduino - Biblioteca Servo
- Servo.attach()
- Servo.write()
- Servo.writeMicroseconds()
- Servo.read()
- Servo.attached()
- Servo.detach()
- Serial.begin()
- Serial.println()
- delay()
- for loop
- while loop
- if else
- loop()
- setup()
- String.toInt()
Código
remote_rotate.php (PHP)
<!DOCTYPE html> <html> <head> <title>PHPoC Shield - Web Remote Control for Arduino</title> <meta name="viewport" content="width=device-width, initial-scale=0.7, maximum-scale=0.7"> <style> body { text-align: center; font-size: 15pt; } h1 { font-weight: bold; font-size: 25pt; } h2 { font-weight: bold; font-size: 15pt; } button { font-weight: bold; font-size: 15pt; } </style> <script> var canvas_width = 400, canvas_height = 400; var plate_radius = 160; var click_state = 0; var last_plate_angle = 0 var plate_angle = 0, last_angle = 0; var ws; function init() { var canvas = document.getElementById("remote"); canvas.addEventListener("touchstart", mouse_down); canvas.addEventListener("touchend", mouse_up); canvas.addEventListener("touchmove", mouse_move); canvas.addEventListener("mousedown", mouse_down); canvas.addEventListener("mouseup", mouse_up); canvas.addEventListener("mousemove", mouse_move); var ctx = canvas.getContext("2d"); ctx.translate(canvas_width / 2, canvas_height / 2); rotate_plate(0); } function connect_onclick() { if(ws == null) { var ws_host_addr = "<?echo _SERVER("HTTP_HOST")?>"; var debug = document.getElementById("debug"); if((navigator.platform.indexOf("Win") != -1) && (ws_host_addr.charAt(0) == "[")) { ws_host_addr = ws_host_addr.replace(/[\[\]]/g, ''); ws_host_addr = ws_host_addr.replace(/:/g, "-"); ws_host_addr += ".ipv6-literal.net"; } ws = new WebSocket("ws://" + ws_host_addr + "/remote_slide", "text.phpoc"); document.getElementById("ws_state").innerHTML = "CONNECTING"; ws.onopen = ws_onopen; ws.onclose = ws_onclose; ws.onmessage = ws_onmessage; } else ws.close(); } function ws_onopen() { document.getElementById("ws_state").innerHTML = "<font color='blue'>CONNECTED</font>"; document.getElementById("bt_connect").innerHTML = "Disconnect"; } function ws_onclose() { document.getElementById("ws_state").innerHTML = "<font color='gray'>CLOSED</font>"; document.getElementById("bt_connect").innerHTML = "Connect"; ws.onopen = null; ws.onclose = null; ws.onmessage = null; ws = null; } function ws_onmessage(e_msg) { e_msg = e_msg || window.event; alert("msg : " + e_msg.data); } function rotate_plate(angle) { var canvas = document.getElementById("remote"); var ctx = canvas.getContext("2d"); ctx.clearRect(-canvas_width / 2, -canvas_height / 2, canvas_width, canvas_height); ctx.rotate(angle / 180 * Math.PI); ctx.strokeStyle="red"; ctx.fillStyle="red"; ctx.beginPath(); ctx.arc(0, 0, plate_radius, Math.PI, Math.PI * 1.5); ctx.lineTo(0, 0); ctx.lineTo(-plate_radius, 0); ctx.fill(); ctx.stroke(); ctx.strokeStyle="blue"; ctx.fillStyle="blue"; ctx.beginPath(); ctx.arc(0, 0, plate_radius, 0, Math.PI / 2); ctx.lineTo(0, 0); ctx.lineTo(plate_radius, 0); ctx.fill(); ctx.stroke(); ctx.strokeStyle="black"; ctx.arc(0, 0, plate_radius, 0, Math.PI * 2); ctx.stroke(); ctx.rotate(-angle / 180 * Math.PI); } function mouse_down() { if(ws == null) return; var dist_min, dist_max, dist; event.preventDefault(); if(event.offsetX) { x = event.offsetX - canvas_width / 2; y = canvas_height / 2 - event.offsetY; dist_min = 40; dist_max = plate_radius; } else if(event.layerX) { x = event.layerX - canvas_width / 2; y = canvas_height / 2 - event.layerY; dist_min = 40; dist_max = canvas_width / 2; } else { x = (Math.round(event.touches[0].pageX - event.touches[0].target.offsetLeft)) - canvas_width / 2; y = canvas_height / 2 - (Math.round(event.touches[0].pageY - event.touches[0].target.offsetTop)); dist_min = 40; dist_max = canvas_width / 2; } var dist = Math.round(Math.sqrt(x * x + y * y)); if((dist > dist_min) && (dist < dist_max)) { click_state = 1; last_angle = Math.round(Math.atan2(y, x) / Math.PI * 180); } } function mouse_up() { if(ws == null) return; event.preventDefault(); click_state = 0; } function mouse_move() { if(ws == null) return; var dist_min, dist_max, angle, dist; event.preventDefault(); if(!click_state) return; if(event.offsetX) { x = event.offsetX - canvas_width / 2; y = canvas_height / 2 - event.offsetY; dist_min = 40; dist_max = plate_radius; } else if(event.layerX) { x = event.layerX - canvas_width / 2; y = canvas_height / 2 - event.layerY; dist_min = 40; dist_max = canvas_width / 2; } else { x = (Math.round(event.touches[0].pageX - event.touches[0].target.offsetLeft)) - canvas_width / 2; y = canvas_height / 2 - (Math.round(event.touches[0].pageY - event.touches[0].target.offsetTop)); dist_min = 40; dist_max = canvas_width / 2; } angle = Math.round(Math.atan2(y, x) / Math.PI * 180); dist = Math.round(Math.sqrt(x * x + y * y)); if((dist < dist_min) || (dist > dist_max)) { click_state = 0; return; } if((Math.abs(angle) > 90) && (angle * last_angle < 0)) { if(last_angle > 0) last_angle = -180; else last_angle = 180; } plate_angle += (angle - last_angle); last_angle = angle; if(plate_angle > 180) plate_angle = 180; if(plate_angle < 0) plate_angle = 0; rotate_plate(-plate_angle); if(plate_angle != last_plate_angle) { if(ws && ws.readyState) { ws.send("C" + plate_angle.toString() + "\r\n"); last_plate_angle = plate_angle; debug = document.getElementById("debug"); debug.innerHTML = plate_angle; } } } window.onload = init; </script> </head> <body> <p> <h1>Web Remote Control / Rotate</h1> </p> <canvas id="remote" width="400" height="400"></canvas> <h2> <p> WebSocket : <span id="ws_state">null</span><br> Angle : <span id="debug">0</span> </p> <button id="bt_connect" type="button" onclick="connect_onclick();">Connect</button> </h2> </body> </html>
Código Arduino
/* arduino web server - remote control (slide switch) */
#include "SPI.h"
#include "Phpoc.h"
#include <Servo.h>
PhpocServer server(80);
Servo myservo; // create servo object to control a servo
char slideName;
int slideValue;
void setup() {
Serial.begin(9600);
while(!Serial) ;
Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
server.beginWebSocket("remote_slide");
Serial.print("WebSocket server address : ");
Serial.println(Phpoc.localIP());
myservo.attach(9); // attaches the servo on pin 9 to the servo object
myservo.write(1);
}
void loop() {
// wait for a new client:
PhpocClient client = server.available();
if (client) {
String slideStr = client.readLine();
if(slideStr) {
slideValue = slideStr.substring(1).toInt();
myservo.write(slideValue);
Serial.print("Angle: ");
Serial.println(slideValue);
}
}
}
Processo de manufatura
- Sistema de Iluminação DMX Controlado via Web – Controlador Mestre Arduino
- Construa um Spybot Controlado por Bluetooth com Arduino
- Mealheiro Inteligente: Controlar Aceitador de Moedas com Arduino Nano
- Controle Inteligente de Eletrodomésticos via Web e Apps Móveis
- Central de Controle de Potência Arduino: N-FET, P-FET, Relé e Kit RTC
- Controlar um LED via Bluetooth com Arduino – Guia DIY Simples
- Controlador de Umidificador DIY com Arduino e Relé – Configuração Segura de Alta Tensão
- Controle Dois Motores de Passo com Arduino Nano e Joystick – Tutorial Simples
- Arduino UNO com Shield WiFi: Exibição de Temperatura em Tempo Real na Web via Serial
- Proteja seu Arduino com Desbloqueio por Padrão Web – Configuração Fácil e Controle Remoto