jetson nano傳感器實驗


1.rgb實驗

import Jetson.GPIO as GPIO
import time


red_pin = 17
green_pin = 18
blue_pin = 27


# 初始化程序
def init_setup():
    GPIO.setmode(GPIO.BCM)    # 采用實際的物理管腳給GPIO口
    GPIO.setwarnings(False)     # 去除GPIO口警告
    GPIO.setup([red_pin,green_pin,blue_pin], GPIO.OUT, initial=0)   # 設置Pin模式為輸出模式,low

# 關閉RGB-LED燈
def all_off():
    GPIO.output(red_pin, GPIO.LOW)    #  設置Pin管腳為低電平(0V)關閉LED
    GPIO.output(green_pin, GPIO.LOW)
    GPIO.output(blue_pin, GPIO.LOW)

def destroy():
    all_off()  # 關閉RGB-LED燈
    GPIO.cleanup()  # 釋放資源

def red_on():
    GPIO.output(red_pin,GPIO.HIGH)
    GPIO.output(green_pin,GPIO.LOW)
    GPIO.output(blue_pin,GPIO.LOW)

def green_on():
    GPIO.output(red_pin,GPIO.LOW)
    GPIO.output(green_pin,GPIO.HIGH)
    GPIO.output(blue_pin,GPIO.LOW)

def blue_on():
    GPIO.output(red_pin,GPIO.LOW)
    GPIO.output(green_pin,GPIO.LOW)
    GPIO.output(blue_pin,GPIO.HIGH)

def all_on():
    GPIO.output(red_pin,GPIO.HIGH)
    GPIO.output(green_pin,GPIO.HIGH)
    GPIO.output(blue_pin,GPIO.HIGH)


init_setup() # 初始化設置函數

if __name__ == '__main__':
    try:
        while 1:
            inp = input('input command: ')
            if inp == 'r':
                red_on()
            elif inp == 'g':
                green_on()
            elif inp == 'b':
                blue_on()
            elif inp == 'a':
                all_on()
            elif inp == 'e':
                destroy()
                break
    except KeyboardInterrupt:
        destroy()
rgb.py

2.七彩燈實驗

# 導入樹莓Pi GPIO庫
import RPi.GPIO as GPIO
# 從time模塊導入sleep函數
from time import sleep

# 定義七彩燈控制管腳
Led_pin = 25
# 暫時忽略警告
GPIO.setwarnings(False)
# 設置GPIO模式作為 GPIO.BCM
GPIO.setmode(GPIO.BCM)
# 將七彩LED引腳作為輸出引腳,並將初始值設置為HIGH(打開)
GPIO.setup(Led_pin, GPIO.OUT,initial=GPIO.HIGH)

def destroy():
    GPIO.output(Led_pin, GPIO.LOW)
    GPIO.cleanup()

try:
    while 1:
        pass
except KeyboardInterrupt:
    destroy()
qicaideng.py

3.OLED實驗

import time

import Adafruit_SSD1306

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

# 128x32顯示器,硬件I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=None, i2c_bus=1, gpio=1)

# 初始化庫。
disp.begin()
# 清除顯示內容
disp.clear()
disp.display()

#為繪圖創建空白圖像。
#確保為1位顏色創建模式為“1”的圖像(單色)
width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# 載入默認字體
font = ImageFont.load_default()

# 獲取要在圖像上繪制的繪圖對象。
draw = ImageDraw.Draw(image)

def oled_main(text):
    try:
        while True:
            # 畫一個黑色填充框清除圖像。
            draw.rectangle((0,0,width,height), outline=0, fill=0)
            draw.text((50,10),text,font=font,fill=255)

            # 顯示圖像。
            disp.image(image)
            disp.display()
            time.sleep(3)
    except KeyboardInterrupt:
        disp.clear()
        disp.display()

if __name__ == '__main__':
    oled_main('ZLTech')
OLED.py

4.蜂鳴器實驗

import RPi.GPIO as GPIO
import time

pin = 6    # 有源蜂鳴器管腳定義

