Skip to content

Instantly share code, notes, and snippets.

@tzechienchu
Created July 15, 2021 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzechienchu/691fccef3c241534c42976a2d6e9402a to your computer and use it in GitHub Desktop.
Save tzechienchu/691fccef3c241534c42976a2d6e9402a to your computer and use it in GitHub Desktop.
PWM from ChiselBook
import chisel3._
import chisel3.util._
class PWM extends Module {
val io = IO(new Bundle {
val pwm = Output(Bool())
})
def pwmfn(nrCycles: Int, din:UInt):Bool = {
val cntReg = RegInit(0.U(unsignedBitLength(nrCycles - 1).W))
cntReg := Mux(cntReg === (nrCycles-1).U, 0.U, cntReg + 1.U)
din > cntReg
}
val FREQ = 50*1000*1000
val MAX = FREQ/1000
val mReg = RegInit(0.U(32.W))
val upReg = RegInit(true.B)
when (mReg < FREQ.U && upReg) {
mReg := mReg + 1.U
} .elsewhen (mReg === FREQ.U && upReg) {
upReg := false.B
} .elsewhen (mReg > 0.U && !upReg) {
mReg := mReg - 1.U
} .otherwise {
upReg := true.B
}
val pwm = pwmfn(MAX, mReg >> 10)
io.pwm := pwm
}
object PWM extends App {
(new chisel3.stage.ChiselStage).emitVerilog(new PWM)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment