usain usain
Published © CC BY-NC

Smart Car

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

AdvancedWork in progress6 hours8,152
Smart Car

Things used in this project

Hardware components

Arduino Nano R3
Arduino Nano R3
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×2
Buzzer
Buzzer
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1
Car Mobile Charger
×1
gps
×1
Raspberry Pi 3 Model B
Raspberry Pi 3 Model B
×1
LED (generic)
LED (generic)
×3
Resistor 221 ohm
Resistor 221 ohm
×3

Software apps and online services

Arduino IDE
Arduino IDE
ARTIK Cloud for IoT
Samsung ARTIK Cloud for IoT
Google Maps
Google Maps

Story

Read more

Schematics

full schematic image

File missing, please reupload.

full circuit schematic fritzing

Code

Full project arduino code

Arduino
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 pi

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

Credits

usain usain

usain usain

2 projects • 4 followers

Comments