réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Un forum dédie à vos questions concernant l'intégration à Domoticz des capteurs et gateway mysensors.org
Répondre
fcgyougui
Messages : 14
Enregistré le : 22 juil. 2017, 19:51

réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par fcgyougui » 15 nov. 2018, 19:31

Bonsoir.

comme dit dans le titre, j'ai réalisé une box pour mon bassin qui:
mesure le courant entrant / sortant de ma batterie suivant la charge de mes panneaux solaires et les accessoires qui y sont connectés.
La partie electro se comporte biens, mais je bloque sur le sketch a proprement parler.

la box se compose de:
- un arduino nano v3 et un NRF24L01+ pour la liaison,
- un module de mesure de tension https://www.ebay.fr/itm/5342-1-%C3%A0-1 ... 2749.l2649
- un module de mesure de courant https://www.ebay.fr/itm/1322-5A-20A-30A ... 2749.l2649
- deux sondes dallas avec leurs résistances
- 1 led et sa résistance
- 1 inter poussoir
- 3 relais
- une alim 5v stabilisé.

pour le câblage, j'ai repris le schema dispo ici:https://forum.mysensors.org/topic/3840/ ... ry-monitor
Image

sauf que j'ai changé les ports de la led et du poussoir en respectivement D4 et D5 pour pouvoir connecter les relais en D6, D7 et D8.

Voici le premier sketch, concernant tout sauf les relais:

Code : Tout sélectionner

 /*Sketch for a MySensor node to monitor a 12v battery with a solar panel for charging
 * The node monitors battery voltage,current into and out of the battery, ambient temperature and battery temperature.
 * 2 x DS18b20 dallas temperature ic's their data pins connected to arduino digital pin 3
 * 1 x ACS712 current sensor module connected to  arduino analog pin A4
 * 1 x 25v voltage sensor module connected to arduino analog pin A0
 * 1 x nRF24L01+  2.4ghz tranceiver connected as per the MySensors web site.
 * 1 x LED connected via a 330 ohm resistor to pin 6
 * 1 x push button connected to pin 5
 */
 
#include <MySensor.h>  
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>
 

#define ONE_WIRE_BUS 3                       // Ds18b20 data wire is connected to digital pin 3 on the Arduino
#define ID_S_TEMPA 0                         // First temp device
#define ID_S_TEMPB 1                         // second temp device
#define ID_S_MULTIMETERV 3                   // Multimeter device for voltage measurement
#define ID_S_MULTIMETERC 4                   // Multimeter device for positive current measurement 
#define ID_S_MULTIMETERC1 5                  // Multimeter device for negative current measurement
#define NUM_SAMPLES 10                       // number of analog voltage samples to take per reading


int ledPin = 6;                               // the pin for the LED
int buttonPin = 5;                            // the input pin for offset pushbutton
int buttonState = 0;                          // variable for reading the pin status
unsigned long SLEEP_TIME = 30000;            // Sleep time between reads (in milliseconds)
int lastmilli = 25000;                       // set to an arbitary number outside of expected current sensor range to ensure a change when first run 
float sensitivity = 100 ;                    //change this to 185 for ACS712-5 or to 100 for ACS712-20A or to 66 for ACS712-30A
int VQ = 0;                                  //Placeholder for quiescent voltage calculations
int ACSPin = A4;                             // Analog pin number the ACS712 data pin connects to
float lastTemperature[2];                    //Array to hold the last temp readings sent to gateway, only send new data if different
int sum = 0;                                 // sum of voltage samples taken
unsigned char sample_count = 0;              // current sample number
int lastVoltage = 30000;                     // set to an arbitary number outside of expected voltage sensor range to ensure a change when first run
int voltagePin = A0;                         // analog pin voltage sensor or voltage divider is connected to
int voltSenseMax = 25000;                    // set to the maximum input voltage in millivolts of your voltage divider input    
OneWire oneWire(ONE_WIRE_BUS);               // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire);         // Pass our oneWire reference to Dallas Temperature.

MySensor gw;

// ------ Initialize  messages -------
MyMessage msg(0,V_TEMP);                     
MyMessage msg_S_MULTIMETERv(ID_S_MULTIMETERV,V_VOLTAGE);
MyMessage msg_S_MULTIMETERc(ID_S_MULTIMETERC,V_CURRENT);
MyMessage msg_S_MULTIMETERc1(ID_S_MULTIMETERC1,V_CURRENT); 

void setup()
{
 
sensors.begin();                                    // Start up the onewire library
gw.begin();                                         // Startup and initialize MySensors library. Set callback for incoming messages. 
gw.sendSketchInfo("Battery Status Sensor", "1");    // Send the sketch version information to the gateway and Controller

// ------ Present all sensors to controller ------
gw.present(ID_S_TEMPA, S_TEMP);
gw.present(ID_S_TEMPB, S_TEMP);
gw.present(ID_S_MULTIMETERV,V_VOLTAGE);
gw.present(ID_S_MULTIMETERC,V_CURRENT);
gw.present(ID_S_MULTIMETERC1,V_CURRENT);


pinMode(buttonPin, INPUT_PULLUP);                     // Set buttonPin as input and turn on internal pull up resistor
pinMode(ledPin, OUTPUT);                              // Set ledPin as output
digitalWrite(ledPin, LOW);                            // Make sure ledPin is off

// ------ load offset for current sensor
int validCheck = gw.loadState(0);
if (validCheck == 120){                          // check to see if valid data exists
  VQ = gw.loadState(1);                               // Load count offset into VQ
//  Serial.print(" positive VQ offset loaded..."); Serial.println(VQ);
 }
 else if (validCheck == 125) {
  VQ = -abs(gw.loadState(1));
//  Serial.print(" negative VQ offset loaded..."); Serial.println(VQ);
 }
else {
// Serial.println("VQ offset not set");
}

delay(500);  
}
 
void loop()
{

buttonState = digitalRead(buttonPin);
//Serial.print("buttonstate..."); Serial.println(buttonState);
 if (buttonState == LOW) {
    VQ = determineVQ(ACSPin);                           //Returns the offset count needed to show zero with no load

    
  if (VQ >= 0 && VQ < 255) {                              //check for valid data. VQ is positive number
    gw.saveState(0, 120);                               // Store 120 value  in eeprom position 0. use this to check for valid data at boot
    gw.saveState(1, VQ);                                // Store offset count in eeprom. in case of re-boot  
  }
  else if (VQ < 0 && VQ > -255) {                              // VQ is a negative number. negatives cannot be stored in eeprom
    gw.saveState(0, 125);                               // Store 125 value  in eeprom position 0. use this to check for valid data at boot
    gw.saveState(1, abs(VQ));                                // convert VQ to positive and  Store offset count in eeprom. in case of re-boot   
  }

  }

// ------------------ Start voltage readings --------------------
 

 sample_count = 0;
 sum = 0;
 while (sample_count < NUM_SAMPLES) {                                   // take a number of voltage samples  
  sum += analogRead(voltagePin);
  sample_count++;
  delay(10);
 }
//Serial.print("sum count..."); Serial.println((sum / NUM_SAMPLES));      // print the count result. will be between 0 and 1023
int voltageI = map(sum/NUM_SAMPLES,0,1023,0,voltSenseMax);              // map the reading and get our result in millivolts
//Serial.print("mapped volts..."); Serial.println(voltageI / 1000.0, 1);  // convert millivolts back to volts and print. the 1 at the end determines how many decimal places to show


if ( voltageI != lastVoltage) {                                         // check if we have a new value. only send data if it is different
 gw.send(msg_S_MULTIMETERv.set(voltageI / 1000.0, 1));                  // voltagel is in millivolts so we divide by 1000 to convert back to volts and
                                                                        // send voltage message to gateway with 1 decimal place
 lastVoltage = voltageI;                                                // copy the current voltage reading for testing on the next loop 
}

//--------------------Start Current readings---------------------------------

int milli = readCurrent(ACSPin);                                       // take a reading from the ACS712 and send to the readcurrent function

//Serial.print("Milliamps..."); Serial.println(milli);                   // print the value (in milliamps) returned

if ( milli != lastmilli)                                               // check if value has changed
{
 if ( milli > 0)                                                       // Battery is charging
 {
  gw.send(msg_S_MULTIMETERc.set(milli/1000.0, 1));                     // Send new data to charging amp device
  gw.send(msg_S_MULTIMETERc1.set(0));                                  // set the dis-charging amp device to zero
  lastmilli =  milli;
 }
 else if (milli < 0)                                                  // Battery is discharging
 {
  gw.send(msg_S_MULTIMETERc.set(0));                                  // set the charging amp device to zero
  gw.send(msg_S_MULTIMETERc1.set(abs(milli)/1000.0, 1));             //  use abs(milli) to Send a positive number  to dis-charging amp device
  lastmilli =  milli; 
 }
else                                                                // No current flowing, set both to zero
{
 gw.send(msg_S_MULTIMETERc.set(0));
 gw.send(msg_S_MULTIMETERc1.set(0));
 lastmilli =  milli;
}
}
 
//----------------------Teperature readings start------------------------
  
  Serial.println(" Requesting temperatures...");
 
 // Fetch temperatures from Dallas sensors
  sensors.requestTemperatures();                  // call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

  // ------- query conversion time and sleep until conversion completed ------
  int16_t conversionTime = sensors.millisToWaitForConversion(sensors.getResolution());
  gw.sleep(conversionTime);

 for (int i=0; i<2; i++) {
//  Serial.print("Temperature for Device: ");Serial.print(i);Serial.print(" is: ");
 // Serial.println(sensors.getTempCByIndex(i)); // Why "byIndex"? 
    // You can have more than one IC on the same bus. 
    // 0 refers to the first IC on the wire

 float temperature = static_cast<float>(static_cast<int>((sensors.getTempCByIndex(i)) * 10.)) / 10.;  // Fetch and round temperature to one decimal in celcius

if (lastTemperature[i] != temperature)               // check for a changed temperature reading
  {
   gw.send(msg.setSensor(i).set(temperature,1));     // Send in the new temperature
   lastTemperature[i]=temperature;                   // Save new temperatures for next compare
  }     
}
gw.sleep(SLEEP_TIME);
}



/*-------------- Function to get the offset required for ACS712 to show zero with no current flowing -----------------*/
int determineVQ(int PIN)                  
 {
  digitalWrite(ledPin, HIGH);                                      // Turn on LED to indicate offset being calculated
  delay(500);                                                      // Delay to hold LED on
  digitalWrite(ledPin, LOW);                                       // Turn off LED
  delay(150);                                                      // Delay to let readings stabilise
//  Serial.print("estimating avg. quiscent voltage:");
  long acsCount = 0;
  for (int i=0; i<5000; i++)                                       //read 5000 samples to stabilise value
   {
    acsCount += analogRead(PIN);                                   // read the count value between 0 and 1023 and add it to acsCount
    delay(1);                                           
   }
  acsCount /= 5000;                                                      // acsCount now eaquals the average of the 5000 readings taken
//  Serial.print(map(acsCount, 0, 1023, 0, 5000));Serial.println(" mV");   //Print the avg in millivolts
//  Serial.print("acsCount:");Serial.println(acsCount);                               //Print the actual count value
  
  return int(acsCount - 512);                                            // return the count difference. 512 is the count for 2.5v which is what the reading should be with no current flow                           
  
}


 /*--------------- Function to read current flowing ------------------*/
 
int readCurrent(int PIN) 
{
 int count = 0;
 for (int i=0; i<5; i++)                                        //read 5 analog count samples to stabilise value
  {
   count += analogRead(PIN) - VQ;                               //subtract the offset count VQ to improve accuracy
   delay(1);
 //  Serial.print("raw count..."); Serial.println(count);
  }
 /* Notes on the conversion below
  *  .00488 is the volt value per count of the arduino adc. The analog pin measures from 0 to 5 volt and then assigns the result to 
  *  a count from 0 to 1023, thats 1024 counts including zero. If we devide 5v by 1024 we get .oo488 volts for each count.  
  *  
  *  The (count/5) just gets us the average of our 5 count samples.
  *  
  *  So after the first part of the equation  (.00488 * (count/5) is complete we have converted our count reading into volts. 
  *  
  *  The ACS712 can measure current flow in both directions so it outputs a voltage of  2.5v as it's center point (when no current is flowing).
  *  To allow for this offset we must subtract the 2.5v to center our voltage reading.
  *  
  * Thats what the next part does (.00488 * (count/5)) - 2.5) After this is complete we are left with either a negative or  positive voltage
  * reading or a reading of zero for no current flow.
  * 
  * NOTE: While the ACS712 is a 5v device it does not use the full 0 to 5v for it's output. The datasheet shows the 20A version has a sensitivity of
  *  100mv per amp, so if we multiply 100mv by 20 we get 2v.  That means the 20A ACS712 has an output range from .5v to 4.5v.  
  * 
  * So to convert our reading in volts to a reading in amps we need to add the last part ((.00488 * (count/5)) - 2.5)/(sensitivity/1000).
  * The variable sensitivity is defined at the begining of the sketch and holds the ACS712 sensitvity amount, it is stored in millivolts. 
  * That is 66mv for the 30amp,  100mv for the 20amp and 185mv for the 5amp. As sensitivity is in millivolts we need to devide it by 1000 
  * to convert it back to volts so we can use it in the equation. 
  * 
  * Now we have our Amps value stored in the float amps. Integers are much easier to work with when checking for zero so we multiply by 1000 
  * to convert it to milliamps and return it as an integer.
*/

//Serial.print("VQ = ..."); Serial.println(VQ);
//Serial.print("current count..."); Serial.println(count/5);
//Serial.print("map  milliamps..."); Serial.println(map((count/5), 102, 922, -20000, 20000));
 float amps = ((.00488 * (count/5)) - 2.5) / (sensitivity/1000);
// Serial.print("float amps..."); Serial.println(amps, 1);
  return int (amps * 1000);                                         // convert to milliamps and return as an integer

}
sur celui - ci, premier truc, c'est du mysensors v1.x

