SPI slave from https://www.fpga4fun.com/SPI2.html
[trilby-hat-fpga] / i2c.v
1 `include "i2c_bridge.v"
2 `include "ecp5pll.sv"
3
4 module top(
5         input clk,
6
7         inout rtc_sda,
8         inout rtc_scl,
9
10         inout tuner_sda,
11         inout tuner_scl,
12
13         output mhz_16,mhz_96,
14
15         output exp_pin_3, exp_pin_4,
16         output exp_pin_5, exp_pin_6,
17         output exp_pin_7, exp_pin_8,
18
19         output green_led_d7,
20         output orange_led_d8,
21         output red_led_d5,
22         output yellow_led_d6
23 );
24
25         wire [3:0] clocks;
26         ecp5pll
27         #(
28                 .in_hz(24000000),
29                 .out0_hz(16000000),.out0_tol_hz(0) ,
30                 .out1_hz(96000000), .out1_deg( 0), .out1_tol_hz(0)//,
31                 //.out2_hz(60000000), .out2_deg(180), .out2_tol_hz(0),
32         )
33         ecp5pll_inst
34         (
35                 .clk_i(clk),
36                 .clk_o(clocks)
37         );
38
39         assign mhz_16 = clocks[0];
40         assign mhz_96 = clocks[1];
41
42 /*
43         assign exp_pin_4 = clocks[0];
44         assign exp_pin_8 = clocks[1];
45 */
46         assign exp_pin_4 = rtc_scl;
47         assign exp_pin_8 = rtc_sda;
48
49         assign green_led_d7  = rtc_scl;
50         assign orange_led_d8 = rtc_sda;
51         assign red_led_d5    = tuner_scl;
52         assign yellow_led_d6 = tuner_sda;
53
54
55   localparam bridge_clk_div = 3; // div = 1+2^n, 24/(1+2^2)=4 MHz
56   reg [bridge_clk_div:0] bridge_cnt;
57   always @(posedge clk) // 24 MHz
58   begin
59     if(bridge_cnt[bridge_clk_div])
60       bridge_cnt <= 0;
61     else
62       bridge_cnt <= bridge_cnt + 1;
63   end
64   wire clk_bridge_en = bridge_cnt[bridge_clk_div];
65
66   wire [1:0] i2c_sda_i = {rtc_sda, tuner_sda};
67   wire [1:0] i2c_sda_t;
68   i2c_bridge i2c_sda_bridge_i
69   (
70     .clk(clk),
71     .clk_en(clk_bridge_en),
72     .i(i2c_sda_i),
73     .t(i2c_sda_t)
74   );
75   assign rtc_sda = i2c_sda_t[1] ? 1'bz : 1'b0;
76   assign tuner_sda = i2c_sda_t[0] ? 1'bz : 1'b0;
77
78   wire [1:0] i2c_scl_i = {rtc_scl, tuner_scl};
79   wire [1:0] i2c_scl_t;
80   i2c_bridge i2c_scl_bridge_i
81   (
82     .clk(clk),
83     .clk_en(clk_bridge_en),
84     .i(i2c_scl_i),
85     .t(i2c_scl_t)
86   );
87   assign rtc_scl = i2c_scl_t[1] ? 1'bz : 1'b0;
88   assign tuner_scl = i2c_scl_t[0] ? 1'bz : 1'b0;
89
90 endmodule