Skip to content

Instantly share code, notes, and snippets.

@Martoni
Created March 23, 2021 10:30
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 Martoni/e1cf2b6ca365d2590049b80a632cfab0 to your computer and use it in GitHub Desktop.
Save Martoni/e1cf2b6ca365d2590049b80a632cfab0 to your computer and use it in GitHub Desktop.
Simple Chisel PWM
import chisel3._
import chisel3.util._
import chisel3.stage.{ChiselStage, ChiselGeneratorAnnotation}
class SimplePWM(val insize: Int = 16) extends Module {
val io = IO(new Bundle {
val inval = Flipped(Decoupled(UInt(insize.W)))
val pwm_o = Output(Bool())
})
val dutyReg = RegInit("h8".U(insize.W))
val dutyHoldReg = RegInit("h8".U(insize.W))
val maxValue = ((1 << insize) - 1)
val countReg = RegInit(maxValue.U)
val pwmReg = RegInit(false.B)
/* Record duty cycle value */
when(io.inval.valid & io.inval.ready) {
dutyReg := io.inval.bits
}
io.inval.ready := RegNext(~io.inval.valid)
/* count periods */
countReg := countReg - 1.U
pwmReg := false.B
when(countReg === 0.U){
when(dutyHoldReg =/= 0.U){
pwmReg := true.B
}
countReg := maxValue.U
dutyHoldReg := dutyReg
}.otherwise {
when(countReg <= dutyHoldReg){
pwmReg := true.B
}
}
io.pwm_o := pwmReg
}
object SimplePWMDriver extends App {
var insize=16
if(args.length > 0) {
for(arg <- args) {
val argvalue = arg.split("=")
if(argvalue(0) == "insize"){
insize = argvalue(1).toInt
}
}
}
println("*****************************************")
println("* Generate verilog for SimplePWM module *")
println("* insize = " + insize)
println("*****************************************")
(new chisel3.stage.ChiselStage).execute(
Array("-X", "verilog"),
Seq(ChiselGeneratorAnnotation(
() => new SimplePWM(insize=insize))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment