diff --git a/examples/bare5.rs b/examples/bare5.rs index df04e70e38d69399af5a413276fed3addbeeb0ea..24d8394ff2f92cb44930bf85dbde966acc98afe2 100644 --- a/examples/bare5.rs +++ b/examples/bare5.rs @@ -57,12 +57,20 @@ mod stm32f40x { // width (field width) // value (new value that the field should take) // - // impl VolatileCell<u32> { - // #[inline(always)] - // pub fn modify(&self, offset: u8, width: u8, value: u32) { - // // your code here - // } - // } + impl VolatileCell<u32> { + #[inline(always)] + pub fn modify(&self, offset: u8, width: u8, value: u32) { + // your code here + let mask:u32 = (1<<width)-1 ; + let mut valueOfMask: u32 = 0; + if (width > 0 ){ + valueOfMask = mask & value; + } + let reader = self.read() & !(mask << offset); + self.write(reader | (value & valueOfMask) << offset); + + } + } #[repr(C)] #[allow(non_snake_case)] @@ -141,27 +149,27 @@ fn wait(i: u32) { } // simple test of Your `modify` -//fn test() { -// let t:VolatileCell<u32> = unsafe { core::mem::uninitialized() }; -// t.write(0); -// assert!(t.read() == 0); -// t.modify(3, 3, 0b10101); +fn test() { + let t:VolatileCell<u32> = unsafe { core::mem::uninitialized() }; + t.write(0); + assert!(t.read() == 0); + t.modify(3, 3, 0b10101); // // // // 10101 // // ..0111000 // // --------- // // 000101000 -// assert!(t.read() == 0b101 << 3); -// t.modify(4, 3, 0b10001); + assert!(t.read() == 0b101 << 3); + t.modify(4, 3, 0b10001); // // 000101000 // // 111 // // 001 // // 000011000 -// assert!(t.read() == 0b011 << 3); + assert!(t.read() == 0b011 << 3); // if << is used, your code will panic in dev (debug), but not in release mode -// t.modify(32, 3, 1); -//} + t.modify(32, 3, 1); +} // system startup, can be hidden from the user #[entry] @@ -191,7 +199,7 @@ fn idle(rcc: &mut RCC, gpioa: &mut GPIOA) { //gpioa.BSRRH.write(1 << 5); // set bit, output hight (turn on led) // alternatively to set the bit high we can // read the value, or with PA5 (bit 5) and write back - gpioa.ODR.write(gpioa.ODR.read() | (1 << 5)); + gpioa.ODR.modify(5, 1, 1); wait(10_000); @@ -199,7 +207,7 @@ fn idle(rcc: &mut RCC, gpioa: &mut GPIOA) { //gpioa.BSRRL.write(1 << 5); // clear bit, output low (turn off led) // alternatively to clear the bit we can // read the value, mask out PA5 (bit 5) and write back - gpioa.ODR.write(gpioa.ODR.read() & !(1 << 5)); + gpioa.ODR.modify(5, 1, 0); wait(10_000); } }