2019年6月5日 星期三

Raspberry Pi筆記:Python控制74HC595晶片

基本原理:

74HC595晶片透過三個輸入針腳來產生1與0給74HC595晶片,晶片會將最新輸入的值塞在8個位元的最前面,原先在晶片的值則往後位移。晶片紀錄的8個值分別透過QA~QH輸出。
輸入值的方式,是透過變動SERRCLK、SRCLK三個針腳的電壓達成。
參閱ref.1 page.2
- SRCLK電壓由 低 ➡  變化時會依據SER針腳的電壓狀態產生一個值
- 當SER為高電壓時,會產生1;當SER為低電壓時,會產生0
- 最後,當RCLK電壓由 低 ➡  變化時會將所有產生的值塞到8位元紀錄當中

接線:

QBLED 2VCC3.3V
QCLED 3QALED 1
QDLED 4SERGPIO#16
QELED 5OEGND
QFLED 6RCLKGPIO#20
QGLED 7SRCLKGPIO#21
QHLED 8SRCLR3.3V
GNDGNDQH'
74HC595允許電壓從3V到6V,可以放心使用5V作為工作電壓

Python程式:

import RPi.GPIO as GPIO
import time

SRCLK = 21
RCLK = 20
SER = 16

# init
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

GPIO.setup(SRCLK, GPIO.OUT)
GPIO.setup(RCLK, GPIO.OUT)
GPIO.setup(SER, GPIO.OUT)
GPIO.output(SER, GPIO.LOW)
GPIO.output(SRCLK, GPIO.LOW)
GPIO.output(RCLK, GPIO.LOW)

# mode 1: all 1
GPIO.output(SER, GPIO.HIGH)
for i in range(8):
  GPIO.output(SRCLK, GPIO.HIGH)
  GPIO.output(SRCLK, GPIO.LOW)
GPIO.output(RCLK, GPIO.HIGH)
GPIO.output(RCLK, GPIO.LOW)
time.sleep(1)

# mode 2: all 0
GPIO.output(SER, GPIO.LOW)
for i in range(8):
  GPIO.output(SRCLK, GPIO.HIGH)
  GPIO.output(SRCLK, GPIO.LOW)
GPIO.output(RCLK, GPIO.HIGH)
GPIO.output(RCLK, GPIO.LOW)
time.sleep(1)

# mode 3: A ~ G to 1 sequentially
GPIO.output(SER, GPIO.HIGH)
for i in range(8):
  GPIO.output(SRCLK, GPIO.HIGH)
  GPIO.output(SRCLK, GPIO.LOW)
  GPIO.output(RCLK, GPIO.HIGH)
  GPIO.output(RCLK, GPIO.LOW)
  time.sleep(0.5)

# mode 4: A ~ G to 0 sequentially
GPIO.output(SER, GPIO.LOW)
for i in range(8):
  GPIO.output(SRCLK, GPIO.HIGH)
  GPIO.output(SRCLK, GPIO.LOW)
  GPIO.output(RCLK, GPIO.HIGH)
  GPIO.output(RCLK, GPIO.LOW)
  time.sleep(0.5)

# mode 5: 0 & 1 crossing sequence
mode = GPIO.HIGH
for i in range(8):
  GPIO.output(SER, mode)
  GPIO.output(SRCLK, GPIO.HIGH)
  GPIO.output(SRCLK, GPIO.LOW)
  GPIO.output(RCLK, GPIO.HIGH)
  GPIO.output(RCLK, GPIO.LOW)
  GPIO.output(RCLK, GPIO.HIGH)
  GPIO.output(RCLK, GPIO.LOW)
  if mode == GPIO.HIGH:
    mode = GPIO.LOW
  else:
    mode = GPIO.HIGH
  time.sleep(0.5)
GPIO.output(SER, GPIO.LOW)
for i in range(8):
  GPIO.output(SRCLK, GPIO.HIGH)
  GPIO.output(SRCLK, GPIO.LOW)
  GPIO.output(RCLK, GPIO.HIGH)
  GPIO.output(RCLK, GPIO.LOW)
  time.sleep(0.5)

程式下載:

https://github.com/1412chen/rpi_learning/tree/master/74HC595N
- led.py: 控制LED交互閃爍

參考:

1. https://www.ti.com/lit/ds/symlink/cd74hc595.pdf
2. https://circuitdigest.com/microcontroller-projects/raspberry-pi-74hc595-shift-register-tutorial

沒有留言:

張貼留言