Skip to content

Instantly share code, notes, and snippets.

@tzechienchu
Last active Jul 16, 2021
Embed
What would you like to do?
Debounce
import chisel3._
import chisel3.util._
object MyLib {
def FPGA_FREQ() = 50*1000*1000
def sync(v: Bool) = RegNext(RegNext(v))
def rising(v: Bool) = v & !RegNext(v)
def tickGen(fac: Int) = {
val reg = RegInit(0.U(log2Up(fac).W))
val tick = reg === (fac - 1).U
reg := Mux(tick, 0.U, reg + 1.U)
tick
}
def filter3(v: Bool, t: Bool) = {
val reg = RegInit(0.U(3.W))
when (t) {
reg := Cat(reg(1,0), v)
}
(reg(2) & reg(1)) | (reg(2) & reg(0)) | (reg(1) & reg(0))
}
def counter8(t: Bool) = {
val reg = RegInit(0.U(8.W))
when (t) {
reg := reg + 1.U
}
reg
}
def sevenSeg(sw: UInt, dp: Bool) = {
val sevSeg = WireInit(0.U(7.W))
switch (sw) {
is (0.U) {sevSeg := "b0111111".U}
is (1.U) {sevSeg := "b0000110".U}
is (2.U) {sevSeg := "b1011011".U}
is (3.U) {sevSeg := "b1001111".U}
is (4.U) {sevSeg := "b1100110".U}
is (5.U) {sevSeg := "b1101101".U}
is (6.U) {sevSeg := "b1111101".U}
is (7.U) {sevSeg := "b0000111".U}
is (8.U) {sevSeg := "b1111111".U}
is (9.U) {sevSeg := "b1101111".U}
is (10.U) {sevSeg := "b1110111".U}
is (11.U) {sevSeg := "b1111100".U}
is (12.U) {sevSeg := "b0111001".U}
is (13.U) {sevSeg := "b1011110".U}
is (14.U) {sevSeg := "b1111001".U}
is (15.U) {sevSeg := "b1110001".U}
}
Cat(~dp,~sevSeg)
}
}
class Debounce extends Module {
val io = IO(new Bundle {
val btnIn = Input(Bool())
val btnOk = Output(Bool())
val btnOnce = Output(Bool())
})
val btnIn = io.btnIn
val btnSync = MyLib.sync(btnIn)
val tick = MyLib.tickGen(10*1000*1000)
val btnDeb = Reg(Bool())
when (tick) {
btnDeb := btnSync
}
val btnOk = MyLib.filter3(btnDeb, tick)
val btnOnce = MyLib.rising(btnOk)
io.btnOk := btnOk
io.btnOnce := btnOnce
}
class DebounceTop extends Module {
val io = IO(new Bundle {
val btnIn = Input(Bool())
val hex2A = Output(UInt(16.W))
val hex2B = Output(UInt(16.W))
})
val DebounceM = Module(new Debounce())
val btnIn = io.btnIn
val btnRawOnce = MyLib.rising(btnIn)
DebounceM.io.btnIn := btnIn
val btnOk = DebounceM.io.btnOk
val btnOnce = DebounceM.io.btnOnce
val counterA = MyLib.counter8(btnRawOnce)
val counterB = MyLib.counter8(btnOnce)
val Hex1 = MyLib.sevenSeg(counterA(3,0), 0.B)
val Hex2 = MyLib.sevenSeg(counterA(7,4), 0.B)
val Hex3 = MyLib.sevenSeg(counterB(3,0), 0.B)
val Hex4 = MyLib.sevenSeg(counterB(7,4), 0.B)
io.hex2A := Cat(Hex1, Hex2)
io.hex2B := Cat(Hex3, Hex4)
}
object DebounceTop extends App {
(new chisel3.stage.ChiselStage).emitVerilog(new DebounceTop())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment