Smart Parking System

Hardware components:
Pi 3 02
Raspberry Pi 3 Model B
× 1
Ardgen mega
Arduino Mega 2560 & Genuino Mega 2560
× 1
51gzz5eu9pl. sx425
HC-SR04
× 3
Software apps and online services:
Artik logo cloud
Samsung IoT ARTIK Cloud for IoT
New google maps logo
Google Maps
Ide web
Arduino IDE

Smart Parking System

STORY

Finding a free parking lot in a congested city like Bangalore is very hard. Here, if anyone wants to go outside from home with personal car first thing comes in his mind is about parking, where he will park his car. Most of the cases, people go to a parking station and find that all parking slot are full and then he have to search for another parking lot. So, it is a big hassle and many people keep in fear about parking of his car when he gets out with his car.

So, I was thinking, how the problem can be solved and finally I succeeded to make a cloud based smart parking system and I hope implementing the system can remove the parking problem of my city. ARTIK Cloud is really a nice and appropriate platform for such job.

Using this system a user will be will able to find an available parking lot easily using mobile or web app from anywhere. The system updates parking data every 30 seconds.

In this project I will show you how you can easily build such smart system. Definitely, I will use ARTIK Cloud platform, the coolest IoT cloud platform. Before going to the details, enjoy the demo video of my demo project.

For this demo system you have to create only one new devices in Samsung Artik Cloud platform. I will show it here. I named my devices as rainbow-parking, and store parking data such as free slots in a parking lot. Raspi sends parking information according to the preset rules.

Steps involved in this project:

1. Making one device in Artik Cloud Platform

2. Making one application in Artik Cloud

3. Making one rule in Artik Cloud

4. Preparing Arduino

5. Connecting the Sensors

6. Preparing Raspberry Pi

7. Developing Web Application

So, Let’s start one by one. First thing first. Let’s start with making a new device in Artik cloud platform.

Step 1: Making a new device in Artik Cloud Platform

A) Log in to your Samsung account and Click on DEVELOPER option from top right corner.

Log in to your Samsung account and Click on DEVELOPER option from top right corner

B) From the DASHBOARD select DEVICE TYPES and Click on NEW

B) From the DASHBOARD select DEVICE TYPES and Click on NEW

C) On the DEVICE DISPLAY NAME type a name for the device and give a UNIQUE NAME, then click to CREATE DEVICE TYPE.

then click to CREATE DEVICE TYPE.

D) Click on + NEW MANIFEST

Click on + NEW MANIFEST

E) Type a FIELD NAME for your sensor data you will upload and store here and mention the DATA TYPE as integer. Then click to SAVE

DATA TYPE as integer

Block Diagram of Smart Parking System

Block Diagram of Smart Parking System

F) Then click NEXT: DEVICE ACTIONS

Then click NEXT DEVICE ACTIONS

G) Make an action or select from the STANDARD ACTIONS. Click to SAVE. For our project actions will not be required. Then click to NEXT:ACTIVE MANIFEST.

ACTIVE MANIFEST

H) Take a look to Device Fields and again click to NEXT:ACTIVE MANIFEST.

Take a look to Device Fields and again click to NEXT

I) Congratulation! you successfully created your first device. Now you have to connect the device to Artik cloud. So, let’s do it.

Congratulation! you successfully created your first device

J) Go to MY ARTIK CLOUD from right top corner.

Go to MY ARTIK CLOUD from right top corner

K) Click on MY ARTIK CLOUD and select DEVICES.

Click on MY ARTIK CLOUD and select DEVICES.

L) Click to +Add another device.

Click to +Add another device.

M) Type the name of the device you just created and click on it.

Type the name of the device you just created and click on it.

N) Click on CONNECT DEVICE… button.

Click on CONNECT DEVICE... button

O) Your device is connected to the CLOUD.

Your device is connected to the CLOUD

P) Click on it. Generate Token, Note down your DEVICE ID and DEVICE TOKEN. These will be required latter every time you want to connect to your device from physical devices, web apps or android apps.

These will be required latter every time you want to connect to your device

Step 2: Making rule in Artik Cloud

In this step we will make a rule where we set some conditions according to which Artik cloud will generate an action when the condition meets and the devices and applications subscribed to the action receive a message instantly.

A) Select RULES from the MY ARTIK CLOUD menu and Click on NEW RULE

Select RULES from the MY ARTIK CLOUD menu and Click on NEW RULE

B) From IF selection box select a data field for a device and set a value and condition. Then select an action for a specific device from THEN field. You can set a constant parameter value or can select a value from another device data. To define a data field from another device click on download icon shown in red box.

To define a data field from another device click on download icon shown in red box.

C) Select a device from the drop-down and then select data field.

a device from the drop-down and then select data field

D) Then click on SAVE RULE.

Then click on SAVE RULE

Step 3. Preparing Arduino

The main work of the Arduino in my project is to collect data from sensors connected to parking stations and to send the data to Raspberry pi using serial port. Here i used Arduino Mega is implemented for one parking stations. we can connect more Arduino boards for different Parking Stations. Here I used ultrasonic sensors and can be used in any location.