et celui que je veux intégrer:

Code : Tout sélectionner

/**
 * The MySensors Arduino library handles the wireless radio link and protocol
 * between your home built sensors/actuators and HA controller of choice.
 * The sensors forms a self healing radio network with optional repeaters. Each
 * repeater and gateway builds a routing tables in EEPROM which keeps track of the
 * network topology allowing messages to be routed to nodes.
 *
 * Created by Henrik Ekblad <henrik.ekblad@mysensors.org>
 * Copyright (C) 2013-2015 Sensnology AB
 * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
 *
 * Documentation: http://www.mysensors.org
 * Support Forum: http://forum.mysensors.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 *******************************
 *
 * REVISION HISTORY
 * Version 1.0 - Henrik Ekblad
 *
 * DESCRIPTION
 * Example sketch showing how to control physical relays.
 * This example will remember relay state after power failure.
 * http://www.mysensors.org/build/relay
 */

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enable and select radio type attached
#define MY_RADIO_NRF24
//#define MY_RADIO_NRF5_ESB
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95

// Enable repeater functionality for this node
#define MY_REPEATER_FEATURE

#include <MySensors.h>

#define RELAY_PIN 4  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
#define NUMBER_OF_RELAYS 1 // Total number of attached relays
#define RELAY_ON 1  // GPIO value to write to turn on attached relay
#define RELAY_OFF 0 // GPIO value to write to turn off attached relay


void before()
{
	for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
		// Then set relay pins in output mode
		pinMode(pin, OUTPUT);
		// Set relay to last known state (using eeprom storage)
		digitalWrite(pin, loadState(sensor)?RELAY_ON:RELAY_OFF);
	}
}

void setup()
{

}

void presentation()
{
	// Send the sketch version information to the gateway and Controller
	sendSketchInfo("Relay", "1.0");

	for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
		// Register all sensors to gw (they will be created as child devices)
		present(sensor, S_BINARY);
	}
}


void loop()
{

}

void receive(const MyMessage &message)
{
	// We only expect one type of message from controller. But we better check anyway.
	if (message.type==V_STATUS) {
		// Change relay state
		digitalWrite(message.sensor-1+RELAY_PIN, message.getBool()?RELAY_ON:RELAY_OFF);
		// Store state in eeprom
		saveState(message.sensor, message.getBool());
		// Write some debug info
		Serial.print("Incoming change for sensor:");
		Serial.print(message.sensor);
		Serial.print(", New status: ");
		Serial.println(message.getBool());
	}
}

Et voilà pour le moment ou moi j'en suis:

Code : Tout sélectionner

 /*Sketch for a MySensor node to monitor a 12v battery with a solar panel for charging
 * The node monitors battery voltage,current into and out of the battery, ambient temperature and battery temperature.
 * 2 x DS18b20 dallas temperature ic's their data pins connected to arduino digital pin 3
 * 1 x ACS712 current sensor module connected to  arduino analog pin A4
 * 1 x 25v voltage sensor module connected to arduino analog pin A0
 * 1 x nRF24L01+  2.4ghz tranceiver connected as per the MySensors web site.
 * 1 x LED connected via a 330 ohm resistor to pin 6
 * 1 x push button connected to pin 5
 */

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enable and select radio type attached
#define MY_RADIO_NRF24

// Enable repeater functionality for this node
#define MY_REPEATER_FEATURE
 
#include <MySensors.h> 
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>
 

#define ONE_WIRE_BUS 3                       // Ds18b20 data wire is connected to digital pin 3 on the Arduino
#define ID_S_TEMPA 0                         // First temp device
#define ID_S_TEMPB 1                         // second temp device
#define ID_S_MULTIMETERV 3                   // Multimeter device for voltage measurement
#define ID_S_MULTIMETERC 4                   // Multimeter device for positive current measurement 
#define ID_S_MULTIMETERC1 5                  // Multimeter device for negative current measurement
#define NUM_SAMPLES 10                       // number of analog voltage samples to take per reading

#define RELAY_PIN 6  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
#define NUMBER_OF_RELAYS 3 // Total number of attached relays
#define RELAY_ON 1  // GPIO value to write to turn on attached relay
#define RELAY_OFF 0 // GPIO value to write to turn off attached relay
#define MY_NODE_ID 7
#define MY_PARENT_NODE_ID 0
#define MY_RF24_PA_LEVEL RF24_PA_LOW



int ledPin = 5;                               // the pin for the LED
int buttonPin = 4;                            // the input pin for offset pushbutton
int buttonState = 0;                          // variable for reading the pin status
unsigned long SLEEP_TIME = 30000;            // Sleep time between reads (in milliseconds)
int lastmilli = 25000;                       // set to an arbitary number outside of expected current sensor range to ensure a change when first run 
float sensitivity = 66 ;                    //change this to 185 for ACS712-5 or to 100 for ACS712-20A or to 66 for ACS712-30A
int VQ = 0;                                  //Placeholder for quiescent voltage calculations
int ACSPin = A4;                             // Analog pin number the ACS712 data pin connects to
float lastTemperature[2];                    //Array to hold the last temp readings sent to gateway, only send new data if different
int sum = 0;                                 // sum of voltage samples taken
unsigned char sample_count = 0;              // current sample number
int lastVoltage = 30000;                     // set to an arbitary number outside of expected voltage sensor range to ensure a change when first run
int voltagePin = A0;                         // analog pin voltage sensor or voltage divider is connected to
int voltSenseMax = 25000;                    // set to the maximum input voltage in millivolts of your voltage divider input    
OneWire oneWire(ONE_WIRE_BUS);               // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire);         // Pass our oneWire reference to Dallas Temperature.


// ------ Initialize  messages -------
MyMessage msg(0,V_TEMP);                     
MyMessage msg_S_MULTIMETERv(ID_S_MULTIMETERV,V_VOLTAGE);
MyMessage msg_S_MULTIMETERc(ID_S_MULTIMETERC,V_CURRENT);
MyMessage msg_S_MULTIMETERc1(ID_S_MULTIMETERC1,V_CURRENT); 

void before()
{
  for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
    // Then set relay pins in output mode
    pinMode(pin, OUTPUT);
    // Set relay to last known state (using eeprom storage)
    digitalWrite(pin, loadState(sensor)?RELAY_ON:RELAY_OFF);
  }
}

