2 * Copyright (c) 2019 Tilman Sauerbeck (tilman at code-monkey de)
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 type Reg8 = register::Register<u8>;
27 type Reg32 = register::Register<u32>;
29 const I2C_BASE: u32 = 0x40066000;
31 pub const I2C0: u32 = I2C_BASE + 0x0000;
32 pub const I2C1: u32 = I2C_BASE + 0x1000;
34 const SIM_SCGC4: u32 = 0x40048034;
36 const SIM_SCGC4_I2C0: u32 = 1 << 6;
37 const SIM_SCGC4_I2C1: u32 = 1 << 7;
39 const I2C_F : u32 = 0x01;
40 const I2C_C1 : u32 = 0x02;
41 const I2C_S1 : u32 = 0x03;
42 const I2C_D : u32 = 0x04;
44 const I2C_C1_TX : u8 = 1 << 4;
45 const I2C_C1_MST : u8 = 1 << 5;
46 const I2C_C1_IICEN: u8 = 1 << 7;
48 const I2C_S1_IICIF: u8 = 1 << 1;
50 const I2C_F_ICR_SHIFT: u8 = 0;
52 pub fn configure(i2c: u32) {
54 let mut scgc4 = Reg32::new(SIM_SCGC4);
57 scgc4.modify(|v| v | SIM_SCGC4_I2C0);
59 scgc4.modify(|v| v | SIM_SCGC4_I2C1);
63 let mut f = Reg8::new(i2c + I2C_F);
64 f.write(0x12 << I2C_F_ICR_SHIFT);
66 let mut c1 = Reg8::new(i2c + I2C_C1);
67 c1.write(I2C_C1_IICEN);
70 fn prepare_tx(i2c: u32, slave_address: u8) {
71 let mut c1 = Reg8::new(i2c + I2C_C1);
73 c1.modify(|v| v | I2C_C1_TX);
74 c1.modify(|v| v | I2C_C1_MST);
76 let mut d = Reg8::new(i2c + I2C_D);
77 d.write((slave_address << 1) | 0);
80 fn finish_tx(i2c: u32) {
81 let mut c1 = Reg8::new(i2c + I2C_C1);
83 c1.modify(|v| v & !I2C_C1_MST);
84 c1.modify(|v| v & !I2C_C1_TX);
87 fn wait_for_and_ack_interrupt(i2c: u32) {
88 let mut s1 = Reg8::new(i2c + I2C_S1);
90 // Wait for interrupt to occur.
91 while (s1.read() & I2C_S1_IICIF) == 0 {
94 // Acknowledge interrupt.
95 s1.modify(|v| v | I2C_S1_IICIF);
98 fn tx(i2c: u32, data: u8) {
99 wait_for_and_ack_interrupt(i2c);
101 let mut d = Reg8::new(i2c + I2C_D);
105 pub fn tx16(i2c: u32, slave_address: u8, data: u16) {
106 prepare_tx(i2c, slave_address);
108 tx(i2c, (data >> 0) as u8);
109 tx(i2c, (data >> 8) as u8);
111 wait_for_and_ack_interrupt(i2c);