Arduino Sensors

From Network Security Wiki


Here you will find a brief introduction and simple usage guide/instructions along with simple Sketch for arduino based sensors & addons like displays, motors, modules, etc.

        This page is under construction.

TM1637

Connecting TM1637 4x7 Segment Display to Arduino

Source: tronixstuff.com

#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 2
#define DIO 3

#define TEST_DELAY   2000

const uint8_t SEG_DONE[] = {
	SEG_B | SEG_C | SEG_D | SEG_E | SEG_G,           // d
	SEG_A | SEG_B | SEG_C | SEG_D | SEG_E | SEG_F,   // O
	SEG_C | SEG_E | SEG_G,                           // n
	SEG_A | SEG_D | SEG_E | SEG_F | SEG_G            // E
	};
TM1637Display display(CLK, DIO);

void setup()
{
}

void loop()
{
  int k;
  uint8_t data[] = { 0xff, 0xff, 0xff, 0xff };
  display.setBrightness(0x0f);
  
  // All segments on
  display.setSegments(data);
  delay(TEST_DELAY);
  
  // Selectively set different digits
  data[0] = 0b01001001;
  data[1] = display.encodeDigit(1);
  data[2] = display.encodeDigit(2);
  data[3] = display.encodeDigit(3);
  
  for(k = 3; k >= 0; k--) {
	display.setSegments(data, 1, k);
	delay(TEST_DELAY);
	}
	
  display.setSegments(data+2, 2, 2);
  delay(TEST_DELAY);
  
  display.setSegments(data+2, 2, 1);
  delay(TEST_DELAY);
  
  display.setSegments(data+1, 3, 1);
  delay(TEST_DELAY);
 
  
  // Show decimal numbers with/without leading zeros
  bool lz = false;
  for (uint8_t z = 0; z < 2; z++) {
	for(k = 0; k < 10000; k += k*4 + 7) {
		display.showNumberDec(k, lz);
		delay(TEST_DELAY);
	}
	lz = true;
  }
  
  // Show decimal number whose length is smaller than 4
  for(k = 0; k < 4; k++)
	data[k] = 0;
  display.setSegments(data);
  
  display.showNumberDec(153, false, 3, 1);
  delay(TEST_DELAY);
  display.showNumberDec(22, false, 2, 2);
  delay(TEST_DELAY);
  display.showNumberDec(0, true, 1, 3);
  delay(TEST_DELAY);
  display.showNumberDec(0, true, 1, 2);
  delay(TEST_DELAY);
  display.showNumberDec(0, true, 1, 1);
  delay(TEST_DELAY);
  display.showNumberDec(0, true, 1, 0);
  delay(TEST_DELAY);

  // Brightness Test
  for(k = 0; k < 4; k++)
	data[k] = 0xff;
  for(k = 0; k < 16; k++) {
    display.setBrightness(k);
    display.setSegments(data);
    delay(TEST_DELAY);
  }
    
  // Done!
  display.setSegments(SEG_DONE);
  
  while(1);
}


DS3231

Setting Time for first usage
  • You can uncomment the below 3 lines from the below give sketch code to set time for first time.
  • Set a near future time & either start uploading the code 2-3 seconds before the exact time(which was set).
  • Otherwise upload time code before the time & press the reset button on Arduino at the exact time.
  • After time is synced, comment these lines & reupload the code again o Arduino.
  • Otherwise same time will be set on every powerup or reset of arduino
 //rtc.setDOW(WEDNESDAY);            // Set Day-of-Week to SUNDAY
 //rtc.setTime(12, 0, 0);            // Set the time to 12:00:00 (24hr format)
 //rtc.setDate(1, 1, 2014);          // Set the date to January 1st, 2014


DS3231 RTC Clock Using Non-Rechargeable Batteries

Source: raspberrypi-spy.co.uk, woodsgood.ca

DS3231 RTC Clock with TM1637 Display

Source: instructables.com

#include <TM1637Display.h>
#include <TM1637.h>
// Arduino Uno/2009:
// ----------------------
// DS3231:  SDA pin   -> Arduino Analog 4 or the dedicated SDA pin
//          SCL pin   -> Arduino Analog 5 or the dedicated SCL pin
#include <Wire.h>
#include <DS3231.h>
#include <config.h>

#define DISPLAY_CLK_PIN 2  
#define DISPLAY_DIO_PIN 3

int led = 3;
TM1637 display(DISPLAY_CLK_PIN, DISPLAY_DIO_PIN);
DS3231  rtc(SDA, SCL);
Time  t;

