※9v건전지가 없으니 pi에서 5v에 연결한다.
import RPi.GPIO as GPIO
import time
B_IA_pwm = 18
B_IB = 17
B_IA_pwm2 = 19
B_IB2 = 16
GPIO.setmode(GPIO.BCM)
GPIO.setup(B_IA_pwm, GPIO.OUT)
GPIO.setup(B_IB, GPIO.OUT)
GPIO.setup(B_IA_pwm2, GPIO.OUT)
GPIO.setup(B_IB2, GPIO.OUT)
pwm = GPIO.PWM(B_IA_pwm, 1000.0)
pwm2 = GPIO.PWM(B_IA_pwm2, 1000.0)
pwm.start(0.0)
pwm2.start(0.0)
try:
while True:
GPIO.output(B_IB, False)
GPIO.output(B_IB2, False)
pwm.ChangeDutyCycle(0.0)
pwm2.ChangeDutyCycle(0.0)
time.sleep(1.0)
GPIO.output(B_IB, True)
GPIO.output(B_IB2, True)
pwm.ChangeDutyCycle(0.0)
pwm2.ChangeDutyCycle(0.0)
time.sleep(1.0)
GPIO.output(B_IB, True)
GPIO.output(B_IB2, True)
pwm.ChangeDutyCycle(100.0)
pwm2.ChangeDutyCycle(100.0)
time.sleep(1.0)
GPIO.output(B_IB, False)
GPIO.output(B_IB2, False)
pwm.ChangeDutyCycle(100.0)
pwm2.ChangeDutyCycle(100.0)
time.sleep(1.0)
except KeyboardInterrupt:
pass
pwm.ChangeDutyCycle(0.0)
pwm2.ChangeDutyCycle(0.0)
pwm.stop()
pwm2.stop()
GPIO.cleanup()
sudo reaspi-config
입력
명령어 기반 라즈베리파이 설정 프로그램임.
아래 사진과 같이 설정하고 라즈베리파일을 재부팅 한다.
ls -l /dev/ | grep serial
입력하여 ttyS0을 확인한다.
import serial
serialP = serial.Serial('/dev/ttyS0', baudrate = 9600, timeout = 30.0)
serialcmd = 'AT+ADDR?'
serialP.write(serialcmd.encode())
try:
while True:
dat = serialP.read(100)
print(dat)
except KeyboardInterrupt:
pass
serialP.close()
코드를 짜서 내 블루투스 모듈의 맥주소 확인은 가능하나 책에서 안내한 BLEJoystick앱에서 블루투스검색을 못하고 있다.
최신 스마트폰에서 작동을 안하는 것일까? 어플 업데이트가 필요해 보인다.
아이폰은 된다.
빵판 내부를 연결할 때 필요한 회로 선이 없어서 패스
pca9685.py
본 라이브러리를 사용해야 한다.
sudo raspi-config
입력하여 아래와 같이 설정
import smbus
import pca9685
import time
led_pin = 11
i2c_bus = smbus.SMBus(1) # 1 : /dev/i2c-1 (port I2C1)
pwm = pca9685.PWM(i2c_bus)
pwm.setFreq(1000)
try:
while True:
pwm.setDuty(led_pin, 0)
time.sleep(0.5)
pwm.setDuty(led_pin, 4095)
time.sleep(0.5)
except KeyboardInterrupt:
pass
pwm.setDuty(led_pin, 0)
i2c_bus.close()
import smbus
import pca9685
import time
led_pin = 11
i2c_bus = smbus.SMBus(1) # 1 : /dev/i2c-1 (port I2C1)
pwm = pca9685.PWM(i2c_bus)
pwm.setFreq(1000)
try:
while True:
# pwm.setDuty(led_pin, 0)
# time.sleep(0.5)
# pwm.setDuty(led_pin, 4095)
# time.sleep(0.5)
for dutyCycle in range(0,4096,8):
pwm.setDuty(led_pin, dutyCycle)
time.sleep(0.001)
for dutyCycle in range(4095,-1,-8):
pwm.setDuty(led_pin, dutyCycle)
time.sleep(0.001)
except KeyboardInterrupt:
pass
pwm.setDuty(led_pin, 0)
i2c_bus.close()
A누르면 밝기 최대, S누르면 꺼짐, D누르면 LED점멸
아래와 같이 하면 D입력후 while에서 나갈 수 없다.
import smbus
import pca9685
import time
led_pin = 11
i2c_bus = smbus.SMBus(1) # 1 : /dev/i2c-1 (port I2C1)
pwm = pca9685.PWM(i2c_bus)
pwm.setFreq(1000)
try:
while True:
userInput = input()
if userInput == 'A':
pwm.setDuty(led_pin, 4095)
# time.sleep(0.5)
elif userInput == 'S':
pwm.setDuty(led_pin, 0)
elif userInput == 'D':
while True:
pwm.setDuty(led_pin, 0)
time.sleep(0.5)
pwm.setDuty(led_pin, 4095)
time.sleep(0.5)
except KeyboardInterrupt:
pass
pwm.setDuty(led_pin, 0)
i2c_bus.close()
# 강사님코드
import smbus
import pca9685
import time
import threading
led_pin =11
i2c_bus = smbus.SMBus(1)
pwm = pca9685.PWM(i2c_bus)
pwm.setFreq(1000)
flag_exit = False
userInput ="f"
def blink_led():
global userInput
while True:
if userInput == "a":
pwm.setDuty(led_pin, 4095)
elif userInput == "s":
pwm.setDuty(led_pin, 0)
elif userInput == "d":
pwm.setDuty(led_pin, 4095)
time.sleep(0.5)
pwm.setDuty(led_pin, 0)
time.sleep(0.5)
else:
pwm.setDuty(led_pin, 0)
if flag_exit: break
tBL = threading.Thread(target=blink_led)
tBL.start()
try:
while True:
userInput = input() # for string
print(userInput)
except KeyboardInterrupt:
pass
tBL.join()
pwm.setDuty(led_pin,0)
i2c_bus.close()
import smbus
import pca9685
import time
buzzer_pin = 11
i2c_bus = smbus.SMBus(1) # 1 : /dev/i2c-1 (port I2C1)
pwm = pca9685.PWM(i2c_bus)
pwm.setDuty(buzzer_pin, 2047)
try:
while True:
for cnt in range(3):
pwm.setFreq(262)
time.sleep(1.0)
pwm.setFreq(294)
time.sleep(1.0)
except KeyboardInterrupt:
pass
pwm.setDuty(buzzer_pin, 0)
i2c_bus.close()
import smbus
import pca9685
import time
buzzer_pin = 11
melody = [262,294,330,349,392,440,494,523]
i2c_bus = smbus.SMBus(1) # 1 : /dev/i2c-1 (port I2C1)
pwm = pca9685.PWM(i2c_bus)
pwm.setDuty(buzzer_pin, 2047)
try:
while True:
for note in range(8):
pwm.setFreq(melody[note])
time.sleep(0.5)
except KeyboardInterrupt:
pass
pwm.setDuty(buzzer_pin, 0)
i2c_bus.close()
import smbus
import pca9685
import time
buzzer_pin = 11
melody = 0
i2c_bus = smbus.SMBus(1) # 1 : /dev/i2c-1 (port I2C1)
pwm = pca9685.PWM(i2c_bus)
pwm.setDuty(buzzer_pin, 2047)
try:
while True:
userInput = input()
print(type(userInput))
userInput = int(userInput)
print(type(userInput))
pwm.setFreq(userInput)
time.sleep(0.5)
except KeyboardInterrupt:
pass
pwm.setDuty(buzzer_pin, 0)
i2c_bus.close()
sudo apt update
입력y
입력sudo apt install python3-opencv
입력 모두 y
입력sudo python3 <파일명>
입력하여sudo raspi-config
입력후 설정필요 p351
아래와 같이 터미널에 출력되며 VNC서버가 활성화 된다.
비밀번호는 raspberry
이제 코딩은 vscode에서 하고 실행은 vns에서 할 것이다.
사진은 미리 폴더에 넣어주자
import cv2
img = cv2.imread('photo.jpg')
cv2.imshow('photo', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
압축해제한 폴더 자체를 home/pi/Downloads에 넣어주고
실습에서 사용할 아래 두 파일을 코딩파일과 동일한 폴더에 넣어준다.
import cv2
img = cv2.imread('photo.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow('photo', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
sudo raspi-config
입력
카메라 인식이 안되서 패스
코드는 콜라비 참조할 것
# code1
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, img = cap.read()
if ret:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
img = cv2.rectangle(img, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imwrite('faces_capture.jpg',img)
cv2.imshow('Video Capture', img)
key = cv2.waitKey(1) &0xFF
if key ==ord('k'):
cv2.imwrite('capture.jpg',img)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
# code2
import cv2
import datetime
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
now = datetime.datetime.now().strftime("%d_%H-%M-%S")
while cap.isOpened():
ret, img = cap.read()
if ret:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imwrite("captureface"+ str(now)+".png", img)
cv2.imshow('Video Capture', img)
key = cv2.waitKey(1) &0xFF
if key == 27:
break
elif key == ord('k'):
print("캡쳐")
cv2.imwrite("capture"+ str(now)+".png", img)
cap.release()
cv2.destroyAllWindows()
# code3
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
count = 0
def captureImg(img):
global count
cv2.imwrite('output' + str(count) + '.png', img)
count = count + 1
while cap.isOpened():
ret, img = cap.read()
if ret:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for(x, y, w, h) in faces:
img = cv2.rectangle(img, (x, y), (x + w,y + h), (255, 0, 0), 2)
captureImg(img)
cv2.imshow('Video Capture', img)
key = cv2.waitKey(1) &0xFF
if key == 27:
break
elif key == ord('k'):
captureImg(img)
cap.release()
cv2.destroyAllWindows()
# code4
import cv2
capture = cv2.VideoCapture(0)
print("aa")
if capture.isOpened():
print('width:', capture.get(cv2.CAP_PROP_FRAME_WIDTH))
print('height:', capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
print('fps:', capture.get(cv2.CAP_PROP_FPS))
else :
print("fail")
num = 0
numface=0
while capture.isOpened():
ret, img = capture.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imwrite("./photoface{0}.jpg".format(numface), img)
numface+=1
if ret:
cv2.imshow('aa',img)
key = cv2.waitKey(1) &0xFF
if key == 27:
break
if key == ord('k'):
num += 1
cv2.imwrite("./photo{0}.jpg".format(num), img)
capture.release()
cv2.destroyAllWindows()