Skip to content
  • MySensors
  • OpenHardware.io
  • Categories
  • Recent
  • Tags
  • Popular
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo
  1. Home
  2. Controllers
  3. Home Assistant
  4. Need guidance in creating sketch for Analog Moisture sensor

Need guidance in creating sketch for Analog Moisture sensor

Scheduled Pinned Locked Moved Home Assistant
4 Posts 3 Posters 67 Views 3 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    mrhutchinsonmn
    wrote on last edited by
    #1

    I am taking my 1st stab at creating a sketch to present to HA. I have very little understanding on how to do that and would like assistance correcting my understanding and successfully sending data from my analog moisture sensor to HA. What I have so far does attempt to present itself but HA complains about child ids (no matter what I use. Tried 0,10,20,100). I am certain I have other issues with sending the correct data but my first goal is to get the sensor to present itself and become available to work with in HA.

    [mysensors.sensor] child_id 0 already exists in children of node 105, cannot add child
    
    

    Here is the sketch I am working with, followed by the sketch I am referencing.

    /*
      AnalogReadSerial
    
      Reads an analog input on pin 0, prints the result to the Serial Monitor.
      Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
      Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
    
      This example code is in the public domain.
    
      http://www.arduino.cc/en/Tutorial/AnalogReadSerial
    */
    
    // Enable debug prints
    // #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_RF24
    //#define MY_RADIO_NRF5_ESB
    //#define MY_RADIO_RFM69
    //#define MY_RADIO_RFM95
    #define CHILD_ID 0
    #include <MySensors.h>
    MyMessage msg(CHILD_ID, V_LEVEL);
    // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }
    void presentation()
    {
      sendSketchInfo("Analog Soil Moisture Sensor", "1.0");
      present(CHILD_ID, S_MOISTURE);
    }
    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // print out the value you read:
      Serial.println(sensorValue);
      delay(10000);        // delay in between reads for stability
    }
    
    /*
     * 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-2019 Sensnology AB
     * Full contributor list: https://github.com/mysensors/MySensors/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.
     *
     *******************************
     *
     * DESCRIPTION
     *
     * Arduino soil moisture based on gypsum sensor/resistive sensor to avoid electric catalyse in soil
     *  Required to interface the sensor: 2 * 4.7kOhm + 2 * 1N4148
     *
     * Gypsum sensor and calibration:
     *  DIY: See http://vanderleevineyard.com/1/category/vinduino/1.html
     *  Built: Davis / Watermark 200SS
     *    http://www.cooking-hacks.com/watermark-soil-moisture-sensor?_bksrc=item2item&_bkloc=product
     *    http://www.irrometer.com/pdf/supportmaterial/sensors/voltage-WM-chart.pdf
     *    cb (centibar) http://www.irrometer.com/basics.html
     *      0-10 Saturated Soil. Occurs for a day or two after irrigation
     *      10-20 Soil is adequately wet (except coarse sands which are drying out at this range)
     *      30-60 Usual range to irrigate or water (except heavy clay soils).
     *      60-100 Usual range to irrigate heavy clay soils
     *      100-200 Soil is becoming dangerously dry for maximum production. Proceed with caution.
     *
     * Connection:
     * D6, D7: alternative powering to avoid sensor degradation
     * A0, A1: alternative resistance measuring
     *
     *  Based on:
     *  "Vinduino" portable soil moisture sensor code V3.00
     *   Date December 31, 2012
     *   Reinier van der Lee and Theodore Kaskalis
     *   www.vanderleevineyard.com
     * Contributor: epierre
     */
    
    // Copyright (C) 2015, Reinier van der Lee
    // www.vanderleevineyard.com
    
    // 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 3 of the License, or
    // 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.
    
    // Enable debug prints to serial monitor
    #define MY_DEBUG
    
    // Enable and select radio type attached
    #define MY_RADIO_RF24
    //#define MY_RADIO_NRF5_ESB
    //#define MY_RADIO_RFM69
    //#define MY_RADIO_RFM95
    
    #include <math.h>       // Conversion equation from resistance to %
    #include <MySensors.h>
    
    // Setting up format for reading 3 soil sensors
    #define NUM_READS (int)10    // Number of sensor reads for filtering
    #define CHILD_ID 0
    
    MyMessage msg(CHILD_ID, V_LEVEL);
    uint32_t SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
    
    long buffer[NUM_READS];
    int idx;
    
    /// @brief Structure to be used in percentage and resistance values matrix to be filtered (have to be in pairs)
    typedef struct {
      int moisture; //!< Moisture
      long resistance; //!< Resistance
    } values;
    
    const long knownResistor = 4700;  // Constant value of known resistor in Ohms
    
    int supplyVoltage;                // Measured supply voltage
    int sensorVoltage;                // Measured sensor voltage
    
    values valueOf[NUM_READS];        // Calculated moisture percentages and resistances to be sorted and filtered
    
    int i;                            // Simple index variable
    
    void setup()
    {
      // initialize the digital pins as an output.
      // Pin 6,7 is for sensor 1
      // initialize the digital pin as an output.
      // Pin 6 is sense resistor voltage supply 1
      pinMode(6, OUTPUT);
    
      // initialize the digital pin as an output.
      // Pin 7 is sense resistor voltage supply 2
      pinMode(7, OUTPUT);
    }
    
    void presentation()
    {
      sendSketchInfo("Soil Moisture Sensor Reverse Polarity", "1.0");
      present(CHILD_ID, S_MOISTURE);
    }
    
    void loop()
    {
    
      measure(6,7,1);
      Serial.print ("\t");
      Serial.println (average());
      long read1 = average();
    
      measure(7,6,0);
      Serial.print ("\t");
      Serial.println (average());
      long read2= average();
    
      long sensor1 = (read1 + read2)/2;
    
      Serial.print ("resistance bias =" );
      Serial.println (read1-read2);
      Serial.print ("sensor bias compensated value = ");
      Serial.println (sensor1);
      Serial.println ();
    
      //send back the values
      send(msg.set((int32_t)ceil(sensor1)));
      // delay until next measurement (msec)
      sleep(SLEEP_TIME);
    }
    
    void measure (int phase_b, int phase_a, int analog_input)
    {
      // read sensor, filter, and calculate resistance value
      // Noise filter: median filter
    
      for (i=0; i<NUM_READS; i++) {
    
        // Read 1 pair of voltage values
        digitalWrite(phase_a, HIGH);                 // set the voltage supply on
        delayMicroseconds(25);
        supplyVoltage = analogRead(analog_input);   // read the supply voltage
        delayMicroseconds(25);
        digitalWrite(phase_a, LOW);                  // set the voltage supply off
        delay(1);
    
        digitalWrite(phase_b, HIGH);                 // set the voltage supply on
        delayMicroseconds(25);
        sensorVoltage = analogRead(analog_input);   // read the sensor voltage
        delayMicroseconds(25);
        digitalWrite(phase_b, LOW);                  // set the voltage supply off
    
        // Calculate resistance
        // the 0.5 add-term is used to round to the nearest integer
        // Tip: no need to transform 0-1023 voltage value to 0-5 range, due to following fraction
        long resistance = (knownResistor * (supplyVoltage - sensorVoltage ) / sensorVoltage) ;
    
        delay(1);
        addReading(resistance);
        Serial.print (resistance);
        Serial.print ("\t");
      }
    }
    
    
    
    // Averaging algorithm
    void addReading(long resistance)
    {
      buffer[idx] = resistance;
      idx++;
      if (idx >= NUM_READS) {
        idx = 0;
      }
    }
    
    long average()
    {
      long sum = 0;
      for (int cnt = 0; cnt < NUM_READS; cnt++) {
        sum += buffer[cnt];
      }
      return (long)(sum / NUM_READS);
    }
    
    YveauxY 1 Reply Last reply
    0
    • M mrhutchinsonmn

      I am taking my 1st stab at creating a sketch to present to HA. I have very little understanding on how to do that and would like assistance correcting my understanding and successfully sending data from my analog moisture sensor to HA. What I have so far does attempt to present itself but HA complains about child ids (no matter what I use. Tried 0,10,20,100). I am certain I have other issues with sending the correct data but my first goal is to get the sensor to present itself and become available to work with in HA.

      [mysensors.sensor] child_id 0 already exists in children of node 105, cannot add child
      
      

      Here is the sketch I am working with, followed by the sketch I am referencing.

      /*
        AnalogReadSerial
      
        Reads an analog input on pin 0, prints the result to the Serial Monitor.
        Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
        Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
      
        This example code is in the public domain.
      
        http://www.arduino.cc/en/Tutorial/AnalogReadSerial
      */
      
      // Enable debug prints
      // #define MY_DEBUG
      
      // Enable and select radio type attached
      #define MY_RADIO_RF24
      //#define MY_RADIO_NRF5_ESB
      //#define MY_RADIO_RFM69
      //#define MY_RADIO_RFM95
      #define CHILD_ID 0
      #include <MySensors.h>
      MyMessage msg(CHILD_ID, V_LEVEL);
      // the setup routine runs once when you press reset:
      void setup() {
        // initialize serial communication at 9600 bits per second:
        Serial.begin(9600);
      }
      void presentation()
      {
        sendSketchInfo("Analog Soil Moisture Sensor", "1.0");
        present(CHILD_ID, S_MOISTURE);
      }
      // the loop routine runs over and over again forever:
      void loop() {
        // read the input on analog pin 0:
        int sensorValue = analogRead(A0);
        // print out the value you read:
        Serial.println(sensorValue);
        delay(10000);        // delay in between reads for stability
      }
      
      /*
       * 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-2019 Sensnology AB
       * Full contributor list: https://github.com/mysensors/MySensors/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.
       *
       *******************************
       *
       * DESCRIPTION
       *
       * Arduino soil moisture based on gypsum sensor/resistive sensor to avoid electric catalyse in soil
       *  Required to interface the sensor: 2 * 4.7kOhm + 2 * 1N4148
       *
       * Gypsum sensor and calibration:
       *  DIY: See http://vanderleevineyard.com/1/category/vinduino/1.html
       *  Built: Davis / Watermark 200SS
       *    http://www.cooking-hacks.com/watermark-soil-moisture-sensor?_bksrc=item2item&_bkloc=product
       *    http://www.irrometer.com/pdf/supportmaterial/sensors/voltage-WM-chart.pdf
       *    cb (centibar) http://www.irrometer.com/basics.html
       *      0-10 Saturated Soil. Occurs for a day or two after irrigation
       *      10-20 Soil is adequately wet (except coarse sands which are drying out at this range)
       *      30-60 Usual range to irrigate or water (except heavy clay soils).
       *      60-100 Usual range to irrigate heavy clay soils
       *      100-200 Soil is becoming dangerously dry for maximum production. Proceed with caution.
       *
       * Connection:
       * D6, D7: alternative powering to avoid sensor degradation
       * A0, A1: alternative resistance measuring
       *
       *  Based on:
       *  "Vinduino" portable soil moisture sensor code V3.00
       *   Date December 31, 2012
       *   Reinier van der Lee and Theodore Kaskalis
       *   www.vanderleevineyard.com
       * Contributor: epierre
       */
      
      // Copyright (C) 2015, Reinier van der Lee
      // www.vanderleevineyard.com
      
      // 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 3 of the License, or
      // 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.
      
      // Enable debug prints to serial monitor
      #define MY_DEBUG
      
      // Enable and select radio type attached
      #define MY_RADIO_RF24
      //#define MY_RADIO_NRF5_ESB
      //#define MY_RADIO_RFM69
      //#define MY_RADIO_RFM95
      
      #include <math.h>       // Conversion equation from resistance to %
      #include <MySensors.h>
      
      // Setting up format for reading 3 soil sensors
      #define NUM_READS (int)10    // Number of sensor reads for filtering
      #define CHILD_ID 0
      
      MyMessage msg(CHILD_ID, V_LEVEL);
      uint32_t SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
      
      long buffer[NUM_READS];
      int idx;
      
      /// @brief Structure to be used in percentage and resistance values matrix to be filtered (have to be in pairs)
      typedef struct {
        int moisture; //!< Moisture
        long resistance; //!< Resistance
      } values;
      
      const long knownResistor = 4700;  // Constant value of known resistor in Ohms
      
      int supplyVoltage;                // Measured supply voltage
      int sensorVoltage;                // Measured sensor voltage
      
      values valueOf[NUM_READS];        // Calculated moisture percentages and resistances to be sorted and filtered
      
      int i;                            // Simple index variable
      
      void setup()
      {
        // initialize the digital pins as an output.
        // Pin 6,7 is for sensor 1
        // initialize the digital pin as an output.
        // Pin 6 is sense resistor voltage supply 1
        pinMode(6, OUTPUT);
      
        // initialize the digital pin as an output.
        // Pin 7 is sense resistor voltage supply 2
        pinMode(7, OUTPUT);
      }
      
      void presentation()
      {
        sendSketchInfo("Soil Moisture Sensor Reverse Polarity", "1.0");
        present(CHILD_ID, S_MOISTURE);
      }
      
      void loop()
      {
      
        measure(6,7,1);
        Serial.print ("\t");
        Serial.println (average());
        long read1 = average();
      
        measure(7,6,0);
        Serial.print ("\t");
        Serial.println (average());
        long read2= average();
      
        long sensor1 = (read1 + read2)/2;
      
        Serial.print ("resistance bias =" );
        Serial.println (read1-read2);
        Serial.print ("sensor bias compensated value = ");
        Serial.println (sensor1);
        Serial.println ();
      
        //send back the values
        send(msg.set((int32_t)ceil(sensor1)));
        // delay until next measurement (msec)
        sleep(SLEEP_TIME);
      }
      
      void measure (int phase_b, int phase_a, int analog_input)
      {
        // read sensor, filter, and calculate resistance value
        // Noise filter: median filter
      
        for (i=0; i<NUM_READS; i++) {
      
          // Read 1 pair of voltage values
          digitalWrite(phase_a, HIGH);                 // set the voltage supply on
          delayMicroseconds(25);
          supplyVoltage = analogRead(analog_input);   // read the supply voltage
          delayMicroseconds(25);
          digitalWrite(phase_a, LOW);                  // set the voltage supply off
          delay(1);
      
          digitalWrite(phase_b, HIGH);                 // set the voltage supply on
          delayMicroseconds(25);
          sensorVoltage = analogRead(analog_input);   // read the sensor voltage
          delayMicroseconds(25);
          digitalWrite(phase_b, LOW);                  // set the voltage supply off
      
          // Calculate resistance
          // the 0.5 add-term is used to round to the nearest integer
          // Tip: no need to transform 0-1023 voltage value to 0-5 range, due to following fraction
          long resistance = (knownResistor * (supplyVoltage - sensorVoltage ) / sensorVoltage) ;
      
          delay(1);
          addReading(resistance);
          Serial.print (resistance);
          Serial.print ("\t");
        }
      }
      
      
      
      // Averaging algorithm
      void addReading(long resistance)
      {
        buffer[idx] = resistance;
        idx++;
        if (idx >= NUM_READS) {
          idx = 0;
        }
      }
      
      long average()
      {
        long sum = 0;
        for (int cnt = 0; cnt < NUM_READS; cnt++) {
          sum += buffer[cnt];
        }
        return (long)(sum / NUM_READS);
      }
      
      YveauxY Offline
      YveauxY Offline
      Yveaux
      Mod
      wrote on last edited by
      #2

      @mrhutchinsonmn [ your post was moved to Home Assistant category ]

      http://yveaux.blogspot.nl

      1 Reply Last reply
      0
      • BearWithBeardB Offline
        BearWithBeardB Offline
        BearWithBeard
        wrote on last edited by BearWithBeard
        #3

        In your sketch you present a moisture sensor with a child ID of 0 to Home Assistant, but you do not send any actual values for this sensor in your loop. As long there is no data, Home Assistant will not display anything in the web interface. Try adding send(msg.set(sensorValue)); to your loop and see if this does what you expect.


        The log message from Home Assistant is nothing to worry about by itself. When a node presents its sensors, Home Assistant looks up if they are already known and listed in your persistance file.

        If no entry with the presented child ID exists for a specific node in the persistance file, Home Assistant will add it and log to the console, that a new device has been added.

        Otherwise, if a child with the presented ID already exists, it does nothing but log the warning you got. You can safely ignore this as long as the sensor type stays the same, but if the newly presented sensor is of a different type, Home Assistant will not overwrite / change it to the new type and it will not show the new sensor values in the web interface. In this case, you would have to remove the conflicting child object manually from your persistance file, reload your configuration and present your sensors again.

        1 Reply Last reply
        1
        • M Offline
          M Offline
          mrhutchinsonmn
          wrote on last edited by
          #4

          Ha!! That worked!
          That is so cool! I am going to be automating watering of my garden based on individual plant needs and can easily do that now!
          Thank you!

          1 Reply Last reply
          0
          Reply
          • Reply as topic
          Log in to reply
          • Oldest to Newest
          • Newest to Oldest
          • Most Votes


          18

          Online

          11.7k

          Users

          11.2k

          Topics

          113.1k

          Posts


          Copyright 2025 TBD   |   Forum Guidelines   |   Privacy Policy   |   Terms of Service
          • Login

          • Don't have an account? Register

          • Login or register to search.
          • First post
            Last post
          0
          • MySensors
          • OpenHardware.io
          • Categories
          • Recent
          • Tags
          • Popular