void setup()
{
 
sensors.begin();                                    // Start up the onewire library
sendSketchInfo("Battery Status Sensor", "1");    // Send the sketch version information to the gateway and Controller

// ------ Present all sensors to controller ------
present(ID_S_TEMPA, S_TEMP);
present(ID_S_TEMPB, S_TEMP);
present(ID_S_MULTIMETERV,V_VOLTAGE);
present(ID_S_MULTIMETERC,V_CURRENT);
present(ID_S_MULTIMETERC1,V_CURRENT);


pinMode(buttonPin, INPUT_PULLUP);                     // Set buttonPin as input and turn on internal pull up resistor
pinMode(ledPin, OUTPUT);                              // Set ledPin as output
digitalWrite(ledPin, LOW);                            // Make sure ledPin is off

// ------ load offset for current sensor
int validCheck = loadState(0);
if (validCheck == 120){                          // check to see if valid data exists
  VQ = loadState(1);                               // Load count offset into VQ
//  Serial.print(" positive VQ offset loaded..."); Serial.println(VQ);
 }
 else if (validCheck == 125) {
  VQ = -abs(loadState(1));
//  Serial.print(" negative VQ offset loaded..."); Serial.println(VQ);
 }
else {
// Serial.println("VQ offset not set");
}

delay(500);  
}

void presentation()
{
  // Send the sketch version information to the gateway and Controller
  sendSketchInfo("Relay", "1.0");

  for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
    // Register all sensors to gw (they will be created as child devices)
    present(sensor, S_BINARY);
  }
}
 
void loop()
{

buttonState = digitalRead(buttonPin);
//Serial.print("buttonstate..."); Serial.println(buttonState);
 if (buttonState == LOW) {
    VQ = determineVQ(ACSPin);                           //Returns the offset count needed to show zero with no load

    
  if (VQ >= 0 && VQ < 255) {                              //check for valid data. VQ is positive number
    saveState(0, 120);                               // Store 120 value  in eeprom position 0. use this to check for valid data at boot
    saveState(1, VQ);                                // Store offset count in eeprom. in case of re-boot  
  }
  else if (VQ < 0 && VQ > -255) {                              // VQ is a negative number. negatives cannot be stored in eeprom
    saveState(0, 125);                               // Store 125 value  in eeprom position 0. use this to check for valid data at boot
    saveState(1, abs(VQ));                                // convert VQ to positive and  Store offset count in eeprom. in case of re-boot   
  }

  }

// ------------------ Start voltage readings --------------------
 

 sample_count = 0;
 sum = 0;
 while (sample_count < NUM_SAMPLES) {                                   // take a number of voltage samples  
  sum += analogRead(voltagePin);
  sample_count++;
  delay(10);
 }
//Serial.print("sum count..."); Serial.println((sum / NUM_SAMPLES));      // print the count result. will be between 0 and 1023
int voltageI = map(sum/NUM_SAMPLES,0,1023,0,voltSenseMax);              // map the reading and get our result in millivolts
//Serial.print("mapped volts..."); Serial.println(voltageI / 1000.0, 1);  // convert millivolts back to volts and print. the 1 at the end determines how many decimal places to show


if ( voltageI != lastVoltage) {                                         // check if we have a new value. only send data if it is different
 send(msg_S_MULTIMETERv.set(voltageI / 1000.0, 1));                  // voltagel is in millivolts so we divide by 1000 to convert back to volts and
                                                                        // send voltage message to gateway with 1 decimal place
 lastVoltage = voltageI;                                                // copy the current voltage reading for testing on the next loop 
}

//--------------------Start Current readings---------------------------------

int milli = readCurrent(ACSPin);                                       // take a reading from the ACS712 and send to the readcurrent function

//Serial.print("Milliamps..."); Serial.println(milli);                   // print the value (in milliamps) returned

if ( milli != lastmilli)                                               // check if value has changed
{
 if ( milli > 0)                                                       // Battery is charging
 {
  send(msg_S_MULTIMETERc.set(milli/1000.0, 1));                     // Send new data to charging amp device
  send(msg_S_MULTIMETERc1.set(0));                                  // set the dis-charging amp device to zero
  lastmilli =  milli;
 }
 else if (milli < 0)                                                  // Battery is discharging
 {
  send(msg_S_MULTIMETERc.set(0));                                  // set the charging amp device to zero
  send(msg_S_MULTIMETERc1.set(abs(milli)/1000.0, 1));             //  use abs(milli) to Send a positive number  to dis-charging amp device
  lastmilli =  milli; 
 }
else                                                                // No current flowing, set both to zero
{
 send(msg_S_MULTIMETERc.set(0));
 send(msg_S_MULTIMETERc1.set(0));
 lastmilli =  milli;
}
}
 
//----------------------Teperature readings start------------------------
  
  Serial.println(" Requesting temperatures...");
 
 // Fetch temperatures from Dallas sensors
  sensors.requestTemperatures();                  // call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

  // ------- query conversion time and sleep until conversion completed ------
  int16_t conversionTime = sensors.millisToWaitForConversion(sensors.getResolution());
  sleep(conversionTime);

 for (int i=0; i<2; i++) {
//  Serial.print("Temperature for Device: ");Serial.print(i);Serial.print(" is: ");
 // Serial.println(sensors.getTempCByIndex(i)); // Why "byIndex"? 
    // You can have more than one IC on the same bus. 
    // 0 refers to the first IC on the wire

 float temperature = static_cast<float>(static_cast<int>((sensors.getTempCByIndex(i)) * 10.)) / 10.;  // Fetch and round temperature to one decimal in celcius

if (lastTemperature[i] != temperature)               // check for a changed temperature reading
  {
   send(msg.setSensor(i).set(temperature,1));     // Send in the new temperature
   lastTemperature[i]=temperature;                   // Save new temperatures for next compare
  }     
}
sleep(SLEEP_TIME);
}



/*-------------- Function to get the offset required for ACS712 to show zero with no current flowing -----------------*/
int determineVQ(int PIN)                  
 {
  digitalWrite(ledPin, HIGH);                                      // Turn on LED to indicate offset being calculated
  delay(500);                                                      // Delay to hold LED on
  digitalWrite(ledPin, LOW);                                       // Turn off LED
  delay(150);                                                      // Delay to let readings stabilise
//  Serial.print("estimating avg. quiscent voltage:");
  long acsCount = 0;
  for (int i=0; i<5000; i++)                                       //read 5000 samples to stabilise value
   {
    acsCount += analogRead(PIN);                                   // read the count value between 0 and 1023 and add it to acsCount
    delay(1);                                           
   }
  acsCount /= 5000;                                                      // acsCount now eaquals the average of the 5000 readings taken
//  Serial.print(map(acsCount, 0, 1023, 0, 5000));Serial.println(" mV");   //Print the avg in millivolts
//  Serial.print("acsCount:");Serial.println(acsCount);                               //Print the actual count value
  
  return int(acsCount - 512);                                            // return the count difference. 512 is the count for 2.5v which is what the reading should be with no current flow                           
  
}


 /*--------------- Function to read current flowing ------------------*/
 
