Arduino Mega gw wired directly via USB to HASS.IO?



  • I swear I've spend hours pouring over the documentation and the forums, but I simply cannot find a straight or working answer for this.

    I'd like to use an Arduino Mega as both a gateway AND use its pins as sensors/switches, and I'd like to connect it directly to a Raspberry Pi 3 B+ running Home Assistant (hass.io) and use Home Assistant as the controller.

    I know 98% of peoples uses cases are wireless, so they involve radios, but mine is all wired and I'd like to do it as I describe.

    As far as I can tell, this involves Serial communication somehow, but its not exactly clear either how to initialize MySensors gateway sketch to communicate over the USB port much less how that is accessed on the USB host device.

    Can someone please point me in the right direction for what I'd like to do? Any help would be greatly appreciated.


  • Mod

    Hin@servo386, welcome to the forum!

    Yes, you are on the right track. In MySensors terminology, the Mega becomes a serial gateway with locally attached sensors.

    Build a serial gateway as described on https://www.mysensors.org/build/serial_gateway but comment out #define MY_RADIO_RF24 since you don't need any other sensor nodes.

    In the serial gateway example, add code for your locally attached sensors, just as if you were building a "normal" MySensors node.

    Upload the sketch to the mega, with debug turned on, and make sure the mega is able to read the sensors.

    Connect the mega to the controller computer over usb. Add it to Hass following the instructions linked in "plugin and install instructions" at https://www.mysensors.org/controller/homeassistant



  • Thank you so much! I've got the example "door open/door close" dummy sensor sketch succesfully talking to my HASS.IO.

    I'm literally going to type this sentence so that people might find this later in a forum search if they are looking like I was for an answer: direct to USB, wired USB, hass.io arduino mega, serial gateway no radio, local sensor no radio serial gateway usb.

    Sorry for that but i was tearing my hair out looking for this simple solution and could not find it.

    The trick is to comment out the RF radios (all of them). It wasn't clear to me that blanking out all the radios meant it would still do serial. The part to config on the HASS seemed clear to me (/dev/ttyACM0) but since I couldn't get the gateway part to work I had no idea if that was even right.

    Again, thanks so much.


  • Mod

    @servo386 great work, thanks for reporting back!



  • Could I bother you to ask:

    Now that I've made my fake door open and close a bunch, is there an example that shows the initializing and presenting of multiple local sensors (local to the gateway) and what that looks like?

    I tried to simply put another present(2, S_DOOR) as child 2 and another door but.. I dont think HA see's it. Am i approaching this wrong?

    Also, does sendSketchInfo have to be done for every sensor local to the gateway or is it just presenting the one name under which all the sensors will be "children" ?

    Any help would be appreciated.


  • Mod

    @servo386 there can be many present() but only one sendsketchinfo



  • Thanks! I have successfully created TWO dummy doors now! lol

    This was instructive to understanding how the presentation of multiple local sensors looks like, since most examples show only one.

    My next task is to learn how to control a switch (ie two way communication)

    Here it is for anyone else for whom this might be helpful:

    #include <MySensors.h>
    
    #define OPEN_DOORONE 1
    #define CLOSE_DOORONE 0
    #define CLOSE_DOORTWO 0
    #define OPEN_DOORTWO 1
    #define DOORONE_ID 1
    #define DOORTWO_ID 2
    
    MyMessage msg1(DOORONE_ID, V_TRIPPED);
    MyMessage msg2(DOORTWO_ID, V_TRIPPED);
    
    
    uint8_t value_doorone = OPEN_DOORONE;
    uint8_t value_doortwo = OPEN_DOORTWO;
    
    void setup()
    {
    	// Setup locally attached sensors
    }
    
    void presentation()
    {
    	// Present locally attached sensors
     sendSketchInfo("JERTestDoorsss", "1.0");
     present(DOORONE_ID, S_DOOR);
     present(DOORTWO_ID, S_DOOR);
    }
    
    void loop()
    {
    	// Send locally attached sensor data here
    
      value_doorone = value_doorone == OPEN_DOORONE ? CLOSE_DOORONE : OPEN_DOORONE;
      send(msg1.set(value_doorone));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      
    }
    


  • So trying to activate a switch (by reading the state of a binary value) does not seem to be working.

    With this code, my 2 fake doors show up in Home Assistant, but my S_BINARY does not, despite presenting it. Am I missing something?

    
    #include <MySensors.h>
    
    #define OPEN_DOORONE 1
    #define CLOSE_DOORONE 0
    #define CLOSE_DOORTWO 0
    #define OPEN_DOORTWO 1
    #define DOORONE_ID 1
    #define DOORTWO_ID 2
    #define LEDSWITCH_ID 3
    
    #define RELAY_PIN 11
    #define RELAY_ON 1
    #define RELAY_OFF 0
    
    
    
    MyMessage msg1(DOORONE_ID, V_TRIPPED);
    MyMessage msg2(DOORTWO_ID, V_TRIPPED);
    
    
    uint8_t value_doorone = OPEN_DOORONE;
    uint8_t value_doortwo = OPEN_DOORTWO;
    bool state;
    
    void before()
    {
      pinMode(RELAY_PIN, OUTPUT);
      digitalWrite(RELAY_PIN, RELAY_OFF);
    }
    
    void setup()
    {
    	// Setup locally attached sensors
    }
    
    void presentation()
    {
    	// Present locally attached sensors
     sendSketchInfo("JERTestDoorsss", "1.0");
     present(DOORONE_ID, S_DOOR);
     present(DOORTWO_ID, S_DOOR);
     present(LEDSWITCH_ID, S_BINARY);
    }
    
    void loop()
    {
    	// Send locally attached sensor data here
    
      value_doorone = value_doorone == OPEN_DOORONE ? CLOSE_DOORONE : OPEN_DOORONE;
      send(msg1.set(value_doorone));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      value_doortwo = value_doortwo == OPEN_DOORTWO ? CLOSE_DOORTWO : OPEN_DOORTWO;
      send(msg2.set(value_doortwo));
      sleep(2000);
      
    }
    
    void receive(const MyMessage &message)
    {
      if (message.type == V_STATUS)
      {
        state = message.getBool();
        digitalWrite(RELAY_PIN, state?RELAY_ON:RELAY_OFF);
      }
    }```


  • Not even just using the example relay code works. destined output pin is permanently on (HIGH) and activating the switch in controller has no effect on it.

    Help please....


  • Mod

    @servo386 when the node is sleeping, it can not receive messages. Use wait() instead.

    When troubleshooting, the debug output is where you'll se what is happening.



  • Hi servo. Below is my sketch that works in Home Assistant (DHT, reed, relay, motion sensors). It has only problem with multiple DHT but I'm working on it.

    When connecting via USB use: #define MY_GATEWAY_SERIAL

    // Enable debug prints to serial monitor
    #define MY_DEBUG
    
    // Enable serial gateway
    #define MY_GATEWAY_SERIAL
    
    // Define a lower baud rate for Arduino's running on 8 MHz (Arduino Pro Mini 3.3V & SenseBender)
    #if F_CPU == 8000000L
    #define MY_BAUD_RATE 38400
    #endif
    
    // Enable inclusion mode
    #define MY_INCLUSION_MODE_FEATURE
    // Enable Inclusion mode button on gateway
    #define MY_INCLUSION_BUTTON_FEATURE
    
    // Inverses behavior of inclusion button (if using external pullup)
    //#define MY_INCLUSION_BUTTON_EXTERNAL_PULLUP
    
    // Set inclusion mode duration (in seconds)
    #define MY_INCLUSION_MODE_DURATION 60 
    // Digital pin used for inclusion mode button
    #define MY_INCLUSION_MODE_BUTTON_PIN  3 
    
    #include <SPI.h>
    #include <MySensors.h>  
    #include <Bounce2.h>
    #include <DHT.h> // DHT11, DHT22 sensors
    
    // ------- PINS DEFINITION
    
    // RELAYS
    // Arduino Digital I/O pin number for first relay (second on pin+1 etc)
    // Relay for first floor - 10 pcs (Przelaczniki SSR - pierwsze pietro)
    #define RELAY_PIN_1 22
    
    // Buttons for Relays - to use normal wall switches (Przyciski / laczniki scienne - pierwsze pietro)
    #define BUTTON_PIN A0 
    
    #define NUMBER_OF_RELAYS 10 // 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
    
    // Arduino Digital I/O pin for button/reed switch
    // Reeds 
    #define REED_PIN_1 5
    
    
    // PIR  SENSORS
    uint32_t SLEEP_TIME = 1000; // 120000; // Sleep time between reports (in milliseconds)
    #define DIGITAL_INPUT_SENSOR1 22   // The digital input you attached your motion sensor.  (Only 2 and 3 generates interrupt!)
    #define DIGITAL_INPUT_SENSOR2 23
    #define SLEEP_NODE true
    
    // DHT22
    #define DHTPIN 4        // Broche sur laquelle est branché le DHT / what pin we're connected to
    #define DHTTYPE DHT22   // DHT 22  (AM2302), DHT11
    
    #define DHTPIN2 24        // Broche sur laquelle est branché le DHT / what pin we're connected to
    #define DHTTYPE2 DHT22   // DHT 22  (AM2302), DHT11
    
    #define DHTPIN3 25        // Broche sur laquelle est branché le DHT / what pin we're connected to
    #define DHTTYPE3 DHT22   // DHT 22  (AM2302), DHT11
    
    // ------- Data for Motion sensor
    
    int oldValueA = 0;
    int oldValueB = 0;
    
    bool stateA = false;
    bool stateB = false;
    
    unsigned long timeDHT1 = 30000; // 30 seconds
    unsigned long timeDHT2 = 31000; // 30 seconds
    unsigned long timeDHT3 = 32000; // 30 seconds
    
    unsigned long actualTime = 0;
    unsigned long recentTimeHum1 = 0;
    
    unsigned long actualTime2 = 0;
    unsigned long recentTimeHum2 = 0;
    
    unsigned long actualTime3 = 0;
    
    unsigned long recentTimeHum3 = 0;
    
    // Initialize DHT sensor
    float lastTemp;
    float lastTemp2;
    float lastTemp3;
    
    float lastHum;
    float lastHum2;
    float lastHum3;
    
    boolean metric = true;
    
    // for reed switch
    int oldValue=-1;
    
    bool state = false;
    
    // Relay for save state inside Arduino's EEPROM
    bool loadedState1 = false;
    
    bool initialValueSent = false;
    
    // ------- CHILD IDs 
    
    // REEDS
    #define CHILD_ID_REED1 0   // Id of the sensor child
    
    // Define CHILD_IDs
    #define CHILD_ID_TEMP1 1 // Id of the sensor child
    #define CHILD_ID_HUM1 2 // Id of the sensor child
    
    #define CHILD_ID_MOTION1 3   // Id of the sensor child
    #define CHILD_ID_MOTION2 4 // Id of the sensor child
    
    #define CHILD_ID_RELAY1 5 // Id of the sensor child
    
    #define CHILD_ID_TEMP2 6 // Id of the sensor child
    #define CHILD_ID_HUM2 7 // Id of the sensor child
    
    #define CHILD_ID_TEMP3 8 // Id of the sensor child
    #define CHILD_ID_HUM3 9 // Id of the sensor child
    
    // ------- 
    
    void before()
    {
      for (int sensor=1, pin=RELAY_PIN_1; 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);
      }
    }
    
    // Reed switches needs debouncers
    Bounce debouncer_reed1 = Bounce();
    
    //Relays switched - don't need debouncers
    Bounce debouncer_relay1 = Bounce();
    Bounce debouncer = Bounce();
    
    // Debouncer for Motion sensor
    Bounce debouncerA = Bounce();
    Bounce debouncerB = Bounce();
    
    // Initialize Relay
    MyMessage msg(CHILD_ID_RELAY1, V_STATUS);
    
    // Initialize reed switches
    MyMessage msgReed1(CHILD_ID_REED1, V_TRIPPED);
    
    
    // Initialize DHT22
    MyMessage msgTemp(CHILD_ID_TEMP1, V_TEMP);
    MyMessage msgHum(CHILD_ID_HUM1, V_HUM);
    
    MyMessage msgTemp2(CHILD_ID_TEMP2, V_TEMP);
    MyMessage msgHum2(CHILD_ID_HUM2, V_HUM);
    
    MyMessage msgTemp3(CHILD_ID_TEMP3, V_TEMP);
    MyMessage msgHum3(CHILD_ID_HUM3, V_HUM);
    
    // Initialize motion message
    MyMessage msg_motion1(CHILD_ID_MOTION1, V_TRIPPED);
    MyMessage msg_motion2(CHILD_ID_MOTION2, V_TRIPPED);
    
    
    void setup() {
    
       // Setup locally attached sensors
      delay(100); 
    
       // Setup the button.
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      // After setting up the button, setup debouncer.
      debouncer.attach(BUTTON_PIN);
      debouncer.interval(5);
      debouncer_relay1.attach(RELAY_PIN_1);
      debouncer_relay1.interval(5);
      // Setup the button
      pinMode(REED_PIN_1,INPUT_PULLUP);
      debouncer_reed1.attach(REED_PIN_1);
      debouncer_reed1.interval(10);
     
      // Make sure relays are off when starting up
      digitalWrite(RELAY_PIN_1, RELAY_OFF);
      // Then set relay pins in output mode
      pinMode(RELAY_PIN_1, OUTPUT);
    
      // Set relay to last known state (using eeprom storage) 
      loadedState1 = loadState(CHILD_ID_RELAY1);
    
      
      // setup debouncer for Reed switch
      debouncer_reed1.attach(REED_PIN_1);
      debouncer_reed1.interval(5);
    
      pinMode(REED_PIN_1,INPUT);
      digitalWrite(REED_PIN_1,HIGH);
    
      // Setup PIR Motion sensor "button"
      pinMode(DIGITAL_INPUT_SENSOR1, INPUT_PULLUP); // Setup the button Activate internal pull-up
      pinMode(DIGITAL_INPUT_SENSOR2, INPUT_PULLUP); //  sets the motion sensor digital pin as input / Setup the button Activate internal pull-up
      
        // setup debouncer for motion sensor
      debouncerA.attach(DIGITAL_INPUT_SENSOR1);
      debouncerA.interval(5);
    
      debouncerB.attach(DIGITAL_INPUT_SENSOR2);
      debouncerB.interval(5);
      
    }
    
    void presentation()  {
      sendSketchInfo("Arduino5", "1.0");
      
      // Register all sensors to gw (gateway - they will be created as child devices)
      present(CHILD_ID_RELAY1, S_BINARY);
      
      present(CHILD_ID_REED1, S_DOOR);  
    
      present(CHILD_ID_TEMP1, S_TEMP);
      present(CHILD_ID_HUM1, S_HUM);
      
      present(CHILD_ID_TEMP2, S_TEMP);
      present(CHILD_ID_HUM2, S_HUM);
      
      present(CHILD_ID_TEMP3, S_TEMP);
      present(CHILD_ID_HUM3, S_HUM);  
      
      present(CHILD_ID_MOTION1, S_MOTION);
      present(CHILD_ID_MOTION2, S_MOTION);
    
    }
    
    void loop() {
    
    actualTime = millis();
    
      // --- DHT22 SENSOR1 
      if (actualTime - recentTimeHum1 >= timeDHT1) {
    
        recentTimeHum1 = actualTime;
        // DHT sensor
        DHT dht(DHTPIN, DHTTYPE); // Creation of a dht object in the loop otherwise the values are not measured on awakening
        float temperature = dht.readTemperature();
        float humidity = dht.readHumidity();
        if (isnan(temperature)) {
          //Serial.println("Cannot read DHT temperature");
        } else {
          if (temperature != lastTemp) {
            lastTemp = temperature;
            if (!metric) {
              temperature = dht.readTemperature(true);
            }
    
            //Serial.print("T: ");
            //Serial.print(temperature);
            //Serial.print(" | H: ");
            //Serial.println(humidity);
            send(msgTemp.set(temperature, 1));
            send(msgHum.set(humidity, 1));
          } else {
            //Serial.println("Temperature doesn't change => don't update changes");
            //Serial.print("T: ");
            //Serial.print(temperature);
            //Serial.print(" | H: ");
            //Serial.println(humidity);
            send(msgTemp.set(temperature, 1));
            send(msgHum.set(humidity, 1));
          }
        }
    
      }    
      // --- DHT22 SENSOR END
    
      // --- DHT22 SENSOR2
      if (actualTime2 - recentTimeHum2 >= timeDHT2) {
    
        recentTimeHum2 = actualTime2;
        // DHT2 sensor
        DHT dht2(DHTPIN2, DHTTYPE2); // Creation of a dht object in the loop otherwise the values are not measured on awakening
        float temperature2 = dht2.readTemperature();
        float humidity2 = dht2.readHumidity();
        if (isnan(temperature2)) {
          //Serial.println("Cannot read DHT temperature");
        } else {
          if (temperature2 != lastTemp2) {
            lastTemp2 = temperature2;
            if (!metric) {
              temperature2 = dht2.readTemperature(true);
            }
    
            send(msgTemp2.set(temperature2, 1));
            send(msgHum2.set(humidity2, 1));
          } else {
            send(msgTemp2.set(temperature2, 1));
            send(msgHum2.set(humidity2, 1));
          }
        }
    
      }    
      // --- DHT22 SENSOR END
    
      // --- DHT22 SENSOR2
      if (actualTime3 - recentTimeHum3 >= timeDHT3) {
    
        recentTimeHum3 = actualTime3;
        // DHT3 sensor
        DHT dht3(DHTPIN3, DHTTYPE3); // Creation of a dht object in the loop otherwise the values are not measured on awakening
        float temperature3 = dht3.readTemperature();
        float humidity3 = dht3.readHumidity();
        if (isnan(temperature3)) {
          //Serial.println("Cannot read DHT temperature");
        } else {
          if (temperature3 != lastTemp3) {
            lastTemp3 = temperature3;
            if (!metric) {
              temperature3 = dht3.readTemperature(true);
            }
    
            send(msgTemp3.set(temperature3, 1));
            send(msgHum3.set(humidity3, 1));
          } else {
            send(msgTemp3.set(temperature3, 1));
            send(msgHum3.set(humidity3, 1));
          }
        }
    
      }    
      // --- DHT22 SENSOR END
    
      // ---- MOTION SENSOR START
    
      debouncerA.update();
      // Get the update value
      int valueA = debouncerA.read();
    
      if (valueA != oldValueA) {
        // Send in the new value
        send(msg_motion1.set(valueA == HIGH ? 1 : 0)); // Send tripped value to gw
        oldValueA = valueA;
        wait(5);
      }    
    
      debouncerB.update();
      // Get the update value
      int valueB = debouncerB.read();
    
      if (valueB != oldValueB) {
        // Send in the new value
        send(msg_motion2.set(valueB == HIGH ? 1 : 0)); // Send tripped value to gw
        oldValueB = valueB;
        wait(5);
      }  
    
     // --- MOTION SENSOR END
     
      if (!initialValueSent) {
        //Serial.println("Sending initial value");
        send(msg.set(loadedState1?RELAY_ON:RELAY_OFF));
        //Serial.println("Requesting initial value from controller");
    
      // Reed Switch
        int value1 = debouncer_reed1.read();
        send(msgReed1.set(value1==HIGH ? 1 : 0));
        wait(5);
    
        request(CHILD_ID_RELAY1, V_STATUS);
        request(CHILD_ID_REED1, V_TRIPPED);
        
        wait(2000, C_SET, V_STATUS);
    
      }
    
      // Send locally attached sensor data here 
      if (debouncer.update()) {
        // Get the update value.
        int value = debouncer.read();
        // Send in the new value.
        if(value != oldValue){
             saveState(CHILD_ID_RELAY1, !loadState(CHILD_ID_RELAY1));
             digitalWrite(RELAY_PIN_1, loadState(CHILD_ID_RELAY1)?RELAY_ON:RELAY_OFF);
             send(msg.set(loadState(CHILD_ID_RELAY1)));
     
            oldValue = value;
        }
      }
    
    
    
       // Send locally attached sensor data here  
       if (debouncer_reed1.update()) {
          // reed
         // Get the update value
        int value = debouncer_reed1.read();
          if (value != oldValue) {
             // Send in the new value
             send(msgReed1.set(value==HIGH ? 1 : 0));
             oldValue = value;
          }
       }
    
          
    }
    
    void receive(const MyMessage &message) {
      if (message.isAck()) {
         //Serial.println("This is an ack from gateway");
      }
    
      if (message.type == V_STATUS) {
        if (!initialValueSent) {
          //Serial.println("Receiving initial value from controller");
          initialValueSent = true;
        }
    
        switch (message.sensor) {
          case CHILD_ID_RELAY1:
            loadedState1 =  message.getBool();
            digitalWrite(RELAY_PIN_1, loadedState1 ? RELAY_ON : RELAY_OFF);
            saveState(CHILD_ID_RELAY1, loadedState1);
            send(msg.set(loadedState1?RELAY_ON:RELAY_OFF));
            break;
    
    /*
          case CHILD_ID_RELAY2:
            loadedState2 = message.getBool();
            digitalWrite(RELAY_PIN_2, loadedState2 ? RELAY_ON : RELAY_OFF);
            saveState(CHILD_RELAY2, loadedState2);
            send(msg2.set(loadedState2?RELAY_ON:RELAY_OFF));
            break;
            */
        }
     /* Remove debug - not needed in Home Assistant
        // Write some debug info
        Serial.print("Incoming change for sensor:");
        Serial.print(message.sensor);
        Serial.print(", New status: ");
        Serial.println(message.getBool());
    */
    
      }
    
    }
    

Log in to reply
 

Suggested Topics

  • 3
  • 6
  • 2
  • 1

61
Online

11.4k
Users

11.1k
Topics

112.7k
Posts