Project in progress
Smart Car

Smart Car © CC BY-NC

Smart car with a parking system, thief alarm, and car locator

  • 4,402 views
  • 0 comments
  • 15 respects

Components and supplies

Apps and online services

About this project

How many times have you parked your car and forgot where it is?

How hard is it for you to park your car and know the distance between you and the car behind you ?

Sometimes you give your car to your son and don't know where he is .

With this device you can easily track the position of your car.

This kit helps you find your car's location and activate an alarm using your mobile phone. You can get your car's position by reading Latitude and Longitude and putting the coordinates into google maps.

www.gps-coordinates.net

This is a step by step tutorial showing how to make this system, including components.

Ultrasonic sensor

Basic Ultrasonic sensor code that prints the distance between the sensor and object in front of it:

//ultrasonic Arduino code 
#define echoPin 7 // Echo Pin  
#define trigPin 8 // Trigger Pin  
long duration, distance ; // Duration used to calculate distance  
void setup() {   
pinMode(trigPin, OUTPUT);  
pinMode(echoPin, INPUT);  
Serial.begin (9600);  
}  
void loop() {  
/* The following trigPin/echoPin cycle is used to determine the  
distance of the nearest object by bouncing soundwaves off of it. */   
digitalWrite(trigPin, LOW);   
delayMicroseconds(2);   
digitalWrite(trigPin, HIGH);  
delayMicroseconds(10);   
digitalWrite(trigPin, LOW);  
duration = pulseIn(echoPin, HIGH);  
//Calculate the distance (in cm) based on the speed of sound.  
distance = duration/58.2;  
Serial.println(distance);  
//Delay 50ms before next reading.  
delay(50);   
} 

Buzzer

Buzzer Code that will be used to indicate the distance of object in front or behind the car during parking mode also will alarm user if car is switched on when it is in security mode:

const int freq = 500; 
const int dur = 20; 
const int buzzer = 3; 
void setup() { 
 // put your setup code here, to run once: 
 pinMode(buzzer, OUTPUT); 
} 
void loop() { 
 // put your main code here, to run repeatedly: 
 tone(buzzer, freq, dur); 
 delay(50); 
} 

Gps Module

GPS NMEA 6m code that will give us latitude and longitude that we will use to get the car position at any time the commented lines with // at the beginning we wouldn't use also you are free to uncomment them if you want

Here is the video explaining how it works : 

#include "TinyGPS++.h" 
#include "SoftwareSerial.h" 
SoftwareSerial serial_connection(10, 11); //RX=pin 10, TX=pin 11 
TinyGPSPlus gps;//This is the GPS object that will pretty much do all the grunt work with the NMEA data 
void setup() 
{ 
 Serial.begin(9600);//This opens up communications to the Serial monitor in the Arduino IDE 
 serial_connection.begin(9600);//This opens up communications to the GPS 
 Serial.println("GPS Start");//Just show to the monitor that the sketch has started 
} 
void loop() 
{ 
 while(serial_connection.available())//While there are characters to come from the GPS 
 { 
   gps.encode(serial_connection.read());//This feeds the serial NMEA data into the library one char at a time 
 } 
 if(gps.location.isUpdated())//This will pretty much be fired all the time anyway but will at least reduce it to only after a package of NMEA data comes in 
 { 
   //Get the latest info from the gps object which it derived from the data sent by the GPS unit 
   Serial.println("Satellite Count:"); 
   Serial.println(gps.satellites.value()); 
   Serial.println("Latitude:"); 
   Serial.println(gps.location.lat(), 6); 
   Serial.println("Longitude:"); 
   Serial.println(gps.location.lng(), 6); 
   Serial.println("Speed MPH:"); 
   Serial.println(gps.speed.mph()); 
   Serial.println("Altitude Feet:"); 
   Serial.println(gps.altitude.feet()); 
   Serial.println(""); 
 } 
} 
/* 
* $GPRMC,183729,A,3907.356,N,12102.482,W,000.0,360.0,080301,015.5,E*6F 
$GPRMB,A,,,,,,,,,,,,V*71 
$GPGGA,183730,3907.356,N,12102.482,W,1,05,1.6,646.4,M,-24.1,M,,*75 
$GPGSA,A,3,02,,,07,,09,24,26,,,,,1.6,1.6,1.0*3D 
$GPGSV,2,1,08,02,43,088,38,04,42,145,00,05,11,291,00,07,60,043,35*71 
$GPGSV,2,2,08,08,02,145,00,09,46,303,47,24,16,178,32,26,18,231,43*77 
$PGRME,22.0,M,52.9,M,51.0,M*14 
$GPGLL,3907.360,N,12102.481,W,183730,A*33 
$PGRMZ,2062,f,3*2D 
$PGRMM,WGS 84*06 
$GPBOD,,T,,M,,*47 
$GPRTE,1,1,c,0*07 
$GPRMC,183731,A,3907.482,N,12102.436,W,000.0,360.0,080301,015.5,E*67 
$GPRMB,A,,,,,,,,,,,,V*71 
*/  

