라즈베리파이 환경설정하기

bakjinho·2024년 10월 6일

1. Raspberry pi 설치 네트워크 설정 방법

1. 설치 설정

  1. Host PC에서 Host PC에서 Raspberry Pi imager v1.6.1 download 후 실행
  2. 라즈베리 파이의 SD카드를 Host PC에 입력 후 imager를 사용해 설치
  3. 운영체제 선택, 저장소 선택, 유저 정보 입력(id, passwd)
  4. 다운로드 후 SD카드 내 boot 디렉토리에 아래와 같이 설정
    • cmdline.txt에서 ext4 가음 ip=... 세팅
    • ssh이름의 txt파일(ssh.txt) 생성

2. 네트워크 설정

  1. 사용자 환경에 맞는 ip, subnet, gateway, DNS를 Host PC에 설정(이더넷 설정)
  2. Host PC와 라즈베리 파이를 랜선으로 다이렉트 연결
  3. cmdline.txt에서 위에서 작성한 ip=...을 삭제
  4. 라즈베리 파이와 연결된 공유기에 들어가 할당된 ip를 확인 후 ssh로 연결

(AP 설정) 유선으로 외부 인터넷을 연결하는 방법

  1. direct 방식으로 별도의 client로 접속하지 않을 경우
    • 사용자 장소에 할당된 IP를 각각 RBP에 할당
  2. 공유기를 사용하는 경우 다음과 같은 공유기 세팅
    1. iptime 공유기 접속 → PC에서 유선으로 공유기 연결 후 브라우저에서 192.168.0.1 접속
    2. 인터넷 설정을 동적 IP방식으로 아래 사진과 같이 설정
    3. 고급설정 → 네트워크설정 정보 → 내부 네트워크 설정에서 내부 IP 주소를 공유기의 백본 케이블의 공유기 IP 대역과 다르게 설정
    4. 이후 PC 및 RBP를 내부 IP주소의 하나로 설정
    5. DHCP 서버설정에서와 같은 DNS IP 주소를 client PC, RBP에 설정(RBP일 경우 /etc/resov.conf에 기입)

3. Raspberry Pi OS 설정

스페이스바 ←선택 키

  • sudo raspi-config
    • localization
      • en_uS.UTF-8 UTF-8
      • timezone, Asia Seoul
      • Keyboard setting
      • WLAN country: GB
    • interface
      • Camera enable
      • VNC enable
      • SPI enable
      • Serial Port enable
    • Advanced
      • A1(Expnad FS Ensure) 선택 ⇒ Pi OS가 SD 카드를 전부 다 사용하도록 설정
    • Update
  • Paspberry Pi SW 저장소 update
    • sudo apt update
    • sudo apt upgrade
  • web browser 한글 폰트 처리
    • sudo apt install -y fonts-unfonts-core

(네트워크 관리자)

  • client PC, RBP 세팅, 유/무선 네트워크 설치 이후 Hadoop 설치

4. wringpi library 설치

  • sudo apt-get purge wiringpi ⇒ 기존 wiringpi 제거
  • hash -r
  • sudo apt-get install git-core
  • cd ~
  • git clone https://github.com/WiringPi/WiringPi
  • cd ~/WiringPi
  • git pull origin
  • ./build
  • gpio -v ⇒ 버전 확인

5. 보드 test 진행

중요 ) 보드에 전원을 넣기 전에 Raspberry Pi down 후 넣기

  • gpio readall ⇒ 보드 핀 별 상태 확인

    • BCM ⇒ cpu에서 할당한 번호
    • wPi ⇒ wiringapi lib에서 할당한 번호
    • gpio -g mode 6 out ⇒ wPi가 6번인 것을 output으로 전환
    • gpio -g write 6 1(0) ⇒ 1 : 켜기 2 : 끄기

6. samba 설치

윈도우에서 리눅스, 유닉스를 연결해주는 프로그램

  • samba 패키지 설치
    • sudo apt install samba samba-common-bin
      error 발생 시) sudo apt-get update후 재 실행
    • GUI에서 no 선택
  • 사용자 추가 및 암호 설정
    • sudo smbpasswd -a [id][password]
  • smb.conf 파일 수정
    • sudo vi /etc/samba/smb.conf
      • [pi]
        comment = rpi smaba server by username ← 설명
        path = /home/pi
        valid user = pi
        writable = yes
        browseable = yes
  • samba 서버 재실행
    • sudo service smbd restart
  • host PC 접속
    • cmd 창에 net use z: \192.168.0.7\pi /user:[id][password] 입력
    • 내컴퓨터 우클릭 → 네트워크 드라이브 연결에서 \192.168.0.7[id]으로 연결

