close

Arduino

ArduinoKnowledgeBase

Remote Smart Air Quality Monitoring System Using LoRa, SIM800L and ThingSpeak

20190514_153253

Overview

Air pollution is one of the largest environmental and public health challenges in the world today. Air pollution leads to adverse effects on our health, climate and ecosystem. Monitoring air quality is essential to understanding and preventing air pollution, as well as assessing emission sources in order to preserve a healthier air condition and contribute to the fight against the greenhouse effect.

This project aims to create two devices that are able to communicate with each other via LoRa wireless communication. There are many sensors that can be used to monitor air quality, but for this project we’ll focus on two the DSM501A dust sensor and MQ131 ozone gas sensor. These sensors will be connected to the first device with the Ra-02 LoRa module as the client transceiver. The second device will have the LoRa shield as the server transceiver and SIM800L as the gateway connection for ThingSpeak.


Hardware Used

Software Used

Libraries Used


Application Description

Ra-02 SX1278 LoRa Module

The Ra-02 LoRa module can be used for ultra-long distance spread spectrum communication, with compatible FSK (frequency shift keying) remote modulation and demodulation. This provides a solution for the traditional wireless design which has poor distance coverage, anti-interference and power consumption. The Ra-02 can be widely used in a variety of networking occasions such as automatic meter reading, home building automation, security systems, and remote irrigation systems.

Specifications:

  • Interface: SPI
  • Programmable Bit Rate: up to 300 kbps
  • Frequency Range: 410-525 MHz
  • Antenna: IPEX
  • Max Transmit Power: 18 +/- 1 dBm
  • Power Supply: 2.5~3.7 V, Typically 3.3 V
  • Operating Temperature: -30~85 °C

Dragino LoRa Shield

The Dragino LoRa Shield is a long range transceiver on a Arduino shield form factor and based on Open source library. The LoRa Shield allows the user to send data and reach extremely long ranges at low data-rates. It provides ultra-long range spread spectrum communication and high interference immunity whilst minimizing current consumption.

Specifications:

  • Maximum Link Budget: 168 dB
  • Programmable Bit Rate: up to 300 kbps
  • High Sensitivity: down to -148 dBm
  • Bullet-proof front end: IIP3 = -12.5 dBm
  • Rx Current: 10.3 mA
  • Register Retention: 200 nA
  • Synthesizer Resolution: 61 Hz
  • Modulation: FSK, GFSK, MSK, GMSK, LoRaTM and OOK
  • Dynamic Range RSSI: 127 dB

How Do They Work?

They use a technique called spread spectrum communication. Information is transmitted over a much wider bandwidth than is necessary. By doing so, strength against external narrowband interference is increased. Since the wider the bandwidth of any transmitted signal, the lower the relative influence of interference over a small part of the bandwidth will be. The spread spectrum techniques allow for simultaneous multiplexing of multiple transmissions in the same bandwidth. Since multiple users can share the same spread spectrum bandwidth without interfering with one another, these can be called as multiple access techniques.

You can learn more about spread spectrum communications by clicking here.

SIM800L GSM/GPRS Module

The SIM800L is a cellular module which allows for GPRS data transmission, sending and receiving SMS and making and receiving voice calls. The board is compact in size and has low current consumption. It even features a power saving technique which limits current consumption to as low as 1 mA when not in use. To top it off, the module supports quad-band GSM/GPRS network, meaning it works pretty much anywhere in the world.

How does it work?

The module is intended to operate similar to a cellular phone with a SIM card. After it is powered, the module boots up, searches for the nearest cellular network and connects to it automatically. The LED displays on the board indicate the connection state. It blinks fast when there’s no network coverage, but blinks slow when connected.

DSM501A Dust Sensor

The DSM501A dust sensor module is a low cost and compact particle density sensor. It is capable of quantitative particle measurement of fine particles as small as one micron

How does it work?

An infrared emitting diode and a phototransistor are diagonally arranged inside of the device. This allows it to detect the reflected light of dust in the surrounding air. It is especially effective in detecting very fine particles like cigarette smoke, and is commonly used in air purifier systems.

MQ131 Ozone Gas Sensor

The MQ131 Ozone Gas Sensor, as its name suggests, can sense ozone gas (O3). It has a high sensitivity to ozone while also being sensitive to strong oxides such as CL2 and NO2. These are widely used in air quality monitoring applications, whether it is domestic or industrial.

How does it work?

Inside the black bakelite of the ozone gas sensor is a rather sensitive material called Tungsten trioxide (WO3). Its conductivity is high in clean air, but when ozone gas is present in the surrounding, the conductivity gets lower. Users can convert the change of conductivity to correspond to the output signal for the gas concentration detected.


Hardware Setup

Client (Ra-02 LoRa Module with with Sensors)

Ra-02 LoRa Module Connections

  • 3.3V connected to Arduino 3.3V
  • RST connected to Arduino pin 9
  • DI00 connected to Arduino pin 2
  • GND connected to Arduino Ground
  • NSS connected to Arduino pin 10
  • MOSI connected to Arduino pin 11
  • MISO connected to Arduino pin 12
  • SCK connected to Arduino pin 13

DSM501A Dust Sensor Connections

  • 3rd Wire (VCC) connected to Arduino 5V
  • 4th Wire (PM2.5) connected to Arduino pin 7
  • 5th Wire (GND) connected to Arduino Ground

MQ131 Ozone Gas Sensor Connections

  • A0 connected to Arduino pin A0
  • VCC and GND connected to Arduino 5V and Ground respectively

Server (Dragino LoRa Shield with the SIM800L Module)


ThingSpeak Setup

To setup ThingSpeak, first you have to Sign up on their website https://thingspeak.com. If you already have an account, login and click on “Channels.”

In doing so, you should be directed to your channels page. Click on “New Channel” to create a new channel.

Once loaded, you will be presented with the Channel Settings. Fill up whatever is required and check 2 fields, one for each sensor reading display. You only need to give it a name and a description; the rest are unnecessary.

When you’re done, just scroll to the bottom of the page and hit “Save Channel.” After this, you will be able to view the display privately by clicking the “Private View” tab on top. You can customize the field charts by clicking the pencil icon.

You would also need to get the API keys for your Arduino code in order for the SIM800L to transmit the data to ThingSpeak. To check your API key, click on the “API Keys” tab at the top.


Code

Client (Ra-02 LoRa Module with with Sensors)

Server (Dragino LoRa Shield with the SIM800L Module)


Code Breakdown

Client Code

Pre-Initialization

Before we start, we must include the libraries to be used in the project. The RHReliableDatagram is for sending addressed, acknowledged, and retransmitted datagrams and is under the RH_RF95 library. These two libraries depend on the SPI (Serial Peripheral Interface) to function so that one is included as well. DSM501 and MQ131 libraries are for the dust sensor and ozone gas sensor respectively.

After that, we define the client address and server address. This is important to make sure you’re communicating one-on-one with the your LoRa shield and not any others which could be nearby. Next, we create the RF95 driver object and datagram manager with the driver and client address as the parameters.

Next, we assign the pins to the sensors. For the DSM501, the first parameter is for PM1.0 which we assigned to pin 6. The second parameter is for PM2.5. For the MQ131, the first parameter is for the heater which is already integrated into the module so you can assign it to any pin that’s not already used. The ozone gas sensor we are using is the black bakelite low concentration version so we indicate it on the third parameter. The 10000 is the load resistance. Lastly, we initialize the variable buf to store incoming messages.

void setup()

Inside the setup() function, we set the Serial baud rate to 9600 bps which is the default for serial communication. We then put an if statement to check if the reliable datagram manager has initialized or not by printing a message when it fails. After that, we initialize the DSM501 and MQ131. The base resistance of the MQ131 module was obtained by running o3sensor.calibrate() in code and the time to read is set to 30 seconds.

void loop()

Inside the loop() function, we grab the dust sensor reading with dsm501.update() and then get the particulate matter density of particles over 2.5 µm using dsm501.getParticleWeight(1). We then have to convert this float value to a string and store it in a variable at the same time using dtostrf().

This data can then be sent to the server-side using manager.sendtoWait(). This sends the message (with retries) and waits for an acknowledgement. It returns true if an acknowledgement is received which allows it to print the acknowledgement reply using manager.recvfromAckTimeout().

Next, we grab the ozone gas sensor reading with o3sensor.begin() and then get the value reading in µg/m3 using o3sensor.getO3(UG_M3). If you want to get the parts per billion which is more commonly used in global statistical data reports then you can do so with o3sensor.getO3(PBB) instead. Similar to the dust sensor reading above, we then have to convert the float value to a string and store it in a variable at the same time using dtostrf().

This part is similar to the one above where we send the sensor readings to the server-side, but this time it’s for the ozone gas sensor.

Server Code

Pre-Initialization

Again, we must include the libraries to be used in the project. The SoftwareSerial library allows serial communication on other digital pins of the Arduino which allows us to use pins 2 and 3 as a receiver and transmitter respectively. This also allows us to use it as a debug serial and print out the message received later on.

After that, we define the client address and server address. Again, this is important to make sure you’re communicating one-on-one with the the Ra-02 and not any others which could be nearby so make sure they are the same with what’s in the client-side code. Next, we create the RF95 driver object and datagram manager with the driver and server address as the parameters.

Here, we create the message we want to send to the client when the server-side receives a message as well as initialize the variable buf to store the incoming sensor reading data. The index will be used later to distinguish between the two data values received.

void setup()

Inside the setup() function, we set the serial baud rate to 9600 bps which is the default for serial communication and the GSM serial baud rate to 4800 bps. After that, we put an if statement to check if the reliable datagram manager has initialized or not by printing a message when it fails.

SIM800L AT Commands for Sending Data to ThingSpeak

AT (ATtention) commands are instructions used to control a modem. Firstly, AT+CIPMODE=0 sets the TCPIP application mode to normal as this is necessary to govern the connection of the SIM800L to the Internet. Secondly, AT+CIPMUX=0 starts up a single IP connection and AT+CGATT=1 attaches us to the GPRS service. Thirdly, AT+CSTT=”APN” starts task and sets the access point name to the url specified and AT+CIICR brings up the wireless connections with GPRS. You can find the APN to use for the SIM card you have online.

