Python Forum
wiimote on raspberry pi controller servos, lights, and sounds
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
wiimote on raspberry pi controller servos, lights, and sounds
#1
This works:

#!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# wii_remote_1.py
# Connect a Nintendo Wii Remote via Bluetooth
# and  read the button states in Python.
#
# Project URL :
# http://www.raspberrypi-spy.co.uk/?p=1101
#
# Author : Matt Hawkins
# Date   : 30/01/2013
# Updated 8/2020 by Gabriel Vos aka Knoxvilles_joker
# http://alienslegacy.com
# updates done to allow for sound and servo controls and read full feature set of nunchuk
# Please note if using notepad and not notepad++ you must check for excess carriage returns in linux with the nano, vim, or your other preferred editor
# Please note python is very picky about syntax and spaces edit at own risk

# Licensed under GPL/GNU licensing distribute as you see fit but please include header above.
# Not to be used for commercial gain or profit unless credit given to authors.

# -----------------------
# Import required Python libraries
# -----------------------
import cwiid
import time
import os
import subprocess
import board
from board import SCL, SDA
import busio
from adafruit_pca9685 import PCA9685
i2c_bus = busio.I2C(SCL, SDA)
pca = PCA9685(i2c_bus)
pca.frequency = 50
# standard servo declearations for controls
from adafruit_servokit import ServoKit
kit = ServoKit(channels=16)
# class adafruit_moter.servo.Servo(pwm.out, *, actuation_range=180, minPpulse=750, max_pluse=2250)

#import adafruit_fxas21002c
#i2c=busio.I2C(board.SCL, board.SDA)
#sensor1=adafruit_fxas21002c.FXAS21002C(i2c)
import adafruit_mpu6050
i2c = busio.I2C(board.SCL, board.SDA)
sensor1 = adafruit_mpu6050.MPU6050(i2c)
#was mpu = but used old value to easily change code

# due to servo placement and positioning, you have to set the initial deployment angles at settings
# other than zero and ensure that time is given so proper travel can occur without causing undue binding issues.

time.sleep(0.1)
kit.servo[0].angle=160
#time.sleep(3)
kit.servo[1].angle=24
kit.servo[2].angle=140
# 0-2 are basically place holders for armature.
kit.servo[3].angle=180
#kit.servo[4].angle=0
#kit.servo[5].angle=90
#kit.servo[6].angle=0
kit.servo[7].angle=0
kit.servo[13].angle=0
kit.servo[14].angle=90
# these turn all the lights to an off state
kit.servo[6].angle=0
kit.servo[10].angle=0
kit.servo[11].angle=0
kit.servo[15].angle=0


# These are the options for the pwm portion of the servo bonnett
#set_pulse_widge_range(min_pulse, max_pulse)
# kit.servo[0].set_pulse_width_range(1000, 2000)
#pca.channels[15].duty_cycle = 0x7fff

button_delay = 0.1
# these are values for button depress bounces.  I use a counter to ensure accidental presses do not cause undue issues
# this also allows for gpio input if at some point there is a need to switch to RPi.GPIO button inputs with minimal change
# addressing for issues with debounce and system noise on button presses
# note that only ascii characters 0-128 are allowed.  Any special characters are not recognized for character counter names.
btn1cnt = 0
btn2cnt = 0
btnupcnt = 0
btnleftcnt = 0
btndowncnt = 0
btnrightcnt = 0
btnacnt = 0
btnbcnt = 0
btnccnt = 0
btnzcnt = 0
btnhomecnt = 0
btnminuscnt = 0
btnpluscnt = 0

# As a rule I place everything in /boot.  It is not neccessarily a recommend practice but makes later upgrades and midstream
# changes much easier to perform if there are major code updates.

