---
# System prepended metadata

title: 使用Jetson nano進行yolov8推理，並控制伺服馬達
tags: [Documentation, Templates]

---

---
title: 'Project documentation template'
disqus: hackmd
---



[TOC]

## 啟用Docker容器
在本機終端上執行此程式
```gherkin=
sudo docker run -it \
    --privileged \
    --device /dev/gpiochip0 \
    --runtime=nvidia \
    --device=/dev/video0:/dev/video0 \
    --ipc=host \
    -v /home/jetson-nano/Desktop:/data \
    -e DISPLAY=$DISPLAY \
    -v /tmp/.X11-unix:/tmp/.X11-unix \
    ultralytics/ultralytics:latest-jetson-jetpack4
```

建立python腳本
---
自行選擇習慣的腳本編輯器，這裡使用nano
```gherkin=
import cv2
from ultralytics import YOLO
import Jetson.GPIO as GPIO
import time
import threading

# Load the YOLOv8 model
model = YOLO("yolov8n.engine")

# Set up GPIO for servo control
GPIO.setmode(GPIO.BCM)
servo_pin = 13
GPIO.setup(servo_pin, GPIO.OUT)
pwm = GPIO.PWM(servo_pin, 50)  # 50Hz
pwm.start(0)

# Define duty cycles for 0 and 90 degrees
duty_cycle_90 = 7.5
duty_cycle_0 = 2.5

# Define labels and confidence threshold
labels = ["mouse", "keyboard"]
confidence_threshold = 0.7

# Function to change servo duty cycle
def set_servo_duty_cycle(duty_cycle, duration=2):
    pwm.ChangeDutyCycle(duty_cycle)
    time.sleep(duration)

# Open the video file
cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("Error: Could not open webcam.")
    exit()

# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLOv8 tracking on the frame, persisting tracks between frames
        try:
            results = model.track(frame, persist=True)
        except Exception as e:
            print(f"Error during tracking: {e}")
            break

        # Visualize the results on the frame
        annotated_frame = results[0].plot()

        # Process results and perform actions based on detected labels
        for result in results:
            for box in result.boxes:
                label_index = int(box.cls[0].item())  # Label index
                confidence = box.conf[0].item()  # Confidence score

                # Ensure result.names is accessible
                if hasattr(result, 'names') and label_index < len(result.names):
                    label = result.names[label_index]  # Label name

                    # Trigger servo motor based on label
                    if label == labels[0] and confidence > confidence_threshold:
                        threading.Thread(target=set_servo_duty_cycle, args=(duty_cycle_90,)).start()
                    elif label == labels[1] and confidence > confidence_threshold:
                        threading.Thread(target=set_servo_duty_cycle, args=(duty_cycle_0,)).start()

        # Display the annotated frame
        cv2.imshow("YOLOv8 Tracking", annotated_frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
pwm.stop()
GPIO.cleanup()
```

下載Jetson.GPIO套件
---
```gherkin
apt install Jetson.GPIO
```
```gherkin
Name: Jetson.GPIO
Version: 2.1.6
Summary: A module to control Jetson GPIO channels
Home-page: https://github.com/NVIDIA/jetson-gpio
Author: NVIDIA
Author-email: linux-tegra-bugs@nvidia.com
License: MIT
Location: /usr/local/lib/python3.8/dist-packages
Requires: 
Required-by: 
```
測試馬達用腳本
```gherkin

import Jetson.GPIO as GPIO
import time

# 
GPIO.setmode(GPIO.BCM)

#    
servo_pin = 13

#      
GPIO.setup(servo_pin, GPIO.OUT)

#     
pwm = GPIO.PWM(servo_pin, 50)  # 50Hz

# 
pwm.start(0)


duty_cycle_90 = 7.5  # 90   
duty_cycle_0 = 2.5   # 0    

try:
    #   
    time.sleep(1)
    pwm.ChangeDutyCycle(duty_cycle_90)
    time.sleep(2)  # 

    #
    pwm.ChangeDutyCycle(duty_cycle_0)
    time.sleep(1)  #  

finally:
    #      
    pwm.stop()
    GPIO.cleanup()
```
設定PWM
```gherkin
sudo /opt/nvidia/jetson-io/jetson-io.py
```


