Project showcase
Smart Traffic Light

Smart Traffic Light © CC BY-NC-ND

Smart light that turn on at noon when anyone pass in street and turn off at morning also check its state and report if it need to be fixed.

  • 10,108 views
  • 9 comments
  • 21 respects

Components and supplies

Apps and online services

About this project

Overview

When I was on my way on a desert road I found lot of lamps switched on in the morning and some of these lamps are out of service and some of lamps remain on for a long time at night with nobody passing in the street. But how can we put off the light at morning and put it on at night and if the weather is cloudy during day time when anybody pass near this lamp?

Also how can we check all these lamp periodically, if a man checked these lamps each time it would be very hard task and will have high cost.

So in my project I used photo resistor (light dependent resistance) that change it's resistance value depending on the light falling on it and a PIR sensor to detect whether there is anyone in the street or not .

I used one LDR sensor on top of the lamp post to detect the light intensity falling on road if the light intensity is low (at night or at cloudy weather ) then light the lamp turn on else turn it off.

And I fixed another LDR sensor beside the lamp so it can detect the light intensity emitted by the lamp first when the lamp is new we will save the LDR reading and if this reading drop down by a value more than accepted then we can know that this lamp need to be changed and if it turn off the LDR will read very low or no intensity and we know that the lamp is out of service.

And the PIR sensor detect any body emitting infrared (ex : car , animal , person ) in a range of about 7 meters.

I took these readings on an arduino nano board or any other board with same pins and connect it to a raspberry pi 3 in order to upload these data to artik cloud and also I use a small led connected to the raspberry pi that can be turned on or off by using actions sent from android app to the cloud so the person who is going to fix the lamp can know which one is the lamp he want however if he go to fix the lamp at morning

For the circuit simulation click here: https://circuits.io/circuits/2761527-smart-light/embed#breadboard

The code I used is from: https://developer.artik.cloud/documentation/tutorials/an-iot=remote-control.html

and

https://www.artik.io/blog/2016/05/monitor-fire-temprature-using-artik-cloud-open-source-iot-hardware-android/

All the code for Arduino, Raspberry Pi and Android are attached. Here is a video of the project working:

Attention: In this video I have used a button instead of PIR sensor for testing purpose as the PIR would detect me at all situations , the PIR is tested and works exactly the same as it prints 1 on the Arduino like the button.

Step by step tutorial

If you need any help building this project leave me a comment.

Code

arduino codeArduino
// select the input pin for the LDR sensor beside the led
int ledSensor = A1 ;    
// select the input pin for the LDR sensor on top of lamp that feel sunlight
int sunSensor = A0 ;    
// select the input pin for the LED
int led = 13 ;    
// pir sensor
int pirSensor = 2 ;

// variable to store the value coming from the sensor beside the led
int ledSensorValue = 0;  
// variable to store the value coming from the sensor on top of lamp that feel sunlight
int sunSensorValue = 0 ; 
// variable to store the value coming from the  pir sensor 
int pirSensorValue = 0 ;

void setup() {
  //open serial communication
  Serial.begin(9600);
  // declare the ledPin as an OUTPUT:
  pinMode(led, OUTPUT); 
  // declare the ledPin as an OUTPUT:
  pinMode(pirSensor, INPUT); 
}