# I may have to use the sub process command set to allow for multi tasking but that is at a later stage
# These are the files for sound playback over the 3.5mm audio output going over the 3.5mm jack from the hdmi port.
# wav files are played with aplay and mp3 files are played with mpg123 engaged using the os.system command subset
# playsound does not appear to play nice with python 3.7 and is not an option currently
#SFX
file1 = "/boot/minigun.wav"
file2 = "/boot/gameover.wav"
#themes
afam = "/boot/addamsfamily.mp3"
pred = "/boot/predator.mp3"
alienc = "/boot/alienscomplex.mp3"
combat = "/boot/combatdroppercussion.mp3"
liftoff = "/boot/liftoff.mp3"
lv426 = "/boot/lv426.mp3"
gb = "/boot/ghostbusters.mp3"
halloween = "/boot/halloweenteme.mp3"
filedown = "/boot/alienisolationintro.mp3"
laser = "/boot/laser.wav"
cannon = "/boot/cannon.wav"
# branches
army = "/boot/armyhymn.mp3"
af = "/boot/airforcesong.mp3"
usmc = "/boot/usmchymn.mp3"
navy = "/boot/navyhymn.mp3"
# sound tracks
b2 = "/boot/b2theme.mp3"
b3 = "/boot/b3introtheme.mp3"
everyrule = "/boot/everyrule.mp3"
jh = "/boot/jhsettingthewoodsonfire.mp3"
jumprope = "/boot/jumprope.mp3"
rammstein = "/boot/rammsteinhallelujah.mp3"
lithiumflower = "/boot/lithiumflower.mp3"
thriller = "/boot/thriller.mp3"
# misc sound effects found later in project
candy ="/boot/candy.wav"
anytime = "/boot/anytime.wav"
death = "/boot/death.wav"
demon = "/boot/demon.wav"
hell = "/boot/hell.wav"
jerry = "/boot/jerry.wav"
otherside = "/boot/otherside.wav"


#subprocess.Popen(['espeak', '--stdout', '-a200', '-g13', '-k01', '-p1', '-s160', '-ven-sc', "Shall we play aa game"], stdout=PIPE)
#subprocess.Popen(['aplay'])
print ('Press 1 + 2 on your Wii Remote now ...')
time.sleep(1)

# Connect to the Wii Remote. If it times out
# then quit.
# note that this is a clean way to quit script if stuff is not connected at startup.
p1 = subprocess.Popen(['espeak', '-a200', '--stdout', '-g13', '-k01', '-p1', "Hit Red Button nnow"], stdout=subprocess.PIPE)
subprocess.Popen(['aplay'], stdin=p1.stdout, stdout=subprocess.PIPE)
try:
  wii=cwiid.Wiimote()
except RuntimeError:
  print ("Error opening wiimote connection")
  quit()

print ('Wii Remote connected...\n')
print ('Press some buttons!\n')
print ('Press PLUS and MINUS together to disconnect and quit.\n')
wii.led = 1
wii.rpt_mode = cwiid.RPT_BTN  | cwiid.RPT_ACC | cwiid.RPT_NUNCHUK

while True:
#  Do not turn this line on unless you like spam in your command line output if you do comment the same line above first though
#  wii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC | cwiid.RPT_NUNCHUK
#  below are values pulled from the wm.state data array and stored to be used to drive various functions
#  you can comment out the status display to troubleshoot button pushes.  all buttons are accounted for in the script
  time.sleep(0.1) # pause required to get time for readings.
  battery = wii.state['battery']
  buttons = wii.state['buttons']
  # Wii Accelerometer readings are 0 - 255.  It is a true accelerommeter and it is meant to be used with the IR pointer for calibration in accurate use
  # Online documentation indicates that a light source can be used for referenc ein plcase of a light bar, but your mileage will vary.
  # this function is not used but is reported
  wacc= wii.state['acc']
  # I will be getting a wii motion device at some point and adding it but until then only the nunchuck accelerometer and joystick movements are used.
  nunbut = wii.state['nunchuk']
  nbut =nunbut['buttons']
  nacc =nunbut['acc']
  # Nunchuk stick range appears to be 226 - 26
  nstick= nunbut['stick']
  nstickx= int(((nstick[0]-26)/200)*180)
  nsticky= int(((nstick[1]-26)/200)*180)
  # Nunchuck range appears to be 250 - 26
  naccx  = int(((nacc[0]-20)/233)*180)
  naccy  = int(((nacc[1]-20)/233)*180)
  naccz  = int(((nacc[2]-20)/233)*180)
  time.sleep(button_delay)