Next, AT+CIFSR gets your local IP address and AT+CIPSTART=”TCP”,”184.106.153.149″,”80″ will start up the TCP connection to ThingSpeak. Lastly, AT+CIPSEND=80 allows you to send data to ThingSpeak with about 80 characters length. This is where the GET command is run. Change the API key in the updateTS string; you have to make sure the API key in the link matches the one in your channel by checking the “API Keys” tab in your ThingSpeak channel. It’s also important to note that AT+CIPSHUT has to be sent by the end of all these to ensure that the GPRS is deactivated. If you don’t shut it down, it may time itself out.

void loop()

Inside the loop() function, we check for when there’s a message received with manager.available() and if index is 1, that means it’s the first sensor’s data. recvfromAck() will get the data from the buffer and print it in the serial monitor. Once done, it will call the gsmSend() function which contains all the AT commands to send the data to ThingSpeak then set the index to 2 so it knows the second sensor’s data is next to come.

This part is similar to the one above where we send the data to ThingSpeak, but this time it’s for the second received data which is from the second sensor.


Conclusion

LoRa is a low data rate, low power, and low power wireless platform technology for building IoT networks. It is more cost efficient in the long run compared to other alternatives due to its wide list of features. The transceivers can communicate in up to 15 kilometers distance away from each other which is really far, often more than enough for many applications. LoRa Technology operates in the unlicensed ISM band, therefore is legal and great for educational purposes.

The sensors I used for this project were a bit harder to test due to the difficulty of finding values to compare. One has to be very specific in searching online for air quality monitoring value standards for dust particulate matter and ozone gas concentration. Luckily, the libraries we have for both sensors handle the calculation for us.


Sensor Reading Comparison

These are the guidelines or standards defined by the World Health Organization for dust particulate matter PM2.5 and Ground-Level Ozone Gas:

To get the AQI (Air Quality Index) for comparison, you can use an online AQI calculator.


References

read more
ArduinoKnowledgeBase

Bluetooth-Controlled Mini Lift Using Stepper Motor with Android Mobile App

20190504_165443

Overview

This Mini Lift project is achieved with the use of a stepper motor. The motor will rotate either clockwise or counterclockwise depending if you want it to go up or down, controlled by a mobile app with Bluetooth. Additionally, the TFT LCD display is to show the user which floor it is currently on as well as when it is moving.


Hardware Used

Software Used

Libraries Used


Application Description

Stepper Motor NEMA 17

A stepper motor, also known as step motor or stepping motor, is a type of brushless DC electric motor. Very precise positioning and speed control can be achieved with a computer controlled stepping. For this reason, stepper motors are the motor of choice for many precision motion control applications. 

How does it work?

Stepper motors divide a full rotation into a number of equal steps. They have multiple coils that are organized in groups called phases. By using electromagnets to energize each phase in sequence, the motor will rotate, one step at a time.

Specifications:

  • Phase: 2
  • Step Angle: 1.8 degrees
  • Step angle accuracy: +/- 5% (full step, not load)
  • Rated Current: 1.3 A
  • Phase Resistance: 2.4 Ω
  • Resistance accuracy: +/- 10%
  • Phase Inductance: 2.8 mH
  • Inductance accuracy: +/- 20%
  • Holding Torque: 28 N.cm
  • Detent Torque: 1.6 N.cm
  • Rotor Inertia: 34 g.cm²

Stepper Motor Driver DRV8825

The DRV8825 stepper motor driver features adjustable current limiting, over-current protection, over-temperature protection, and six microstep resolutions (down to 1/32-step). It operates from 8.2 V to 45 V and can deliver up to approximately 1.5 A per phase without a heat sink or forced air flow (rated for up to 2.2 A per coil with sufficient additional cooling).

How does it work?

The stepper motor driver is the circuit that controls how the stepper motor operates. It works by sending current through various phases in pulses to the stepper motor. The DRV8825, which is a microstepping driver, allows higher resolutions by allowing intermediate step locations, which are achieved by energizing the coils with intermediate current levels.

Specifications:

  • Operating Voltage: 8.2-45 V
  • Continuous current per phase: 1.5 A
  • Maximum current per phase: 2.2 A
  • Logic Voltage: 2.5-5.25 V
  • Microstep Resolutions: Full, 1/2, 1/4, 1/8, 1/16, and 1/32

HC-05 Bluetooth Module

The HC-05 Bluetooth Module is an easy to use Bluetooth SPP (Serial Port Protocol) module, designed for transparent wireless serial connection setup. It is one of the highest rated and used wireless communication protocols in embedded projects due to its low cost and wide range of applications.

How does it work?

Serial port Bluetooth module is fully qualified Bluetooth V2.0+EDR (Enhanced Data Rate) 3Mbps Modulation with complete 2.4GHz radio transceiver and baseband. It uses CSR Bluecore 04-External single chip Bluetooth system with CMOS technology and with Adaptive Frequency Hopping feature. In layman’s terms, the Bluetooth technology manages the wireless communication channel. The Bluetooth modules can transmit and receive the data wirelessly. It communicates via serial communication which makes an easy way to interface with a microcontroller.

