Search code examples
rustarduinohalrust-no-std

Get pin number in rust arduino_hal


I'm trying to port the firmata firmware in rust, more as an exercise to learn arduino coding than anything else.

However, I required to know the pin number, indeed part of the protocol requires doing algebra with the pin number to send to the serial port e.g. REPORT_ANALOG | (pin_number & 0xF).

However, when i instantiate a pin through pin!, the object does not give me access to the pin number.

I'm trying different ways, such as doing a match case to instantiate the pin in a custom struct to store the pin number,

let pin = match pin_number {
            0 => pins.d0,
            1 => pins.d1,
            2 => pins.d2,
            ...

but i'm getting typing issues as there does not seem to be a generic pin type

`match` arms have incompatible types
expected struct `avr_hal_generic::port::Pin<_, PD0>`
   found struct `avr_hal_generic::port::Pin<_, PD1>

is there a method, even unsafe to get back the pin number?


Solution

  • There is likely a better way to implement the firmata protocol, but if you need to convert the types to numbers you can do so with a trait:

    fn pin_number<MODE, PIN: PinNumber>(_: &avr_hal_generic::port::Pin<MODE, PIN>) -> usize {
        PIN::PIN_NUMBER
    } 
    trait PinNumber {
        const PIN_NUMBER: usize;
    }
    impl PinNumber for PD0 {
        const PIN_NUMBER: usize = 0;
    }
    impl PinNumber for PD1 {
        const PIN_NUMBER: usize = 1;
    }
    // …