I have trouble, j = pygame.joystick.Joystick() - python

My example code from google.
#!/usr/bin/env python
import pygame
from pygame import
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
# Initialise the pygame library
pygame.init()
# Connect to the first JoyStick16:11:10:05:0B:1C
j = pygame.joystick.Joystick(0)
j.init()
print 'Initialized Joystick : %s' % j.get_name()
# Setup the various GPIO values, using the BCM numbers for now
MotorA0 = 16
MotorA1 = 18
MotorAE = 22
MotorB0 = 23
MotorB1 = 21
MotorBE = 19
16:11:10:05:0B:1C
A0 = False
A1 = False
B0 = False
B1 = False
GPIO.setup(MotorA0,GPIO.OUT)
GPIO.setup(MotorA1,GPIO.OUT)
GPIO.setup(MotorAE,GPIO.OUT)
GPIO.setup(MotorB0,GPIO.OUT)
GPIO.setup(MotorB1,GPIO.OUT)
GPIO.setup(MotorBE,GPIO.OUT)
# Set all the Motors to 'off'
GPIO.output(MotorA0, A0)
GPIO.output(MotorA1, A1)
GPIO.output(MotorAE, False)
GPIO.output(MotorBE, False)
GPIO.output(MotorB0, B0)
GPIO.output(MotorB1, B1)
# Only start the motors when the inputs go above the following threshold
threshold = 0.60
LeftTrack = 0
RightTrack = 0
# Configure the motors to match the current settings.
def setmotors():
GPIO.output(MotorA0, A0)
GPIO.output(MotorA1, A1)
GPIO.output(MotorAE, True)
GPIO.output(MotorBE, True)
GPIO.output(MotorB0, B0)
GPIO.output(MotorB1, B1)
# Try and run the main code, and in case of failure we can stop the motors
try:
# Turn on the motors
GPIO.output(MotorAE, True)
GPIO.output(MotorBE, True)
# This is the main loop
while True:
# Check for any queued events and then process each one
events = pygame.event.get()
for event in events:
UpdateMotors = 0
# Check if one of the joysticks has moved
if event.type == pygame.JOYAXISMOTION:
if event.axis == 1:
LeftTrack = event.value
UpdateMotors = 1
elif event.axis == 3:
RightTrack = event.value
UpdateMotors = 1
# Check if we need to update what the motors are doing
if UpdateMotors:
# Check how to configure the left motor
# Move forwards
if (RightTrack > threshold):
A0 = False
A1 = True
# Move backwards
elif (RightTrack < -threshold):
A0 = True
A1 = False
# Stopping
else:
A0 = False
A1 = False
# And do the same for the right motor
if (LeftTrack > threshold):
B0 = False
B1 = True
# Move backwards
elif (LeftTrack < -threshold):
B0 = True
B1 = False
# Otherwise stop
else:
B0 = False
B1 = False
# Now we've worked out what is going on we can tell the
# motors what they need to do
setmotors()
except KeyboardInterrupt:
# Turn off the motors
GPIO.output(MotorAE, False)
GPIO.output(MotorBE, False)
j.quit()#!/usr/bin/env python
GPIO.cleanup()
When i run this code, i have a troubleshoot.
Traceback (most recent call last):
File "control.py", line 13, in
j = pygame.joystick.Joystick()
TypeError: function takes exactly 1 argument (0 given)

Your issue is that the command line j=pygame.joystick.Joystick(0) is calling the first ps3 controller that is available and paired to your raspberry pi (or whatever device you are using).
With that said, if you do not have a ps3 controller paired with the device, it will never work, because the next command line calls the Ps3controller 0 , and in your case, seems not to be any installed or paired.
Also some other issues with your code:
Line 4: Erase this line completely
Line 26: This was suppose to have a # hashtag before it, used only for notation. You can actually delete this line because it was notes from someone else's project anyway.
Line 78: The indentation is incorrect. it has to follow the indentation of the "while True" loop above it. So to fix it, make sure to backspace the command in line 78 all the way to the left, then press spacebar 8 times, or press TAB key 2 times, same thing. that will fix it!
Now your code works. actually one last thing, make sure to install pygame library as well, type this in the Xterminal(im using raspberry pi with raspbian) if u don't have it yet: sudo apt-get install python-pygame
I hope this all helped. I know you will have more questions, this code used to piss me off!lol

Related

Python3.6 and Pyautogui - Pixel commands - TypeError: __new__() takes 4 positional arguments but 5 were given