Specifications:

  • Input Voltage: 5 V
  • Communication Method: Serial
  • Frequency: 2.4 GHz
  • Default PIN/password: 1234
  • Master and slave mode can be switched

2.2-inch TFT LCD Display ILI9341 (240×320)

TFT LCD is short for thin-film-transistor liquid-crystal display. It is a variant of a LCD that uses thin-film transistor technology to improve image qualities such as addressability and contrast. These are commonly used in appliances including computer monitors, mobile phones, handheld devices, video game systems, navigation systems, projectors, and television.

How does it work?

All the pixels on a TFT LCD screen are configured in a row-and-column format, and each pixel is attached to a very tiny silicon transistor that rests directly on the glass panel. This setup allows each pixel to be given a charge and for the charge to be kept even when the screen is refreshed to produce a new image.


Hardware Setup

2.2-inch TFT LCD Display Connections

Important note: The 2.2-inch TFT LCD display we are using can only work on 3.3V logic. Unlike most Arduino boards, the Arduino Due board runs at 3.3V making it the perfect one to use. Of course, other boards like the Arduino Uno can still be used as long as there is proper logic level shift applied using resistors. Click here for a guide on that.

  • SDO/MISO connected to Arduino Due SPI MISO2 pin
  • LED connected to Arduino Due 5V with a 47Ω resistor in series
  • SCK connected to Arduino Due SPI SCK2 pin
  • SDI/MOSI connected to Arduino Due SPI MOSI2 pin
  • DC/RS connected to Arduino Due pin 26
  • RESET connected to Arduino Due pin 22
  • CS connected to Arduino Due pin 24
  • Vcc and Gnd connected to Arduino Due 5V and Ground respectively

HC-05 Bluetooth Module Connections

  • RXD connected to Arduino Due pin TX2 16
  • TXD connected to Arduino Due pin D4
  • Vcc and Gnd connected to Arduino Due 5V and Ground respectively

Stepper Motor Driver DRV8825 Connections

  • DIR connected to Arduino Due pin 2
  • STEP connected to Arduino Due pin 3
  • RESET and SLEEP connected to Arduino Due 5V
  • GND (left of image) connected to Arduino Due Ground
  • VMT and GND (right of image) connected to 9V power supply and its Ground respectively with a 100uF capacitor in series

Stepper Motor NEMA 17 Connections

Important note: Before connecting the stepper motor to the driver, we must first limit the current of the driver that would be going into the motor.
The stepper motor we are using has a maximum current rating of 1.3 A with a 2.4Ω phase resistance, which would indicate a maximum motor supply of 3.12V. Using this motor with a higher voltage would allow higher step rates, but the current must actively be limited to under 1.3 A to prevent damage to the motor.

One way to set the current limit is to adjust and measure the voltage on the REF pin to calculate the resulting current limit. The REF pin is the circle on the circuit board and can be adjusted using a small screwdriver. The current limit is twice of the reference voltage so to set the current limit to 1.3A, we must set the reference voltage to 0.65V.

  • 1st wire (usually red) connected to Stepper Motor Driver pin 1B
  • 2nd wire (usually black) connected to Stepper Motor Driver pin 2B
  • 3rd wire (usually blue) connected to Stepper Motor Driver pin 1A
  • 4th wire (usually green) connected to Stepper Motor Driver pin 2A

Android App Setup

For the Android mobile app, we will use the cloud-based MIT app inventor. In just a few steps, you can set it up and start building apps! First things first, you will need to install the App Inventor Companion App on your Android device. If you do not have an Android device, you’ll need to install software on your computer so that you can use the on-screen Android emulator. Learn more about the initial setup by clicking here.

Once all that is done, click on the Project tab, then start a new project and give it a proper name. When you’re in the main interface, you’ll see a palette on the left, a viewer in the middle, then a components and properties tab on the right. Drag and drop the following components from the palette onto the viewer screen accordingly and in order (left). To make it easier to identify the components, change their names to whatever you want using the rename button that is below (right). Following this format with specific components inside a certain arrangement makes it easier to hide or show a group of components at a time when needed later on.

You can customize the labels and buttons to your own liking. Personally, I have added my own custom button images as well as a grayscale version of it to be used when the button is disabled. You can also add a background image on Screen1 to make it look prettier (left). After this, uncheck VerticalArrangement3’s visibility so it will look like a pre-connected screen (right).

To see how the app looks on your phone, connect it to the App Inventor Companion by clicking on the connect button on the top menu and selecting AI companion. An importable .aia file download for this will be included below with the code, as well as an .apk for direct installation.


Code

Arduino Code

MIT App Inventor Code


Code Breakdown

Arduino Code

Pre-Initialization

Before we start, we must include the libraries to be used in the project. The Adafruit_ILI9341 library is needed to control what the TFT LCD display, and since it uses and depends on Serial Peripheral Interface, the SPI library is also included.

