使用PCA9685控制LED

时间:2016-04-21 12:47:52

标签: python raspberry-pi raspberry-pi2

我已经购买了Adafruit PCA9685并完成了库安装,但是,我不知道如何编程。我想基于我写的以下代码:

import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub

GPIO.setmode(GPIO.BCM)

PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27

GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)

FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 #  flickering effect

# Duty Cycle (0 <= dc <=100)

living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)

porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)

fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)

# PubNub

pubnub = Pubnub(publish_key='demo', subscribe_key='demo')

channel = 'pi-house'

def _callback(m, channel):
    print(m)

    dc = m['brightness'] *10

    if m['item'] == 'light-living':
        living.ChangeDutyCycle(dc)

    elif m['item'] == 'light-porch':
        porch.ChangeDutyCycle(dc)

    elif m['item'] == 'fireplace':
        fire.ChangeDutyCycle(dc)

def _error(m):
  print(m)

pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)

try:
    while 1:
        pass
except KeyboardInterrupt:
    GPIO.cleanup()
    sys.exit(1)

我不知道这是否相似。我买它是因为我希望能够用Raspberry pi中的PWM控制更多的LED。我调查了它,发现了特定于这个芯片的各种奇怪的命令和术语。

谢谢!

2 个答案:

答案 0 :(得分:1)

首先,如果您查看数据表的第29页(图15),它表明对于直接LED连接,您需要将LED倒置连接。即将LED的地线连接到PCA9685上的PWM线,将LED的正极连接到V +

代码非常简单(下面是Arduino)你使用函数pwm.setPWM(uint8_t num, uint16_t on, uint16_t off)来打开和关闭LED并达到不同的亮度级别。

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

void setup()
{
Serial.begin(9600);

pwm.begin();
pwm.setPWMFreq(1600);  //This is the maximum PWM frequency

pwm.setPWM(1,0,4095); //this turns on the LED connected to channel one (I suspect the only line you're really looking for)
}

希望能回答你的问题!

答案 1 :(得分:0)

请参见下文如何使用python

    const snapshotToArray = snapshot => {

        snapshot.forEach(childSnapshot => {

            let item = childSnapshot.val();
            item.key = childSnapshot.key;
            console.log(childSnapshot.key);
      })
      }
      this.ref = firebase.database().ref('users/' + user.uid + '/Posts');
      this.ref.on('value', resp => {

        this.infos = [];
        this.infos = snapshotToArray(resp);


      });

logKey(snapshot){
    console.log(item.key);

      }

<ion-card *ngFor="let info of infos" >
      <ion-item detail lines="full" (click)="logKey()">
          <div class="row">Key - {{info.key}}</div>   
      </ion-item>
</ion-card>