common: Add the gpio module.
[gps-watch.git] / src / common / gpio.rs
diff --git a/src/common/gpio.rs b/src/common/gpio.rs
new file mode 100644 (file)
index 0000000..6f6dd3d
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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 GPIO_BASE: u32 = 0x400ff000;
+
+pub const GPIOA: u32 = GPIO_BASE + 0x000;
+pub const GPIOB: u32 = GPIO_BASE + 0x040;
+pub const GPIOC: u32 = GPIO_BASE + 0x080;
+pub const GPIOD: u32 = GPIO_BASE + 0x0c0;
+pub const GPIOE: u32 = GPIO_BASE + 0x100;
+
+pub enum Direction {
+    Input,
+    Output
+}
+
+const GPIO_PSOR: u32 = 0x04;
+const GPIO_PCOR: u32 = 0x08;
+const GPIO_PTOR: u32 = 0x0c;
+const GPIO_PDIR: u32 = 0x10;
+const GPIO_PDDR: u32 = 0x14;
+
+pub fn set(gpio: u32, pin_mask: u32) {
+    Reg32::new(gpio + GPIO_PSOR).write(pin_mask);
+}
+
+pub fn clear(gpio: u32, pin_mask: u32) {
+    Reg32::new(gpio + GPIO_PCOR).write(pin_mask);
+}
+
+pub fn toggle(gpio: u32, pin_mask: u32) {
+    Reg32::new(gpio + GPIO_PTOR).write(pin_mask);
+}
+
+pub fn set_direction(gpio: u32, pin_mask: u32, direction: Direction) {
+    let mut pddr = Reg32::new(gpio + GPIO_PDDR);
+
+    match direction {
+        Direction::Output => {
+            pddr.modify(|v| v | pin_mask);
+        },
+        Direction::Input => {
+            pddr.modify(|v| v & !pin_mask);
+        }
+    }
+}
+
+pub fn get(gpio: u32) -> u32 {
+    Reg32::new(gpio + GPIO_PDIR).read()
+}