Dimmer and automaticly turn "on" and "off" the light



  • Hello,

    I have dimmer code wchitch allow turn "on" or "off" the light from switch or domoticz when light level is ">" or "<" 350.
    I wont that light when is "on" and light level change from < 350 to > 350 light automaticly "off" and sen information to domoticz but I cant do that 😞
    I have something like this but this only send information to domoticz and no change lighgt status.
    Sorry this change light status but only from "on" to "off", when light level change to < 350 light turn "on" and I dont know why for a moment turn "off"

    
    void autolight()
    {
      if (analogRead(photoPin) > 350 &&  analogRead(LED_PIN) > 0)
      {//Turn "off" the light
        analogWrite(LED_PIN,0);
      
        gw.send(dimmerMsg.set(0), true);
                             return;
      }
      else if (analogRead(photoPin) < 350 &&  analogRead(LED_PIN) == 0)
      {// Turn "on" the light
        analogWrite(LED_PIN,100);
      
        gw.send(dimmerMsg.set(100), true);
                             return;
        }
    }
    void incomingMessage(const MyMessage &message)
    {
    if (message.type == V_LIGHT) {
      
      if (analogRead(photoPin) < 350) {
                       // Incoming on/off command sent from controller ("1" or "0")
                             int lightState = message.getString()[0] == '1';
                             int newLevel = 0;
                                if (lightState==LIGHT_ON) {
                                   // Pick up last saved dimmer level from the eeprom
                                   newLevel = loadLevelState(EEPROM_DIM_LEVEL_SAVE);
                                } 
                       // Send dimmer level back to controller with ack enabled
                             gw.send(dimmerMsg.set(newLevel), true);
                       // We do not change any levels here until ack comes back from gateway 
                             return;
      } else {
                             gw.send(dimmerMsg.set(0), true);
                             return;
         }
    
    } else if (message.type == V_DIMMER) {
        
      if (analogRead(photoPin) < 350) {
                       // Incoming dim-level command sent from controller (or ack message)
                             fadeTo = atoi(message.getString(convBuffer));
                       // Save received dim value to eeprom (unless turned off). Will be
                       // retreived when a on command comes in
                             if (fadeTo != 0)
                                    saveLevelState(EEPROM_DIM_LEVEL_SAVE, fadeTo);
      } else {
                             gw.send(dimmerMsg.set(0), true);
                             return;
      }
     }```

  • Hero Member

    @jacek In your icomingMessage routine, it looks you have no code to turn the light off, although I might be misinterpreting it.

    Cheers
    Al



  • Sorry it' s complite incomingMessages code:

    void incomingMessage(const MyMessage &message)
    {
    if (message.type == V_LIGHT) {
      
      if (analogRead(photoPin) < 350) {
                       // Incoming on/off command sent from controller ("1" or "0")
                             int lightState = message.getString()[0] == '1';
                             int newLevel = 0;
                                if (lightState==LIGHT_ON) {
                                   // Pick up last saved dimmer level from the eeprom
                                   newLevel = loadLevelState(EEPROM_DIM_LEVEL_SAVE);
                                } 
                       // Send dimmer level back to controller with ack enabled
                             gw.send(dimmerMsg.set(newLevel), true);
                       // We do not change any levels here until ack comes back from gateway 
                             return;
      } else {
                             gw.send(dimmerMsg.set(0), true);
                             return;
         }
    
    } else if (message.type == V_DIMMER) {
        
      if (analogRead(photoPin) < 350) {
                       // Incoming dim-level command sent from controller (or ack message)
                             fadeTo = atoi(message.getString(convBuffer));
                       // Save received dim value to eeprom (unless turned off). Will be
                       // retreived when a on command comes in
                             if (fadeTo != 0)
                                    saveLevelState(EEPROM_DIM_LEVEL_SAVE, fadeTo);
      } else {
                             gw.send(dimmerMsg.set(0), true);
                             return;
      }
     }
      saveLevelState(EEPROM_DIM_LEVEL_LAST, fadeTo);
      
      Serial.print("New light level received: ");
      Serial.println(fadeTo);
    
      if (!changedByKnob) 
        knob.write(fadeTo); 
        
      // Cancel send if user turns knob while message comes in
      changedByKnob = false;
      sendDimValue = false;
    
      // Stard fading to new light level
      startFade();
    }
    

  • Hero Member

    @jacek It looks like you have an endless loop to me,
    To initiate turning off the light due to a high ambient level, you call gw.send(dimmerMsg.set(0), true); which will instruct domoticz to send a command back which should be acted upon in your incomingMessage routine. In that routine, if the ambient light level is high, you send the same command back to domoticz: gw.send(dimmerMsg.set(0), true);. It's not clear to me what the rest of the functions after that do but they won't be executed due to your return command. What does the serial output show when high ambient light triggers this?



  • You have right ist loop but I do not know where 🙂

    This is complit code:

    
    #include <SPI.h>
    #include <Encoder.h>
    #include <MySensor.h>  
    #include <Bounce2.h>
    #include <DallasTemperature.h>
    #include <OneWire.h>
    
    #define COMPARE_TEMP 1 // Send temperature only if changed? 1 = Yes 0 = No
    #define ONE_WIRE_BUS 19 // Pin where dallase sensor is connected 
    #define MAX_ATTACHED_DS18B20 1
    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 the oneWire reference to Dallas Temperature. 
    
    #define LED_PIN 3           // Arduino pin attached to MOSFET Gate pin
    #define KNOB_ENC_PIN_1 4    // Rotary encoder input pin 1
    #define KNOB_ENC_PIN_2 5    // Rotary encoder input pin 2
    #define KNOB_BUTTON_PIN 6   // Rotary encoder button pin
    #define photoPin A6         // Fotorezystor 
    #define FADE_DELAY 10       // Delay in ms for each percentage fade up/down (10ms = 1s full-range dim)
    #define SEND_THROTTLE_DELAY 400 // Number of milliseconds before sending after user stops turning knob
    #define SN "DimmableLED /w button"
    #define SV "1.2"
    
    #define CHILD_ID_LIGHT 12
    #define ID 11
    #define EEPROM_DIM_LEVEL_LAST 1
    #define EEPROM_DIM_LEVEL_SAVE 2
    
    #define LIGHT_OFF 0
    #define LIGHT_ON 1
    
    
    int dimValue;
    int fadeTo;
    int fadeDelta;
    int persons;
    byte oldButtonVal;
    bool changedByKnob=false;
    bool sendDimValue=false;
    unsigned long lastFadeStep;
    unsigned long sendDimTimeout;
    char convBuffer[10];
    
    float lastTemperature[MAX_ATTACHED_DS18B20];
    int numSensors=0;
    boolean receivedConfig = false;
    boolean metric = true;
    
    unsigned long on = 0;
    unsigned long onT = 0;
    
    MySensor gw;
    
    // Initialize temperature message
    MyMessage msg(0,V_TEMP);
    MyMessage dimmerMsg(CHILD_ID_LIGHT, V_DIMMER);
    MyMessage msgl(0, V_LIGHT_LEVEL);
    
    ////WENT
    //Relay Relays[noRelays]; 
    //Bounce debouncer1[noRelays];
    //MyMessage msg1[noRelays];
    ////END
    Encoder knob(KNOB_ENC_PIN_1, KNOB_ENC_PIN_2);  
    Bounce debouncer = Bounce(); 
    int lastLightLevel;
    
    void setup()  
    { 
      
       // The third argument enables repeater mode.
    //  gw.begin(NULL, AUTO, true);
    
      //Send the sensor node sketch version information to the gateway
     // gw.sendSketchInfo("Repeater Node", "1.0");
    
    
      
      // Set knob button pin as input (with debounce)
      pinMode(KNOB_BUTTON_PIN, INPUT);
      pinMode(photoPin, INPUT);
      digitalWrite(KNOB_BUTTON_PIN, HIGH);
      debouncer.attach(KNOB_BUTTON_PIN);
      debouncer.interval(5);
      oldButtonVal = debouncer.read();
    
      // Set analog led pin to off
      analogWrite( LED_PIN, 0);
    
      // Init mysensors library
      gw.begin(incomingMessage, ID, true);
    
      // Send the Sketch Version Information to the Gateway
      gw.present(CHILD_ID_LIGHT, S_DIMMER);
      
      gw.sendSketchInfo(SN, SV);
      gw.sendSketchInfo("Repeater Node", "1.0");
      // Retreive our last dim levels from the eprom
      fadeTo = dimValue = 0;
      byte oldLevel = 0;
      Serial.print("Sending in last known light level to controller: ");
      Serial.println(oldLevel);  
      gw.send(dimmerMsg.set(oldLevel), true);   
    
      Serial.println("Ready to receive messages..."); 
    
       // Startup up the OneWire library
      sensors.begin();
      // requestTemperatures() will not block current thread
      sensors.setWaitForConversion(false);
      // Fetch the number of attached temperature sensors  
      numSensors = sensors.getDeviceCount();
    
      // Present all sensors to controller
      for (int i=0; i<numSensors && i<MAX_ATTACHED_DS18B20; i++) {   
         gw.present(i, S_TEMP);
         
      }
      gw.present(15, S_LIGHT_LEVEL);
    
    }
    
    void loop()      
    {
      // Process incoming messages (like config and light state from controller)
      gw.process();
    
      // Sprawdzenie temperatury
      CheckTemp();
      onT = onT + 1;
      on = on + 1;
      if (on > 401 + 2*ID) {
      // Poziom swiata
      lightLevel();
      on = 0;
      }
    
      if (analogRead(photoPin) > 350) { persons = 0;} else {persons = 1;}
        
      // Check if someone has pressed the knob button
      checkButtonClick();
      
      // Fade light to new dim value
      fadeStep();
    
       //Autolight
      autolight();
    }
    
    void autolight()
    {
      if (analogRead(photoPin) > 350 &&  analogRead(LED_PIN) > 0)
      {//Turn "off" the light
        analogWrite(LED_PIN,0);
      
        gw.send(dimmerMsg.set(0), true);
                             return;
      }
      else if (analogRead(photoPin) < 350 &&  analogRead(LED_PIN) == 0)
      {// Turn "on" the light
       // analogWrite(LED_PIN,100);
      
        gw.send(dimmerMsg.set(0), true);
                             return;
        }
    }
    
    void lightLevel()
    {
    int lightLevel = (analogRead(photoPin)); 
      Serial.println(lightLevel);
      if (lightLevel != lastLightLevel) {
          gw.send(msgl.set(lightLevel));
          lastLightLevel = lightLevel;
      }
    }
    
    
    void CheckTemp()
    {
    
    // Fetch temperatures from Dallas sensors
      sensors.requestTemperatures();
      
      // Read temperatures and send them to controller 
      for (int i=0; i<numSensors && i<MAX_ATTACHED_DS18B20; i++) {
     
        // Fetch and round temperature to one decimal
        float temperature = static_cast<float>(static_cast<int>((gw.getConfig().isMetric?sensors.getTempCByIndex(i):sensors.getTempFByIndex(i)) * 10.)) / 10.;
     
        // Only send data if temperature has changed and no error
        #if COMPARE_TEMP == 1
        if (lastTemperature[i] != temperature && temperature != -127.00 && temperature != 85.00) {
        #else
        if (temperature != -127.00 && temperature != 85.00) {
        #endif
          
              if (onT > 400 + 2*ID) {
          // Send in the new temperature
          gw.send(msg.setSensor(i).set(temperature,1));
             onT = 0; }
          // Save new temperatures for next compare
          lastTemperature[i]=temperature;
        }
      }
      
    }
    
    
    
    
    void incomingMessage(const MyMessage &message)
    {
      if (message.type == V_LIGHT) {
      
         if (analogRead(photoPin) < 350) {
        // Incoming on/off command sent from controller ("1" or "0")
        int lightState = message.getString()[0] == '1';
        int newLevel = 0;
        if (lightState==LIGHT_ON) {
          // Pick up last saved dimmer level from the eeprom
          newLevel = loadLevelState(EEPROM_DIM_LEVEL_SAVE);
        } 
        // Send dimmer level back to controller with ack enabled
        gw.send(dimmerMsg.set(newLevel), true);
        // We do not change any levels here until ack comes back from gateway 
        return;
         } else {
    
          gw.send(dimmerMsg.set(0), true);
          return;
         }
    
      } else if (message.type == V_DIMMER) {
        
    if (analogRead(photoPin) < 350) {
        // Incoming dim-level command sent from controller (or ack message)
        fadeTo = atoi(message.getString(convBuffer));
        // Save received dim value to eeprom (unless turned off). Will be
        // retreived when a on command comes in
        if (fadeTo != 0)
          saveLevelState(EEPROM_DIM_LEVEL_SAVE, fadeTo);
      } else {
        gw.send(dimmerMsg.set(0), true);
          return;
      }
      }
      saveLevelState(EEPROM_DIM_LEVEL_LAST, fadeTo);
      
      Serial.print("New light level received: ");
      Serial.println(fadeTo);
    
      if (!changedByKnob) 
        knob.write(fadeTo); 
        
      // Cancel send if user turns knob while message comes in
      changedByKnob = false;
      sendDimValue = false;
    
      // Stard fading to new light level
      startFade(); 
    }
    
    
    void checkButtonClick()
    {
    if ( persons == 1 ) {
      debouncer.update();
      byte buttonVal = debouncer.read();
      byte newLevel = 0;
      if (buttonVal != oldButtonVal && buttonVal == LOW) {
        if (dimValue==0) {
          // Turn on light. Set the level to last saved dim value
         // int saved = loadLevelState(EEPROM_DIM_LEVEL_SAVE);
         int saved = 100;
          newLevel = saved > 0 ? saved : 100;
        }
        gw.send(dimmerMsg.set(newLevel),true);
      }
      oldButtonVal = buttonVal;
     }
    }
    
    void startFade() {
      fadeDelta = ( fadeTo - dimValue ) < 0 ? -1 : 1;
      lastFadeStep = millis();
    }
    
    // This method provides a graceful none-blocking fade up/down effect
    void fadeStep() {
      
      unsigned long currentTime  = millis();
      if ( dimValue != fadeTo && currentTime > lastFadeStep + FADE_DELAY) {
        dimValue += fadeDelta;
        analogWrite( LED_PIN, (int)(dimValue / 100. * 255) );
        lastFadeStep = currentTime;
        
        Serial.print("Fading level: ");
        Serial.println(dimValue);
    
        if (fadeTo == dimValue && changedByKnob) {
          sendDimValue = true;
          sendDimTimeout = currentTime;
        }
      } 
      // Wait a few millisecs before sending in new value (if user still turns the knob)
      if (sendDimValue && currentTime > sendDimTimeout + SEND_THROTTLE_DELAY)  {
         // We're done fading.. send in new dim-value to controller.
         // Send in new dim value with ack (will be picked up in incomingMessage) 
        gw.send(dimmerMsg.set(dimValue), true); // Send new dimmer value and request ack back
        sendDimValue = false;
      }
    }
    
    // Make sure only to store/fetch values in the range 0-100 from eeprom
    int loadLevelState(byte pos) {
      return min(max(gw.loadState(pos),0),100);
    }
    void saveLevelState(byte pos, byte data) {
      gw.saveState(pos,min(max(data,0),100));
    }
    
    
    
    

  • Hero Member

    @jacek As I mentioned, you call gw.send(dimmerMsg.set(0), true); again in the incomingMessage routine. By doing that, you are asking Domoticz to send another off command. Instead you should have a command there to actually set the dim level on the pins to the value that you want. I'm not too familiar with this code, but looking at it, you should just save the new state there and then continue with the routine, rather than calling return;

    Cheers
    Al


  • Contest Winner

    @jacek By the looks of your code you're doing the following.

    1. Domoticz sends a command to your Node.
    2. You ignore the value and assign 0 as the value.
    3. You send the new value - which is allways 0 - to domoticz.

    So basically you turn off the lamp no matter what the command is what Domoticz is sending to the node.

    At least that's what I think. But I'm a bit tired have been studying for too many hours today 😉


Log in to reply
 

Suggested Topics

10
Online

11.4k
Users

11.1k
Topics

112.7k
Posts