This lab is available as part of my online portfolio at: https://lehi.dev/labs/lab4
The purpose of this lab is to learn how to implement an event hub, send topic messages to subscribed clients, get experience with multiple actuators interaction. These principles include:
- Become more familiar with Arduino IDE in order to use in conjunction with Wemos D1 Mini microcontrollers and Ultrasonic Sensor HC-SR04.
- Enumerate requirements from use case and user stories.
- Develop a minimum viable product and refactor it to account for new requirements.
- Become more familiar with representing the desired system by using flowcharts, state diagrams, etc.
- Learn to plan what materials will be necessary to accomplish the system’s purpose
- Build Iot sensors by utilizing GPIO pins for inputs.
- Learn how to design an IoT interaction between a sensor and an actuator.
- Implement an Event Hub for publish/subscribe notifications between devices
- Develop a communications protocol for devices across the event bus
- Establish more complex conditions for the actuator involving multiple sensors
- Personal Computer
- 3 x Wemos D1 Mini microcontrollers (ESP8266)
- 3 x 2.5A USB Power Supply with micro USB Cable
- 3 x breadboard
- 1 x Ultrasonic Sensor HC-SR04
- 1 x Reed Switch
- 1 x Red LED
- 1 x Yellow LED
- 1 x Green LED
- 3 x 220 Ω Resistor (RRBlBlBr)
- Arduino IDE
- Jump wires
- Soldering iron
- GPIO pinout guide
The following resources were used in this lab:
- https://arduinojson.org/v5/example/parser/ – Great tutorial on how to use JSON messages.
- https://arduinojson.org/v5/api/jsonbuffer/clear/ – Arduino json documentation – clear buffer.
- https://arduinojson.org/v5/assistant/ – Good resource to find out how big of a buffer you should set for the messages.
- https://www.arduino.cc/en/Reference.StringToCharArray – Arduino documentation about String to Char Array.
- https://stackoverflow.com/questions/7383606/converting-an-int-or-string-to-a-char-array-on-arduino – Good example showing String to Char Array conversion.
- https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/tochararray/ – Another reference about toCharArray
- https://randomnerdtutorials.com/how-to-install-mosquitto-broker-on-raspberry-pi/ – How to install mosquito broker on raspberry pi.
- https://github.com/todddb/basic_mqtt/blob/master/basic_mqtt.ino – Greate example on basic mqtt between raspberry pi and arduino Wemos, posting to a topic and receiving a message subscription.
- http://www.instructables.com/id/Programming-the-WeMos-Using-Arduino-SoftwareIDE/ – programming wemos D1 mini
- https://www.arduino.cc/en/Main/Software – Arduino IDE software download
- http://fritzing.org/download/ – Fritzing is a great tool to visualize electronics prototype.
- https://www.baldengineer.com/mqtt-tutorial.html/installing-pubsubclient-for-arduino – Installing Pubsubclient on arduino.
- https://github.com/bblanchon/ArduinoJson/blob/master/examples/JsonParserExample/JsonParserExample.ino – Another good example on how to use the ArduinoJson.
- https://github.com/bblanchon/ArduinoJson – github repo for ArduinoJson for documentation.
- https://randomnerdtutorials.com/monitor-your-door-using-magnetic-reed-switch-and-arduino/ – Good tutorial to get Reed Switch started.
- https://learningsuite.byu.edu/plugins/Upload/fileDownload.php?fileId=0898d64c-l7be-qzXX-AmEv-ua2991b70838 – Lab4 requirements.
- Solder the headers on 3 Wemos D1 mini in order to utilize the breadboard and jump wires, LEDs, Ultrasonic Sensor HC-SR04 and Reed Switch.
- Download and install Arduino IDE from https://www.arduino.cc/en/Main/Software
- Install CH341 version 1.4 from the following website: https://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html
- Add Wemos D1 library to the Arduino IDE:
- Arduino > Preferences > (in addition Boards Manager URLs paste the following: https://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html)
- Tools > Board > Boards Manager > (search for “esp8266”) then click install.
- Tools > Board > “LOLIN(WEMOS) D1 R2 & mini”
- Then selected the connected arduino by going to:
- Tools > Port > /dev/cu.wchusbserial14510
- Used the Arduino IDE to develop the code for the stoplight, Ultrasonic Sensor HC-SR04 and Reed Switch.
- Used the Arduino GPIO pinout to decide which pins to use for this project from https://wiki.wemos.cc/products:d1:d1_mini#documentation.
- In version 1 I wanted to design a system that all it would do was to measure the distance in centimeters of an object and the Ultrasonic Sensor HC-SR04 and print out the distance using Serial Monitor.
- In Version 2 Make the arduino that has the Ultrasonic Sensor HC-SR04 send messages to mosquito message broker and subscribe itself so you can see the message coming through before you can see on the stoplight arduino through Serial monitor prints.
- Refactor stoplight arduino so that it no longer send messages via http. Subscribe to topics that will be used for the communication between all devices.
- Reused the existing lab 2 breadboard, leds, resistors with Wemos D1 mini, to accept messages from mosquito message broker, the messages are commands to turn on and off led lights.
- I Chose the following pins to be on:
- Pin D6: Green color
- Pin D8: Yellow color
- Pin D1: Red color
- Pin G: Ground
- I had one Ground pin from GPIO to breadboard negative column, then connected 220 Ω resistors to LEDs negative end point.
- I Chose the following pins to be on:
- In version 3, once I got the Ultrasonic Sensor HC-SR04 working and printing out the distance of an object in comparison to the Ultrasonic Sensor HC-SR04 through messages using Mosquito message broker.
- Install MQTT on arduino:
- Go to Tools > Manage Libraries
- Search for: PubSubClient (by Nick O’Leary)
- Install and include the library in all 3 code base
- I then started the process of adding a third arduino with a reed switch. You can communicate using the same topic or using a different topic as long as the clients subscribe to all topics they need to listen to.
- With a new soldered arduino then connected the reed switch and using a GPIO pin for input and 3V.
- As the reed switch come close in proximity it closes the circuit which transitions its state to “LOW”. Open circuit is then “HIGH”.
- For this lab we want to send a message to the stoplight when the circuit is closed then send a message to stoplight letting it know that it can operate as normal, turning on lights and sensing proximity. As the circuit becomes open, then send a message to stoplight arduino letting it know to turn off all the lights and disregard any message command to turn on lights.
- The logic set up was the following in pseudo code:
- Keep track of current led lights state so that once we need to change a state then send a message through Mosquito message broker to let clients know that the topic has changed.
- Keep track of Reed Switch state so once it changes its state then send a message through Mosquito message broker to let clients know that the topic has changed.
- If Reed Switch circuit is closed update a server variable and let clients know of the change.
- If Reed Switch circuit is open update a server variable and let clients know of the change.
- Only send a message on state change and not all the time because that will generate too many unnecessary messages that only makes the system noisy.
- If Reed Switch is open then:
- if distance > farAway then turn on green led light
- if distance > caution then turn on yellow led light
- if distance > perfectDistance then turn on red led light
- if distance > tooFar then blink the turning on yellow led light
- Keep track which led should be on or off for each led lights.
- Turn on the led that should be on, and off for the led lights that should be off.
- Functionality: State machine as shown on the diagram below, this is a simplified form of the state machine. The message broker accepts messages from both reed switch arduino as well as ultrasonic sensor and then sends these messages to any client that is subscribed to receive a message in a given topic such as the stoplight arduino as to let it know whether it should accept commands or not depending on the state of reed switch. The basic concept is described below for each component and its role with stoplight and leds state.
- On Start up, the machine will be on LED Off state
- Case “LED OFF”
- If system receives /ledOn then system changes to “LED ON” state.
- If system receives /ledOff then system remain in “LED OFF” state.
- Case “LED ON”
- If system receives /ledOn then system remains in “LED ON” state.
- If system receives /ledOff then system changes to “LED OFF” state.
- System Flow: See Appendix 1.
- Component and Schematic Diagram: The stoplight system and the Ultrasonic Sensor HC-SR04 and Reed Switch are represented below by the following diagrams (Component and Schematic Diagram respectively)
Diagrams were facilitated by open source programs such as: Google drive plugin draw.io Diagrams and Fritzing.
- Program the code in the Arduino IDE
- Code the Arduino GPIO pins interaction with breadboards, resistors, LEDs, Ultrasonic Sensor HC-SR04 and Reed Switch accordingly to match the previous component/schematic diagram.
- Test/Debug constantly so the final product would be bug free. You can debug by first making sure the baud rate is set up in setup method. Then click on serial monitor icon . Do this Debugging step with all 3 arduinos as to see what is happening as you code.
- Use commands such as Serial.println(<variableToBeEvaluated>) to print out debug messages, so you can make sure what you think the code is doing is actually happening.
- How does the communication between devices change with the shift to using an event hub? How does this facilitate greater scalability?
This is a much better approach because now I don’t need to have a direct connection to each device by hitting their IP addresses to communicate with with them. When I add a new device there is no need to change the code that sends new message because the only thing needed in this architecture is the new client subscribes to a topic. This immensely increases the scalability because all you need to get to a bigger scale is add more clients listening on a specific topic to get messages.
- What are strengths and weaknesses of the direct communication between the sensor and actuator? What are strengths and weaknesses of the event hub? Which do you feel is better for this application?
The strengths and weaknesses for direct communication is that I noticed that the sent commands were a bit faster because there is no overhead of a message broker, but the weakness is that it is difficult to scale and every time you had to add a new client code needed to be changed to take into account the new client direct connection. The strengths and weaknesses of an event hub is that it is easy to scale and add new clients subscribed to a topic message broker, but the weakness is that the overhead of a message broker does slow down, maybe unnoticeably, but the overhead is there. Hands down the message broker is a better architecture due to flexibility in adding clients, it stores and makes sure that the messages are delivered to subscribed clients.
- What was the biggest challenge you overcame in this lab?
Adding the Reed Switch and making all 3 pieces of arduino work well together was difficult at first, perhaps due to the bare Reed Switch connections I had connecting to arduino. Also I wanted to send JSON messages as compared to just string and then doing string manipulation. It was a bit difficult because the message broker callback required to transform the data from pointer type byte to a String then transform from String to Char Array, then parse it as json format.
- Please estimate the total time you spent on this lab and report.
- 1 hour building and refactoring the circuit
- 15 hours coding the server and fixing bugs and getting acquainted with the Ultrasonic Sensor HC-SR04, debugging issue.
- 3 hours working on the lab report using tools such as Google draw.io Diagrams and fritzing.
- 2 hours publishing a website with lab 1 instructions, mainly dealing with formats.
Certification of Work
I certify that the solution presented in this lab represents my own work. In the case where I have borrowed code or ideas from another person, I have provided a link to the author’s work in the references, and included a citation in the comments of my code.
— Lehi Alcantara
Appendix 1: System Flowchart
Appendix 2: Stoplight Arduino Monitor Output
Appendix 3: Ultrasonic Sensor HC-SR04 Monitor Output
Appendix 4: Reed Switch Monitor Output
Appendix 4: Arduino Code
(Available at https://github.com/ylehilds/iot-event-bus)