# this is using the fxas21002c gyroscope as part of the setup that will mount to the head.  I may change this as I incorporate a QWIIC board.
# 
  gyro_x, gyro_y, gyro_z=sensor1.gyro
  rightxa=(((int(gyro_x--256)/(256--256))*180))
  rightza=(((int(gyro_z--256)/(256--256))*180))
# the round() function drops off all additional decimal points.  Useful to provide clean number readouts and input
# note that on more complex numerical calculations it is vital to do rounding as the last step.  rounding errors
# create final calculation deviation and can skew result with sometimes noticable results.
  rightx = round(rightxa)
  rightz = round(rightza)
# These are disabled as the wiimote accelerometer has too odd a range of settings and is not a true tilt sensor
# It was meant to be used in conjuction with a ir ptr for calibration and pointing ability
# This is great for calibration based upon device input range is 0-255
# waccx  = int(((
 # waccy  = int(((
 # waccz  = int(((
  print(wii.state)
  print('wb nb bat joyxy, accxyz')
  print(buttons, nbut, battery, nstickx, nsticky, naccx, naccy, naccz)
  print("gx", rightx, "gz", rightz, gyro_y)

  time.sleep(0.1)
  # servo setup is as follows:
  # main track left is 0, 1 is tilt arm left. 2 is tilt arm left levelling servo, 3 is pan servo for left and right action
  # 5 is main tilt right servo, 6 is levelling servo right, 7 is right pan left right servo
  # 10 is pwm light for firing, 15 is head laser
  # I am still playing with pwm signaling with opto couplers with a full 5v laser setup.
  # due to some issues with coding we have to do an if else to allow for servo2 the second tilt servo to function properly.  
  if (btnhomecnt == 1):
    kit.servo[2].angle=nstickx
    kit.servo[3].angle=nsticky
    kit.servo[14].angle=rightx
    kit.servo[7].angle=rightz
# use naccx if you want to use nunchuk accelerometer settings
  else:
    kit.servo[2].angle = 140
    kit.servo[3].angle = 180
    kit.servo[14].angle = 90
   # kit.servo[5].angle = 90

  time.sleep(button_delay)
  #this was to determine that we need to loop y axis out of bound
  #kit.servo[3].angle = nsticky
  time.sleep(button_delay)
  # the midarm servo is being set to always maintain a level status regardless of arm tilt.  based on my calculations with a 1:1 gear ratio
 # kit.servo[2].angle = nsticky # implemented design indicates that the geared unit needs to be the x tilt mechanism the main armature is just a placement deal
  kit.servo[4].angle = naccx
  kit.servo[6].angle = naccz
  #kit.servo[5].angle = naccx
  # If Plus and Minus buttons pressed
  # together then rumble and quit.
  # This is a great way to exit code if you set it to run at startup and need console control back.
  # This failsafe is a great way to ensure if you have buggy code you have an opportunity to fix it
  # By default I will typically place this in the \boot directory.
  if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
    print ('\nClosing connection ...')
    wii.rumble = 1
    time.sleep(1)
    kit.servo[0].angle = 160
    time.sleep(3)
    kit.servo[1].angle = 24
    time.sleep(2)
    kit.servo[2].angle = 140
    kit.servo[3].angle = 180
    kit.servo[4].angle = 0
    kit.servo[5].angle = 90
    kit.servo[6].angle = 0
    kit.servo[7].angle = 0
    kit.servo[13].angle = 0
    kit.servo[14].angle = 90

    time.sleep(4)
    wii.rumble = 0
    exit(wii)
  # this notifies you that the battery is low and prevents comm errors by ensuring you change the battery out.
  # This will constantly rumble until battery is replaced.
  if (battery <= 79):
    print ('please change battery now')
    wii.rumble = 1
    kit.servo[0].angle = 160
    time.sleep(3)
    kit.servo[1].angle = 24
    kit.servo[2].angle = 140
    kit.servo[3].angle = 180
    kit.servo[4].angle = 0
    kit.servo[5].angle = 90
    kit.servo[6].angle = 0
    kit.servo[7].angle = 0
    kit.servo[13].angle = 0
    kit.servo[14].angle = 90

    time.sleep(1)
    wii.rumble = 0