After that, we define the direction and step pins for the stepper motor, as well as the steps per revolution. Typical stepper motors are 1.8 degrees per step, which is 200 steps per revolution. Next, we define the DC, CS, and reset pins for the TFT LCD display and create TFT object with the respective pins assigned.

Next, we initialize the variables to be used later on. input is to store the incoming input data. lastInput is to store the previous input. The other variables will be explained later down the line.

void setup()

Inside the setup() function, we set the Serial2 baud rate to 9600 bps which is the default for serial communication. Arduino Due has 4 serial pins and we’re using Serial2 which is located on pins 16 and 17. We also initialize the TFT and immediately call in the displayFloor function (to be explained later). Next, we set the stepper motor pins as output.

Stepper motor control functions

The moveUp and moveDown functions are pretty similar with the only difference being the direction pin being set to HIGH for rotating the motor clockwise, and LOW for rotating it counter-clockwise. It’s basically a for loop that would turn the motors up to a certain point and the delayMicroseconds dictate how fast you want it to go. The steps per revolution multiplied by the floorDiff to dictate how many times it should rotate and then added by a compensation value. This compensation value is important if you are using a one-sided rolling belt method for the lift like I did, because as the rubber belt rolls, it will accumulate radius and require lesser rotations to reach the same height.

TFT display functions

The displayFloor function prints the text on the TFT LCD display. First, the screen is filled black and rotated 90 degrees so it will be on landscape view. The 1 in the setRotation parameter indicates 90 degrees and you can set it from 0-3. Then, the cursor is set on the specific coordinates to have the text that is about to be printed on the center of the screen. If you want it at the top, then the cursor coordinates would be 0 and 0. Printing the text would be similar to how you’d normally print it in the serial monitor. A cool thing with the library we used is that we can also customize the text color and text size.

The displayMoving function is what gets called when the stepper motor is moving. It basically just shows from which floor to which floor it is moving. (char)24 and (char)25 are up and down arrows respectively. Like the displayFloor function, I have tried to make it look a bit more fancy by setting text colors and adding makeshift borders.

serialEvent function

The serialEvent function checks for when there is data in the Bluetooth Serial. While there’s data available, it will store that data in the input variable and then set the boolean stringComplete to true to indicate that it has received the data successfully.

void loop()

Inside the loop() function, we call in the serialEvent which will tell us when it has received data successfully. If it has received data, it goes into the if statement and sends the received data to through Serial2. If the last input is lesser than the new input then it calls the moveUp function, otherwise, it calls the moveDown function. floorDiff is calculated here so it knows how many times to move up or move down. After moving, it calls the displayFloor function to display which floor it is currently at. The delay here is necessary so there is time for the communication to process. Next, the new input is stored as the last input and the boolean stringComplete is set back to false to indicate that it has finished receiving the data and there are no more available to receive.

There’s a long block of code in the loop where I set the calibration values depending on how much the rubber belt has rolled that I did not include here (but is in the downloadable file) since that depends on what rubber belt you are using, and if you are even using the one-sided rolling belt method.

MIT App Inventor Code

Connection Buttons

Since the MIT App Inventor uses code blocks, it should be easier to understand. When the BluetoothBTN (ListPicker) is clicked, “.BeforePicking” is what happens before the user picks something from a certain list. In this case, we want to show the user a list of Bluetooth devices nearby that they can connect to so we set the BluetoothBTN’s elements to the that.

“.AfterPicking” is what happens after the user has picked a Bluetooth device to connect to. If it has connected to the HC-05 Bluetooth module successfully, it will set the visibility of VerticalArrangement2, which contains the ConnectLabel and BluetoothBTN to false and set visibility of VerticalArrangement3, which contains the other components to true. Following that, it checks for the state of the lift so the app takes off where it has left. If for example, it was at floor 1, the floor 1 button would be disabled. The app should look like this afterwards.

The DisconnectBTN does exactly what it names implies – it disconnects the app from the Bluetooth device and sets VerticalArrangement2 back to true and VerticalArrangement3 back to false, which are the settings prior to connection.

Floor Buttons

For the rest of the code, it’s what happens when you click on the floor buttons. When the Floor1BTN is clicked, it checks if the user is still connected to the Bluetooth device and sends the value 1 via Bluetooth for the HC-05 Bluetooth module to receive. This value will be stored in the input variable in the Arduino code which helps in telling the stepper motor how many times it has to rotate with the calculations explained above.

The rest of the code is just to disable the button after it has been pressed by setting enabled to false and changing the button image to the grayscale version, then enable the other buttons which would have been previously disabled by setting enabled to true and changing the button image back to the regular version.


Conclusion

Stepper motors are really strong. The motor’s position can be caused to move and hold at one of these steps as long as the motor is carefully sized to the application in respect to torque and speed. In my case, it was able to lift up a bunch of office supplies. It can lift weights heavier than this, according to several experiments that have been conducted by other sources. Furthermore, they are used in a wide variety of applications such as industrial machines, medical scanners, blood analysis machinery, 3D printing equipment, etc.


References

read more
ArduinoKnowledgeBase

Bluetooth-Controlled AC Light Dimmer with Android Mobile App

Featured Image

Overview

