djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 9:51 am

Hello,
I am asking for your help because I have several problems. I'm starting with Python, my code isn't super clean :)

I have a Waveshare 3.2C, RPI 3A + screen under Retropie.
The objective of my code below is to change the screen brightness under Retropie when I press the screen push button (GPIO24) with 3 brightness values: 900, 350 and 150. (1024 being the max and 1 the minimum). The value ​​changes after each click of the button to switch from one value to another.

My problems are as follows:
1. The Python script takes 100% of the CPU, I don't know how to fix this.

2. Each time the GPIO24 button is clicked, the values ​​do not come out in order, I have to press 8 or 10 times for example to get the value 150 instead of clicking the button 3 times.

3. Under Retropie in a game, when I run gpio -g pwm 18 1024 from the shell, then gpio -g mode 18 pwm, the sound is cutted off, we can hear a big click in the speaker of the Headphone output. Then I type gpio pwmc 1000 and a big noizy sound appears.

Thank you very much for your help.

djblex

Code: Select all

#!/usr/bin/env python2.7

import RPi.GPIO as GPIO
import time
import os
from time import sleep
import subprocess
import RPi.GPIO as GPIO


btn = 24


# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(ledPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up


count = 0

isButtonPressed = False
while True:


    if GPIO.input(btn) == GPIO.LOW and isButtonPressed:
        isButtonPressed = False
        time.sleep(0.1)

    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed:
        isButtonPressed = True
        count += 1
        os.system('gpio -g mode 18 pwm')
        os.system('gpio -g pwm 18 900')
        os.system('gpio pwmc 0')
        time.sleep(0.1)
        print ("900b")
        time.sleep(0.1)
    
    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed:
        isButtonPressed = True
        count += 1
        os.system('gpio -g mode 18 pwm')
        os.system('gpio -g pwm 18 350')
        os.system('gpio pwmc 0')
        time.sleep(0.1)
        print ("350b")
     
    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed:
        isButtonPressed = True
        count += 1
        os.system('gpio -g mode 18 pwm')
        os.system('gpio -g pwm 18 150')
        os.system('gpio pwmc 0')
        time.sleep(0.1)
        print ("150b")
     
    GPIO.cleanup()

try:
	while True:

		# faites ce qui vous plait
		sleep (2)

# on reinitialise les ports GPIO en sortie de script
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

gordon77
Posts: 5678
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 10:09 am

1. Put a time.sleep() in your while loop, try small values.
2. Try increasing your other time.sleep() values, could but button bounce

djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 6:04 pm

Thanks for your advices.
Unfortunately, I tried setting the time.sleep higher but it takes a bit longer for the processor to reach 100%.
I reworked the script a little cleaner but it's the same, the processor stays at 100% every time I do the command "gpio -g pwm" value "" in the script (triggered after each click on the button) .
The only way I have found is to place a "break" at the end of each command but the script no longer changes to another value when I click the button.
It would take a condition, but I don't know which one.
If you have any ideas :)
thank you

Code: Select all

#!/usr/bin/env python2.7

import RPi.GPIO as GPIO
import time
import os
from time import sleep
import subprocess