# The battery replace code is a physical reminder that battery is low.
# This is a failsafe to ensure that battery drop off is not severe.
# The value is 0-255 but I have seen it drop to 70s before comms are lost.
# The most I have seen it in is the upper 100s.  Mileage will vary based upon batteries in use
# Please bear in mind wiimote is only designed for standard AA batteries.  Do not cheat with fancier batteries
# The setup and maintenance is intended to be a lower cost setup.


  # Check if other buttons are pressed by
  # doing a bitwise AND of the buttons number
  # and the predefined constant for that button.
  # I am using a counter based setup for actions.
  # Theoretically this could lead to infinite number of actions after sequential number is reached
  # This is great if you are wanting a sequential set of sounds to play in sequence, or a start and reset sequence on a set servo or light
  # Please note that at the beginning for servos you want them all to reset to their neutral start positions.
  # This ensures if things crashed on the last go around you are not hyper extending or retracting servos beyond their active range
  # This lowers power consumption and esures minimal breakage issues

  if (buttons & cwiid.BTN_LEFT):
    print ('Left pressed')
    btnleftcnt = btnleftcnt +1
    print (btnleftcnt, "presses so far")
    time.sleep(button_delay)
  if (btnleftcnt == 2):
    subprocess.Popen(['mpg123', '-q', pred])
    print (btnleftcnt, "playing pred1")
    btnleftcnt = btnleftcnt +1
  if (btnleftcnt == 5):
    btnleftcnt = btnleftcnt +1
    os.system("pkill mpg123")
    print (btnleftcnt, "presses so far")
  if (btnleftcnt == 11):
    btnleftcnt = 0
    time.sleep(button_delay)

  if(buttons & cwiid.BTN_RIGHT):
    print ('Right pressed')
    btnrightcnt = btnrightcnt +1
    print (btnrightcnt, "presses so far")
    time.sleep(button_delay)
  if (btnrightcnt == 2):
    subprocess.Popen(['aplay', '-q', file2])
    btnrightcnt = btnrightcnt +1
    print (btnrightcnt, "playing file2")
    time.sleep(button_delay)
  if (btnrightcnt == 5):
    btnrightcnt = btnrightcnt +1
    os.system("pkill aplay")
  if (btnrightcnt == 8):
    subprocess.Popen(['mpg123', '-q', jumprope])
    btnrightcnt = btnrightcnt +1
    print (btnrightcnt, "playing jumprope")
    time.sleep(button_delay)
# jumprope is so short that a simple stop command should not be needed
# the os.system("pkill app") really is meant for longer file plays
  if (btnrightcnt == 11):
    subprocess.Popen(['mpg123', '-q', afam])
    btnrightcnt = btnrightcnt +1
    print (btnrightcnt, "playing addamsfamily")
    time.sleep(button_delay)
  if (btnrightcnt == 14):
    btnrightcnt = btnrightcnt +1
    os.system("pkill mpg123")
  if (btnrightcnt == 17):
    btnrightcnt = 0
    time.sleep(button_delay)

  if (buttons & cwiid.BTN_UP):
    print ('Up pressed')
    btnupcnt = btnupcnt +1
    print (btnupcnt, "presses so far")
    time.sleep(button_delay)
  if (btnupcnt == 2):
    subprocess.Popen(['mpg123', '-q', filedown])
    btnupcnt = btnupcnt +1
    print (btnupcnt, "playing filedown")
    time.sleep(button_delay)
  if (btnupcnt == 5):
    btnupcnt = btnupcnt +1
    os.system("pkill mpg123")
  if (btnupcnt == 8):
    subprocess.Popen(['mpg123', '-q', alienc])
    btnupcnt = btnupcnt +1
    print (btnupcnt, "playing alienc")
    time.sleep(button_delay)
  if (btnupcnt == 11):
    btnupcnt = btnupcnt +1
    os.system("pkill mpg123")
  if (btnupcnt == 14):
    btnupcnt = btnupcnt +1
    subprocess.Popen(['mpg123', '-q', combat])
    print (btnupcnt, "playing combat")
    time.sleep(button_delay)
  if (btnupcnt == 17):
    btnupcnt = btnupcnt +1
    os.system("pkill mpg123")
  if (btnupcnt == 20):
    btnupcnt = btnupcnt +1
    subprocess.Popen(['mpg123', '-q', liftoff])
    time.sleep(button_delay)
    print (btnupcnt, "playing liftoff")
  if (btnupcnt == 23):
    btnupcnt = btnupcnt +1
    os.system("pkill mpg123")
  if (btnupcnt == 26):
    btnupcnt = btnupcnt +1
    subprocess.Popen(['mpg123', '-q', lv426])
    time.sleep(button_delay)
    print (btnupcnt, "playing lv426")
  if (btnupcnt == 29):
    btnupcnt = btnupcnt +1
    os.system("pkill mpg123")
  if (btnupcnt == 32):
    btnupcnt = 0
    time.sleep(button_delay)


  if (buttons & cwiid.BTN_DOWN):
    print ('Down pressed')
    btndowncnt = btndowncnt +1
    print (btndowncnt, "presses so far")
    time.sleep(button_delay)
  if (btndowncnt == 2):
    subprocess.Popen(['mpg123', '-q', af])
    time.sleep(button_delay)
    btndowncnt = btndowncnt +1
    print (btndowncnt, "playing af")
  if (btndowncnt == 5):
    btndowncnt = btndowncnt +1
    os.system("pkill mpg123")
  if (btndowncnt == 8):
    btndowncnt = btndowncnt +1
    subprocess.Popen(['mpg123', '-q', army])
    time.sleep(button_delay)
    print (btndowncnt, "playing army")
  if (btndowncnt == 11):
    btndowncnt = btndowncnt +1
    os.system("pkill mpg123")
  if (btndowncnt == 14):
    subprocess.Popen(['mpg123', '-q', navy])
    time.sleep(button_delay)
    btndowncnt = btndowncnt +1
    print (btndowncnt, "playing navy")
  if (btndowncnt == 17):
    btndowncnt = btndowncnt +1
    os.system("pkill mpg123")
  if (btndowncnt == 20):
    btndowncnt = btndowncnt +1
    subprocess.Popen(['mpg123', '-q', usmc])
    time.sleep(button_delay)
    print (btndowncnt, "playing usmc")
  if (btndowncnt == 23):
    btndowncnt = btndowncnt +1
    os.system("pkill mpg123")
  if (btndowncnt == 26):
    btndowncnt = 0
    time.sleep(button_delay)
    print (btndowncnt, "resetting count, restarting loop")

  if (buttons & cwiid.BTN_1):
    print ('Button 1 pressed')
    btn1cnt = btn1cnt +1;
    print(btn1cnt, "presses so far")
    time.sleep(button_delay)
  if (btn1cnt == 3):
    print (btn1cnt, "reached playing minigun snd");