int readCurrent(int PIN) 
{
 int count = 0;
 for (int i=0; i<5; i++)                                        //read 5 analog count samples to stabilise value
  {
   count += analogRead(PIN) - VQ;                               //subtract the offset count VQ to improve accuracy
   delay(1);
 //  Serial.print("raw count..."); Serial.println(count);
  }
 /* Notes on the conversion below
  *  .00488 is the volt value per count of the arduino adc. The analog pin measures from 0 to 5 volt and then assigns the result to 
  *  a count from 0 to 1023, thats 1024 counts including zero. If we devide 5v by 1024 we get .oo488 volts for each count.  
  *  
  *  The (count/5) just gets us the average of our 5 count samples.
  *  
  *  So after the first part of the equation  (.00488 * (count/5) is complete we have converted our count reading into volts. 
  *  
  *  The ACS712 can measure current flow in both directions so it outputs a voltage of  2.5v as it's center point (when no current is flowing).
  *  To allow for this offset we must subtract the 2.5v to center our voltage reading.
  *  
  * Thats what the next part does (.00488 * (count/5)) - 2.5) After this is complete we are left with either a negative or  positive voltage
  * reading or a reading of zero for no current flow.
  * 
  * NOTE: While the ACS712 is a 5v device it does not use the full 0 to 5v for it's output. The datasheet shows the 20A version has a sensitivity of
  *  100mv per amp, so if we multiply 100mv by 20 we get 2v.  That means the 20A ACS712 has an output range from .5v to 4.5v.  
  * 
  * So to convert our reading in volts to a reading in amps we need to add the last part ((.00488 * (count/5)) - 2.5)/(sensitivity/1000).
  * The variable sensitivity is defined at the begining of the sketch and holds the ACS712 sensitvity amount, it is stored in millivolts. 
  * That is 66mv for the 30amp,  100mv for the 20amp and 185mv for the 5amp. As sensitivity is in millivolts we need to devide it by 1000 
  * to convert it back to volts so we can use it in the equation. 
  * 
  * Now we have our Amps value stored in the float amps. Integers are much easier to work with when checking for zero so we multiply by 1000 
  * to convert it to milliamps and return it as an integer.
*/

//Serial.print("VQ = ..."); Serial.println(VQ);
//Serial.print("current count..."); Serial.println(count/5);
//Serial.print("map  milliamps..."); Serial.println(map((count/5), 102, 922, -20000, 20000));
 float amps = ((.00488 * (count/5)) - 2.5) / (sensitivity/1000);
// Serial.print("float amps..."); Serial.println(amps, 1);
  return int (amps * 1000);                                         // convert to milliamps and return as an integer

}

void receive(const MyMessage &message)
{
  // We only expect one type of message from controller. But we better check anyway.
  if (message.type==V_STATUS) {
    // Change relay state
    digitalWrite(message.sensor-1+RELAY_PIN, message.getBool()?RELAY_ON:RELAY_OFF);
    // Store state in eeprom
    saveState(message.sensor, message.getBool());
    // Write some debug info
    Serial.print("Incoming change for sensor:");
    Serial.print(message.sensor);
    Serial.print(", New status: ");
    Serial.println(message.getBool());
  }
}
Le code semble bon, il s'injecte biens, a priori tout fonctionne (biens que j'ai un doute sur la mesure de courant, mais sa au pire je le corrigerais par la suite) mais je n'ai aucun relais.

J'en appelle donc a votre bon cœur (msieur dames!) pour me filer la main, car la programmation.... je suis une bonne vieille bille!
Merci d'avance :)

Disable adblock

This site is supported by ads and donations.
If you see this text you are blocking our ads.
Please consider a Donation to support the site.


mickaelr30
Messages : 145
Enregistré le : 29 août 2015, 15:57

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par mickaelr30 » 15 nov. 2018, 22:13

salut,
essaye d'enlever le sleep(SLEEP_TIME);
j'avais le même problème
a+
Domoticz + Imperihome + Mydomoathome
1-wire : 12 DS18b20 + 3 DS2413
Z-Wave : 8 FGR221 + 3 FGS222 + 3 FGSD002
téléinfo : 2 modules ( consommation + production)
Mysensors+ 1 arduino éclairage LED neopixels
2 caméra IP + 2 raspberry (XBMC,piscine)

fcgyougui
Messages : 14
Enregistré le : 22 juil. 2017, 19:51

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par fcgyougui » 15 nov. 2018, 22:24

salut :)
je l'enleve completement?
je pense savoir d'ou viens une part du souci, je pense que le noeud déclare les devices avec les memes id. du genre le premier relais en 1 et .... le premier capteur aussi!

mickaelr30
Messages : 145
Enregistré le : 29 août 2015, 15:57

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par mickaelr30 » 15 nov. 2018, 22:48