PIR Motion Sensor

PIR motion detection sensor is a sensor that feel infra red emitted by any living body so it will detect the presence of anybody in the car if you are activating the secure mode the buzzer will make alarm give high voltage if it senses anybody and low if there is no body you can simulate this sensor by using button connected to same pins with a resistance

/* PIR sensor tester*/ 
int ledPin = 13; // choose the pin for the LED 
int inputPin = 2; // choose the input pin (for PIR sensor) 
int pirState = LOW; // we start, assuming no motion detected 
int val = 0; // variable for reading the pin status 
void setup() { 
pinMode(ledPin, OUTPUT); // declare LED as output 
pinMode(inputPin, INPUT); // declare sensor as input 
Serial.begin(9600); 
} 
void loop(){ 
val = digitalRead(inputPin); // read input value 
if (val == HIGH) { // check if the input is HIGH 
digitalWrite(ledPin, HIGH); // turn LED ON 
if (pirState == LOW) { 
// we have just turned on 
Serial.println("Motion detected!"); 
// We only want to print on the output change, not state 
pirState = HIGH; 
} 
} else { 
digitalWrite(ledPin, LOW); // turn LED OFF 
if (pirState == HIGH){ 
// we have just turned of 
Serial.println("Motion ended!"); 
// We only want to print on the output change, not state 
pirState = LOW; 
} 
} 
} 

Here are steps how to create artik device and connect it to cloud and make rule for it :

========================================

Wiring It all

Testing the 3 modes (Parking mode , Alarm mode , off mode) and ultrasonic sensor with GPS and Raspberry pi connected

here i am testing ultrasonic sensor and the buzzer that increase it's sound when my hand comes nearer (sorry there was a problem with the sound in the video i will update it ) you may also notice that a switch is used instead of PIR sensor to detect the theft mode i made it like this to be easier with less wiring on the breadboard just for demo but the concept is the same

Adding web app

follow this tutorial to create web app with dashboard to monitor the data

https://developer.artik.cloud/documentation/tutorials/your-first-application.html

here is the final website dashboard

Code

Full project arduino codeArduino
this code is the combination of all sensors that make device work in 3 modes
//==============================================
// led constants from pin 10 to 12 
//==============================================
const int ledPin1 = 10;     // parking mode 
const int ledPin2 = 11;     // find my car mode
const int ledPin3 = 12;     // theif alarm mode 

// variables will change:
int ledState1 = LOW;         // variable for reading the led 1 status
int ledState2 = LOW;         // variable for reading the led 2 status
int ledState3 = LOW;         // variable for reading the led 3 status

//==============================================
// pir sensor constants 
//============================================== 
int inputPin = 9 ; // choose the input pin (for PIR sensor) 
int pirState = LOW ; // we start, assuming no motion detected 
int pirval = 0; // variable for reading the pin status 

//==============================================
// police buzzer constants 
//============================================== 
const int freq = 500;
const int dur = 10;
const int buzzer = 3;

//==============================================
// GPS constants 
//============================================== 
#include "TinyGPS++.h" 
#include "SoftwareSerial.h" 
SoftwareSerial serial_connection(5, 4); //RX=pin 5, TX=pin 4 
TinyGPSPlus gps;//This is the GPS object that will pretty much do all the grunt work with the NMEA data 
long Latitude ,  Longitude ;

//==============================================
// Ultrasonic Sensor constants 
//============================================== 
#define echoPin 7 // Echo Pin  
#define trigPin 8 // Trigger Pin  
long duration, distance ; // Duration used to calculate distance 

//==============================================
// Declaring values to be printed 
//============================================== 
int mode = 0 ;
int gpsState = false ;

void setup() 
{
  
  // initialize the led pin as an input
  
  pinMode(ledPin1, INPUT);
  pinMode(ledPin2, INPUT);
  pinMode(ledPin3, INPUT);
  
  // declare sensor as input
  
  pinMode(inputPin, INPUT);  
  Serial.begin(9600); 

  // declare buzzer pin as output
  
  pinMode(buzzer, OUTPUT);

  // GPS declaration 
  serial_connection.begin(9600);//This opens up communications to the GPS
  Serial.println("GPS Start");//Just show to the monitor that the sketch has started 

  //Ultrasonic declaration
  pinMode(trigPin, OUTPUT);  
  pinMode(echoPin, INPUT);  

}