void loop() {
    // read the value from the sunSensor
    sunSensorValue = analogRead(sunSensor);
   
  // determine a value that when read from sunLightSensor the led turn on  
  if (sunSensorValue > 900 )
  {
    // read the value from the pirSensor
    pirSensorValue = digitalRead (pirSensor);
    // if there is anyone in the street pirSensorValue will be 1
    if (pirSensorValue == 1) 
    {
    // turn the LED on (HIGH is the voltage level)
    digitalWrite(13, HIGH); 
    Serial.print(String(1));//led is on
    Serial.print(",");
    Serial.print(String(sunSensorValue)); //sunSensorReading
    Serial.print(",");
    ledSensorValue = analogRead(ledSensor); 
    Serial.print(String(ledSensorValue));// ledSensorReading
    Serial.print(",");
    Serial.println(String(pirSensorValue));// sunSensorReading
    
    
    }else if (pirSensorValue == 0){
    //if there is nobody in the street then pirSensorReading will be 0 and light will turn off
    
    // turn the LED off (LOW is the voltage level)
    digitalWrite(13, LOW); 
    Serial.print(String(0));//led is off
    Serial.print(",");
    Serial.print(String(sunSensorValue)); //sunSensorReading
    Serial.print(",");
    ledSensorValue = analogRead(ledSensor); 
    Serial.print(String(ledSensorValue));// ledSensorReading
    Serial.print(",");
    Serial.println(String(pirSensorValue));// sunSensorReading
    
      }
    

    }
    // if it is sunny enough
    else if (sunSensorValue < 900)
    {
      // turn the LED off by making the voltage LOW
     digitalWrite(13, LOW);
    Serial.print(String(0)); //led is off
    Serial.print(",");
    Serial.print(String(sunSensorValue));// sunSensorReading
    Serial.print(",");
    ledSensorValue = analogRead(ledSensor);
    Serial.print(String(ledSensorValue));// ledSensorReading
    Serial.print(",");
    pirSensorValue = digitalRead (pirSensor);
    Serial.println(String(pirSensorValue));// sunSensorReading
    
    }
  //end of first statment 
  //delay for 10 seconds then take the reading again
  delay(10000);
  
}
raspberry pi codeJavaScript
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "your device id here";
var device_token = "device token id";

var WebSocket = require('ws');
var gpio = require('rpi-gpio');

var isWebSocketReady = false;
var ws = null;

var myPin = 11;// physical pin #
var myLEDState = 0;
var pirState ="";

var serialport = require("serialport")
var SerialPort = serialport.SerialPort;
//write the port name arduino connected in
var sp = new SerialPort("/dev/ttyUSB0", {
    baudrate: 9600,
    parser: serialport.parsers.readline("\n")
});

var WebSocket = require('ws');

/**
 * Gets the current time in millis
 */
function getTimeMillis(){
    return parseInt(Date.now().toString());
}

/**
 * Create a /websocket device channel connection 
 */
function start() { //Create the WebSocket connection
    isWebSocketReady = false;
    ws = new WebSocket(webSocketUrl);
    ws.on('open', function() {
        console.log("WebSocket connection is open ....");
        register();
    });
    ws.on('message', function(data) {
 //      console.log("Received message: " + data + '\n');
         handleRcvMsg(data);
    });
    ws.on('close', function() {
        console.log("WebSocket connection is closed ....");
	exitClosePins();
    });

    gpio.setup(myPin, gpio.DIR_OUT, function(err) {
        if (err) throw err;
        myLEDState = false; // default to false after setting up
        console.log('Setting pin ' + myPin + ' to out succeeded! \n');
     });
}

/**
 * Sends a register message to the websocket and starts the message flooder
 */
function register(){
    console.log("Registering device on the websocket connection");
    try{
        var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
        console.log('Sending register message ' + registerMessage + '\n');
        ws.send(registerMessage, {mask: true});
        isWebSocketReady = true;
    }
    catch (e) {
        console.error('Failed to register messages. Error in registering message: ' + e.toString());
    }   
}



/**
 * Handle Actions
   Example of the received message with Action type:
   {
   "type":"action","cts":1451436813630,"ts":1451436813631,
   "mid":"37e1d61b61b74a3ba962726cb3ef62f1",
   "sdid”:”xxxx”,
   "ddid”:”xxxx”,
   "data":{"actions":[{"name":"setOn","parameters":{}}]},
   "ddtid":"dtf3cdb9880d2e418f915fb9252e267051","uid":"650xxxx”,”mv":1
   }
 */
