Search Results
163 results found with an empty search
- Random data Sending & Receiving Using NRF24L01 Wireless Transceiver
In this tutorial to learn sending and receiving random data from NRF24L01 Wireless Transceiver using Arduino nano. we will learn how to make Radio Frequency wireless communication using the nRF24L01+PA transceiver module is designed to operate in 2.4 GHz worldwide ISM frequency band and uses GFSK modulation for data transmission. The data transfer rate can be one of 250kbps, 1Mbps and 2Mbps. The NRF24L01 module is a low-cost ultra-low power, bi-directional transceiver module. The module can achieve data rates as high as 2Mbits! and uses a high-speed SPI interface in order to communicate with the Arduino and IOT. Components required Transmitter: Arduino Nano - 1 no LCD1602 with I²C - 1no nRF24L01+PA- 1no 3.3V breakup module -1no Receiver: Arduino Nano - 1 no LCD1602 with I²C - 1no nRF24L01+PA- 1no 3.3V breakup module -1no Circuit diagram The diagram shows the detail connections of NRF24L01module with Arduino. Connect VCC of NRF24L01 module to Arduino Nano’s 3V3 pin Connect GND of NRF24L01 module to Arduino Nano’s GND pin Connect CE of NRF24L01 module to Arduino Nano’s Digital Pin 7 Connect CSN of NRF24L01 module to Arduino Nano’s Digital Pin 8 Connect SCK of NRF24L01 module to Arduino Nano’s Digital Pin 13 Connect MOS of NRF24L01 module to Arduino Nano’s Digital Pin 11 Connect MISO of NRF24L01 module to Arduino Nano’s Digital 12 NRF24L01 Wireless RF Module Refer blog for more detail: https://www.dofbot.com/post/nrf24l01-wireless-temperature-monitor-with-bluetooth Transmitter Circuit: The transmitter circuit side consists of an Arduino Nano, nRF24L01+PA module and 1602 LCD with I2C module. Arduino generate random data and sends it to the nRF24L01 Transmitter. Then the nRF transmitter circuit transmits the data into the air. Receiver Circuit: The receiver circuit side consists of an Arduino Nano, nRF24L01+PA module and 1602 LCD with I2C module. The nRF module receives the random data from the transmitter and sends it to LCD display through Arduino. Installing Library NRF24L01: you need to Download and install the RF library. LiquidCrystal_I2C.h : you need to Download and install the LiquidCrystal_I2C library. Follow the next steps to install those libraries. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After installing the required libraries, copy the following code to your Arduino IDE. Arduino Code Transmitter Code #include "nRF24L01.h" //NRF24L01 library created by TMRh20 https://github.com/TMRh20/RF24 #include "RF24.h" #include "SPI.h" #include LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x3F for a 16 chars and 2 line display int SentMessage[1] = {000}; // Used to store value before being sent through the NRF24L01 RF24 radio(7, 8); // NRF24L01 used SPI pins + Pin 9 and 10 on the NANO const byte address[6] = "00001"; void setup(void) { lcd.init(); lcd.backlight(); lcd.setCursor(0, 0); lcd.print("Initializing"); lcd.setCursor(0, 1); lcd.print("Transmitter"); delay(2000); radio.begin(); // Start the NRF24L01 // Max power radio.setPALevel( RF24_PA_MAX ) ; // Min speed (for better range I presume) radio.setDataRate( RF24_250KBPS ) ; // 8 bits CRC radio.setCRCLength( RF24_CRC_8 ) ; // increase the delay between retries & # of retries radio.setRetries(15, 15); radio.setAutoAck(false); radio.openWritingPipe(address); radio.setPALevel(RF24_PA_MIN); radio.stopListening(); } void loop(void) { int num ; num = random(0, 100); SentMessage[0] = num; DataToLcd((String) SentMessage[0], 0); radio.write(SentMessage, 1); // Send value through NRF24L01 delay(1000); } void DataToLcd(String message1, int delayValue) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("NRF Transmitter"); lcd.setCursor(0, 1); lcd.print("Sending data:"); lcd.setCursor(13, 1); lcd.print(message1); delay(delayValue); } Subscribe and Download code. Transmitter Receiver Code #include "nRF24L01.h" //NRF24L01 library created by TMRh20 https://github.com/TMRh20/RF24 #include "RF24.h" #include "SPI.h" #include LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x3F for a 16 chars and 2 line display int SentMessage[1] = {000}; // Used to store value before being sent through the NRF24L01 RF24 radio(7, 8); // NRF24L01 used SPI pins + Pin 9 and 10 on the NANO const byte address[6] = "00001"; void setup(void) { lcd.init(); lcd.backlight(); lcd.setCursor(0, 0); lcd.print("Initializing"); lcd.setCursor(0, 1); lcd.print("Transmitter"); delay(2000); radio.begin(); // Start the NRF24L01 // Max power radio.setPALevel( RF24_PA_MAX ) ; // Min speed (for better range I presume) radio.setDataRate( RF24_250KBPS ) ; // 8 bits CRC radio.setCRCLength( RF24_CRC_8 ) ; // increase the delay between retries & # of retries radio.setRetries(15, 15); radio.setAutoAck(false); radio.openWritingPipe(address); radio.setPALevel(RF24_PA_MIN); radio.stopListening(); } void loop(void) { int num ; num = random(0, 100); SentMessage[0] = num; DataToLcd((String) SentMessage[0], 0); radio.write(SentMessage, 1); // Send value through NRF24L01 delay(1000); } void DataToLcd(String message1, int delayValue) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("NRF Transmitter"); lcd.setCursor(0, 1); lcd.print("Sending data:"); lcd.setCursor(13, 1); lcd.print(message1); delay(delayValue); } Subscribe and Download code. Receiver Demo Code description we need to include the basic SPI and the newly installed RF24 libraries and create an RF24 object. The two arguments here are the CSN and CE pins. RF24 radio(7, 8); // CE, CSN Next we need to create a byte array which will represent the address, or the so called pipe through which the two modules will communicate. const byte address[6] = "00001"; We can change the value of this address to any 5 letter string and this enables to choose to which receiver we will talk, so in our case we will have the same address at both the receiver and the transmitter.
- nRF24L01 Wireless Temperature Monitor with Bluetooth
In this tutorial, we will learn how to make Radio Frequency wireless communication using the nRF24L01+PA transceiver module that operates on 2.4 - 2.5 GHz (ISM band) with range 1000m distance. An arduino based wireless communication and interface DHT 11 temperature Monitor. The transmitter circuit side consists of an Arduino Nano, nRF24L01+PA module and DHT11 Temperature sensor. Arduino gets data from the DHT11 sensor and sends it to the nRF24L01 Transmitter. Then the nRF transmitter circuit transmits the data into the air. The receiver circuit side consists of an Arduino Nano, nRF24L01+PA module, 1602 LCD with I2C module and Bluetooth HC-05. The nRF module receives the data from the transmitter and sends it to Arduino. An arduino send data to Bluetooth. Components required Transmitter: Arduino Nano - 1 no DHT 11 - 1 no nRF24L01+PA- 1no Receiver: Arduino Nano - 1 no Bluetooth HC-05 - 1 no LCD1602 with I²C - 1no nRF24L01+PA- 1no Circuit diagram Transmitter Circuit: Receiver Circuit: NRF24L01 Wireless RF Module The NRF24L01 module is the latest in RF modules. This module uses the 2.4GHz transceiver from Nordic Semiconductor, the NRF24L01+. This transceiver IC operates in the 2.4GHz band and has many new features! Take all the coolness of the 2.4GHz NRF24L01+PA+LNA SMA Wireless Transceiver Antenna and add some extra pipelines, buffers, and an auto-retransmit feature. This board features a reverse polarized SMA connector for maximum RF range. And there is PA and LNA circuit on board, with the external antenna it can reach long distance than the one without these parts. This module comes with the 2.4G antenna (2DB), with a 250Kbps transmission rate on open-air it can reach the 800-1K meters communication distance. Circuit Diagram for nRF24L01 PA You can easily add it with your own MCU/ARM/PIC/AVR/STM32 system! What’s more, this nRF24L01+ module is designed with the Power amplifier and SMA antenna This allowed you to use the wireless communication up to 1000 meters! (No barrier) Features : It uses 2.4GHz global open ISM band, with license-free. Transmit power is greater than +20 dBm. Support six-channel data reception. 2Mbit/s speed makes high-quality VoIP possible Multi-frequency points: 125 frequency points meet the needs of multi-point communications and frequency hopping. Low cost: integrated with high-speed signal processing parts associated with RF protocol, such as: automatically re-send lost packets and generate acknowledge signal; SPI interface facilitates the communication with MCU I/O port. Facilitate the development for customers, without development RF part. Software programming is fully compatible with NRF24L01 modules. The PA stands for Power Amplifier. It merely boosts the power of the signal being transmitted from the nRF24L01+ chip. Whereas, LNA stands for Low-Noise Amplifier. The function of the LNA is to take the extremely weak and uncertain signal from the antenna (usually on the order of microvolts or under -100 dBm) and amplify it to a more useful level (usually about 0.5 to 1V) The low-noise amplifier (LNA) of the receive path and the power amplifier (PA) of the transmit path connect to the antenna via a duplexer, which separates the two signals and prevents the relatively powerful PA output from overloading the sensitive LNA input. RF Channel Frequency The nRF24L01+ transceiver module transmits and receives data on a certain frequency called Channel. Also in order for two or more transceiver modules to communicate with each other, they need to be on the same channel. This channel could be any frequency in the 2.4 GHz ISM band or to be more precise, it could be between 2.400 to 2.525 GHz (2400 to 2525 MHz). Each channel occupies a bandwidth of less than 1MHz. This gives us 125 possible channels with 1MHz spacing. So, the module can use 125 different channels which give a possibility to have a network of 125 independently working modems in one place. ie The channel occupies a bandwidth of less than 1MHz at 250kbps and 1Mbps air data rate. However at 2Mbps air data rate, 2MHz bandwidth is occupied (wider than the resolution of RF channel frequency setting). So, to ensure non-overlapping channels and reduce cross-talk in 2Mbps mode, you need to keep 2MHz spacing between two channels. nRF24L01+ Multiceiver Network The nRF24L01+ provides a feature called Multiceiver. It’s an abbreviation for Multiple Transmitters Single Receiver. In which each RF channel is logically divided into 6 parallel data channels called Data Pipes. In other words, a data pipe is a logical channel in the physical RF Channel. Each data pipe has its own physical address (Data Pipe Address) and can be configured. The primary receiver acting as a hub receiver collecting information from 6 different transmitter nodes simultaneously. The hub receiver can stop listening any time and acts as a transmitter. But this can only be done one pipe/node at a time. Arduino Nano We have a complete understanding of how nRF24L01+ transceiver module works, we can begin hooking it up to our Arduino Nano Connect VCC pin on the module to 3.3V on the Arduino and GND pin to ground. The pins CSN and CE can be connected to any digital pin on the Arduino. In our case, it’s connected to digital pin#7 and #8 respectively. Now we are remaining with the pins that are used for SPI communication. As nRF24L01+ transceiver module require a lot of data transfer, they will give the best performance when connected up to the hardware SPI pins on a microcontroller. The hardware SPI pins are much faster than ‘bit-banging’ the interface code using another set of pins. Note that each Arduino Board has different SPI pins which should be connected accordingly. For Arduino boards such as the UNO/Nano V3.0 those pins are digital 13 (SCK), 12 (MISO) and 11 (MOSI). Installing Library To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. DHT11: you need to Download and install the DHT11 library. Adafruit Unified Sensor Download and install the sensor library. Adafruit BusIO Download and install the signal library. NRF24L01: you need to Download and install the RF library. After installing the required libraries, copy the following code to your Arduino IDE. Arduino Code Transmitter Code #include #include #include #include "DHT.h" const byte address[6] = "00001"; #define DHTPIN 2 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); RF24 radio(7, 8); // CN and CSN pins of nrf struct MyData { byte h; byte t; }; MyData data; void setup() { Serial.begin(9600); dht.begin(); radio.begin(); radio.setAutoAck(false); radio.setDataRate(RF24_250KBPS); radio.openWritingPipe(address); radio.setPALevel(RF24_PA_MIN); radio.stopListening(); } void loop() { data.h = dht.readHumidity(); data.t = dht.readTemperature(); if (isnan(data.h) || isnan(data.t)){ Serial.println(F("Failed to read from DHT sensor!")); return; } Serial.print("Humidity: "); Serial.print(data.h); Serial.print("Temperature: "); Serial.print(data.t); radio.write(&data, sizeof(MyData)); delay(1000); } Subscribe and Download code. Transmitter Receiver Code #include #include #include #include #include LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display const byte address[6] = "00001"; RF24 radio(7, 8); // CN and CSN pins of nrf struct MyData { byte h; byte t; }; MyData data; void setup() { Serial.begin(9600); radio.begin(); lcd.init(); // initialize the lcd // Print a message to the LCD. lcd.backlight(); radio.setAutoAck(false); radio.setDataRate(RF24_250KBPS); radio.openReadingPipe(0, address); radio.setPALevel(RF24_PA_MIN); radio.startListening(); //lcd.println("Receiver "); } void ReceiveData() { if ( radio.available() ) { radio.read(&data, sizeof(MyData)); } } void loop() { ReceiveData(); // Serial.print("Humidity: "); lcd.setCursor(0,0); lcd.print("HUMIDITY:"); lcd.print(data.h); lcd.print("%"); lcd.setCursor(0,1); //Serial.print("Temperature: "); // Serial.print(\n); lcd.print("TEMPERATURE:"); lcd.print(data.t); lcd.print((char)223); lcd.print("C"); Serial.print(data.h); Serial.print(":"); Serial.print(data.t); Serial.print("\n"); delay(5000); } Subscribe and Download code. Receiver Amcharts Here to used amChart Gauge for Temperature and Humididty data visualization. Refer below demo HTML code for Gauges. https://www.amcharts.com/demos/#gauges Android application First open Mobile application and select Bluetooth image button, after that select Bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). Subscribe and Android App
- Water Level Controller with Real time Data Logger and Bluetooth
Learn here to create Arduino Based Water Level controller with RTC data logger. We’ll use the HC SR04 ultrasonic to measure tank level, the real time clock (RTC) module to take time stamps and the SD card module to save the water storage in liter, water filled in percentage and Pump motor ON/OFF status on the SD card, and Bluetooth send water level data to android application for HTML Java script Tank Gauge display. Components required Arduino Nano - 1 no Micro SD card Module - 1no Memory Card 16GB (16GB used in this Project)- 1no HC SR04 - 1 no DS1307 RTC I²Cmodule - 1 no Bluetooth HC-05 - 1 no Jumper wires Circuit diagram HC-SR04 HC-SR04 Ultrasonic sensor is a 4 pin module, whose pin names are Vcc, Trigger, Echo and Ground respectively. This sensor is a very popular sensor used in many applications where measuring distance or sensing objects are required. The module has two eyes like projects in the front which forms the Ultrasonic transmitter and Receiver. The sensor works with the simple high school formula that Distance = Speed × Time This economical sensor provides 2cm to 400cm of non-contact measurement functionality with a ranging accuracy that can reach up to 3mm. VCC (Power) to Arduino Nano 5V Trig (Trigger) to Arduino Nano D2 Pin Echo (Receive) to Arduino Nano D3 Pin GND (Ground) to Arduino Nano GND Pin. Refer more Data sheet Download Refer to project Real time Temperature data logger for more detail. https://www.dofbot.com/post/real-time-temperature-data-logger-with-bluetooth The Arduino Nano board The Arduino Nano board provides more or less the same functionality of the Arduino Duemilanove but in a more compact design. Comparing to the Arduino Duemilanove board, the Arduino Nano board lack a DC power jack and has a mini-USB connector instead of a standard USB. Technical specifications of the Arduino Nano board The technical specifications of the Arduino Nano board are as follows: Microcontroller ATmega328 Operating Voltage (logic level): 5 V Input Voltage (recommended): 7-12 V Input Voltage (limits): 6-20 V Digital I/O Pins : 14 (of which 6 provide PWM output) Analog Input Pins: 8 DC Current per I/O Pin: 40 mA Flash Memory 32 KB (ATmega328) of which 2 KB used by bootloader SRAM: 2 KB (ATmega328) EEPROM: 1 KB (ATmega328) Clock Speed: 16 MHz Dimensions: 0.73" x 1.70" Powering the Arduino Nano The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source. Programming the Arduino Nano board The Arduino Nano can be programmed using the free Arduino software (download). Select "Arduino Diecimila, Duemilanove, or Nano w/ ATmega168" or "Arduino Duemilanove or Nano w/ ATmega328" from the Tools > Board menu. The ATmega328 microcontroller on the Arduino Nano board comes preburned with a bootloader that allows you to upload new code to it without the use of an external hardware programmer. You can also bypass the bootloader and program the microcontroller through the ICSP (In-Circuit Serial Programming) header. Cylinder Volume Calculator Vertical cylinder shaped tank is the area, A, of the circular end times the height, h. Volume=A.h A = πr² where r is the radius which is equal to d/2. d is diameter of Cylinder. Therefore, Volume = πr²h Rectangle shaped tank is length times width times height. Therefore, Volume = lwh A sphere of diameter d split in half and separated by a cylinder of diameter d Where r = d/2. Therefore, Volume = (4/3)πr³ Installing arduino Library Download Ultrasonic library , we need to use this library. DS1307: you need to Download and install the RTC library. Follow the next steps to install those libraries. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After installing the required libraries, copy the following code to your Arduino IDE. Arduino Code: // include the SD library: #include // Include SPI library (needed for the SD card) #include // Include SD library #include // for the RTC #include Ultrasonic ultrasonic(2, 3); int distance; int Lowlevel = 20; // Pump ON - Percentage 20% you can change the value as per your need int Highlevel = 70; // Pump OFF - Percentage 70% you can change the value as per your need File dataFile; int TankHeight = 17; // Manually enter Tank height in cm // Cylinder Tank volume V = πr2h, where h= 30cm, r = 15cm // Rectancle Tank volume V = lwh, where h= 17cm, w = 14cm, l= 17cm; Volume = 4 .03 liters int TotalVolume = 4; // mini tank Volume = 4 .03 liters int Volume; float Percentage,math; // Real Time Clock RTC_DS1307 rtc; #define MOTORPIN 8 // Pump relay String Data; void setup() { Serial.begin(9600); pinMode(MOTORPIN,OUTPUT);// Relay pin as output pin // setup for the RTC while(!Serial); // for Leonardo/Micro/Zero if(! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } else { // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } if(! rtc.isrunning()) { Serial.println("RTC is NOT running!"); } while (!Serial); // wait for serial port to connect. Needed for native USB port only Serial.print("Initializing SD card..."); if (!SD.begin()) { Serial.println("initialization failed!"); while (1); } Serial.println("initialization done."); delay(2000); } void loop() { // Wait a few seconds between measurements. delay(2000); distance = ultrasonic.read(); math = TankHeight-distance; Percentage = (math/TankHeight)*100; // Volume = (TotalVolume/100)*Percentage; if ((Percentage >= 0) && (Percentage <= 100)) if(Percentage <= Lowlevel) // Relay ON when reached Low Level point {digitalWrite(MOTORPIN,HIGH);} if(Percentage >= Highlevel) // Relay OFF when reached High Level point {digitalWrite(MOTORPIN,LOW);} dataFile = SD.open("LevelLog.txt", FILE_WRITE); DateTime now = rtc.now(); if (dataFile) { // Serial.print("Tank Level: "); Data = (String)TotalVolume + ":" + (String)Percentage+ ":"+ (String)(digitalRead(MOTORPIN)); Serial.println(Data); delay(1000); dataFile.print(now.year(), DEC); dataFile.print('/'); dataFile.print(now.month(), DEC); dataFile.print('/'); dataFile.print(now.day(), DEC); dataFile.print(','); dataFile.print(now.hour(), DEC); dataFile.print(':'); dataFile.print(now.minute(), DEC); dataFile.print(':'); dataFile.print(now.second(), DEC); dataFile.print(","); dataFile.print(F("Tank Level: ")); dataFile.print(Percentage); dataFile.print(F("Pump Status ")); dataFile.print(digitalRead(MOTORPIN)); dataFile.close(); } // if the file didn't open, print an error: else Serial.println("error opening LevelLog.txt"); } Subscribe and Download code. Serial Monitor After a successful upload, open the Serial Monitor at a baud rate of 9600. Press the “EN/RST” button on the Arduino Uno board and see the Temerature, Humidity and Heat index vaule in Serial monitor at every 15 second. SD Card First Power off the arduino nano and remove SD card from module and connect to the PC using SD card reader. The SD card contains LEVELLOG.txt file, the txt file have water level percentage and Pump status with Time stamp. HTML JS Code Here to used amChart Gauge for Tank Level and Storage data visualization. For code https://www.amcharts.com/ HTML code for Sphere Android Application First open Mobile application and select Bluetooth image button, after that select Bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). Subscribe and Download code. Android App
- Real Time Temperature Data Logger with Bluetooth
Learn here to create Arduino Based temperature data logger. We’ll use the DHT11 to measure temperature and Humidity, the real time clock (RTC) module to take time stamps and the SD card module to save the temperature, Humidity and Heat index data on the SD card, and Bluetooth send temperature data to HTML Java script Gauge display using android application. Components required Arduino Nano - 1 no Micro SD card Module - 1no Memory Card 16GB (16GB used in this Project)- 1no DHT 11 - 1 no DS1307 RTC I²Cmodule - 1 no Bluetooth HC-05 - 1 no Jumper wires Circuit diagram Micro SD Card Adapter Module SD cards or Micro SD cards are widely used in various applications, such as data logging, data visualization, and many more. Micro SD Card Adapter modules make it easier for us to access these SD cards with ease. The Micro SD Card Adapter module is an easy-to-use module with an SPI interface and an on-board 3.3V voltage regulator to provide proper supply to the SD card. The diagram shows the detail connections of SD module with Arduino. MOSI (Master Out Slave In) - pin 11 MISO (Master In Slave Out) - pin 12 SCK (Clock)- pin 13 CS (Chip Select) - pin 10 GND-GND VCC-5v or 3.3v. A Micro SD Card adapter module can be easily connected to an arduino. Since the module communicates via the SPI protocol, we need to connect the MISO, MOSI, SCK, and CS of the module to the MCU’s. Along with the SD card holder, the module has a 3.3V voltage regulator, along with a 74LVC125A Level shifter IC. Data Sheet Bluetooth HC-05 Module HC-05 is a Bluetooth module which is designed for wireless communication. This module can be used in a master or slave configuration. Bluetooth serial modules allow all serial enabled devices to communicate with each other using Bluetooth. HC-05 has red LED which indicates connection status, whether the Bluetooth is connected or not. Before connecting to HC-05 module this red LED blinks continuously in a periodic manner. When it gets connected to any other Bluetooth device, its blinking slows down to two seconds. This module works on 3.3 V. We can connect 5V supply voltage as well since the module has on board 5 to 3.3 V regulator. As HC-05 Bluetooth module has 3.3 V level for RX/TX and microcontroller can detect 3.3 V level, so, no need to shift transmit level of HC-05 module. But we need to shift the transmit voltage level from microcontroller to RX of HC-05 module. HC-05 Default Settings Default Bluetooth Name: “HC-05” Default Password: 1234 or 0000 Default Communication: Slave Default Mode: Data Mode Data Mode Baud Rate: 9600 DHT 11 DHT11 digital temperature and humidity sensor is a calibrated digital signal output of the temperature and humidity combined sensor. It uses a dedicated digital modules capture technology and the temperature and humidity sensor technology to ensure that products with high reliability and excellent long-term stability. Sensor includes a resistive element and a sense of wet NTC temperature measurement devices, and with a high-performance 8-bit micro controller connected. Data Sheet DHT11 Specifications: Operating Voltage: 3.5V to 5.5V Operating current: 0.3mA (measuring) 60uA (standby) Output: Serial data Temperature Range: 0°C to 50°C Humidity Range: 20% to 90% Resolution: Temperature and Humidity both are 16-bit Accuracy: ±1°C and ±1% DHT11 Equivalent Temperature Sensors: DHT22, AM2302, SHT71 DS1307 RTC Module DS1307 Module is a real-time clock module with 32kHz and has an onboard battery backup. This module provides seconds, minutes, hours, date, week and year with leap-year compensation up to 2100. It is a small size module that’s why it is easy to plug in even on a breadboard. It has the functionality to set in 24 hours and 12 hours. It is a real time clock module so after removing the power also it sore the real-time and whenever power is given, it starts with real time. Module is compatible with microprocessors and Arduino. Data Sheet Pin Connection to Arduino. SCL – analog pin5 SDA – analog pin4 Vcc - +5V Gnd - Gnd Code To Update the RTC time adjusment using the following the code in Void setup. Unslash the "set DS3231time (x,x,x,x,x,x,x) // set the initial time here: // DS3231 seconds, minutes, hours, day, date, month, year // setDS3231time(30,42,21,4,15,12,21); Example: setDS3231time(30,42,21,4,15,12,21); 30 - Seconds 42- Minute 21- Hours 4-Wednesday 15-date 12-Month 21-Year. Arduino Nano The Arduino Nano is another popular Arduino development board very much similar to the Arduino UNO. They use the same Processor (Atmega328p) and hence they both can share the same program. Data Sheet Powering you Arduino Nano: There are total three ways by which you can power your Nano. USB Jack: Connect the mini USB jack to a phone charger or computer through a cable and it will draw power required for the board to function Vin Pin: The Vin pin can be supplied with an unregulated 6-12V to power the board. The on-board voltage regulator regulates it to +5V. +5V Pin: If you have a regulated +5V supply then you can directly provide this o the +5V pin of the Arduino. Input/output: There are total 14 digital Pins and 8 Analog pins on your Nano board. The digital pins can be used to interface sensors by using them as input pins or drive loads by using them as output pins. A simple function like pinMode() and digitalWrite() can be used to control their operation. The operating voltage is 0V and 5V for digital pins. The analog pins can measure analog voltage from 0V to 5V using any of the 8 Analog pins using a simple function like analogRead(). These pins apart from serving their purpose, can also be used for special purposes, which are discussed below: Serial Pins 0 (Rx) and 1 (Tx): Rx and Tx pins are used to receive and transmit TTL serial data. They are connected with the corresponding ATmega328P USB to TTL serial chip. External Interrupt Pins 2 and 3: These pins can be configured to trigger an interrupt on a low value, a rising or falling edge, or a change in value. PWM Pins 3, 5, 6, 9 and 11: These pins provide an 8-bit PWM output by using analogWrite() function. SPI Pins 10 (SS), 11 (MOSI), 12 (MISO) and 13 (SCK): These pins are used for SPI communication. In-built LED Pin 13: This pin is connected with a built-in LED. When pin 13 is HIGH – LED is on and when pin 13 is LOW, it is off. I2C A4 (SDA) and A5 (SCA): Used for IIC communication using Wire library. AREF: Used to provide reference voltage for analog inputs with analogReference() function. Reset Pin: Making this pin LOW, resets the micro controller. Installing adafruit Library To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. DHT11: you need to Download and install the DHT11 library. DS1307: you need to Download and install the RTC library. Adafruit Unified Sensor Download and install the sensor library. Adafruit BusIO Download and install the signal library. After installing the required libraries, copy the following code to your Arduino IDE. Arduino Code Subscribe and Download code. /* SD card test This example shows how use the utility libraries on which the' SD library is based in order to get info about your SD card. Very useful for testing a card when you're not sure whether its working or not. The circuit: SD card attached to SPI bus as follows: ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila ** CS - depends on your SD card shield or module. Pin 10 used here for consistency with other Arduino examples */ // include the SD library: #include // Include SPI library (needed for the SD card) #include // Include SD library #include // for the RTC File dataFile; // REQUIRES the following Arduino libraries: // - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library // - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor #include "DHT.h" #define DHTPIN 2 // Digital pin connected to the DHT sensor // Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 -- // Pin 15 can work but DHT must be disconnected during program upload. // Uncomment whatever type you're using! #define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 // to 3.3V instead of 5V! // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 3 (on the right) of the sensor to GROUND (if your sensor has 3 pins) // Connect pin 4 (on the right) of the sensor to GROUND and leave the pin 3 EMPTY (if your sensor has 4 pins) // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor // Initialize DHT sensor. // Note that older versions of this library took an optional third parameter to // tweak the timings for faster processors. This parameter is no longer needed // as the current DHT reading algorithm adjusts itself to work on faster procs. DHT dht(DHTPIN, DHTTYPE); // Real Time Clock RTC_DS1307 rtc; void setup() { Serial.begin(9600); // set the initial time here: // DS3231 seconds, minutes, hours, day, date, month, year // setDS3231time(30,42,21,4,15,12,21); Serial.println(F("DHTxx test!")); dht.begin(); // setup for the RTC while(!Serial); // for Leonardo/Micro/Zero if(! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } else { // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } if(! rtc.isrunning()) { Serial.println("RTC is NOT running!"); } while (!Serial); // wait for serial port to connect. Needed for native USB port only Serial.print("Initializing SD card..."); if (!SD.begin()) { Serial.println("initialization failed!"); while (1); } Serial.println("initialization done."); delay(2000); } void loop() { // Wait a few seconds between measurements. delay(2000); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) float f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println(F("Failed to read from DHT sensor!")); return; } // Compute heat index in Fahrenheit (the default) float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); dataFile = SD.open("DHT11Log.txt", FILE_WRITE); DateTime now = rtc.now(); if (dataFile) { // Serial.print(F("Humidity: ")); Serial.print(h); Serial.print("|"); // Serial.print(F("% Temperature: ")); Serial.print(t); Serial.print("|"); // Serial.print(F("°C ")); // Serial.print(f); // Serial.print(F("°F Heat index: ")); Serial.print(hic); Serial.print("|"); // Serial.print(F("°C ")); Serial.print(hif); Serial.print("\n"); delay(15000); // Serial.println(F("°F")); // Write data to SD card file (DHT11Log.txt) dataFile.print(now.year(), DEC); dataFile.print('/'); dataFile.print(now.month(), DEC); dataFile.print('/'); dataFile.print(now.day(), DEC); dataFile.print(','); dataFile.print(now.hour(), DEC); dataFile.print(':'); dataFile.print(now.minute(), DEC); dataFile.print(':'); dataFile.print(now.second(), DEC); dataFile.print(","); dataFile.print(F("Humidity: ")); dataFile.print(h); dataFile.print(F("% Temperature: ")); dataFile.print(t); dataFile.print(F("°C ")); dataFile.print(f); dataFile.print(F("°F Heat index: ")); dataFile.print(hic); dataFile.print(F("°C ")); dataFile.print(hif); dataFile.println(F("°F")); dataFile.close(); } // if the file didn't open, print an error: else Serial.println("error opening DHT11Log.txt"); } Subscribe and Download code. Serial Monitor After a successful upload, open the Serial Monitor at a baud rate of 9600. Press the “EN/RST” button on the Arduino Uno board and see the Temerature, Humidity and Heat index vaule in Serial monitor at every 15 second. SD Card First Power off the arduino nano and remove SD card from module and connect to the PC using SD card reader. The SD card contains DHT11log.txt file, the txt file have Temperature data with Time stamp. Android application First open Mobile application and select Bluetooth image button, after that select Bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). Subscribe and Download code. Android App offline App Download (Gauge work without internet) MIT BLOCK MIT app inventor Block image for android application development. Amcharts Here to used amChart Gauge for Temperature and Humididty data visualization. Refer below demo HTML code for Gauges. https://www.amcharts.com/demos/#gauges Html code for angular gauge
- Water Level Controller for Multiple Tanks
Learn here to create Arduino Based Water Level controller with bluetooth. We’ll use the HC SR04 ultrasonic to measure tank level, Bluetooth send water level percentage and Pump motor ON/OFF status data to android application for HTML Java script Tank Gauge display. Components required Arduino Nano - 1 no HC SR04 - 3 no Bluetooth HC-05 - 1 no Jumper wires Circuit diagram Refer to project Water level controller with Real time data logger for more detail. https://www.dofbot.com/post/water-level-controller-with-real-time-data-logger-and-bluetooth Installing arduino Library Download Ultrasonic library , we need to use this library. Follow the next steps to install those libraries. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After installing the required libraries, copy the following code to your Arduino IDE. Arduino Code: #include Ultrasonic ultrasonic1(2, 3); Ultrasonic ultrasonic2(4, 5); Ultrasonic ultrasonic3(8, 9); // Tank T1 int T1distance; int T1Lowlevel = 20; // Tank1 Pump ON - T1Percentage 20% you can change the value as per your need int T1Highlevel = 70; // Tank 1Pump OFF - T1Percentage 70% you can change the value as per your need int T1TankHeight = 22; // Tank1 Manually enter Tank height in cm float T1Percentage,T1Math; #define T1MOTORPIN 6 // Tank 1 Pump relay ///// // Tank T2 int T2distance; int T2Lowlevel = 20; // Tank 2 Pump ON - T1Percentage 20% you can change the value as per your need int T2Highlevel = 70; // Tank 2 Pump OFF - T1Percentage 70% you can change the value as per your need int T2TankHeight = 18; // Tank 2 Manually enter Tank height in cm float T2Percentage,T2Math; #define T2MOTORPIN 7 // Tank 2 Pump relay ///// // Tank T3 int T3distance; int T3Lowlevel = 20; // Tank 3 Pump ON - T1Percentage 20% you can change the value as per your need int T3Highlevel = 70; // Tank 3 Pump OFF - T1Percentage 70% you can change the value as per your need int T3TankHeight = 15; // Tank 3 Manually enter Tank height in cm float T3Percentage,T3Math; #define T3MOTORPIN 10 // Tank 3 Pump relay //// String Data; void setup() { Serial.begin(9600); Serial.setTimeout(100); pinMode(T1MOTORPIN,OUTPUT);// Relay pin as output pin pinMode(T2MOTORPIN,OUTPUT);// Relay pin as output pin pinMode(T3MOTORPIN,OUTPUT);// Relay pin as output pin // digitalWrite(MOTORPIN,LOW); // unslash Start Up Turn off the relay condition // digitalWrite(MOTORPIN,High); //unslash Start Up Turn ON the relay condition delay(1000); } void loop() { // Tank 1 loop T1distance = ultrasonic1.read(); T1Math = T1TankHeight-T1distance; T1Percentage = (T1Math/T1TankHeight)*100; if ((T1Percentage >= 0) && (T1Percentage <= 100)) if(T1Percentage <= T1Lowlevel) // Relay ON when reached Low Level point {digitalWrite(T1MOTORPIN,HIGH);} if(T1Percentage >= T1Highlevel) // Relay OFF when reached High Level point {digitalWrite(T1MOTORPIN,LOW);} // end // Tank 2 loop T2distance = ultrasonic2.read(); T2Math = T2TankHeight-T2distance; T2Percentage = (T2Math/T2TankHeight)*100; if ((T2Percentage >= 0) && (T2Percentage <= 100)) if(T2Percentage <= T2Lowlevel) // Relay ON when reached Low Level point {digitalWrite(T2MOTORPIN,HIGH);} if(T2Percentage >= T2Highlevel) // Relay OFF when reached High Level point {digitalWrite(T2MOTORPIN,LOW);} // end // Tank 3 loop T3distance = ultrasonic3.read(); T3Math = T3TankHeight-T3distance; T3Percentage = (T3Math/T3TankHeight)*100; if ((T3Percentage >= 0) && (T3Percentage <= 100)) if(T3Percentage <= T3Lowlevel) // Relay ON when reached Low Level point {digitalWrite(T3MOTORPIN,HIGH);} if(T3Percentage >= T3Highlevel) // Relay OFF when reached High Level point {digitalWrite(T3MOTORPIN,LOW);} // end Data = (String)T1Percentage+":"+(String)T2Percentage+":"+(String)T3Percentage+ ":"+(String)(digitalRead(T1MOTORPIN))+":"+(String)(digitalRead(T2MOTORPIN))+":"+(String)(digitalRead(T3MOTORPIN)); Serial.println(Data); delay(5000); } Subscribe and Download code. Serial Monitor After a successful upload, open the Serial Monitor at a baud rate of 9600. Press the “EN/RST” button on the Arduino Uno board and see the Tank percentage and Pump ON/OFF status for each tanks in Serial monitor. Android Application First open Mobile application and select Bluetooth image button, after that select Bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). Subscribe and Download code. Here to used amChart for Tank Level data visualization. https://www.amcharts.com/ HTML code for Multiple tanks, referf below.
- Interfacing SD card module with Arduino - Card Info, Read/Write and DATA LOGGER Functions
The micro SD Card Module is a simple solution for transferring data to and from a standard SD card. This module has SPI interface which is compatible with any SD card and it uses 5V or 3.3V power supply which is compatible with Arduino UNO/Mega. Some times we have the need for a way to store data in our projects, and most of the time, the EEPROM which comes readily to mind has a limited storage capacity, and issues with the format and nature of data it can hold. All this and more makes it probably not the best for storing data like text, CSV, audio, video or image files. To get around this we could use an SD card to store the data, and remove the card when we need to view on some other platform etc. That is why today’s project is focusing on how to interface an SD card module with an Arduino. Secure Digital (SD) is a non-volatile memory card format developed by the SD Card Association (SDA) for use in portable devices like mobile phones, cameras etc. Secure Digital includes four card families as follows- 1. SDSC: Standard Capacity SD. It has storage capacity of 2GB uses FAT- 12 and FAT-16 file systems. 2. SDHC: High Capacity SD. It has storage capacity ranging from 2GB to 32GB uses FAT-32 file system. 3. SDXC: extended Capacity SD. It has storage capacity ranging from 32GB to 2TB uses exFAT file system. 4. SDIO: It combines INPUT/OUTPUT functions with data storage. File System SD card is a block-addressable storage device, in which the host device can read or write fixed-size blocks by specifying their block number. Most SD cards are formatted with one or more MBR (Master Boot Record) partitions in which the first partition contains the file system which enables it to work like hard disks. 1. For SDSC card Capacity smaller than 16 MB- FAT 12 Capacity between 16 MB and 32 MB- FAT 16 Capacity larger than 32 MB- FAT 16B 2. For SDHC cards Capacity smaller than 7.8 GB- FAT 32 Capacity greater than 7.8 GB- FAT 32 3. For SDXC cards exFAT Subscribe The Arduino Micro SD card Module is an SPI Communication based device. It is compatible with the TF SD cards used in mobile phones and can be used to provide some sort of external storage for micro controller and microprocessor based projects, to store different kind of data types from images to videos. SD cards generally are 3.3v logic level based devices, but with the aid of the Micro SD card module, the signals are converted to 5v via a logic level converter implemented on the SD card Module. Components required Arduino Nano - 1 no Micro SD card Module - 1no Memory Card 16GB (16GB used in this Project)- 1no Jumper wires Circuit diagram The diagram shows the detail connections of SD module with Arduino. MOSI (Master Out Slave In) - pin 11 MISO (Master In Slave Out) - pin 12 SCK (Clock)- pin 13 CS (Chip Select) - pin 4 GND-GND VCC-5v or 3.3v. The operating voltage of any standard micro SD Cards is 3.3 V. So we cannot directly connect it to circuits that use 5V logic. In fact, any voltages exceeding 3.6V will permanently damage the micro SD card. That’s why; the module has an onboard ultra-low dropout regulator that will convert voltages from 3.3V – 6V down to ~3.3V. There’s also a 74LVC125A chip on the module which converts the interface logic from 3.3V-5V to 3.3V. This is called logic level shifting. That means you can use this board to interact with both 3.3V and 5V microcontrollers like Arduino. Arduino Library Library will be using the inbuilt code provided by Arduino IDE. The code in the Arduino IDE uses the two library files – SPI.h SD.h These library files direct contain function definitions which are used for SD card read-write operations. For accessing code in Arduino IDE you can follow the following mention steps- Copy the code above and paste it into the Arduino IDE, Upload it to your board and you should see something like what is displayed below on your serial monitor. SD Card Information Download Code // include the SD library: #include #include // set up variables using the SD utility library functions: Sd2Card card; SdVolume volume; SdFile root; // change this to match your SD shield or module; // Arduino Ethernet shield: pin 4 // Adafruit SD shields and modules: pin 10 // Sparkfun SD shield: pin 8 // MKRZero SD: SDCARD_SS_PIN const int chipSelect = 4; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.print("\nInitializing SD card..."); // we'll use the initialization code from the utility libraries // since we're just testing if the card is working! if (!card.init(SPI_HALF_SPEED, chipSelect)) { Serial.println("initialization failed. Things to check:"); Serial.println("* is a card inserted?"); Serial.println("* is your wiring correct?"); Serial.println("* did you change the chipSelect pin to match your shield or module?"); while (1); } else { Serial.println("Wiring is correct and a card is present."); } // print the type of card Serial.println(); Serial.print("Card type: "); switch (card.type()) { case SD_CARD_TYPE_SD1: Serial.println("SD1"); break; case SD_CARD_TYPE_SD2: Serial.println("SD2"); break; case SD_CARD_TYPE_SDHC: Serial.println("SDHC"); break; default: Serial.println("Unknown"); } // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32 if (!volume.init(card)) { Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card"); while (1); } Serial.print("Clusters: "); Serial.println(volume.clusterCount()); Serial.print("Blocks x Cluster: "); Serial.println(volume.blocksPerCluster()); Serial.print("Total Blocks: "); Serial.println(volume.blocksPerCluster() * volume.clusterCount()); Serial.println(); // print the type and size of the first FAT-type volume uint32_t volumesize; Serial.print("Volume type is: FAT"); Serial.println(volume.fatType(), DEC); volumesize = volume.blocksPerCluster(); // clusters are collections of blocks volumesize *= volume.clusterCount(); // we'll have a lot of clusters volumesize /= 2; // SD card blocks are always 512 bytes (2 blocks are 1KB) Serial.print("Volume size (Kb): "); Serial.println(volumesize); Serial.print("Volume size (Mb): "); volumesize /= 1024; Serial.println(volumesize); Serial.print("Volume size (Gb): "); Serial.println((float)volumesize / 1024.0); Serial.println("\nFiles found on the card (name, date and size in bytes): "); root.openRoot(volume); // list all files in the card with date and size root.ls(LS_R | LS_DATE | LS_SIZE); } void loop(void) { } Serial monitor After a successful upload, open the Serial Monitor at a baud rate of 9600. see the result on Serial monitor. SD Card Read/Write Subscribe Download Code Code Explanation: The sketch starts with including the built in SD library and the SPI library which allows us to easily communicate with the SD card over SPI interface. #include #include After the libraries have been included, the next thing we do is declare the Arduino pin to which the chipSelect (CS) pin of the SD card module is connected. The CS pin is the only one that is not really fixed as any of the Arduino digital pin. We don’t need to declare other SPI pins since we are using hardware SPI interface and these pins are already declared in the SPI library. After declaring the pin, we then create an object myFile, which will be used later on to store data on the SD card. const int chipSelect = 10; File myFile; Next, in the setup() section: We start the serial communication for showing the results on the serial monitor. Now, using the SD.begin() function we will initialize the SD card and if initialization is successful the “if” statement becomes true and the String “initialization done.” gets printed on the serial monitor, else the string “initialization failed!” gets printed and the program terminates. Serial.begin(9600); Serial.print("Initializing SD card..."); if (!SD.begin()) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); Next, the SD.open() function will open the file named “test.txt”. In our case, as such file is not present, it’ll be created. The other parameter FILE_WRITE opens the file in read-write mode. myFile = SD.open("test.txt", FILE_WRITE); Once the file is opened, we will print the “Writing to test.txt…” message on the serial monitor and then using the myFile.println() function we will write the text “testing 1, 2, 3.” into the file. After that we need to use close() function to ensure that the data written to the file is saved. if (myFile) { Serial.print("Writing to test.txt..."); myFile.println("testing 1, 2, 3."); myFile.close(); Serial.println("done."); } else { Serial.println("error opening test.txt"); } Now let’s read the same file to check if the write operation was successful.To do that, we will use the same function, SD.open() , but this time as the file “test.txt” has already been created, the function will just open the file. Then using the myFile.read() function we will read from the file and print it on the serial monitor. The read() function actually reads just one character at a time, so therefore we need to use the “while” loop and the function myFile.available() to read all characters in file. At the end we need to close the file. myFile = SD.open("test.txt"); if (myFile) { Serial.println("test.txt:"); while (myFile.available()) { Serial.write(myFile.read()); } myFile.close(); } else { Serial.println("error opening test.txt"); } Since this is just a demo sketch to demonstrate how to read and write files, there is no point to run the code multiple times so all the code was placed in the setup() function which runs just once, instead of putting it in a loop() function which runs over and over again. void loop() { } Serial monitor After a successful upload, open the Serial Monitor at a baud rate of 9600. see the result on Serial monitor. SD Card DATA LOGGER Subscribe Download Code #include #include const int chipSelect = 4; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.print("Initializing SD card..."); // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: while (1); } Serial.println("card initialized."); } void loop() { // make a string for assembling the data to log: String dataString = ""; // read three sensors and append to the string: for (int analogPin = 0; analogPin < 3; analogPin++) { int sensor = analogRead(analogPin); dataString += String(sensor); if (analogPin < 2) { dataString += ","; } } // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("datalog.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println(dataString); dataFile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.println("error opening datalog.txt"); } } Serial monitor After a successful upload, open the Serial Monitor at a baud rate of 9600. see the result on Serial monitor. Note You can use print() and println() functions just like Serial objects, to write strings, variables, etc Read() only returns a character at a time. It does not read a full line or a number! The SD card library does not support ‘long filenames’. Instead, it uses the 3 format for file names, so keep file names short! For example datalog.txt is fine. Also keep in mind that file names do not have ‘case’ sensitivity, so datalog.txt is the same file as DataLog.Txt is the same file as DATALOG.TXT Subscribe
- NodeMCU Based Color Finder using TCS3200 Sensor
In this tutorial we will make a color Finder using a color sensor TCS3200, LCD display and NodeMCU8266 12E dev board. TCS3200 consisting of 64 diode in the combination which are embedded in a single small chip. the working depends on the main fact which is, every 16 diodes are coated with a different color. RED, BLUE, Green, and transparent. when the light refracts from these color patterns every four different colors coated photodiodes will receive the different light frequency. which helps the sensor to differentiate between the color. Circuit Diagram Components Required NodeMCU ESP8266 TCS3200 color Sensor Jumper Wires LCD 16x2, I2C Module TCS3200 color Sensor Module This Arduino compatible TCS3200 color sensor module consist of a TAOS TCS3200 RGB sensor chip and 4 white LEDs. The main part of the module is the TCS3200 chip which is a Color Light-to-Frequency Converter. The white LEDs are used for providing proper lighting for the sensor to detect the object colour correctly. This chip can sense a wide variety of colours and it gives the output in the form of corresponding frequency. This module can be used for making colour sorting robots, test strip reading, colour matching tests etc. The TCS3200 chip consist of an 8 x 8 array of photodiodes. Each photodiode have either a red, green, or blue filter, or no filter. The filters of each color are distributed evenly throughout the array to eliminate location bias among the colors. Internal circuits includes an oscillator which produces a square-wave output whose frequency is proportional to the intensity of the chosen color. Features and Specifications Input voltage: (2.7V to 5.5V) Interface: Digital TTL High-resolution conversion of light intensity to frequency Programmable colour and full-scale output frequency No need of ADC(Can be directly connected to the digital pins of the microcontroller) Power down feature Working temperature: -40oC to 85oC Size: 28.4×28.4mm(1.12×1.12″) Pin Configuration PIN PIN NAME NUMBER DESCRIPTION GND 4 Power supply ground. All voltages are reference to the ground. VCC 5 Supply voltage OE 3 Enable for FO (Active low) OUT 6 Output frequency (fo) S0, S1 1, 2 Select lines for output frequency scaling S2, S3 7,8 Select lines for photodiode type. Logic level S0 S1 OUTPUT FREQUENCY SCALING(f0) L L Power down L H 2% H L 20% H H 100% Photodiode Logic S2 S3 PHOTODIODE TYPE L L RED L H BLUE H L CLEAR (NO FILTER) H H GREEN The sensor has four different types of filter covered diodes. In the 8 x 8 array of photodiodes, 16 photodiodes have Red filters, 16 have Blue filters, 16 have Green filters and the rest 16 photodiodes are clear with no filters. Each type can be activated using the S2, S3 selection inputs. Since each photodiodes are coated with different filters each of them can detect the corresponding colours. For example, when choosing the red filter, only red incident light can get through, blue and green will be prevented. By measuring the frequency, we get the red light intensity. Similarly, when choose other filters we can get blue or green light. We can also set the frequency scaling option by using the S0, S1 select lines. Normally, in Arduino 20% frequency scaling is used. How to use the module Pin Configuration TCS3200 color sensor module can be used to detect the colous with the help of a microcontroller. Actually, the microcontroller is measuring the output frequency from the 6th pin. To determine the color of an object, we’ve to measure the frequency from 6th pin when each filter is activated. Set both S2 and S3 to LOW, measure the frequency. Now we get the intensity of RED component in the object. Set S2 to LOW and S3 to HIGH in order to get the intensity of BLUE component in the object. Set both S2 and S3 to HIGH and get the intensity of GREEN component in the object. Compare the frequencies of the three components to get the actual colour of the object. TIP: In Arduino, we can use the ‘pulseIn’ command to get the frequency variations. e.g.: digitalWrite(S2, LOW); digitalWrite(S3, LOW); //Activating photodiode with red filter red = pulseIn(outpin, LOW); Here we get the value corresponding to the red color component of the object color. Similarly, we’ve to activate each photodiodes by changing the S2 and S3 states and read the corresponding values of green and blue colour components of the object colour. For a Red object we get an approximate value of red=16, green=53 and blue=45. This may vary from ambient light and experiment setup. For good results, it’s better to cover the object and sensor from ambient light. Programming Logic First set the input pins as input and output pins as output. No need to use analog pins. Set S0 and S1 to high or low to set desired frequency scaling. In loop, activate each filters by setting S2 and S3 to HIGH or LOW and measure frequency ‘fo’ from 6th pin to get corresponding colour intensity. Compare frequencies of each colour to determine the colour of the object. Component Datasheet PDF: TCS3200 Color Sensor Datasheeet Installing the arduino Library DownloadLiquid crystalLibrary. After downloading the .zip files, add the libraries in Arduino IDE by clicking on To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. Subscribe and download code. Arduino Code: #include // set the LCD number of columns and rows int lcdColumns = 16; int lcdRows = 2; LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // change your I2C ADDRESS HERE EXAMPLE 0x3F const int s0 = D3; const int s1 = D4; const int s2 = D5; const int s3 = D6; const int out = D7; int red = 0; int green = 0; int blue = 0; int redcolor= 0; int greencolor= 0; int bluecolor= 0; int yellowcolor= 0; int color= 0; void setup() { Serial.begin(9600); lcd.init(); lcd.backlight(); lcd.setCursor(0, 0); lcd.print("ESP Color Finder"); pinMode(s0, OUTPUT); pinMode(s1, OUTPUT); pinMode(s2, OUTPUT); pinMode(s3, OUTPUT); pinMode(out, INPUT); digitalWrite(s0, HIGH); digitalWrite(s1, HIGH); } void loop() { digitalWrite(s2, LOW); digitalWrite(s3, LOW); //count OUT, pRed, RED red = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); digitalWrite(s3, HIGH); //count OUT, pBLUE, BLUE blue = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); digitalWrite(s2, HIGH); //count OUT, pGreen, GREEN green = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); Serial.print("R Intensity:"); Serial.print(red, DEC); Serial.print(" G Intensity: "); Serial.print(green, DEC); Serial.print(" B Intensity : "); Serial.print(blue, DEC); if(red<18 & red>6 & green<32 & green>26 & blue<29 & blue>20){ delay(250); redcolor++; Serial.print("Red"); lcd.setCursor(0, 1); lcd.print(" Red "); delay(2000); lcd.clear(); } if(red<30 & red>26 & green<40 & green>36 & blue<30 &blue>26){ delay(250); bluecolor++; Serial.print("Blue"); lcd.setCursor(0, 1); lcd.print(" Blue "); delay(2000); lcd.clear(); } if(red<24 & red>20 & green<24 & green>20 & blue<22 & blue>18){ delay(250); greencolor++; Serial.print("Green"); lcd.setCursor(0, 1); lcd.print(" Green "); delay(2000); lcd.clear(); } if(red<16 & red>12 & green<24 & green>20 & blue<26 & blue>22){ delay(250); yellowcolor++; Serial.print("Yellow"); lcd.setCursor(0, 1); lcd.print(" Yellow "); delay(2000); lcd.clear(); } Serial.println(); // delay(1000); }
- Arduino Nano Based Weather Monitor with Bluetooth HC-05
In this tutorial shows how to connect BMP280 barometric pressure, temperature and altitude sensor interface to Arduino Nano board with Bluetooth HC-05 and android application for output monitor. Circuit Diagram Components Required Arduino Nano - 1 no Bluetooth module HC-05 - 1no BMP 280 - 1no BMP280 Pressure Sensor Module: The GY-BMP280 Barometer Sensor is a breakout board for Bosch BMP280 high-precision and low-power digital barometer. It can be used to measure temperature and atmospheric pressure accurately. It can be connected to a microcontroller with I2C. Applications of GY-BMP280 Module Enhancement of GPS navigation (e.g. time-to-first-fix improvement, dead-reckoning, slope detection) Indoor navigation (floor detection, elevator detection) Outdoor navigation, leisure and sports applications Weather forecast, Home weather stations Health care application (e.g. sirometry) Vertical velocity indication (e.g. risk/sink speed) Handsets such as mobile phones, tablet PCs, GPS devices Flying toys Watches Bluetooth HC-05 Module HC-05 is a Bluetooth module which is designed for wireless communication. This module can be used in a master or slave configuration. Bluetooth serial modules allow all serial enabled devices to communicate with each other using Bluetooth. It has 6 pins, 1.Key/EN: It is used to bring Bluetooth module in AT commands mode. If Key/EN pin is set to high, then this module will work in command mode. Otherwise by default it is in data mode. The default baud rate of HC-05 in command mode is 38400bps and 9600 in data mode. HC-05 module has two modes, Data mode: Exchange of data between devices. Command mode: It uses AT commands which are used to change setting of HC-05. To send these commands to module serial (USART) port is used. 2. VCC: Connect 5 V or 3.3 V to this Pin. 3. GND: Ground Pin of module. 4. TXD: Transmit Serial data (wirelessly received data by Bluetooth module transmitted out serially on TXD pin) 5. RXD: Receive data serially (received data will be transmitted wirelessly by Bluetooth module). 6. State: It tells whether module is connected or not. HC-05 module Information HC-05 has red LED which indicates connection status, whether the Bluetooth is connected or not. Before connecting to HC-05 module this red LED blinks continuously in a periodic manner. When it gets connected to any other Bluetooth device, its blinking slows down to two seconds. This module works on 3.3 V. We can connect 5V supply voltage as well since the module has on board 5 to 3.3 V regulator. As HC-05 Bluetooth module has 3.3 V level for RX/TX and microcontroller can detect 3.3 V level, so, no need to shift transmit level of HC-05 module. But we need to shift the transmit voltage level from microcontroller to RX of HC-05 module. HC-05 Default Settings Default Bluetooth Name: “HC-05” Default Password: 1234 or 0000 Default Communication: Slave Default Mode: Data Mode Data Mode Baud Rate: 9600, 8, N, 1 Command Mode Baud Rate: 38400, 8, N, 1 Default firmware: LINVOR Installing the Arduino Library Download Adafruit_BMP280_Library , we need to use this library. Follow the next steps to install those libraries. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After installing the required libraries, copy the following code to your Arduino IDE. Subscribe and Download code. Download Android application. Mobile Output First open Mobile application BMP280 and select Bluetooth image, after that select bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). Arduino Code #include #include #include Adafruit_BMP280 bmp; // I2C Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor(); Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor(); //Adafruit_BMP280 bmp(BMP_CS); // hardware SPI //Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK); void setup() { Serial.begin(9600); Serial.println(F("BMP280 test")); //if (!bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID)) { if (!bmp.begin()) { Serial.println(F("Could not find a valid BMP280 sensor, check wiring or " "try a different address!")); while (1) delay(10); } /* Default settings from datasheet. */ bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */ Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */ Adafruit_BMP280::FILTER_X16, /* Filtering. */ Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */ bmp_temp->printSensorDetails(); } void loop() { sensors_event_t temp_event, pressure_event; bmp_temp->getEvent(&temp_event); bmp_pressure->getEvent(&pressure_event); // Serial.print(F("Temperature = ")); Serial.print(bmp.readTemperature()); // Serial.println("°C"); Serial.print("|"); // Serial.print(F("Pressure = ")); Serial.print(pressure_event.pressure); // Serial.println(" hPa"); Serial.print("|"); // Serial.print(F("Approx altitude = ")); Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */ // Serial.println(" m"); Serial.print("\n"); delay(1000); }
- DS18B20 Digital Thermometer with Bluetooth Interface
Here to learn Arduino based bluetooth temperature sensor measures the temperature via the DS18B20 integrated digital temperature sensor and makes it available via bluetooth. This creating a kind of remote temperature monitor and temperature reading is transmitted via the Arduino’s serial port to the Arduino bluetooth module. Then the android application receive celsius & fahrenheit temperature reading and displays digital reading and therometer gauge display in mobile screen. Circuit Diagram: Components Required: Arduino Nano Board - 1 no DS18B20 with Probe - 1 no Resistor 4k7- 1 no HC-05 Bluetooth Module- 1no DS18B20 The DS18B20 is a 1-wire programmable Temperature sensor from maxim integrated. It is widely used to measure temperature in hard environments like in chemical solutions, mines or soil etc. The constriction of the sensor is rugged and also can be purchased with a waterproof option making the mounting process easy. It can measure a wide range of temperature from -55°C to +125° with a decent accuracy of ±5°C. Each sensor has a unique address and requires only one pin of the MCU to transfer data so it a very good choice for measuring temperature at multiple points without compromising much of your digital pins on the microcontroller. How to use the DS18B20 Sensor The sensor works with the method of 1-Wire communication. It requires only the data pin connected to the microcontroller with a pull up resistor and the other two pins are used for power as shown below. The pull-up resistor is used to keep the line in high state when the bus is not in use. The temperature value measured by the sensor will be stored in a 2-byte register inside the sensor. This data can be read by the using the 1- wire method by sending in a sequence of data. There are two types of commands that are to be sent to read the values, one is a ROM command and the other is function command. The address value of each ROM memory along with the sequence is given in the datasheet below. You have to read through it to understand how to communicate with the sensor. Applications Measuring temperature at hard environments Liquid temperature measurement Applications where temperature has to be measured at multiple points DS18B20 Sensor Specifications Programmable Digital Temperature Sensor Communicates using 1-Wire method Operating voltage: 3V to 5V Temperature Range: -55°C to +125°C Accuracy: ±0.5°C Output Resolution: 9-bit to 12-bit (programmable) Unique 64-bit address enables multiplexing Conversion time: 750ms at 12-bit Programmable alarm options Available as To-92, SOP and even as a waterproof sensor Bluetooth HC-05 Module HC-05 is a Bluetooth module which is designed for wireless communication. This module can be used in a master or slave configuration. Bluetooth serial modules allow all serial enabled devices to communicate with each other using Bluetooth. It has 6 pins, 1.Key/EN: It is used to bring Bluetooth module in AT commands mode. If Key/EN pin is set to high, then this module will work in command mode. Otherwise by default it is in data mode. The default baud rate of HC-05 in command mode is 38400bps and 9600 in data mode. HC-05 module has two modes, Data mode: Exchange of data between devices. Command mode: It uses AT commands which are used to change setting of HC-05. To send these commands to module serial (USART) port is used. 2. VCC: Connect 5 V or 3.3 V to this Pin. 3. GND: Ground Pin of module. 4. TXD: Transmit Serial data (wirelessly received data by Bluetooth module transmitted out serially on TXD pin) 5. RXD: Receive data serially (received data will be transmitted wirelessly by Bluetooth module). 6. State: It tells whether module is connected or not. HC-05 module Information HC-05 has red LED which indicates connection status, whether the Bluetooth is connected or not. Before connecting to HC-05 module this red LED blinks continuously in a periodic manner. When it gets connected to any other Bluetooth device, its blinking slows down to two seconds. This module works on 3.3 V. We can connect 5V supply voltage as well since the module has on board 5 to 3.3 V regulator. As HC-05 Bluetooth module has 3.3 V level for RX/TX and microcontroller can detect 3.3 V level, so, no need to shift transmit level of HC-05 module. But we need to shift the transmit voltage level from microcontroller to RX of HC-05 module. HC-05 Default Settings Default Bluetooth Name: “HC-05” Default Password: 1234 or 0000 Default Communication: Slave Default Mode: Data Mode Data Mode Baud Rate: 9600, 8, N, 1 Command Mode Baud Rate: 38400, 8, N, 1 Default firmware: LINVOR Installing the Arduino Library Installing Libraries for DS18B20 To interface with the DS18B20 temperature sensor, you need to install the One Wire library . Follow the next steps to install those libraries. 1. Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The Library Manager should open. 2. Type “onewire” in the search box and install the OneWire library by Paul Stoffregen. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After installing the required libraries, copy the following code to your Arduino IDE. Subscribe and Download code. After a successful upload, open the Serial Monitor at a baud rate of 9600. Press the “EN/RST” button on the Arduino Uno board and see the result in monitor. Mobile Output First open Mobile application Thermometer_BT and select Bluetooth Connect button, after that select bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). Demo Video: Subscribe and Download code. Android Download Arduino code #include // OneWire DS18S20, DS18B20, DS1822 Temperature Example // http://www.pjrc.com/teensy/td_libs_OneWire.html OneWire ds(5); // on pin 10 (a 4.7K resistor is necessary) String temperature; void setup(void) { Serial.begin(9600); } void loop(void) { byte i; byte present = 0; byte type_s; byte data[12]; byte addr[8]; float celsius, fahrenheit; if ( !ds.search(addr)) { ds.reset_search(); delay(250); return; } for( i = 0; i < 8; i++) { //// Serial.write(' '); } if (OneWire::crc8(addr, 7) != addr[7]) { return; } // the first ROM byte indicates which chip switch (addr[0]) { case 0x10: type_s = 1; break; case 0x28: type_s = 0; break; case 0x22: type_s = 0; break; default: return; } ds.reset(); ds.select(addr); ds.write(0x44, 1); // start conversion, with parasite power on at the end delay(1000); // maybe 750ms is enough, maybe not // we might do a ds.depower() here, but the reset will take care of it. present = ds.reset(); ds.select(addr); ds.write(0xBE); // Read Scratchpad for ( i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); } // Convert the data to actual temperature // because the result is a 16 bit signed integer, it should // be stored to an "int16_t" type, which is always 16 bits // even when compiled on a 32 bit processor. int16_t raw = (data[1] << 8) | data[0]; if (type_s) { raw = raw << 3; // 9 bit resolution default if (data[7] == 0x10) { // "count remain" gives full 12 bit resolution raw = (raw & 0xFFF0) + 12 - data[6]; } } else { byte cfg = (data[4] & 0x60); // at lower res, the low bits are undefined, so let's zero them if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms //// default is 12 bit resolution, 750 ms conversion time } celsius = (float)raw / 16.0; fahrenheit = celsius * 1.8 + 32.0; temperature = (String) celsius + "," + (String) fahrenheit ; Serial.println(temperature); }
- Earth Quake Monitoring and Email Notification using Vibration Sensor
To make a simple Earth Quake monitoring device and learn how to connect and control the digital vibration sensor module to IOT Cloud (myDevices Cayenne). Earthquake “is also known as tremor, temblor or quake“ is actually the shaking of the earth’s surface, which results due to the sudden release of the energy in the Earth’ lithosphere which creates seismic waves. In very simple words, the word earthquake can be described as the seismic event – whether natural or caused by the humans that generate seismic waves. As the seismic waves or the vibration waves can also be generated by the humans, so the false readings can be generated by the monitoring sensors. To overcome this problem every city can have 2 or 3 more sensors to further ensure the earthquake. The main objective of project is to work on the real-time earthquake detector sensor network, and design such a low-cost real-time earthquake detector monitoring system that can be easily used throughout the country or world. So that’s why I decided to work on this project and make our own monitoring system for the earthquake based on the wifi module, vibration sensor, and IoT platform. On the other hand, Cayenne is an IoT cloud platform that provides several cloud services, such as: Data visualization IoT cloud Alerts Scheduling Events We will focus our attention on data visualization and on the IoT cloud services. Circuit diagram Components Required Vibration sensor SW-420 - 1 no Node MCU ESP8266 12E - 1 no NodeMCU NodeMCU ESP8266-12E MCU is a development board with one analogue and many general-purpose input output (GPIO) pins. It has 4MB flash memory, and can operate at a default clock frequency of 80MHz. In this project, digital pin D0 of NodeMCU is used to read Data of Vibration Sensor. Cayenne Cayenne IoT Platform accelerates the development of IoT-based solutions, including quick design, prototyping and other commercialized projects. It is a drag-and-drop IoT project builder that can help developers build complete, ready-to-use IoT solutions with little to no coding. Cayenne IoT Platform contains a vast catalogue of certified IoT-ready devices and connectivity options. This allows users to easily add any device to the library utilizing MQTT API. All devices in Cayenne are interoperable and benefit from features such as rules engine, asset tracking, remote monitoring and control, and tools to visualize real-time and historical data. MQTT is a lightweight messaging protocol for sensors and mobile devices. Vibration Sensor SW420 Vibration Sensor Module comes with SW-420 vibration sensor, integrated with adjustable sensitivity via on board potentiometer. There are also LED indicators for power and the digital output status on board. It has a simple and straight forward 3-pin interface, VCC, GND and the DO (digital output). It supports 3.3V or 5V power. This vibration sensor module is compatible with any microcontroller that has a digital input, so of course any popular microcontroller such and PIC, Arduino and Raspberry Pi are compatible. A direct interface is essential to using this sensor. The DO pin will be LOW when there is no vibration, and indicator LED will lit up. Module Features: SW-420 using the company’s production of normally closed type vibration sensor. The comparator output, the signal is clean, the waveform, the driving ability to exceed 15mA Operating voltage 3.3V-5V The output in the form: Digital switching outputs (0 and 1) A fixed bolt hole for easy installation Small board PCB size: 3.2cm x 1.4cm Wide voltage LM393 comparator Uses: This Vibration Sensor can be used to detect vibration from any angle. There is an on-board potentiometer to adjust the threshold of vibration. It outputs logic HIGH when this module not triggered while logic Low when triggered. Application •Automobie alarm. •Movement detection. •Vibration detecting Applications Features NodeMCU programming with Arduino IDE You need Arduino IDE software to program NodeMCU. Steps for adding NodeMCU ESP8266 board and library to Arduino IDE are given below. Open Arduino IDE. Go to File menu and select Preferences. Copy this package and paste in Additional Boards Manager URL. Go to Tools and select Boards Manager. Type esp8266 in search box and press Enter. Install the latest version. From Tools menu, select NodeMCU 1.0 (ESP-12E module) board. Select Include Library from Sketch menu. Download the library from this link. Click on Add ZIP Library and add Cayenne-MQTT-ESP-master zip file, or directly copy the folder (Cayenne-MQTT-ESP-master) and paste it in Libraries folder of Arduino IDE. Subscribe and Download code. Arduino Code #define CAYENNE_PRINT Serial // Comment this out to disable prints and save space #include // sensors int vs = D0; // vibration sensor //Make a wifi name and password as access point char ssid[] = "TP-Link_3200"; // your SSID char wifiPassword[] = "95001121379884265554"; // YOUR WIFI PASSWORD // Cayenne authentication info. This should be obtained from the Cayenne Dashboard. char username[] = "2031dd30-5414-11eb-b767-3f1a8f1211ba"; char password[] = "f2ce829d98df3a768328ac6936eae9fd47d28289"; char clientID[] = "9ab212f0-b9db-11eb-8779-7d56e82df461"; void setup(){ Serial.begin(115200); Serial.print("Setup"); Cayenne.begin(username, password, clientID, ssid, wifiPassword); pinMode(vs ,INPUT); delay(10); } void loop(){ Cayenne.loop(); long measurement =vibration(); delay(50); Serial.println(measurement); //Write to Cayenne Dashboard` Cayenne.virtualWrite(V0,measurement); } long vibration(){ long measurement=pulseIn (vs, HIGH); return measurement; } Download code Hardware interfacing with Cayenne IoT platform To interface the circuit with the IoT platform, open this link on any browser. Click on Add new and then Device/Widget in Settings, Add New Device here and select Generic ESP8266 for in this project. Configure device Generic ESP8266, MQTT username, password and client ID from Create App Paste these respective details under username, password and client ID in Arduino source code , along with your Wi-Fi name and password. After successfully compiling and uploading the code to NodeMCU, You will see ESP8266 connected to Wi-Fi. After the connection is established, the previous page is automatically updated on Cayenne. A new dashboard opens in the browser. Cayenne generates an ID and a device icon for your device.
- Bluetooth Controlled Automatic Door using PIR Sensor
Here to learn How to Make an Bluetooth controlled Automatic Door Opening and closing System Using Arduino, PIR Sensor HC-SR501 and android application, which automatically opens and closes the door by detecting a person and controlled by android app. You might have seen Automatic Door Opener Systems at office, shopping malls, cinemas, hospitals etc. where, as soon as a person approaches the door (at about 2 or 3 feet), the door automatically slides open. And after some time (about 5 to 10 seconds), the door closes by sliding in the reverse direction. Such Automatic Door Opener Systems are very useful as you do not need a person to standby the door and open it whenever a guest comes. Also, since the doors are opened and closed only when a person approaches the door. This automatic control and Stop control using bluetooth HC-05 through android application. So, In order to understand the potential of this concept, we have implemented a simple Automatic Door Opener System using Arduino and PIR HC-SR501 Sensor, Servo and Bluetooth. Circuit Diagram Components Required Arduino Nano - 1 no Bluetooth module HC-05 - 1no PIR HC-SR501sensor - 1 no Servo mini - 1 no HC-SR501 PIR sensor The PIR sensor stands for Passive Infrared sensor. It is a low cost sensor which can detect the presence of Human beings or animals. This sensor has three output pins Vcc, Output and Ground The module can be powered from voltage 4.5V to 20V but, typically 5V is used. Once the module is powered allow the module to calibrate itself for few minutes, 2 minutes is a well settled time. Then observe the output on the output pin. Before we analyze the output we need to know that there are two operating modes in this sensor such as Repeatable(H) and Non- Repeatable(L) and mode. The Repeatable mode is the default mode. The output of the sensor can be set by shorting any two pins on the left of the module. Repeatable(H) mode (used in this Project) In Repeatable(H) mode the output pin Dout will go high (3.3V) when a person is detected within range and goes low after a particular time (time is set by “Off time control” potentiometer). In this mode the output pin will go high irrespective of whether the person is still present inside the range or has left the area. The sensitivity can be set using the “sensitivity control” potentiometer Non- Repeatable(L) mode In “I” mode the output pin Dout will go high (3.3V) when a person is detected within range and will stay high as long as he/she stays within the limit of the Sensors range. Once the person has left the area the pin will go low after the particular time which can be set using the potentiometer. The sensitivity can be set using the “sensitivity control” potentiometer There are two important materials present in the sensor one is the pyroelectric crystal which can detect the heat signatures from a living organism (humans/animals) and the other is a Fresnel lenses which can widen the range of the sensor. Yes the white colour things is just a lense that is used to widen the range of the sensor, if you remove the lense you can find the Pyroelectric sensor inside it covered inside a protective metal casing as shown above. PIR Sensor Applications Automatic Street/Garage/Warehouse or Garden Lights Burglar Alarms Security cams as motion detectors Industrial Automation Control Download Datasheet Bluetooth HC-05 Module HC-05 is a Bluetooth module which is designed for wireless communication. This module can be used in a master or slave configuration. Bluetooth serial modules allow all serial enabled devices to communicate with each other using Bluetooth. It has 6 pins, 1.Key/EN: It is used to bring Bluetooth module in AT commands mode. If Key/EN pin is set to high, then this module will work in command mode. Otherwise by default it is in data mode. The default baud rate of HC-05 in command mode is 38400bps and 9600 in data mode. HC-05 module has two modes, Data mode: Exchange of data between devices. Command mode: It uses AT commands which are used to change setting of HC-05. To send these commands to module serial (USART) port is used. 2. VCC: Connect 5 V or 3.3 V to this Pin. 3. GND: Ground Pin of module. 4. TXD: Transmit Serial data (wirelessly received data by Bluetooth module transmitted out serially on TXD pin) 5. RXD: Receive data serially (received data will be transmitted wirelessly by Bluetooth module). 6. State: It tells whether module is connected or not. HC-05 module Information HC-05 has red LED which indicates connection status, whether the Bluetooth is connected or not. Before connecting to HC-05 module this red LED blinks continuously in a periodic manner. When it gets connected to any other Bluetooth device, its blinking slows down to two seconds. This module works on 3.3 V. We can connect 5V supply voltage as well since the module has on board 5 to 3.3 V regulator. As HC-05 Bluetooth module has 3.3 V level for RX/TX and microcontroller can detect 3.3 V level, so, no need to shift transmit level of HC-05 module. But we need to shift the transmit voltage level from microcontroller to RX of HC-05 module. HC-05 Default Settings Default Bluetooth Name: “HC-05” Default Password: 1234 or 0000 Default Communication: Slave Default Mode: Data Mode Data Mode Baud Rate: 9600, 8, N, 1 Command Mode Baud Rate: 38400, 8, N, 1 Default firmware: LINVOR Installing the Arduino Library No special library for this project. Subscribe and Download code. Download Android application. Download aia file for android development Mobile Output First open Mobile application BT PIR and select Bluetooth image, after that select bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). Arduino Code: #include const int PIR_PIN = 8; // Arduino pin connected to motion sensor's pin const int SERVO_PIN = 9; // Arduino pin connected to servo motor's pin Servo servo; // create servo object to control a servo // variables will change: int angle = 0; // the current angle of servo motor int lastMotionState; // the previous state of motion sensor int currentMotionState; // the current state of motion sensor char switchstate; void setup() { Serial.begin(9600); // initialize serial pinMode(PIR_PIN, INPUT); // set arduino pin to input mode servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object servo.write(angle); currentMotionState = digitalRead(PIR_PIN); } void loop() { while(Serial.available()>0){ //code to be executed only when Serial.available()>0 /*Serial.available>0 is to check if there is any reading from the HC-05 Bluetooth module.*/ switchstate = Serial.read(); /*The character we had declared earlier is now being assigned a value- the value of whatever Serial.read() is.*/ //Serial.read() is to read the value coming from app. Serial.print(switchstate); //This will print the value onto the Serial monitor. Serial.print("\n"); //This moves to the next line after every new line printed. delay(15); } lastMotionState = currentMotionState; // save the last state currentMotionState = digitalRead(PIR_PIN); // read new state if (currentMotionState == LOW && lastMotionState == HIGH && (switchstate == 'A')) { // pin state change: LOW -> HIGH // Serial.println("DOOR CLOSE"); Serial.println(currentMotionState); servo.write(0); } //else if (currentMotionState == HIGH && lastMotionState == LOW && (switchstate == 'A')) { // pin state change: HIGH -> LOW // Serial.println("DOOR OPEN"); Serial.println(currentMotionState); servo.write(90); } }
- IoT Based Object Angle measure using MPU 6050 and Blynk
In this tutorial, Measuring the angle (Object Position) using MPU6050 sensor and connect with Blynk IoT cloud Platform.The MPU6050 sensor module has a built-in gyroscope and an accelerometer sensor. The gyroscope is used to determine the orientation and the accelerometer provides information about the angle, such as X, Y, and Z-axis data. Circuit diagram Components Required LCD 20X4 line I2C - 1 no ESP8266 12e- NodeMCU - 1 no MPU6050 Accelerometer - 1 no MPU6050 Sensor MPU6050 sensor module is complete 6-axis Motion Tracking Device. It combines 3-axis Gyroscope, 3-axis Accelerometer and Digital Motion Processor all in small package. Also, it has additional feature of on-chip Temperature sensor. It has I2C bus interface to communicate with the microcontrollers. A micro-electro-mechanical system (MEMS) is used to measure velocity, acceleration, orientation, displacement, and many other motion-related parameters. The MPU6050 module comes with an I2C and auxiliary I2C interfaces. The SCL and SDA pins of the MPU6050 are connected to the D1 and D2 pins of the NodeMCU, while the VCC and GND pins of the MPU6050 are connected to the 3.3V and Ground pin of NodeMCU. 3-Axis Gyroscope The MPU6050 consist of 3-axis Gyroscope with Micro Electro Mechanical System(MEMS) technology. It is used to detect rotational velocity along the X, Y, Z axes as shown in below figure When the gyros are rotated about any of the sense axes, the Coriolis Effect causes a vibration that is detected by a MEM inside MPU6050. The resulting signal is amplified, demodulated, and filtered to produce a voltage that is proportional to the angular rate. This voltage is digitized using 16-bit ADC to sample each axis. The full-scale range of output are +/- 250, +/- 500, +/- 1000, +/- 2000. It measures the angular velocity along each axis in degree per second unit. 3-Axis Accelerometer The MPU6050 consist 3-axis Accelerometer with Micro Electro Mechanical (MEMs) technology. It used to detect angle of tilt or inclination along the X, Y and Z axes as shown in below figure Acceleration along the axes deflects the movable mass. This displacement of moving plate (mass) unbalances the differential capacitor which results in sensor output. Output amplitude is proportional to acceleration. 16-bit ADC is used to get digitized output. The full-scale range of acceleration are +/- 2g, +/- 4g, +/- 8g, +/- 16g. It measured in g (gravity force) unit. When device placed on flat surface it will measure 0g on X and Y axis and +1g on Z axis. DMP (Digital Motion Processor) The embedded Digital Motion Processor (DMP) is used to compute motion processing algorithms. It takes data from gyroscope, accelerometer and additional 3rd party sensor such as magnetometer and processes the data. It provides motion data like roll, pitch, yaw angles, landscape and portrait sense etc. It minimizes the processes of host in computing motion data. The resulting data can be read from DMP registers. On-chip Temperature Sensor On-chip temperature sensor output is digitized using ADC. The reading from temperature sensor can be read from sensor data register. The MPU-6050 module has 8 pins, INT: Interrupt digital output pin. AD0: I2C Slave Address LSB pin. This is 0th bit in 7-bit slave address of device. If connected to VCC then it is read as logic one and slave address changes. XCL: Auxiliary Serial Clock pin. This pin is used to connect other I2C interface enabled sensors SCL pin to MPU-6050. XDA: Auxiliary Serial Data pin. This pin is used to connect other I2C interface enabled sensors SDA pin to MPU-6050. SCL: Serial Clock pin. Connect this pin to microcontrollers SCL pin. SDA: Serial Data pin. Connect this pin to microcontrollers SDA pin. GND: Ground pin. Connect this pin to ground connection. VCC: Power supply pin. Connect this pin to +5V DC supply. MPU-6050 module has Slave address (When AD0 = 0, i.e. it is not connected to Vcc) as, Slave Write address(SLA+W): 0xD0 Slave Read address(SLA+R): 0xD1 MPU-6050 has various registers to control and configure its mode of operation. So, kindly go through MPU-6050 datasheet and MPU-6050 Register Map. Calculations Note that gyroscope and accelerometer sensor data of MPU6050 module consists of 16-bit raw data in 2’s complement form. Temperature sensor data of MPU6050 module consists of 16-bit data (not in 2’s complement form). Now suppose we have selected, - Accelerometer full scale range of +/- 2g with Sensitivity Scale Factor of 16,384 LSB(Count)/g. - Gyroscope full scale range of +/- 250 °/s with Sensitivity Scale Factor of 131 LSB (Count)/°/s. then, To get sensor raw data, we need to first perform 2’s complement on sensor data of Accelerometer and gyroscope. After getting sensor raw data we can calculate acceleration and angular velocity by dividing sensor raw data with their sensitivity scale factor as follows, Accelerometer values in g (g force) Acceleration along the X axis = (Accelerometer X axis raw data/16384) g. Acceleration along the Y axis = (Accelerometer Y axis raw data/16384) g. Acceleration along the Z axis = (Accelerometer Z axis raw data/16384) g. Gyroscope values in °/s (degree per second) Angular velocity along the X axis = (Gyroscope X axis raw data/131) °/s. Angular velocity along the Y axis = (Gyroscope Y axis raw data/131) °/s. Angular velocity along the Z axis = (Gyroscope Z axis raw data/131) °/s. Temperature value in °/c (degree per Celsius) Temperature in degrees C = ((temperature sensor data)/340 + 36.53) °/c. For example, Suppose, after 2’ complement we get accelerometer X axes raw value = +15454 Then Ax = +15454/16384 = 0.94 g. Blynk App Is an IoT platform to connect your devices to the cloud, design apps to control them, analyze telemetry data, and manage your deployed products at scale Blynk IoT Setup: First of all, open the blynk application. Click on the create a new project Click on Choice Tools and select NodeMCU ESP8266. Make sure the connection type is set to WIFI. Watch video for further setup. Installing Library Download these libraries from the given links. Blynk Download - Blynk Library can connect any hardware over Ethernet, WiFi, or GSM, 2G, 3G, LTE, etc. Liquid Crystal Download After downloading the .zip files, add the libraries in Arduino IDE by clicking on To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. Subscribe and download code. Subscribe and Download code. Arduino Code #include #include #define BLYNK_PRINT Serial #include #include #include #include LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display char auth[] = "xxxxxx"; // You should get Auth Token in the Blynk App new project from NODEMCU // WiFi network Credentials const char* ssid = "xxxxx"; // your SSID const char* password = "xxxx"; //your WIFI Password const int MPU_addr=0x68; int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; int minVal=265; int maxVal=402; double x; double y; double z; void setup(){ Wire.begin(); Wire.beginTransmission(MPU_addr); Wire.write(0x6B); Wire.write(0); Wire.endTransmission(true); Serial.begin(9600); Blynk.begin(auth, ssid, password); lcd.init(); // initialize the lcd // Print a message to the LCD. lcd.backlight(); } void loop(){ Blynk.run(); Wire.beginTransmission(MPU_addr); Wire.write(0x3B); Wire.endTransmission(false); Wire.requestFrom(MPU_addr,14,true); AcX=Wire.read()<<8|Wire.read(); AcY=Wire.read()<<8|Wire.read(); AcZ=Wire.read()<<8|Wire.read(); int xAng = map(AcX,minVal,maxVal,-90,90); int yAng = map(AcY,minVal,maxVal,-90,90); int zAng = map(AcZ,minVal,maxVal,-90,90); x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI); y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI); z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI); Serial.print("AngleX= "); Serial.println(x); Serial.print("AngleY= "); Serial.println(y); Serial.print("AngleZ= "); Serial.println(z); Serial.println(" ***************"); lcd.setCursor(0,0); lcd.print("3 Axis Angle Monitor"); lcd.setCursor(0,1); lcd.print("X"); lcd.print((char)223); lcd.print(": "); lcd.print(x); lcd.setCursor(0,2); lcd.print("Y"); lcd.print((char)223); lcd.print(": "); lcd.print(y); lcd.setCursor(0,3); lcd.print("Z"); lcd.print((char)223); lcd.print(": "); lcd.print(z); Blynk.virtualWrite(V1, x); Blynk.virtualWrite(V2, y); Blynk.virtualWrite(V3, z); delay(1000); } Then, upload the code to your NodeMCU board. Make sure you have selected the right board and COM port. Also, make sure you’ve inserted your WiFi Credentials in the code. After a successful upload, open the Serial Monitor at a baud rate of 9600.