The light level in a room has a huge effect on one’s mood and productivity. Lighting can contribute to your alertness and awakeness in the mornings, and it can either entice you to feel tired or keep you up all night. With all of these discoveries on the effects of lighting, it is becoming more and more important to be able to control lighting. In addition, a mobile app that uses Bluetooth to control and dim lights would be perfect!

Having a dimmer installed in the lighting systems of your home or office gives you the ability to adjust the intensity and brightness based upon the particular time of day and the specific task at hand.


Hardware Used

Important note: Luminescent lamps or gas discharge lamps do not support dimming. Filament lamps or LED lamps are recommended, but not all support dimming either. Make sure to check if the lamp is capable of dimming effects.

Software Used

Libraries Used


Application Description

AC Light Dimmer Module

The AC Light Dimmer is designed to control the alternating current voltage, which can transfer current up to 600V/16А. It is basically a TRIAC with some supporting components. The power part of the dimmer is isolated from the control to exclude the possibility of high current disruption to a microcontroller. This is mainly used to smoothly change the light brightness of lamps, but can also be applied to control fans, pumps, air cleaners, etc.

How does it work?

The AC Light Dimmer uses Pulse Skipping Modulation (PSM), or as some sources call it, Pulse Skip Modulation, to achieve dimming. It has a zero-crossing detection, which gives a signal on the Z-C pin every time the AC sine wave crosses zero voltage. PSM works with modulating the number of pulses or full sine wave periods that are transmitted to the load. Imagine you want to dim the light in 100 distinct values. For 100% brightness, PWM pin should be set to HIGH when a full sine wave is starting up until 100 periods. For 25% brightness, PWM pin should be set to HIGH for 25 full periods and then LOW for the next 75 periods. To make things easier, all these will be handled by the Robotdyn dimmer library which will be discussed later down in the codes.

Specifications:

  • Power: 600 V / 16 A
  • AC Frequency: 50/60 Hz
  • TRIAC: BTA16 – 600B
  • Modulation: Pulse Skipping Modulation
  • Logic Level Input Voltage: 5 V

HC-05 Bluetooth Module

The HC-05 Bluetooth Module is an easy to use Bluetooth SPP (Serial Port Protocol) module, designed for transparent wireless serial connection setup. It is one of the highest rated and used wireless communication protocols in embedded projects due to its low cost and wide range of applications.

How does it work?

Serial port Bluetooth module is fully qualified Bluetooth V2.0+EDR (Enhanced Data Rate) 3Mbps Modulation with complete 2.4GHz radio transceiver and baseband. It uses CSR Bluecore 04-External single chip Bluetooth system with CMOS technology and with Adaptive Frequency Hopping feature. In layman’s terms, the Bluetooth technology manages the wireless communication channel. The Bluetooth modules can transmit and receive the data wirelessly. It communicates via serial communication which makes an easy way to interface with a microcontroller.

Specifications:

  • Input Voltage: 5 V
  • Communication Method: Serial
  • Frequency: 2.4 GHz
  • Default PIN/password: 1234
  • Master and slave mode can be switched

Hardware Setup

HC-05 Bluetooth module connections

  • RXD connected to Arduino pin D5
  • TXD connected to Arduino pin D4
  • Vcc and Gnd connected to 5V and Ground respectively

AC Light Dimmer module connections

  • Z-C connected to Arduino pin D2
  • PWM connected to Arduino pin D3
  • Vcc and Gnd connected to 5V and Ground respectively

Android App Setup

For the Android mobile app, we will use the cloud-based MIT app inventor. In just a few steps, you can set it up and start building apps! First things first, you will need to install the App Inventor Companion App on your Android device. If you do not have an Android device, you’ll need to install software on your computer so that you can use the on-screen Android emulator. Learn more about the initial setup by clicking here.

Once all that is done, click on the Project tab, then start a new project and give it a proper name. When you’re in the main interface, you’ll see a palette on the left, a viewer in the middle, then a components and properties tab on the right. Drag and drop the following components from the palette onto the viewer screen accordingly and in order (left). To make it easier to identify the components, change the label names to whatever you want using the rename button that is below (right). Following this format with specific components inside a certain arrangement makes it easier to hide or show a group of components at a time when needed later on.

Change the label and button texts accordingly and add an image to the BluetoothBTN to give the user a button to click on for connecting. You can also add a background image on Screen1 to make it look prettier (left). After this, hide VerticalArrangement3 so it will look like a pre-connected screen (right).

To see how the app looks on your phone, connect it to the App Inventor Companion by clicking on the connect button on the top menu and selecting AI companion. An importable .aia file download for this will be included below with the code, as well as an .apk for direct installation.


Code

Arduino Code

MIT App Inventor Code


Code Breakdown

Arduino Code

Pre-Initialization

Before we start, we must include the libraries to be used in the project. The Arduino hardware has built-in support for serial communication on pins 0 and 1. The SoftwareSerial library allows serial communication on other digital pins of the Arduino which allows us to use pins 4 and 5 as a receiver and transmitter respectively. This also allows us to use it as a debug serial and print out the message received later on.

