如何优化此代码以降低CPU消耗

时间:2017-04-22 15:05:15

标签: python raspberry-pi

我有一个python代码,它有一个无限循环,可以直观地扫描覆盆子pi的引脚。但是pi的资源消耗非常大。可以请某人建议我如何减少代码中的CPU使用率。

from matrixKeypad_RPi_GPIO import keypad
from time import sleep
import urllib2
kp = keypad()
var = 1
s1=True
s2=True
s3=True
s4=True
s5=True
s6=True
s7=True
def digit():
    # Loop while waiting for a keypress
    r = None
    while r == None:
        r = kp.getKey()
    return r
while var == 1:
    d=digit()
    if d==1:
        if s1==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r1=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r1=OFF')
        s1^=True
    if d==2:
        if s2==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r2=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r2=OFF')
        s2^=True
    if d==3:
        if s3==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r3=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r3=OFF')
        s3^=True
    if d==4:
        if s4==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r4=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r4=OFF')
        s4^=True
    if d==5:
        if s5==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r5=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r5=OFF')
        s5^=True
    if d==6:
        if s6==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r6=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r6=OFF')
        s6^=True
    if d==7:
        if s7==True :
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r7=ON')
        else:
            urllib2.urlopen('http://192.168.0.2:8080/classicui/CMD?r7=OFF')
        s7^=True
    sleep(1)

0 个答案:

没有答案