软件pwm在python中使用带有raspberry的I2C

时间:2014-08-20 09:40:59

标签: python raspberry-pi i2c pwm

我正在寻找使用带有覆盆子pi的mcp23017 gpio-expander作为led调光器的解决方案,但每隔4-5秒就有一个短暂的闪烁。如果我直接使用gpio,我会进行闪烁也是如此(如果你尝试的话,在代码中注释/取消注释相关部分) 我不能使用rpi.gpio software-pwm或pi-blaster,因为它不能通过i2c使用,如果你有一个解决方案让这个包准备好i2c它也会很棒 我认为这个问题在于解决GPIO的问题,但我没有得到它

#!/usr/bin/python
# -*- coding: utf-8 -*-

# uncomment line 14-20 for using I2C and comment line 24-35, switch for using GPIO directly

import smbus
import time
import RPi.GPIO as GPIO

liste = [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# print liste #debugging ...
periodendauer = 0.001 # means 1000Hz

# # to send data to mcp23017
# b = smbus.SMBus(1) # 0 indicates /dev/i2c-0, muss auf 1 stehen (für rev2)
# while True:
    # for values in liste:
        # b.write_byte_data(0x20,0x14,values) #send data via smbus(I2C) to mcp23017
        # # print values #debugging only
        # time.sleep(periodendauer)


# to send data direct to gpio-pin
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
while True:
    for values in liste:
        if values > 0:
            values = True
        else:
            values = False
        GPIO.output(7,values)
        # print values #debugging only
        time.sleep(periodendauer)

1 个答案:

答案 0 :(得分:-1)

根据评论,我重写了我对你问题的回答。

我通过删除I2C部分和注释简化了应用程序并删除了睡眠功能。我这样做是为了向您展示Raspbery Pi对于您想要使用它的方式的精确计时是多么不可靠。我在代码中添加的是在for循环的开始和结束时测量的时间,因此它现在测量“liste”数组的整个循环处理而不是单个“值”的长度。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import time
import RPi.GPIO as GPIO
import sys

liste = [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0]

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
while True:
    ms = time.time() * 1000.0
    for values in liste:
        if values > 0:
            values = True
        else:
            values = False
        GPIO.output(7,values)
    me = time.time() * 1000.0 - ms
    sys.stdout.write("\r{0:4.4f}".format(me)),
    sys.stdout.flush()

我家里的Banana Pi有相同的GPIO输出,但请在Raspberry上运行,你会得到相同的结果(可能有更长的周期时间)。对我来说,结果是在4-5ms之间,有几个6ms长度的脉冲,有时它超过10ms。这就是为什么你有闪烁的领导。

对于基于I2C的解决方案,我建议使用专用的I2C PWM驱动板来产生平滑的PWM信号,例如恩智浦的PCA9685。

相关问题