void loop() {
  // read the state of the pushbutton value:
    ledState1 = digitalRead(ledPin1);
    ledState2 = digitalRead(ledPin2);
    ledState3 = digitalRead(ledPin3);

  //read the GPS values
    while(serial_connection.available())//While there are characters to come from the GPS 
    { 
    gps.encode(serial_connection.read());//This feeds the serial NMEA data into the library one char at a time 
    } 
    if(gps.location.isUpdated())//This will pretty much be fired all the time anyway but will at least reduce it to only after a package of NMEA data comes in 
    { 
   //Get the latest info from the gps object which it derived from the data sent by the GPS unit 
    Latitude =  gps.location.lat() ;
    Longitude =  gps.location.lng();  
    }

  
  // check the mode that is chosen .

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // device off MODE 
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
   if (ledState1 == LOW && ledState2 == LOW && ledState3 == LOW) 
    {
     mode = 0 ;
     gpsState = true ;
    
 // print mode , pirState , gpsState , longtude , latitude
    Serial.print(String(mode)); //mode number
    Serial.print(",");
    Serial.print(String(pirState)); //print if there is somebody in the car or not 
    Serial.print(","); 
    Serial.print(String(gpsState));// gpsState
    Serial.print(",");
    Serial.print(String(Longitude));// Longitude
    Serial.print(",");
    Serial.println(String(Latitude));// Latitude
  }

  
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // PARKING MODE 
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // if led 1 is HIGH then parking mode is active .
  else if (ledState1 == HIGH && ledState2 == LOW && ledState3 == LOW) 
  {
   mode = 1 ;
   gpsState = false ;
   
   /* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */ 
 
 digitalWrite(trigPin, LOW); 
 delayMicroseconds(2); 
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);  
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 
 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 int no =2;
 if(distance < 7){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 15){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 20){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 25){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 30){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 35){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 40){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 45){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 50){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } else if (distance < 55){
   tone(buzzer, freq, dur);
   delay(distance*no);
 } 
 
Serial.print(String(distance)); //mode number
    
 //Delay 50ms before next reading.
 delay(500);

 // values to be printed on the cloud in mode 1
 // print mode , pirState , gpsState , Longitude , Latitude
    Serial.print(String(1)); //mode number
    Serial.print(",");
    Serial.print(String(0)); //print if there is somebody in the car or not 
    Serial.print(",");
    Serial.print(String(gpsState));// GPS State
    Serial.print(",");
    Serial.print(String(Longitude));// Longitude
    Serial.print(",");
    Serial.println(String(Latitude));// Latitude
     }   
    
  
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // FIND MY CAR MODE 
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // if led 2 is HIGH then gps tracking (find my car) mode is active .
  else if (ledState1 == LOW && ledState2 == HIGH && ledState3 == LOW) 
  {
    
   mode = 2 ;
   gpsState = true ;
   
    // turn on alarm  
   tone(buzzer, freq, 1500);
   delay(1000);
   tone(buzzer, freq, 500);
   delay(500);

 // values to be printed on the cloud in mode 1
 // print mode , pirState , gpsState , longitude , Latitude
    Serial.print(String(mode)); //mode number
    Serial.print(",");
    Serial.print(String(pirState)); //print if there is somebody in the car or not 
    Serial.print(","); 
    Serial.print(String(gpsState));// GPS State
    Serial.print(",");
    Serial.print(String(Longitude));// Longitude
    Serial.print(",");
    Serial.println(String(Latitude));// Latitude
      }

  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  // THIEF ALARM MODE 
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  
  // if led 3 is HIGH then alarm mode is active .
  else if (ledState1 == LOW && ledState2 == LOW && ledState3 == HIGH) 
  {
   mode = 3 ;
   gpsState = true ;
   
   //check the PIR sensor state to make alarm & report car location if anybody entered the car 
   pirval = digitalRead(inputPin); // read input value 
   if (pirval == HIGH ) { 
    
   // turn on alarm  
   tone(buzzer, freq, 1000);
   delay(100);
   tone(buzzer, freq, 500);
   delay(500);
 
    } 
     
    else { 
    } 


 // print mode , pirState , gpsState , longtude , Latitude
    Serial.print(String(3)); //mode number
    Serial.print(",");
    Serial.print(String(pirval)); //print if there is somebody in the car or not 
    Serial.print(","); 
    Serial.print(String(gpsState));// gpsState
    Serial.print(",");
    Serial.print(String(Longitude));// Longitude
    Serial.print(",");
    Serial.println(String(Latitude));// Latitude
  
  }

 
}
code connecting arduino with cloud through raspberry piJavaScript
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";

