I have bought an Adafruit PCA9685 and completed the library installation, however, I have no clue of how to Program it. I want to base it on the following code I wrote:
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)
I dont know if on this its similar. I bought it because I wanted to be able to control more LED's with PWM from the Raspberry pi. I looked into it and found all kinds of weird commands and terms specific to this Chip.
Thanks!
First, If you look at page 29 of the data sheet (fig. 15) it shows that for Direct LED connection, you need to connect your LEDs inverted. i.e. connect the ground of the LED to the PWM line on the PCA9685 and the positive of the LED to the V+
Code is pretty simple (below is for an Arduino) And you use the function pwm.setPWM(uint8_t num, uint16_t on, uint16_t off) to turn the LEDs on and off and to different levels of brightness.
#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)
}
Hope that answers your question!
See below how to do this in python
import Adafruit_PCA9685
pwm = Adafruit_PCA9685.PCA9685()
pwm.set_pwm_freq(60)
# Demo using LED on Channel 12 of the PCA9685
# Wire up the LED on Channel 12 such that
# Shortleg of LED goes to GND and
# Long leg goes to PWM pin on channel 12
pwm.set_pwm(12,0,4095) # Full bright
time.sleep(5)
pwm.set_pwm(12,1024,3072) # half bright
time.sleep(5)
pwm.set_pwm(12,0,0) #off
time.sleep(5)
Related
I am trying to make a Smart Alarm using Arduino UNO, Ultrasonic Sensor and Bolt Wifi Module.
So, from the Arduino part, the code has been compiled and uploaded, but the Python part gives an Attribute Error. The main libraries which I am using are 'conf' and 'boltiot'. The above error gives in the 6th line of the code.
Python Code:
import conf, json, time
from boltiot import Bolt
limit=105 #This is distance b/w sensor and wall
max_time=20
min_time=18
mybolt=Bolt(conf.bolt_api_key, conf.device_id) #Code Error here
response=mybolt.serialRead('10')
print(response)
def buzzer_action(pin, value):
response=mybolt.digitalWrite(pin, value)
ticks=time.time() #gets the current time
ltime=time.localtime(ticks) #gets the local time
current_hour=ltime.tm_hour #gets the current hour
while True:
response=mybolt.serialRead('10')
data=json.loads(response)
distance= data['value'].rstrip()
print("Distance:", distance) #distance recieved from Arduino
if(current_hour<max_time and current_hour>=min_time):
print("Current Hour:", current_hour)
if int(distance) < limit: #If the person is sleeping then the distance will decrease
print("Limit Exceeded || Buzzer Action")
buzzer_action(1, "HIGH") #buzzer beeps
time.sleep(5)
buzzer_action(1, "LOW") #buzzer stops
continue
else:
time.sleep(10) #waits for 10 seconds
continue
time.sleep(10) #waits for 10 second and again repeats all steps
Arduino Code:
#include <Ultrasonic.h>
Ultrasonic ultrasonic(12, 13);
void setup()
{
Serial.begin(9600);
}
I am trying to communicate with a raspberry pi pico with my raspberry pi 4 over uart. The below code does transmit data, but I am only receiving data from the print statement.
import os
import utime
from machine import ADC
temp_sensor = ADC(4) # Default connection of temperature sensor
def temperature():
# get raw sensor data
raw_sensor_data = temp_sensor.read_u16()
# convert raw value to equivalent voltage
sensor_voltage = (raw_sensor_data / 65535)*3.3
# convert voltage to temperature (celcius)
temperature = 27. - (sensor_voltage - 0.706)/0.001721
return temperature
#print setup information :
print("OS Name : ",os.uname())
uart = machine.UART(0, baudrate = 9600)
print("UART Info : ", uart)
utime.sleep(3)
while True:
temp = temperature()
print(str(temp))
uart.write(str(temp))
utime.sleep(1)
And the code on my raspberry pi 4 is:
import serial
import time
import numpy as np
import matplotlib.pyplot as plt
#ser = serial.Serial('COM14',9600)
ser = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(1)
while True:
# read two bytes of data
#data = (ser.read(8))
data = (ser.readline())
# convert bytestring to unicode transformation format -8 bit
temperature = str(data).encode("utf-8")
#print("Pico's Core Temperature : " + temperature + " Degree Celcius")
print(temperature)
The output in the terminal on my RPI 4 is:
27.2332
26.443
26.443
26.564
There is an extra new line between. If I remove print(str(temp)) from the pico code I get nothing. I can put just about anything in uart.write(str(temp)) and still receive the print statement, but without the uart.write() I will receive nothing.
extra new line: this problem is just because the print ends with new line you can change print(str(temp)) to print(str(temp), end="") in raspberry pi pico code
with respect to your second problem I don't think that uart.write(str(temp))is doing something useful. print statement is the way to send data to raspberry pi
A way I use to send data to raspberry pi is:
raspberry pi pico send the number of chars of the message then send the message
while True:
temp = temperature()
print(len(str(temp)))
utime.sleep(1)
print(str(temp))
utime.sleep(1)
the length would be between 1 and 9 so raspberry pi will receive 1 char
in raspberry pi code
while True:
# read length of data
length = int(ser.read(1).encode("utf-8"))
# read the data
data = (ser.read(length))
#convert bytestring to unicode transformation format -8 bit
temperature = str(data).encode("utf-8")
print(temperature)
I'm trying to use pyfirmata to send and receive data between Arduino Uno R3 and my python program. At Arduino installed StandartFirmata sketch.
Code is:
from time import sleep
import serial
import pyfirmata
com_port_number = str(int(input('Введите номер COM-порта ')))
port = 'COM' + com_port_number # COM port number
print('Выбран порт COM ', port)
try:
board = pyfirmata.Arduino(port)
except serial.SerialException:
print('Не удается подключится к выбранному COM-порту')
com_port_number = str(int(input('Введите номер СОМ-порта')))
port = 'COM' + com_port_number
board = pyfirmata.Arduino(port)
sleep(1)
it = pyfirmata.util.Iterator(board)
it.start()
temp_list = []
potentiomentr = board.get_pin('a:0:o')
acid_control = board.get_pin('a:2:o')
stock_control = board.get_pin('a:3:o')
temperature_pin = board.get_pin('d:4:i') # well, this line is worked fine. Temperature sensor works correctly
in_connection_pc = board.get_pin('d:0:o') #but now i have InvalidPinDefError
triac = board.get_pin('d:6:o')
level = board.get_pin('d:8:i')
in_engine = board.get_pin('d:5:o')
in_triac = board.get_pin('d:10:o')
in_pump = board.get_pin('d:11:o')
drive_control = board.get_pin('d:12:o')
pump_control = board.get_pin('d:13:o')
while 1: # бесконечный цикл
a = temperature_pin.read()
b = in_connection_pc.write(1)
print(a)
list.append(a,b)
print(list)
sleep(3)
board.exit()
But i have some strange mistake:
Traceback (most recent call last):
File "C:/Users/lomil/PycharmProjects/Pyython_and_CSV_love/test_analog.py", line 22, in <module>
in_connection_pc = board.get_pin('d:0:i') #but now i have InvalidPinDefError??
File "C:\Users\lomil\Python_32\lib\site-packages\pyfirmata\pyfirmata.py", line 220, in get_pin
raise InvalidPinDefError('Invalid pin definition: UNAVAILABLE pin {0} at position on {1}'.format(pin_def, self.name))
pyfirmata.pyfirmata.InvalidPinDefError: Invalid pin definition: UNAVAILABLE pin d:0:i at position on COM1
When I commented all lines except
temperature_pin = board.get_pin('d:4:i')
It worked, but I can not understand what's wrong with other pins. They are totally good and worked fine when I wrote test sketch to Arduino.
The error message is actually complaining: UNAVAILABLE pin d:0:i at position on COM1. On the Arduino Uno (and most Arduinos) digital pins 0 and 1 are dual-use pins and are also used for communications over the serial port, aka COM port.
Firmata works by constantly communicating over the serial port so you can't actually use digital pins 0 and 1 for anything else while using Firmata.
So whatever wire you have plugged into your Arduino on digital pin 0, you need to move to another unused digital pin, like pin 3. So, if you move that wire to digital pin 3, then in code you would now need in_connection_pc = board.get_pin('d:3:o').
I wrote the following code for my US-100 ultrasonic distance measurement sensor. But I am getting junk results everytime. when ever I am moving my sensor, I dont get any change in reading. Also, when I am connecting GND and VCC to sensor, input stops generating. Need help with Circuit diagram for connecting US-100 to Raspberry pi 3 and errors in this code which lead to junk results
import RPi.GPIO as GPIO
import time
import logging
LOG_FILENAME='US_100.log'
logging.basicConfig(format='%(asctime)s %(message)s',filename='US_100',
level=logging.DEBUG)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while True:
GPIO.output(TRIG,False)
time.sleep(1.5)
print("Waiting for sensor to settle")
GPIO.output(TRIG,True)
time.sleep(0.0001)
GPIO.output(TRIG, False)
pulse_start=time.time()
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = (pulse_end-pulse_start)
print("Pulse duration =%1f " %pulse_duration)
distance = (pulse_duration*343/2)
if distance >0.5 and distance <400:
print("Distance = %1f" %distance)
else:
print("Out of Range")
logging.debug(distance)
Image of results which I am getting even though the object is 15-20cm apart.
Output Image
I just finished all of the prototyping of this project:, and I encountered 2 problems: https://www.pubnub.com/blog/2015-03-17-building-a-model-smart-home-with-raspberry-pi/
I cant run all of the programs at once(Humidity and Temperature, LEDs, Micro Servo motors, etc...)
I can't have more than three LED's (technically two)
What can I do to run everything at once, so it is all displayed in the WEB UI? How can I have more LED's, since the limit is 50mah which is about 2 LED's? (they can be three per 'room', so three per GPIO pin or just per GPIO). I dont see hoe it could work with such a power limit. Also, they need to be controlled with PWM. There simply isn't enough power on the Raspberry Pi!
the code for the DHT22 sensor is:
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def callback(message):
print(message)
#published in this fashion to comply with Eon
while True:
h,t = dht.read_retry(dht.DHT22, 4)
temp='{0:0.1f}'.format(t)
hum='{0:0.1f}'.format(h)
message = {'temperature': temp, 'humidity': hum}
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
pubnub.publish(channel=channel, message=message, callback=callback, error=callback)
the code for the led's is:
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)
Thanks!