#    os.system("aplay " + file1);
#   I am replacing the above with a subprocess that will allow for multitasking/sub process concurrency.
#   It makes for some interesting sound combinations...
#   It appears that concurrency limit is about 4.  This is the only way to play sounds and keep the script read loop running
#    Moving servos and having sound effects
#    For shorter sound effects I am not invoking a pkill command set.
    subprocess.Popen(['aplay', '-q', file1])
    btn1cnt = 0
    time.sleep(button_delay)

  if (buttons & cwiid.BTN_2):
    print ('Button 2 pressed')
    btn2cnt = btn2cnt +1;
    print(btn2cnt, "presses so far");
    time.sleep(button_delay)
  if (btn2cnt == 2):
    print (btn2cnt, "reached playing gameover")
    subprocess.Popen(['aplay', '-q', file2])
    btn2cnt = btn2cnt +1
    time.sleep(button_delay)
# gameover is a super short clip comparatively so no pkill is needed
  if (btn2cnt == 5):
    print (btn2cnt, "presses so far")
    subprocess.Popen(['mpg123', '-q', rammstein])
    btn2cnt = btn2cnt +1
    print ("playing rammstein")
  if (btn2cnt == 8):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 11):
    print(btn2cnt, "presses so far")
    subprocess.Popen(['mpg123', '-q', lithiumflower])
    btn2cnt = btn2cnt +1
    print ("playing lithium flower")
  if (btn2cnt == 14):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 17):
    btn2cnt = btn2cnt +1
    print (btn2cnt, "presses so far")
    subprocess.Popen(['mpg123', '-q', thriller])
    print ("playing thriller")
  if (btn2cnt == 20):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 23):
    btn2cnt = btn2cnt +1
    print (btn2cnt, "presses so far")
    subprocess.Popen(['mpg123', '-q', gb])
    print ("playing ghostbusters instrumental")
  if (btn2cnt == 26):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 29):
    btn2cnt = btn2cnt +1
    print (btn2cnt, "presses so far")
    subprocess.Popen(['mpg123', '-q', halloween])
    print ("playing halloween instrumental them")
  if (btn2cnt == 32):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 35):
    print (btn2cnt, "presses so far")
    btn2cnt = btn2cnt +1
    subprocess.Popen(['mpg123', '-q', jh])
    print ("playing setting wodds on fire with joker and harley")
  if (btn2cnt == 38):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 41):
    btn2cnt = btn2cnt +1
    subprocess.Popen(['mpg123', '-q', b2])
    print ("playing borderlands2 theme song")
  if (btn2cnt == 44):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 47):
    btn2cnt = btn2cnt +1
    subprocess.Popen(['mpg123', '-q', b3])
    print ("playing borderlands3 themesong")
  if (btn2cnt == 50):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 53):
    btn2cnt = btn2cnt +1
    subprocess.Popen(['mpg123', '-q', everyrule])
    print ("playing everyone wants to rule the world")
  if (btn2cnt == 56):
    btn2cnt = btn2cnt +1
    os.system("pkill mpg123")
  if (btn2cnt == 59):
    btn2cnt = 0
    print ("resetting count")


  if (buttons & cwiid.BTN_A):
    print ('Button A pressed engaging disengaging laser')
    btnacnt = btnacnt +1
    print(btnacnt, "presses so far")
    time.sleep(button_delay)
  if (btnacnt == 2):
    subprocess.Popen(['mplayer', laser])
    kit.servo[15].angle = 110
    kit.servo[4].angle = 110
    time.sleep(button_delay)
    btnacnt = btnacnt +1
    print (btnacnt, "playing and lighting laser")
  if (btnacnt == 5):
    subprocess.Popen(['mplayer', laser])
    kit.servo[15].angle = 40
    kit.servo[4].angle = 40
    btnacnt = btnacnt +1
    print (btnacnt, "playing laser and powering down")
  if (btnacnt == 8):
    btnacnt = 0
    print (btnacnt, "resetting count restarting a loop")
    time.sleep(button_delay)

  if (buttons & cwiid.BTN_B):
    print ('Button B pressed')
    btnbcnt = btnbcnt +1;
    print(btnbcnt, "presses so far");
    time.sleep(button_delay)
  if (btnbcnt == 3):
    print('btnbcnt reached playing laser sound');
    kit.servo[11].angle = 110
    time.sleep(1)
    kit.servo[10].angle = 110
    subprocess.Popen(['mplayer', cannon])
    time.sleep(.5)
    kit.servo[10].angle = 40
    time.sleep(.2)
    kit.servo[11].angle = 40
    btnbcnt = 0;
    print (btnbcnt, "playing cannon sound and lighting up")
    time.sleep(button_delay);

  if (buttons & cwiid.BTN_HOME):
    print ('Home Button pressed')
    btnhomecnt = btnhomecnt +1;
    print(btnhomecnt, "presses so far");
    time.sleep(button_delay)
  if (btnhomecnt == 0):
    # Initial starting point.  This ensures no movements until you are ready and accounts for accidental presses as you fumble with things suiting up and powering stuff on.
    kit.servo[0].angle = 160
