RS485/RS232/Serial transport class for mysensors.org



  • Hi everyone !

    I needed a wired solution for my several nodes.
    Here is the serial rs485/rs232 wired network transport for mysensors.
    https://github.com/leodesigner/mysensors-serial-transport
    It is based on the Majenko ICSC serial library.
    Can you please test it? It is a beta version - but it is working for me.
    (However, I am still waiting for my rs485 boards to arrive)
    You can find more technical information at
    http://sourceforge.net/p/arduino-icsc/wiki/RS-485/

    To use it, you have to:

    1. Put SerialTransport.cpp and SerialTransport.h to folder/directory/path SerialTransport in your library.
    2. Add #include <SerialTransport.h> to your .ino sketch
    3. Replace transport class with:
      MyTransportSerial transport(Serial,0,-1); // serial port, node, dePin (-1 disabled)

    Please let me know about bugs and how it is working for you.


  • Hardware Contributor

    so cool 😃 it seems very interesting, and could be a nice addition. I will look at it. thx for share
    👍


  • Admin

    @LeoDesigner said:

    https://github.com/leodesigner/mysensors-serial-transport

    Great addition if you get this verified and running!


  • Hero Member

    Woah, nice!! I've thought about doing the same but didn't find the time.
    I will try to test, the RS485 are already lying on my desk.


  • Contest Winner

    I have to wait before my Guests will leave, but this is something I'm interested in. Will check it in a week or two. I want to have a sensor that checks whenever I lay in my bed. I'd preffer to transfer this kind of details wired and not wireless 😉



  • Testing this will be next thing in my todo-list. Just ordered needed parts 🙂



  • I just started a thread on using sensors without a radio. So this really caught my attention. Would it be possible to modify it to use the USB Serial interface for arduinos that have it?



  • @shabba I am not quite understood what exactly you want to do with USB. You can use arduino nano without any problems at all.
    All you have to do just to make sure to disconnect your RS485 bus from RX pin during the time when you will upload your sketch/firmware.
    Also it is possible to use this class without any converters at all. See attached simple schematics on github page.
    Regarding USB - you can attach an RS485-USB adapter to this bus as well too.
    So it is an universal solution for a serial communication between many arduinos via serial port. Please note about possibility to connect this bus to RPi directly. ICSC lib include the library for RPi too.
    Also, it's better to disable DEBUG option in mysensors config file to avoid additional traffic on the serial bus.



  • @LeoDesigner Sorry for not being clear. I was looking to connect my Arduino Mega (has about a dozen sensors and relays connected to it) to my existing RPi2 sensors serial gateway (using a UNO). I was hoping I could use a second USB/Serial port on the RPi2 to receive messages from the Mega.



  • @shabba Take a look to https://github.com/MajenkoLibraries/ICSC/tree/master/debian
    It may be a starting point for you. You can adopt this part of the ICSC library to your RPi2 setup.



  • Finally I am received my RS485 modules.
    Here is the working example of gateway with two nodes:

    RS485 Arduino transport for Mysensors.org – 00:14
    — Axel Vivaldi


  • Admin

    @LeoDesigner

    To test this I ordered a few of these..
    http://www.ebay.com/itm/381374599127?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

    Hope they are the correct model.



  • @hek
    My modules are from http://www.aliexpress.com/item/FREE-SHIPPING-5PCS-LOT-MAX485-module-RS485-module-TTL-turn-RS-485-module-MCU-development-accessories/1718665649.html
    They are the same as yours - based on MAX485.
    However, it is possible to run a simple TTL signal level bus on a short distances.
    (https://github.com/leodesigner/mysensors-serial-transport/blob/master/sch.png)


  • Admin

    @LeoDesigner

    I've incorporated a slimmed down of the RS485 transport layer in this branch (soon to be merged into development):

    https://github.com/mysensors/Arduino/tree/serial-transport/libraries/MySensors

    But I've still haven't received my RS485 modules... Do you have time to run a small test?

    Gateway:
    https://github.com/mysensors/Arduino/tree/serial-transport/libraries/MySensors/examples/GatewaySerialRS485

    And a test-motion sensor sketch:
    https://github.com/mysensors/Arduino/tree/serial-transport/libraries/MySensors/examples/MotionSensorRS485

    But you could use any example just replacing #define MY_RADIO_RF24 with #define MY_RS485

    I've used the AltSerial library for RS485 communication so we can cope with dual serial ports on the serial gateway. This library requires using pins documented in sketch.



  • @hek
    My example boxes are installed right now on the site and doing a daily job 🙂
    It will take time to build a new one. I may try a breadboard, but I am still busy to finish additional improvements to mysensors.org project. (I will share them later - it's will be interesting too - I hope 🙂 )

    Actually, it's easy to test RS485 transport without a RS485 converters - just use a simple schematics I have been talking before.
    Also, you may want to look to this: https://github.com/MajenkoLibraries/ICSC/pulls
    It's untested support for SoftwareSerial option for library.
    With AltSerial we will be forced to use only a documented pins.

    Anyway - I am glad to contribute a bit to great mysensors community.


  • Admin

    Thanks,

    @LeoDesigner said:

    With AltSerial we will be forced to use only a documented pins.

    Yes, I know. But AltSerial can handle higher speeds. I preferred that over the SoftwareSerial flexibility regarding pin selection. Hope I did the right choice 😉



  • @hek
    Speed is one of the reasons why I have decided to use hardware serial. 🙂
    But we should be flexible and universal as much as we can. I had been thinking also to add support for over the wire firmware update. As you have done with wireless.


  • Admin

    With a new bootloader? Using external flash+DualOptiBoot it should work already.



  • @hek
    Sure - but it can be possible done with standard bootloader - we just have to emulate standard Arduino sketch upload process on the gateway side. But I am not sure if it's possible to do with half duplex protocol. Just an idea.


  • Admin

    Interesting idea. Looking forward hearing about your results.


  • Admin

    @LeoDesigner

    If using the standard bootloader, wouldn't it break the FW update if one of the other nodes on the bus starts to transmit?



  • @tbowmo
    Node will listen RS485 bus before it will try to transmit anything (just like Ethernet).
    So other nodes will behave yourself 🙂
    But we have another difficulty: standard bootloader know nothing about TX/RX (dePin) management. So, we need to modify it to be able correctly emulate Arduino upload process. Maybe a simple schematics with diode will work in that case.
    I am still busy with other improvements.


  • Hero Member

    @hek I've tested your code and can't get it working yet.

    I've installed the gateway and a DHT22 sketch on two nanos and connected them directly via D8 and D9.

    // Enable RS485 transport layer
    #define MY_RS485
    
    // Set RS485 baud rate to use
    #define MY_RS485_BAUD_RATE 9600
    
    
    #include <MySensor.h>
    #include <DHT.h>  
    
    #define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway)
    #define CHILD_ID_HUM 0
    #define CHILD_ID_TEMP 1
    #define HUMIDITY_SENSOR_DIGITAL_PIN 3
    #define RS485_DE_PIN 4
    unsigned long SLEEP_TIME = 3000; // Sleep time between reads (in milliseconds)
    
    // Initialize motion message
    DHT dht;
    boolean metric = true; 
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    
    void setup()  
    {  
      dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN);
    }
    
    void presentation()  {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Humidity Sensor", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID_HUM, S_HUM);
      present(CHILD_ID_TEMP, S_TEMP);
    }
    
    void loop()     
    {     
      float temperature = dht.getTemperature();
      if (isnan(temperature)) {
          Serial.println("Failed reading temperature from DHT");
      } else  {
        send(msgTemp.set(temperature, 1));
        Serial.print("T: ");
        Serial.println(temperature);
      }
      
      float humidity = dht.getHumidity();
      if (isnan(humidity)) {
          Serial.println("Failed reading humidity from DHT");
      } else {
          send(msgHum.set(humidity, 1));
          Serial.print("H: ");
          Serial.println(humidity);
      }
      // Sleep until interrupt comes in on motion sensor. Send update every two minute. 
      sleep(SLEEP_TIME);
    }
    

    The sketch is working fine according to serial output. But nothing is seen on the gateway.

    So, to find out, where there is a problem, I connected my Programmer (mySmartUSB MK3) to D8/D9 of the sensor and I'm able to see that there is output but the chars are not readable so I tried different baudrates than 9600. That didn' help. What I can say is, that the output is generated every 3 seconds, so the ports are right.

    To make sure I'm not doing something wrong with the programmer, I connected it to D0/D1 and switched baudrate to 115200 and it shows the serial output as expected.

    Any idea where to look next?


  • Hero Member

    So, I've tried to further invest the problem and there is something wrong with _dev.write() in transportSend(). It is too much C-Kungfu for me but there is something wrong with the conversion of data.

    • _dev.write("bla") looks good in terminal
    • _dev.write(to) throws trash in the terminal
    • Serial.println(to) looks good in terminal

    Here is the output of the soft-serial:

    #���X��z
                   �Humidity Sensor��X
    ��
         �1.0�X��b�X��b�X
                                         ��*�������X
                                                         ��*�gfB�X
                                                                        ��*�������X
        ��*�gfB�X
                       
    

    Another thing:

    The management of the DE-Pin is missing right?


  • Admin

    to is a uint_t...so I guess it could generate trash in the terminal when showing the low ASCII values. Guess you'd have to use some other program to view the bytes sent.

    Yes, de-pin was stripped away. Would it be useful in your setup?

    (thankful for your help out testing it... I need some more time before I can setup a test rig)


  • Hero Member

    Holy crap ...
    It was too obvious. 😞

    Gateway can't work with this code:
    https://github.com/mysensors/Arduino/blob/development/libraries/MySensors/examples/GatewaySerialRS485/GatewaySerialRS485.ino

    #define MY_DEFAULT_ERR_LED_PIN 7  // Error led pin
    #define MY_DEFAULT_RX_LED_PIN  8  // Receive led pin
    #define MY_DEFAULT_TX_LED_PIN  9  // the PCB, on board LED
    

    @hek: Your code works!

    The de-pin is set to high if a node wants to send something, otherwise it is set to ground.
    I'll try to add that code.


  • Admin

    @TimO

    😊 I Sorry.. should have changed those pin assignments of course... I'll push an update ASAP.



  • @hek
    I am wondering why did you remove the code responsible for dePin management ?
    It's not possible to use MAX485 boards without tx/rx management.


  • Hero Member

    @LeoDesigner : yeah, you're right, that is needed.

    But there seems to be another problem, I can't get the current development code to work. I've simply interconnected two Nanos at D8/D9. The gateway and the motion example come up fine according to serial output and the motion sensor definiatly sends something via AltSerial but the gateway doesn't seem to recognize it.

    A simple test, where I pipe the input on hardware serial of one nano to AltSerial on the second nano and from there to hardware serial works just fine, so hardware and AltSerial is working.

    Sender:

    #include <AltSoftSerial.h>
    
    AltSoftSerial altSerial;
    
    void setup() {
      Serial.begin(115200);
      Serial.println("Demo begins");
    
      altSerial.begin(115200);
    
    }
    
    void loop() {
      char c;
    
      if (Serial.available()) {
        c = Serial.read();
        altSerial.print(c);
      }
    
    }
    

    Receiver:

    #include <AltSoftSerial.h>
    
    AltSoftSerial altSerial;
    
    void setup() {
      Serial.begin(115200);
      Serial.println("Demo begins");
    
      altSerial.begin(115200);
    
    }
    
    void loop() {
      char c;
    
      if (altSerial.available()) {
        c = altSerial.read();
        Serial.print(c);
      }
    
    }
    

  • Admin





  • @LeoDesigner

    I'm searching for a usb transport class, could i use this??

    I'd like to connect my arduino (with sensors/actuators connected to it) to my rasberrypi through usb, without the wireless part, but still see them as mysensors sensors.

    Is this possible or could someone make a transport class for it???



  • @MarkV
    Regarding the USB to RS485 adapters:
    I think they are using a some kind of serial to USB chip like CH340/341. So your RPi will be able to see RS485 bus as the regular serial port. It may work. It worth trying, you can always build an Ethernet GW later in other case.

    @shabba
    I am using exactly the same MAX485 modules. It is much more reliable media comparing to radio communication.

    @hek
    Thanks for adding DE pin management code.


  • Hardware Contributor

    hi.

    I am not sure if it can be useful.. I have read this note recently, about rs485 powering chip (3.3v or 5v). And I found this interesting, for knowledge..
    https://e2e.ti.com/support/interface/industrial_interface/f/142/t/93260
    So what I understand here, and it makes sense, is that : even if some rs485 chips are able to be powered with 3.3v or 5v, if you want to power it with 3.3v, it can work of course with a 5v chip, but it is better to use a true 3.3v chip only. Because they are more sensitive to be rs485 compliant (better internal transistor).

    Always good to know 😃



  • @TimO I cloned the current development branch, and tried to use a modified motion sketch, and a gateway sketch, simply interconnecting two mini-pros with TTL serial : the same problem appears.

    I can only see garbage sent on the AltSerial pins, so the gateway don't see the message.

    Before I dig more and start debugging, did anybody made progress on that problem ?


  • Hero Member

    @anti: I'm glad, I'm not the only one! 🙂
    I've tried to find the problem, but had no luck.

    What is bugging me: it was working with a early version, before it was merged into development, but I don't see any changes.

    I've not tested the latest / current version though.



  • Hi!

    Glad to see 'wired' version of MySensor protocol coming.
    One question - how long wires and how many sensors on one pair/multiple pairs will be supported?

    I'm thinking about cabling for new home, which means many meters of cable to every sensor/door/actuator/ligth/meter etc.

    In best scenario - one cat5e - one termination (sensor/node/etc.)
    Currently I'm looking for a cabled version of protocol to support it and be 101% stable (no hiccups and freezes over the protocol), so I can rely on my home.

    MySensors seems to be great to implement, but I'm worried about the signal... I was thinking about letting something around 12-24-30V thru one pair of Cat5 to power all nodes from one power-source (with backup batteries).

    Or - are there any better alternatives for RS485, that doesn't need resistors, have no limitations of 32 devices etc?



  • @andriej
    According to: https://en.wikipedia.org/wiki/RS-485
    "It offers data transmission speeds of 35 Mbit/s up to 10 m and 100 kbit/s at 1200 m. "
    also check this: https://www.maximintegrated.com/en/app-notes/index.mvp/id/367
    You may design a bus with up to 256 nodes.
    CAT5 is the best choice anyway for any type of communication (I mean you can run regular Ethernet on them too).
    Check the video at the beginning of the post. It's a working example of two remote nodes connected only with one CAT5 cable over 50m. They are working at 115200 - however speed might be up to 1 Mbit/s.



  • @LeoDesigner but how would I connect all sensors in house and relays too?
    SOme resistors needed? Star topology? Few gateways?



  • @andriej
    The star topology could be a problem. However for low speed nodes this may work anyway.
    You may need something like RS485 hub 🙂 or a GW with many RS485 bus ports.
    Or just a separate MAX485 board for each node. You need to test it.



  • @TimO Well... it turns out that the garbage seen on the wire was not garbage, just the binary serial protocol. And the node was desperately attempting to find a parent, with no success.

    FYI this is how I workaround it. But I did not feel like I could fix it for 100% sure.

    The gateway ignored the broadcasts from the node. The following code in MyTransportRS485 triggered for probably wrong reasons (sender=0; nodeid=0;station=broadcast) :

                   if ((_recSender == _nodeId) ||
                      (_recStation != _nodeId &&
                       _recStation != BROADCAST_ADDRESS)) {
                              _dev.print(" wrongid: ");
    

    Since the gateway was not responding correctly to the node broadcasts, I solved the serial communication problem between node and gateway by defining a fixed node Id :

    #define MY_NODE_ID 10
    

    (ps: the MySensors version used was cloned from git today)



  • Replying to myself... Of course the "Controller" MUST be properly connected
    for dynamic nodes IDs to function properly, since it's the controller's job to affect the node ids.

    This explains a part of my original problem.



  • I think, that CAN transceiver chip is better then RS485 transceiver chip.
    Then we dont need direction setting pin and bus state is better determined, becose CAn bus is prepered for bus collisions, RS485 not.
    I mean only CAN bus transceiver, not CAN controller ! For example MCP2551 or MCP2562.
    And we can use normal serial library.



  • @kimot what would be the CAN topology needed?
    Does it support star topology? Im looking for a in-home bus over cat5e in walls...

    Regards





  • Ok so if it's line-wire, then maybe I could wire all cat5e's to one patch-panel, terminate them there and from the patchpanel I could daisy-chain them on one magistral connection and also feed the 12/24V on one pair (i.e. orange/white orange) and data (i.e. blue/white blue).

    How do you guys think it would work for cables in-home in-wall?
    I guess the power feed would work ok (even including the voltage drop) but what about the RS485/CAN length?
    I plan to run cat5 to every switch.

    Still can't decide if I should connect on-wall switches straight to Arduino (to control relays further) or to use small arduinos inside every wall switch to better control sensors there (temperature on wall) and possibility to program every switch differently. The idea is to get every wire to basement anyway.



  • @andriej
    RS485 was not designet for multimaster communication, where 2 devices can communicate on the bus at same time. RS485 bus state at this time is not defined. For example if node on RS485 on one end of bus sends message end perform "control" lisening on bus if recieve the same message( what is with correct circuit of RS485 transsiever immposible ), then this received message can be the same. But if in the same time another node on oposite end of bus sends different message, then node on the middle of bus recieves something random.
    But CAN bus has allways defined state. It has dominate state and recesive state, so node witch send dominate bit cannot be pushed yb node witch at the same time sends recesive bit. I now, thet this feature we cannot use with normal serial communication, but still we can controll correct sending of datagram by lisening bus by sender. If we recieve the same message what we send, there is 100% shure, that the same message lisens every node on CAN bus. On RS485 this is not garanted. Bus topology is the same end we dont need "dePin". So we can use normal serial library. And CAN transciever is not so expensive as wrote LeoDesigner. Look here:

    http://www.ebay.com/itm/10PCS-MCP2551-I-SN-IC-TRANSCEIVER-CAN-HI-SPD-8-SOIC-NEW-/171541737564?hash=item27f0af305c:g:nbQAAOSwIBBUZU~k

    And sorry for my english



  • @kimot Thank you for the information - your english is good enough to understand. 🙂

    I'm just looking for more simple protocol than ethernet to send data from various places - wired.
    And it seems that, for longer distance and cat5e cable in-wall, ethernet is the only choice 😞



  • @andriej
    Just put CAT5e to every place (or even two CAT5e to each TV, room - as I done myself). Later you will decide what kind of signals will travel over CAT5e wire. It can be Ethernet or RS485, CANbus, or something else. Regular twisted pair Ethernet is also has a star topology with central hub/switch. (You may also remember an old Ethernet system with one base cable and terminating resistors on the both ends). For a really long distance - RS485 is the winner anyway - up to 1200m on slow speed.



  • @LeoDesigner I will put cat5e for 'LAN' purposes to proper socket, but I also want to control my lights not via connecting/disconnecting 230V in-wall, but in central control panel.
    I was planning to use doorbell push buttons on walls just to give signal to automation and then MCU will set proper relays/dimmers on/off etc.

    That's why I was thinking about putting cat5e also to on-wall switches, then on 1 pair make the +/-12V signal, another pair for data bus etc. And now I'm looking for most efficient way to connect it everything together.
    Each room will have temperature sensor for sure (in the switch), some may have dimmers etc. Last idea was to put mini arduinos inside the hole in wall, but I'm afraid of resetting them every once in a while, just because arduino likes to hang itself...



  • @andriej remember to calculate how much current you can take thru cat5e and how much load there can be with one pair.
    From wikipedia: "Maximum current per conductor 0.577A". So this would make P=UxI -> 12Vx0.577A=6.92W. There is calculations where one nano can take max 1.4Watts. You could use more wires of the car5e for power or lift voltage upper. 48Vx0.577A=27.70W 😉



  • @pjr I'm aware of that 🙂
    Still struggling with decision either to use the CAT5e just as a loooong cable to (doorbell) switch or use it to PoE small nanos all over the place and run i.e. MQTT on each wall-switch separate.
    In second option the RS485 protocol would be the best, because of small form factor (smaller than ethernet port inside switch) and possibility to use MySensors too 😉



  • @kimot what has to be done to prepare MySensors to use CAN?
    I'm thinking about ordering some modules for tests. 🙂


  • Hero Member

    @andriej said:

    use it to PoE small nanos all over the place

    Which components do you have in mind? I 'm thinking in that direction too.



  • @TimO this small W5100 module: http://www.aliexpress.com/item/TOP-Mini-W5100-LAN-Ethernet-Shield-Network-Module-board-Best/32457200047.html with step-down dc converter. 🙂
    Cheaper than the PoE standard version.



  • @andriej
    It is a pity that not paying more attention mysensors.org for nodes interconnected by wires. But it is very difficult to find peer-to-peer protocol for RS485. Mainly because of solving collisions on the bus when multiple sensors. But it is very difficult to find peer-to-peer protocol for RS485. Mainly because of solving collisions on the bus when multiple sensors. I think that used ICSC library does not address this matter satisfactorily and with a larger number of sensor problems arise. ICSC library uses a Serial Software library by heavyweight each node on the bus, because all must be checke every bit transmitted on the bus. Look at different implementation:

    www.mrbus.org

    I think, thet using hardware UART is absolutely necessary.
    Or why when we use a separate module for radio transmission, we use the special module for robust message transfer over the wired bus? CAN controllers are not so expensive in this days:

    http://www.ebay.com/itm/MCP2515-CAN-Bus-Module-Board-TJA1050-receiver-SPI-For-51-MCU-ARM-controller-M2-/381500570180?hash=item58d334ba44:g:OhcAAOSw3KFWfANk

    After correct CAN controller configuration, we simply write a message to the CAN controller and forgot about it. No check or bus arbitration. And through interrupt pin from the controller just pick up the incoming message with our ID or broadcast.

    I know it's not as simple as using only RS485 transmitter itself, but we are guaranteed connecting maximum of 110 nodes and various libraries for Arduino for this CAN controller exist.



  • @andriej
    But on the other side, with simply CANbus, we have got only 8 byte payload for our data.



  • @kimot so the only thing that's left is TCP/IP and MQTT...



  • @kimot
    Thanks for pointing to mrbus.org.
    I have seen this before - it's really nice implementation of RS485 bus management.
    It's worth trying to implement it. However, I can see only one weak point of ICSC lib. It's a moment when both nodes listening a bus and starting to transmit at the same time. In this case the both packets will be lost. (This situation can occur only during the transmission of the first starting byte, so higher bus speed can make this situation rare.)
    I have both the radio and wired mysensors network. And wired network in order of magnitude is more reliable. I have a really small amount of lost packets. The packets are retransmitted only due delay in the code of the nodes.



  • HELP: Please instructions on how I can run this RS485 transport class for beginners.

    Some basic questions:

    1. First point instructions: File "SerialTransport.h" and "SerialTransport.cpp" download to C:\Program Files (x86)\Arduino\libraries\MySensors[here]. is this correct ?
    2. On the second point instructions: "Add #include <SerialTransport.h> to your .ino sketch" but examples do not have this:
      https://github.com/mysensors/Arduino/tree/development/libraries/MySensors/examples/MotionSensorRS485
      https://github.com/mysensors/Arduino/tree/development/libraries/MySensors/examples/GatewaySerialRS485
      way ?
      In what file i must put this line "#include <SerialTransport.h>" ? main sketch ?
    3. The third point instructions: Replace transport class with: "Replace transport class with: " where exactly ? Maybe I have a different version MySensors because I can not find the declaration "#define MY_RADIO_RF24" and replace it with a "#define MY_RS485". I do not know how to change the NRF to RS485 in lib MySensors. Please precise instructions with examples for the current version lib MySensors.
    4. Can I get examples of sketch (confirmed that work with the physical bus RS485) Gateway and sensor.

    I use Windows, path of arduino lib is: C:\Program Files (x86)\Arduino\libraries.

    The only thing that works:
    When I connect RS485 to USB on Raspberry Pi (domoticz) and on the other side sensor (Arduino Pro Mini + DHT22) received on Raspberry:

    radek@raspberrypi $ cat /dev/ttyUSB0
    radi init fail
    

    It sent the sensor by the RS485 to Rasberry PI. So the RS485 is working properly.

    Sorry for my English and thank you for your help.



  • I think those instructions are written for older version of the library. Now you could just copy those examples and try without changing anything.... I think 😉



  • In the examples, there is no information on how to disable the radio NRF24 and enable RS485, this is my main problem.

    MySensors still try init Radio NRF, because no radio connected in sending "radio init fail"

    Renovate the house and so I want to use it:
    Raspberry Pi (Domoticz) <--- USB ---> MySensor Gateway RS485 <--- RS485 (Cat5e) ---> MySensors Sensors & Actuators (x 20)

    Will show photos when I finish.


  • Admin

    @radekzm said:

    In the examples, there is no information on how to disable the radio NRF24 and enable RS485, this is my main problem.

    It is this line that activates the RS485 transport (also note that no radio is activated).
    https://github.com/mysensors/Arduino/blob/development/libraries/MySensors/examples/GatewaySerialRS485/GatewaySerialRS485.ino#L56

    I haven't had the opportunity to test this thoroughly. So there might be issues.



  • I think that constat value:

    #define MY_RS485
    

    https://github.com/mysensors/Arduino/blob/development/libraries/MySensors/examples/GatewaySerialRS485/GatewaySerialRS485.ino#L56

    It is doing nothing and changes nothing. This constat value is only on exmaple sketch. It is not a reference to the constat value in the library MySensros and mysensors-serial-transport.

    Searching 1628 files for "MY_RS485"
    0 matches

    ??? I still do not know how to use the RS485 instead of NRF24 ???


  • Admin



  • That's exactly what I looking for !. In my version of the library that are missing.
    In my version of the library that (supports RS485) are missing.
    I downloaded the Library https://github.com/mysensors/Arduino/archive/master.zip this is my problem.
    Should I download from https://github.com/mysensors/Arduino/tree/development/libraries/MySensors.

    The last question: Do I have just these two files download and replace from second url and that all ?


  • Admin

    You'll have to download replace everything in MySensors library folder.



  • @radekzm said:

    HELP: Please instructions on how I can run this RS485 transport class for beginners.

    You have to use a stable 1.5.2 version for my RS485 transport class. Not a development branch. You also may want to try development version too. The instruction was written for 1.5 (1.5.2) version of mysensors libs.

    Some basic questions:

    1. First point instructions: File "SerialTransport.h" and "SerialTransport.cpp" download to C:\Program Files (x86)\Arduino\libraries\MySensors[here]. is this correct ?

    ...\Arduino\libraries\SerialTransport\ [HERE]

    1. On the second point instructions: "Add #include <SerialTransport.h> to your .ino sketch" but examples do not have this:
      https://github.com/mysensors/Arduino/tree/development/libraries/MySensors/examples/MotionSensorRS485
      https://github.com/mysensors/Arduino/tree/development/libraries/MySensors/examples/GatewaySerialRS485
      way ?

    They are for development version - not for stable 1.5.2

    In what file i must put this line "#include <SerialTransport.h>" ? main sketch ?
    Yes.

    1. The third point instructions: Replace transport class with: "Replace transport class with: " where exactly ? Maybe I have a different version MySensors because I can not find the declaration "#define MY_RADIO_RF24" and replace it with a "#define MY_RS485". I do not know how to change the NRF to RS485 in lib MySensors. Please precise instructions with examples for the current version lib MySensors.

    Please check examples for version 1.5 (1.5.2)

    1. Can I get examples of sketch (confirmed that work with the physical bus RS485) Gateway and sensor.
    /*
    * MockMySensors 485
    *
    * This skecth is intended to crate fake sensors which register and respond to the controller
    * 
    * Barduino 2015
    */
    
    #include <MySigningNone.h>
    //#include <MyTransportRFM69.h>
    //#include <MyTransportNRF24.h>
    #include <MyHwATMega328.h>
    #include <MySigningAtsha204Soft.h>
    #include <MySigningAtsha204.h>
    
    #include <SPI.h>
    #include <MySensor.h>  
    #include <MyMessage.h>
    
    #include <SerialTransport.h>
    
    
    #define RADIO_ERROR_LED_PIN 9  // Error led pin
    #define RADIO_RX_LED_PIN    8  // Receive led pin
    #define RADIO_TX_LED_PIN    7  // the PCB, on board LED
    
    
    // Wait times
    #define LONG_WAIT 500
    #define SHORT_WAIT 50
    
    #define SKETCH_NAME "FakeMySensors 485 241"
    #define SKETCH_VERSION "v0.2"
    
    // Global Vars
    // unsigned long SLEEP_TIME = 60000; // Sleep time between reads (in milliseconds)
    unsigned long SLEEP_TIME = 3000; // Sleep time between reads (in milliseconds)
    
    boolean metric = true;
    long randNumber;
    
    // Instanciate MySersors Gateway
    //MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);
    //MyTransportRFM69 transport;
    MyTransportSerial transport(Serial,241,6); // serial port, node, dePin (-1 disabled)
    
    
    // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
    //MySigningNone signer;
    //MySigningAtsha204Soft signer;
    //MySigningAtsha204 signer;
    
    // Hardware profile 
    MyHwATMega328 hw;
    
    // Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
    // To use LEDs blinking, uncomment WITH_LEDS_BLINKING in MyConfig.h
    #ifdef WITH_LEDS_BLINKING
    MySensor gw(transport, hw /*, signer*/, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN);
    #else
    MySensor gw(transport, hw /*, signer*/);
    #endif
    
    //Instanciate Messages objects
    
    #ifdef ID_S_DOOR
      MyMessage msg_S_DOOR(ID_S_DOOR,V_TRIPPED);
    #endif
    
    
    ......
    ......
    

    I use Windows, path of arduino lib is: C:\Program Files (x86)\Arduino\libraries.

    You have to decide which version of the library to use.
    My SerialTransport is written only for version 1.5.2
    It's tested and working. BTW, I will upload updated version in a few minutes to github.



  • I still have a few questions:

    Use: https://github.com/mysensors/Arduino/tree/development/libraries/MySensors.

    1) Architecture: Do I understand correctly, example test:
    raspberry pi domoticz [USB] <---- USB RS232 built-in Arduino nano ----> (hardware RS232, PIN: tx/rx) Arduino Nano (Gatwey RS485) (AltSoftSerial, PIN: 2,7,8) <---- RS485 AltSoftSerial ----> (AltSoftSerial, PIN: 2,7,8) Arduino Pro Mini <------ PIN 3, DHT22

    2) Gatwey RS485 Arduino Nano:

    • USB port of the Arduino Nano plugs in to Raspberry PI and set MySensors USB gateway in Domoticz ?
    • Gatwaey to communicate with RS485 uses AltSoftSerial ? Whta PIN ? R0 / DI ?
    • Gatwey Arduino Nano to communicate with Raspberry PI (Domoticz) use hardware USB (built in RS232) ?
    • Gatweway don't have Debug mode (no free RS) ? When uploading have I must turn of debug mode in MyConfig.h when use RS485?
    • DE PIN 2 ?
    • RO PIN 8 ?
    • DI PIN 9 ?
    • PIN 2/8/9 connected directly without pull-up resistors or current limiting ?
      /**
    ...
     * The gateway uses AltSoftSerial to handle two serial links 
     * on one Arduino. Use the following pins for RS485 link
     * 
     *  Board          Transmit  Receive   PWM Unusable
     * -----          --------  -------   ------------
     * Teensy 3.0 & 3.1  21        20         22
     * Teensy 2.0         9        10       (none)
     * Teensy++ 2.0      25         4       26, 27
     * Arduino Uno        9         8         10  <----- Form https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html .... (& other ATMEGA328)
     * Arduino Leonardo   5        13       (none)
     * Arduino Mega      46        48       44, 45
     * Wiring-S           5         6          4
     * Sanguino          13        14         12
     * 
     */
    
    // Enable debug prints to serial monitor
    #define MY_DEBUG 
    
    // Enable RS485 transport layer
    #define MY_RS485
    
    // Define this to enables DE-pin management on defined pin 
    #define MY_RS485_DE_PIN 2
    
    // Set RS485 baud rate to use
    #define MY_RS485_BAUD_RATE 9600
    
    // Enable serial gateway
    #define MY_GATEWAY_SERIAL
    
    // Flash leds on rx/tx/err
    #define MY_LEDS_BLINKING_FEATURE
    // Set blinking period
    #define MY_DEFAULT_LED_BLINK_PERIOD 300
    
    // Enable inclusion mode
    //#define MY_INCLUSION_MODE_FEATURE
    // Enable Inclusion mode button on gateway
    //#define MY_INCLUSION_BUTTON_FEATURE
    // 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 
    
    #define MY_DEFAULT_ERR_LED_PIN 4  // Error led pin
    #define MY_DEFAULT_RX_LED_PIN  5  // Receive led pin
    #define MY_DEFAULT_TX_LED_PIN  6  // the PCB, on board LED
    
    #include <SPI.h>
    #include <MySensor.h>  
    
    void setup() { 
      // Setup locally attached sensors
    }
    
    void presentation() {
     // Present locally attached sensors 
    }
    
    void loop() { 
      // Send locally attached sensor data here 
    }
    
    

    3) Sensor Arduino Pro mini

    • What uses to communicate with RS485 bus ? Hardware RS232 Pin RX /TX or AltSoftSerial Pin 2/7/8 ?
    • If use AltSoftSerial: PIN 2/8/9 connected directly without pull-up resistors or current limiting ?
    • When uploading have I must turn of debug mode in MyConfig.h when use RS485?
    /**
    ...
    // Enable RS485 transport layer
    #define MY_RS485
    
    // Define this to enables DE-pin manag ement on defined pin 
    #define MY_RS485_DE_PIN 2
    
    // Set RS485 baud rate to use
    #define MY_RS485_BAUD_RATE 9600
    
    #include <SPI.h>
    #include <MySensor.h>
    #include <DHT.h>  
    
    #define MY_NODE_ID 15
    #define CHILD_ID_HUM 0
    #define CHILD_ID_TEMP 1
    #define HUMIDITY_SENSOR_DIGITAL_PIN 3
    unsigned long SLEEP_TIME = 2000; // Sleep time between reads (in milliseconds)
    
    // Initialize sensors
    DHT dht;
    float lastTemp;
    float lastHum;
    boolean metric = true; 
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    
    // Debug
    //#include <SoftwareSerial.h>
    //SoftwareSerial mySerial(3, 4); // RX, TX
    
    void setup()  
    {    
      //mySerial.begin(4800);
      //mySerial.println("Hello, world?");  
      dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); 
      metric = getConfig().isMetric;  
    }
    
    
    void presentation()  { 
      // Send the Sketch Version Information to the Gateway
      sendSketchInfo("Falskiego LED salon", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID_HUM, S_HUM);
      present(CHILD_ID_TEMP, S_TEMP);
    }
    
    
    void loop()     
    {     
      delay(dht.getMinimumSamplingPeriod());
     
      // Fetch temperatures from DHT sensor
      float temperature = dht.getTemperature();
      if (isnan(temperature)) {
          Serial.println("Failed reading temperature from DHT");
      } else if (temperature != lastTemp) {
        lastTemp = temperature;
        if (!metric) {
          temperature = dht.toFahrenheit(temperature);
        }
        send(msgTemp.set(temperature, 1));
        #ifdef MY_DEBUG
        Serial.print("T: ");
        Serial.println(temperature);
        #endif
      }
      
      // Fetch humidity from DHT sensor
      float humidity = dht.getHumidity();
      if (isnan(humidity)) {
          Serial.println("Failed reading humidity from DHT");
      } else if (humidity != lastHum) {
          lastHum = humidity;
          send(msgHum.set(humidity, 1));
          #ifdef MY_DEBUG
          Serial.print("H: ");
          Serial.println(humidity);
          #endif
      }
      
      sleep(SLEEP_TIME); //sleep a bit
    }
    
    

    Schema
    Schema
    Schema



  • This post is deleted!


  • I made a test: did the system sends data from the sensor DHT22 to the rail 485 using only library AltSoftSerial and everything works properly. So the connection is ok.
    I used the same libraries:

    #include <AltSoftSerial.h>
    

    The same connections:
    http://cmss.pl/arduino/MySensor_RS485_test02_a.JPG
    alt text

    A ) RS485 Gatwaey (arduino nano):
    http://cmss.pl/arduino/MySensor_RS485_test02_b.JPG
    alt text

    #define MY_RS485_DE_PIN 2
    

    DE and RE -> Pin 2
    RO -> Pin 8
    DI -> Pin 9
    Uploaded example MySensors Gatwey 485 and own code.

    B ) RS485 Sensor DHT22 (arduino nano):
    http://cmss.pl/arduino/MySensor_RS485_test02_c.JPG
    alt text

    #define MY_RS485_DE_PIN 2
    

    DE and RE -> Pin 2
    RO -> Pin 8
    DI -> Pin 9

    Unfortunately, nothing works, no reaction, empty on debug console.

    Any ideas what could be wrong, what to check ???


  • Admin

    Sorry to hear, I still haven't verified this so there might be problems.
    It's this file that should be of interest:

    https://github.com/mysensors/Arduino/blob/development/libraries/MySensors/core/MyTransportRS485.cpp

    Would be excellent if you had the time to debug it.



  • @hek
    Ok I will try.



  • Hi I've tried a couple of months ago with success.
    Maybe you have to connect also the GND cable each other.

    Bye



  • Hi,
    I have tired similar configuration as radekzm.
    2 x Arduino nano connected via RS485 and is looks like only rs485 is not working so my question is; How to verified that connection between to arduinos using library AltSoftSerial is ok ?

    Are this connections PIN <-> RS485 (below) OK ?

    DE and RE -> Pin 2
    RO -> Pin 8
    DI -> Pin 9

    And below example is working fine (SoftwareSerial.h library)

    https://arduino-info.wikispaces.com/SoftwareSerialRS485Example



  • @Michal

    I'll help when I get back from work.



  • @LeoDesigner
    I'm trying a Gateway & 4 relays/4 switches configuration using 1.5.2 version. As @Michal my configuration works fine with this example: https://arduino-info.wikispaces.com/SoftwareSerialRS485Example

    Anything wrong with my sketches?

    Gateway:

    /**
     * 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.
     *
     *******************************
     *
     * DESCRIPTION
     * The ArduinoGateway prints data received from sensors on the serial link. 
     * The gateway accepts input on seral which will be sent out on radio network.
     *
     * The GW code is designed for Arduino Nano 328p / 16MHz
     *
     * Wire connections (OPTIONAL):
     * - Inclusion button should be connected between digital pin 3 and GND  
     * - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series
     *
     * LEDs (OPTIONAL):
     * - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h
     * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved
     * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
     * - ERR (red) - fast blink on error during transmission error or recieve crc error 
     * 
     */
    
    #define NO_PORTB_PINCHANGES  
    
    #include <MySigningNone.h>
    #include <MyTransportRFM69.h>
    //#include <MyTransportNRF24.h>
    //#include <MyHwATMega328.h>
    #include <MySigningAtsha204Soft.h>
    #include <MySigningAtsha204.h>
    #include <SerialTransport.h>
    
    #include <SPI.h>  
    #include <MyParserSerial.h>  
    #include <MySensor.h>  
    #include <stdarg.h>
    #include <PinChangeInt.h>
    #include "GatewayUtil.h"
    
    #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled
    #define INCLUSION_MODE_PIN  3 // Digital pin used for inclusion mode button
    #define RADIO_ERROR_LED_PIN 4  // Error led pin
    #define RADIO_RX_LED_PIN    6  // Receive led pin
    #define RADIO_TX_LED_PIN    5  // the PCB, on board LED
    
    // NRFRF24L01 radio driver (set low transmit power by default) 
    //MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);
    //MyTransportRFM69 transport;
    MyTransportSerial transport(Serial,AUTO,2);
    
    // Message signing driver (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
    //MySigningNone signer;
    //MySigningAtsha204Soft signer;
    //MySigningAtsha204 signer;
    
    // Hardware profile 
    MyHwATMega328 hw;
    
    // Construct MySensors library (signer needed if MY_SIGNING_FEATURE is turned on in MyConfig.h)
    // To use LEDs blinking, uncomment WITH_LEDS_BLINKING in MyConfig.h
    #ifdef WITH_LEDS_BLINKING
    MySensor gw(transport, hw /*, signer*/, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN);
    #else
    MySensor gw(transport, hw /*, signer*/);
    #endif
    
    char inputString[MAX_RECEIVE_LENGTH] = "";    // A string to hold incoming commands from serial/ethernet interface
    int inputPos = 0;
    boolean commandComplete = false;  // whether the string is complete
    
    void parseAndSend(char *commandBuffer);
    
    void output(const char *fmt, ... ) {
       va_list args;
       va_start (args, fmt );
       vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args);
       va_end (args);
       Serial.print(serialBuffer);
    }
    
      
    void setup()  
    { 
      gw.begin(incomingMessage, 0, true, 0);
    
      setupGateway(INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output);
    
      // Add interrupt for inclusion button to pin
      PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING);
    
    
      // Send startup log message on serial
      serial(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"),  C_INTERNAL, I_GATEWAY_READY);
    }
    
    void loop()  
    { 
      gw.process();
    
      checkButtonTriggeredInclusion();
      checkInclusionFinished();
      
      if (commandComplete) {
        // A command wass issued from serial interface
        // We will now try to send it to the actuator
        parseAndSend(gw, inputString);
        commandComplete = false;  
        inputPos = 0;
      }
    }
    
    
    /*
      SerialEvent occurs whenever a new data comes in the
     hardware serial RX.  This routine is run between each
     time loop() runs, so using delay inside loop can delay
     response.  Multiple bytes of data may be available.
     */
    void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read(); 
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
        if (inputPos<MAX_RECEIVE_LENGTH-1 && !commandComplete) { 
          if (inChar == '\n') {
            inputString[inputPos] = 0;
            commandComplete = true;
          } else {
            // add it to the inputString:
            inputString[inputPos] = inChar;
            inputPos++;
          }
        } else {
           // Incoming message too long. Throw away 
            inputPos = 0;
        }
      }
    }
    
    
    

    4 relays / 4 switches

    /*
      State change detection (edge detection)
    
     Often, you don't need to know the state of a digital input all the time,
     but you just need to know when the input changes from one state to another.
     For example, you want to know when a button goes from OFF to ON.  This is called
     state change detection, or edge detection.
    
     This example shows how to detect when a button or button changes from off to on
     and on to off.
    
     The circuit:
     * pushbutton attached to pin 2 from +5V
     * 10K resistor attached to pin 2 from ground
     * LED attached from pin 13 to ground (or use the built-in LED on
       most Arduino boards)
    
     created  27 Sep 2005
     modified 30 Aug 2011
     by Tom Igoe
    
    This example code is in the public domain.
    
     http://www.arduino.cc/en/Tutorial/ButtonStateChange
    
     */
    
    #include <MySigningNone.h>
    //#include <MyTransportNRF24.h>
    //#include <MyTransportRFM69.h>
    #include <SerialTransport.h>
    #include <MyHwATMega328.h>
    #include <MySensor.h>
    #include <SPI.h>
    
    // this constant won't change:
    int buttonPin[] = {9, 10, 11, 12};          // array of pins that the pushbutton is attached to
    int relayPin[] = {3, 4, 5, 6};           // array of pins that the relay is attached to
    int pinCount = 4;                  // number of buttons/relays attached
    
    // Variables will change:
    int buttonState[] = {0, 0};         // current state of the button
    int lastButtonState[] = {0, 0};     // previous state of the button
    
    #define RELAY_ON 1
    #define RELAY_OFF 0
    int relayState[] = {RELAY_OFF, RELAY_OFF};   // counter for the number of button presses
    
    
    // NRFRF24L01 radio driver (set low transmit power by default) 
    MyTransportSerial transport(Serial,AUTO,2); 
    //MyTransportRFM69 radio;
    // Message signing driver (none default)
    //MySigningNone signer;
    // Select AtMega328 hardware profile
    MyHwATMega328 hw;
    // Construct MySensors library
    MySensor gw(transport, hw);
    
    void setup() 
    {
      // Initialize library and add callback for incoming messages
      gw.begin(incomingMessage, AUTO, true);
      // Send the sketch version information to the gateway and Controller
      gw.sendSketchInfo("Relays & Buttons", "1.0");
      
      for (int i = 0; i < pinCount; i++) {
        // Register all sensors to gw (they will be created as child devices)
        gw.present(buttonPin[i], S_LIGHT);
        gw.present(relayPin[i], S_LIGHT);
        
        // initialize the button pin as a input:
        pinMode(buttonPin[i], INPUT);
        digitalWrite(buttonPin[i], 0);
        // initialize the relay as an output:
        pinMode(relayPin[i], OUTPUT);
        digitalWrite(relayPin[i], gw.loadState(i)?RELAY_ON:RELAY_OFF);
      }
    }
    
    
    void loop() {
      // Alway process incoming messages whenever possible
      gw.process();
      
      for (int i = 0; i < pinCount; i++) {
        MyMessage msg(relayPin[i], V_LIGHT);
        buttonState[i] = digitalRead(buttonPin[i]);
    
        if (buttonState[i] != lastButtonState[i]) {
          if (buttonState[i] == 1) {
    //         gw.send(msg.set(relayState[i]==RELAY_ON ? RELAY_OFF : RELAY_ON));
    //          if(relayState[i]==RELAY_ON) gw.send(msg.set(RELAY_OFF));
    //          else                        gw.send(msg.set(RELAY_ON));
              if(relayState[i]==RELAY_ON) relayState[i]=RELAY_OFF;
              else                        relayState[i]=RELAY_ON;
          }
          lastButtonState[i] = buttonState[i];
        }
        digitalWrite(relayPin[i], relayState[i]);
      }
    }
    
    
    void incomingMessage(const MyMessage &message) {
      // We only expect one type of message from controller. But we better check anyway.
      if (message.type==V_LIGHT) {
          for (int i = 0; i < pinCount; i++) {
            // digitalWrite(message.sensor-1+relayPin[1], message.getBool()?RELAY_ON:RELAY_OFF);
          }
       } 
    }
    
    


  • @elmarculino
    In Gateway:

    #include <MyTransportRFM69.h>
    //#include <MyTransportNRF24.h>
    //#include <MyHwATMega328.h>
    ...
    MyTransportSerial transport(Serial,AUTO,2);
    
    
    

    Should be:

    //#include <MyTransportRFM69.h>
    //#include <MyTransportNRF24.h>
    #include <MyHwATMega328.h>
    ....
    MyTransportSerial transport(Serial,0,2);
    

    In 4relay / 4 switches:
    Personally I am assigning a static ID to nodes, so I did not tested an AUTO option in gw.init. However I think this it should work. Also make sure you are downloaded a latest Serial transport class from github with some minor corrections.



  • @LeoDesigner
    Thanks for the help. I made the changes you pointed out, but still no lucky. What controller are you using? This should work in a direct crossover connection too?



  • @elmarculino
    I am using a custom controller based on the node-red, mqtt broker and homeassitant with mqtt bindings. But this is not essential - you can use 'nc GW_IP GW_PORT' from unix command line to issue commands to gateway directly. Try to separate your basic building blocks to smallest parts and then debug it.



  • @LeoDesigner I still could not make it work in 1.5.2 with your library, but I will keep trying. Thanks!

    @hek I finally could make a gateway / sensor (Humidity) connection via RS485 using the development branch. Is any Controller compatible with the development branch? Thanks!

    0;255;3;0;9;Starting gateway (RSNGA-, 2.0.0-beta)
    0;255;3;0;9;Radio init successful.
    0;255;3;0;14;Gateway startup complete.
    0;255;3;0;9;Init complete, id=0, parent=0, distance=0
    0;255;3;0;9;read: 1-1-0 s=0,c=1,t=1,pt=7,l=5,sg=0:44.0
    1;0;1;0;1;44.0
    0;255;3;0;9;read: 1-1-0 s=0,c=1,t=1,pt=7,l=5,sg=0:43.0
    1;0;1;0;1;43.0
    0;255;3;0;9;read: 1-1-0 s=0,c=1,t=1,pt=7,l=5,sg=0:44.0
    1;0;1;0;1;44.0
    0;255;3;0;9;read: 1-1-0 s=1,c=1,t=0,pt=7,l=5,sg=0:27.0
    1;1;1;0;0;27.0
    

  • Admin

    Great to hear. Did you need to make any adjustments?

    Yes, the serial protocol is backward compatible. So any controller should work as good.



  • @hek None. Works out of the box. But I could not make it work with Home Assistant.

    Pin 9 >>> DI
    Pin 8 >>> RO
    Pin 2 >>> DE and RE

    INFO:mysensors.mysensors:/dev/ttyUSB0 is open...
    INFO:mysensors.mysensors:Connected to /dev/ttyUSB0
    INFO:mysensors.mysensors:n:0 c:255 t:3 s:9 p:read: 1-1-0 s=0,c=1,
    WARNING:mysensors.mysensors:Error decoding message from gateway, probably received bad byte.
    WARNING:mysensors.mysensors:Error decoding message from gateway, probably received bad byte.
    WARNING:mysensors.mysensors:Error decoding message from gateway, probably received bad byte.```


  • @LeoDesigner My 1.5.2 RS485 Humidity sensor send the same messages as the example Humidity sketch, but shows a lot of 'X' and '?' characters at 115200 in Serial Console.

    The console with the example Humidity sketch is clean:

    sensor started, id=1, parent=0, distance=1
    send: 1-1-0-0 s=255,c=3,t=11,pt=0,l=8,sg=0,st=ok:Humidity
    send: 1-1-0-0 s=255,c=3,t=12,pt=0,l=3,sg=0,st=ok:1.0
    send: 1-1-0-0 s=0,c=0,t=7,pt=0,l=0,sg=0,st=ok:
    send: 1-1-0-0 s=1,c=0,t=6,pt=0,l=0,sg=0,st=ok:
    send: 1-1-0-0 s=1,c=1,t=0,pt=7,l=5,sg=0,st=ok:26.0
    T: 26.00
    send: 1-1-0-0 s=0,c=1,t=1,pt=7,l=5,sg=0,st=ok:44.0
    H: 44.00
    

    Do you know what can be causing it? Am I doing anything wrong, again?

    #include <SPI.h>
    #include <MySensor.h>  
    #include <DHT.h>  
    #include <MyHwATMega328.h>
    #include <SerialTransport.h>
    
    #define CHILD_ID_HUM 0
    #define CHILD_ID_TEMP 1
    #define HUMIDITY_SENSOR_DIGITAL_PIN 3
    unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds)
    
    MyTransportSerial transport(Serial,5,2); 
    MyHwATMega328 hw;
    MySensor gw(transport, hw);
    DHT dht;
    float lastTemp;
    float lastHum;
    boolean metric = true; 
    MyMessage msgHum(CHILD_ID_HUM, V_HUM);
    MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP);
    
    
    void setup()  
    { 
      gw.begin();
      dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); 
    
      // Send the Sketch Version Information to the Gateway
      gw.sendSketchInfo("Humidity", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      gw.present(CHILD_ID_HUM, S_HUM);
      gw.present(CHILD_ID_TEMP, S_TEMP);
      
      metric = gw.getConfig().isMetric;
    }
    
    void loop()      
    {  
      delay(dht.getMinimumSamplingPeriod());
    
      float temperature = dht.getTemperature();
      if (isnan(temperature)) {
          Serial.println("Failed reading temperature from DHT");
      } else if (temperature != lastTemp) {
        lastTemp = temperature;
        if (!metric) {
          temperature = dht.toFahrenheit(temperature);
        }
        gw.send(msgTemp.set(temperature, 1));
        Serial.print("T: ");
        Serial.println(temperature);
      }
      
      float humidity = dht.getHumidity();
      if (isnan(humidity)) {
          Serial.println("Failed reading humidity from DHT");
      } else if (humidity != lastHum) {
          lastHum = humidity;
          gw.send(msgHum.set(humidity, 1));
          Serial.print("H: ");
          Serial.println(humidity);
      }
    
      gw.sleep(SLEEP_TIME); //sleep a bit
    }
    


  • @elmarculino
    My library is using a standard hardware serial port of arduino - you have to disable debug option in MySensors config and use the serial port only for RS485. The 'garbage' you are receiving are actual binary communication packets intended only for RS485 bus. You have to disconnect your serial to usb adapter in case if you are using Arduino Pro. Please take a closer look to the video and schematic coming with the library. You can use and 'sniff' your serial console - but you must to disable any additional serial debug prints to the console in production mode. Remember - your serial console is a RS485 bus with this library.



  • @radekzm
    OK, what I did:
    on one Arduino nano I have this sketch
    https://github.com/mysensors/Arduino/blob/development/libraries/MySensors/examples/GatewaySerialRS485/GatewaySerialRS485.ino
    on second arduino nano I have conbined two sketches:
    https://github.com/mysensors/Arduino/blob/development/libraries/MySensors/examples/DistanceSensor/DistanceSensor.ino
    and
    https://github.com/mysensors/Arduino/blob/development/libraries/MySensors/examples/MotionSensorRS485/MotionSensorRS485.ino
    and the results is:

    /**
     * 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
     * This is an example of sensors using RS485 as transport layer
     * 
     * Motion Sensor example using HC-SR501 
     * http://www.mysensors.org/build/motion
     * 
     * The transport uses AltSoftSerial to handle two serial links 
     * on one Arduino. Use the following pins for RS485 link
     * 
     *  Board          Transmit  Receive   PWM Unusable
     * -----          --------  -------   ------------
     * Teensy 3.0 & 3.1  21        20         22
     * Teensy 2.0         9        10       (none)
     * Teensy++ 2.0      25         4       26, 27
     * Arduino Uno        9         8         10
     * Arduino Leonardo   5        13       (none)
     * Arduino Mega      46        48       44, 45
     * Wiring-S           5         6          4
     * Sanguino          13        14         12 * 
     * 
     */
    
    
    // Enable RS485 transport layer
    #define MY_RS485
    
    // Define this to enables DE-pin management on defined pin 
    #define MY_RS485_DE_PIN 2
    
    // Set RS485 baud rate to use
    #define MY_RS485_BAUD_RATE 9600
    
    #include <SPI.h>
    #include <MySensor.h>
    #include <NewPing.h>
    
    #define CHILD_ID 1
    #define TRIGGER_PIN  5  // Arduino pin tied to trigger pin on the ultrasonic sensor.
    #define ECHO_PIN     6  // Arduino pin tied to echo pin on the ultrasonic sensor.
    #define MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
    unsigned long SLEEP_TIME = 5000; // Sleep time between reads (in milliseconds)
    
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
    MyMessage msg(CHILD_ID, V_DISTANCE);
    int lastDist;
    boolean metric = true; 
    
    void setup()  
    {  
      metric = getConfig().isMetric;
    }
    
    void presentation() {
      // Send the sketch version information to the gateway and Controller
      sendSketchInfo("Distance Sensor", "1.0");
    
      // Register all sensors to gw (they will be created as child devices)
      present(CHILD_ID, S_DISTANCE);
    }
    
    void loop()     
    {     
      int dist = metric?sonar.ping_cm():sonar.ping_in();
      Serial.print("Ping: ");
      Serial.print(dist); // Convert ping time to distance in cm and print result (0 = outside set distance range)
      Serial.println(metric?" cm":" in");
    
      if (dist != lastDist) {
          send(msg.set(dist));
          lastDist = dist;
      }
    
      sleep(SLEEP_TIME);
    }
    

    On serial port (/dev/ttyUSB0) Controller (first nano) I see:
    0;255;3;0;9;Starting gateway (RSNGA-, 2.0.0-beta)
    0;255;3;0;9;Radio init successful.
    0;255;3;0;14;Gateway startup complete.
    0;255;3;0;9;Init complete, id=0, parent=0, distance=0

    on serial port(/dev/ttyUSB1) in node is see:
    ...
    Ping: 33 cm
    Ping: 34 cm
    Ping: 34 cm
    Ping: 33 cm
    Ping: 33 cm
    Ping: 33 cm
    Ping: 5 cm
    Ping: 91 cm
    Ping: 88 cm
    Ping: 89 cm
    ......

    But I expect to see some message on controller. What can I check? Do you see and mistakes ?



  • Hi,
    I am new in mysensors and arduino however I already use domoticz with mysensors and rflink.
    Everything is working fine however now I plan to renovate my house and I would like to put wire connection using max485 and arduino. Problem is that it is now working 😞 I have tried 1.5.4 version and also development branch. It seems that signal is not getting to gateway. I nothing see on arduino gateway except of initalization gateway. I have started to use two nano but I also tried combination nano and mega without success. I would be very appreciate if someone who done it could more describe how to make that it works.
    I tried https://arduino-info.wikispaces.com/SoftwareSerialRS485Example and it works fine.
    I use for nano combination pins 2 (de/re), 8 (ro),9(di)



  • @Mariusz jak jesteś Polakiem ? Jeżeli tak to mogę Ci pomóc po polsku będzie łatwiej 🙂


  • Hardware Contributor

    @radekzm Please use private chat/PM if you don't intend everyone to read it.



  • @m26872
    I'm sorry and promises to improve 🙂

    @Mariusz
    In my case the solution was in MyConfig.h file (in my case C:\Program Files (x86)\Arduino\libraries\MySensors):

    1. Disable function MY_DISABLED_SERIAL
      commenting lines 49
      // #define MY_DISABLED_SERIAL

    2. Disable function MY_DEBUG
      commenting lines 36
      //#define MY_DEBUG

    3. Correct connection is on my pictures enclosed in the above comment

    Board | Transmit | Receive | PWM Unusable
    Arduino Uno | 9 | 8 | 10 <----- Form https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html .... (& other ATMEGA328)
    Arduino Leonardo | 5 | 13 | (none)
    Arduino Mega | 46 | 48 | 44, 45

    DE and RE -> Pin 2
    RO -> Pin 8
    DI -> Pin 9

    1. To check the hardware and connections run the "Example Program" from https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html

    2. Use development branch



  • @LeoDesigner
    Hi, I am trying to do almost the same, but I would like to use softwareSerial instead of altsoft. The reason why I would do this is that i can barely fit the arduino nano inside my case, and an additional rs485 module would not fit and that I have 8 nodes connected on the softwareserial . I have tested software serial on arduino and it seems to work fine up to 15meters, I also adjusted the baudrate to 9600 since my node does not send out/receive large amount of data. I read that you did some work on software serial and were wondering if you could take a look at this thread.



  • Is there any how-to's on this transport class as far as the hardware goes? How does it work with multiple nodes? Is it like a ring pattern? or do all the nodes have to have a dedicated connection to the gateway.


  • Admin

    Depends on your physical transport layer. I would say a multidrop link where everything is in parallel..



  • Is it possible, to built a esp8266 wifi gateway and communicate GW to node with rs485?
    In altsoft esp8266 is not decleared, so i can't use it out of the box.

    Btw: I tested my_rs485 with nano as GW and Pro Mini as node, and it worked great. Thank you 🙂


  • Admin

    @hausinger I don't think so. I haven't heard of anyone trying. I guess you'd have to replace alt-soft-serial with something else.


  • Hardware Contributor

    @hausinger if you know about coding..



  • Hi,

    Any reason why this lib is not using Serial1 or Serial2 on Arduino Mega 2560 instead of AltSoftSerial?


  • Admin

    @Bartek-Celary
    No, not really. Just that not many that uses 2560.



  • How about adding the following define to use the Serial1/2 on Mega. I have not tested yet but assuming the AltSoftSerial lib has the same interface/functionality it should work.

    #define MY_RS485_SERIAL Serial1
    
    diff --git a/core/MyTransportRS485.cpp b/core/MyTransportRS485.cpp
    index 814f721..ea35c9e 100644
    --- a/core/MyTransportRS485.cpp
    +++ b/core/MyTransportRS485.cpp
    @@ -92,7 +92,11 @@ unsigned char _recSender;
     unsigned char _recCS;
     unsigned char _recCalcCS;
     
    +#if defined(MY_RS485_SERIAL)
    +HardwareSerial& _dev = MY_RS485_SERIAL;
    +#else
     AltSoftSerial _dev;
    +#endif
     
     
     unsigned char _nodeId;
    

  • Admin

    Looks like a neat solution. If it verifies ok, please create a pull request agains the development branch.


Log in to reply
 

Suggested Topics

  • 7
  • 2
  • 16
  • 8
  • 3
  • 36
  • 4

1
Online

11.4k
Users

11.1k
Topics

112.7k
Posts