cannot find evdev2 module - python

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?

Related

why won't my python desktop pet program do anything when i try to run it when it has no errors detected?

Here's the link to the tutorial I followed.
When I try to run it from IDLE, it only says RESTART:
C:\Users\USER\Downloads\pythonpetashy.py and doesn't do anything
I'm using Python 3.10.4 on Windows.
And here is the code:
import random
import tkinter as tk
import pyautogui
x = 1400
cycle = 0
check = 1
idle_num = [1,2,3,4]
popo_num = [13,15]
angy_num = [10,11,12]
walk_left = [5,6,7]
walk_right = [8,9,14]
event_number = random.randrange(1,3,1)
impath = r"C:\Users\USER\Downloads\desktop project"
#transfer random no. to event
def event(cycle,check,event_number,x):
if event_number in idle_num:
check = 0
print('idle')
window.after(400,update,cycle,check,event_number,x) #no. 1,2,3,4 = idle
elif event_number in popo_num:
check = 1
print('idle to popo')
window.after(100,update,cycle,check,event_number,x) #no. 13,15 = idle to popo
elif event_number in walk_left:
check = 3
print('walking towards left')
window.after(100,update,cycle,check,event_number,x)#no. 5,6,7 = walk towards left
elif event_number in walk_right:
check = 4
print('walking towards right')
window.after(100,update,cycle,check,event_number,x)#no. 8,9,14 = walk towards right
elif event_number in angy_num:
check = 2
print('angy')
window.after(100,update,cycle,check,event_number,x)#no. 10,11,12 = angy
#make the gif work
def gif_work(cycle,frames,event_number,first_num,last_num) :
if cycle < len(frames) -1:
cycle+=1
else:
cycle = 0
event_number = random.randrange(first_num,last_num+1,1)
return cycle, event_number
def update(cycle,check,event_number,x):
#idle
if check ==0:
frame = idle[cycle]
cycle ,event_number = gif_work(cycle,idle,event_number,1,9)
#idle to popo
elif check ==1:
frame = idle_to_popo[cycle]
cycle ,event_number = gif_work(cycle,idle_to_popo,event_number,1,9)
#angy
elif check == 2:
frame = angy[cycle]
cycle ,event_number = gif_work(cycle,angy,event_number,1,9)
#walk toward left
elif check == 3:
frame = walk_positive[cycle]
cycle, event_number = gif_work(cycle,walk_positive,event_number,1,9)
x -= 3
#walk towards right
elif check == 4:
frame = walk_negative[cycle]
cycle, event_number = gif_work(cycle,walk_positive,event_number,1,9)
x -= -3
window.geometry('100x100+'+str(x)+'1050')
label.configure(image=frame)
window.after(1,event,cycle,check,event_number,x)
window = tk.Tk()
#call ashy's action .gif to an array
idle = [tk.PhotoImage(file=impath+'\idleme.gif',format = 'gif -index %i' %(i)) for i in range(8)]#idle gif, 8 frames
idle_to_popo = [tk.PhotoImage(file=impath+'\idletopopo.gif',format = 'gif -index %i' %(i)) for i in range(13)] #idle to popo gif, 13 frames
angy = [tk.PhotoImage(file= r"C:\Users\USER\Downloads\desktop project\angyme.gif",format = 'gif -index %i' %(i)) for i in range(15)]#angy me gif, 15 frames
walk_positive = [tk.PhotoImage(file=impath+'\walkingleft.gif',format = 'gif -index %i' %(i)) for i in range(13)]#walking left gif, 13 frames
walk_negative = [tk.PhotoImage(file=impath+'\walkingright.gif',format = 'gif -index %i' %(i)) for i in range(13)]#walking right gif, 13 frames
#window configuration
window.config(highlightbackground='black')
window.overrideredirect(True)
window.wm_attributes('-transparentcolor','black')
label = tk.Label(window,bd=0,bg='black')
label.pack()
#loop the program
window.after(1,update,cycle,check,event_number,x)
window.mainloop()
I'm completely new to the world of Python programming, so I guess it was kind of ambitious for me to attempt to make a more complicated program. I followed everything the tutorial said, but I have no idea why it won't do anything since there aren't any errors detected. Admittedly, I did underestimate the complications of making such a program, but it's supposed to be a gift so I really want this to work.
a bit of explanation on what it's supposed to do, basically it should open a transparent window where the GIFs i've made would show up and move around randomly like a normal desktop pet would.