#    time.sleep(4)
    kit.servo[1].angle = 24
    kit.servo[3].angle = 180
    kit.servo[2].angle = 140
    kit.servo[13].angle = 0
    kit.servo[14].angle = 90
    kit.servo[5].angle = 90
#   tilt angle control is done through an if or else statement at beginning of script to constrain movement in down position
    time.sleep(button_delay);
  if (btnhomecnt == 1):
    kit.servo[0].angle = 10
    kit.servo[1].angle = 95
    kit.servo[13].angle = 51
    #this is the operating position.  Other arms will get added as I get the build out further along.
#   I had to add a separate failsafe check to reset btnhome count to prevent erraneous readings for the angle of the cannon on the y axis.
  if (btnhomecnt == 2):
  #  time.sleep(4)
    btnhomecnt = 0

  if (buttons & cwiid.BTN_MINUS):
    print ('Minus Button pressed')
    btnminuscnt = btnminuscnt +1;
    print(btnminuscnt, "presses so far");
    time.sleep(button_delay);
  if (btnminuscnt == 2):
    os.system("amixer set HDMI -- 400")
    btnminuscnt = btnminuscnt +1
  if (btnminuscnt == 5):
    time.sleep(button_delay)
    btnminuscnt = btnminuscnt +1
    os.system("amixer set HDMI -- 200")
  if (btnminuscnt == 8):
    btnminuscnt = btnminuscnt +1
    os.system("amixer set HDMI -- 0")
  if (btnminuscnt == 11):
    btnminuscnt = btnminuscnt +1
    os.system("amixer set HDMI -- -2000")
  if (btnminuscnt == 14):
    btnminuscnt = btnminuscnt +1
    os.system("amixer set HDMI -- -4000")
  if (btnminuscnt == 17):
    btnminuscnt = btnminuscnt +1
    os.system("amixer set HDMI -- -10200")
  if (btnminuscnt == 20):
    print ("resetting count");
    btnminuscnt = 0
    time.sleep(button_delay);

  if (buttons & cwiid.BTN_PLUS):
    print ('Plus Button pressed')
    btnpluscnt = btnpluscnt +1
    print (btnpluscnt, "presses so far")
    time.sleep(button_delay)
  if (btnpluscnt == 2):
    btnpluscnt = btnpluscnt +1
    print (btnpluscnt, "presses so far")
    subprocess.Popen(['mplayer', anytime])
  if (btnpluscnt == 5):
    btnpluscnt = btnpluscnt +1
    subprocess.Popen(['mplayer', demon])
  if (btnpluscnt == 8):
    btnpluscnt = btnpluscnt +1
    print (btnpluscnt, "presses so far")
    subprocess.Popen(['mplayer', candy])
  if (btnpluscnt == 11):
    btnpluscnt = btnpluscnt +1
    print (btnpluscnt, "presses so far")
    subprocess.Popen(['mplayer', hell])
  if (btnpluscnt == 14):
    btnpluscnt = btnpluscnt +1
    print (btnpluscnt, "presses so far")
    subprocess.Popen(['mplayer', death])
  if (btnpluscnt == 17):
    btnpluscnt = btnpluscnt +1
    subprocess.Popen(['mplayer', jerry])
    print (btnpluscnt, "presses so far")
  if (btnpluscnt == 20):
    btnpluscnt = btnpluscnt +1
    subprocess.Popen(['mplayer', otherside])
    print (btnpluscnt, "presses so far")
  if (btnpluscnt == 23):
    btnpluscnt = 0
    print ("resetting count and resetting loop")



  if (nbut & cwiid.NUNCHUK_BTN_C):
    print ('nunchuk c pressed')
    btnccnt = btnccnt +1;
    print (btnccnt, "presses so far")
    time.sleep(button_delay)
  if (btnccnt == 2):
    kit.servo[6].angle = 110
    subprocess.Popen(['mplayer', laser])
    time.sleep(.2)
    btnccnt = btnccnt +1
  if (btnccnt == 5):
    print ('fire left cannon, lights')
    subprocess.Popen(['mplayer', laser])
    time.sleep(1)
    kit.servo[6].angle = 40
    btnccnt = 0

  if (nbut & cwiid.NUNCHUK_BTN_Z):
    btnzcnt = btnzcnt +1
    print (btnzcnt, "presses so far")
    print ('nunchuk z pressed')
    time.sleep(button_delay)
  if (btnzcnt == 2):
  #  kit.servo[6].angle = 110
    subprocess.Popen(['mplayer', laser])
    time.sleep(.3)
    btnzcnt = btnzcnt +1
  if (btnzcnt == 5):
    btnzcnt = btnzcnt +1
    kit.servo[4].angle= 110
    kit.servo[11].angle= 110
  if (btnzcnt == 8):
    btnzcnt = btnzcnt +1
    kit.servo[15].angle=110
    kit.servo[10].angle=110
    subprocess.Popen(['mplayer', cannon])
    time.sleep(.5)
    kit.servo[15].angle=40
    kit.servo[10].angle=40
  if (btnzcnt == 11):
    btnzcnt = btnzcnt +1
  if (btnzcnt == 14):
    print ('fire right cannon, lights')
    kit.servo[4].angle = 40
    kit.servo[11].angle = 40
    subprocess.Popen(['mplayer', laser])
    btnzcnt = 0
    time.sleep(button_delay)
    time.sleep(1)
   # kit.servo[6].angle = 40

  if (nbut - cwiid.NUNCHUK_BTN_Z - cwiid.NUNCHUK_BTN_C == 0):
    print ('nunchuk c plus z pressed')
    time.sleep(button_delay)
