- 기초 

wikidocs.net/21920

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

- 웹캠 영상 띄우기 (openCV 폴더에 파일 저장)

 

webnautes.tistory.com/1290

 

OpenCV에서 캡처한 영상을 pyQt5 윈도우에 보여주기

OpenCV에서 캡처한 영상을 pyQt5로 작성된 GUI에서 보여주는 방법을 다룹니다. 깃허브에 있는 코드를 수정하여 사용했습니다. 처음 실행하면 버튼 2개만 보입니다. start 버튼을 클릭하면 웹캠 영상이

webnautes.tistory.com

import cv2
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui


class ShowVideo(QtCore.QObject):

    flag = 0

    camera = cv2.VideoCapture(0)

    ret, image = camera.read()
    height, width = image.shape[:2]

    VideoSignal1 = QtCore.pyqtSignal(QtGui.QImage)
    VideoSignal2 = QtCore.pyqtSignal(QtGui.QImage)

    def __init__(self, parent=None):
        super(ShowVideo, self).__init__(parent)

    @QtCore.pyqtSlot()
    def startVideo(self):
        global image

        run_video = True
        while run_video:
            ret, image = self.camera.read()
            color_swapped_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

            qt_image1 = QtGui.QImage(color_swapped_image.data,
                                    self.width,
                                    self.height,
                                    color_swapped_image.strides[0],
                                    QtGui.QImage.Format_RGB888)
            self.VideoSignal1.emit(qt_image1)


            if self.flag:
                img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                img_canny = cv2.Canny(img_gray, 50, 100)

                qt_image2 = QtGui.QImage(img_canny.data,
                                         self.width,
                                         self.height,
                                         img_canny.strides[0],
                                         QtGui.QImage.Format_Grayscale8)

                self.VideoSignal2.emit(qt_image2)


            loop = QtCore.QEventLoop()
            QtCore.QTimer.singleShot(25, loop.quit) #25 ms
            loop.exec_()

    @QtCore.pyqtSlot()
    def canny(self):
        self.flag = 1 - self.flag


class ImageViewer(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ImageViewer, self).__init__(parent)
        self.image = QtGui.QImage()
        self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawImage(0, 0, self.image)
        self.image = QtGui.QImage()

    def initUI(self):
        self.setWindowTitle('Test')

    @QtCore.pyqtSlot(QtGui.QImage)
    def setImage(self, image):
        if image.isNull():
            print("Viewer Dropped frame!")

        self.image = image
        if image.size() != self.size():
            self.setFixedSize(image.size())
        self.update()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)


    thread = QtCore.QThread()
    thread.start()
    vid = ShowVideo()
    vid.moveToThread(thread)

    image_viewer1 = ImageViewer()
    image_viewer2 = ImageViewer()

    vid.VideoSignal1.connect(image_viewer1.setImage)
    vid.VideoSignal2.connect(image_viewer2.setImage)

    push_button1 = QtWidgets.QPushButton('Start')
    push_button2 = QtWidgets.QPushButton('Canny')
    push_button1.clicked.connect(vid.startVideo)
    push_button2.clicked.connect(vid.canny)

    vertical_layout = QtWidgets.QVBoxLayout()
    horizontal_layout = QtWidgets.QHBoxLayout()
    horizontal_layout.addWidget(image_viewer1)
    horizontal_layout.addWidget(image_viewer2)
    vertical_layout.addLayout(horizontal_layout)
    vertical_layout.addWidget(push_button1)
    vertical_layout.addWidget(push_button2)

    layout_widget = QtWidgets.QWidget()
    layout_widget.setLayout(vertical_layout)

    main_window = QtWidgets.QMainWindow()
    main_window.setCentralWidget(layout_widget)
    main_window.show()
    sys.exit(app.exec_())

 

- 얼굴인식 

blog.naver.com/ljy9378/221438230814

 

8편 : 실시간 얼굴인식 카메라 | 실시간 카메라 영상에서 사람 얼굴 판별하기

