Andurino IDE - Odczyt stanu pinu cyfrowego podłączonego do Supli

Sibikk
Posty: 366
Rejestracja: pn lis 07, 2016 12:42 pm
Lokalizacja: Katowice
Kontakt:

@Piotr61 użyj opcji </> ciężko się czyta forum jak posty są tak długie. sorki za off
Obrazek
Awatar użytkownika
shimano73
Posty: 1968
Rejestracja: ndz lut 28, 2016 12:27 pm
Lokalizacja: Orzesze
Kontakt:

Witam, wykorzystałem fragment kodu
Piotr61 pisze: wt maja 08, 2018 9:54 pm Do obsługi przycisków użyj przerwań od timera.
Np.

Kod: Zaznacz cały

os_timer_t timer;
void buttons_timer() {
	if(!digitalRead(14)) {
		//pin 14 zwarty do GND - zrób coś
	}
}


void setup() {
 
....
  os_timer_disarm(&timer);
  os_timer_setfn(&timer, (os_timer_func_t *)buttons_timer, NULL);
  os_timer_arm(&timer, 50, 1);
no i dla jednego przycisku działa , ale dla dwóch nie chce działać .

Kod: Zaznacz cały

 void buttons_timer() {
	if(!digitalRead(14)) {
		//pin 14 zwarty do GND - zrób coś
	}
	if(!digitalRead(12)) {
		//pin 12 zwarty do GND - zrób coś
	}
}
gdzie popełniłem błąd
W elektronice jak nie wiadomo o co chodzi to zwykle chodzi o zasilanie

Wezmę udział w Supla Offline Party 2024 :)
Awatar użytkownika
Espablo
Posty: 1754
Rejestracja: śr cze 29, 2016 5:04 pm
Lokalizacja: Oświęcim
Kontakt:

Zwiększ czas timer. Może za często sprawdzasz ten pin
Każde urządzenie elektryczne działa o wiele lepiej jeśli podłączysz je do prądu. :? :roll:
mirek1968
Posty: 2
Rejestracja: czw wrz 13, 2018 7:09 pm

A może ktoś jak krowie na rowie pokazać jak zrobić w SuplaNodeMCU
gdy mam dodane 2 przekaźniki ON/OFF tak by móc przełączać je też przyciskiem
i widzieć ten stan w aplikacji , ale też móc wyłączyć z aplikacji bez zmiany stanu włącznika ??

Chyba że się tak aż nie da zrobić ??
mirek1968
Posty: 2
Rejestracja: czw wrz 13, 2018 7:09 pm

szkoda że nikt nie chce pomóc ,
bo wkleić kawałek kodu to każdy potrafi
, ale nie każdy od razu wie jak i gdzie wkleić i dostosować
Awatar użytkownika
Espablo
Posty: 1754
Rejestracja: śr cze 29, 2016 5:04 pm
Lokalizacja: Oświęcim
Kontakt:

mirek1968 pisze: wt wrz 18, 2018 9:22 pm szkoda że nikt nie chce pomóc ,
bo wkleić kawałek kodu to każdy potrafi
, ale nie każdy od razu wie jak i gdzie wkleić i dostosować
Pomógł bym Ci z chęcią ale nie kompiluję na Arduino. Każda gotowa kompilacja działa właśnie tak jak opisałeś wcześniej. Możesz wgrać do NodeMCU i potestować.
Każde urządzenie elektryczne działa o wiele lepiej jeśli podłączysz je do prądu. :? :roll:
Awatar użytkownika
slawek
Posty: 2465
Rejestracja: pn mar 14, 2016 11:48 pm
Lokalizacja: Biała Podlaska

Może to ci coś pomoże

Kod: Zaznacz cały

/* Przygotowane przez kolegę elmaya na poniższych bibliotekach
 * Działa z bibliotekami: FS.h            w wersji: 1.0.3
 *                        WiFiManager.h   w wersji: 0.12.0
 *                        ArduinoJson.h   w wersji: 5.13.2
 * zmodyfikowany przez wojtas567 dodane kilka praktycznych dodatków :) 
 * dostosowany do własnych potrzeb przez @slawek*/

#include <FS.h>  

#include <ESP8266WiFi.h>
#define SUPLADEVICE_CPP
#include <SuplaDevice.h>

#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h> 
#include <ArduinoJson.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
extern "C" {
#include "user_interface.h"
}
#include <DHT.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define DHTPIN 3 // GPIO 3-RX
#define DHTTYPE DHT22