Python script module not found on rerun of script

I am running a python script on RaspberryPi 4, and today when I ran the script again, it showed me the error ModuleNotFoundError: No module named 'adafruit_ssd1306' although I ran this same script yesterday about 10 times, it ran perfectly without any errors. I did not change anything in the script, not even its location. I tried force reinstalling the library,
running the script from another location, rebooting the pi, running it as sudo but none of them worked either.
By using pip3 freeze it shows that the package is installed and trying to install the package again says that the requirement is already satisfied.
Python version: 3.7
Main.py
import time
import board
import digitalio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
import requests
WIDTH = 128
HEIGHT = 64 # Change to 64 if needed
BORDER = 5
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
API_KEY = "API Key"
sign = '°'
# Use for I2C.
i2c = board.I2C()
oled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c, addr=0x3C)
dir_pin = digitalio.DigitalInOut(board.D23)
step_pin = digitalio.DigitalInOut(board.D24)
call_b = digitalio.DigitalInOut(board.D18)
dir_pin.direction = digitalio.Direction.INPUT
step_pin.direction = digitalio.Direction.INPUT
call_b.direction = digitalio.Direction.INPUT
dir_pin.pull = digitalio.Pull.UP
step_pin.pull = digitalio.Pull.UP
prev_value = True
cities = ['Delhi','Tokyo','London','San Francisco',
'kanpur','Mumbai','portugal','Toronto','Sydney','Paris','New York','Dubai',
'Moscow','Rome','Madrid','Riyadh','Bangkok','Cairo','Istanbul','Kolkata',
'Beijing','Seoul','Shanghai','Osaka','Hong Kong','Bangalore','Kathmandu',
'Chennai','Kathmandu','Manila','Jakarta','Tehran','Baghdad','Riyadh','Abu Dhabi',
'Dubai','Kuala Lumpur','Chennai','Kathmandu','Manila','Jakarta','Tehran','Baghdad']
font_size = 12
font = ImageFont.truetype('/home/pi/Desktop/Poppins-Regular.ttf', font_size)
font_big = ImageFont.truetype('/home/pi/Desktop/Poppins-Regular.ttf', font_size+4)
font_xl = ImageFont.truetype('/home/pi/Desktop/Poppins-Regular.ttf', font_size+7)
max_cities = len(cities) - 1
value = 0
def get_temp(city):
url = BASE_URL + "q=" + city + "&appid=" + API_KEY
r = requests.get(url)
if r.status_code == 200:
data = r.json()
temp = data['main']['temp']
humidity = data['main']['humidity']
temp = int(temp)
humidity = int(humidity)
temp = temp - 273
#humidity = humidity+"%"
temp = str(temp)+sign+'c'
# h = "Humidity: "+str(humidity)
return temp
def create_image(temp,city):
image = Image.new("1", (oled.width, oled.height))
draw = ImageDraw.Draw(image)
(fw,fh) = font.getsize(city)
(w,h) = font_xl.getsize(temp)
draw.text((128//2 - fw//2,12),city,fill=255,font=font) # city name
draw.text((128//2 - w//2,30),temp,fill=255,font=font_xl) # temp
return image
def text_image(city):
image_ = Image.new("1", (oled.width, oled.height))
draw = ImageDraw.Draw(image_)
(font_width, font_height) = font_big.getsize(city)
draw.text((128//2 - font_width//2, 64//2 - font_height//2),city, font=font_big, fill=255)
oled.fill(0)
oled.image(image_)
oled.show()
g = "Temprature\n Meter"
intro = Image.new("1", (oled.width, oled.height))
d = ImageDraw.Draw(intro)
# Draw text
(font_width, font_height) = font.getsize(g)
d.text((20, 6),
g, font=font_big, fill=255)
oled.fill(0)
oled.image(intro)
oled.show()
timer = 0
while True:
if prev_value != step_pin.value:
if step_pin.value == False:
if dir_pin.value == False:
print("left") # left
value = value + 1
if value > max_cities:
value = 1
print(value)
selected_city = cities[value]
print(selected_city)
text_image(selected_city)
else:
print("right") # right
if value == 0:
value = max_cities
else:
value = value - 1
print(value)
selected_city = cities[value]
print(selected_city)
text_image(selected_city)
prev_value = step_pin.value
while call_b.value == False:
timer = timer+1
if timer > 70000 and timer < 150000:
oled.fill(0)
oled.show()
timer = 0
print("blank")
time.sleep(2)
print("active")
elif timer < 15000 and timer > 500:
t = get_temp(selected_city)
print(t)
# display the data to the OLED
image = create_image(t,selected_city)
oled.fill(0) #clear display
oled.show()
oled.image(image)
oled.show()
timer = 0
time.sleep(1)
else:
timer = 0
it is sometimes happen when I forgot to activate the virtualenv, even I can install new libraries using pip or pip3 without virtualenv. But python main.py won't run. Then I realized that I haven't turn on the virtual environment.
1- make sure you typed the name of module correctly
2- make sure you use the correct python version
python3:
python3 script.py
3- also make sure it installed with the correct pip installer you may used pip for python2 by mistake
python3 -m pip install some_module
4- better way to make a virtual environment
virtualenv -p python3 env
# then
. env/bin/activate
python # ← will run python3
you may read
this answer on stack overflow about venv and pip versions
and official documentation for venv
you may search for virtual environment on raspberry pi if there is any different setups may be needed but as I remember it is most likely like Ubuntu

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

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

Raspberry Pi: Error when using Kivy's TextInput(): [CRITICAL] [Clipboard ] Unable to find any valuable Clipboard provider at all

I wrote a dmx control program in python using kivy.
I tried to copy it onto a raspberry pi 2 version b (with raspberian installed on it, python and kivy as described in the manual of kivy->manual installation on a raspberry pi.)
Everything works fine, i only get an error, when a TextInput() is displayed on the widget currently loaded. I got these errors:
On my computer running windows 7 x64 everything is going fine.
Following I tried to solve the problem:
I changed all "TextInput" into "Label" widgets, everything worked. So it must be the TextInput
I connected a USB keyboard on the raspberry pi to check, if the error has something to do with missing key input devices - there is no change with oder without keyboard.
Here is the contents of the kivy config.ini file:
[kivy]
keyboard_repeat_delay = 300
keyboard_repeat_rate = 30
log_dir = logs
log_enable = 1
log_level = info
log_name = kivy_%y-%m-%d_%_.txt
window_icon =
keyboard_mode =
keyboard_layout = qwerty
desktop = 1
exit_on_escape = 0
pause_on_minimize = 0
config_version = 14
[graphics]
display = -1
fullscreen = 0
height = 600
left = 0
maxfps = 60
multisamples = 2
position = auto
rotation = 0
show_cursor = 1
top = 0
width = 800
resizable = 1
borderless = 0
window_state = visible
minimum_width = 0
minimum_height = 0
[input]
mouse = mouse
%(name)s = probesysfs,provider=hidinput,param=invert_y=0
[postproc]
double_tap_distance = 20
double_tap_time = 250
ignore = []
jitter_distance = 0
jitter_ignore_devices = mouse,mactouch,
retain_distance = 50
retain_time = 0
triple_tap_distance = 20
triple_tap_time = 375
[widgets]
scroll_timeout = 250
scroll_distance = 20
scroll_friction = 1.
scroll_stoptime = 300
scroll_moves = 5
[modules]
This solved it for me:
sudo apt-get install xclip xsel

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