oui enlève le complétement car le sleeptime met en pause l'arduino du coup quand tu envoi un ordre elle ne continu pas son programme.
quand je veux temporiser l'envoi de mesure je fais plutot cette methode :
if (millis()-previousMillisOneWire >= SEND_ONE_WIRE) {
previousMillisOneWire = millis();
un peu de lecture : http://arlotto.univ-tln.fr/arduino/arti ... a-fonction
Domoticz + Imperihome + Mydomoathome
1-wire : 12 DS18b20 + 3 DS2413
Z-Wave : 8 FGR221 + 3 FGS222 + 3 FGSD002
téléinfo : 2 modules ( consommation + production)
Mysensors+ 1 arduino éclairage LED neopixels
2 caméra IP + 2 raspberry (XBMC,piscine)

Disable adblock

This site is supported by ads and donations.
If you see this text you are blocking our ads.
Please consider a Donation to support the site.


domdom
Messages : 62
Enregistré le : 20 mai 2016, 10:48
Localisation : Ille-et-Vilaine

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par domdom » 15 nov. 2018, 22:54

Bonsoir,

Il y a plusieurs problèmes en effet :
1. un sketch ne peut avoir normalement qu'un seul appel à la fonction sendSketchInfo() -> cette fonction permet de présenter, à la gateway, le nom et la version du noeud -> un noeud ne peut avoir plusieurs noms

2. pour chaque fonction du noeud, un appel à la fonction present() doit être effectué pour que la gateway sache que le noeud en question gère cette fonction -> une fonction est définie par un numéro qui doit être unique pour le noeud (on peut le voir comme un numéro de canal) -> tu as des appels de la fonction present() avec le même ID, il faut corriger cela et utiliser des ID uniques

3. lorsqu'on fait un capteur, celui-ci peut se permettre, pour économiser l'énergie, de s'endormir régulièrement, se réveiller, effectuer une mesure, l'envoyer puis se rendormir. Lorsque tu veux commander un actionneur, le noeud ne doit pas dormir, sinon, il y a de fortes chances pour qu'il soit en train de dormir lorsqu'une commande sera envoyée par la gateway -> dans ce cas, le message sera perdu -> il faut donc supprimer le sleep

Sinon, c'est du détail, mais ça aide beaucoup à mieux comprendre comment marche un programme. Depuis le version 2 de MySensors, il est conseillé de mettre regrouper les appels sendSketchInfo() et present() dans la même fonction, à savoir la fonction presentation().

Bon courage

fcgyougui
Messages : 14
Enregistré le : 22 juil. 2017, 19:51

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par fcgyougui » 15 nov. 2018, 23:27

Bon, j'ai fais pas mal de test. Enlever les sleep etait une bétise :)
je les ai remplacé par wait, car en les enlevant totalement l'arduino m'envoyais des trams a tour de bras!
Le seule truc que je ne trouve pas, c'est les températures.
les enfants sonts biens créé en id 4 et 5, mais les valeurs s'enregistrent sur les child id 0 et 1 :)
enfin j'ai biens avancé!

fcgyougui
Messages : 14
Enregistré le : 22 juil. 2017, 19:51

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par fcgyougui » 15 nov. 2018, 23:33

domdom a écrit :
15 nov. 2018, 22:54
Bonsoir,

Il y a plusieurs problèmes en effet :
1. un sketch ne peut avoir normalement qu'un seul appel à la fonction sendSketchInfo() -> cette fonction permet de présenter, à la gateway, le nom et la version du noeud -> un noeud ne peut avoir plusieurs noms

2. pour chaque fonction du noeud, un appel à la fonction present() doit être effectué pour que la gateway sache que le noeud en question gère cette fonction -> une fonction est définie par un numéro qui doit être unique pour le noeud (on peut le voir comme un numéro de canal) -> tu as des appels de la fonction present() avec le même ID, il faut corriger cela et utiliser des ID uniques

3. lorsqu'on fait un capteur, celui-ci peut se permettre, pour économiser l'énergie, de s'endormir régulièrement, se réveiller, effectuer une mesure, l'envoyer puis se rendormir. Lorsque tu veux commander un actionneur, le noeud ne doit pas dormir, sinon, il y a de fortes chances pour qu'il soit en train de dormir lorsqu'une commande sera envoyée par la gateway -> dans ce cas, le message sera perdu -> il faut donc supprimer le sleep

Sinon, c'est du détail, mais ça aide beaucoup à mieux comprendre comment marche un programme. Depuis le version 2 de MySensors, il est conseillé de mettre regrouper les appels sendSketchInfo() et present() dans la même fonction, à savoir la fonction presentation().

Bon courage
Mince, on s'est croisé :)
1: oui j'ai vu, c'est corrigé :)
2: je ne suis pas sur de comprendre, mais je crois que c'est ce que j'ai fais (ou essayé) en changeant l'id des premières sondes. j'ai voulu changer l'id des relais, mais les numéros semblent être calculés, et j'ai pas compris par quel formule (c'est pas des math' sa!)
3: en supprimant totalement le sleep, l'arduino n'attendait plus les 30 sec. entre mesures de température.... et vu comme il carbure, il m'as mis domoticz dans tous ses états! :D avec un WAIT a la place, sa semble régler le problème....

Bref, merci pour la réponse rapide. Manque plus que les valeurs qui s'enregistrent sur le mauvais ... euh... nœud?, et ce sera bon!
:geek:

fcgyougui
Messages : 14
Enregistré le : 22 juil. 2017, 19:51

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par fcgyougui » 15 nov. 2018, 23:34

je post le sketch modifié:

Code : Tout sélectionner

 /*Sketch for a MySensor node to monitor a 12v battery with a solar panel for charging
 * The node monitors battery voltage,current into and out of the battery, ambient temperature and battery temperature.
 * 2 x DS18b20 dallas temperature ic's their data pins connected to arduino digital pin 3
 * 1 x ACS712 current sensor module connected to  arduino analog pin A4
 * 1 x 25v voltage sensor module connected to arduino analog pin A0
 * 1 x nRF24L01+  2.4ghz tranceiver connected as per the MySensors web site.
 * 1 x LED connected via a 330 ohm resistor to pin 6
 * 1 x push button connected to pin 5
 */

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enable and select radio type attached
#define MY_RADIO_NRF24


 
#include <MySensors.h> 
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>
 

#define ONE_WIRE_BUS 3                       // Ds18b20 data wire is connected to digital pin 3 on the Arduino
#define ID_S_TEMPA 4                         // First temp device
#define ID_S_TEMPB 5                         // second temp device
#define ID_S_MULTIMETERV 7                   // Multimeter device for voltage measurement
#define ID_S_MULTIMETERC 8                   // Multimeter device for positive current measurement 
#define ID_S_MULTIMETERC1 9                  // Multimeter device for negative current measurement
#define NUM_SAMPLES 10                       // number of analog voltage samples to take per reading

#define RELAY_PIN 6  // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
#define NUMBER_OF_RELAYS 3 // Total number of attached relays
#define RELAY_ON 1  // GPIO value to write to turn on attached relay
#define RELAY_OFF 0 // GPIO value to write to turn off attached relay
#define MY_NODE_ID 10
#define MY_PARENT_NODE_ID 0
#define MY_RF24_PA_LEVEL RF24_PA_MAX



int ledPin = 5;                               // the pin for the LED
int buttonPin = 4;                            // the input pin for offset pushbutton
int buttonState = 0;                          // variable for reading the pin status
unsigned long SLEEP_TIME = 30000;            // Sleep time between reads (in milliseconds)
int lastmilli = 25000;                       // set to an arbitary number outside of expected current sensor range to ensure a change when first run 
float sensitivity = 66 ;                    //change this to 185 for ACS712-5 or to 100 for ACS712-20A or to 66 for ACS712-30A
int VQ = 0;                                  //Placeholder for quiescent voltage calculations
int ACSPin = A4;                             // Analog pin number the ACS712 data pin connects to
float lastTemperature[2];                    //Array to hold the last temp readings sent to gateway, only send new data if different
int sum = 0;                                 // sum of voltage samples taken
unsigned char sample_count = 0;              // current sample number
int lastVoltage = 30000;                     // set to an arbitary number outside of expected voltage sensor range to ensure a change when first run
int voltagePin = A0;                         // analog pin voltage sensor or voltage divider is connected to
int voltSenseMax = 25000;                    // set to the maximum input voltage in millivolts of your voltage divider input    
OneWire oneWire(ONE_WIRE_BUS);               // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire);         // Pass our oneWire reference to Dallas Temperature.


