Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
lucio
Published © GPL3+

Smart Traffic Signal Light

Real traffic signal light managed with Raspberry Pi.

IntermediateProtip5,741
Smart Traffic Signal Light

Things used in this project

Hardware components

Raspberry Pi 4 Model B
Raspberry Pi 4 Model B
×1
Traffic Signal Light
×1
wire 1.5mm 10A (power cord)
×1
Heatsink Case with Dual Fan
×1

Story

Read more

Schematics

Wiring Schematic Diagram

Code

servidor.py

Python
This is the file to start the webserver in Raspberry Pi. This script generates a 'cookie.txt' file for auto running (i.e., continuous red, yellow and green sequence). When the user select another option, the 'cookie.txt' file is removed, and the auto running is stoped.
#!/bin/python
#SemaforoTel: server
#Author: Lucio A. Rocha
#Last update: 25/02/2022-17:24

import web
import RPi.GPIO as GPIO
from time import sleep
from datetime import datetime
import sys
from os.path import exists
from os import remove

mySleep = 10

R1 = 19
R2 = 26
R3 = 20
R4 = 21

#Enable auto
cookie = "/home/pi/cookie.txt"

#Initialize the ports
t = ( R1, R2, R3 )
c = ( 'VERMELHO', 'AMARELO', 'VERDE' )

GPIO.setmode(GPIO.BCM)

for i in t:
	GPIO.setup(i, GPIO.OUT)
	GPIO.output(i,True) #disable port

render = web.template.render('/home/pi/templates/')
urls = (
	'/','index',
	'/update','update',
	'/auto','auto'
)

class index:
	def GET(self):
		GPIO.output(R1, True) 		
		GPIO.output(R2, True) 		
		GPIO.output(R3, True) 		
		
		if exists(cookie):
			remove(cookie)

		return render.index('')
class update:
	def GET(self):
		campo = int(web.input(led=0).led)
		if campo==1:
			GPIO.output(R1, False) #enable
			GPIO.output(R2, True) 
			GPIO.output(R3, True) 
		elif campo==2:
			GPIO.output(R1, True) 		
			GPIO.output(R2, False) #enable
			GPIO.output(R3, True)
		elif campo==3:
			GPIO.output(R1, True) 		
			GPIO.output(R2, True) 
			GPIO.output(R3, False) #enable
		else:
			GPIO.output(R1, True) 		
			GPIO.output(R2, True) 
			GPIO.output(R3, True) 

		if exists(cookie):
			remove(cookie)	
		return render.index(campo)

class auto:
	def GET(self):
		try:
			f = open(cookie,"w")
			f.close()

			while exists(cookie):
				j=0
				for k in t:

					#disable all
					for i in t:
						GPIO.output(i, True) #disable
					
					GPIO.output(k, False) #enable port
					print('[',str(datetime.now()),'] -> ',c[j],sep='')
					sleep(mySleep)
					GPIO.output(k, True) #disable port
					sleep(1)
					j=j+1
					if j>2: j=0
		except Exception as e:
			print('Error:',str(e))

if __name__ == "__main__":
	app = web.application(urls, globals())
	app.run()

semaforo_auto.py

Python
This is the script that runs continuously the sequence red, yellow and green of the traffic signal light.
#!/bin/python
#SemaforoTel
#Author: Lucio A. Rocha
#Last update: 25/02/2022-12:02

import RPi.GPIO as GPIO
import sys
from time import sleep
from datetime import datetime

GPIO.setmode(GPIO.BCM)

#args = sys.argv
#mySleep = int(args[1]) #Receive mySleep as argument
mySleep = 10

R1 = 19
R2 = 26
R3 = 20
R4 = 21

#Initialize the ports
t = ( R1, R2, R3 )
c = ( 'VERMELHO', 'AMARELO', 'VERDE' )
for i in t:
   GPIO.setup(i, GPIO.OUT)
   GPIO.output(i,True) #disable port

try:
   while True:
      j=0
      for i in t:
        GPIO.output(i, False) #enable port
        print('[',str(datetime.now()),'] -> ',c[j],sep='')
        sleep(mySleep)
        GPIO.output(i, True) #disable port
        sleep(1)
        j=j+1
        if j>2: j=0
finally:
   GPIO.cleanup()

fim.py

Python
This files cleanup the environment. This file must be run to cleanup previous running.
#!/bin/python
# SemaforoTel
# Description: Stop semaforo running
# Author: Lucio A. Rocha
# Last update: 25/02/2022 - 13:16

import os, subprocess

#r = subprocess.run(['ps', 'aux'], stdout=subprocess.PIPE)
#print(r.stdout,'.')

# Try to kill 'semaforo_auto.py'
pid = subprocess.check_output('ps aux | grep semaforo_auto | head -n 1 | awk \'{print $2}\'', shell=True, text=True)
print('+SemaforoTel PID:',pid)

try:
	cmd = 'kill -9 ' + pid
	s = subprocess.check_output(cmd, shell=True, text=True)
	print(s)
except:
	print('No semaforo_auto.py active.')


# Try to kill 'servidor.py'
pid = subprocess.check_output('ps aux | grep servidor.py | head -n 1 | awk \'{print $2}\'', shell=True, text=True)
print('+Servidor PID:',pid)

try:
	cmd = 'kill -9 ' + pid
	s = subprocess.check_output(cmd, shell=True, text=True)
	print(s)
except:
	print('No servidor.py active.')

#Clean GPIO
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

R1 = 19
R2 = 26
R3 = 20
R4 = 21

#Initialize the ports
t = ( R1, R2, R3 )

for i in t:
   GPIO.setup(i, GPIO.OUT)
   GPIO.output(i,True) #disable port

GPIO.cleanup()

index.html

Python
This is the front-end page to interact with the user through a browser. The user can manage the traffic signal light in a web browser. This file must be placed in the "templates" folder of web.py directory.
$def with (campo)
<p align="center"><img src="static/logotipo.png" width="250px" height="150px"></p>
<pre align="center">Projeto SEMAFOROTEL</pre>

$if campo:
   <p align="center"><em>Active LED:</em> $campo</p>
$else:
   <p align="center"><em>Hello</em> SemaforoTel.</p>

<form align="center" action="http://localhost:8080/update">
	<input 	type="hidden"
		name="led"
		value="1">
	<input type="submit" value="VERMELHO" style="background-color:red;color:black;width:150px;height:40px;"/>
</form>

<form align="center" action="http://localhost:8080/update">
	<input 	type="hidden"
		name="led"
		value="2">
	<input type="submit" value="AMARELO" style="background-color:yellow;color:black;width:150px;height:40px;"/>
</form>

<form align="center" action="http://localhost:8080/update">
	<input 	type="hidden"
		name="led"
		value="3">
	<input type="submit" value="VERDE" style="background-color:green;color:black;width:150px;height:40px;"/>
</form>

<form align="center" action="http://localhost:8080/update">
	<input 	type="hidden"
		name="led"
		value="0">
	<input type="submit" value="APAGAR" style="background-color:white;color:black;width:150px;height:40px;"/>
</form>

<form align="center" action="http://localhost:8080/auto">
	<input 	type="hidden"
		name="led"
		value="0">
	<input type="submit" value="AUTOMTICO" style="background-color:aqua;color:black;width:150px;height:40px;"/>
</form>

<pre align="center"></pre>

Credits

lucio

lucio

0 projects • 0 followers

Comments