0% found this document useful (0 votes)
134 views23 pages

From App

This 3 sentence summary provides the high level information about the document: The document contains code snippets for an embedded C program used on a PIC microcontroller to measure temperature and RPM from an ADC and display it on an LCD, as well as Python code running on a Raspberry Pi to communicate with the PIC microcontroller and GPS module to log sensor and location data to a text file and trigger SMS or email alerts if certain conditions are met based on the sensor readings and GPIO inputs. The Python code includes functions for GPS data parsing, serial communication with the PIC, reading sensors and GPIO states, sending alerts via SMS and email, and uploading data to a server.

Uploaded by

justforbook
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
134 views23 pages

From App

This 3 sentence summary provides the high level information about the document: The document contains code snippets for an embedded C program used on a PIC microcontroller to measure temperature and RPM from an ADC and display it on an LCD, as well as Python code running on a Raspberry Pi to communicate with the PIC microcontroller and GPS module to log sensor and location data to a text file and trigger SMS or email alerts if certain conditions are met based on the sensor readings and GPIO inputs. The Python code includes functions for GPS data parsing, serial communication with the PIC, reading sensors and GPIO states, sending alerts via SMS and email, and uploading data to a server.

Uploaded by

justforbook
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

APPENDIX A

EMBEDDED C PROGRAM CODE FOR PIC

#include<pic.h>
#include<ADC.h>
#include<stdlib.h>
#include<lcd.h>
#include<uart.h>
#define _XTAL_FREQ 16000000
__CONFIG(0X3F7A);

void main()
{
char c[5],c1[5];
int temp,n;
T0SE=1;
uart_init(9600);
lcd_init();
lcd_clear();
adc_init();
while(1)
{
lcd_goto(1,1);
lcd_puts("Temp= ");
lcd_goto(2,1);
lcd_puts("Speed= ");
lcd_goto(2,8);
itoa(c1,n,10);
lcd_puts(c1);
lcd_goto(2,12);
lcd_puts("RPM");
temp=(adc_read(0)/2)-1;
lcd_goto(1,7);
itoa(c,temp,10);
lcd_puts(c);
uart_write('#');
uart_puts(c);
uart_write('$');
uart_puts(c1);
TMR0=0X00;
__delay_ms(2000);
n=TMR0;
n=n*30;
lcd_clear(); } }
APPENDIX B

PYTHON PROGRAM CODE FOR RASPBERRY PI3

import RPi.GPIO as GPIO #Enables internal pull_up/pull_down


import time
import serial
import thread
import urllib2
import os

#---------- B.2 -------------------------------------#


from twilio import TwilioRestException
from twilio.rest import TwilioRestClient
#---------- B.2 -------------------------------------#

#---------- B.4 ---------------------------------------------------#


import email
import email.utils
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
#---------- B.4 ---------------------------------------------------#

#---------- B.1 -------------------------------------------------------------------------#


GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(38,1,pull_up_down=GPIO.PUD_UP) #For alcohol
GPIO.setup(36,1,pull_up_down=GPIO.PUD_UP) #for interfacing water sensor

GPIO.setup(31,1,pull_up_down=GPIO.PUD_UP) #Horn
GPIO.setup(33,1,pull_up_down=GPIO.PUD_UP) #Brake
GPIO.setup(35,1,pull_up_down=GPIO.PUD_UP)#right indicator
GPIO.setup(37,1,pull_up_down=GPIO.PUD_UP)#left indicator
GPIO.setup(32,1,pull_up_down=GPIO.PUD_UP)#piezo sensor

GPIO.setup(8,0) #right indicator output


GPIO.setup(10,0) # left indicator output
GPIO.setup(40,0) # buzzer output
#---------- B.1 -------------------------------------------------------------------------#
picser=serial.Serial('/dev/ttyUSB1',baudrate=9600,timeout=1) #object for serial communication
with Pic

#---------- B.6 -------------------------------------------------------------------------------------------------#


gpsser=serial.Serial('/dev/ttyUSB0',baudrate=9600,timeout=1) # object for serial communication
with GPS TXR
#---------- B.6 -------------------------------------------------------------------------------------------------#

#--------------------------------- B.16 -------------------------------------------------------------------------#


data='#0$0' # variables initialized
lat='0'
lon='0'
temp='0'
rpm='0'
tim='0'
RI='0'
LI='0'
al='0'
b='0'
h='0'
m='0'
TS='0'
ST='0'

file=open("/home/pi/Desktop/bb.txt","w") # txt file created to write the datas inside SD card


of raspberry
#--------------------------------- B.16 -------------------------------------------------------------------------#

#--------------------------------- B.11 -------------------------------------------------------------------------#


def txn(idn,val): # upload to server - Function for transmission( server id, updated value)
try:
request = urllib2.Request("http://nodeiot.online/site/up.php?id=%d&value=%s"%(idn,val),
headers={"Accept" : "text/html","User-Agent": "Mozilla/5.0 (Windows NT 10.0;
WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": "http://thewebsite.com",
"Connection": "keep-alive"})
contents = urllib2.urlopen(request).read()
except:
print 'Sending Failed'
#--------------------------------- B.11 -------------------------------------------------------------------------#