Next, we define the pins to be used for PWM and zero-crossing. In our case, PWM is in pin 3. If you’re using an Arduino Uno, Leonardo, Mega, M0, or Zero, you don’t need to define the zero-crossing pin since it is already set by default in the Robotdyn library. In case you’re using other boards, define the zero-crossing pin accordingly and use the commented out dimmerLamp line of code to initialize the dimmer instead.

After that, we initialize the variable for an input and set the minimum and maximum brightness. The values for these will depend on the lamp used. However, several tests have to be conducted to get them. In my case, anything on or below 35 won’t turn on the lamp so I set that as the minimum and anything above or on 85 won’t make it brighter so I set that as the maximum.

void setup()

Inside the setup() function, we set the serial and Bluetooth serial baud rate to 9600 bps which is the default for serial communication. We then initialize the dimmer and print a message in the Serial to indicate a successful initialization.

serialEvent function

Before going to the loop() function, we must first understand what role the serialEvent function play, serialEvent checks for when there is data in the Bluetooth Serial. While there’s data available, it will store that data in the input variable and then set the boolean stringComplete to true to indicate that it has received the data successfully.

void loop()

Inside the loop() function, we call in the serialEvent which will tell us when it has received data successfully. If it has received data, it goes into the if statement and maps the input value from 0 to 100 to the minimum and maximum brightness we have set earlier. After that we set the lamp’s power with dimmer.setPower() then print the value on the serial for debugging purposes. We then set the boolean stringComplete back to false to indicate that it has finished receiving the data and there are no more available to receive.

MIT App Inventor Code

Connection buttons

Since the MIT App Inventor uses code blocks, it should be easier to understand. When the BluetoothBTN (ListPicker) is clicked, “.BeforePicking” is what happens before the user picks something from a certain list. In this case, we want to show the user a list of Bluetooth devices nearby that they can connect to so we set the BluetoothBTN’s elements to the that.

“.AfterPicking” is what happens after the user has picked a Bluetooth device to connect to. If it has connected to the HC-05 Bluetooth module successfully, it will set the visibility of VerticalArrangement2, which contains the ConnectLabel and BluetoothBTN to false and set visibility of VerticalArrangement3, which contains the other components to true. The app should look like this afterwards.

The DisconnectBTN does exactly what it names implies – it disconnects the app from the Bluetooth device and sets VerticalArrangement2 back to true and VerticalArrangement3 back to false, which are the settings prior to connection.

Slider

Here’s the most important part of the code. “.PositionChanged” is triggered when the slider’s position changes. Inside the function we set the BrightnessValue label’s text to the slider’s thumb position. The thumb position is where the slider is currently at so having the label indicate its value will be helpful for the user. At the same time, it checks if the user is still connected to the Bluetooth device and sends the thumb position value via Bluetooth for the HC-05 Bluetooth module to receive.


Conclusion

Bluetooth wireless communication has been rising in popularity nowadays due to its low cost and wide range of applications. Moreover, most modern phones have Bluetooth, making it excellent controllers for Bluetooth-supported devices. This opens up a lot of possibilities with IOT that incorporate Bluetooth as a way of communication.

MIT App Inventor is a great place for beginners and hobbyists to begin making their mobile apps. It does not require a lot of background in programming and has an interface that is easy to use and understand. In other words, it’s a great stepping stone towards creating mobile applications.


References

read more
ArduinoKnowledgeBase

Wireless Security System using APDS-9960 Gesture Sensor and 433MHz RF Transmitter-Receiver

20190416_133554

Overview

Ever wanted a home security system wherein the alarm is far away from the main gate without having to use long wires? Perhaps somewhere inside your room where you can see the flashing light indicators and hear the buzzer even with headphones on. Using the APDS-9960 Gesture sensor along with the 433MHz RF Transmitter and Receiver Pair, this system can be achieved!

With a few tweaks on the code, this can even be turned into a monitoring system for people entering or leaving the house. There are many possibilities, limited to what you replace the actuator with.


Hardware Used

Software Used

Libraries Used


Application Description

APDS-9960 Gesture Sensor

The APDS-9960 Gesture Sensor module is not only capable of touchless gesture sensing, but is also capable of advanced proximity detection, ambient light sensing, and RGB color sensing. Four sensors in such a slim modular package! For this project however, we’ll only be focusing on the gesture sensing. You can check out how to use its proximity sensing feature to turn LEDs on by clicking here.

How does it work?

It utilizes four directional photodiodes to sense reflected IR energy to convert physical motion information (i.e. velocity, direction and distance) to a digital information. Learn more from its datasheet.

433MHz RF Transmitter-Receiver Pair

The 433MHz RF Transmitter and Receiver Pairis widely used because it has high volume of applications compared IR and is inexpensive. RF signals can travel from the transmitter to the receiver even when there is obstruction present, which is perfect for this project. Its range can reach up to 200 meters, which is more than enough for the project.

How does it work?

• Transmitter

When the RF transmitter receives serial data, it transmits it to the receiver through an antenna. The saw resonator inside the transmitter will run and produce a constant RF output carrier wave of 433MHz when logic 1 is sent. The transmitter does not draw power when transmitting logic 0 since it fully suppresses the carrier frequency. This means that it is power efficient, as it significantly decreases power consumption. This technique is known as ASK or amplitude shift keying.