실시간 얼굴인식 카메라 | 실시간 카메라 영상에서 사람 얼굴 판별하기프로젝트 목차0편 : 개요1편 : 라즈...

blog.naver.com

 

-pyqt 설치

sudo apt-get install python3-pyqt5
sudo apt-get install qttools5-dev-tools 

-ui 사용

1.

1)윈도우에서 C:\Users\w\anaconda3\Library\bin 에 있는 qt design으로 ui 파일 생성

안녕하세요 글 넣어봄 

2)cmd에서 pyuic5 -x hello.ui -o hello.py (ui파일을 py파일로 생성)

 

3)py파일 안의 내용을 복사해서 라즈베리파이에서 실행

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'hello.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(150, 100, 91, 31))
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(Dialog.accept)
        self.buttonBox.rejected.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButton.setText(_translate("Dialog", "안녕하세요"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

 

- hello 누르면 welcome창 뜸 

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'hello.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox

def button_click():
    print("Button Pressed")
    QMessageBox.information(Dialog, 'Example','Welcome')

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
        self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.pushButton1 = QtWidgets.QPushButton(Dialog)
        self.pushButton1.setGeometry(QtCore.QRect(140, 70, 131, 91))
        self.pushButton1.setObjectName("pushButton1")
        

        self.retranslateUi(Dialog)
        self.buttonBox.accepted.connect(Dialog.accept)
        self.buttonBox.rejected.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButton1.setText(_translate("Dialog", "hello"))
        self.pushButton1.clicked.connect( button_click )
        
if __name__=="__main__":
    import sys
    app=QtWidgets.QApplication(sys.argv)
    Dialog=QtWidgets.QDialog()
    ui=Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

 

 

 

- 라즈베리 안에 있는 Qt 5 Designer 실행 후 ui 생성 후 저장 (a.ui)

- 파이썬 파일과 ui파일이 같은 폴더에 있어야 함 

 loadUi('a.ui',self) : 파일 이름 적기 

import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.uic import loadUi

class MyQtProgramming(QDialog):
    def __init__(self):
        super(MyQtProgramming, self).__init__()
        loadUi('a.ui',self)
        self.setWindowTitle("My Hello Program")
        self.pushButton.clicked.connect(self.on_pushButton_clicked)
    
    @pyqtSlot()
    def on_pushButton_clicked(self):
        self.label.setText('Welcome : '+self.lineEdit.text())
        
app=QApplication(sys.argv)
widget=MyQtProgramming()
widget.show()
sys.exit(app.exec_())

 

reasley.com/?p=837

 

[라즈베리파이 4] SD 카드 이미지 백업 – Win32DiskImager

뤼즌의 IT 블로그

reasley.com

- 백업한 파일 가져오려면 write 

- motion 설치 

 

blog.naver.com/PostView.nhn?blogId=nkkh159&logNo=220346387545

 

라즈베리파이에 웹캠을 달고 motion을 이용해 스트리밍하기

라즈베리파이에 USB 웹캠을 장착, 네트워크 스트리밍을 통해 실시간으로 영상을 보는 방법입니다.사용할...

blog.naver.com

m.blog.naver.com/PostView.nhn?blogId=nicepants&logNo=220808526202&proxyReferer=https:%2F%2Fwww.google.com%2F

 

라즈베리 파이 - Cloud Cam 따라하기(3) - Motion

Motion - Software motion detector 링크: http://www.lavrsen.dk/foswiki/bin/view/Motion/WebHome ...

blog.naver.com

 

-fswebcam 설치

wikidocs.net/3185

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

-opencv 설치

blog.naver.com/ljy9378/221434540374 

 

6편 : 라즈베리 파이에 OpenCV 설치하기

라즈베리 파이에 OpenCV 설치하기프로젝트 목차0편 : 개요1편 : 라즈베리 파이에 라즈비안(OS) 설치(...

blog.naver.com

 

mkdir openCV
cd openCV

git clone https://github.com/dltpdn/opencv-for-rpi.git
cd opencv-for-rpi
ls

ls 하면 

README.md 가 있음 

vi로 열면 링크 주소가 나오는데 그 주소로 들어가면 

github.com/dltpdn/opencv-for-rpi/releases

 

Releases · dltpdn/opencv-for-rpi

OpenCV debian package installation files for Raspberry-Pi - dltpdn/opencv-for-rpi

github.com

Installation instructions 부분 따라하면 됨. 

 

wget https://github.com/dltpdn/opencv-for-rpi/releases/download/4.2.0_buster_pi3b/opencv4.2.0.deb.tar
tar -xvf opencv4.2.0.deb.tar
sudo apt-get install -y ./OpenCV*.deb
pkg-config --modversion opencv4

-> 4.2.0 버전 뜸 

 

pip install opencv-python

위의 코드로 안되면 

sudo apt-get install opencv-python

끝~

- Design a Custom Character for an LCD

mikeyancey.com/hamcalc/lcd_characters.php

 

LCD Custom Character Generator

Design a Custom Character for an LCD First off - this is not my original design. Bruno Maia / Icontexto.com built this originally. It's been a very useful tool, but in recent months, it's disappeared. I thought I'd just make a quickie re-build of it, so I

mikeyancey.com

 

- HOW TO SETUP AN I2C LCD ON THE RASPBERRY PI

 

 

How to Setup an I2C LCD on the Raspberry Pi

How to use I2C to connect an LCD to the Raspberry Pi. Learn how to scroll, position, and clear text, print the date, time, IP address, and sensor data.

www.circuitbasics.com

devicemart.blogspot.com/2019/06/i2c-1602-lcd.html

 

[흥프로] 라즈베리파이 실습 예제 I2C 1602 LCD 모듈 사용하기

전기/전자부품, 로봇/기계부품, 코딩교육 국내 1위 쇼핑몰 디바이스마트 공식 블로그입니다.

devicemart.blogspot.com

- 가변저항(파란색)으로 lcd 밝기 조절 가능 

 

 

- Preferences->Raspberry Pi Configuration

Enable 확인 

sudo apt-get install i2c-tools
sudo apt-get install python-smbus
i2cdetect -y 1

 

lcd address 확인 

 

 

 

- INSTALLING THE LIBRARY

# -*- coding: utf-8 -*-
# Original code found at:
# https://gist.github.com/DenisFromHR/cc863375a6e19dce359d

"""
Compiled, mashed and generally mutilated 2014-2015 by Denis Pleic
Made available under GNU GENERAL PUBLIC LICENSE

# Modified Python I2C library for Raspberry Pi
# as found on http://www.recantha.co.uk/blog/?p=4849
# Joined existing 'i2c_lib.py' and 'lcddriver.py' into a single library
# added bits and pieces from various sources
# By DenisFromHR (Denis Pleic)
# 2015-02-10, ver 0.1

"""

# i2c bus (0 -- original Pi, 1 -- Rev 2 Pi)
I2CBUS = 1

# LCD Address
ADDRESS = 0x3f 

import smbus
from time import sleep

class i2c_device:
   def __init__(self, addr, port=I2CBUS):
      self.addr = addr
      self.bus = smbus.SMBus(port)

# Write a single command
   def write_cmd(self, cmd):
      self.bus.write_byte(self.addr, cmd)
      sleep(0.0001)

# Write a command and argument
   def write_cmd_arg(self, cmd, data):
      self.bus.write_byte_data(self.addr, cmd, data)
      sleep(0.0001)

# Write a block of data
   def write_block_data(self, cmd, data):
      self.bus.write_block_data(self.addr, cmd, data)
      sleep(0.0001)

# Read a single byte
   def read(self):
      return self.bus.read_byte(self.addr)

# Read
   def read_data(self, cmd):
      return self.bus.read_byte_data(self.addr, cmd)

# Read a block of data
   def read_block_data(self, cmd):
      return self.bus.read_block_data(self.addr, cmd)


# commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80

# flags for display entry mode
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00

# flags for display on/off control
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00

# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00

# flags for function set
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00

# flags for backlight control
LCD_BACKLIGHT = 0x08
LCD_NOBACKLIGHT = 0x00

En = 0b00000100 # Enable bit
Rw = 0b00000010 # Read/Write bit
Rs = 0b00000001 # Register select bit

class lcd:
   #initializes objects and lcd
   def __init__(self):
      self.lcd_device = i2c_device(ADDRESS)

      self.lcd_write(0x03)
      self.lcd_write(0x03)
      self.lcd_write(0x03)
      self.lcd_write(0x02)

      self.lcd_write(LCD_FUNCTIONSET | LCD_2LINE | LCD_5x8DOTS | LCD_4BITMODE)
      self.lcd_write(LCD_DISPLAYCONTROL | LCD_DISPLAYON)
      self.lcd_write(LCD_CLEARDISPLAY)
      self.lcd_write(LCD_ENTRYMODESET | LCD_ENTRYLEFT)
      sleep(0.2)


   # clocks EN to latch command
   def lcd_strobe(self, data):
      self.lcd_device.write_cmd(data | En | LCD_BACKLIGHT)
      sleep(.0005)
      self.lcd_device.write_cmd(((data & ~En) | LCD_BACKLIGHT))
      sleep(.0001)

   def lcd_write_four_bits(self, data):
      self.lcd_device.write_cmd(data | LCD_BACKLIGHT)
      self.lcd_strobe(data)

   # write a command to lcd
   def lcd_write(self, cmd, mode=0):
      self.lcd_write_four_bits(mode | (cmd & 0xF0))
      self.lcd_write_four_bits(mode | ((cmd << 4) & 0xF0))

   # write a character to lcd (or character rom) 0x09: backlight | RS=DR<
   # works!
   def lcd_write_char(self, charvalue, mode=1):
      self.lcd_write_four_bits(mode | (charvalue & 0xF0))
      self.lcd_write_four_bits(mode | ((charvalue << 4) & 0xF0))
  
   # put string function with optional char positioning
   def lcd_display_string(self, string, line=1, pos=0):
    if line == 1:
      pos_new = pos
    elif line == 2:
      pos_new = 0x40 + pos
    elif line == 3:
      pos_new = 0x14 + pos
    elif line == 4:
      pos_new = 0x54 + pos

    self.lcd_write(0x80 + pos_new)

    for char in string:
      self.lcd_write(ord(char), Rs)

   # clear lcd and set to home
   def lcd_clear(self):
      self.lcd_write(LCD_CLEARDISPLAY)
      self.lcd_write(LCD_RETURNHOME)

   # define backlight on/off (lcd.backlight(1); off= lcd.backlight(0)
   def backlight(self, state): # for state, 1 = on, 0 = off
      if state == 1:
         self.lcd_device.write_cmd(LCD_BACKLIGHT)
      elif state == 0:
         self.lcd_device.write_cmd(LCD_NOBACKLIGHT)

   # add custom characters (0 - 7)
   def lcd_load_custom_chars(self, fontdata):
      self.lcd_write(0x40);
      for char in fontdata:
         for line in char:
            self.lcd_write_char(line)  

 

- lcd_text.py 파일 생성 

import I2C_LCD_driver
from time import *

mylcd = I2C_LCD_driver.lcd()

mylcd.lcd_display_string("Hello World!", 1) 

 ("Hello World!", 1, 2)로 바꾸면 글자 위치 바뀜 1=>행(1~2) 2=> 위치(1~3)

->lcd에 Hello World! 출력됨

 

 

- 날짜/시간 출력 

import I2C_LCD_driver
import time
mylcd = I2C_LCD_driver.lcd()


while True:
    mylcd.lcd_display_string("Time: %s" %time.strftime("%H:%M:%S"), 1)
    
    mylcd.lcd_display_string("Date: %s" %time.strftime("%m/%d/%Y"), 2)

 

-온습도 센서 + lcd 

import RPi.GPIO as GPIO
import time
import Adafruit_DHT
import I2C_LCD_driver
from time import *

sensor = Adafruit_DHT.DHT11
pin = 4


try:
    while True:
        h,t = Adafruit_DHT.read_retry(sensor,pin)
        mylcd = I2C_LCD_driver.lcd()
        if h is not None and t is not None:
            print("Temperate={0:0.1f}*C Humidity={1:0.1f}%".format(t,h))
            mylcd.lcd_display_string("Temperate={0:0.1f}*C".format(t),1)
            mylcd.lcd_display_string("Humidity={0:0.1f}%".format(h),2)
        else:
            print("Read error")

        
except KeyboardInterrupt:
    print("bye")

finally:
    print("End of Program")

 

- 온습도 센서+ led추가+ lcd

import RPi.GPIO as GPIO
import time
import Adafruit_DHT
import I2C_LCD_driver
from time import *

GPIO.setmode(GPIO.BCM)

sensor = Adafruit_DHT.DHT11
pin = 4
LED_R= 13 
LED_G= 19
LED_B= 26

GPIO.setup(LED_R, GPIO.OUT)
GPIO.setup(LED_G, GPIO.OUT)
GPIO.setup(LED_B, GPIO.OUT)

try:
    while True:
        h,t = Adafruit_DHT.read_retry(sensor,pin)
        mylcd = I2C_LCD_driver.lcd()
        if h is not None and t is not None:
            if t > 27:
             GPIO.output(LED_R, True)
             GPIO.output(LED_G, False)
             GPIO.output(LED_B, False)
             print("Temperate={0:0.1f}*C Humidity={1:0.1f}%".format(t,h))
             mylcd.lcd_display_string("Temperate={0:0.1f}*C".format(t),1)
             mylcd.lcd_display_string("Humidity={0:0.1f}%".format(h),2)
             
            elif t < 10:
             GPIO.output(LED_R, False)
             GPIO.output(LED_G, False)
             GPIO.output(LED_B, True)
             print("Temperate={0:0.1f}*C Humidity={1:0.1f}%".format(t,h))
             mylcd.lcd_display_string("Temperate={0:0.1f}*C".format(t),1)
             mylcd.lcd_display_string("Humidity={0:0.1f}%".format(h),2)
             
            elif t >10 and t < 27:
             GPIO.output(LED_R, False)
             GPIO.output(LED_G, True)
             GPIO.output(LED_B, False)
             print("Temperate={0:0.1f}*C Humidity={1:0.1f}%".format(t,h))
             mylcd.lcd_display_string("Temperate={0:0.1f}*C".format(t),1)
             mylcd.lcd_display_string("Humidity={0:0.1f}%".format(h),2)   
                
        else: 
            print("Read error")
        
except KeyboardInterrupt:
    GPIO.output(LED_R, False)
    GPIO.output(LED_G, False)
    GPIO.output(LED_B, False)
    print("bye")
finally:
    print("End of Program")

 

- 글자 출력 

import I2C_LCD_driver
from time import *

mylcd = I2C_LCD_driver.lcd()

fontdata1 = [
        # char(0) - Upper-left character
        [ 0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b11111, 
          0b11111 ],

        # char(1) - Upper-middle character
        [ 0b00000, 
          0b00000, 
          0b00100, 
          0b00110, 
          0b00111, 
          0b00111, 
          0b11111, 
          0b11111 ],
        
        # char(2) - Upper-right character
        [ 0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b10000, 
          0b11000 ],
        
        # char(3) - Lower-left character
        [ 0b11111, 
          0b11111, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000 ],
       
        # char(4) - Lower-middle character
        [ 0b11111, 
          0b11111, 
          0b00111, 
          0b00111, 
          0b00110, 
          0b00100, 
          0b00000, 
          0b00000 ],
        
        # char(5) - Lower-right character
        [ 0b11000, 
          0b10000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000, 
          0b00000 ],
]

mylcd.lcd_load_custom_chars(fontdata1)

mylcd.lcd_write(0x80)
mylcd.lcd_write_char(0)
mylcd.lcd_write_char(1)
mylcd.lcd_write_char(2)

mylcd.lcd_write(0xC0)
mylcd.lcd_write_char(3)
mylcd.lcd_write_char(4)
mylcd.lcd_write_char(5)

 

- 2< distance_value < 300일 때 GREEN, 그 외에는 RED 출력 

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
LED_R = 13 
LED_G = 19

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(LED_R, GPIO.OUT)
GPIO.setup(LED_G, GPIO.OUT)

def getDistance():
    GPIO.output(TRIG, False)
    time.sleep(1) #1초마다 값을 냄 
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)
    
    while GPIO.input(ECHO) == 0:
        pulse_start = time.time()
    while GPIO.input(ECHO) == 1:
        pulse_end = time.time()
    
    pulse_duration = pulse_end - pulse_start
    distance= round(pulse_duration*17150,2)
    
    return distance

if __name__ == '__main__':
    try:
        while True:
            distance_value = getDistance()
            if distance_value > 2 and distance_value < 300:
                print("Distance is %.2f cm"%distance_value)
                GPIO.output(LED_G, GPIO.HIGH)
                GPIO.output(LED_R, GPIO.LOW)
            else:
                print("Out of Range")
                GPIO.output(LED_R, GPIO.HIGH)
                GPIO.output(LED_G, GPIO.LOW)
                
    except KeyboardInterrupt:
       GPIO.output(LED_R, GPIO.LOW)
       GPIO.output(LED_G, GPIO.LOW)
       GPIO.cleanup()

 

- 가까우면 red, 멀어지면 green에 가까워지는 코드 

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
LED_R = 13 
LED_G = 19

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(LED_R, GPIO.OUT)
GPIO.setup(LED_G, GPIO.OUT)

RED=GPIO.PWM(LED_R,100)
RED.start(0)
GREEN=GPIO.PWM(LED_G,100)
GREEN.start(0)

def getDistance():
    GPIO.output(TRIG, False)
    time.sleep(1) #1초마다 값을 냄 
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)
    
    while GPIO.input(ECHO) == 0:
        pulse_start = time.time()
    while GPIO.input(ECHO) == 1:
        pulse_end = time.time()
    
    pulse_duration = pulse_end - pulse_start
    distance= round(pulse_duration*17150,2)
    
    return distance

if __name__ == '__main__':
    try:
        while True:
            distance_value = getDistance()
            if distance_value > 2 and distance_value < 50:
                x= distance_value*2
                print("Distance is %.2f cm"%distance_value)
                RED.ChangeDutyCycle(101-x)
                GREEN.ChangeDutyCycle(x)
                
            else:
                print("Out of Range")
         
    except KeyboardInterrupt:
       GPIO.output(LED_R, GPIO.LOW)
       GPIO.output(LED_G, GPIO.LOW)
       GPIO.cleanup()

 

 

 

- 색상 참고 

 

 

- 스위치 누르면  RGB LED색깔 바꾸기

(nputIO == False and count== 0 조건에서 count가 +1되는 순간 그 다음 조건문 실행이 너무 빨라서 

time.sleep(1)을 추가하였음.)

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM) #GPIO.BOARD
GPIO.setwarnings(False)

