common: Add the nvic module.
[gps-watch.git] / src / common / nvic.rs
diff --git a/src/common/nvic.rs b/src/common/nvic.rs
new file mode 100644 (file)
index 0000000..38aece3
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2019 Tilman Sauerbeck (tilman at code-monkey de)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+use register;
+
+type Reg32 = register::Register<u32>;
+
+const NVIC_BASE: u32 = 0xe000e100;
+
+const NVIC_ISER: u32 = NVIC_BASE + 0x000;
+const NVIC_ICER: u32 = NVIC_BASE + 0x080;
+const NVIC_IP  : u32 = NVIC_BASE + 0x300;
+
+pub fn enable_irq(irq_number: u32) {
+    let mut iser = Reg32::new(NVIC_ISER);
+
+    iser.write(1 << irq_number);
+}
+
+pub fn disable_irq(irq_number: u32) {
+    let mut icer = Reg32::new(NVIC_ICER);
+
+    icer.write(1 << irq_number);
+}
+
+fn ip_offset(irq_number: u32) -> u32 {
+    irq_number & !3
+}
+
+fn ip_shift(irq_number: u32) -> u32 {
+    (irq_number & 3) * 8
+}
+
+pub fn set_priority(irq_number: u32, priority: u32) {
+    let mut ip = Reg32::new(NVIC_IP + ip_offset(irq_number));
+
+    ip.modify(|v| {
+        let mut m = v;
+
+        m &= !(0xff << ip_shift(irq_number));
+        m |= priority << ip_shift(irq_number);
+        m
+    });
+}