// ------ Initialize  messages -------
MyMessage msg(4,V_TEMP);                     
MyMessage msg_S_MULTIMETERv(ID_S_MULTIMETERV,V_VOLTAGE);
MyMessage msg_S_MULTIMETERc(ID_S_MULTIMETERC,V_CURRENT);
MyMessage msg_S_MULTIMETERc1(ID_S_MULTIMETERC1,V_CURRENT); 

void before()
{
  for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
    // Then set relay pins in output mode
    pinMode(pin, OUTPUT);
    // Set relay to last known state (using eeprom storage)
    digitalWrite(pin, loadState(sensor)?RELAY_ON:RELAY_OFF);
  }
}

void setup()
{
 
sensors.begin();                                    // Start up the onewire library
sendSketchInfo("Battery Status Sensor + relay", "1");    // Send the sketch version information to the gateway and Controller

// ------ Present all sensors to controller ------
present(ID_S_TEMPA, S_TEMP);
present(ID_S_TEMPB, S_TEMP);
present(ID_S_MULTIMETERV,V_VOLTAGE);
present(ID_S_MULTIMETERC,V_CURRENT);
present(ID_S_MULTIMETERC1,V_CURRENT);


pinMode(buttonPin, INPUT_PULLUP);                     // Set buttonPin as input and turn on internal pull up resistor
pinMode(ledPin, OUTPUT);                              // Set ledPin as output
digitalWrite(ledPin, LOW);                            // Make sure ledPin is off

// ------ load offset for current sensor
int validCheck = loadState(0);
if (validCheck == 120){                          // check to see if valid data exists
  VQ = loadState(1);                               // Load count offset into VQ
//  Serial.print(" positive VQ offset loaded..."); Serial.println(VQ);
 }
 else if (validCheck == 125) {
  VQ = -abs(loadState(1));
//  Serial.print(" negative VQ offset loaded..."); Serial.println(VQ);
 }
else {
// Serial.println("VQ offset not set");
}

delay(500);  
}

void presentation()
{
  

  for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
    // Register all sensors to gw (they will be created as child devices)
    present(sensor, S_BINARY);
  }
}
 
void loop()
{

buttonState = digitalRead(buttonPin);
//Serial.print("buttonstate..."); Serial.println(buttonState);
 if (buttonState == LOW) {
    VQ = determineVQ(ACSPin);                           //Returns the offset count needed to show zero with no load

    
  if (VQ >= 0 && VQ < 255) {                              //check for valid data. VQ is positive number
    saveState(0, 120);                               // Store 120 value  in eeprom position 0. use this to check for valid data at boot
    saveState(1, VQ);                                // Store offset count in eeprom. in case of re-boot  
  }
  else if (VQ < 0 && VQ > -255) {                              // VQ is a negative number. negatives cannot be stored in eeprom
    saveState(0, 125);                               // Store 125 value  in eeprom position 0. use this to check for valid data at boot
    saveState(1, abs(VQ));                                // convert VQ to positive and  Store offset count in eeprom. in case of re-boot   
  }

  }

// ------------------ Start voltage readings --------------------
 

 sample_count = 0;
 sum = 0;
 while (sample_count < NUM_SAMPLES) {                                   // take a number of voltage samples  
  sum += analogRead(voltagePin);
  sample_count++;
  delay(10);
 }
//Serial.print("sum count..."); Serial.println((sum / NUM_SAMPLES));      // print the count result. will be between 0 and 1023
int voltageI = map(sum/NUM_SAMPLES,0,1023,0,voltSenseMax);              // map the reading and get our result in millivolts
//Serial.print("mapped volts..."); Serial.println(voltageI / 1000.0, 1);  // convert millivolts back to volts and print. the 1 at the end determines how many decimal places to show


if ( voltageI != lastVoltage) {                                         // check if we have a new value. only send data if it is different
 send(msg_S_MULTIMETERv.set(voltageI / 1180.00, 2));                  // voltagel is in millivolts so we divide by 1000 to convert back to volts and
                                                                        // send voltage message to gateway with 1 decimal place
 lastVoltage = voltageI;                                                // copy the current voltage reading for testing on the next loop 
}

//--------------------Start Current readings---------------------------------

int milli = readCurrent(ACSPin);                                       // take a reading from the ACS712 and send to the readcurrent function

//Serial.print("Milliamps..."); Serial.println(milli);                   // print the value (in milliamps) returned

if ( milli != lastmilli)                                               // check if value has changed
{
 if ( milli > 0)                                                       // Battery is charging
 {
  send(msg_S_MULTIMETERc.set(milli/1000.0, 1));                     // Send new data to charging amp device
  send(msg_S_MULTIMETERc1.set(0));                                  // set the dis-charging amp device to zero
  lastmilli =  milli;
 }
 else if (milli < 0)                                                  // Battery is discharging
 {
  send(msg_S_MULTIMETERc.set(0));                                  // set the charging amp device to zero
  send(msg_S_MULTIMETERc1.set(abs(milli)/1000.0, 1));             //  use abs(milli) to Send a positive number  to dis-charging amp device
  lastmilli =  milli; 
 }
else                                                                // No current flowing, set both to zero
{
 send(msg_S_MULTIMETERc.set(0));
 send(msg_S_MULTIMETERc1.set(0));
 lastmilli =  milli;
}
}
 
//----------------------Teperature readings start------------------------
  
  Serial.println(" Requesting temperatures...");
 
 // Fetch temperatures from Dallas sensors
  sensors.requestTemperatures();                  // call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

  // ------- query conversion time and sleep until conversion completed ------
  int16_t conversionTime = sensors.millisToWaitForConversion(sensors.getResolution());
  wait(conversionTime);

 for (int i=0; i<2; i++) {
//  Serial.print("Temperature for Device: ");Serial.print(i);Serial.print(" is: ");
 // Serial.println(sensors.getTempCByIndex(i)); // Why "byIndex"? 
    // You can have more than one IC on the same bus. 
    // 0 refers to the first IC on the wire

 float temperature = static_cast<float>(static_cast<int>((sensors.getTempCByIndex(i)) * 10.)) / 10.;  // Fetch and round temperature to one decimal in celcius

if (lastTemperature[i] != temperature)               // check for a changed temperature reading
  {
   send(msg.setSensor(i).set(temperature,1));     // Send in the new temperature
   lastTemperature[i]=temperature;                   // Save new temperatures for next compare
  }     
}
wait(SLEEP_TIME);
}



