-->
Page 1 of 6

GPIO not switching..code issue?

PostPosted: Sun Jan 12, 2020 4:47 pm
by GreenBlood
Hi Peeps, can someone have a nosie through this failry simple sketch pls and see if you can see why my gpio outputs are not triggering my relays? Ive been though it for days trying to figure it out!
Cheers!
Steve

Code: Select all/*
 * based on-
 * Rui Santos project
 * Complete Project Details http://randomnerdtutorials.com
*/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "fauxmoESP.h"

#define WIFI_SSID "wifipass"
#define WIFI_PASS "password"
#define REMOTE_BTN_1 4 //up (D2)
#define REMOTE_BTN_2 14//down (D5)
#define REMOTE_BTN_3 12  //select (D6)
#define REMOTE_BTN_4 5//stop (D1)
#define UP "blinds Up"
#define Down "blinds Down"
#define Light_Block "Blinds light Block"

fauxmoESP fauxmo;

void setup() {
  // Init serial port and clean garbage
  Serial.begin(115200);
  Serial.println();

  // Wi-Fi connection
  wifiSetup();

  // Set Buttons
  pinMode(REMOTE_BTN_1, OUTPUT);          //up
  digitalWrite(REMOTE_BTN_1, HIGH);

  pinMode(REMOTE_BTN_2, OUTPUT);          //down
  digitalWrite(REMOTE_BTN_2, LOW);
 
  pinMode(REMOTE_BTN_3, OUTPUT);          //select
  digitalWrite(REMOTE_BTN_3, HIGH);

  pinMode(REMOTE_BTN_4, OUTPUT);          //stop
  digitalWrite(REMOTE_BTN_4, HIGH);

  fauxmo.createServer(true); // not needed, this is the default value
  fauxmo.setPort(80); // This is required for gen3 devices
  fauxmo.enable(true);
 
  // You can use different ways to invoke alexa to modify the devices state:
  // "Alexa, turn lamp two on"
  fauxmo.addDevice(UP);
  fauxmo.addDevice(Down);
  fauxmo.addDevice(Light_Block);

  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {                          //command recieved
    // Callback when a command from Alexa is received.
    Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);
   
    if ( (strcmp(device_name, UP) == 0) ) {                                                                                           //blinds up
     down();     
    }
    if ( (strcmp(device_name, Down) == 0) ) {                                                                                         //blinds down
      // this just sets a variable that the main loop() does something about
      Serial.println("BtnDown 2 called by Alexa");
      digitalWrite(REMOTE_BTN_1, LOW);
      delay(1000);//1 second
      Serial.println("low");
      digitalWrite(REMOTE_BTN_1, HIGH);
      Serial.println("high");
    }
        if ( (strcmp(device_name, Light_Block) == 0) ) {                                                                              //set blinds to block light
      // this just sets a variable that the main loop() does something about
      Serial.println("Block light btn3 called by Alexa");

        digitalWrite(REMOTE_BTN_1, LOW);//open fully
        delay(1000);//1 second
        digitalWrite(REMOTE_BTN_1, HIGH);
        delay(30);                        //wait for blonds to open fully
       
        digitalWrite(REMOTE_BTN_3, LOW);//select first blind
        delay(1000);//1 seconds
        digitalWrite(REMOTE_BTN_3, HIGH);
        delay(500);
        digitalWrite(REMOTE_BTN_1, LOW);//HIGHer it for 12.5 seconds
        delay(500);
        digitalWrite(REMOTE_BTN_1, HIGH);
        delay(12500);//12.5 seconds                       
        digitalWrite(REMOTE_BTN_4, LOW);//stop it
        delay(1000);//1 second
        digitalWrite(REMOTE_BTN_4, HIGH);



       
        digitalWrite(REMOTE_BTN_3, LOW);//select second blind
        delay(1000);//1 seconds
        digitalWrite(REMOTE_BTN_3, HIGH);
       
        digitalWrite(REMOTE_BTN_3, LOW);//raise it for ...seconds
        delay(8000);//8 seconds
        digitalWrite(REMOTE_BTN_3, HIGH);
       
      //etc
     
    }
  });
}