I'm relatively new to Python and I'm attempting to make a fun little project using Pyautogui and Python3.6. The goal of this project is to create a tensorflow powered project that learns to play chess. The problem I am now encountering is that whenever I try to use any of the pixel commands - e.g. pyautogui.pixel(...) or screenshot.getpixel(...) - an error pops up and says this:
Traceback (most recent call last):
File "main.py", line 109, in <module>
Score()
File "main.py", line 100, in Score
if gui.pixelMatchesColor(tempX, tempY, (87, 83, 82), tolerance=20):
File "/Users/student/Library/Python/3.6/lib/python/site-packages/pyscreeze/__init__.py", line 413, in pixelMatchesColor
pix = pixel(x, y)
File "/Users/student/Library/Python/3.6/lib/python/site-packages/pyscreeze/__init__.py", line 436, in pixel
return RGB(*screenshot().getpixel((x, y)))
TypeError: __new__() takes 4 positional arguments but 5 were given
I just want to note that all other commands work fine and that it's only the pixel ones that don't work.
I have installed everything including pyautogui(duh), pyscreeze, pymsgbox, pytweening, xlib, opencv, and any other package I could think of. These were installed using this command: pip3 install package-name-here --user. I needed the --user because I don't currently have administrator rights to my computer so I'm wondering if that could have something to do with my current predicament.
I also encountered an earlier post in my search for an answer but I forgot where I found it, so I'm sorry but I can't link it, but basically it said that I should go through and remove all pycache folders. I did this using the terminal command in the ~/Library/Python/3.6 folder:
find . -name "__pycache__" -type f -o -name "__pycache__" -type d -exec rm -rf {} \
I am in no need of an exact solution to this problem, but I'm wondering if there's some way to use the pyautogui.pixelMatchesColor(...) function or any similar one that you recommend that can have a tolerance - e.g. that the RGB values can be 10 units off and still return true.
For those of you that are interested, here is my full code:
#
# IMPORT ALL NECESSARY THINGS
#
import os, time, sys, pyautogui as gui, argparse as arg
#
# FAILSAFES
#
gui.FAILSAFE = True
gui.PAUSE = 0.1
#
# SET UP ARGUMENT PARSER
#
parser = arg.ArgumentParser(description='A machine learning script powered by TensorFlow designed to be run on "chess.com" using Python.')
parser.add_argument("-s", "--sleep", nargs='?', type=int, default='5', help='Number of seconds that the program should sleep before starting. This gives you time to move over to the website before the program looks for the gamboard on screen.')
args = parser.parse_args()
#
# ASKS USER FOR WHAT SIDE IT IS ON
#
side = input("Are you white or black? ")
if side == "W" or side == "w" or side == "white" or side == "White":
side = "W"
elif side == "B" or side == "b" or side == "black" or side == "Black":
side = "B"
else:
print("Invalid selection for which side!")
side = None
sys.exit(0)
#
# PRINT "READY" AND THEN WAIT FOR SPECIFIED AMOUNT OF TIME - DEFAULT 5 SECONDS
#
print("Ready! Waiting for " + str(args.sleep) + " seconds!")
time.sleep(int(args.sleep))
#
# GET AREA OF GAMEBOARD ON SCREEN
#
if side == "W":
gameboard = gui.locateOnScreen('./img/white/chessboard_white.png', confidence=0.55, grayscale=True)
left = gameboard.left - 10
top = gameboard.top - 5
right = gameboard.left + gameboard.width + 10
bottom = gameboard.top + gameboard.height + 15
elif side == "B":
gameboard = gui.locateOnScreen('./img/black/chessboard_black.png', confidence=0.55, grayscale=True)
left = gameboard.left - 10
top = gameboard.top - 5
right = gameboard.left + gameboard.width + 10
bottom = gameboard.top + gameboard.height + 15
widthInterval = (right - gameboard.left) / 8
heightInterval = (bottom - gameboard.top) / 8
#
# DEFINES A FUNCTION THAT COUNTS THE SCORE
# - NUMBER OF YOU SIDE AND THEN SUBTRACT THE NUMBER OF OPPOSITE SIDE
#
def Score():
for i in range(8):
for j in range(8):
tempX = 32 + (i * widthInterval)
tempY = 32 + (j * heightInterval)
if gui.pixelMatchesColor(tempX, tempY, (87, 83, 82), tolerance=20):
print("True!")
if side == "W":
print("White!")
elif side == "B":
print("Black!")
Score()
Note: The problem occurs in the last 10ish lines of the above code.
Thank you so much for your help and please don't hesitate to let me know if you need any more info from me!
Max

cannot find evdev2 module