BUTTON= 21
LED_R = 13
LED_G = 19
LED_B = 26

GPIO.setup(BUTTON, GPIO.IN)
GPIO.setup(LED_R, GPIO.OUT)
GPIO.setup(LED_G, GPIO.OUT)
GPIO.setup(LED_B, GPIO.OUT)

count = 0

try:
    while True:
        inputIO = GPIO.input(BUTTON)
        
        if  inputIO == False and count== 0:
            print("RED")
            GPIO.output(LED_R, GPIO.HIGH)
            GPIO.output(LED_G, GPIO.LOW)
            GPIO.output(LED_B, GPIO.LOW)
            time.sleep(1)
            count +=1
        
        elif inputIO == False and count== 1:
             print("GREEN")
             GPIO.output(LED_R, GPIO.LOW)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.LOW)
             time.sleep(1)
             count +=1
             
        elif inputIO == False and count== 2:
             print("BLUE")
             GPIO.output(LED_R, GPIO.LOW)
             GPIO.output(LED_G, GPIO.LOW)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(1)
             count +=1
             
        elif inputIO == False and count== 3:
             print("YELLOW")
             GPIO.output(LED_R, GPIO.HIGH)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.LOW)
             time.sleep(1)
             count +=1
             
        elif inputIO == False and count== 4:
             print("MAGENTA")
             GPIO.output(LED_R, GPIO.HIGH)
             GPIO.output(LED_G, GPIO.LOW)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(1)
             count +=1
        
        elif inputIO == False and count== 5:
             print("CYAN")
             GPIO.output(LED_R, GPIO.LOW)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(1)
             count +=1
        
        elif inputIO == False and count== 6:
             print("WHITE")
             GPIO.output(LED_R, GPIO.HIGH)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(1)
             count +=1
    
        else:
            print("NO LED")
            GPIO.output(LED_R, GPIO.LOW)
            GPIO.output(LED_G, GPIO.LOW)
            GPIO.output(LED_B, GPIO.LOW)     

