import machine, os, utime
from machine import SPI, Pin, I2C, ADC
from time import sleep
import ssd1306
#import sh1107
import dht
import math
#---------------------------------------
#### PINOS ESP32 ########################
#---------------------------------------
pin_button =13
pin_button_b =25
#motion sensor corredor
pin_ms_hall = 32
pin_led_red = 33
pin_led_yellow = 12
#motion sensor room
pin_ms_room_1 = 4
pin_ms_room_2 = 2
#Sensor de temperatura NTC
pin_sensorNTCHall= 35
pin_sensorNTCOut= 27
#OLED
pin_scl=22
pin_sda=21
#Sensor de temp & hum
pin_sensorDHT=15
#sensor de luz ldr
pin_ldrIn=14
pin_ldrHall= 34
pin_ldrOut=26
#Cartão microSD
pin_sd_cs = 5 #tem de ser o GPIO05->D5
pin_sd_di = 23 #tem de ser o D23
pin_sd_do = 19 #tem de ser o D19
pin_sd_sck = 18 #tem de ser o D18
#------------------------------------------------------
#### HALL BUTTON AND MOTION SENSOR #####################
#------------------------------------------------------
button = machine.Pin(pin_button, machine.Pin.IN, machine.Pin.PULL_UP)
ms_hall = Pin(pin_ms_hall, Pin.IN)
led_red = Pin(pin_led_red, Pin.OUT)
led_yellow = Pin(pin_led_yellow, Pin.OUT)
button_falling = 0
ms_hall_rising = False
button_state = 1
ms_hall_state = False
button_before = 1
ms_hall_before = False
hall_door = 0
hall_counter = 0
#-------------------------------------------------------
#### ROOM MOTION SENSORS ###############################
#-------------------------------------------------------
ms_room_1 = Pin(pin_ms_room_1, Pin.IN)
ms_room_2 = Pin(pin_ms_room_2, Pin.IN)
ms_room_1_rising = False
ms_room_2_rising = False
ms_room_1_state = False
ms_room_2_state = False
ms_room_1_before = False
ms_room_2_before = False
room_door = 0
room_counter = 0
#---------------------------------------------------
#### SENSOR TEMP NTC ###############################
#---------------------------------------------------
sensorNTCHall = ADC(Pin(pin_sensorNTCHall))
sensorNTCOut = ADC(Pin(pin_sensorNTCOut))
janelaHall = 0
AChall = 0
#------------------------------------------------
#### OLED #######################################
#------------------------------------------------
i2c = I2C(0, scl=Pin(pin_scl), sda=Pin(pin_sda))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
#oled = sh1107.SH1107_I2C(oled_width, oled_height, i2c, addr=0x3c)
oled.fill(0)
oled.text('starting...', 0, 0)
oled.show()
def functionDisplay(celsiusSala,celsiusOut,hum,room_counter,hall_counter,luxIn,luxOut):
oled.fill(0) #limpa o OLED
#mostra temp e humidade no oled
show_string='"Estado da sala"'
oled.text(show_string, 1, 0)
show_string= 'Ti:'+ str(celsiusSala)+'C '
oled.text(show_string, 0, 20)
show_string= 'To:'+ str(celsiusOut)+'C '
oled.text(show_string, 71, 20)
show_string= 'humidity: '+ str(hum)+'% '
oled.text(show_string, 0, 30)
if((celsiusSala<=25 and celsiusSala>=19) and (hum <=60 and hum>=45)):
show_string='---Agradavel---'
led_yellow.off()
led_red.off()
oled.text(show_string, 5, 10)
show_string='Luz sala: '+str(luxIn)+"lux"
oled.text(show_string, 0, 40)
show_string='Luz out: '+str(luxOut)+"lux"
oled.text(show_string, 0, 50)
elif (celsiusSala>=50 or celsiusSala<=6) or (hum <=5 or hum>=90):
show_string='---Perigoso---'
led_red.on()
led_yellow.off()
oled.text(show_string, 5, 10)
show_string='Pessoas sala: '+str(room_counter)
oled.text(show_string, 0, 40)
show_string='Pessoas Ed: '+str(hall_counter)
oled.text(show_string, 0, 50)
else:
show_string='-incomodativo-'
led_yellow.on()
led_red.off()
oled.text(show_string, 0, 10)
if(luzSala==1):
show_string='Luzes Ligadas'
oled.text(show_string, 0, 40)
else:
show_string='Luzes Apagadas'
oled.text(show_string, 0, 40)
if(janelaSala==0):
show_string='Janela fechada'
oled.text(show_string, 0, 50)
else:
show_string='Janela aberta'
oled.text(show_string, 0, 50)
oled.show()
#------------------------------------------------------------
#### SENSOR DE TEMP & HUMIDADE ###############################
#-------------------------------------------------------------
sensorDHT = dht.DHT22(Pin(pin_sensorDHT))
#sensorDHT = dht.DHT11(Pin(pin_sensorDHT))
hum_anterior = 0
hum = 0
janelaSala = 0
ACsala = 0
#-------------------------------------------------------
#### SENSOR DE LUZ LDR ###############################
#-------------------------------------------------------
ldrIn= ADC(Pin(pin_ldrIn))
ldrOut= ADC(Pin(pin_ldrOut))
ldrHall= ADC(Pin(pin_ldrHall))
cortinaSala = 0
luzSala = 0
cortinaHall = 0
luzHall = 0
#ldr.atten(ADC.ATTN_11BD)
#-------------------------------------------------------
#### Cartão MicroSD ###############################
#-------------------------------------------------------
# Iniciar a comunicação com o cartão SD
button_b = machine.Pin(pin_button_b, machine.Pin.IN, machine.Pin.PULL_UP)
button_before_b = 1
button_state_b = 1
sd = machine.SDCard(slot=2)
os.mount(sd, '/sd') # mount
"""sd = machine.SDCard(slot=2)
vfs=os.VfsFat(sd)
os.mount(vfs, "/sd") # mount
fn = open('/sd/Dados.txt', 'w')
fn.write('Dados Armazenados: \n')
fn.close()"""
#função para retornar a data atual
def data_atual():
timestamp = utime.time()
data_atual = utime.localtime(timestamp)
data_string = "{:02d}/{:02d}/{:04d} {:02d}h:{:02d}m:{:02d}s\n".format(data_atual[2], data_atual[1], data_atual[0], data_atual[3], data_atual[4], data_atual[5])
return data_string
def store_dados(string):
#os.mount(sd, '/sd') # mount
# open the file in "append mode" for appending a line
file = open("/sd/Dados.txt","a")
string=string+" "+data_atual()
file.write(string)
file.close()
#sd.deinit() # unmount
def show_dados():
#os.mount(sd, '/sd') # mount
# Open the file in "read mode".
# Read the file and print the text on debug port.
file = open("/sd/Dados.txt", "r")
if file != 0:
print("Reading from SD card")
read_data = file.read()
print (read_data)
file.close()
#sd.deinit() # unmount
print('«Energy efficiency monitoring system»')
while True:
try:
##############################################################
#### HALL BUTTON AND MOTION SENSOR & Led blue ################
##############################################################
#read button and motion sensor
button_state = button.value()
ms_hall_state = ms_hall.value()
#detect falling edge of button and rising of sensor
if (button_state==0) and (button_before==1):
button_falling = 1
elif (ms_hall_state) and not(ms_hall_before):
ms_hall_rising = True
#detect person entering or exiting
if (button_falling==1) and (hall_door==0): #start entering
hall_door = 1
print("Entering: Hall door opening")
elif (ms_hall_rising) and (hall_door==1): #end entering
hall_door = 0
hall_counter += 1
print("Entering: Hall door closing")
print("Pessoas no Edificio: ", hall_counter)
elif (ms_hall_rising) and (hall_door==0): #start exiting
hall_door = 1
print("Exiting: Hall door opening")
elif (button_falling==1) and (hall_door==1): #end exiting
hall_door = 0
print("Exiting: Hall door closing")
if (hall_counter>=1):
hall_counter -= 1
print("Pessoas no Edificio: ", hall_counter)
#variables refresh
button_before = button_state
ms_hall_before = ms_hall_state
button_falling = 0
ms_hall_rising = False
########################################################
#### ROOM MOTION SENSORS & LED Red #####################
########################################################
#read motion sensors
ms_room_1_state = ms_room_1.value();
ms_room_2_state = ms_room_2.value();
#detect rising edge of motion sensors
if (ms_room_1_state) and not(ms_room_1_before):
ms_room_1_rising = True
elif (ms_room_2_state) and not(ms_room_2_before):
ms_room_2_rising = True
#detect person entering or exiting
if (ms_room_1_rising) and (room_door==0): #start entering
room_door = 1
print("Entering: Room door opening")
elif (ms_room_2_rising) and (room_door==1): #end entering
room_door = 0
room_counter+= 1
print("Entering: Room door closing")
print("Pessoas na sala: ", room_counter)
elif (ms_room_2_rising) and (room_door==0): #start exiting
room_door = 1
print("Exiting: Room door opening")
elif (ms_room_1_rising) and (room_door==1): #end exiting
room_door = 0
print("Exiting: Room door closing")
if (room_counter >= 1):
room_counter -= 1
print("Pessoas na sala: ", room_counter)
#variables refresh
ms_room_1_before = ms_room_1_state
ms_room_2_before = ms_room_2_state
ms_room_1_rising = False
ms_room_2_rising = False
########################################################
#### SENSOR TEMP NTC ###################################
########################################################
#Sensor read
analogValue = sensorNTCHall.read()
celsiusHall = 1 / (math.log(1 / (4095. / analogValue - 1)) / 3950 + 1.0 / 298.15) - 273.15
#print('temperature corredor:', round(celsiusHall,1),'ºC')
analogValue1 = sensorNTCOut.read()
celsiusOut = 1 / (math.log(1 / (4095. / analogValue1 - 1)) / 3950 + 1.0 / 298.15) - 273.15
#print('temperature exterior :', round(celsiusOut,1),'ºC')
if(janelaHall == 0) and (AChall == 0):
if (celsiusOut >= 25 and celsiusHall >= 27):
print("AC corredor Arrefece");
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature corredor:', round(celsiusHall,1),'ºC');
AChall = -1;
elif (celsiusHall <= 15):
print('AC corredor Aquece');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature corredor:', round(celsiusHall,1),'ºC');
AChall = 1;
elif (celsiusOut <= 20 and celsiusHall >= 25):
print('Abrir Janela corredor');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature corredor:', round(celsiusHall,1),'ºC');
janelaHall = 1;
elif(celsiusHall <= 20 and celsiusOut >= 25):
print('Abrir Janela corredor');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature corredor:', round(celsiusHall,1),'ºC');
janelaHall = 2;
elif(janelaHall == 1):
if(celsiusHall <= celsiusOut):
print('Fechar Janela corredor');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature corredor:', round(celsiusHall,1),'ºC');
janelaHall = 0;
elif(janelaHall == 2):
if(celsiusHall >= celsiusOut ):
print('Fechar Janela corredor');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature corredor:', round(celsiusHall,1),'ºC');
janelaHall = 0;
else:
if((celsiusHall >= 19 and AChall == 1) or (celsiusHall <= 24 and AChall == -1)):
print('AC corredor Desliga');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature corredor:', round(celsiusHall,1),'ºC');
AChall = 0;
########################################################
#### SENSOR LDR ###################################
########################################################
#Sensor LDR IN sala
#Convert the analog value into lux value:
analogValue = ldrIn.read();
voltage = analogValue / 4096. * 5;
resistance = 2000 * voltage / (1 - voltage / 5);
luxIn = int(pow(50 * 1e3 * pow(10, 0.7) / resistance, (1 / 0.7)));
#Sensor LDR HALL
analogValue = ldrHall.read();
voltage = analogValue / 4096. * 5;
resistance = 2000 * voltage / (1 - voltage / 5);
luxHall = int(pow(50 * 1e3 * pow(10, 0.7) / resistance, (1 / 0.7)));
#Sensor LDR Out
analogValue = ldrOut.read();
voltage = analogValue / 4096. * 5;
resistance = 2000 * voltage / (1 - voltage / 5);
luxOut = int(pow(50 * 1e3 * pow(10, 0.7) / resistance, (1 / 0.7)));
#cortina & Luz corredor
if (luxHall >= 500):
if (luxOut >= 2000 and cortinaHall == 1):
print('Cortinas do corredor Fechadas')
print('luminosidade exterior: ',luxOut)
print('luminosidade corredor: ',luxHall)
cortinaHall = 0
elif (luzHall == 1):
print('Luzes do corredor Desligadas')
print('luminosidade exterior: ',luxOut)
print('luminosidade corredor: ',luxHall)
luzHall = 0
elif (luxHall <= 300 and luzHall == 0):
if (luxOut >= 400 and cortinaHall == 0):
print('Cortinas do corredor Abertas')
print('luminosidade exterior: ',luxOut)
print('luminosidade corredor: ',luxHall)
cortinaHall = 1
else:
print('Luzes do corredor Ligadas')
print('luminosidade exterior: ',luxOut)
print('luminosidade corredor: ',luxHall)
luzHall = 1
#cortina & Luz sala
if (luxIn >= 500):
if (luxOut >= 2000 and cortinaSala == 1):
print('Cortinas da sala Fechadas')
print('luminosidade exterior: ',luxOut)
print('luminosidade sala: ',luxIn)
cortinaSala = 0
elif (luzSala == 1):
print('Luzes da sala Desligadas')
print('luminosidade exterior: ',luxOut)
print('luminosidade sala: ',luxIn)
luzSala = 0
elif (luxIn <= 300 and luzSala == 0):
if (luxOut >= 400 and cortinaSala == 0):
print('Cortinas da sala Abertas')
print('luminosidade exterior: ',luxOut)
print('luminosidade sala: ',luxIn)
cortinaSala = 1
else:
print('Luzes da sala Ligadas')
print('luminosidade exterior: ',luxOut)
print('luminosidade sala: ',luxIn)
luzSala = 1
########################################################
#### SENSOR TEMP AND HUM ###############################
########################################################
#Sensor temp e humidade
sensorDHT.measure()
celsiusSala=sensorDHT.temperature()
hum=sensorDHT.humidity()
if(hum>60) and (hum_anterior<=60):
print("Acender deshumidificador")
print('humidity anterior sala:', hum_anterior,'%')
print('humidity atual sala:', hum,'%')
elif(hum<=60) and (hum_anterior>60):
print("Apagar deshumidificador")
print('humidity anterior sala:', hum_anterior,'%')
print('humidity atual sala:', hum,'%')
hum_anterior=hum
if(janelaSala == 0) and (ACsala == 0):
if (celsiusOut >= 25 and celsiusSala >= 27):
print('AC sala Arrefece');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature Sala:', celsiusSala, 'ºC');
ACsala = -1;
elif (celsiusSala <= 15):
print('AC sala Aquece');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature Sala:', celsiusSala, 'ºC');
ACsala = 1;
elif (celsiusOut <= 20 and celsiusSala >= 25):
print('Abrir Janela sala');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature Sala:', celsiusSala, 'ºC');
janelaSala = 1;
elif(celsiusSala <= 20 and celsiusOut >= 25):
print('Abrir Janela sala');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature Sala:', celsiusSala, 'ºC');
janelaSala = 2;
elif(janelaSala == 1):
if(celsiusSala <= celsiusOut):
print('Fechar Janela sala');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature Sala:', celsiusSala, 'ºC');
janelaSala = 0;
elif(janelaSala == 2):
if(celsiusSala >= celsiusOut ):
print('Fechar Janela sala');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature Sala:', celsiusSala, 'ºC');
janelaSala = 0;
else:
if((celsiusSala >= 19 and ACsala == 1) or (celsiusSala <= 24 and ACsala == -1)):
print('AC sala Desliga');
print('temperature exterior :', round(celsiusOut,1),'ºC');
print('temperature Sala:', celsiusSala, 'ºC');
ACsala = 0;
########################################################
################# OLED ###############################
########################################################
functionDisplay(celsiusSala,celsiusOut,hum,room_counter,hall_counter,luxIn,luxOut)
########################################################
#### CARTÃO MICRO SD ###################################
########################################################
#read button
button_state_b = button_b.value()
#detect falling edge of button and rising of sensor
if (button_state_b==0) and (button_before_b==1):
print('Ficheiros do sdcard: ', os.listdir('/sd')) # list directory contents
store_dados("Temperature exterior : "+ str(round(celsiusOut,1))+"ºC")
store_dados("Temperature corredor: : "+ str(round(celsiusHall,1))+"ºC")
store_dados("Temperature Sala: : "+ str(round(celsiusSala,1))+"ºC")
store_dados("Humidity sala: : "+ str(round(hum,1))+"%")
store_dados("Luminosidade exterior: : "+ str(round(luxOut,1))+"lux")
store_dados("Luminosidade corredor: : "+ str(round(luxHall,1))+"lux")
store_dados("Luminosidade sala: : "+ str(round(luxIn,1))+"lux")
if(button_state == 1):
store_dados("button state entry: Inactive")
else:
store_dados("button state entry: Active")
store_dados("button state storege: Active")
if(ms_hall_state == 1):
store_dados("Motion sensor hall state: Active")
else:
store_dados("Motion sensor hall state: Inactive")
if(ms_room_1_state == 1):
store_dados("Motion sensor_A Room state: Active")
else:
store_dados("Motion sensor_A Room state: Inactive")
if(ms_room_2_state == 1):
store_dados("Motion sensor_B Room state: Active")
else:
store_dados("Motion sensor_B Room state: Inactive")
store_dados("Pessoas na Sala: : "+ str(room_counter))
store_dados("Pessoas no Edificio: : "+ str(hall_counter))
show_dados()
#variables refresh
button_before_b = button_state_b
########################################################
#### Print valores sensores ############################
########################################################
"""print('---------Print dos Valores dos sensores-----------------')
print('temperature exterior :', round(celsiusOut,1),'ºC')
print('temperature corredor:', round(celsiusHall,1),'ºC')
print('temperature Sala:', celsiusSala, 'C')
print('humidity sala:', hum,'%')
print('luminosidade exterior: ',luxOut)
print('luminosidade corredor: ',luxHall)
print('luminosidade sala: ',luxIn)
print("button_state: ", button_state)
print("ms_hall_state: ", ms_hall_state)
print("ms_room_1_state: ", ms_room_1_state)
print("ms_room_2_state: ", ms_room_2_state)
print("Ocupacao Ed: ", hall_counter)
print("Ocupacao sala: ", room_counter)
print('-------------------------------------------------------')"""
#sleep(2) #2s
except OSError as err:
print('falha na execução')
sd.deinit() # unmount