rahul-thakoor / rust_gpiozero

A library inspired by gpiozero written in Rust
https://crates.io/crates/rust_gpiozero
Apache License 2.0
230 stars 27 forks source link

Not a press/release state change #41

Open johansmitsnl opened 1 year ago

johansmitsnl commented 1 year ago

I thought that when I have this code it should switch from press to release and back. Instead it does only work on the flanks. So when I press it fires. When I release it does nothing. When I press again it fires the release.

use rust_gpiozero::{Button, Debounce, LED};
use std::time::Duration;

fn main() {
    // Led output
    let led = LED::new(17);
    // Create a button which is attached to Pin 27
    let mut button = Button::new(27)
        // Add debouncing so that subsequent presses within 100ms don't trigger a press
        .debounce(Duration::from_millis(100));

    led.off();
    println!("Ready for input changed");

    button.wait_for_press(None);
    println!("Button status is pressed {}", button.is_active());
    led.on();

    button.wait_for_release(None);
    println!("Button status is released {}", button.is_active());
    led.off();
}

Output is: < comments between here >

Ready for input changed => Led is off
< Press button >
Button status is pressed false < Why is status false since it is pressed? >
< Release button >
< Nothing happens wait for 2 seconds >
<Press button >
Button status is released false

I try to make the same example as in Python:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# LED
GPIO.setup(17,GPIO.OUT)

# Input
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.output(17,GPIO.HIGH)

while True:
    input_state = GPIO.input(27)
    if input_state == False:
       GPIO.output(17,GPIO.LOW)
    else:
      GPIO.output(17,GPIO.HIGH)

    time.sleep(0.1)

Note that in Python I use the GPIO.PUD_UP

johansmitsnl commented 1 year ago

a refactor to this works as the python code:

use rust_gpiozero::{InputDevice, LED};
use std::{thread, time::Duration};

fn main() {
    // Led output
    let mut led = LED::new(17);
    // Create a button which is attached to Pin 17
    let button = InputDevice::new_with_pullup(27);

    led.on();
    println!("Ready for input changed");

    loop {
        if button.is_active() {
            println!("Button status is pressed");
            led.on();
        } else {
            println!("Button status is released");
            led.off();
        }

        thread::sleep(Duration::from_millis(300));
    }
}