except KeyboardInterrupt:
    GPIO.output(LED_R, GPIO.LOW)
    GPIO.output(LED_G, GPIO.LOW)
    GPIO.output(LED_B, GPIO.LOW)
    GPIO.cleanup()

 

 

-위의 코드 반복실행

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM) #GPIO.BOARD
GPIO.setwarnings(False)

BUTTON= 4
LED_R = 5
LED_G = 6
LED_B = 13

GPIO.setup(BUTTON, GPIO.IN)
GPIO.setup(LED_R, GPIO.OUT)
GPIO.setup(LED_G, GPIO.OUT)
GPIO.setup(LED_B, GPIO.OUT)

count = 0

try:
    while True:
        inputIO = GPIO.input(BUTTON)
        
        if  inputIO == True and count== 0:
            print("RED")
            GPIO.output(LED_R, GPIO.HIGH)
            GPIO.output(LED_G, GPIO.LOW)
            GPIO.output(LED_B, GPIO.LOW)
            time.sleep(0.2)
            count +=1
        
        elif inputIO == True and count== 1:
             print("GREEN")
             GPIO.output(LED_R, GPIO.LOW)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.LOW)
             time.sleep(0.2)
             count +=1
             
        elif inputIO == True and count== 2:
             print("BLUE")
             GPIO.output(LED_R, GPIO.LOW)
             GPIO.output(LED_G, GPIO.LOW)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(0.2)
             count +=1
             
        elif inputIO == True and count== 3:
             print("YELLOW")
             GPIO.output(LED_R, GPIO.HIGH)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.LOW)
             time.sleep(0.2)
             count +=1
             
        elif inputIO == True and count== 4:
             print("MAGENTA")
             GPIO.output(LED_R, GPIO.HIGH)
             GPIO.output(LED_G, GPIO.LOW)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(0.2)
             count +=1
        
        elif inputIO == True and count== 5:
             print("CYAN")
             GPIO.output(LED_R, GPIO.LOW)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(0.2)
             count +=1
        
        elif inputIO == True and count== 6:
             print("WHITE")
             GPIO.output(LED_R, GPIO.HIGH)
             GPIO.output(LED_G, GPIO.HIGH)
             GPIO.output(LED_B, GPIO.HIGH)
             time.sleep(0.2)
             count = 0
    
        else:
           
            GPIO.output(LED_R, GPIO.LOW)
            GPIO.output(LED_G, GPIO.LOW)
            GPIO.output(LED_B, GPIO.LOW)     

except KeyboardInterrupt:
    GPIO.output(LED_R, GPIO.LOW)
    GPIO.output(LED_G, GPIO.LOW)
    GPIO.output(LED_B, GPIO.LOW)
    GPIO.cleanup()

1. 초음파 센서 사용하기

 

blog.naver.com/roboholic84/220319850312

 

[라즈베리파이 강좌] 라즈베리파이로 초음파센서 사용하기 - python편

이번시간에는 디지털 신호를 사용하는 센서중 하나인 초음파 센서(HC-SR04)를 사용해 보도록 하겠습니...

blog.naver.com

1) 초음파 센서를 이용하여 거리 출력하기 

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

def getDistance():
    GPIO.output(TRIG, False)
    time.sleep(1) #1초마다 값을 냄 
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)
    
    while GPIO.input(ECHO) == 0:
        pulse_start = time.time()
    while GPIO.input(ECHO) == 1:
        pulse_end = time.time()
    
    pulse_duration = pulse_end - pulse_start
    distance= round(pulse_duration*17150,2)
    
    return distance

if __name__ == '__main__':
    try:
        while True:
            distance_value = getDistance()
            if distance_value > 2 and distance_value < 300:
                print("Distance is %.2f cm"%distance_value)
            else:
                print("Out of Range")
    except KeyboardInterrupt:
        GPIO.cleanup()

 

