http://www.shumeipai.net/thread-7315-1-1.html
看了上面这个帖子,认真研究了原版RC-Switch后,决定用python实现该代码。但在使用中发现python自带得sleep函数不能提供微妙级的延时,所以加载了c库中的usleep()微妙级延时函数。
硬件连接见原帖,调用方法:
python send.py FFFFFFFFFFF0 打开
python send.py FFFFFFFFFFFF 关闭
该代码仅实现了发射功能,接收功能由于手头没模块,没有写。
py315M.rar
(10 KB, 下载次数: 13)
源码下载
如果不能解压,将文件后缀改为tar
具体代码如下:
pyswitch.py- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import RPi.GPIO as GPIO
- import time
- import ctypes
- GPIO.setwarnings(False)
- class pySwitch(object):
- def __init__(self,nPulseLength=350,nRepeatTime=10):
- self.nPulseLength=nPulseLength
- self.nRepeatTime=nRepeatTime
- def enableSend(self,nSendPin):
- self.nSendPin=nSendPin
- GPIO.setmode(GPIO.BOARD)
- GPIO.setup(self.nSendPin,GPIO.OUT)
- def disableSend(self,nSendPin):
- self.nSendPin=-1
- GPIO.cleanup()
- def send(self,sSendCode):
- nRepeat=0
- while(nRepeat<self.nRepeatTime):
- for i in range(len(sSendCode)):
- if sSendCode[i]=="0":
- self.send0()
- elif sSendCode[i]=="1":
- self.send1()
- elif sSendCode[i]=="F":
- self.sendF()
- else:
- print 'undefine'
- self.sendSync()
- nRepeat=nRepeat+1
- def send0(self):
- self.transmit(1,3)
- self.transmit(1,3)
- def send1(self):
- self.transmit(3,1)
- self.transmit(3,1)
- def sendF(self):
- self.transmit(1,3)
- self.transmit(3,1)
- def sendSync(self):
- self.transmit(1,31)
- def transmit(self,nHighPulse,nLowPulse):
- if self.nSendPin!=-1:
- cUsleep=ctypes.CDLL("./libpysleep.so")
- GPIO.output(self.nSendPin,GPIO.HIGH)
- cUsleep.pysleep(nHighPulse*self.nPulseLength)
- # time.sleep(0.000001*nHighPulse*self.nPulseLength)
- GPIO.output(self.nSendPin,GPIO.LOW)
- cUsleep.pysleep(nLowPulse*self.nPulseLength)
- # time.sleep(0.000001*nLowPulse*self.nPulseLength)
复制代码 send.py |
|