void setup()
{
  Serial.begin(115200);

  display.set();
  display.init();
  pinMode(led, OUTPUT);

  rtc.begin();
  
  // The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
}

void loop()
{
  int8_t timeDisp[4];
  t = rtc.getTime();
  timeDisp[0] = t.hour / 10;
  timeDisp[1] = t.hour % 10;
  timeDisp[2] = t.min / 10;
  timeDisp[3] = t.min % 10;
  display.point(t.sec % 2 ? POINT_ON : POINT_OFF);  //Colon Blibk
  display.display(timeDisp);
  delay (1000);
}


Library

Source: rinkydinkelectronics.com

HC-SR04

HC-SR04 UltraSonic Distance Sensor with TM1637 Display

Source: codebender.cc

#include <Arduino.h>
#include <TM1637Display.h>
#include <NewPing.h>

const byte TRIGGER_PIN = 11; 
const byte ECHO_PIN    = 12; 
const int MAX_DISTANCE = 500;

const byte CLK = 3;
const byte DIO = 4;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
TM1637Display display(CLK, DIO);

void setup()
{
  Serial.begin(115200);
  display.setBrightness(0x0f);
}

void loop()
{
  delay(500);                   
  int x = sonar.ping_cm();
  display.showNumberDec(x,false,3,1);
  Serial.print(x);
  Serial.println(" cm");
}


Library

Source: arduino.cc

MQ-2 Gas Sensor

  • If using the sensor for first time, leave it powered on for about 24-48 hours(Burn-in Time).
  • Just calibrate it to get about 100-150 from analogRead in a good air condition.
  • Normal air returns ~100-150


const int sensorPin= 0;
const int buzzerPin= 11;
int smoke_level;
int powerLED = 13;
int greenLED = 9;
int redLED = 7;
int threshold = 400;                       // Your threshold value
int i = 0;

void setup() {
pinMode(sensorPin, INPUT);                 //the smoke sensor will be an input to the arduino
pinMode(buzzerPin, OUTPUT);                //the buzzer serves an output in the circuit
pinMode(powerLED, OUTPUT);
Serial.begin(9600);
digitalWrite(buzzerPin, LOW);              //keep buzzer silent on startup
}

void pulsePowerLED() {
  digitalWrite(powerLED, HIGH);
  delay(100);
  digitalWrite(powerLED, LOW);
  delay(100);
}

void alarm(){
for (int i=0; i<20; i++)
{
  digitalWrite(powerLED, HIGH);
  digitalWrite(buzzerPin, HIGH);
  delay(500);
  digitalWrite(powerLED, LOW);
  digitalWrite(buzzerPin, LOW);
  delay(100);
}
}

void loop() {
  if (millis() / 1000 / 20 < 1)             //we need to give the device some time to stabilize
  {
    Serial.println("Calibrating for 20 seconds... ");
    while(millis() / 1000 / 20 < 1) {
      pulsePowerLED();                     //pulse our power / blue LED so the user knows something is happening
    }
    Serial.println("Calibrated.");
  }
  
smoke_level= analogRead(sensorPin);        //arduino reads the value from the smoke sensor
Serial.println(smoke_level);

if(smoke_level > threshold)
    alarm();
else
    digitalWrite(buzzerPin, LOW);
    digitalWrite(powerLED, HIGH);
    delay(100);
    digitalWrite(powerLED, LOW);
    delay(2000);                           // Wait for 2 seconds
}


DS18B20

Source: tweaking4all.com

#include <OneWire.h>
#include <DallasTemperature.h>
#include <TM1637Display.h> 

#define ONE_WIRE_BUS 7

OneWire oneWire(ONE_WIRE_BUS); // Setup to communicate with any OneWire device
DallasTemperature sensors(&oneWire);

#define CLK 3
#define DIO 2
TM1637Display display(CLK, DIO);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library");

  sensors.begin();
  sensors.setResolution(12);
  display.setBrightness(0x0c);
}

void loop(void)
{ 
  sensors.requestTemperatures();    // Send the command to get temperatures
  delay(1000);
  float temp = sensors.getTempCByIndex(0);
  int temp2 = temp * 100;
  display.showNumberDec(temp2);
  Serial.print("Temperature is: ");
  Serial.print(sensors.getTempCByIndex(0));
  Serial.print(" C, ");
}


JHD162A LCD

Source: rastating.com, circuitstoday.com

Pin 1 to GND
Pin 2 to 5v
Pin 3 to center pin of 10k ohm Pot(103), One leg to +VCC & other to GND
Pin 4 to Arduino pin 12
Pin 5 to GND
Pin 6 to Arduino pin 11
Pin 11 to Arduino pin 5
Pin 12 to Arduino pin 4
Pin 13 to Arduino pin 3
Pin 14 to Arduino pin 2
Pin 15 to 5v through a 220 ohm resistor
Pin 16 to GND

