코드

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 9

//https://www.instructables.

com/Temperature-Displayed-on-4-Digit-7-segment-common/
#step1
// 220 Ohm 필요
const int co2_limit = 190; // 일산화탄소 수치
const int serialDelay = 50; // 0.05 초에 한번 씩 읽기
const int force_limit = 500; // 충격센서 임계치
const long interval = 3000; // 몇초간 경고 표시
const long interval1 = 500; // LED 깜빡깜빡 경고 표시

const int sensorPins[6] = {A0, A1, A2, A3, A4, A5}; // 각 센서 정렬, A0 충격감지센서
const int digitPins[3] = {5, 6, 7}; // FND 자리 선택, 5 가 1 의 자리
const int clockPin = 11; // 74HC595 Pin 11
const int latchPin = 12; // 74HC595 Pin 12
const int dataPin = 13; // 74HC595 Pin 14
const int force_alert_Pin = 9; // 충격 감지 경보 LED
const int force_buzzer_Pin = 10; // 충격 감지 경보 부저
const int co2_alert_Pin = 8; // 일산화 탄소 감지 경보
const int fnd_reset_Pin = 4; // 리셋 핀

const byte digit[10] = { //seven segment digits in bits


B00111111, //0
B01011011, //1
B01011011, //2
B01001111, //3
B01100110, //4
B01101101, //5
B01111101, //6
B00000111, //7
B01111111, //8
B01101111 //9
};

int digitBuffer[4] = { 0 };
int digitScan = 0;
int forceValue;
int buttonState = 0;
int cnt = 0;
int force_timer_flag = 0;
int co2_timer_flag = 0;
unsigned long force_curr_time = 0;
unsigned long force_prev_time = 0;
unsigned long force_mid_time = 0;
unsigned long co2_curr_time = 0;
unsigned long co2_prev_time = 0;
int incomingByte = 0;
int ledState = LOW;

void setup(){
for(int i=0;i<6;i++){pinMode(sensorPins[i], INPUT);}
for(int i=0;i<3;i++){pinMode(digitPins[i], OUTPUT);}
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(dataPin, OUTPUT);
pinMode(force_alert_Pin, OUTPUT);
pinMode(force_buzzer_Pin, OUTPUT);
pinMode(co2_alert_Pin, OUTPUT);
pinMode(fnd_reset_Pin, INPUT);
Serial.begin(9600);
}

/*
void updateDisp(){
for(byte j=0; j<4; j++){digitalWrite(digitPins[j], LOW);}
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
digitalWrite(latchPin, HIGH);
delayMicroseconds(100);
digitalWrite(digitPins[digitScan], HIGH);
digitalWrite(latchPin, LOW);
//if(digitScan==2) shiftOut(dataPin, clockPin, MSBFIRST,
~(digit[digitBuffer[digitScan]] | B10000000)); //print the decimal point on the
3rd digit 최상위 비트가 1
//else
shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]);
digitalWrite(latchPin, HIGH);
digitScan++;
if(digitScan>3) digitScan=0;
}
*/
void fndOff(){ // FND 모두 끄기
for(byte j=0; j<4; j++)
digitalWrite(digitPins[j], LOW);
}

void updateDisp(){
for(int i=0; i<3 ; i++){
digitalWrite(latchPin, LOW);
fndOff();
shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[i]]);
digitalWrite(latchPin, HIGH);
digitalWrite(digitPins[i], HIGH);
delay(1);
}
}

void sendSerial(int num, int var) {


String tmp;
tmp = String(num) + "," + String(var);
Serial.println(tmp);
}

void co2_alert_set(){
co2_timer_flag=1;
co2_prev_time = millis();
digitalWrite(co2_alert_Pin, HIGH);
}

