plorefice / dht11-rs

Platform-agnostic Rust driver for the DHT11 temperature and humidity sensor
Apache License 2.0
15 stars 7 forks source link

gpio.pe2.into_open_drain_output() #2

Closed pdgilbert closed 4 years ago

pdgilbert commented 4 years ago

I'm new to Rust and embedded programming and am trying to work through some examples. I have a dht11 chip and so came across your repository while looking for examples of how to use it. My nucleo-64 board has a stm32f411re which does not have a pe2 pin, but I think I can use GPIOA and the pa8 pin. I am trying to understand

    let pin = gpio.pe2.into_open_drain_output();

Is it really correct that this is configured as output? I think '.into_open_drain' might be doing an alternate function setting. Could you explain what this really does?

plorefice commented 4 years ago

The function is correct, .into_open_drain_output() will configure a pin as a GPO in open-drain mode, without any alternate function attached. Without going into details, open-drain means that the pin can only force one electrical state (in this case, a logical 0), and has to rely on a pull-up resistor to put a 1 on the wire. It is commonly used for wires which can be driven by multiple sources.

In the case of the DHT11, this is kind of a trick/hack: on most microcontrollers (STM32F4xx in particular), the electrical state of an open-drain output can also be read as an input, so basically the pin acts both as an input and an output that can only pull down the bus to a logical 0. This works well in this case due to the protocol implemented by the DTH11, which is a variation of a 1-Wire bus. If you want additional details, you could have a look at the DHT11 datasheet (section 5).

The alternative way to do this would be to switch the pin between output and input during communication, which right now is hard to do in a hardware-independent way, and would require additional traits and probably a far bit of hack-ish code. I hope I've cleared things up for you, otherwise feel free to ask.

pdgilbert commented 4 years ago

Thank you very much for the detailed explanation!