前几天买了个继电器,搞了下,代码贴下,连接12引脚,10秒监听一次。python需要requests模块。
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import RPi.GPIO as GPIO
- import requests
- import json
- import time
- def main():
- GPIO.setwarnings(False)
- GPIO.setmode(GPIO.BOARD)
- GPIO.setup(12, GPIO.OUT)
- GPIO.setup(12, GPIO.OUT)
- #GPIO.output(12, GPIO.HIGH)
- while True:
- print u'监听开关状态...'
- status()
- time.sleep(10)
- #GPIO.output(12, GPIO.HIGH)
- #time.sleep(1)
- #GPIO.output(12, GPIO.LOW)
- #time.sleep(1)
-
- def status():
- apiurl = 'http://api.yeelink.net/v1.1/device/****/sensor/****/datapoints'
- apiheaders = {'U-ApiKey': '************************', 'content-type': 'application/json'}
- tmp = requests.get(apiurl, headers=apiheaders)
- switch = tmp.json()
- #print switch
- if switch['value'] == 1:
- print("开关打开...")
- if (GPIO.input(12) == 0):
- GPIO.output(12, GPIO.HIGH)
- else:
- print("开关关闭...")
- if (GPIO.input(12) == 1):
- GPIO.output(12, GPIO.LOW)
-
- if __name__ == '__main__':
- main()
复制代码 |