# GPIO設置函數
def init_setup():
    GPIO.setmode(GPIO.BCM)  # 采用實際的物理管腳給GPIO口
    GPIO.setwarnings(False)   # 關閉GPIO警告提示
    GPIO.setup(pin, GPIO.OUT, initial=0)  # 設置有源蜂鳴器管腳為輸出模式

#  打開蜂鳴器
def beep_on():
    GPIO.output(pin, GPIO.HIGH)  # 蜂鳴器為高電平觸發,所以使能蜂鳴器讓其發聲

# 關閉蜂鳴器
def beep_off():
    GPIO.output(pin, GPIO.LOW) # 蜂鳴器設置為低電平,關閉蜂鳥器

# 控制蜂鳴器鳴叫
def beep(x):
    beep_on()     # 打開蜂鳴器控制
    time.sleep(x)  # 延時時間
    beep_off()    # 關閉蜂鳴器控制
    time.sleep(x)   # 延時時間

# 循環函數
def loop():
    while True:
        beep(0.5) # 控制蜂鳴器鳴叫,延時時間為500mm

def destroy():
    GPIO.output(pin, GPIO.LOW) # 關閉蜂鳴器鳴叫
    GPIO.cleanup()  # 釋放資源


# 程序入口
if __name__ == '__main__': 
    init_setup() # 設置GPIO管腳
    try:  # 檢測異常
        loop()      # 調用循環函數
    except KeyboardInterrupt:  # 當按下Ctrl+C時,將執行destroy()子程序
        destroy()    # 釋放資源
youyuan_beep.py
import RPi.GPIO as GPIO
import time

output_pin = 33  # 無源蜂鳴器管腳

# 音譜定義
Tone_CL = [0, 131, 147, 165, 175, 196, 211, 248] # 低C音符的頻率
Tone_CM = [0, 262, 294, 330, 350, 393, 441, 495] # 中C音的頻率
Tone_CH = [0, 525, 589, 661, 700, 786, 882, 990] # 高C音符的頻率

# 第一首歌音譜
song_1 = [ Tone_CM[3], Tone_CM[5], Tone_CM[6], Tone_CM[3], Tone_CM[2], Tone_CM[3], Tone_CM[5], Tone_CM[6], 
                                    Tone_CH[1], Tone_CM[6], Tone_CM[5], Tone_CM[1], Tone_CM[3], Tone_CM[2], Tone_CM[2], Tone_CM[3], 
                                    Tone_CM[5], Tone_CM[2], Tone_CM[3], Tone_CM[3], Tone_CL[6], Tone_CL[6], Tone_CL[6], Tone_CM[1],
                                    Tone_CM[2], Tone_CM[3], Tone_CM[2], Tone_CL[7], Tone_CL[6], Tone_CM[1], Tone_CL[5] ]

# 第1首歌的節拍,1表示1/8拍
beat_1 = [ 1, 1, 3, 1, 1, 3, 1, 1,
                                   1, 1, 1, 1, 1, 1, 3, 1, 
                                   1, 3, 1, 1, 1, 1, 1, 1, 
                                   1, 2, 1, 1, 1, 1, 1, 1, 
                                   1, 1, 3]

# 第二首歌音譜
song_2 = [Tone_CM[1], Tone_CM[1], Tone_CM[1], Tone_CL[5], Tone_CM[3], Tone_CM[3], Tone_CM[3], Tone_CM[1],
                                   Tone_CM[1], Tone_CM[3], Tone_CM[5], Tone_CM[5], Tone_CM[4], Tone_CM[3], Tone_CM[2], Tone_CM[2], 
                                   Tone_CM[3], Tone_CM[4], Tone_CM[4], Tone_CM[3], Tone_CM[2], Tone_CM[3], Tone_CM[1], Tone_CM[1], 
                                   Tone_CM[3], Tone_CM[2], Tone_CL[5], Tone_CL[7], Tone_CM[2], Tone_CM[1]]

# 第2首歌的節拍,1表示1/8拍
beat_2 = [ 1, 1, 2, 2, 1, 1, 2, 2, 
                                   1, 1, 2, 2, 1, 1, 3, 1, 
                                   1, 2, 2, 1, 1, 2, 2, 1, 
                                   1, 2, 2, 1, 1, 3 ]