And the script to launch it at startup:
#/usr/bin/python
import psutil
from subprocess import Popen
import time
import os
import subprocess
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(21, GPIO.FALLING, bouncetime=2000)
btn21cnt = 0
btn21run = 0
while True:
  for process in psutil.process_iter():
    if process.cmdline() == ['python3', 'wii_remote_final2.py']:
      btn21run = 1
#    else:
 #     print('Process not found: starting it.')
  #    btn21run = 0
  if GPIO.event_detected(21):
    btn21cnt = btn21cnt + 1
    subprocess.Popen(['play', '-n', '-c1', 'synth', '0.25', 'sine', '1000'])
    print(btn21cnt, "presses so far")
    time.sleep(0.1)
  if (btn21cnt == 3):
    print(btn21cnt, "threshold reached stopping script")
    os.system("killall -9 wii_remote_final2.py")
    btn21cnt - btn21cnt + 1
  if (btn21cnt == 6):
    print(btn21cnt, "threshold reached starting script")
    subprocess.run(['python3', '/boot/wii_remote_final2.py'])
    btn21cnt = 0
Reply
#2
Do you have a question? If not - I will move this to Code Review or Code Share section of the forum
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Apr-19-2021, 05:24 AM)buran Wrote: Do you have a question? If not - I will move this to Code Review or Code Share section of the forum

Ah, I did not see that section, please move there if you would be so kind. Thanks!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020