In visual studio I am trying to upload my code onto the ev3de (which is in python). It does work but as soon as I try to run it on the ev3, the program goes straight back to the screen before. When I try and run the program there are a few errors: It cannot find a module called pyev3, which I have never heard of, and it also cannot find the cwiid module, for the wiimote. Here is the code (it's not from myself):
#!/usr/bin/env python3
# Drive your robot with a wii remote!
# Left motor on port B, right motor on port C,
# vertical arm on port D.
# Requires the package 'python-cwiid'.
# Make sure bluetooth is enabled in brickman
# before trying to use this. Hold 2 to go forward
# and 1 to go backward.
import sys
import os
import time
import cwiid
import pyev3
def clamp(value, lower, upper):
return min(upper, max(value, lower))
print('press 1+2 on the wiimote now')
time.sleep(1)
w = cwiid.Wiimote()
print('connected?')
w.led = 6
w.rpt_mode = cwiid.RPT_ACC | cwiid.RPT_BTN
left_motor = pyev3.Motor(pyev3.OUTPUT_B)
left_motor.reset()
left_motor.run_mode = 'forever'
left_motor.regulation_mode = 'on'
right_motor = pyev3.Motor(pyev3.OUTPUT_C)
right_motor.reset()
right_motor.run_mode = 'forever'
right_motor.regulation_mode = 'on'
arm = pyev3.Motor(pyev3.OUTPUT_D)
arm.reset()
arm.run_mode = 'forever'
arm.regulation_mode = 'off'
target_distance = 8
top_speed = 720
left_motor.run = 1
right_motor.run = 1
last_btn_state = 0
move = 0
try:
while True:
state = w.state
buttons = state['buttons']
if buttons != last_btn_state:
if buttons & cwiid.BTN_MINUS:
top_speed -= 10
print (top_speed)
if buttons & cwiid.BTN_PLUS:
top_speed += 10
print (top_speed)
if buttons & cwiid.BTN_2:
move = 1
elif buttons & cwiid.BTN_1:
move = -1
else:
move = 0
if buttons & cwiid.BTN_LEFT:
arm.duty_cycle_sp = 100
arm.run = 1
elif buttons & cwiid.BTN_RIGHT:
arm.duty_cycle_sp = -100
arm.run = 1
else:
arm.run = 0
print (top_speed, move)
last_btn_state = buttons
if move:
acc = state['acc']
tilt = (clamp(acc[1], 95, 145) - 120) / 25.0 # roughly between -0.5 and 0.5
turn = top_speed * tilt
turn = clamp(turn, -abs(top_speed), abs(top_speed))
left_motor.pulses_per_second_sp = int(top_speed - turn) * move
right_motor.pulses_per_second_sp = int(top_speed + turn) * move
else:
left_motor.pulses_per_second_sp = 0
right_motor.pulses_per_second_sp = 0
finally:
left_motor.run = 0
right_motor.run = 0
When I run this one in Visual Studio Code, this happens:
File "c:/Users/User/Documents/fingers_crossed/drive.py", line 13, in
import cwiid ModuleNotFoundError: No module named 'cwiid' PS
C:\Users\User\Documents\fingers_crossed>
Also, why can't my robot find the ev3dev2 module?

Brookstone rover 2.0 Python program to control from computer isn't working

I have a python program that controls a Brookstone Rover 2.0 from a computer through openCV and pygame and I've been working on this for 7 hours now and it has been nothing but errors after errors and this is what it's showing me now
PS C:\users\sessi\desktop> C:\Users\sessi\Desktop\rover\ps3rover20.py
Traceback (most recent call last):
File "C:\Users\sessi\Desktop\rover\ps3rover20.py", line 168, in <module>
rover = PS3Rover()
File "C:\Users\sessi\Desktop\rover\ps3rover20.py", line 58, in __init__
Rover20.__init__(self)
File "C:\Program Files\Python 3.5\lib\site-packages\roverpylot-0.1-py3.5.egg\rover\__init__.py", line 182, in __init__
Rover.__init__(self)
File "C:\Program Files\Python 3.5\lib\site-packages\roverpylot-0.1-py3.5.egg\rover\__init__.py", line 47, in __init__
self._sendCommandIntRequest(0, [0, 0, 0, 0])
File "C:\Program Files\Python 3.5\lib\site-packages\roverpylot-0.1-py3.5.egg\rover\__init__.py", line 149, in _sendCommandIntRequest
bytevals.append(ord(c))
TypeError: ord() expected string of length 1, but int found
These are the two files that it's getting errors from
ps3rover20.py
#!/usr/bin/env python
'''
ps3rover20.py Drive the Brookstone Rover 2.0 via the P3 Controller, displaying
the streaming video using OpenCV.
Copyright (C) 2014 Simon D. Levy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
# You may want to adjust these buttons for your own controller
BUTTON_LIGHTS = 3 # Square button toggles lights
BUTTON_STEALTH = 1 # Circle button toggles stealth mode
BUTTON_CAMERA_UP = 0 # Triangle button raises camera
BUTTON_CAMERA_DOWN = 2 # X button lowers camera
# Avoid button bounce by enforcing lag between button events
MIN_BUTTON_LAG_SEC = 0.5
# Avoid close-to-zero values on axis
MIN_AXIS_ABSVAL = 0.01
from rover import Rover20
import time
import pygame
import sys
import signal
# Supports CTRL-C to override threads
def _signal_handler(signal, frame):
frame.f_locals['rover'].close()
sys.exit(0)
# Try to start OpenCV for video
try:
import cv
except:
cv = None
# Rover subclass for PS3 + OpenCV
class PS3Rover(Rover20):
def __init__(self):
# Set up basics
Rover20.__init__(self)
self.wname = 'Rover 2.0: Hit ESC to quit'
self.quit = False
# Set up controller using PyGame
pygame.display.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(0)
self.controller.init()
# Defaults on startup: lights off, ordinary camera
self.lightsAreOn = False
self.stealthIsOn = False
# Tracks button-press times for debouncing
self.lastButtonTime = 0
# Try to create OpenCV named window
try:
if cv:
cv.NamedWindow(self.wname, cv.CV_WINDOW_AUTOSIZE )
else:
pass
except:
pass
self.pcmfile = open('rover20.pcm', 'w')
# Automagically called by Rover class
def processAudio(self, pcmsamples, timestamp_10msec):
for samp in pcmsamples:
self.pcmfile.write('%d\n' % samp)
# Automagically called by Rover class
def processVideo(self, jpegbytes, timestamp_10msec):
# Update controller events
pygame.event.pump()
# Toggle lights
self.lightsAreOn = self.checkButton(self.lightsAreOn, BUTTON_LIGHTS, self.turnLightsOn, self.turnLightsOff)
# Toggle night vision (infrared camera)
self.stealthIsOn = self.checkButton(self.stealthIsOn, BUTTON_STEALTH, self.turnStealthOn, self.turnStealthOff)
# Move camera up/down
if self.controller.get_button(BUTTON_CAMERA_UP):
self.moveCameraVertical(1)
elif self.controller.get_button(BUTTON_CAMERA_DOWN):
self.moveCameraVertical(-1)
else:
self.moveCameraVertical(0)
# Set treads based on axes
self.setTreads(self.axis(1), self.axis(3))
# Display video image if possible
try:
if cv:
# Save image to file on disk and load as OpenCV image
fname = 'tmp.jpg'
fd = open(fname, 'w')
fd.write(jpegbytes)
fd.close()
image = cv.LoadImage(fname)
# Show image
cv.ShowImage(self.wname, image )
if cv.WaitKey(1) & 0xFF == 27: # ESC
self.quit = True
else:
pass
except:
pass
# Converts Y coordinate of specified axis to +/-1 or 0
def axis(self, index):
value = -self.controller.get_axis(index)
if value > MIN_AXIS_ABSVAL:
return 1
elif value < -MIN_AXIS_ABSVAL:
return -1
else:
return 0
# Handles button bounce by waiting a specified time between button presses
def checkButton(self, flag, buttonID, onRoutine=None, offRoutine=None):
if self.controller.get_button(buttonID):
if (time.time() - self.lastButtonTime) > MIN_BUTTON_LAG_SEC:
self.lastButtonTime = time.time()
if flag:
if offRoutine:
offRoutine()
flag = False
else:
if onRoutine:
onRoutine()
flag = True
return flag
# main -----------------------------------------------------------------------------------
if __name__ == '__main__':
# Create a PS3 Rover object
rover = PS3Rover()
# Set up signal handler for CTRL-C
signal.signal(signal.SIGINT, _signal_handler)
# Loop until user hits quit button on controller
while not rover.quit:
pass
# Shut down Rover
rover.close()
__ init__.py
'''
Python classes for interacting with the Brookstone Rover 2.0
and Rover Revolution
Copyright (C) 2015 Simon D. Levy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
import struct
import threading
import socket
import time
from blowfish import Blowfish
from adpcm import decodeADPCMToPCM
from byteutils import *
class Rover:
def __init__(self):
''' Creates a Rover object that you can communicate with.
'''
self.HOST = '192.168.1.100'
self.PORT = 80
TARGET_ID = 'AC13'
TARGET_PASSWORD = 'AC13'
self.TREAD_DELAY_SEC = 1.0
self.KEEPALIVE_PERIOD_SEC = 60
# Create command socket connection to Rover
self.commandsock = self._newSocket()
# Send login request with four arbitrary numbers
self._sendCommandIntRequest(0, [0, 0, 0, 0])
# Get login reply
reply = self._receiveCommandReply(82)
# Extract Blowfish key from camera ID in reply
cameraID = reply[25:37].decode('utf-8')
key = TARGET_ID + ':' + cameraID + '-save-private:' + TARGET_PASSWORD
# Extract Blowfish inputs from rest of reply
L1 = bytes_to_int(reply, 66)
R1 = bytes_to_int(reply, 70)
L2 = bytes_to_int(reply, 74)
R2 = bytes_to_int(reply, 78)
# Make Blowfish cipher from key
bf = _RoverBlowfish(key)
# Encrypt inputs from reply
L1,R1 = bf.encrypt(L1, R1)
L2,R2 = bf.encrypt(L2, R2)
# Send encrypted reply to Rover
self._sendCommandIntRequest(2, [L1, R1, L2, R2])
# Ignore reply from Rover
self._receiveCommandReply(26)
# Start timer task for keep-alive message every 60 seconds
self._startKeepaliveTask()
# Set up vertical camera controller
self.cameraVertical = _RoverCamera(self, 1)
# Send video-start request
self._sendCommandIntRequest(4, [1])
# Get reply from Rover
reply = self._receiveCommandReply(29)
# Create media socket connection to Rover
self.mediasock = self._newSocket()
# Send video-start request based on last four bytes of reply
self._sendRequest(self.mediasock, 'V', 0, 4, map(ord, reply[25:]))
# Send audio-start request
self._sendCommandByteRequest(8, [1])
# Ignore audio-start reply
self._receiveCommandReply(25)
# Receive images on another thread until closed
self.is_active = True
self.reader_thread = _MediaThread(self)
self.reader_thread.start()
def close(self):
''' Closes off commuincation with Rover.
'''
self.keepalive_timer.cancel()
self.is_active = False
self.commandsock.close()
if self.mediasock:
self.mediasock.close()
def turnStealthOn(self):
''' Turns on stealth mode (infrared).
'''
self._sendCameraRequest(94)
def turnStealthOff(self):
''' Turns off stealth mode (infrared).
'''
self._sendCameraRequest(95)
def moveCameraVertical(self, where):
''' Moves the camera up or down, or stops moving it. A nonzero value for the
where parameter causes the camera to move up (+) or down (-). A
zero value stops the camera from moving.
'''
self.cameraVertical.move(where)
def _startKeepaliveTask(self,):
self._sendCommandByteRequest(255)
self.keepalive_timer = \
threading.Timer(self.KEEPALIVE_PERIOD_SEC, self._startKeepaliveTask, [])
self.keepalive_timer.start()
def _sendCommandByteRequest(self, id, bytes=[]):
self._sendCommandRequest(id, len(bytes), bytes)
def _sendCommandIntRequest(self, id, intvals):
bytevals = []
for val in intvals:
for c in struct.pack('I', val):
bytevals.append(ord(c))
self._sendCommandRequest(id, 4*len(intvals), bytevals)
def _sendCommandRequest(self, id, n, contents):
self._sendRequest(self.commandsock, 'O', id, n, contents)
def _sendRequest(self, sock, c, id, n, contents):
bytes = [ord('M'), ord('O'), ord('_'), ord(c), id, \
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n, 0, 0, 0, 0, 0, 0, 0]
bytes.extend(contents)
request = ''.join(map(chr, bytes))
sock.send(request)
def _receiveCommandReply(self, count):
reply = self.commandsock.recv(count)
return reply
def _newSocket(self):
sock = socket.socket()
sock.connect((self.HOST, self.PORT))
return sock
def _sendDeviceControlRequest(self, a, b) :
self._sendCommandByteRequest(250, [a,b])
def _sendCameraRequest(self, request):
self._sendCommandByteRequest(14, [request])
class Rover20(Rover):
def __init__(self):
Rover.__init__(self)
# Set up treads
self.leftTread = _RoverTread(self, 4)
self.rightTread = _RoverTread(self, 1)
def close(self):
''' Closes off commuincation with Rover.
'''
Rover.close(self)
# Stop moving treads
self.setTreads(0, 0)
def getBatteryPercentage(self):
''' Returns percentage of battery remaining.
'''
self._sendCommandByteRequest(251)
reply = self._receiveCommandReply(32)
return 15 * ord(reply[23])
def setTreads(self, left, right):
''' Sets the speed of the left and right treads (wheels). + = forward;
- = backward; 0 = stop. Values should be in [-1..+1].
'''
currTime = time.time()
self.leftTread.update(left)
self.rightTread.update(right)
def turnLightsOn(self):
''' Turns the headlights and taillights on.
'''
self._setLights(8)
def turnLightsOff(self):
''' Turns the headlights and taillights off.
'''
self._setLights(9)
def _setLights(self, onoff):
self._sendDeviceControlRequest(onoff, 0)
def processVideo(self, jpegbytes, timestamp_10msec):
''' Proccesses bytes from a JPEG image streamed from Rover.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def processAudio(self, pcmsamples, timestamp_10msec):
''' Proccesses a block of 320 PCM audio samples streamed from Rover.
Audio is sampled at 8192 Hz and quantized to +/- 2^15.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def _spinWheels(self, wheeldir, speed):
# 1: Right, forward
# 2: Right, backward
# 4: Left, forward
# 5: Left, backward
self._sendDeviceControlRequest(wheeldir, speed)
class Revolution(Rover):
def __init__(self):
Rover.__init__(self)
self.steerdir_prev = 0
self.command_prev = 0
self.goslow_prev = 0
self.using_turret = False
# Set up vertical camera controller
self.cameraHorizontal = _RoverCamera(self, 5)
def drive(self, wheeldir, steerdir, goslow):
goslow = 1 if goslow else 0
command = 0
if wheeldir == +1 and steerdir == 0:
command = 1
if wheeldir == -1 and steerdir == 0:
command = 2
if wheeldir == 0 and steerdir == +1:
command = 4
if wheeldir == 0 and steerdir == -1:
command = 5
if wheeldir == +1 and steerdir == -1:
command = 6
if wheeldir == +1 and steerdir == +1:
command = 7
if wheeldir == -1 and steerdir == -1:
command = 8
if wheeldir == -1 and steerdir == +1:
command = 9
if steerdir == 0 and self.steerdir_prev != 0:
command = 3
if command != self.command_prev or goslow != self.goslow_prev:
self._sendDeviceControlRequest(command, goslow)
self.steerdir_prev = steerdir
self.command_prev = command
self.goslow_prev = goslow
def processVideo(self, imgbytes, timestamp_msec):
''' Proccesses bytes from an image streamed from Rover.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def processAudio(self, audiobytes, timestamp_msec):
''' Proccesses a block of 1024 PCM audio samples streamed from Rover.
Audio is sampled at 8192 Hz and quantized to +/- 2^15.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def useTurretCamera(self):
''' Switches to turret camera.
'''
self._sendUseCameraRequest(1)
def useDrivingCamera(self):
''' Switches to driving camera.
'''
self._sendUseCameraRequest(2)
def moveCameraHorizontal(self, where):
''' Moves the camera up or down, or stops moving it. A nonzero value for the
where parameter causes the camera to move up (+) or down (-). A
zero value stops the camera from moving.
'''
self.cameraHorizontal.move(where)
def _sendUseCameraRequest(self, camera):
self._sendCommandByteRequest(19, [6, camera])
# "Private" classes ===========================================================
# A special Blowfish variant with P-arrays set to zero instead of digits of Pi
class _RoverBlowfish(Blowfish):
def __init__(self, key):
ORIG_P = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self._keygen(key, ORIG_P)
# A thread for reading streaming media from the Rover
class _MediaThread(threading.Thread):
def __init__(self, rover):
threading.Thread.__init__(self)
self.rover = rover
self.BUFSIZE = 1024
def run(self):
# Accumulates media bytes
mediabytes = ''
# Starts True; set to False by Rover.close()
while self.rover.is_active:
# Grab bytes from rover, halting on failure
try:
buf = self.rover.mediasock.recv(self.BUFSIZE)
except:
break
# Do we have a media frame start?
k = buf.find('MO_V')
# Yes
if k >= 0:
# Already have media bytes?
if len(mediabytes) > 0:
# Yes: add to media bytes up through start of new
mediabytes += buf[0:k]
# Both video and audio messages are time-stamped in 10msec units
timestamp = bytes_to_uint(mediabytes, 23)
# Video bytes: call processing routine
if ord(mediabytes[4]) == 1:
self.rover.processVideo(mediabytes[36:], timestamp)
# Audio bytes: call processing routine
else:
audsize = bytes_to_uint(mediabytes, 36)
sampend = 40 + audsize
offset = bytes_to_short(mediabytes, sampend)
index = ord(mediabytes[sampend+2])
pcmsamples = decodeADPCMToPCM(mediabytes[40:sampend], offset, index)
self.rover.processAudio(pcmsamples, timestamp)
# Start over with new bytes
mediabytes = buf[k:]
# No media bytes yet: start with new bytes
else:
mediabytes = buf[k:]
# No: accumulate media bytes
else:
mediabytes += buf
class _RoverTread(object):
def __init__(self, rover, index):
self.rover = rover
self.index = index
self.isMoving = False
self.startTime = 0
def update(self, value):
if value == 0:
if self.isMoving:
self.rover._spinWheels(self.index, 0)
self.isMoving = False
else:
if value > 0:
wheel = self.index
else:
wheel = self.index + 1
currTime = time.time()
if (currTime - self.startTime) > self.rover.TREAD_DELAY_SEC:
self.startTime = currTime
self.rover._spinWheels(wheel, int(round(abs(value)*10)))
self.isMoving = True
class _RoverCamera(object):
def __init__(self, rover, stopcmd):
self.rover = rover
self.stopcmd = stopcmd
self.isMoving = False
def move(self, where):
if where == 0:
if self.isMoving:
self.rover._sendCameraRequest(self.stopcmd)
self.isMoving = False
elif not self.isMoving:
if where == 1:
self.rover._sendCameraRequest(self.stopcmd-1)
else:
self.rover._sendCameraRequest(self.stopcmd+1)
self.isMoving = True
I know almost nothing about python by the way.
I'm using windows 10 64 bit
At
https://github.com/simondlevy/RoverPylot
it says:
Tips for Windows
Rob Crawley has put a lot of work into getting RoverPylot to work
smoothly on Windows 10. Here are his changes:
Original: # Create a named temporary file for video stream tmpfile =
tempfile.NamedTemporaryFile()
Changed to: tmpfile = tempfile.NamedTemporaryFile(mode='w+b',
bufsize=0 , suffix='.avi', prefix='RoverRev',
dir='\Python27\RoverRev_WinPylot', delete=False) Original: # Wait a
few seconds, then being playing the tmp video file cmd = 'ffplay
-window_title Rover_Revolution -framerate %d %s' % (FRAMERATE, tmpfile.name)
Changed to: cmd = '/Python27/ffmpeg/bin/ffplay.exe -x 640 -y 480
-window_title Rover_Revolution -framerate %d %s' % (FRAMERATE, tmpfile.name) Your files paths may be different than those listed
below, so make your changes accordingly
Which means that the author uses Python 2.7. From your error reports I gather you use Python 3.5, which treats bytes differently. Install and use 2.7 instead.

pyqt4 QTextEdit won't work in my code because of a loop

I have this code that creates a text edit window :
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self.initUI()
print("just started the ui")
def initUI(self):
print("i am in initUi")
self.text = QtGui.QTextEdit(self)
self.setCentralWidget(self.text)
# x and y coordinates on the screen, width, height
self.setGeometry(100,100,1030,800)
self.setWindowTitle("Writer")
sleep(1)
the write_msg() function is ok and writes text to my terminal as expected. but now i would like to use this function to write inside the QTextEdit. problem is that write_msg() has a while loop inside if i have the while loop the window never pop's up, if i remove the while loop window pops up, the editor is there and i can type from my keyboard anything but my function can not work while it fundamental for it.
Here is my write_msg() function :
def write_msg():
print("i am in write_msg function")
#Each analog sensor has some characters to roll
sensor16=['1','-','\\','/','*','!']
sensor15=['4','G','H','I']
sensor14=['7','P','Q','R','S']
sensor13=['*']
sensor12=['2','A','B','C']
sensor11=['5','J','K','L']
sensor10=['8','T','U','V']
sensor09=['0',' ']
sensor08=['3','D','E','F']
sensor07=['6','M','N','O']
sensor06=['9','W','X','Y','Z']
sensor05=['#']
sensor04=['BACKSPACE']
sensor03=['DELETE ALL']
sensor02=['READ']
sensor01=['TRANSMITE']
sensor=[sensor01,sensor02,sensor03,sensor04,sensor05,sensor06,sensor07,sensor08,sensor09,sensor10,sensor11,sensor12,sensor13,sensor14,sensor15,sensor16]
#the maximum number of times each sensor can be pressed
#before it rols back to the first character.
max_press=[1,1,1,1,1,5,4,4,2,4,4,4,1,5,4,6]
num_press=0
message=[]
steps=0
i=0
x=0
key=0
key_pressed=0
#message_string="kjsdfgaqlkfvbnajkefnvbsfejfhvbjhkefrbvksjehdjefbv"
#print(message_string)
#p1 = subprocess.Popen(["minimodem" , '--tx' , '300'], stdin=subprocess.PIPE)
#p1.stdin.write(bytes(message_string, 'UTF-8'))
while state == "wrt":
print("i am looping")
binary_x="{0:04b}".format(x)
GPIO.output(15, int(binary_x[0]))
GPIO.output(13, int(binary_x[1]))
GPIO.output(11, int(binary_x[2]))
GPIO.output(7, int(binary_x[3]))
# average three readings to get a more stable one
channeldata_1 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_2 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_3 = read_mcp3002(0) # get CH0 input
channeldata = (channeldata_1+channeldata_2+channeldata_3)/3
#
# Voltage = (CHX data * (V-ref [= 3300 mV] * 2 [= 1:2 input divider]) / 1024 [= 10bit resolution] #
voltage = int(round(((channeldata * vref * 2) / resolution),0))+ calibration
#print(voltage)
if DEBUG : print("Data (bin) {0:010b}".format(channeldata))
#key_pressed=x
if x==15 : # some problem with this sensor so i had to go and twicked the thresshold
voltage = voltage - 500
#time.sleep(0.05)
if ( voltage > 2500) : #key is released
keypressed = False
keyreleased = True
x=x+1
if ( voltage <= 2500) : #key is pressed
keypressed = True
keyreleased = False
key_pressed=x#define which key is pressed
if key_pressed==0 and key!=0:
transmite(message)
sleep(0.01)
x=x+1
if key_pressed==1:
state == "rd_msg"
x=x+1
if key_pressed==2:
sys.stdout.write('\033[2K')
sys.stdout.write('\033[1G')
message_len = len(message)
for m in range(message_len):
del message[m]
x=x+1
if key_pressed==3:
#print('\b\b')
print('\b ', end="", flush=True)
sys.stdout.write('\010')
message_len = len(message)
del message[message_len]
sleep(1)
x=x+1
if key_pressed > 3:
print("i am pressing a number")
if key == key_pressed :
while num_press <= (max_press[key_pressed]) and keyreleased==False:
# average three readings to get a more stable one
channeldata_1 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_2 = read_mcp3002(0) # get CH0 input
sleep(0.001)
channeldata_3 = read_mcp3002(0) # get CH0 input
channeldata = (channeldata_1+channeldata_2+channeldata_3)/3
#
# Voltage = (CHX data * (V-ref [= 3300 mV] * 2 [= 1:2 input divider]) / 1024 [= 10bit resolution]
#
voltage = int(round(((channeldata * vref * 2) / resolution),0))+ calibration
if DEBUG : print("Data (bin) {0:010b}".format(channeldata))
if x==15 : # some problem with this sensor so i had to go and twicked the thresshold
voltage = voltage - 500
time.sleep(0.05)
if ( voltage > 2500) : #key is released
keyreleased = True
keypressed = False
sys.stdout.write('\033[1C')
char=sensor[key_pressed][num_press-1]
message.append(char)
self.text.setText(char)
num_press=0
else :
keypressed = True
keyreleased= False
if num_press <= max_press[key_pressed] and keyreleased == False:
print(sensor[key_pressed][num_press], end="", flush=True)
sys.stdout.write('\010')
num_press=num_press+1
time.sleep(0.5)
if num_press == max_press[key_pressed] :
num_press=0
if x == 16 :
x=0
key = key_pressed
I have to continuously change the value of x increasing it from 0 to 16 for this function to work properly. Any one has any idea ?
ok ! i've tried to use threading so i can run my write_msg() function but couldn't get it to work either, if i comment the threading the text editor window pops up normally, like nothing happened, and if i uncomment it it pops out this error message:
pi#raspberrypi:~ $ sudo python3 ./Documents/Examples/texting_app.py
[xcb] Unknown sequence number while processing reply
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python3: ../../src/xcb_io.c:635: _XReply: Assertion `!xcb_xlib_threads_sequence_lost' failed.
this is the code in main() to start everything:
def main():
#t = threading.Thread(target=write_msg)
#t.daemon = True
#t.start()
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())

How do perform time-based audio with Pygame?

This is my first question on StackOverflow, so here goes:
Edit: I have edited this a few times, just fixing typing mistakes and updating the code. Even after adding various changes to the code, the issue still remains the exact same.
Also, pygame.mixer.music.fadeout() is not what I'm looking for. This code will also be for when I want to lower music volume to perhaps 50% on, say, pausing the game or entering a talk scene.
With Pygame, I am trying to perform music volume manipulation based on how much time has passed. I already have some decent code created, but it's not performing how I thought it intuitively should. Also, I should note that I am using the component-based EBS system I ripped from PySDL2. Here is the link to the EBS module: https://bitbucket.org/marcusva/py-sdl2/src/02a4bc4f79d9440fe98e372e0ffaadacaefaa5c6/sdl2/ext/ebs.py?at=default
This is my initial block of code:
import pygame
from pygame.locals import *
# Setup import paths for module.
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
sys.path.insert(0, parent_dir)
sys.path.insert(0, os.path.join(parent_dir, "Game"))
import Game
from Porting.sdl2.ext import ebs
pygame.display.quit()
print("Counting down...")
for n in range(5):
print(str(n + 1))
pygame.time.delay(1000)
appworld = ebs.World()
audio_system = Game.audio.AudioSystem(44100, -16, 2, 4096)
appworld.add_system(audio_system)
test1 = Game.sprites.AudioSprite(appworld)
test2 = Game.sprites.AudioSprite(appworld)
test1.audio = Game.audio.Audio(database["BGMusic0"], True)
test2.audio = Game.audio.Audio(database["BGMusic1"], True)
game_clock = pygame.time.Clock()
volume_change_clock = pygame.time.Clock()
loop = True
time_passed = 0
while loop:
game_clock.tick(60)
appworld.process()
time_passed += volume_change_clock.tick(60)
if time_passed > (10 * 1000):
print(time_passed)
if not audio_system.music_volume_changed:
audio_system.set_music_volume(0, True)
My next block of code:
import pygame
from Porting.sdl2.ext import ebs
class AudioSystem(ebs.System):
def __init__(self, frequency, bit_size, channels, buffer):
super(AudioSystem, self).__init__()
self.componenttypes = Audio,
pygame.mixer.init(frequency, bit_size, channels, buffer)
pygame.mixer.set_num_channels(200)
self.frequency = frequency
self.bit_size = bit_size
self.channels = channels
self.buffer = buffer
self.music_volume_change_clock = None
self.music_volume_changed = False
self.music_volume_current = 0
self.music_volume_new = 0
self.music_fade = False
self.music_change_speed = 0
self.time_passed_total = 0
self.time_passed_remainder = 0
def process(self, world, componentsets):
for audio in componentsets:
if audio.is_music:
music = pygame.mixer.music
if not pygame.mixer.music.get_busy():
music.load(audio.file)
music.play()
if self.music_volume_changed:
self.music_volume_current = music.get_volume() * 100
if self.music_volume_current != self.music_volume_new and self.music_fade:
time_passed = self.music_volume_change_clock.tick(60)
self.time_passed_total += time_passed
self.time_passed_total += self.time_passed_remainder
self.time_passed_remainder = 0
if self.time_passed_total > self.music_change_speed:
self.time_passed_remainder = self.time_passed_total % self.music_change_speed
volume_change_amount = int(self.time_passed_total / self.music_change_speed)
self.time_passed_total = 0
if self.music_volume_current > self.music_volume_new:
self.music_volume_current -= volume_change_amount
music.set_volume(self.music_volume_current / 100)
elif self.music_current_volume < self.music_volume_new:
self.music_volume_current += volume_change_amount
music.set_volume(self.music_volume_current / 100)
elif self.music_volume_current != self.music_volume_new:
music.set_volume(self.music_volume_current / 100)
else:
self.music_volume_changed = False
self.music_fade = False
else:
if not audio.channel:
audio.channel = pygame.mixer.find_channel()
audio.channel.play()
def set_music_volume(self, percent, fade = False, change_speed = 50):
self.music_volume_changed = True
self.music_volume_new = percent
self.music_fade = fade
self.music_change_speed = change_speed
self.music_volume_change_clock = pygame.time.Clock()
class Audio(object):
def __init__(self, file, is_music = False):
self.is_music = is_music
if self.is_music:
self.file = file
else:
self.channel = None
self.file = pygame.mixer.Sound(file)
My testing has shown that manipulating the parameter of Clock.tick() in my Game.audio module in various ways influences how quickly the audio playing falls from 100 to 0. Leaving it blank causes it to stop almost instantaneously. At 60, it falls to 0 in around 2 seconds, which baffles me. At 30, in 1 second. At 5, it falls slowly, with the volume never seeming to reach 0. I want to completely desynchronize my audio volume manipulation completely from my game's frame-rate, but I am unsure of how I would accomplish that. I want to avoid threading and multiprocessing if possible.
Thanks in advance! :)
Clock.tick()'s parameter is used to call the SDL sleep function to limit how many times the loop runs per second.
Calling it with Clock.tick(5) limits it to five loops per second.
I've also never used two clocks in the same code, especially with the multiple ticks (all of which will calculate their sleep time individually). Instead of that, consider using the return value of tick (the time in ms since the last call), and use that to track time through the whole application.
Example:
timer = 0
Do things
timer += main_clock.tick(FPS)

Categories

Resources