/*-------------- Function to get the offset required for ACS712 to show zero with no current flowing -----------------*/
int determineVQ(int PIN)                  
 {
  digitalWrite(ledPin, HIGH);                                      // Turn on LED to indicate offset being calculated
  delay(500);                                                      // Delay to hold LED on
  digitalWrite(ledPin, LOW);                                       // Turn off LED
  delay(150);                                                      // Delay to let readings stabilise
//  Serial.print("estimating avg. quiscent voltage:");
  long acsCount = 0;
  for (int i=0; i<5000; i++)                                       //read 5000 samples to stabilise value
   {
    acsCount += analogRead(PIN);                                   // read the count value between 0 and 1023 and add it to acsCount
    delay(1);                                           
   }
  acsCount /= 5000;                                                      // acsCount now eaquals the average of the 5000 readings taken
//  Serial.print(map(acsCount, 0, 1023, 0, 5000));Serial.println(" mV");   //Print the avg in millivolts
//  Serial.print("acsCount:");Serial.println(acsCount);                               //Print the actual count value
  
  return int(acsCount - 512);                                            // return the count difference. 512 is the count for 2.5v which is what the reading should be with no current flow                           
  
}


 /*--------------- Function to read current flowing ------------------*/
 
int readCurrent(int PIN) 
{
 int count = 0;
 for (int i=0; i<5; i++)                                        //read 5 analog count samples to stabilise value
  {
   count += analogRead(PIN) - VQ;                               //subtract the offset count VQ to improve accuracy
   delay(1);
 //  Serial.print("raw count..."); Serial.println(count);
  }
 /* Notes on the conversion below
  *  .00488 is the volt value per count of the arduino adc. The analog pin measures from 0 to 5 volt and then assigns the result to 
  *  a count from 0 to 1023, thats 1024 counts including zero. If we devide 5v by 1024 we get .oo488 volts for each count.  
  *  
  *  The (count/5) just gets us the average of our 5 count samples.
  *  
  *  So after the first part of the equation  (.00488 * (count/5) is complete we have converted our count reading into volts. 
  *  
  *  The ACS712 can measure current flow in both directions so it outputs a voltage of  2.5v as it's center point (when no current is flowing).
  *  To allow for this offset we must subtract the 2.5v to center our voltage reading.
  *  
  * Thats what the next part does (.00488 * (count/5)) - 2.5) After this is complete we are left with either a negative or  positive voltage
  * reading or a reading of zero for no current flow.
  * 
  * NOTE: While the ACS712 is a 5v device it does not use the full 0 to 5v for it's output. The datasheet shows the 20A version has a sensitivity of
  *  100mv per amp, so if we multiply 100mv by 20 we get 2v.  That means the 20A ACS712 has an output range from .5v to 4.5v.  
  * 
  * So to convert our reading in volts to a reading in amps we need to add the last part ((.00488 * (count/5)) - 2.5)/(sensitivity/1000).
  * The variable sensitivity is defined at the begining of the sketch and holds the ACS712 sensitvity amount, it is stored in millivolts. 
  * That is 66mv for the 30amp,  100mv for the 20amp and 185mv for the 5amp. As sensitivity is in millivolts we need to devide it by 1000 
  * to convert it back to volts so we can use it in the equation. 
  * 
  * Now we have our Amps value stored in the float amps. Integers are much easier to work with when checking for zero so we multiply by 1000 
  * to convert it to milliamps and return it as an integer.
*/

//Serial.print("VQ = ..."); Serial.println(VQ);
//Serial.print("current count..."); Serial.println(count/5);
//Serial.print("map  milliamps..."); Serial.println(map((count/5), 102, 922, -20000, 20000));
 float amps = ((.00488 * (count/5)) - 2.5) / (sensitivity/1000);
// Serial.print("float amps..."); Serial.println(amps, 1);
  return int (amps * 1000);                                         // convert to milliamps and return as an integer

}

void receive(const MyMessage &message)
{
  // We only expect one type of message from controller. But we better check anyway.
  if (message.type==V_STATUS) {
    // Change relay state
    digitalWrite(message.sensor-1+RELAY_PIN, message.getBool()?RELAY_ON:RELAY_OFF);
    // Store state in eeprom
    saveState(message.sensor, message.getBool());
    // Write some debug info
    Serial.print("Incoming change for sensor:");
    Serial.print(message.sensor);
    Serial.print(", New status: ");
    Serial.println(message.getBool());
  }
}

domdom
Messages : 62
Enregistré le : 20 mai 2016, 10:48
Localisation : Ille-et-Vilaine

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par domdom » 16 nov. 2018, 10:04

2. Les sketchs d'exemple du site mySensors sont parfois un peu tordus et/ou peu didactiques.
La boucle suivante :

Code : Tout sélectionner

  for (int sensor=1, pin=RELAY_PIN; sensor<=NUMBER_OF_RELAYS; sensor++, pin++) {
    present(sensor, S_BINARY);
  }
est un peu tordue.

Pour mémoire, une boucle for s'écrit :
for (instructions initiales; condition d'arrêt; instructions exécutées à chaque boucle)

Du coup, le code peut également s'écrire :

Code : Tout sélectionner

  
  pin=RELAY_PIN;
  for (int sensor=1, ; sensor<=NUMBER_OF_RELAYS; sensor++) {
    present(sensor, S_BINARY);
    pin++
  }
On comprend mieux le code et on peut voir que la fonction present est appelée NUMBER_OF_RELAYS fois, avec les identifiants 1, 2, 3 jusqu'à NUMBER_OF_RELAYS.

Dans ton nouveau code, tu as modifié les valeurs des identifiants, ça doit donc fonctionner.

3. en effet, un wait() est quand même bienvenue ;o)

4. Autre subtilité, lorsqu'un nœud envoie un message à la Gateway, il doit impérativement préciser l'ID associé utilisé lors de l'appel à la fonction present().
Dans ton cas, tu appelles, pour déclarer les deux thermomètres :

Code : Tout sélectionner

present(ID_S_TEMPA, S_TEMP);
present(ID_S_TEMPB, S_TEMP);
du coup, pour remonter les mesures associées, il faut appeler respectivement :

Code : Tout sélectionner

 send(msg.setSensor(ID_S_TEMPA).set(temperature,1));    
 send(msg.setSensor(ID_S_TEMPB).set(temperature,1));    
Comme ID_S_TEMPB = ID_S_TEMPA +1, tu remplacer la ligne :

Code : Tout sélectionner

   send(msg.setSensor(i).set(temperature,1));     // Send in the new temperature
par

Code : Tout sélectionner

   send(msg.setSensor( ID_S_TEMPA + i).set(temperature,1));     // Send in the new temperature
Bon courage

fcgyougui
Messages : 14
Enregistré le : 22 juil. 2017, 19:51

Re: réutiliser un sketch d'une version inférieur a 2.0 et combiner avec un sketch relay

Message par fcgyougui » 17 nov. 2018, 17:11

super!
bon je teste tout sa dans la semaine, une fois que j'aurais reçu mes step down 5 - 3.3v.
je refais une partie du câblage et je vous tiendrais au jus, merci :)

Disable adblock

This site is supported by ads and donations.
If you see this text you are blocking our ads.
Please consider a Donation to support the site.


Répondre