I2c Setup Issue - python

I am trying to setup an Adafruit i2c temperature sensor in Python with a RaspberryPi4. The only example code for this sensor (SCD-40) sets up the i2c by importing board module:
import board
import adafruit_scd4x
i2c = board.I2C() # uses board.SCL and board.SDA
scd4x = adafruit_scd4x.SCD4X(i2c)
*** This works and runs fine on its own. My problem is that I also have 3 stepper motors which I'm controlling using RPI.GPIO:
import RPi.GPIO as GPIO
*** When I try bringing my i2c temperature sensor into the stepper motor Python code, I get an error telling me I cannot use board with RPi.GPIO
ERROR: (GPIO.setmode(GPIO.BOARD) ValueError: A different mode has already been set!)
HOW CAN I SETUP AN I2C SENSOR WITHOUT USING THE import BOARD module? Is there a way to set it using RPi.GPIO

Why do you need 'RPi.GPIO'? You can use 'board' with 'digitalio' to access to GPIOs.
import board
import digitalio
import busio
pin17 = digitalio.DigitalInOut(board.D17)
pin17.direction = digitalio.Direction.OUTPUT
pin17.pull = digitalio.Pull.DOWN
value = pin17.value
You can also use I2C with 'busio'
i2c = busio.I2C(board.SCL, board.SDA)
Read this link and this link.

Related

DHT22 sensor for RaspberryPi system setup issues

So I am using a raspberry pi system and am trying to write code in the python to have the system read the humidity and temperature. We are able to get the humidity sensor to read the humidity and temperature in terminal, so we are somewhat sure we set it up right. When we try to import Adafruit_DHT into python (out written code) we get an error when we run the code. Any help would be greatly appreciated!
Here is more info about the code:
Terminal entry:
pi#raspberrypi:~/Adafruit_Python_DHT/examples $ python AdafruitDHT.py 22 4
Temp=24.1* Humidity=48.4%
Python Code:
import Adafruit_DHT
#set sensore type : options are DHT11, DHT22
sensor=Adafruit_DHT.DHT22
#white is 22
#set GPIO sensor is connected to
gpio=4
#use read_retry method, this will retry up to 15 times to get
#a sensor reading (waiting two seconds between each try
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
#reading the DHT11 is very sensitive to timings and sometimes the Pi might
#fail to get a valid reading (so check)
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
Error from running:
Traceback (most recent call last):
** IDLE Internal Exception:
File "/usr/lib/python3.4/idlelib/run.py", line 353, in runcode
exec(code, self.locals)
File "/home/pi/hopeful dht run.py", line 1, in <module>
import Adafruit_DHT
ImportError: No module named 'Adafruit_DHT'
Thank you so much!
Izzy
You haven't installed the adafruit_dht library. Need to:
Enter the following in your terminal to install the Adafruit Python DHT Library:
sudo pip3 install Adafruit_DHT
https://learn.adafruit.com/adafruit-io-basics-temperature-and-humidity/python-setup
https://www.raspberrypi.org/forums/viewtopic.php?t=235179
***if you have done this, and getting the same error, try running python, python2, or python3. You might not have everything updated.

Setting up Adafruit PDM with Rapsberry Pi 4

