Fady Tarek
Published © CC BY-NC-ND

Smart Traffic Light

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.

IntermediateShowcase (no instructions)3 hours11,071
Smart Traffic Light

Things used in this project

Story

Read more

Schematics

when it is dark or cloudy

when it is sunny

the circuit schematic

raspberry pi

File missing, please reupload.

Code

arduino code

Arduino
// 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 code

JavaScript
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);

Credits

Fady Tarek

Fady Tarek

5 projects • 15 followers

Comments