树莓派上基于Python控制GPIO
希望做到可以自动给阳台的花儿浇水~
有以下几点:
- 控制GPIO的拉高/拉低,并保持一段时间间隔
- 加锁,避免重复
- 有日志记录具体情况
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import RPi.GPIO as GPIO
import time
import fcntl
import logging
class Servant(object):
def __init__(self, name):
self.fobj = open(name, 'w')
self.fd = self.fobj.fileno()
def lock(self):
try:
fcntl.lockf(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
logging.debug("Lock Success")
return True
except:
logging.warning("Lock Fail, Seems another process is watering, exit...")
return False
def unlock(self):
self.fobj.close()
logging.debug("Unlock Success")
def watering(self, inverval):
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)
# for ground
GPIO.output(21, GPIO.LOW)
GPIO.output(20, GPIO.HIGH)
time.sleep(inverval)
GPIO.output(20, GPIO.LOW)
GPIO.cleanup()
def main():
Adam = Servant("/tmp/watering.lock")
logging.basicConfig(filename='/tmp/watering.log',
format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s-%(funcName)s',
level=logging.INFO)
if Adam.lock():
logging.info("Start Watering...")
Adam.watering(90)
Adam.unlock()
logging.info("Stop Watering...")
else:
logging.debug("Exit...")
if __name__ == '__main__':
main()
标签:__,树莓,logging,Python,self,watering,GPIO,def
From: https://www.cnblogs.com/adam-ma/p/18008297