raspberry pi python等待输入使用大部分cpu

时间:2017-07-19 16:00:07

标签: python raspberry-pi cpu-usage

我的python程序等待来自键盘的输入,然后根据该输入运行。在等待输入时,它占用了cpu的93%,但一旦收到输入,它只使用1.5%。

相关代码是:

class keypad():
    KEYPAD = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    ["*",0,"#"]
    ]
    ROW = [21,6,13,19]
    COLUMN = [12,16,20]

    def __init__(self):
        GPIO.setmode(GPIO.BCM);
    def getKey(self):
        for j in range(len(self.COLUMN)):
            GPIO.setup(self.COLUMN[j], GPIO.OUT)
            GPIO.output(self.COLUMN[j], GPIO.LOW)

        for i in range(len(self.ROW)):
            GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)

        rowVal = -1
        for i in range(len(self.ROW)):
            tmpRead = GPIO.input(self.ROW[i])
            if tmpRead == 0:
                rowVal = i

        if (rowVal < 0) or (rowVal > 3):
            self.exit()
            return
        for j in range(len(self.COLUMN)):
            GPIO.setup(self.COLUMN[j], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

        GPIO.setup(self.ROW[rowVal], GPIO.OUT)
        GPIO.output(self.ROW[rowVal], GPIO.HIGH)

        colVal = -1
        for j in range(len(self.COLUMN)):
            tmpRead = GPIO.input(self.COLUMN[j])
            if tmpRead == 1:
                colVal = j

        if (colVal < 0) or (colVal > 2):
            self.exit()
            return

        self.exit()
        return self.KEYPAD[rowVal][colVal]

    def exit(self):
        for i in range(len(self.ROW)):
            GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)
        for j in range(len(self.COLUMN)):
            GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)

def phys_in():
        while True:
                kp = keypad()   
                list = ['']
                digit = None
                while True:
                    digit = kp.getKey()
                    if digit != None and digit != '*' and digit != '#':
                        list.append(str(digit))
                        time.sleep(.5)
                        digit = None
                    elif digit == '*':
                        while True:
                            stop = kp.getKey()
                            temp_con.t = int(''.join(list))

对我来说,等待输入将使用如此多的cpu是没有意义的。任何人都可以提供一些现场的原因吗?

0 个答案:

没有答案