1. 程式人生 > >利用樹莓派漏極輸出控制電機 Using Raspberry Pi open drain output GPIO to control a moter

利用樹莓派漏極輸出控制電機 Using Raspberry Pi open drain output GPIO to control a moter

  • Keyword關鍵字

Raspberry Pi樹莓派, GPIO 通用IO, open drain output漏極輸出

  • Motivation動機

專案中有一個pwm控制的電機,需要漏極開路[8]( An open collector is a common type of output found on many integrated circuits (IC), which behaves like a switch that is either connected to ground or disconnected.

)作為輸入。控制端採用raspberry pi3.

也就是說需要raspberry pi3輸出一個漏極開路的PWM訊號

然而在raspberry pi3中沒有現成的解決方案提供漏極開路輸出pwm訊號[5]

找到RPi.GPIO.PUD_OFF功能[7](輸入高阻,相當於斷開),於是我們通過輸入高阻,輸出低電平和延時自行搭建漏極開路輸出pwm訊號。

  • Precondition前提

raspberry pi3+(2018-10-09-raspbian-stretch, raspberry pi基本操作超出本文件範圍,請參考[1])

RPi.GPIO[2](安裝 pip install RPi.GPIO, 關於pip參見[3] )

python3

  • Circuit Diagram電路

  • Code程式碼

程式碼主要參考[4],如果python2.x,請將input()改為raw_input()

import RPi.GPIO as GPIO
import time
pwm_pin =4
GPIO.setmode(GPIO.BCM)

def buzz(pitch, duration, dutyratio):
    period = 1.0 / pitch
    delay = period * dutyratio
    cycles = int(duration * pitch)
    for i in range(cycles):
        GPIO.setup(pwm_pin, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
        time.sleep(delay)        
        GPIO.setup(pwm_pin, GPIO.OUT)
        GPIO.output(pwm_pin, False)
        time.sleep(period-delay)
        
while True:
    pitch_s = input("Enter Pitch (1 to 1000): ")
    pitch = float(pitch_s)
    duration_s = input("Enter Duration (seconds): ")
    duration = float(duration_s)
    dutyratio_s = input("Enter dutyratio (>0,<1): ")
    dutyratio = float(dutyratio_s)    
    buzz(pitch, duration,dutyratio)
  • Reference參考文獻
  1. https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up
  2. https://pypi.org/project/RPi.GPIO/
  3. https://pypi.org/project/pip/
  4. Raspberry.Pi.Cookbook.pdf,Simon Monk,9.3. Make a Buzzing Sound
  5. https://electronicshobbyists.com/raspberry-pi-pwm-tutorial-control-brightness-of-led-and-servo-motor/ 
  6. https://learn.sparkfun.com/tutorials/raspberry-gpio/all
  7. https://www.programcreek.com/python/example/98873/RPi.GPIO.PUD_OFF
  8. https://en.wikipedia.org/wiki/Open_collector