void loop() {
  // fauxmoESP uses an async TCP server but a sync UDP server
  // Therefore, we have to manually poll for UDP packets
  fauxmo.handle();
}

 void down() {
  Serial.println("BtnUp 1 called by Alexa");
      digitalWrite(REMOTE_BTN_1, LOW);
      delay(1000);//1 second
      Serial.println("low");
      digitalWrite(REMOTE_BTN_1, HIGH);
      Serial.println("high");
 }
 
// Wi-Fi Connection
void wifiSetup() {
  // Set WIFI module to STA mode
  WiFi.mode(WIFI_STA);
  // Connect
  Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
    Serial.print("attempting to connect to wifi");
  // Wait
  while (WiFi.status() != WL_CONNECTED) {
   
    Serial.print(".");
    delay(100);
  }
  Serial.println();

  // Connected!
  Serial.printf("Connected to - SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
}

Re: GPIO not switching..code issue?

PostPosted: Sun Jan 12, 2020 5:28 pm
by Bonzo
By coincidence I tried some fauxmo examples last weekend as I received a dot for Christmas and could not get them to work.

I ended up using an example from "kakopappa" and he has some examples online. It uses an online service ( sinric ) which I did not really want to use but I needed something to prove the Alexa would actually switch a relay/LED.

Code: Select all/*
 Version 0.1 - Feb 10 2018
*/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsClient.h> //  https://github.com/kakopappa/sinric/wiki/How-to-add-dependency-libraries
#include <ArduinoJson.h> // https://github.com/kakopappa/sinric/wiki/How-to-add-dependency-libraries

int device_1 = 5;
ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
WiFiClient client;

#define MyApiKey "********" // TODO: Change to your sinric API Key. Your API Key is displayed on sinric.com dashboard
#define MySSID "********" // TODO: Change to your Wifi network SSID
#define MyWifiPassword "********" // TODO: Change to your Wifi network password

#define API_ENDPOINT "http://sinric.com"
#define HEARTBEAT_INTERVAL 300000 // 5 Minutes

uint64_t heartbeatTimestamp = 0;
bool isConnected = false;

void turnOn(String deviceId) {
  if (deviceId == "********") // Device ID of first device
  { 
    Serial.print("Turn on device id: ");
    Serial.println(deviceId);
    digitalWrite(device_1, HIGH);   
  }
  else if (deviceId == "5axxxxxxxxxxxxxxxxxxx") // Device ID of second device
  {
    Serial.print("Turn on device id: ");
    Serial.println(deviceId);
  }
  else {
    Serial.print("Turn on for unknown device id: ");
    Serial.println(deviceId);   
  }     
}

void turnOff(String deviceId) {
   if (deviceId == "********") // Device ID of first device
   { 
     Serial.print("Turn off Device ID: ");
     Serial.println(deviceId);
     digitalWrite(device_1, LOW);     
   }
   else if (deviceId == "5axxxxxxxxxxxxxxxxxxx") // Device ID of second device
   {
     Serial.print("Turn off Device ID: ");
     Serial.println(deviceId);
  }
  else {
     Serial.print("Turn off for unknown device id: ");
     Serial.println(deviceId);   
  }
}

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
  switch(type) {
    case WStype_DISCONNECTED:
      isConnected = false;   
      Serial.printf("[WSc] Webservice disconnected from sinric.com!\n");
      break;
    case WStype_CONNECTED: {
      isConnected = true;
      Serial.printf("[WSc] Service connected to sinric.com at url: %s\n", payload);
      Serial.printf("Waiting for commands from sinric.com ...\n");       
      }
      break;
    case WStype_TEXT: {
        Serial.printf("[WSc] get text: %s\n", payload);
        // Example payloads

        // For Light device type
        // {"deviceId": xxxx, "action": "setPowerState", value: "ON"} // https://developer.amazon.com/docs/device-apis/alexa-powercontroller.html
        // {"deviceId": xxxx, "action": "AdjustBrightness", value: 3} // https://developer.amazon.com/docs/device-apis/alexa-brightnesscontroller.html
        // {"deviceId": xxxx, "action": "setBrightness", value: 42} // https://developer.amazon.com/docs/device-apis/alexa-brightnesscontroller.html
        // {"deviceId": xxxx, "action": "SetColor", value: {"hue": 350.5,  "saturation": 0.7138, "brightness": 0.6501}} // https://developer.amazon.com/docs/device-apis/alexa-colorcontroller.html
        // {"deviceId": xxxx, "action": "DecreaseColorTemperature"} // https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html
        // {"deviceId": xxxx, "action": "IncreaseColorTemperature"} // https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html
        // {"deviceId": xxxx, "action": "SetColorTemperature", value: 2200} // https://developer.amazon.com/docs/device-apis/alexa-colortemperaturecontroller.html
       
#if ARDUINOJSON_VERSION_MAJOR == 5
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject((char*)payload);
#endif
#if ARDUINOJSON_VERSION_MAJOR == 6       
        DynamicJsonDocument json(1024);
        deserializeJson(json, (char*) payload);     
#endif       
        String deviceId = json ["deviceId"];     
        String action = json ["action"];
       
        if(action == "setPowerState") { // Switch or Light
            String value = json ["value"];
            if(value == "ON") {
                turnOn(deviceId);
            } else {
                turnOff(deviceId);
            }
        }
        else if(action == "SetColor") {
            // Alexa, set the device name to red
            // get text: {"deviceId":"xxxx","action":"SetColor","value":{"hue":0,"saturation":1,"brightness":1}}
            String hue = json ["value"]["hue"];
            String saturation = json ["value"]["saturation"];
            String brightness = json ["value"]["brightness"];

            Serial.println("[WSc] hue: " + hue);
            Serial.println("[WSc] saturation: " + saturation);
            Serial.println("[WSc] brightness: " + brightness);
        }
        else if(action == "SetBrightness") {
         
        }
        else if(action == "AdjustBrightness") {
         
        }
        else if (action == "test") {
            Serial.println("[WSc] received test command from sinric.com");
        }
      }
      break;
    case WStype_BIN:
      Serial.printf("[WSc] get binary length: %u\n", length);
      break;
    default: break;
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(device_1, OUTPUT);
 
  WiFiMulti.addAP(MySSID, MyWifiPassword);
  Serial.println();
  Serial.print("Connecting to Wifi: ");
  Serial.println(MySSID); 

  // Waiting for Wifi connect
  while(WiFiMulti.run() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  if(WiFiMulti.run() == WL_CONNECTED) {
    Serial.println("");
    Serial.print("WiFi connected. ");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  }

  // server address, port and URL
  webSocket.begin("iot.sinric.com", 80, "/");

  // event handler
  webSocket.onEvent(webSocketEvent);
  webSocket.setAuthorization("apikey", MyApiKey);
 
  // try again every 5000ms if connection has failed
  webSocket.setReconnectInterval(5000);   // If you see 'class WebSocketsClient' has no member named 'setReconnectInterval' error update arduinoWebSockets
}

void loop() {
  webSocket.loop();
 
  if(isConnected) {
      uint64_t now = millis();
     
      // Send heartbeat in order to avoid disconnections during ISP resetting IPs over night. Thanks @MacSass
      if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
          heartbeatTimestamp = now;
          webSocket.sendTXT("H");         
      }
  }   
}

Re: GPIO not switching..code issue?

PostPosted: Sun Jan 12, 2020 5:55 pm
by GreenBlood
It’s being detected by alexa, and the serial reads are showing that the code is running, but no gpio switching:-(

Re: GPIO not switching..code issue?

PostPosted: Mon Jan 13, 2020 4:00 am
by btidey
Questions:

Are you saying that the serial is showing that fauxmo.onSetState is being called?

down and up seem to do the same thing. Is that right?

Are you saying that the GPIO pin is not changing state (pulsed) in that routine or that you are not seeing the final action that you expect?

If the latter then you need to explain the hardware connection and actions from the GPIO.