Created
July 15, 2021 09:04
-
-
Save tzechienchu/691fccef3c241534c42976a2d6e9402a to your computer and use it in GitHub Desktop.
PWM from ChiselBook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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