// Setup a DHT instance
DHT dht(DHTPIN, DHTTYPE);

// Setup a oneWire instance
OneWire oneWire(02); // GPIO 02

// Pass oneWire reference to Dallas Temperature
DallasTemperature sensors(&oneWire);

ADC_MODE(ADC_VCC);

#define BTN_COUNT 2

WiFiClient client;
const char* host = "supla";
const char* update_path = "/nowy";
const char* update_username = "admin";
const char* update_password = "supla";

ESP8266WebServer httpServer(81);
ESP8266HTTPUpdateServer httpUpdater;

//define your default values here, if there are different values in config.json, they are overwritten.
//length should be max size + 1 
char Supla_server[40];
char Location_id[15];
char Location_Pass[20];
byte mac[6];

//flag for saving data
bool shouldSaveConfig = false;
bool initialConfig = false;

#define TRIGGER_PIN 5
int timeout           = 120; // seconds to run for

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Powinien zapisać konfigurację");
  shouldSaveConfig = true;
}
void ondemandwifiCallback () {
// The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_Supla_server("server", "supla server", Supla_server, 40);
  WiFiManagerParameter custom_Location_id("ID", "Location_id", Location_id, 15);
  WiFiManagerParameter custom_Location_Pass("Password", "Location_Pass", Location_Pass, 20);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);
  
  //add all your parameters here
  wifiManager.addParameter(&custom_Supla_server);
  wifiManager.addParameter(&custom_Location_id);
  wifiManager.addParameter(&custom_Location_Pass);

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  wifiManager.setMinimumSignalQuality();

  // set configportal timeout
    wifiManager.setConfigPortalTimeout(timeout);

    if (!wifiManager.startConfigPortal("UNI-IDE")) {
      Serial.println("nie udało się połączyć w osiągniętym limicie czasu");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
      ESP.restart();
      delay(5000);
    }
    //if you get here you have connected to the WiFi
    Serial.println("połaczono... :)");
    
    //read updated parameters
    strcpy(Supla_server, custom_Supla_server.getValue());
    strcpy(Location_id, custom_Location_id.getValue());
    strcpy(Location_Pass, custom_Location_Pass.getValue());
}

// obsługa przycisków
typedef struct {
  int pin;
  int relay_pin;
  int channel;
  int ms;
  char last_val;
  unsigned long last_time;
} _btn_t;

_btn_t btn[BTN_COUNT];

void supla_timer() {
  char v;
  unsigned long now = millis();
  
  for(int a=0;a<BTN_COUNT;a++)
    if (btn[a].pin > 0) {
        v = digitalRead(btn[a].pin);
        if (v != btn[a].last_val && now - btn[a].last_time ) {
           btn[a].last_val = v;
           btn[a].last_time = now;
           if (v==0)
             {
             if ( btn[a].ms > 0 ) {
                     SuplaDevice.relayOn(btn[a].channel, btn[a].ms);
                 } else {
                 if ( digitalRead(btn[a].relay_pin) == 0 ) {
                  SuplaDevice.relayOff(btn[a].channel);
                  Serial.print("BTN Switsh off relay ");
                  Serial.println(btn[a].relay_pin);
                 } else {
                  SuplaDevice.relayOn(btn[a].channel, 0);
                  Serial.print("BTN Switsh on relay ");
                  Serial.println(btn[a].relay_pin);
                 }        
             }
        }
      }
    }
}
void supla_btn_init() {
  for(int a=0;a<BTN_COUNT;a++)
    if (btn[a].pin > 0) {
        pinMode(btn[a].pin, INPUT_PULLUP);
        btn[a].last_val = digitalRead(btn[a].pin);
        btn[a].last_time = millis();
    }
}

// Obsługa czujnika DHT22 lub BME280 itp
void get_temperature_and_humidity(int channelNumber, double *temp, double *humidity) {

    *temp = dht.readTemperature();
    *humidity = dht.readHumidity();

    if ( isnan(*temp) || isnan(*humidity) ) {
      *temp = -275;
      *humidity = -1;
    }
}

// Obsługa czujnika DS18B20 i odczyt parametrów modułu ESP
double get_temperature(int channelNumber, double last_val) {
    double t = -275;
          switch(channelNumber)
          {
            case 1:
    if ( sensors.getDeviceCount() > 0 )
      {
         sensors.requestTemperatures();
         t = sensors.getTempCByIndex(0);
      }
                    break;
            case 2:
         t = WiFi.RSSI();
                    break;
            case 3:
         t = (ESP.getVcc()/1000.0);
                    break;
            case 4:
         t = (ESP.getFlashChipRealSize()/1024/1024);
                    break;
      };

    return t;  
}

