|
3 S: s& q, ^# ?4 A7 J, s8 f4 l+ @+ |9 ~ P+ e1 {
I2C START / STOP Detector Verilog Code; Z p2 _* t) l* w( G' t
8 Q& \/ @( V$ I5 X
; A$ o5 o4 I4 E& Z4 ~ i
module i2c_start_stop_detector ( N: n4 U% n- X- z+ \ O
input wire clk, // 系統時鐘
/ T. z7 o: q( ]1 a) a# ~. J input wire rst_n, // 非同步 Reset: t- H8 @9 ]: @9 F" t& l8 S
input wire sda, // I2C 資料線+ z6 `% O( k1 t# W2 M
input wire scl, // I2C 時鐘線
. r0 @1 F4 r# |2 }$ L output reg start_detected, // Start 條件偵測到/ ]% Q! U* T f8 X% ^
output reg stop_detected // Stop 條件偵測到 T/ G/ i; ~; \( }3 I( n9 ^! {
);
' k- u) B" U/ k4 h, B( Z& Z. v! v* B. {) P* u
# e, J0 g9 u' [: W8 I' c // 前兩個時鐘週期的 SDA 與 SCL 值1 g+ M3 v6 C! o! z3 x. C
reg sda_d1, sda_d2;
! l% H. m2 M/ M$ s- Y: N$ j: j reg scl_d1;3 G8 {0 M+ X, i' B
) D t5 X g6 x& P0 @' z6 k
: P) F' B' |3 D* N6 ? [! K wire sda_rising = (sda_d2 == 1'b0) && (sda_d1 == 1'b1);
1 Y w8 u6 e1 y, o wire sda_falling = (sda_d2 == 1'b1) && (sda_d1 == 1'b0);1 J. g. v- F: g( U6 s
1 X& t- T/ ?) j( p6 U; @9 d$ Y) s! o% c2 l" S6 F
// Sample SDA and SCL
, g1 m; O- p1 K L2 | always @(posedge clk or negedge rst_n) begin
7 k* P4 ]3 L- y) c if (!rst_n) begin/ n2 ]% n+ s6 \' R
sda_d1 <= 1'b1;, L- {! V4 s- h/ o @, ~' G* Q, R
sda_d2 <= 1'b1;9 Z) ?2 M) E. n; T4 z" s7 u5 d4 S
scl_d1 <= 1'b1;* S8 Q$ w: T$ g1 c! g L
end else begin2 m3 A- `9 J, m9 a; _
sda_d2 <= sda_d1;
3 t3 L- i" E5 K0 Z" W; C sda_d1 <= sda;
) n! G+ A4 _2 b- |! @, m# }5 X scl_d1 <= scl;
. P& V5 c1 ]. C/ I9 A) p8 s3 z3 @ end) c& ^, _/ }1 ]$ {
end# J7 D0 {6 I0 [* ?3 o/ I
2 |6 O4 \ C* k5 l- b4 N4 V2 R* L0 ]- `, U
// 偵測 Start / Stop 條件
3 O0 e$ B: M- N% }% m# V2 l always @(posedge clk or negedge rst_n) begin: i# l( m i$ `9 L; _" y3 J
if (!rst_n) begin
* V6 d1 q7 @/ N, s* t4 {3 @& n start_detected <= 1'b0;
, R" T( S ?$ Y4 A6 y" z S stop_detected <= 1'b0;
0 G4 O4 Y9 b- i2 B end else begin
9 _7 s' U. M+ k! s // I2C START: SDA falling while SCL is high
/ \& o5 I, }! ^" w start_detected <= sda_falling && (scl_d1 == 1'b1);
7 b) v8 D4 R0 V7 }5 B // I2C STOP: SDA rising while SCL is high
* H) b$ T5 a) e/ D stop_detected <= sda_rising && (scl_d1 == 1'b1);
3 U. ?* f8 `4 `* o$ M end- t8 y% w, m% D; d d% ]
end; d4 Y" S) n$ C
6 ?1 ~% s+ N# G. z) h
5 o- I$ V3 j' t4 K( N
endmodule$ E$ A( {2 C" c# ?1 z( h
5 @% R& @: {; o& Z. K

( a# n2 q' M3 q( l2 g% R V: ^* n4 x+ {' \ N4 z, O4 W. J I
|
|