In this lesson we show how to detect light levels with a Raspberry Pi and a photoresistor. The photoresistor is connected in a voltage divider to the ADC0834 AD converter, which then connects to the Raspberry Pi. The schematic of the circuit is below:
Category Archives: Python
Library for I2C Connection of the LCD1602 to the Raspberry PI
This lesson shows how to connect an LCD1602 to a Raspberry Pi using only 4 wires by I2C. You will need to copy the code below, and create a program called LCD1602.py, and save it in the same folder your main python programs are in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | #!/usr/bin/env python3 import time import smbus2 as smbus BUS = smbus.SMBus(1) def write_word(addr, data): global BLEN temp = data if BLEN == 1: temp |= 0x08 else: temp &= 0xF7 BUS.write_byte(addr ,temp) def send_command(comm): # Send bit7-4 firstly buf = comm & 0xF0 buf |= 0x04 # RS = 0, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) # Send bit3-0 secondly buf = (comm & 0x0F) << 4 buf |= 0x04 # RS = 0, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) def send_data(data): # Send bit7-4 firstly buf = data & 0xF0 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) # Send bit3-0 secondly buf = (data & 0x0F) << 4 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) def init(addr, bl): # global BUS # BUS = smbus.SMBus(1) global LCD_ADDR global BLEN LCD_ADDR = addr BLEN = bl try: send_command(0x33) # Must initialize to 8-line mode at first time.sleep(0.005) send_command(0x32) # Then initialize to 4-line mode time.sleep(0.005) send_command(0x28) # 2 Lines & 5*7 dots time.sleep(0.005) send_command(0x0C) # Enable display without cursor time.sleep(0.005) send_command(0x01) # Clear Screen BUS.write_byte(LCD_ADDR, 0x08) except: return False else: return True def clear(): send_command(0x01) # Clear Screen def openlight(): # Enable the backlight BUS.write_byte(0x27,0x08) BUS.close() def write(x, y, str): if x < 0: x = 0 if x > 15: x = 15 if y <0: y = 0 if y > 1: y = 1 # Move cursor addr = 0x80 + 0x40 * y + x send_command(addr) for chr in str: send_data(ord(chr)) if __name__ == '__main__': init(0x27, 1) write(4, 0, 'Hello') write(7, 1, 'world!') |
Using an Arduino with Python LESSON 11: Controlling an LED from Python
In this video lesson, we show how to control an LED using python. Python sends commands to arduino, which then controls the LED. We also create a vPython visual, where the ‘Virtual’ LED mimics the behavior of the real LED. This a really cool demonstration and hope you enjoy it. I include below the code we develop in the video. On the arduino side we end up with the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | int redPin=11; int greenPin=10; int bluePin=9; int redVal=255; int greenVal=255; int blueVal=255; String cmd; void setup() { // put your setup code here, to run once: Serial.begin(115200); pinMode(redPin,OUTPUT); pinMode(greenPin,OUTPUT); pinMode(bluePin,OUTPUT); } void loop() { // put your main code here, to run repeatedly: while(Serial.available()==0){ } redVal=Serial.readStringUntil(':').toInt(); greenVal=Serial.readStringUntil(':').toInt(); blueVal=Serial.readStringUntil('\r').toInt(); analogWrite(redPin,redVal); analogWrite(greenPin,greenVal); analogWrite(bluePin,blueVal); } |
And on the python side we have:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import serial from vpython import * arduinoData=serial.Serial('com3',115200) myOrb=sphere(color=color.black,radius=1) while True: myCmd=input('Please Input Your Color R:G:B 0-255 ') myCmd=myCmd+'\r' arduinoData.write(myCmd.encode()) myColor=myCmd.split(':') red=int(myColor[0]) green=int(myColor[1]) blue=int(myColor[2]) myOrb.color=vector(red/255,green/255,blue/255) |
Using an Arduino with Python LESSON 8: Live Thermometer 3D Visual Using DHT11
In this video lesson we connect the Arduino to a DHT11 temperature and humidity sensor. We show how to wire the device up, and then how to code the Arduino. The data is passed from the Arduino to python. We then create a live 3D thermometer model that updates as the temperature changes.
On the arduino side, this is the code which we use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT11 float tempF; float tempC; float humidity; int setTime=500; int dt=1000; DHT TH(DHTPIN,DHTTYPE); void setup() { // put your setup code here, to run once: Serial.begin(115200); TH.begin(); delay(setTime); } void loop() { // put your main code here, to run repeatedly: tempC=TH.readTemperature(); tempF=TH.readTemperature(true); humidity=TH.readHumidity(); Serial.print(tempF); Serial.print(","); Serial.println(humidity); delay(dt); } |
Then on the python side, we use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import time import serial from vpython import * arduinoData=serial.Serial('com3',115200) time.sleep(.5) digValue=label(text='50',height=20,box=False,pos=vector(0,-2.5,2)) bulb=sphere(radius=1,color=color.red,pos=vector(0,-3,0)) cyl=cylinder(radius=.6,color=color.red,axis=vector(0,1,0),length=6,pos=vector(0,-3,0)) bulbGlass=sphere(radius=1.2,color=color.white,opacity=.25,pos=vector(0,-3,0)) cylGlass=cylinder(radius=.8,color=color.white,axis=vector(0,1,0),opacity=.25,length=6,pos=vector(0,-3,0)) for temp in range(0,115,10): tickPos=4.5/115*temp+1.5 tick=cylinder(radius=.7,color=color.black,length=.1,axis=vector(0,1,0),pos=vector(0,tickPos-3,0)) label=text(text=str(temp),color=color.white,pos=vector(-2,tickPos-3,0),height=.3) while True: while arduinoData.in_waiting==0: pass dataPacket=arduinoData.readline() dataPacket=str(dataPacket,'utf-8') dataPacket=dataPacket.strip('\r\n') dataPacket=dataPacket.split(',') temp=float(dataPacket[0]) hum=float(dataPacket[1]) len=(4.5/115)*temp+1.5 cyl.length=len digValue.text=str(temp) |
Improved Gesture Recognition in Python and MediaPipe
In this video lesson we show you how you can improve the accuracy of your gesture recognition program developed in the last lesson. We do this by normalizing the hand landmarks distance matrix to a standard size. By doing this, you get accurate results independent of the distance your hand is from the camera. For your convenience, I include the code below which we develop in this lesson. Enjoy!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | import time import cv2 print(cv2.__version__) import numpy as np class mpHands: import mediapipe as mp def __init__(self,maxHands=2,tol1=.5,tol2=.5): self.hands=self.mp.solutions.hands.Hands(False,maxHands,tol1,tol2) def Marks(self,frame): myHands=[] frameRGB=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) results=self.hands.process(frameRGB) if results.multi_hand_landmarks != None: for handLandMarks in results.multi_hand_landmarks: myHand=[] for landMark in handLandMarks.landmark: myHand.append((int(landMark.x*width),int(landMark.y*height))) myHands.append(myHand) return myHands def findDistances(handData): distMatrix=np.zeros([len(handData),len(handData)],dtype='float') palmSize=((handData[0][0]-handData[9][0])**2+(handData[0][1]-handData[9][1])**2)**(1./2.) for row in range(0,len(handData)): for column in range(0,len(handData)): distMatrix[row][column]=(((handData[row][0]-handData[column][0])**2+(handData[row][1]-handData[column][1])**2)**(1./2.))/palmSize return distMatrix def findError(gestureMatrix,unknownMatrix,keyPoints): error=0 for row in keyPoints: for column in keyPoints: error=error+abs(gestureMatrix[row][column]-unknownMatrix[row][column]) print(error) return error def findGesture(unknownGesture,knownGestures,keyPoints,gestNames,tol): errorArray=[] for i in range(0,len(gestNames),1): error=findError(knownGestures[i],unknownGesture,keyPoints) errorArray.append(error) errorMin=errorArray[0] minIndex=0 for i in range(0,len(errorArray),1): if errorArray[i]<errorMin: errorMin=errorArray[i] minIndex=i if errorMin<tol: gesture=gestNames[minIndex] if errorMin>=tol: gesture='Unknown' return gesture width=1280 height=720 cam=cv2.VideoCapture(4,cv2.CAP_DSHOW) cam.set(cv2.CAP_PROP_FRAME_WIDTH, width) cam.set(cv2.CAP_PROP_FRAME_HEIGHT,height) cam.set(cv2.CAP_PROP_FPS, 30) cam.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc(*'MJPG')) findHands=mpHands(1) time.sleep(5) keyPoints=[0,4,5,9,13,17,8,12,16,20] train=True tol=10 trainCnt=0 knownGestures=[] numGest=int(input('How Many Gestures Do You Want? ')) gestNames=[] for i in range(0,numGest,1): prompt='Name of Gesture #'+str(i+1)+' ' name=input(prompt) gestNames.append(name) print(gestNames) while True: ignore, frame = cam.read() frame=cv2.resize(frame,(width,height)) handData=findHands.Marks(frame) if train==True: if handData!=[]: print('Please Show Gesture ',gestNames[trainCnt],': Press t when Ready') if cv2.waitKey(1) & 0xff==ord('t'): knownGesture=findDistances(handData[0]) knownGestures.append(knownGesture) trainCnt=trainCnt+1 if trainCnt==numGest: train=False if train == False: if handData!=[]: unknownGesture=findDistances(handData[0]) myGesture=findGesture(unknownGesture,knownGestures,keyPoints,gestNames,tol) #error=findError(knownGesture,unknownGesture,keyPoints) cv2.putText(frame,myGesture,(100,175),cv2.FONT_HERSHEY_SIMPLEX,3,(255,0,0),8) for hand in handData: for ind in keyPoints: cv2.circle(frame,hand[ind],25,(255,0,255),3) cv2.imshow('my WEBcam', frame) cv2.moveWindow('my WEBcam',0,0) if cv2.waitKey(1) & 0xff ==ord('q'): break cam.release() |
s lesson. Enjoy!