void setup() {

  Serial.begin(115200);
  delay(10);

  wifi_station_set_hostname("SUPLA-ESP");  //nazwa w sieci lokalnej

  pinMode(TRIGGER_PIN, INPUT);
  
  if (WiFi.SSID()==""){
    //Serial.println("We haven't got any access point credentials, so get them now");   
    initialConfig = true;
  }
  
  //read configuration from FS json
  Serial.println("adaptacja FS...");
  
  if (SPIFFS.begin()) {
    Serial.println("ładowanie plików systemu");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("odczyt pliku konfiguracyjnego");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("otwarty plik konfiguracji");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;         
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        Serial.println(jsonBuffer.size());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\njson przeanalizowany");

          strcpy(Supla_server, json["Supla_server"]);
          strcpy(Location_id, json["Location_id"]);
          strcpy(Location_Pass, json["Location_Pass"]);

        } else {
          Serial.println("nie udało się załadować konfiguracji json");
          
        }
      }
    }
  } else {
    Serial.println("nie udało się zaadaptować FS");
  }
  WiFi.mode(WIFI_STA); // Force to station mode because if device was switched off while in access point mode it will start up next time in access point mode.

  // Inicjalizacja DHT
  dht.begin(); 
  SuplaDevice.setTemperatureHumidityCallback(&get_temperature_and_humidity);

  // Inicjalizacja DS18B20
  sensors.begin();
  SuplaDevice.setTemperatureCallback(&get_temperature);

  // Replace the falowing GUID
  uint8_t mac[WL_MAC_ADDR_LENGTH];
  WiFi.macAddress(mac);
  char GUID[SUPLA_GUID_SIZE] = {mac[WL_MAC_ADDR_LENGTH - 6], 
                                mac[WL_MAC_ADDR_LENGTH - 5], 
                                mac[WL_MAC_ADDR_LENGTH - 4], 
                                mac[WL_MAC_ADDR_LENGTH - 3], 
                                mac[WL_MAC_ADDR_LENGTH - 2], 
                                mac[WL_MAC_ADDR_LENGTH - 1]};
  
  // CHANNEL0 - DHT22
  SuplaDevice.addDHT22();               // na GPIO2

  // CHANNEL1,2,3 - DS, wifi, zasilanie
  SuplaDevice.addDS18B20Thermometer();  // DS na GPIO03 - RX
  SuplaDevice.addDS18B20Thermometer();  // wyśietla wifi
  SuplaDevice.addDS18B20Thermometer();  // wyśietla zasilanie
  //SuplaDevice.addDS18B20Thermometer();  // wyświetla wielkość pamięci

  // CHANNEL4,5 - RELAY
  SuplaDevice.addRelay(4, false);       // 44 - Pin number where the relay is connected      
  SuplaDevice.addRelay(13, false);      // 45 - Pin number where the relay is connected   

  // CHANNEL5,6 - TWO RELAYS (Roller shutter operation)
  //SuplaDevice.addRollerShutterRelays(5,            // 46 - Pin number where the 1st relay is connected   
  //                                   13, true);    // 47 - Pin number where the 2nd relay is connected  

  // CHANNEL6,7 - Opening sensor (Normal Open)
 // SuplaDevice.addSensorNO(14);   // A0 - Pin number where the sensor is connected
 // SuplaDevice.addSensorNO(12);  // Call SuplaDevice.addSensorNO(A0, true) with an extra "true" parameter
                                // to enable the internal pull-up resistor

  memset(btn, 0, sizeof(btn));
  btn[0].pin =14;         // pin gpio  button D5
  btn[0].relay_pin =4;    // pin gpio on which is relay  D1
  btn[0].channel =4;      // supla channel
  btn[0].ms =0;           // if = 0 Bistable -- if > 0 Monostable for X ms
  btn[1].pin =12;         // pin gpio  button D6
  btn[1].relay_pin =13;   // pin gpio on which is relay  D2
  btn[1].channel =5;      // supla channel
  btn[1].ms =2000;           // if = 0 Bistable -- if > 0 Monostable for X ms
  supla_btn_init();
  SuplaDevice.setTimerFuncImpl(&supla_timer);
  SuplaDevice.setName("UNI-IDE");

  int LocationID = atoi(Location_id);
  SuplaDevice.begin(GUID,              // Global Unique Identifier 
                    mac,               // Ethernet MAC address
                    Supla_server,      // SUPLA server address
                    LocationID,        // Location ID 
                    Location_Pass);    // Location Password


  Serial.println();
  Serial.println("Uruchamianie serwera aktualizacji...");
  WiFi.mode(WIFI_STA);

  MDNS.begin(host);
  httpUpdater.setup(&httpServer, update_path, update_username, update_password);
  httpServer.begin();
  MDNS.addService("http", "tcp", 81);
  Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with username '%s' and password '%s'\n", host, update_path, update_username, update_password);
}