# GPIO設置函數
def init_setup():
    GPIO.setmode(GPIO.BOARD)        # 采用實際的物理管腳給GPIO口
    GPIO.setwarnings(False)         # 關閉GPIO警告提示
    GPIO.setup(output_pin, GPIO.OUT, initial=GPIO.HIGH) # 設置無源蜂鳴器管腳為輸出模式
    global pwm_key     # 指定一個全局變量來替換gpi.pwm
    pwm_key = GPIO.PWM(output_pin, 440) # 設置初始頻率為440
    pwm_key.start(50)    # 按50%工作定額啟動蜂鳴器引腳。

# 循環函數
def loop():
    while True:
        #    播放第一首歌音樂
        for i in range(1, len(song_1)):     # 播放第一首歌
            pwm_key.ChangeFrequency(song_1[i]) # 設置歌曲音符的頻率
            time.sleep(beat_1[i] * 0.5)     # 延遲一個節拍* 0.5秒的音符
        time.sleep(1)       # 等待下一首歌。
        #    播放第二首歌音樂 
        for i in range(1, len(song_2)):     # 播放第二首歌
            pwm_key.ChangeFrequency(song_2[i]) # 設置歌曲音符的頻率
            time.sleep(beat_2[i] * 0.5)     # 延遲一個節拍* 0.5秒的音符

# 釋放資源函數
def destory():
    pwm_key.stop()  # 停止蜂鳴器
    GPIO.output(output_pin, 1)  # 設置蜂鳴器管腳為高電平
    GPIO.cleanup()   # 釋放資源

# 程序入口
if __name__ == '__main__':
    init_setup()
    try:
        loop()
    except KeyboardInterrupt:   # 當按下Ctrl+C時,將執行destroy()子程序
        destory()      # 釋放資源
wuyuan_beep.py

5.按鍵控制有源蜂鳴器

import RPi.GPIO as GPIO
import time

key = 26
#key = 19
beep_pin = 6

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

def on():
    GPIO.output(beep_pin, 1)

def off():
    GPIO.output(beep_pin, 0)

def destroy():
    off()
    GPIO.cleanup()

def test(ver):
    if ver == 0:
        on()
    else:
        off()