Simple Text:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int lastUpdate = 0;  
int currentIndex = 0;  
char* lyrics[] = {  
  "Drink all the...", 
  "     BOOZE!     ",
  "Hack all the... ",
  "    THINGS!     " 
};

void setup() {  
  lcd.begin(16, 2); // LCD no of lines
}

void loop() {  
  int time = millis();
  if ((time  - lastUpdate) >= 800)  // print next line after 800ms
  {
    lcd.setCursor(0, 0);
    if (currentIndex == 0 || currentIndex == 2)
    {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(lyrics[currentIndex]);
    }
    else
    {
      lcd.setCursor(0, 1);
      lcd.print(lyrics[currentIndex]);
    }
    if (currentIndex == 3)    // reset of increment index
    {
      currentIndex = 0;
    }
    else
    {
      currentIndex += 1;
    }
    lastUpdate = time;
  } 
}


Scrolling Text:

#include <LiquidCrystal.h>
int pos=0; // variable to hold cursor position

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
 lcd.begin(16, 2);                              //initializes 16x2 LCD
 lcd.print("Amandeep Singh & Mankirat Singh");   //text to display
}

void loop()
{
  for(pos=0; pos<1; pos++)  
  {
  lcd.scrollDisplayLeft();    //scrolls display left by two positions
  }  
  delay(400);              //sets the speed at which display moves
}

PIR Sensor

Source: instructables.com

int calibrationTime = 30;       //time given to sensor to calibrate
long unsigned int lowIn;         
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;  

int pirPin = 7;    //Digital pin connected to the PIR sensor's output
int ledPin = 8;

void setup(){
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

  Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
  }

void loop(){
     if(digitalRead(pirPin) == HIGH){
       digitalWrite(ledPin, HIGH);
       if(lockLow){  
         lockLow = false;            
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec"); 
         delay(50);
         }         
         takeLowTime = true;
       }

     if(digitalRead(pirPin) == LOW){       
       digitalWrite(ledPin, LOW);

       if(takeLowTime){
        lowIn = millis();   
        takeLowTime = false; 
        }

       if(!lockLow && millis() - lowIn > pause){  
           lockLow = true;                        
           Serial.print("motion ended at ");
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
  }


Reed Switch

Source: electroschematics.com

int ledOpen=8;
int ledClose=10;
int switchReed=6;

void setup(){
  pinMode(ledOpen, OUTPUT);
  pinMode(ledClose, OUTPUT);
  pinMode(switchReed, INPUT);
  Serial.begin(9600);
}

void loop(){
  
  if (digitalRead(switchReed)==HIGH){
    digitalWrite(ledOpen, LOW);
    digitalWrite(ledClose, HIGH);
    Serial.println("Your Door is Closed");
  }
  else {
    digitalWrite(ledOpen, HIGH);
    digitalWrite(ledClose, LOW);
    Serial.println("Your Door is Open");
  }
  delay(1000);
}


LDR

Source: diyhacking.com

Connections

This project will allow you to turn On or Off a LED using LDR.
You can adjust amount of light by adjusting the value of 'sensorValue'.

#include <SoftwareSerial.h>

int sensorPin = A0; // select the input pin for the LDR
int sensorValue; // variable to store the value coming from the sensor
int led = 3;

void setup()
{
  pinMode(led, OUTPUT);
  Serial.begin(9600); 
}

void loop()
{
  sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  if(sensorValue < 300)
  {
     digitalWrite(led,HIGH);
     delay(1000);
  }
  else
   digitalWrite(led,LOW);
   delay(1000);
}


Bluetooth Module

Source: instructables.com

#include <SoftwareSerial.h>

SoftwareSerial SoftSerial(10, 11); // RX, TX
int ledpin=13; 
int BluetoothData;

void setup() 
{
  SoftSerial.begin(9600);
  SoftSerial.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}

void loop() 
{
   if (SoftSerial.available())
     {
       BluetoothData=SoftSerial.read();
       if(BluetoothData=='1'){   
       digitalWrite(ledpin,1);
       SoftSerial.println("LED  On D13 ON ! ");
     }
  if (BluetoothData=='0')
    {
      digitalWrite(ledpin,0);
      SoftSerial.println("LED  On D13 Off ! ");
    }
}
delay(100);
}





{{#widget:DISQUS |id=networkm |uniqid=Arduino Sensors |url=https://aman.awiki.org/wiki/Arduino_Sensors }}