遙控(其實是搖桿控制)電燈(2x3矩陣)

最後編輯:2016-01-06 建立:2015-12-31 歷史紀錄

又名:阿嬤復健器

  • import RPi.GPIO as GPIO
  • import time
  • import spidev
  • import os
  • GPIO.setmode(GPIO.BCM)
  • GPIO.setwarnings(False)
  • pins = [[24,18,14],[25,23,15]]
  • x=1
  • y=1
  • for group in pins:
  • for each in group:
  • GPIO.setup(each, GPIO.OUT)
  • GPIO.output(each, False)
  • def all_off():
  • for group in pins:
  • for each in group:
  • GPIO.output(each, False)
  • def isLeft():
  • return True if vrx_pos < 100 else False
  • def isRight():
  • return True if vrx_pos > 900 else False
  • def isUp():
  • return True if vry_pos < 100 else False
  • def isDown():
  • return True if vry_pos > 900 else False
  • def moveX(x,y):
  • all_off()
  • GPIO.output(pins[y%2][x%3], True)
  • def moveY(x,y):
  • all_off()
  • GPIO.output(pins[y%2][x%3], True)
  • # Open SPI bus
  • spi = spidev.SpiDev()
  • spi.open(0,0)
  • # Function to read SPI data from MCP3008 chip
  • # Channel must be an integer 0-7
  • def ReadChannel(channel):
  • adc = spi.xfer2([1, (8+channel)<<4, 0])
  • data = ((adc[1]&3) << 8) + adc[2]
  • return data
  • # Define sensor channels
  • # (channels 3 to 7 unused)
  • swt_channel = 0
  • vrx_channel = 1
  • vry_channel = 2
  • # Define delay between readings (s)
  • delay = 0.2
  • while True:
  • # Read the joystick position data
  • vrx_pos = ReadChannel(vrx_channel)
  • vry_pos = ReadChannel(vry_channel)
  • # Read switch state
  • swt_val = ReadChannel(swt_channel)
  • # Print out results
  • print "--------------------------------------------"
  • #print("X : {} Y : {} Switch : {}".format(vrx_pos,vry_pos,swt_val))
  • print("X : {} Y : {} ".format(vrx_pos,vry_pos))
  • # Wait before repeating loop
  • time.sleep(delay)0
  • if isLeft():
  • x-=1
  • moveX(x,y)
  • if isRight():
  • x+=1
  • moveX(x,y)
  • if isUp():
  • y-=1
  • moveY(x,y)
  • if isDown():
  • y+=1
  • moveY(x,y)
  • GPIO.cleanup()

 

 

利用"搖桿"和"MCP3008 類比轉換"來控制燈泡,由搖桿輸出數字碼,經由類比轉換讓Respberry Pi 解讀,搖桿上有X與Y軸,分別表示前進與後退,而輸出的類比訊號會介於0~1023之間,其中一個方向會讓類比訊號小於100反之另一個會大於900,再設定大於900與小於100的數字會前後和左右。