[PORADNIK] Arduino IDE

cino111
Posts: 589
Joined: Mon May 07, 2018 8:00 pm

Mon Jul 02, 2018 2:54 am

slawek wrote:
Sun Jul 01, 2018 9:30 pm
Wyrzuć dane swego serwera... zrobiłem to za ciebie... RODO ;)
Dzięki. Tak to jest jak się robi na szybko :roll:
cino111
Posts: 589
Joined: Mon May 07, 2018 8:00 pm

Wed Jul 04, 2018 6:40 pm

cino111 wrote:
Sun Jul 01, 2018 8:50 pm
Ok. Obiecałem, że w weekend ogarnę czujniki temperatury DS18B20, więc zaczynamy.
W pierwszej kolejności musimy odczytać adresy czujników, żeby odczyty na apce pokazywały się do odpowiedniego kanału. Bez tego temperatura na dworze może się pokazywać przy kanale temperatura wewnętrzna i odwrotnie.
Do odczytania czujnika wykorzystamy gotowy program: Plik -> Przykłady -> OneWire -> DS18x20
W programie przy OneWire ds(10); wprowadzamy GPIO pod który mamy podpięty termometr. Po załadowaniu programu i uruchomieniu portu szeregowego pokazuje nam się adres.
Ja mam np. takie:
Device 0 Address: 28FFBC0AC21701FD
Device 0 Address: 28FF08BFC1170159
Device 0 Address: 28FF3299C11702FB
Device 0 Address: 28FFEA16C21701DE
Odczytany adres wpisujemy w postaci { 0x28, 0xFF, 0xBC, 0xA, 0xC2, 0x17, 0x1, 0xFD };
No to piszemy program:

Code: Select all

/*
Copyright (C) AC SOFTWARE SP. Z O.O.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SuplaDevice.h>

/*
 * This example requires Dallas Temperature Control library installed. 
 * https://github.com/milesburton/Arduino-Temperature-Control-Library
 */

 
// Setup a oneWire instance
OneWire oneWire(24); // 24 - Pin number

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

DeviceAddress piec = { 0x28, 0xFF, 0xBC, 0xA, 0xC2, 0x17, 0x1, 0xFD };       // odczytany adres 28FFBC0AC21701FD  
DeviceAddress bojler = { 0x28, 0xFF, 0x8, 0xBF, 0xC1, 0x17, 0x1, 0x59 };     //Odczytany adres 28FF08BFC1170159 
DeviceAddress temp_wew = { 0x28, 0xFF, 0x32, 0x99, 0xC1, 0x17, 0x2, 0xFB };   // odczytany adres 28FF3299C11702FB
DeviceAddress tempNaDworze = { 0x28, 0xFF, 0xEA, 0x16, 0xC2, 0x17, 0x1, 0xDE };    // odczytany adres 28FFEA16C21701DE


// DS18B20 Sensor read implementation
double get_temperature(int channelNumber, double last_val) {

    double t = -275;
    
    if ( sensors.getDeviceCount() > 0 )
      {
         sensors.requestTemperatures();
         switch(channelNumber)

          {
            case 0:
                   
                    t = sensors.getTempC(piec);
                    break;
            case 1:
                    t = sensors.getTempC(bojler);
                    break;
            case 2:
                    t = sensors.getTempC(temp_wew);
                    break;
            case 3:
                    t = sensors.getTempC(tempNaDworze);
                    break;
              
          
             };
      };

    return t;  



}


void setup() {

  Serial.begin(9600);

  // Init DS18B20 library 
  sensors.begin();

  
  
  // Set temperature callback
  SuplaDevice.setTemperatureCallback(&get_temperature);
 
  // Replace the falowing GUID
  char GUID[SUPLA_GUID_SIZE] = {0x2F,0xF9,0xF2,0x22,};
  // with GUID that you can retrieve from https://www.supla.org/arduino/get-guid


  // Ethernet MAC address
  uint8_t mac[6] = {0x00, 0x01, 0x02, 0x04, 0x03, 0x05};

  /*
   * Having your device already registered at cloud.supla.org,
   * you want to change CHANNEL sequence or remove any of them,
   * then you must also remove the device itself from cloud.supla.org.
   * Otherwise you will get "Channel conflict!" error.
   */
    
  
  // CHANNEL0 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();

  // CHANNEL1 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();

  // CHANNEL2 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();

  // CHANNEL3 - Thermometer DS18B20
  SuplaDevice.addDS18B20Thermometer();
  
  
  
  // CHANNEL4 - RELAY
  SuplaDevice.addRelay(44, true);           // 44 - Pin number where the relay is connected      
                                      // Call SuplaDevice.addRelay(44, true) with an extra "true" parameter 
                                      // to enable "port value inversion"
                                      // where HIGH == LOW, and LOW == HIGH   

  // CHANNEL5 - RELAY
  SuplaDevice.addRelay(45, true);           // 45 - Pin number where the relay is connected   

  // CHANNEL6 - RELAY 
  SuplaDevice.addRelay(46, true);           // 46 - Pin number where the relay is connected  

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


  // CHANNEL8 - Opening sensor (Normal Open)
  SuplaDevice.addSensorNO(A1); // A1 - Pin number where the sensor is connected


  


  /*
   * SuplaDevice Initialization.
   * Server address, LocationID and LocationPassword are available at https://cloud.supla.org 
   * If you do not have an account, you can create it at https://cloud.supla.org/account/create
   * SUPLA and SUPLA CLOUD are free of charge
   * 
   */

  SuplaDevice.begin(GUID,              // Global Unique Identifier 
                    mac,               // Ethernet MAC address
                    "svr.supla.org",  // SUPLA server address
                    xxxx,                 // Location ID 
                    "xxxx ");               // Location Password
    
}

void loop() {
  SuplaDevice.iterate();
  

}



Program się kompiluje i powinien działać. Można testować, ja na razie nie mam kiedy.
Sprawdziłem program - śmiga aż miło. SCR z Apki
Attachments
supla 3xDS18B20 na D3 NodeMCU.jpg
supla 3xDS18B20 na D3 NodeMCU.jpg (60.81 KiB) Viewed 2410 times
andras
Posts: 230
Joined: Fri Dec 30, 2016 5:51 pm

Thu Jul 05, 2018 11:45 am

Witam

Czy to jest cały kod ? nie mam gdzie wpisać mojego wifi .

pozdr
cino111
Posts: 589
Joined: Mon May 07, 2018 8:00 pm

Thu Jul 05, 2018 12:25 pm

andras wrote:
Thu Jul 05, 2018 11:45 am
Witam

Czy to jest cały kod ? nie mam gdzie wpisać mojego wifi .

pozdr
To jest kod do Arduino Mega. Jak chcesz na NodeMcu to fragment kodu wklej do swojego programu lub do gotowego z przykładów w Arduino Ide.
cino111
Posts: 589
Joined: Mon May 07, 2018 8:00 pm

Sat Jul 07, 2018 11:45 am

Czy jest możliwość dodania konfiguratora wifi do programu pisanego w Arduino? Ma ktoś taką wiedzę? Może @pzygmunt :?: Jeżeli tak to może ktoś się zgłosi na ochotnika? :mrgreen:
User avatar
pzygmunt
Posts: 6425
Joined: Tue Jan 19, 2016 9:26 am
Location: Paczków
Contact:

Sat Jul 07, 2018 11:47 am

Ja nie mam obecnie zasobów czasowych na to zadanie
cino111
Posts: 589
Joined: Mon May 07, 2018 8:00 pm

Sat Jul 07, 2018 12:01 pm

pzygmunt wrote:
Sat Jul 07, 2018 11:47 am
Ja nie mam obecnie zasobów czasowych na to zadanie
Ale rozumiem, że ogólnie jest taka możliwość?
Jeżeli tak to mógłbyś wkleić kod do konfiguratora z plików *.bin, które kompilujes? Może ktoś sprytniejszy ode mnie na podstawie tego kodu zbudował by to samo na Arduino.
User avatar
pzygmunt
Posts: 6425
Joined: Tue Jan 19, 2016 9:26 am
Location: Paczków
Contact:

Sat Jul 07, 2018 12:05 pm

Wszystkie źródła są na githubie
User avatar
shimano73
Posts: 851
Joined: Sun Feb 28, 2016 12:27 pm
Location: Orzesze

Sat Jul 07, 2018 1:26 pm