2) 초음파 센서를 이용하여 거리 출력하기 ( out of range: RED LED ON, range: GREEN LED ON) 

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
LED_R = 13 
LED_G = 19

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(LED_R, GPIO.OUT)
GPIO.setup(LED_G, GPIO.OUT)

def getDistance():
    GPIO.output(TRIG, False)
    time.sleep(1) #1초마다 값을 냄 
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)
    
    while GPIO.input(ECHO) == 0:
        pulse_start = time.time()
    while GPIO.input(ECHO) == 1:
        pulse_end = time.time()
    
    pulse_duration = pulse_end - pulse_start
    distance= round(pulse_duration*17150,2)
    
    return distance

if __name__ == '__main__':
    try:
        while True:
            distance_value = getDistance()
            if distance_value > 2 and distance_value < 300:
                print("Distance is %.2f cm"%distance_value)
                GPIO.output(LED_G, GPIO.HIGH)
                GPIO.output(LED_R, GPIO.LOW)
            else:
                print("Out of Range")
                GPIO.output(LED_R, GPIO.HIGH)
                GPIO.output(LED_G, GPIO.LOW)
                
    except KeyboardInterrupt:
       GPIO.output(LED_R, GPIO.LOW)
       GPIO.output(LED_G, GPIO.LOW)
       GPIO.cleanup()

 