function handleRcvMsg(msg){
    var msgObj = JSON.parse(msg);
    if (msgObj.type != "action") return; //Early return;

    var actions = msgObj.data.actions;
    var actionName = actions[0].name; //assume that there is only one action in actions
    console.log("The received action is " + actionName);
    var newState;
    if (actionName.toLowerCase() == "seton") {
        newState = true;
    }
    else if (actionName.toLowerCase() == "setoff") {
        newState = false;
    } else {
        console.log('Do nothing since receiving unrecognized action ' + actionName);
        return;
    }
    toggleLED(newState);
}

function toggleLED(value) {
    gpio.write(myPin, value, function(err) {
        if (err) throw err;
        myLEDState = value;
        console.log('toggleLED: wrote ' + value + ' to pin #' + myPin);
        //sendStateToArtikCloud();
    });

}



/**
 * Send one message to ARTIK Cloud containning all data 
 */
function sendData(led, sunState , ledState , pirState , emergencyState ){
    try{
        ts = ', "ts": '+getTimeMillis();
        var data = {
			"led": led ,
			"sunState": sunState ,
            "ledState": ledState ,
            "pirState":pirState , 
            "emergencyState": myLEDState 
            
            };
            
       var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
       console.log('Sending payload ' + payload + '\n');
       ws.send(payload, {mask: true});
       
    } catch (e) {
       console.error('Error in sending a message: ' + e.toString());
    }   
}
 


/** 
 * Properly cleanup the pins
 */
function exitClosePins() {
    gpio.destroy(function() {
        console.log('Exit and destroy all pins!');
        process.exit();
    });
}

/**
 * All start here
 */

start();



sp.on("open", function () {
    sp.on('data', function(data) {
            if (!isWebSocketReady){
                console.log("Websocket is not ready. Skip sending data to ARTIK Cloud (data:" + data +")");
                return;
            }
            console.log("Serial port received data:" + data);
			 var parsedStrs = data.split(",");
			 var lightled = parseInt(parsedStrs[0]);// 1 or 0 
			 var sunreading = parseInt(parsedStrs[1]);// sun or dark reading
			 var ledreading = parseInt(parsedStrs[2]);// weak , good , outofserviec
			 var pirreading = parseInt(parsedStrs[3]);// person in street , nobodyin street

			 var led = true ;
			 var sunState = "";
			 var ledState = "";
			 //var pirState= "";
			 
			 if (lightled==0){
				 led=false;
				 };
				 
			 if (sunreading>900){
			 sunState= "dark"
			 }else if (sunState < 900){
			 sunState = "light"} ;
			 
			 if (ledreading < 1000 && ledreading > 900){
				 ledState="weak"}else if (ledreading > 1000 ) {
					 ledState="outofservice"}else if (ledreading < 900){
						 ledState="light is on"};
						 
			 if(pirreading==1){
				 pirState = "someone is in the street"}else if (pirreading == 0)
				 { pirState = "nobody is in the street"
					 };
			 sendData(led , sunState , ledState , pirState );
		});
});
process.on('SIGINT', exitClosePins);

Schematics

when it is dark or cloudy
Screenshot%20(53)
when it is sunny
Screenshot%20(57)
the circuit schematic
Screenshot%20(61)
raspberry pi

No document.

Comments

Similar projects you might like

Arduino Traffic Light Simulator

Project tutorial by Zachary Haslam

  • 8,054 views
  • 1 comment
  • 20 respects

Smart Home - Smart Rules using ARTIK Cloud & Photon

Project tutorial by Raghavendra Ponuganti

  • 3,864 views
  • 2 comments
  • 12 respects

Arduino-Powered Smart Light (Works with Amazon Echo)

Project tutorial by Tinker Project

  • 14,717 views
  • 7 comments
  • 29 respects

Animated Smart Light with Alexa and Arduino

Project tutorial by Bruno Portaluri

  • 3,652 views
  • 9 comments
  • 23 respects

Smart Garden

Project showcase by patel Dipen

  • 22,291 views
  • 15 comments
  • 59 respects
Add projectSign up / Login