I am relatively new to working with Raspberry pi, Adafruit products and python coding. I have been working on setting up a Adafruit PDM Microphone connected to my RPi 4 and am attempting to running it on python 3. Adafruits tutorials have been amazing so far but I am having some issues getting all the required modules and libraries installed for this one. Is there a way to install Adafruit_zeroPDM and Adafruit_zeroDMA into python? I followed the github download links and tried several methods for installing them using pip3 however I am repeatedly getting errors about missing modules that should be in Adafruit's circuit python library. Is the Adafruit PDM microphone not compatible with RPi?
I have been using the following python code, which is directly taken form the adafruit website(https://learn.adafruit.com/adafruit-pdm-microphone-breakout/circuitpython):
import time
import array
import math
import board
import audiobusio
def mean(values):
return sum(values) /len(values)
def normalized_rms(values):
minbuf = int(mean(values))
samples_sum = sum(
float(sample - minbuf) * (sample - minbuf)
for sample in values
)
return math.sqrt(samples_sum / len(values))
#Main program
mic = audiobusio.PDMIn(board.TX, board.D12, sample_rate=16000, bit_depth=16)
samples = array.array('H', [0] * 160)
while True:
mic.record(samples, len(samples))
magnitude = normalized_rms(samples)
print((magnitude,))
print("Decible Quired")
time.sleep(10)
I am unable to solve a library and module problem. I have downloaded Adafruit_circuitpython library and Adafruit_Blinka library as well as the required Adafruit_ZeroPDM and Adafruit_ZeroDMA however I keep getting the following error.
ModuleNotFoundError: No module named 'audiobusio'
Any help would be greatly appreciated.
Best

Saving video file the time and date in filename

Expected Behavior
Automatically run a program to record a video for a short length of time.
Save the video to a unique filename within a specific directory (to avoid overwriting). Ideally, this filename would include the date and time.
Actual Behavior
Success
Filename is always video.h264.
I have tried all sorts of things that I have found on the net, but they only result in the file name showing part of the code. Annoyingly it worked once, but saved it to somewhere I was not expecting and I changed the code before I realized it had worked!
Full File
# Import Libraries
import os #Gives Python access to Linux commands
import time #Proves time related commands
import RPi.GPIO as GPIO #Gives Python access to the GPIO pins
GPIO.setmode(GPIO.BCM) #Set the GPIO pin naming mode
GPIO.setwarnings(False) #Supress warnings
# Set GPIO pins 18 as output pin
LEDReady = 18 #Red
GPIO.setup(LEDReady,GPIO.OUT)
GPIO.output (LEDReady,GPIO.HIGH)
from subprocess import call
call(["raspivid", "-o", "video.h264", "-t", "50000n"])
time.sleep(10) #Sleep for 10 seconds
GPIO.output (LEDReady,GPIO.LOW)
Adding DATE=$(date +"%Y-%m-%d_%H%M")
and changing video.h264 to $DATE.h264 results in a syntax error for $DATE.
Tantalizingly, I have a file called 20180308_021941.h264 which is exactly what I am after, but I cannot tell you how I managed it!
P.S. the Red LED lighting up is so that I can tell if the Raspberry Pi has fired up properly and has run the Python script.
Thank you for taking the trouble to read this.
Try adding this
from datetime import datetime
date = datetime.now().strftime("%Y%m%d%H:%M:%S")
Then change your call to this
videoFile = date + ".h264"
call(["raspivid", "-o", videoFile, "-t", "50000n"])

Micropython paho module missing?

I'm trying to build a basic MQTT publisher using a nodemcu v3 and a dht11 to send temperature data. I'm using ESPlorer and when I try to upload my code it tells me that the paho module does not exist. My code is as follows:
import time
import network
import paho.mqtt.client as mqtt
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
sta_if.connect('<MySSID>', '<MyPW>')
mqtt = mqtt.Client()
mqtt.connect("randomIPaddress")
pin = machine.Pin(4)
temp_instance = dht11.DHT11(pin)
result = temp_instance.read()
print("Temperature is: %d C" % result.temperature)
print("Humidity is: %d %%" % result.humidity)
message = result.temperature
mqtt.publish("base/dht11/temp", message)
mqtt.loop_forever()
I'm still very confused by how MQTT publishing works, and I can't seem to find any sources that agree with each other on this. Everywhere I look has a different solution for my problem.
Does anyone have an idea why ESPLorer keeps telling me that the paho module doesn't exist? I've already tried installing the module as shown in the documentation but that got me nowhere.
Edit:
https://pypi.python.org/pypi/paho-mqtt/1.1
These where the instructions I followed to install paho.
The paho MQTT client has been written for regular Python. It is unlikely that it would run under MicroPython.
MicroPython includes its own MQTT client called umqtt. There are two versions, umqtt.simple and umqtt.robust.
You can see an example that uses it here.

RE: Getting the Adafruit_I2C Import Changed Into Another GPIO Layout

I have some problems with the MotorBridgeCape. I have all my software and I found most of it at GitHub.com at github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB and at their Wiki at seeedstudio.com/wiki/Motor_Bridge_Cape_v1.0.
Here is my issue. I connect my battery, two motors, and I run the .py file for DC Motors from their Wiki page. I get an error. The error reads as follows:
•Error accessing 0x4B: Check your I2C address
I checked online at their site. The seeedstudio.com site, in the forum section, stated that in 2014 there was an addressed answer. This answer was to update the firmware. I go into my BBB/BBG with the MotorBridgeCape attached and I download the .zip file and then unzip it.
The update to the firmware is as follows:
1.Connect cape to your BBG/BBB, download http://www.seeedstudio.com/wiki/images/ ... e_v1.0.zip to your BBG/BBB
2.unzip the file
3.Go to the directory Motor Bridge Cape V1.0 (cd Motor Bridge Cape V1.0)
4.upload firmware (make flash_firmware)
Once I unzip the .zip file, I get a "directory." The directory is listed as Motor Bridge Cape v1.0. I have no underscores in the file/directory.
So, it is not listed as Motor_Bridge_Cape_v1.0 and I cannot move to that file/directory. So, I used "\" to move to that directory.
So, I get to the directory stated and I use "make flash_Firmware". That gets me errors, too.
Here is the code for the MotorBridgeCapeforBBG_BBB:
https://github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB/blob/master/BBG_MotorBridgeCape/MotorBridge.py
Please see:
from Adafruit_I2C import Adafruit_I2C
import Adafruit_BBIO.GPIO as GPIO
import time
Reset = "P9_23"
MotorBridge = Adafruit_I2C(0x4b)
GPIO.setup(Reset, GPIO.OUT)
ReadMode = 0
WriteMode = 1
DeAddr = 0X4B
ConfigValid = 0x3a6fb67c
DelayTime = 0.005
This software above uses the Adafruit_I2C. Is there a way to change Adafruit_I2C to another "import" of GPIOs that does not have a bug?
The I2C import from Adafruit has a bug in it. If I can change the I2C import to import other GPIOs, like GPIO_46 and so on, I should be able to use the MotorBridgeCapeforBBG_BBB in my current code to make things go.
Please see:
import MotorBridge
import time
MotorName = 1
ClockWise = 1
CounterClockWise = 2
PwmDuty = 90
Frequency = 1000
if __name__=="__main__":
motor = MotorBridge.MotorBridgeCape()
motor.DCMotorInit(MotorName,Frequency)
while True:
motor.DCMotorMove(MotorName,ClockWise,PwmDuty)
time.sleep(2)
motor.DCMotorMove(MotorName,CounterClockWise,PwmDuty)
time.sleep(2)
print "hello"
motor.DCMotorStop(MotorName)
time.sleep(2)
Seth
P.S. Any recommendations would be very helpful.
I changed the line
MotorBridge = Adafruit_I2C(0x4b)
to
MotorBridge = Adafruit_I2C(0x4b,2)
and it worked for me. Also make sure you have python-smbus installed. See this webpage for more information.
Okay...
I checked out the BBG and the Motor Bridge Cape long enough. I did as you stated in the above answer. Thank you. It was that additional 2 in the sequence of the software. I also needed python smbus to run the software correctly.
Seth
An update to this item is now available on github.com at https://github.com/silver2row/bbg/blob/master/MBC/MotorBridge.py.
Also, you can view the README at the beginning of the github repository for accessing smbus2, getting your smbus2 line 302 changed, and for some simple source to test your findings.
There are a lot of changes to set up on your MotorBridge.py file. Please view the differences and change them accordingly.
Seth
the Motor Bridge Cape "needs" the Adafruit_GPIO.I2C library since the Adafruit_BBIO.I2C library is not existent right now. Also...this is old news since the Adafruit_GPIO.I2C library has been deprecated.
It is read only now. You can find that info. here: https://github.com/adafruit/Adafruit_Python_GPIO/blob/master/Adafruit_GPIO/I2C.py.
This is what I use now for the Motor Bridge Cape I2C functionality: https://github.com/kplindegaard/smbus2.
So, instead of using the set up of the old way listed above, use this:
#!/usr/bin/python3
# * Copyright (c) 2015 seeed technology inc.
# * Author : Jiankai Li
# * Create Time: Nov 2015
# * Change Log : Seth Dec. 2019 w/ help from #beagle at Freenode
# * and Prabakar's book called, "BealgeBone by Example."
# * license: http://www.gnu.org/licenses/gpl-3.0.txt is the license for my contributions...
# * license from Mr. Li can be found here: https://github.com/Seeed-Studio/MotorBridgeCapeforBBG_BBB/blob/master/BBG_MotorBridgeCape/MotorBridge.py (MIT).
# FileName : MotorBridge.py
# by Jiankai.li
from smbus2 import SMBus
import time
import pathlib
# reset pin is P9.23, i.e. gpio1.17
reset_pin = pathlib.Path('/sys/class/gpio/gpio49/direction')
reset_pin.write_text('low')
bus = SMBus('/dev/i2c-2')
...
Motor Bridge Cape and the BeagleBoard.org family of boards!

Categories