//defining your artik ids
var device_id = "1f873f665ef34206aa1d2e3de22d7149";
var device_token = "a93154f7257141a595c157c278f74903";

// require websocket that connect cloud to raspberyy pi
var WebSocket = require('ws');

//define the gpio library 
var gpio = require('rpi-gpio');

var isWebSocketReady = false;
var ws = null;

//using pins 11, 13 , 15 for output
var myPin1 = 11;// physical pin #
var myLEDState1 = 0;
var myPin2 = 13;// physical pin #
var myLEDState2 = 0;
var myPin3 = 15;// physical pin #
var myLEDState3 = 0;

// define variable to store data values
var pirState ="";

//define serial port that arduino will be connected to
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();
    });

    //define the 3 gpio pins as output 
    gpio.setup(myPin1, gpio.DIR_OUT, function(err) {
        if (err) throw err;
        myLEDState = false; // default to false after setting up
        console.log('Setting pin1 ' + myPin1 + ' to out succeeded! \n');
     });
     gpio.setup(myPin2, gpio.DIR_OUT, function(err) {
        if (err) throw err;
        myLEDState = false; // default to false after setting up
        console.log('Setting pin2 ' + myPin2 + ' to out succeeded! \n');
     });
      gpio.setup(myPin3, gpio.DIR_OUT, function(err) {
        if (err) throw err;
        myLEDState = false; // default to false after setting up
        //console.log('Setting pin3 ' + myPin3 + ' 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 actionName1 = actions[0].name; 

    console.log("The received action is " + actionName);
    
    //var newState;
    // activating mode zero
    if (actionName.toLowerCase() == "mode0") {
    gpio.write(myPin1, 0);
    gpio.write(myPin2, 0);
    gpio.write(myPin3, 0);
    }
    
    // activating parking mode
    else if (actionName.toLowerCase() == "mode1") {
    gpio.write(myPin1, 1);
    gpio.write(myPin2, 0);
    gpio.write(myPin3, 0);
    }

    // find my car mode 
    else if (actionName.toLowerCase() == "mode2") {
    gpio.write(myPin1, 0);
    gpio.write(myPin2, 1);
    gpio.write(myPin3, 0);
    }
    
    // alarm mode 
    else if (actionName.toLowerCase() == "mode3") {
    gpio.write(myPin1, 0);
    gpio.write(myPin2, 0);
    gpio.write(myPin3, 1);
    } 

    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();
//     });

// }


//data displayed on the artik charts

/**
 * Send one message to ARTIK Cloud containning all data 
 */
function sendData(currentmode  , gpsstate , latitude , longitude , pirsensor ){
    try{
        ts = ', "ts": '+getTimeMillis();
        var data = {
			"currentmode": currentmode ,
            "gpsstate": gpsstate ,
            "latitude":latitude , 
            "longitude": longitude ,
			"pirsensor": pirsensor 
            
            };
            
       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();


// data recieved from arduino serial port 
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 mode = parseInt(parsedStrs[0]);// 1 or 0 
			 var gpsvalue = parseInt(parsedStrs[1]);// sun or dark reading
			 var pirvalue = parseInt(parsedStrs[2]);// weak , good , outofserviec
			 var longitudevalue = parseInt(parsedStrs[3]);// person in street , nobodyin street
             var latitudevalue = parseInt(parsedStrs[4]);// person in street , nobodyin street

			 var mode = 0 ; // intial value
			 var gpsstate = true ;
             var pirsensor = "" ;
             var  latitude = 0 ; 
             var longitude = 0 ;
				 
            // send the mode number to the cloud
            currentmode = mode

            // write true or false depend on gps state
            if (gpsvalue==0){
                gpsstate=false;
                };
            
            // pir sensor here
            if (pirvalue==0){
                pirsensor = "nobody is detected "
                }
             else if (pirvalue == 1){
					pirsensor = "theif detected"};
					
			//gps readings to double
			 latitude = latitudevalue ;
			 longitude = longitudevalue ;
            


			 sendData(currentmode , gpsstate , latitude , longitude  , pirsensor );
		});
});
process.on('SIGINT', exitClosePins);

Schematics

full schematic image

No document.

full circuit schematic fritzing
Smart%20Car.fzz

Comments

Add projectSign up / Login