btn = 24

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(btn, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up

def pwmMode():
    os.system('gpio -g mode 18 pwm &')

def pwm900v():      
    os.system('gpio -g pwm 18 900 &')

def pwm350v():      
    os.system('gpio -g pwm 18 350 &')

def pwm150v():      
    os.system('gpio -g pwm 18 150 &')

def pwmc():
    os.system(['gpio pwmc 0 &'])

# notre fonction de gestion du bouton
def system_button(CHANNEL):
    # cette variable servira a stocker le temps de pression
    button_press_timer = 0


isButtonPressed = False

pwmMode()

count = 0
while True:
	

    if GPIO.input(btn) == GPIO.LOW and isButtonPressed:
        isButtonPressed = False
        time.sleep(0.01)


    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed:
        isButtonPressed = True
        count += 1
        pwm900v()
        print ("900b")
        time.sleep(0.01)

    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed:
        isButtonPressed = True
        count += 1
        pwm350v()
        print ("350b")
        time.sleep(0.01)
     
    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed:
        isButtonPressed = True
        count += 1
        pwm150v()
        print ("150b")
        time.sleep(0.01)

try:
	while True:


		# faites ce qui vous plait
		sleep (2)

# on reinitialise les ports GPIO en sortie de script
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

gordon77
Posts: 5678
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 6:36 pm

Try adding time.sleep here

while True:
time.sleep(0.1)

if GPIO.input(btn) == GPIO.LOW and isButtonPressed:

djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 7:34 pm

Thank you ,
it works for the Processor which stop beeing at 100%.
But now, each time i click on the button, i can't obtain the another value than 900b.
Alternatively, i should see printing values :
900b
350b
150b
900b
350b
150b
...
Attachments
Capture.JPG
Capture.JPG (18.47 KiB) Viewed 958 times

gordon77
Posts: 5678
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:09 pm

You have 3 lines of elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed:

It's only ever going to choose the first one...

gordon77
Posts: 5678
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:15 pm

Try this ...

Code: Select all

#!/usr/bin/env python2.7

import RPi.GPIO as GPIO
import time
import os
from time import sleep
import subprocess


btn = 24
Value = 150

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(btn, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up

def pwmMode():
    os.system('gpio -g mode 18 pwm &')

def pwm900v():      
    os.system('gpio -g pwm 18 900 &')

def pwm350v():      
    os.system('gpio -g pwm 18 350 &')

def pwm150v():      
    os.system('gpio -g pwm 18 150 &')

def pwmc():
    os.system(['gpio pwmc 0 &'])

# notre fonction de gestion du bouton
def system_button(CHANNEL):
    # cette variable servira a stocker le temps de pression
    button_press_timer = 0


isButtonPressed = False

pwmMode()

count = 0
while True:
    time.sleep(0.1)
	

    if GPIO.input(btn) == GPIO.LOW and isButtonPressed:
        isButtonPressed = False
        time.sleep(0.01)


    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed and Value == 150:
        isButtonPressed = True
        count += 1
        Value = 900
        pwm900v()
        print ("900b")
        time.sleep(0.2)
    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed and Value == 900:
        isButtonPressed = True
        count += 1
        Value =350
        pwm350v()
        print ("350b")
        time.sleep(0.2)
     
    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed and Value == 350:
        isButtonPressed = True
        count += 1
        Value = 150
        pwm150v()
        print ("150b")
        time.sleep(0.2)

try:
	while True:


		# faites ce qui vous plait
		sleep (2)

# on reinitialise les ports GPIO en sortie de script
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()
[/quote]
Last edited by gordon77 on Sun May 16, 2021 8:33 pm, edited 1 time in total.

ghp
Posts: 1964
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:21 pm

Let me propose this solution
It separates the detection and debouncing of the button from the other code. A queue is used to send events from the ButtonDebounce class to the main loop.
In the main loop, a state is used to track the brightness levels.

Why do you use the os calls ? You could solve this with rpi.gpio pwm calls also.
Switch to python3. Python2 is obsolete.

Code: Select all

#!/usr/bin/env python3

import RPi.GPIO as GPIO
import os
import queue
import subprocess
import sys
import threading
import time

assert sys.version_info >= (3, 7)

btn = 24

debug = True

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme

class ButtonDebounce:
    def __init__(self, btn, event_queue):
        self.btn = btn
        GPIO.setup(self.btn, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up

        self.event_queue = event_queue
        self.thread = threading.Thread(target=self._run)
        self.thread.start()
        
    def _run(self):
        """debounce the button and send events to a queue"""
        
        print("_run")
        high_count = 0
        low_count = 0
        
        while True:
            time.sleep(0.01)
            if GPIO.input(self.btn) == GPIO.LOW:
                low_count += 1
                high_count = 0
            if GPIO.input(self.btn) == GPIO.HIGH:
                low_count = 0
                high_count += 1
                
            # print(low_count, high_count)    
            
            if high_count == 10:
                self.event_queue.put("high")
            if low_count == 10:
                self.event_queue.put("low")
                
event_queue = queue.Queue()
button_debounce = ButtonDebounce( btn, event_queue)            
                 
def pwmMode():
    cmd = "gpio -g mode 18 pwm &"
    if debug: print( cmd)
    else:   
        """why not execute this os call by a RPI GPIO command ? """
        os.system(cmd)

def pwm900v():      
    cmd = "gpio -g pwm 18 900 &"
    if debug: print( cmd)
    else:   os.system(cmd)

def pwm350v():      
    cmd = "gpio -g pwm 18 350 &"
    if debug: print( cmd)
    else:   os.system(cmd)

def pwm150v():      
    cmd = "gpio -g pwm 18 150 &"
    if debug: print( cmd)
    else:   os.system(cmd)

def pwmc():
    cmd = "gpio pwmc 0 &"
    if debug: print( cmd)
    else:   os.system(cmd)

# notre fonction de gestion du bouton
def system_button(CHANNEL):
    # cette variable servira a stocker le temps de pression
    button_press_timer = 0

pwmMode() # ???

count = 0
OFF = "OFF"
LOW = "LOW"
MEDIUM = "MEDIUM"
HIGH = "HIGH"

pwmc()

state = OFF

try:
    while True:
        
        event = event_queue.get()
        if state == OFF:
            if event == 'high':
                pwm150v()
                state = LOW

        elif state == LOW:
            if event == 'high':
                pwm350v()
                state = MEDIUM
            
        elif state == MEDIUM:
            if event == 'high':
                pwm900v()
                state = HIGH
            
        elif state == HIGH:
            if event == 'high':
                pwm150v()
                state = LOW
        
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:35 pm

yeahhh thank you !!! almost done :)
i have two values in alternate. i don't know why the 150b do not appears !
Image
Attachments
Capture2.JPG
Capture2.JPG (15.93 KiB) Viewed 922 times

gordon77
Posts: 5678
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:36 pm

Try my code again, fixed hopefully

djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:41 pm

My answer below was for you gordon77 :)

gordon77
Posts: 5678
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:42 pm

djblex wrote:
Sun May 16, 2021 8:41 pm
My answer below was for you gordon77 :)
I know, l replied..