7. SFTP로 파일 다운로드

  • 터미널에 sftp [id]@[대상 ip] 입력
  • 패스워드 입력
  • get [디렉토리 경로]

또는 filezilla 사용


2. 센서 / 엑추에이터 코드 빌드

1. 센서 빌드

  • Smart-IOT/all_sensortest
    • gunzip -d *.gz
      tar -xvf [파일명].tar
      
      # test.tar 파일 압축을 푼다면
      # tar -xvf test.tar
      tar -zxvf [파일명].tar.gz
      
      # test.tar.gz 파일 압축풀기
      # tar -zxvf test.tar.gz

2. 엑추에이터 빌드

  • Smart-IOT/all_actutest

3. 카메라 제어

  • sudo apt install mplayer
  • sudo apt install libmp3lame-dev
  • sudo apt install libcamera-apps

  • sudo vi config.txt
[cm5]
dtoverlay=imx219

# 위 내용 추가
  • 사진 촬영
    • libcamera-jpeg -o test.jpg —qt-preview
  • 동영상
    • libcamera-vid -t 10000 -o test.h264 —qt-preview
      (-t 옵션은 ms가 단위로 1000당 1초)
    • ffmpeg -r 30 -i test.h264 -vcodec copy test.mkv
      (동영상 인코딩)

4. 동영상 스트리밍

  • sudo apt install -y python3-picamera2
  • vi camera.py
    #!/usr/bin/python3
    
    # This is the same as mjpeg_server.py, but uses the h/w MJPEG encoder.
    
    import io
    import logging
    import socketserver
    from http import server
    from threading import Condition
    
    from picamera2 import Picamera2
    from picamera2.encoders import MJPEGEncoder
    from picamera2.outputs import FileOutput
    
    PAGE = """\
    <html>
    <head>
    <title>picamera2 MJPEG streaming demo</title>
    </head>
    <body>
    <h1>Picamera2 MJPEG Streaming Demo</h1>
    <img src="stream.mjpg" width="640" height="480" />
    </body>
    </html>
    """
    
    class StreamingOutput(io.BufferedIOBase):
        def __init__(self):
            self.frame = None
            self.condition = Condition()
    
        def write(self, buf):
            with self.condition:
                self.frame = buf
                self.condition.notify_all()
    
    class StreamingHandler(server.BaseHTTPRequestHandler):
        def do_GET(self):
            if self.path == '/':
                self.send_response(301)
                self.send_header('Location', '/index.html')
                self.end_headers()
            elif self.path == '/index.html':
                content = PAGE.encode('utf-8')
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.send_header('Content-Length', len(content))
                self.end_headers()
                self.wfile.write(content)
            elif self.path == '/stream.mjpg':
                self.send_response(200)
                self.send_header('Age', 0)
                self.send_header('Cache-Control', 'no-cache, private')
                self.send_header('Pragma', 'no-cache')
                self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
                self.end_headers()
                try:
                    while True:
                        with output.condition:
                            output.condition.wait()
                            frame = output.frame
                        self.wfile.write(b'--FRAME\r\n')
                        self.send_header('Content-Type', 'image/jpeg')
                        self.send_header('Content-Length', len(frame))
                        self.end_headers()
                        self.wfile.write(frame)
                        self.wfile.write(b'\r\n')
                except Exception as e:
                    logging.warning(
                        'Removed streaming client %s: %s',
                        self.client_address, str(e))
            else:
                self.send_error(404)
                self.end_headers()
    
    class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
        allow_reuse_address = True
        daemon_threads = True
    
    picam2 = Picamera2()
    picam2.configure(picam2.create_video_configuration(main={"size": (640, 480)}))
    output = StreamingOutput()
    picam2.start_recording(MJPEGEncoder(), FileOutput(output))
    
    try:
        address = ('', 8000)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        picam2.stop_recording()
  • ifconfig (자신의 ip주소 확인하기)
  • python3 camera.py
  • 웹브라우저로 http://[ip주소]:8000 접속
profile
hello world!

2개의 댓글

comment-user-thumbnail
2024년 10월 6일

좋은 글 감사합니다!

1개의 답글