void loop() {

    // is configuration portal requested?
  if ( digitalRead(TRIGGER_PIN) == LOW|| (initialConfig))  {
    ondemandwifiCallback () ;
    initialConfig = false; 
  }
  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("zapisywanie konfiguracji");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["Supla_server"] = Supla_server;
    json["Location_id"] = Location_id;
    json["Location_Pass"] = Location_Pass;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("nie udało się otworzyć pliku konfiguracyjnego do zapisu");
    }
    json.prettyPrintTo(Serial);
    json.printTo(configFile);
    configFile.close();
    Serial.println("konfiguracia zapisana");
    shouldSaveConfig = false;
    //end save
  }
  
  if (WiFi.status() != WL_CONNECTED) 
  {
    WiFi_up();
  }
  
  SuplaDevice.iterate();
  SuplaDevice.setTemperatureHumidityCallback(&get_temperature_and_humidity);
  SuplaDevice.setTemperatureCallback(&get_temperature);
  httpServer.handleClient();
}


// Supla.org ethernet layer
    int supla_arduino_tcp_read(void *buf, int count) {
        _supla_int_t size = client.available();
       
        if ( size > 0 ) {
            if ( size > count ) size = count;
            return client.read((uint8_t *)buf, size);
        };
    
        return -1;
    };
    
    int supla_arduino_tcp_write(void *buf, int count) {
        return client.write((const uint8_t *)buf, count);
    };
    
    bool supla_arduino_svr_connect(const char *server, int port) {
          return client.connect(server, 2015);
    }
    
    bool supla_arduino_svr_connected(void) {
          return client.connected();
    }
    
    void supla_arduino_svr_disconnect(void) {
         client.stop();
    }
    
    void supla_arduino_eth_setup(uint8_t mac[6], IPAddress *ip) {

       WiFi_up();
    }

SuplaDeviceCallbacks supla_arduino_get_callbacks(void) {
          SuplaDeviceCallbacks cb;
          
          cb.tcp_read = &supla_arduino_tcp_read;
          cb.tcp_write = &supla_arduino_tcp_write;
          cb.eth_setup = &supla_arduino_eth_setup;
          cb.svr_connected = &supla_arduino_svr_connected;
          cb.svr_connect = &supla_arduino_svr_connect;
          cb.svr_disconnect = &supla_arduino_svr_disconnect;
          cb.get_temperature = &get_temperature;
          cb.get_temperature_and_humidity = get_temperature_and_humidity;
          
          return cb;
}

void WiFi_up() // Procedimiento de conexión para redes WiFi
{
  Serial.print("Łączenie z siecią ");

  WiFi.begin(); // Intentar conectarse a la red

  for (int x = 60; x > 0; x--) 
  {
    if (WiFi.status() == WL_CONNECTED) 

    {
      break;                           
    }
    else                                 
    {
      Serial.print(".");                
      delay(500);                      
    }

  }

  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("");
    Serial.println("Połączono z");
    Serial.println("Adres IP: ");
    Serial.print(WiFi.localIP());
    Serial.print(" / ");
    Serial.println(WiFi.subnetMask());
    Serial.print("geteway: ");
    Serial.println(WiFi.gatewayIP());
    long rssi = WiFi.RSSI();
    Serial.print("siła sygnału (RSSI): ");
    Serial.print(rssi);
    Serial.println(" dBm");
  }
  else    
  {
    Serial.println("");
    Serial.println("brak połączenia");
  }
}
TEORIA jest wtedy gdy wszystko wiemy i nic nie działa
PRAKTYKA jest wtedy gdy wszystko działa a my nie wiemy dlaczego
My łączymy teorię z praktyką czyli nic nie działa i nikt nie wie dlaczego
ODPOWIEDZ

Wróć do „supla-dev”