• Receiver

The receiver module consists of an RF tuned circuit and a couple of OP Amps to amplify the received carrier wave from the transmitter. The amplified signal is then fed to a PLL or Phase Lock Loop which allows the decoder to give better decoded output and noise immunity.

Specifications of the Transmitter:

Specifications of the Receiver:


Hardware Setup

Sensor and Transmitter

APDS-9960 Gesture Sensor Connections

  • SDA connected to Arduino pin A4
  • SCL connected to Arduino pin A5
  • INT connected to Arduino pin D2
  • Vcc and Gnd connected to 5V and Ground respectively

Fun Fact: SCL (Serial Clock) and SDA (Serial Data) pins are the dedicated pins for I2C communication. On the Arduino Uno they are found on Analog pins A4 and A5.

433MHz RF Transmitter Connections

  • Data connected to Arduino pin D12
  • Vcc and Gnd connected to 5V and Ground respectively

Receiver and Actuator

433MHz RF Receiver Connections

  • Data connected to Arduino pin D11
  • Vcc and Gnd connected to 5V and Ground respectively

LEDs and Buzzer Connections

  • LEDs connected to Arduino pins D10 down to D7 respectively
  • Buzzer connected to Arduino pin D6

Code

Transmitter code

Receiver Code


Code Breakdown

Transmitter

Pre-Initialization

First things first, we must include the libraries to be used in the project. The Adafruit_APDS9960 library will allow the Gesture Sensor to work. The RH_ASK library is from the RadioHead packet radio library for embedded processors that uses ASK or amplitude shift keying to send and receive data. This, along with the SPI (Serial Peripheral Interface) library which it is dependent on, will allow the RF Transmitter to work. The ASK object and APDS-9960 object is then created.

void setup()

Inside the setup() function, we set the serial baud rate to 300 bps since tiny RF modules best works on low baud rates. At high baud rates, the chance of data loss during propagating through air is much higher. Following that, the if-else statements will print a message in the Arduino serial to let the user know if the gesture sensor and the RF transmitter has been initialized successfully or not.

The last two lines inside the setup() function will enable the proximity sensor and gesture sensor. Once proximity mode senses something close, the gesture mode will be entered.

void loop()

Inside the loop() function, we try to constantly get a reading from the gesture sensor and store that value in an uint8_t datatype – an unsigned integer that is 8 bits in length, to minimize memory usage. A simple text string is then declared and stored in a character pointer named msg. For this, only one character is used to allow better overall performance, but it does not necessarily have to be one character only. Keep in mind the number of characters in the message, as the count will be needed in the receiver code later on.

When the sensor reads a left swipe gesture, the message “L” will be transmitted using the send() function and if it reads a right swipe gesture, the message “R” will be transmitted instead. The send() function has two parameters – first is the array of data and second is number of bytes to be sent. This is then followed by the waitPacketSent() function which waits until the previous packet is finished being transmitted. After that, a delay of one second is set to give the receiver time to take in the data.

Receiver

Pre-Initialization

Similar to the transmitter side of the code, we must include the libraries to be used in the project. The RH_ASK library is from the RadioHead packet radio library for embedded processors that uses ASK or amplitude shift keying to send and receive data. This, along with the SPI (Serial Peripheral Interface) library which it is dependent on, will allow the RF Transmitter to work. The ASK object is then created.

void setup()

Inside the setup() function, we set the serial baud rate to 300 bps to match the baud rate of the transmitter. Then, we assign the LEDs and buzzer to their respective pins. Following that, the if-else statements will print a message in the Arduino serial to let the user know if the RF receiver has been initialized successfully or not.

void loop()

Inside the loop() function, we create a buffer of size same as the transmitted message. In this case, it’s only one character.

Next, we call a recv() function to turn the receiver on. If there is a valid message available, it copies the message to its first parameter buffer and returns true, otherwise it returns false. If the function returns true, the sketch enters into the nested if statement.

In the nested if statement, strcmp() is used to compared the received string. It will output a 0 if the strings are equal, which is why the ! or NOT is necessary to turn it into a 1. If the message “L” is received, it signifies a left swipe and sweeps the LEDs from right to left, as well as turn the buzzer on and off with a short delay to simulate beeping. If the message “R” is received, it signifies a right swipe and sweeps the LEDs from left tor right. I did not include the buzzer beeping for the right swipe so it only alters the users when someone enters the house.


Conclusion

Wireless communication is always fun to experiment with. There are tons of possibilities that can be brought about using these modules, especially with regards to ease of access and convenience for the user. The 433MHz RF Transmitter-Receiver Pair is interesting because it uses ASK or amplitude shift keying to transmit and receive data and is commonly used in wireless security systems, car alarm systems, remote controls, and sensor reporting.


References

read more

Warning: Cannot assign an empty string to a string offset in /home/createl1/public_html/community/wp-includes/class.wp-scripts.php on line 486

Warning: Cannot assign an empty string to a string offset in /home/createl1/public_html/community/wp-includes/class.wp-scripts.php on line 486