Code: Select all

#!/usr/bin/env python2.7

import RPi.GPIO as GPIO
import time
import os
from time import sleep
import subprocess


btn = 24
Value = 150

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(btn, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up

def pwmMode():
    os.system('gpio -g mode 18 pwm &')

def pwm900v():      
    os.system('gpio -g pwm 18 900 &')

def pwm350v():      
    os.system('gpio -g pwm 18 350 &')

def pwm150v():      
    os.system('gpio -g pwm 18 150 &')

def pwmc():
    os.system(['gpio pwmc 0 &'])

# notre fonction de gestion du bouton
def system_button(CHANNEL):
    # cette variable servira a stocker le temps de pression
    button_press_timer = 0


isButtonPressed = False

pwmMode()

count = 0
while True:
    time.sleep(0.1)
	

    if GPIO.input(btn) == GPIO.LOW and isButtonPressed:
        isButtonPressed = False
        time.sleep(0.01)


    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed and Value == 150:
        isButtonPressed = True
        count += 1
        Value = 900
        pwm900v()
        print ("900b")
        time.sleep(0.2)
    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed and Value == 900:
        isButtonPressed = True
        count += 1
        Value =350
        pwm350v()
        print ("350b")
        time.sleep(0.2)
     
    elif GPIO.input(btn) == GPIO.HIGH and not isButtonPressed and Value == 350:
        isButtonPressed = True
        count += 1
        Value = 150
        pwm150v()
        print ("150b")
        time.sleep(0.2)

try:
	while True:


		# faites ce qui vous plait
		sleep (2)

# on reinitialise les ports GPIO en sortie de script
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:48 pm

For Ghp and Gordon77,
i am really a beginner in python language.
Thanks both for your advices and codes, i will try your script too (Ghp) , i need to install python 3. i will make a reply

ghp
Posts: 1964
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Sun May 16, 2021 8:51 pm

i need to install python 3.
in a current "pi raspbian" aka "pi os", python3 is available.

djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Mon May 17, 2021 12:14 pm

For Ghp,
I tried your code in changing import queue and assert... for it runs.
The Print Values change really well but there are no action brigtness changement as if my Def do not work.
And i can not exit the script with keyboard (ctrl +c)
Sorry for my lack of knowledge and thank for you help :)

Code: Select all


#!/usr/bin/env python3

import RPi.GPIO as GPIO
import os
#import queue
import Queue as queue
import subprocess
import sys
import threading
import time

#assert sys.version_info >= (3, 7)
assert sys.version_info >= (3)
btn = 24

debug = True

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme

class ButtonDebounce:
    def __init__(self, btn, event_queue):
        self.btn = btn
        GPIO.setup(self.btn, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up

        self.event_queue = event_queue
        self.thread = threading.Thread(target=self._run)
        self.thread.start()
        
    def _run(self):
        """debounce the button and send events to a queue"""
        
        print("_run")
        high_count = 0
        low_count = 0
        
        while True:
            time.sleep(0.01)
            if GPIO.input(self.btn) == GPIO.LOW:
                low_count += 1
                high_count = 0
            if GPIO.input(self.btn) == GPIO.HIGH:
                low_count = 0
                high_count += 1
                
            # print(low_count, high_count)    
            
            if high_count == 10:
                self.event_queue.put("high")
            if low_count == 10:
                self.event_queue.put("low")
                
event_queue = queue.Queue()
button_debounce = ButtonDebounce( btn, event_queue)            
                 
def pwmMode():
    cmd = "gpio -g mode 18 pwm &"
    if debug: print( cmd)
    else:   
        """why not execute this os call by a RPI GPIO command ? """
        os.system(cmd)

def pwm900v():      
    cmd = "gpio -g pwm 18 900 &"
    if debug: print( cmd)
    else:   os.system(cmd)

def pwm350v():      
    cmd = "gpio -g pwm 18 350 &"
    if debug: print( cmd)
    else:   os.system(cmd)

def pwm150v():      
    cmd = "gpio -g pwm 18 150 &"
    if debug: print( cmd)
    else:   os.system(cmd)

def pwmc():
    cmd = "gpio pwmc 0 &"
    if debug: print( cmd)
    else:   os.system(cmd)

# notre fonction de gestion du bouton
def system_button(CHANNEL):
    # cette variable servira a stocker le temps de pression
    button_press_timer = 0

pwmMode() # ???

count = 0
OFF = "OFF"
LOW = "LOW"
MEDIUM = "MEDIUM"
HIGH = "HIGH"

pwmc()

state = OFF

try:
    while True:
        
        event = event_queue.get()
        if state == OFF:
            if event == 'high':
                pwm150v()
                state = LOW

        elif state == LOW:
            if event == 'high':
                pwm350v()
                state = MEDIUM
            
        elif state == MEDIUM:
            if event == 'high':
                pwm900v()
                state = HIGH
            
        elif state == HIGH:
            if event == 'high':
                pwm150v()
                state = LOW
        
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

ghp
Posts: 1964
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Mon May 17, 2021 12:31 pm

Code: Select all

debug = True # <<< change to False !

def pwm350v():      
    cmd = "gpio -g pwm 18 350 &"
    if debug: print( cmd)
    else:   os.system(cmd)

gordon77
Posts: 5678
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Mon May 17, 2021 1:15 pm

is this a bit simpler to get you started...

Code: Select all

#!/usr/bin/env python3

import RPi.GPIO as GPIO
import time
import os
from time import sleep

btn = 24

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setwarnings(False)
GPIO.setup(btn, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Button pin set as input w/ pull-up
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 100)
pwm.start(20)

count = 0
while True:
    sleep(0.1)
    if GPIO.input(btn) == GPIO.LOW:
        count += 20
        if count > 100:
            count = 20
        print (count)
        pwm.ChangeDutyCycle(count)
        sleep(0.2)

try:
    while True:
        # faites ce qui vous plait
        sleep(2)

# on reinitialise les ports GPIO en sortie de script
except KeyboardInterrupt:
    GPIO.cleanup()
GPIO.cleanup()

djblex
Posts: 9
Joined: Sun Mar 18, 2018 10:39 pm

Re: Python Issues : press a button to change the brightness on Waveshare 3.2C

Mon May 17, 2021 7:58 pm

Thanks to you both,
your scripts are excellent and i'm learning thanks to you :).

Your last Gordon77 script solves the 3 problems:
1. The Python script is taking 100% of the CPU, I don't know how to fix this problem: SOLVED

2. Each time we click on the GPIO24 button, the values ​​do not come out in order, I have to press 8 or 10 times for example to get the value 150 instead of clicking 3 times on the button: SOLVED

3. Under Retropie in a game, when I run gpio -g pwm 18 1024 from the shell, then gpio -g mode 18 pwm, the sound is muted, we can hear a big click in the speaker of the headphone output. Then I type gpio pwmc 1000 and a big noizy sound appears: SOLVED

I can change the brightness in playing games without cutting off sound or hearing clicks or bizarre Sounds

Thank you for your work :)

Return to “Python”