#---------------- B.5 -------------------------------------------------------------------------------------------#


def mail(to,sub):# function for mailing -mail( TO mail-id, subject)
try: # try and except method adopted for mailing , even net connection not there also no error
will come
fromaddr = "[email protected]"
toaddr = to

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = sub

body = "HELP\n"+'Latitude='+lat+', Longitude='+lon+'\nDate & Time='+tim

msg.attach(MIMEText(body, 'plain'))

filename = "Image"
attachment = open("/home/pi/Desktop/image.jpg", "rb")

part = MIMEBase('application', 'octet-stream')


part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)


server.starttls()
server.login(fromaddr, "goodjobdone123")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
print 'Mail Sent'
except:
print 'Mailing Failed'

#-------------- B.5 -----------------------------------------------------------------------------------------#

#---------- B.3 -------------------------------------------------------------------------#


def mob(msg):
account_sid = "ACb31e6a98d56b4b98a6cf0264a7802ae7" #Your Account SID from
www.twilio.com/console
auth_token = "43a2acfde3aa44c42853962b34643cf8" #Your Auth Token from
www.twilio.com/console
client = TwilioRestClient(account_sid, auth_token)
try:
message = client.messages.create(body=msg,
to="+919947099911", #Replace with your phone number
from_="+18329814729") #Replace with your Twilio number
print 'sent'
except:
print 'msg failed'

#---------- B.3 -------------------------------------------------------------------------#

#---------------------------------- B.7 -------------------------------------------------------------------------#


def gps(threadName, delay):
global lat
global lon
while(1):
msg=gpsser.readline() #To receive datas
if 'GPRMC' in msg: # Lat and long datas will be after "GPRMC" in the collected data
from GPS
lat=str(msg[20:28]) # string position from 22 to 28 will be latitude
lon=str(msg[32:41]) # longitude
#print 'lat='+lat, #print 'lon='+lon

time.sleep(delay)
#--------------------------------- B.7 -------------------------------------------------------------------------#

#--------------------------------- B.10 -------------------------------------------------------------------------#


def pic(threadName, delay):
global data
global rpm
global temp
while(1):
try:
data=picser.readline()

data=str(data)

l=len(data)

temp=str(data[data.index('#')+1:data.index('$')]) # Data format send from pic is


'hashxx$xxx'

rpm=data[data.index('$')+1:l]

print 'rpm='+rpm
print 'temp='+temp

except:
print 'Waiting'

time.sleep(delay)
#--------------------------------- B.10 -------------------------------------------------------------------------#

#--------------------------------- B.14 -------------------------------------------------------------------------#


def status(threadName, delay):
global tim
global RI
global LI
global al
global h
global b
global m
global TS
global ST
while(1):
tim=str(time.ctime()) #system date and time
if(GPIO.input(35)==0):
GPIO.output(8,1)
print 'Right Indicator ON'
RI='\nRight Indicator ON'
RIS='RION,'
else:
GPIO.output(8,0)
RI=''
RIS='RIOFF,'

if(GPIO.input(37)==0):
GPIO.output(10,1)
print 'Left Indicator ON'
LI='\nLeft Indicator ON'
LIS='LION,'
else:
GPIO.output(10,0)
LI=''
LIS='LIOFF,'

if(GPIO.input(38)==0):
print 'Alcohol Detected'
al='\nAlcohol Detected'
als='AD'
else:
als='AnD'
al=''

if(GPIO.input(31)==0):
print 'Horn Pressed'
h='\nHorn Pressed'
HS='HP,'
GPIO.output(40,1)
else:
GPIO.output(40,0)
h=''
HS='HnP,'
if(GPIO.input(33)==0):
print 'Brake Pressed'
b='\nBrake Pressed'
BS='BP,'
else:
b=''
BS='BnP,'
#--------------------------------- B.14 -------------------------------------------------------------------------#

#--------------------------------- B.15 -------------------------------------------------------------------------#


file=open("/home/pi/Desktop/bb.txt","w")
file.write(" ") # write with blank data
file.close()
m= '\n HERE IS THE BLACKBOX DATA SAVED DURING ACCIDENT
\n'+tim+'\nLatitude='+lat+'\nLongitude='+lon+h+b+RI+LI+al+'\nSpeed='+rpm+'\nTem
perature='+temp

file=open("/home/pi/Desktop/bb.txt","w")
file.write(m)
file.close()
TS=tim[0:3]+tim[4:7]+tim[11:19]+',2017,' #collected date and time
ST=RIS+LIS+HS+BS+als+',Temp='+temp+',RPM='+rpm #data collected as status of
vehicle
#--------------------------------- B.15 -------------------------------------------------------------------------#

#--------------------------------- B.9 -------------------------------------------------------------------------#