if __name__ == '__main__':
    try:
        GPIO.setup(key, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(beep_pin, GPIO.OUT, initial=0)
        while 1:
            GPIO.setup(key, GPIO.IN)

            ver = GPIO.input(key)
            GPIO.setup(key, GPIO.OUT, initial=1)
            test(ver)
    except KeyboardInterrupt:
        destroy()
button_beep.py

6.超聲波實驗

import RPi.GPIO as GPIO
import time
import OLED

TRIG_pin = 11  # 超聲波模塊Trig控制管腳, BCM 17 18
ECHO_pin = 12  # 超聲波模塊Echo控制管腳

# 超聲波模塊初始化工作
def init_setup():
    GPIO.setmode(GPIO.BOARD)      # 采用實際的物理管腳給GPIO口
    GPIO.setwarnings(False)       # 忽略GPIO操作注意警告
    GPIO.setup(TRIG_pin, GPIO.OUT) # Tring設置為輸出模式
    GPIO.setup(ECHO_pin, GPIO.IN)  # Echo設置為輸入模式

# 超聲波計算距離函數
def distance():
    GPIO.output(TRIG_pin, 0)  # 開始起始
    time.sleep(0.000002)  # 延時2us
    GPIO.output(TRIG_pin, 1)  # 超聲波啟動信號,延時10us
    time.sleep(0.00001)    # 發出超聲波脈沖
    GPIO.output(TRIG_pin, 0)  # 設置為低電平

    while GPIO.input(ECHO_pin) == 0: # 等待回傳信號
        us_a = 0
    us_time1 = time.time()      # 獲取當前時間
    while GPIO.input(ECHO_pin) == 1: # 回傳信號截止信息
        us_a = 1
    us_time2 = time.time()     # 獲取當前時間
    during = us_time2 - us_time1          # 轉換微秒級的時間

    # 聲速在空氣中的傳播速度為340m/s, 超聲波要經歷一個發送信號和一個回波信息
    # 計算公式如下所示:
    return during * 340 / 2 * 100        # 求出距離

# 循環函數
def loop():
    while True:
        us_dis = distance()   # 獲取超聲波計算距離
        OLED.oled_main(us_dis+'cm')       # 打印超聲波距離值
        time.sleep(0.3)  # 延時300ms 

# 資源釋放函數
def destroy():
    GPIO.cleanup() # 釋放資源

# 程序入口
if __name__ == "__main__":
    init_setup() # 調用初始化函數
    try:
        loop() # 調用循環函數
    except KeyboardInterrupt: # 當按下Ctrl+C時,將執行destroy()子程序
        destroy() # 釋放資源
    else:
        pass
chaoshengbo.py

7.光敏實驗

import PCF8591 as ADC
import RPi.GPIO as GPIO
import time

DO_pin = 17     # 光敏傳感器管腳
GPIO.setmode(GPIO.BCM) # 管腳映射,采用BCM編碼
GPIO.setwarnings(False)

# 初始化工作
def init_setup():
    ADC.setup(0x48)      # 設置PCF8591模塊地址
    GPIO.setup(DO_pin, GPIO.IN) # 光敏傳感器,設置為輸入模式

# 循環函數
def loop():
    #status = 1 # 狀態值
    # 無限循環
    while True:
        print ('Photoresistor Value: ', ADC.read(0)) # 讀取AIN0的值,獲取光敏模擬量值
        time.sleep(0.2)          # 延時200ms

# 程序入口
if __name__ == '__main__':
    try:
        init_setup() # 地址設置
        loop()  # 調用無限循環
    except KeyboardInterrupt: 
        pass
guangmin.py

8.PCF8591

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 說明:這是一個PCF8591模塊的程序。
#      警告:模擬輸入不能超過3.3V!
# 在這個程序中,我們使用電位計進行模擬輸入和控制一個模擬電壓
# 的LED燈,你可以導入這個程序到另一個程序中使用:
# import PCF8591 as ADC
# ADC.Setup(Address)  # 通過 sudo i2cdetect -y -1 可以獲取到IIC的地址
# ADC.read(channal)    # 通道選擇范圍為0-3
# ADC.write(Value)    # 值的范圍為:0-255
#####################################################
import smbus
import time

# 對應比較舊的版本如RPI V1 版本,則 "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

#通過 sudo i2cdetect -y -1 可以獲取到IIC的地址
def setup(Addr):
    global address
    address = Addr

# 讀取模擬量信息
def read(chn): #通道選擇,范圍是0-3之間
    try:
        if chn == 0:
            bus.write_byte(address,0x40)
        if chn == 1:
            bus.write_byte(address,0x41)
        if chn == 2:
            bus.write_byte(address,0x42)
        if chn == 3:
            bus.write_byte(address,0x43)
        bus.read_byte(address) # 開始進行讀取轉換
    except Exception as e:
        print ("Address: %s" % address)
        print (e)
    return bus.read_byte(address)

# 模塊輸出模擬量控制,范圍為0-255
def write(val):
    try:
        temp = val # 將數值賦給temmp 變量
        temp = int(temp) # 將字符串轉換為整型
        # 在終端上打印temp以查看,否則將注釋掉
        bus.write_byte_data(address, 0x40, temp)
    except Exception as e:
        print ("Error: Device address: 0x%2X" % address)
        print (e)

if __name__ == "__main__":
    setup(0x48)
    while True:
        print ('AIN0 = ', read(0))
        print ('AIN1 = ', read(1))
        tmp = read(0)
        tmp = tmp*(255-125)/255+125 # 低於125時LED不會亮,所以請將“0-255”轉換為“125-255”
        write(tmp)
#        time.sleep(0.3)
PCF8591.py
# 由於Jetson Nano GPIO 口不帶模擬量輸出,所以可以擴展出模擬量輸入模塊
import PCF8591 as ADC
import time

# 模塊地址設置
def init_setup():
    ADC.setup(0x48)  # 設置PCF8591模塊地址

# 無限循環
def loop():
    while True:
        print ("AIN0=%d"%ADC.read(0)) #讀取AIN0的數值,插上跳線帽之后,采用的是內部的電位器
        time.sleep(0.5)
        ADC.write(ADC.read(0)) # 控制AOUT輸出電平控制LED燈

# 異常處理函數
def destroy():
    ADC.write(0) #AOUT輸出為0

#程序入口
if __name__ == "__main__":
    try:
        init_setup() #地址設置
        loop()    # 調用無限循環
    except KeyboardInterrupt:
        destroy() #釋放AOUT端口
PCF8591AD_control.py

9.MPU6050實驗

# 說明:驅動三軸加速度、陀螺儀姿態傳感器
import smbus                    # 導入I2C的SMBus模塊
from time import sleep          # 導入延時函數

# 一些MPU6050寄存器及其地址
PWR_MGMT_1   = 0x6B
SMPLRT_DIV   = 0x19
CONFIG       = 0x1A
GYRO_CONFIG  = 0x1B
INT_ENABLE   = 0x38
ACCEL_XOUT_H = 0x3B
ACCEL_YOUT_H = 0x3D
ACCEL_ZOUT_H = 0x3F
GYRO_XOUT_H  = 0x43
GYRO_YOUT_H  = 0x45
GYRO_ZOUT_H  = 0x47

# MPU 6050 初始化工作
def MPU_Init():
    # 寫入抽樣速率寄存器
    zl_bus.write_byte_data(device_address, SMPLRT_DIV, 7)
    # 寫入電源管理寄存器
    zl_bus.write_byte_data(device_address, PWR_MGMT_1, 1)
    # 寫入配置寄存器
    zl_bus.write_byte_data(device_address, CONFIG, 0)
    # 寫入陀螺配置寄存器
    zl_bus.write_byte_data(device_address, GYRO_CONFIG, 24)
    # 寫中斷使能寄存器
    zl_bus.write_byte_data(device_address, INT_ENABLE, 1)

# 讀取MPU6050數據寄存器
def read_data(addr):
    # 加速度值和陀螺值為16位
    high = zl_bus.read_byte_data(device_address, addr)
    low =  zl_bus.read_byte_data(device_address, addr+1)
    # 連接更高和更低的值
    value = ((high << 8) | low)
    # 從mpu6050獲取有符號值
    if(value > 32768):
        value = value - 65536
    return value
 
zl_bus = smbus.SMBus(1)    # 或bus = smbus.SMBus(0)用於較老的版本板
device_address = 0x68   # MPU6050設備地址
MPU_Init()             # 初始化MPU6050
# 打印提示信息
print ("init ok")

# 無限循環
while True:
    # 讀取加速度計原始值
    acc_x = read_data(ACCEL_XOUT_H)
    acc_y = read_data(ACCEL_YOUT_H)
    acc_z = read_data(ACCEL_ZOUT_H)

    # 讀陀螺儀原始值
    gyro_x = read_data(GYRO_XOUT_H)
    gyro_y = read_data(GYRO_YOUT_H)
    gyro_z = read_data(GYRO_ZOUT_H)

    # 全刻度范圍+/- 250度℃,根據靈敏度刻度系數
    Ax = acc_x/16384.0
    Ay = acc_y/16384.0
    Az = acc_z/16384.0

    Gx = gyro_x/131.0
    Gy = gyro_y/131.0
    Gz = gyro_z/131.0

    # 打印出MPU相關信息
    print ("Gx=%.2f" %Gx, u'\u00b0'+ "/s", "\tGy=%.2f" %Gy, u'\u00b0'+ "/s", "\tGz=%.2f" %Gz, u'\u00b0'+ "/s", "\tAx=%.2f g" %Ax, "\tAy=%.2f g" %Ay, "\tAz=%.2f g" %Az)
    sleep(1)  # 延時1s
MPU6050_test.py

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM