E
E
eegmak2021-03-05 20:47:33
Rust
eegmak, 2021-03-05 20:47:33

How to rewrite code like this in style?

the code
let mut x = 24; // mut x: i32

while x>0 {
    x = x - 1;

        block!(timer.wait()).unwrap();
        led.set_high().unwrap();
        led.set_low().unwrap();
        led.set_low().unwrap();
        //led.set_low().unwrap();
        block!(timer.wait()).unwrap();

    
}
x=24;
while x>0 {
    x = x - 1;
        block!(timer.wait()).unwrap();
        led.set_high().unwrap();
        block!(timer.wait()).unwrap();
        led.set_low().unwrap();
    
}
x=24;
while x>0 {
    x = x - 1;

        block!(timer.wait()).unwrap();
        led.set_high().unwrap();
        led.set_low().unwrap();
        led.set_low().unwrap();
        //led.set_low().unwrap();
        block!(timer.wait()).unwrap();

    
}
x=24;
while x>0 {
    x = x - 1;
        block!(timer.wait()).unwrap();
        led.set_high().unwrap();
        block!(timer.wait()).unwrap();
        led.set_low().unwrap();
    
}

explanation:
block!(timer.wait()).unwrap();
        led.set_high().unwrap();
        led.set_low().unwrap();
        led.set_low().unwrap();
        //led.set_low().unwrap();
        block!(timer.wait()).unwrap();
this is a unit
block!(timer.wait()).unwrap();
        led.set_high().unwrap();
        block!(timer.wait()).unwrap();
        led.set_low().unwrap();
this is zero
I need to send 24 bits (1 or zero) 64 times (this is a matrix of 64 rgb LEDs) how to do it in style on rust?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-03-05
@bingo347

I would do something like this:

macro_rules! low_high_wait {
    (low) => {
        led.set_low().unwrap();
    };
    (high) => {
        led.set_high().unwrap();
    };
    (wait) => {
        block!(timer.wait()).unwrap();
    };
    (low, $($rest:tt),+) => {
        low_high_wait!(low);
        low_high_wait!($($rest),+);
    };
    (high, $($rest:tt),+) => {
        low_high_wait!(high);
        low_high_wait!($($rest),+);
    };
    (wait, $($rest:tt),+) => {
        low_high_wait!(wait);
        low_high_wait!($($rest),+);
    };
}
for _ in 0..24 {
    low_high_wait!(wait, high, low, low, wait);
}
for _ in 0..24 {
    low_high_wait!(wait, high, wait, low);
}
for _ in 0..24 {
    low_high_wait!(wait, high, low, low, wait);
}
for _ in 0..24 {
    low_high_wait!(wait, high, wait, low);
}

V
Vasily Bannikov, 2021-03-05
@vabka

1. Read the rustbook - there's a lot of advice on ideomatic code
2. Wrap it up in functions and do some high-level abstraction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question