Jakiś czas temu znalazłem przypadkiem coś takiego
https://starter-kit.nettigo.pl/2018/02 ... ci-flash/
W elektronice jak nie wiadomo o co chodzi to zwykle chodzi o zasilanie
elmaya
Posts: 210
Joined: Wed Jun 27, 2018 5:48 pm
Location: Sevilla

Sat Jul 07, 2018 10:10 pm

hola prueba esto para wifimanager

Code: Select all

#include <FS.h>  

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

#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h> 
#include <ArduinoJson.h>

WiFiClient client;
//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 D3
int timeout           = 120; // seconds to run for


int measurePin = A0;
int ledPower = 5;

int samplingTime = 280;
int deltaTime = 40;
int sleepTime = 9680;

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  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("OnDemandAP")) {
      Serial.println("failed to connect and hit timeout");
      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("connected...yeey :)");
    
    //read updated parameters
    strcpy(Supla_server, custom_Supla_server.getValue());
    strcpy(Location_id, custom_Location_id.getValue());
    strcpy(Location_Pass, custom_Location_Pass.getValue());
  
}

// DS18B20 Sensor read implementation
double get_temperature(int channelNumber, double last_val) {

    
    
    digitalWrite(ledPower,LOW); // power on the LED
    delayMicroseconds(samplingTime);

    voMeasured = analogRead(measurePin); // read the dust value
  
    delayMicroseconds(deltaTime);
    digitalWrite(ledPower,HIGH); // turn the LED off
    delayMicroseconds(sleepTime);

    // 0 - 5.0V mapped to 0 - 1023 integer values 
    calcVoltage = voMeasured * (5.0 / 1024); 
  
    dustDensity = (0.17 * calcVoltage - 0.1)*1000; 
  
    Serial.print("Raw Signal Value (0-1023): ");
    Serial.print(voMeasured);
  
    Serial.print(" - Voltage: ");
    Serial.print(calcVoltage);
  
    Serial.print(" - Dust Density [ug/m3]: ");
    Serial.println(dustDensity);    
    
    
    
    
      
    double t = dustDensity;
    last_val = t;
    

    
    return t;  
}

void setup() {

  Serial.begin(115200);
  //sensors.begin();

  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("mounting FS...");
  
  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        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());
        json.printTo(Serial);
        if (json.success()) {
         // Serial.println("\nparsed json");

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

        } else {
          Serial.println("failed to load json config");
          
        }
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read
  //Serial.println(Location_id);
  //Serial.println(Location_Pass);
  //Serial.println(Supla_server);
 
 
   char GUID[SUPLA_GUID_SIZE] ={0x2F,0xF9,0xF2,0x22,};  // with GUID that you can retrieve from https://www.supla.org/arduino/get-guid.
   WiFi.macAddress(mac);
  
  SuplaDevice.addRelay(12, true);                 
  SuplaDevice.addRelay(13, true);              
  SuplaDevice.addRelay(15, true);
  SuplaDevice.addDS18B20Thermometer();

  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
    
}

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("saving config");
    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("failed to open config file for writing");
    }
    json.prettyPrintTo(Serial);
    json.printTo(configFile);
    configFile.close();
    Serial.println("config saved");
    shouldSaveConfig = false;
    //end save
  }
  
  if (WiFi.status() != WL_CONNECTED) 
  {
    WiFi_up();
  }
  
  SuplaDevice.iterate();
  SuplaDevice.setTemperatureCallback(&get_temperature);
}


// 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 = NULL;
          cb.get_rgbw_value = NULL;
          cb.set_rgbw_value = NULL;
          
          return cb;
}

void WiFi_up() // Procedimiento de conexión para redes WiFi
{
  Serial.print("Conexión a la red ");
 // Serial.println(ssid);

  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("Conexión hecha");
    Serial.println("Adres IP: ");
    Serial.print(WiFi.localIP());
    Serial.print(" / ");
    Serial.println(WiFi.subnetMask());
    Serial.print("puerta: ");
    Serial.println(WiFi.gatewayIP());
    long rssi = WiFi.RSSI();
    Serial.print("Fuerza de la señal (RSSI): ");
    Serial.print(rssi);
    Serial.println(" dBm");
  }
  else    
  {
    Serial.println("");
    Serial.println("La conexión no pudo hacerse");
  }
}
EDIT:poprawiłem czytelność (code)
slawek
Post Reply