2. 온습도 센서 사용하기 

온습도 센서 DHT - 11 (온습도센서에 따라 순서가 다름)

devicemart.blogspot.com/2019/06/dht-11.html

 

[흥프로] 라즈베리파이 실습 예제 온습도 센서 DHT - 11 사용하기

전기/전자부품, 로봇/기계부품, 코딩교육 국내 1위 쇼핑몰 디바이스마트 공식 블로그입니다.

devicemart.blogspot.com

- Adafruit_DHT 라이브러리 설치 

git clone https://github.com/adafruit/Adafruit_Python_DHT.git 

cd Adafruit_Python_DHT

sudo python setup.py install

-코드 입력 (gpio_tem.py 파일)

import time
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 4
try:
    while True :
        h, t = Adafruit_DHT.read_retry(sensor, pin) # h,t-> 습도, 온도/ 순서 바뀌면 값도 바뀜
        if h is not None and t is not None :
            print("Temperature = {0:0.1f}*C Humidity = {1:0.1f}%".format(t, h))
        else :
            print('Read error')
        time.sleep(1)
except KeyboardInterrupt:
    print("Terminated by Keyboard")
 
finally:
    print("End of Program")

-실행 결과 

 

여기까지 하면 python 창에서 실행이 안 됨. 

그래서 

 

www.sharedit.co.kr/posts/8407

 

라즈베리파이4로 온습도 모니터링 해보자

전산실 온습도 모니터링을 라즈베리파이4로 구축한 사용기 올려봅니다.1.목적 : 전산실의 온습도를 웹사이트(내부 경영정보시스템)에서 확인이 필요함. 정밀도는 그닥 필요없음.2....

www.sharedit.co.kr

- 추가로 설치하였음. 

sudo pip3 install Adafruit_DHT

 

 

- sudo pip3 install Adafruit_DHT 설치해줘서 밑에 Adafruit_Python_DHT 폴더 삭제해도 됨 

 


 

+ Recent posts