void force_alert_set(){
cnt++;
force_timer_flag = 1;
force_prev_time = millis();
force_mid_time = millis();
digitalWrite(force_alert_Pin, HIGH);
digitalWrite(force_buzzer_Pin, HIGH);
ledState = HIGH;
}
void loop(){
buttonState = digitalRead(fnd_reset_Pin);
if (buttonState == HIGH){cnt = 0;}
for(int i=0 ; i<6 ; i++){sendSerial(i, analogRead(sensorPins[i]));}
if (force_timer_flag == 1){
force_curr_time = millis();
if (force_curr_time - force_mid_time >= interval1) {
force_mid_time = force_curr_time;
if (ledState == LOW){
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(force_alert_Pin, ledState);
}
if (force_curr_time - force_prev_time >= interval) {
force_timer_flag = 0;
digitalWrite(force_alert_Pin, LOW);
digitalWrite(force_buzzer_Pin, LOW);
}
}
if (co2_timer_flag == 1){
co2_curr_time = millis();
if (co2_curr_time - co2_prev_time >= interval) {
co2_timer_flag = 0;
digitalWrite(co2_alert_Pin, LOW);
}
}
digitBuffer[3] = int(cnt)/1000;
digitBuffer[2] = (int(cnt)%1000)/100;
digitBuffer[1] = (int(cnt)%100)/10;
digitBuffer[0] = (int(cnt)%100)%10;
updateDisp();
if (Serial.available() > 0){
incomingByte = Serial.read();
if (incomingByte == 'f'){force_alert_set();}
if (incomingByte == 'c'){co2_alert_set();}
}
}

import sys
import os
import serial
import time
from PyQt5 import QtCore, QtWidgets, uic
from email.mime.text import MIMEText
import smtplib
import datetime
import queue

def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS',
os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
macro_form = resource_path('find_smoker_2.ui')
form_class = uic.loadUiType(macro_form)[0]

def sendMail(msg): ################################


sendEmail = "dahliahn@naver.com" # 메일 설정
recvEmail = "dahli-effect@naver.com" # 메일 설정
password = "!Dhl151026" # 보내는 메일 비밀번호
smtpName = "smtp.naver.com" # smtp 서버 주소
smtpPort = 587 # smtp 포트 번호
msg = MIMEText(msg) # MIMEText(text , _charset = "utf8")
msg['Subject'] = "적 출현" # 메일 제목
msg['From'] = sendEmail
msg['To'] = recvEmail
# print(msg.as_string())

# s = smtplib.SMTP(smtpName, smtpPort) # 메일 서버 연결
# s.starttls() # TLS 보안 처리
# s.login(sendEmail, password) # 로그인
# s.sendmail(sendEmail, recvEmail, msg.as_string()) # 메일 전송, 문자열로 변환하여
보냅니다.
# s.close() # smtp 서버 연결을 종료합니다.
# print('email send')

class SerialThread(QtCore.QThread):
def __init__(self, queue1, queue2, serial_data, parent=None):
QtCore.QThread.__init__(self, parent)
self.queue1 = queue1
self.queue2 = queue2
self.serialPort = serial_data['port_num']
self.baudRate = serial_data['baud_rate']
def run(self):
try:
self.s = serial.Serial(self.serialPort, self.baudRate)
self.queue1.put("Success")
self.s.write(str.encode('*00T%'))
time.sleep(0.2)
except:
self.queue1.put("Failed")
while True:
try:
time.sleep(.001)
val = self.s.readline()
while not '\\n' in str(val):
time.sleep(.001)
temp = self.readline()
if not not temp.decode():
val = (val.decode()+temp.decode()).encode()
val = val.decode()
val = val.strip()
self.queue1.put(val)
except Exception as e:
print(e)

while self.queue2.qsize():
try:
new = self.queue2.get()
if new == 'c':
self.s.write(str.encode('c'))
if new == 'f':
self.s.write(str.encode('f'))
except queue.Empty:
pass

class MyWindow(QtWidgets.QMainWindow, form_class):


def __init__(self):
super().__init__()
title = "흡연충 감지기"
self.setupUi(self)
self.setWindowTitle(title)

self.queue1 = queue.Queue()
self.queue2 = queue.Queue()
self.current_timer = None
self.e_mail_possible_flag = True
self.initPort()

self.connectBtn.clicked.connect(self.Connect)
self.refreshBtn.clicked.connect(self.Exit)
self.setBtn.clicked.connect(self.Apply)
self.autoApplyBtn.clicked.connect(self.autoApply)
self.checkBox_1.stateChanged.connect(self.Apply)
self.checkBox_2.stateChanged.connect(self.Apply)
self.checkBox_3.stateChanged.connect(self.Apply)
self.checkBox_4.stateChanged.connect(self.Apply)
self.checkBox_5.stateChanged.connect(self.Apply)

def initPort(self):
self.ports = ['COM%s' % (i + 1) for i in range(256)]
self.result = []
for self.port in self.ports:
try:
self.s = serial.Serial(self.port)
self.s.close()
self.result.append(self.port)
except (OSError, serial.SerialException):
pass
for self.portValue in self.result:
self.comport_input.addItem(self.portValue)

def Connect(self):
self.port_num = self.comport_input.currentText()
self.baud_rate = self.baud_input.currentText()
serial_data_to_send = {
'port_num': self.port_num,
'baud_rate': self.baud_rate,
}
self.process_serial()
self.serial_th = SerialThread(self.queue1, self.queue2,
serial_data=serial_data_to_send)
self.serial_th.start()

def Exit(self):
self.close()
def Apply(self):
if self.checkBox_1.isChecked():
self.enableElements(self.progressBar_1, self.limit_input_1,
self.max_input_1)
self.progressBar_1.setMaximum(int(self.max_input_1.text()))

else:
self.disableElements(self.progressBar_1, self.limit_input_1,
self.max_input_1)
if self.checkBox_2.isChecked():
self.enableElements(self.progressBar_2, self.limit_input_2,
self.max_input_2)
self.progressBar_2.setMaximum(int(self.max_input_2.text()))
else:
self.disableElements(self.progressBar_2, self.limit_input_2,
self.max_input_2)
if self.checkBox_3.isChecked():
self.enableElements(self.progressBar_3, self.limit_input_3,
self.max_input_3)
self.progressBar_3.setMaximum(int(self.max_input_3.text()))
else:
self.disableElements(self.progressBar_3, self.limit_input_3,
self.max_input_3)
if self.checkBox_4.isChecked():
self.enableElements(self.progressBar_4, self.limit_input_4,
self.max_input_4)
self.progressBar_4.setMaximum(int(self.max_input_4.text()))
else:
self.disableElements(self.progressBar_4, self.limit_input_4,
self.max_input_4)
if self.checkBox_5.isChecked():
self.enableElements(self.progressBar_5, self.limit_input_5,
self.max_input_5)
self.progressBar_5.setMaximum(int(self.max_input_5.text()))
else:
self.disableElements(self.progressBar_5, self.limit_input_5,
self.max_input_5)

def autoApply(self):
try:
# self.setLimitValue = int(self.progressBar_1.value()) +
int(self.auto_limit_input.text())
#
self.progressBar_1.setMaximum(int(float(self.progressBar_1.value()*float(self.auto_
max_input.text()))))
# self.limit_input_1.setText(str(self.setLimitValue))

self.setMaxValue = int(float(self.progressBar_1.value() *
float(self.auto_max_input.text())))
self.progressBar_1.setMaximum(self.setMaxValue)
self.max_input_1.setText(str(self.setMaxValue))
self.limit_input_1.setText(str(int(self.progressBar_1.value()) +
int(self.auto_limit_input.text())))

self.setMaxValue = int(float(self.progressBar_2.value() *
float(self.auto_max_input.text())))
self.progressBar_2.setMaximum(self.setMaxValue)
self.max_input_2.setText(str(self.setMaxValue))
self.limit_input_2.setText(str(int(self.progressBar_2.value()) +
int(self.auto_limit_input.text())))

self.setMaxValue = int(float(self.progressBar_3.value() *
float(self.auto_max_input.text())))
self.progressBar_3.setMaximum(self.setMaxValue)
self.max_input_3.setText(str(self.setMaxValue))
self.limit_input_3.setText(str(int(self.progressBar_3.value()) +
int(self.auto_limit_input.text())))

self.setMaxValue = int(float(self.progressBar_4.value() *
float(self.auto_max_input.text())))
self.progressBar_4.setMaximum(self.setMaxValue)
self.max_input_4.setText(str(self.setMaxValue))
self.limit_input_4.setText(str(int(self.progressBar_4.value()) +
int(self.auto_limit_input.text())))

self.setMaxValue = int(float(self.progressBar_5.value() *
float(self.auto_max_input.text())))
self.progressBar_5.setMaximum(self.setMaxValue)
self.max_input_5.setText(str(self.setMaxValue))
self.limit_input_5.setText(str(int(self.progressBar_5.value()) +
int(self.auto_limit_input.text())))

except Exception as e:
print(e)

self.Apply()

def enableElements(self, *elements):


for element in elements:
element.setEnabled(True)

# 요소들 입력받아 한꺼번에 비활성화


def disableElements(self, *elements):
for element in elements:
element.setEnabled(False)

def start_timer(self):
if self.current_timer:
self.current_timer.stop()
self.current_timer.deleteLater()
self.current_timer = QtCore.QTimer()
self.current_timer.timeout.connect(self.set_e_mail_flag)
self.current_timer.setSingleShot(True)
self.current_timer.start(5000)

def set_e_mail_flag(self):
self.e_mail_possible_flag = True
print("메일 전송 가능")

def process_serial(self):
value = True
e_mail_request = False
while self.queue1.qsize():
try:
new = self.queue1.get()
tmp = new.split(',')
sensor_number = tmp[0]
if value:
value = False
now = datetime.datetime.now()
nowDatetime = now.strftime('%Y-%m-%d %H:%M:%S')
try:
sensor_value = int(tmp[1])
if sensor_number == '0':
print(sensor_value)
if sensor_value < int(self.lineEdit.text()):
self.queue2.put('f')
self.log = nowDatetime + " / 충격 / " +
str(sensor_value)
self.log_box.appendPlainText(self.log)
if sensor_number == '1' and self.checkBox_1.isChecked():
self.progressBar_1.setValue(sensor_value)
if sensor_value > int(self.limit_input_1.text()):
e_mail_request = True
if sensor_number == '2' and self.checkBox_2.isChecked():
self.progressBar_2.setValue(sensor_value)
if sensor_value > int(self.limit_input_2.text()):
e_mail_request = True
if sensor_number == '3' and self.checkBox_3.isChecked():
self.progressBar_3.setValue(sensor_value)
if sensor_value > int(self.limit_input_3.text()):
e_mail_request = True
if sensor_number == '4' and self.checkBox_4.isChecked():
self.progressBar_4.setValue(sensor_value)
if sensor_value > int(self.limit_input_4.text()):
e_mail_request = True
if sensor_number == '5' and self.checkBox_5.isChecked():
self.progressBar_5.setValue(sensor_value)
if sensor_value > int(self.limit_input_5.text()):
e_mail_request = True
if e_mail_request:
self.queue2.put('c')
self.start_timer()
if self.e_mail_possible_flag and e_mail_request:
self.e_mail_possible_flag = False
e_mail_request = False
sendMail(nowDatetime + " / 일산화 탄소 : " +
str(sensor_number) +
"번 센서 / 값 : " + str(sensor_value))
self.log = nowDatetime + " / Mail / " +
str(sensor_number) + "번 : " + str(sensor_value)
self.log_box.appendPlainText(self.log)
except Exception as e:
print(e)
if new == 'Success':
self.connectBtn.setText('Connected')
self.log = nowDatetime + " / " + new
self.log_box.appendPlainText(self.log)
if new == 'Failed':
self.connectBtn.setText('Connect')
self.log = nowDatetime + " / " + new
self.log_box.appendPlainText(self.log)

except queue.Empty:
pass
QtCore.QTimer.singleShot(100, self.process_serial)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myWindow = MyWindow()
myWindow.show()
app.exec_()

You might also like