For ultrasonic sensors Arduino digital pins were used. Arduino sketch Ultra sonic sensors are attached. Upload appropriate sketch to your Arduino board .

Details about ultrasonic sensor can be found here.

Step 4: Connecting the Sensors

For connecting all the sensors to Arduino please see the schematic section.

Connecting the Sensors

Step 5: Preparing Raspberry Pi

I am assuming that, you have some previous experience in working with Raspberry pi. Lots of beginners tutorials are available in the Internet.

Let’s start our work with raspberry pi. Raspberry pi is working as a WebSocket client and communicates with Artik cloud using WebSocket protocol. I used Node.js for programming. Unlike Python Node is not preinstalled on Raspberry Pi.

A). Install Node and npm on Raspberry pi using following commands in terminal.

sudo apt-get update
sudo apt-get install nodejs npm

B). Install WebSocket client ws to raspberry pi

npm install --save ws

C). Install serialport to raspberry pi

npm install serialport

If you successfully completed all three steps then your pi is ready to communicate with Arduino using serial port and Artik cloud using websocket. As I said earlier two raspberry pis are required for two parking station. So, download the source code for the this from the Github . You can use ftp client like FileZilla to upload the code on raspberry pi. Don’t forget to change DEVICE ID & DEVICE TOKEN in the source code.

D) After uploading the code on raspberry pi run the code by typing the following command into terminal window.

sudo node staff-parking.js

Step 6. Developing Web Application

For developing web application HTML and JavaScript was used. For communicating with Artik cloud here I again used WebSocket protocol. For integrating Map in my application I used Google Map API.

Download the web-app folder from my Github and modify the DEVICE ID and DEVICE TOKEN with your own device id and token. Use ID of the device which generate the action on new data received (edison in my case). Open the websocket.html using a web browser and enjoy. See the demo video..

Schematics

Code

//staff parking data transfer
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "Your Device id"; // staff  parking DEVICE ID
var device_token = "Your Device Token"; //staff parking DEVICE TOKEN
// require websocket module to connect 
// execute following two commands to your pi's terminal
// sudo apt-get update
// npm install websocket
var WebSocket = require('ws');
var isWebSocketReady = false;
var data="";
var ws = null;
// require serialport module to raspberry pi 
// execute following command to terminal
// npm install serialport
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", { //for serial communication with arduino 
    baudrate: 9600,  
// we are using UNO so baudrate is 9600, you might need to change according to your model
    parser: serialport.parsers.readline("\n")
});

var parking_state=0;// variable to check for parking state_gate

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

/**
 * Create a /websocket connection and setup GPIO pin
 */
function start() {
    //Create the WebSocket connection
    isWebSocketReady = false;
    ws = new WebSocket(webSocketUrl);
	// this function invoked on successful connection
    ws.on('open', function() {
        console.log("WebSocket connection is open ....");
		// you must register for successful data transmission
		// registration is for authentication or secure data transfer
        register();
    });
    ws.on('message', function(data) {
      //this loop is called whenever the client sends some message
         handleRcvMsg(data); //data is send to the function handleRcvMsg()
    });
    ws.on('close', function() {
        console.log("WebSocket connection is closed ....");

    });      
    
}

/**
 * Sends a register message to /websocket endpoint
 */
//Client will only work when device gets registered from here
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());
    }    
}


//data after receiving is sent here for processing
// in our case this function will not be used as we will not receive any action
// in raspberry pi. This is for future modification.
function handleRcvMsg(msg){
	// you have to parse the received string
    var msgObj = JSON.parse(msg);
    if (msgObj.type != "action") return; //Early return;

    var actions = msgObj.data.actions;
    var actionName = actions[0].name; 
    console.log("The received action is " + actionName);
  
    //you must know your registered actions in order to perform accordinlgy
    if (actionName.toLowerCase() == "settext") 
    { 
        // do something here after receiving 'parking_state'
		console.log('receving recognized action' + actionName);
    }
    else {
         //this loop executes if some unregistered action is received
         //so you must register every action in cloud
        console.log('Do nothing since receiving unrecognized action ' + actionName);
        return;
    }
   
}



/**
 * Send one message to ARTIK Cloud
 */
//This function is responsible for sending commands to cloud
//function sendStateToArtikCloud(parking) sends number of free parking slot to artik cloud
function sendStateToArtikCloud(parking_slot){
    try{
        ts = ', "ts": '+getTimeMillis();
        var data = {
            "parking_slot": parking_slot
            //setting the parking value from argument to our cloud variable "parking_value"

            };
        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() +'\n');
    }    
}



function exitClosePins() {
    
        console.log('Exit and destroy all pins!');
        process.exit();
    
}


start();
//exectes every time when data is received from arduino (30 sec programmed delay from arduino)
sp.on("open", function () {
    sp.on('data', function(data) {
            console.log("Serial port received data:" + data);
            //sendStateToArtikCloud(data);//free parking slot
			var parking_slot = parseInt(data);
            sendStateToArtikCloud(parking_slot);
           
    });
});

process.on('SIGINT', exitClosePins);
Scroll to Top