if(GPIO.input(36)==0):
print 'accident(Plunged into water)'
acc='Accident\n'+'Plunged into water\n'+'Latitude='+lat+'\nLongitude='+lon
mob(acc) #calling function mob(msg) for sending message to mobile
os.system("sudo fswebcam -r 320x240 /home/pi/Desktop/image.jpg") #calling command
prompt and executing command to capture the image thru usb cam
mail("[email protected]","Accident Detected") #calling function mail( To mail
id, Subject-line)
time.sleep(delay)
#--------------------------------- B.9 -------------------------------------------------------------------------#

def upload(threadName, delay): #continuous upload to server

while(1):
yy=TS+ST
txn(5622692,yy)

time.sleep(delay)

#--------------------------------- B.8 -------------------------------------------------------------------------#


def accident(channel):
if(GPIO.input(32)==0):
print 'accident'
os.system("sudo fswebcam -r 320x240 /home/pi/Desktop/image.jpg")
acc='Accident\n'+'Latitude='+lat+'\nLongitude='+lon
mob(acc)
mail("[email protected]","Accident Detected")
GPIO.output(40,0)
time.sleep(1)
#--------------------------------- B.8 -------------------------------------------------------------------------#

#--------------------------------- B.13 -------------------------------------------------------------------------#


GPIO.add_event_detect(32,GPIO.FALLING,callback=accident,bouncetime=300) # interrupt for
sensing piezo, will call funcion accident
#--------------------------------- B.13 -------------------------------------------------------------------------#

mob('BLACK BOX is ON')

#--------------------------------- B.12 -------------------------------------------------------------------------#


try:
thread.start_new_thread(gps, ("Thread-1", 1, ) )
thread.start_new_thread(upload, ("Thread-1", 1, ) )
thread.start_new_thread(pic, ("Thread-1", 1, ) )
thread.start_new_thread(status, ("Thread-1", .5, ) )

except:
print "Error: unable to start thread"
while 1:
pass
#--------------------------------- B.12 -------------------------------------------------------------------------#
APPENDIX C

PIN DIAGRAM OF 16F877A MICROCONTROLLER

Fig. C.1 PIC 16F77A pin details


Pin Out Description:

Table C.1 Pin out Description


Pin Out Description (Continued...):

Table C.2 Pin out Description


APPENDIX D

REGISTERS OF PIC16F877A UTILIZED FOR THE SYSTEM

D.1 REGISTERS ASSOCIATED WITH TIMER0/COUNTER0

INTCON REGISTER
OPTION_REG REGISTER
D.2 REGISTERS/BITS ASSOCIATED WITH A/D

The conversion of an analog input signal results in a corresponding 10-bit digital number.

The A/D module has high and low-voltage reference input that is software selectable to some

combination of VDD, VSS, RA2 or RA3. It has a unique feature of being able to operate while
the device is in Sleep mode. To operate in Sleep, the A/D clock must be derived from the A/Ds

internal RC oscillator. The A/D module has four registers. These registers are:

A/D Result High Register (ADRESH)

A/D Result Low Register (ADRESL)

A/D Control Register 0 (ADCON0)

A/D Control Register 1 (ADCON1)

A/D RESULT REGISTERS

The ADRESH:ADRESL register pair is the location where the 10-bit A/D result is loaded

at the completion of the A/D conversion. This register pair is 16 bits wide. The A/D module gives

the flexibility to left or right justify the 10-bit result in the 16-bit result register. The A/D Format

Select bit (ADFM) controls this justification. Figure below shows the operation of the A/D result

justification. The extra bits are loaded with 0s. When an A/D result will not overwrite these

locations (A/D disable), these registers may be used as two general purpose 8-bit registers. The

A/D module can operate during Sleep mode. This requires that the A/D clock source be set to RC

(ADCS1:ADCS0 = 11). When the RC clock source is selected, the A/D module waits one

instruction cycle before starting the conversion. This allows the SLEEP instruction to be

executed which eliminates all digital switching noise from the conversion. When the conversion

is completed, the GO/DONE bit will be cleared and the result loaded into the ADRES register. If

the A/D interrupt is enabled, the device will wake-up from Sleep. If the A/D interrupt is not

enabled, the A/D module will then be turned off, although the ADON bit will remain set.
ADCON0 REGISTER (ADDRESS 1Fh)

The ADCON0 register controls the operation of the A/D module. The ADCON1 register

configures the functions of the port pins. The port pins can be configured as analog inputs (RA3

can also be the voltage reference) or as digital I/O.


D3. REGISTERS ASSOCIATED WITH USART ASYNCHRONOUS MODE

The PIE1 register contains the individual enable bits for the peripheral interrupts and can
be programmed on bit level
The PIR1 register contains the individual flag bits for the peripheral interrupts.
RCSTA: RECEIVE STATUS AND CONTROL REGISTER (ADDRESS 18h)
TXSTA: TRANSMIT STATUS AND CONTROL REGISTER (ADDRESS 98h)

You might also like