Giter Club home page Giter Club logo

rust_gpiozero's Introduction

rust_gpiozero

CI Crates.io

A simple interface to GPIO devices with Raspberry Pi.

This library is based on GPIOZero library.

The idea is to get started with physical computing using Rust with little coding by hiding the underlying complexity.

The library uses BCM Pin numbering

Example : Blinking an LED

use rust_gpiozero::*;

fn main() {
    // Create a new LED attached to Pin 17
    let mut led = LED::new(17);

    // on_time = 2 secs, off_time=3 secs
    led.blink(2.0,3.0);

    // prevent program from exiting immediately
    led.wait();
}

Example : Wait for a Button Press

use rust_gpiozero::*;

fn main() {
    // Create a button which is attached to Pin 17
    let mut button = Button::new(17);
    button.wait_for_press(None);
    println!("button pressed");
}

Compare this to using the crate sysfs_gpio to blink an LED on the Raspberry Pi :

extern crate sysfs_gpio;

use sysfs_gpio::{Direction, Pin};
use std::thread::sleep;
use std::time::Duration;

fn main() {
    let my_led = Pin::new(127); // number depends on chip, etc.
    my_led.with_exported(|| {
        loop {
            my_led.set_value(0).unwrap();
            sleep(Duration::from_millis(200));
            my_led.set_value(1).unwrap();
            sleep(Duration::from_millis(200));
        }
    }).unwrap();
}

Install/Use

To use rust_gpiozero, first add this to your Cargo.toml:

[dependencies]
 rust_gpiozero = "^0.2"

Compiling your project on a Raspberry Pi directly can take significant time depending on the model. Ideally, you would cross compile your project then run it on the Raspberry Pi.

More information

Features

The following features are planned :

  • Support for embedded-hal
  • Support for common devices such as Accelerometer, Temperature sensors, etc

Changelog

CHANGELOG.md

License

Licensed under either of

at your option.

Contributing

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Thanks for your interest in rust_gpiozero. I am a newbie rustacean and just started using the language! I am using this project to learn more about Rust. Feel free to give feedback or send PRs. Your experiences and feedback will also benefit others who use this library.

Credits

This library would not be possible without the great work of the maintainers of GPIOZero and rppal

rust_gpiozero's People

Contributors

aldaronlau avatar dcroote avatar dmalenic avatar llewelld avatar owenbrooks avatar rahul-thakoor avatar rustypro avatar thepacketgeek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rust_gpiozero's Issues

Support for Raspberry Pi 4

The provided rust_gpiozero examples do not work on Raspberry Pi 4, but the examples provided with rppal version 0.12.0 do. Is it possible to release a new version of this crate with upgraded rppal dependency to 0.12.0?
According to rppal documentation rppal is compatible with the Raspberry Pi A, A+, B, B+, 2B, 3A+, 3B, 3B+, 4B, CM, CM 3, CM 3+, CM 4, 400, Zero and Zero W.

Questions regarding this project!

Hi, I have some questions regarding this project.

  1. Is this project abandoned as it hasn't been updated for a long time?
  2. Would this crate also work on the Odroid and similar mini computers with GPIO ports?
  3. Is this based on embedded-hal crate?
  4. Is this library stable? If not, would the API have significant changes overtime?
  5. Does this crate support the same amount of devices like the original gpiozero?

Output devices clear effects

When running the following code, the second blink command does not work and it continues to run the first blink:

led.blink(0.05, 0.05, 0.0, 0.0);
thread::sleep(Duration::from_millis(1000));
led.blink(1.0, 1.0, 0.0, 0.0);

Is there any way to stop all current processes?

Improve output device support

Currently only the LED, PWMLED, Buzzer, Motor and Servo output device are implemented. GPIO Zero has support for several others and it would be great to have support for them here too:

  1. LED
  2. PWMLED
  3. RGBLED
  4. Buzzer
  5. TonalBuzzer
  6. Motor
  7. PhaseEnableMotor
  8. Servo
  9. AngularServo

Some questions

Hi I wanted to ask some questions:

This library is based on GPIOZero library.

This is from the README.md. So like is this crate using gpiozero as the backend or is rust_gpiozero a complete rewrite and it uses its own thing?

Does this crate support all the devices as gpiozero supports?

Also is this project still continuing?

Servo jitter on hardware PWM pin

I'm having jitter with a servo running on PWM pin 12 or 18. Sometimes it jumps while it needs to stay still.

Is the hardware PWM used with this library or does it still uses the software PWM?

Unable to make rust servo code work

I've tested this python code on my servo: https://gpiozero.readthedocs.io/en/stable/api_output.html?highlight=servo#servo

from gpiozero import Servo
from time import sleep

servo = Servo(11)

while True:
    servo.min()
    sleep(1)
    servo.mid()
    sleep(1)
    servo.max()
    sleep(1)

and it works as expected, However when I translated it to rust it didn't work, is there anything I'm missing?

(Thanks for porting this library to rust btw ❤️ )

use rust_gpiozero::Servo;
use std::{thread::sleep, time::Duration};

fn main() {
    let mut servo = Servo::new(11);

    loop {
        servo.min();
        sleep(Duration::from_secs(1));
        servo.mid();
        sleep(Duration::from_secs(1));
        servo.max();
        sleep(Duration::from_secs(1));
    }
}

Strange behavior with Button

Hi, Thanks for the nice library, it's faster than python ;-)

I am using a raspberry pi and I tried the following code:

use rust_gpiozero::Debounce;
use rust_gpiozero::*;

use std::{thread, time::Duration};

fn main() -> ! {
    let mut red_button = Button::new(2).debounce(Duration::from_millis(100));

    red_button
        .when_pressed(|x| {
            println!("button pressed {x:?}");
        })
        .unwrap();
    red_button
        .when_released(|x| {
            println!("button released {x:?}");
        })
        .unwrap();
}

What I see when I press the button twice:

$ cargo run
   Compiling rationalizer v0.1.0 (/home/happy/rationalizer)
    Finished dev [unoptimized + debuginfo] target(s) in 3.75s
     Running `target/debug/rationalizer`
button released Low
button released Low
button released Low
button released Low

What I expected:

$ cargo run
   Compiling rationalizer v0.1.0 (/home/happy/rationalizer)
    Finished dev [unoptimized + debuginfo] target(s) in 3.75s
     Running `target/debug/rationalizer`
button pressed High
button released Low
button pressed High
button released Low

Servo set max pulse width math is incorrect

    /// Set the servo's maximum pulse width
    pub fn set_max_pulse_width(&mut self, value: u64) {
        if value >= self.frame_width {

The default frame_width is set to 20, while the default max_pulse_width is 2000. However, my servo goes to 2100. I'm unable to change this because as seen above, 2100 >= 20.

To work around this, I have to set frame_width to something greater than 2100, increase max_pulse_width to 2100, and then decrease frame_width back to 20.

Panic on simple blink example

Raspberry PI4 4GB, Raspberry PI OS up to date version
Simple blink program results in Panic (back trace below). I am trying to learn Rust, cant figure out what the issue is. Simple hello_world type programs run fine, so looks like Rust install is fine. Tried with sudo no difference. Appreciate advice

Attached (had to add .txt extensions otherwise Github does not allow me to attach)
Backtrace
Cargo.toml
main.rs

backtrace.txt

Cargo.toml.txt

main.rs.txt

GPIO still on after program exit

Hi,

I just wrote my first prgram:

use rust_gpiozero::*;
use std::thread::sleep;
use std::time::Duration;

fn main() {
    let mut yellow = LED::new(21);
    let mut red = LED::new(26);
    loop{
       red.on();
       yellow.off();
       sleep(Duration::from_millis(200));
        yellow.on();
        sleep(Duration::from_millis(200));
        red.off();
        sleep(Duration::from_millis(200));
    }
}

Once pressing Ctrl+C the program is exit but the Led still on, even if I removed the wire and returned it, to the GPIO it still on!

Not a press/release state change

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

Concurrency Bug causes DoS

I am using rust_gpiozero v0.2.1 with an Raspberry Pi 4B and found a situation where the library isn't responding to interrupts.
I'm not a 100% sure that it is a concurrency bug, but I was only able to replicate the problem in a concurrent situation.
The following minimal reproducible example responds only alternating between the pins and doesn't continue on every falling edge.

use std::thread;
use std::time::Duration;
use rust_gpiozero::input_devices::DigitalInputDevice;

fn event_loop(pin: u8) -> thread::JoinHandle<()> {
   thread::spawn(move || {
	let mut dev = DigitalInputDevice::new(pin);
	println!("init {} done", pin);
	let mut counter = 0_usize;
	loop {
		println!("await {} off {}", pin, counter);
		dev.wait_for_inactive(None);
		println!("awaited {} off {}", pin, counter);
		thread::sleep(Duration::from_millis(100));
		counter += 1;
	}
   })
}

fn main() {
    let first_el = event_loop(6);
    event_loop(16).join().unwrap();
    first_el.join().unwrap();
}

ETA on support for Thermometer sensors?

I found your book that you wrote up on physical computing. (Well done btw) Floating over to this repo for the crate I saw that other common sensor support is on a todo. Is there an ETA for when some would be added? Something like this would be perfect for a thermostat control application that im building.

Thanks!

Unmable to make LED blink.

I have taken the code from https://rahul-thakoor.github.io/physical-computing-rust/step_6.html#flashing-an-led
And tried to use the version not with a build method. The LED turns on, and does not turn off.

I added printlines to view as shown here

extern crate rust_gpiozero;

use rust_gpiozero::*;
use std::{thread::sleep, time::Duration};

fn main() {
    let mut led = LED::new(17);

    loop {
        println!("Turning on");
        led.on();
        println!("Is on");
        sleep(Duration::from_secs(1));
        println!("Turning off");
        led.off();
        println!("is on");
    }
}

Still no effect. If i kill the program and simply run the LED off, it turns off.

Using a Raspberry Pi Zero W with GPIO pins added on found here.

Crate version is 0.2.1

Any further information please feel free to ask.

Thanks in advance for any assistance/investigation.

Improve input device support

Currently only the Button input device is implemented. GPIO Zero has support for several others and it would be great to have support for them here too:

  1. Button
  2. LineSensor (e.g. infra-red proximity)
  3. MotionSensor
  4. LightSensor
  5. DistanceSensor
  6. RotaryEncoder

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.