boa noite, estou tentando montar um sistema para abrir e fechar a porta de casa, ja tenho um raspberry com home assistant, montei um esp wroom 02 d1 ligado a um servo 360 e um push botton, funciona da seguinte forma: o servo esta ligado diretamente a chave na porta, ele gira a chave por duas voltas para chavear ou abrir a chave, no conector da chave montei um esquema que quando a chave completa uma volta ela aciona o pushbotton que faz a contagem das voltas dadas pela chave.
tudo funciona normalmente, mas as vezes apos a chave girar as duas vezes, o servo gira de volta cerca de meia volta, este movimento nao tem nenhuma indicaçao no codigo, ja tentei trocar a gpio, ja troquei a fonte de alimentacao, tudo sem sucesso.
segue o codigo que estou utilizando:
/**
Copyright 2017 Bruno Horta
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <Servo.h>
// Configuração do acesso ao Broker MQTT
#define MQTT_AUTH true
#define MQTT_USERNAME "xxxxx"
#define MQTT_PASSWORD "xxxxxxxx"
Servo PIN_AIR;
const int buttonPin = D6; // gpio do pushbutton
int buttonState = 0;
int count = 0;
//Constantes
const String HOSTNAME = "servo_porta3"; //NOME DO DEVICE, este nome tambem é utilizado apra criar o Access Point para configuração
const char * MQTT_LOG = "system/log"; // Topico onde o Device Publica informações relacionadas com o sistema
const char * MQTT_SYSTEM_CONTROL_TOPIC = "system/set"; // Topico onde o Device subscreve para aceitar instruções de sistema
const char * MQTT_AIR_TOPIC = "servo/set"; //Topico de exemplo onde o Device subscreve (por exemplo controlar uma lâmpada)
const char* MQTT_SERVER = "192.168.x.x"; //IP ou DNS do Broker MQTT
WiFiClient wclient;
PubSubClient client(MQTT_SERVER,1883,wclient);
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT);
WiFiManager wifiManager;
//wifiManager.resetSettings(); //Limpa a configuração anterior do Wi-Fi SSID e Password, procedimento, 1º descomentar a linha, 2º Fazer Upload do código para o ESP e deixar o ESP arrancar, 3º Voltar a comentar a linha e enviar novamente o código para o ESP
/*define o tempo limite até o portal de configuração ficar novamente inátivo,
útil para quando alteramos a password do AP*/
wifiManager.setTimeout(180);
wifiManager.autoConnect(HOSTNAME.c_str());
client.setCallback(callback); //Registo da função que vai responder ás mensagens vindos do MQTT
}
//Chamada de recepção de mensagem
void callback(char* topic, byte* payload, unsigned int length) {
String payloadStr = "";
for (int i=0; i<length; i++) {
payloadStr += (char)payload[i];
}
String topicStr = String(topic);
if(topicStr.equals(MQTT_SYSTEM_CONTROL_TOPIC)){
if (payloadStr.equals("REBOOT_"+String(HOSTNAME))){
Serial.println("REBOOT");
ESP.restart();
}
}else if(topicStr.equals(MQTT_AIR_TOPIC)){
///////CONTROLE VIA MQTT/////////////////////
if (payloadStr == "ON"){ //ABRE A PORTA
client.publish("servo/confirm", "ON");
PIN_AIR.attach(D7);
PIN_AIR.writeMicroseconds(1600);
}else if (payloadStr == "OFF"){ //FECHA A PORTA
client.publish("servo/confirm", "OFF");
PIN_AIR.attach(D7);
PIN_AIR.writeMicroseconds(1400);
}else if (payloadStr == "CHAVE"){ //SE PORTA ABRIR COM A CHAVE, REDUZ UMA VOLTA
count = 1;
Serial.println(payloadStr);
}
//////TERMINA CONTROLE///////////////////////////////////
}
}
bool checkMqttConnection(){
if (!client.connected()) {
if (MQTT_AUTH ? client.connect(HOSTNAME.c_str(),MQTT_USERNAME, MQTT_PASSWORD) : client.connect(HOSTNAME.c_str())) {
Serial.println("CONNECTED TO MQTT BROKER "+String(MQTT_SERVER));
client.publish(MQTT_LOG,String("CONNECTED_"+HOSTNAME).c_str());
//SUBSCRIÇÃO DE TOPICOS
client.subscribe(MQTT_SYSTEM_CONTROL_TOPIC);
client.subscribe(MQTT_AIR_TOPIC);
}
}
return client.connected();
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
if (checkMqttConnection()){
client.loop();
}
}
buttonState = digitalRead(buttonPin); //le botao
if (buttonState == LOW) { //BOTAO PRECIONADO
count++;
Serial.println(count);
if (count == 3) { //QUANDO CHEGAR A 3, CHAVE GIROU 2X
delay(150); //TEMPO PARA CHAVE SAIR DO BOTAO
PIN_AIR.writeMicroseconds(1500); //DESLIGA MOTOR
Serial.println("motor desligado");
count = 0; //ZERA CONTADOR DE VOLTAS
delay(50); //TEMPO PARA DESCONECTAR O SERVO
PIN_AIR.detach();//DESCONECTA O SERVO
Serial.println("servo desconectado");
}
delay (300); //TEMPO PARA O BOTAO NAO CONTAR MUITO RAPIDO
}
}