def tb_sumbits(): '''' test-bench for the sumbits() implementation ''' Clk = myhdl.Signal(bool(0)) Reset = myhdl.ResetSignal(0, active=1, async=True) D = myhdl.Signal(myhdl.intbv(0)[WIDTH_D:]) Q = myhdl.Signal(myhdl.intbv(0)[WIDTH_Q:]) dut = sumbits(Clk, Reset, D, Q) tCK = 10 ClkCount = myhdl.Signal(myhdl.intbv(0)[8:]) @myhdl.instance def clkgen(): yield hdlutils.genClk(Clk, tCK, ClkCount) @myhdl.instance def resetgen(): yield hdlutils.genReset(Clk, tCK, Reset) @myhdl.instance def stimulusin(): yield hdlutils.delayclks(Clk, tCK, 5) D.next = 0x13 yield hdlutils.delayclks(Clk, tCK, 1) D.next = 0x01 yield hdlutils.delayclks(Clk, tCK, 1) D.next = 0x02 yield hdlutils.delayclks(Clk, tCK, 1) D.next = 0x03 yield hdlutils.delayclks(Clk, tCK, 5) raise myhdl.StopSimulation return dut, clkgen, resetgen, stimulusin
def __init__(self, name, pins, sigtype=None, **pattr): """ relate a port to a device pins and pin attributes name: name for the port pins: a list (tuple) of the pins sigtype: Signal type **pattr: port attributes (vendor specific) """ self.name = name if isinstance(pins, (int, str)): pins = [pins] self.pins = pins self.inuse = False if sigtype is not None: self.sig = sigtype elif len(pins) == 1: self.sig = myhdl.Signal(bool(0)) else: self.sig = myhdl.Signal(myhdl.intbv(0)[len(pins):]) # device specific arguments, when the pin assignment # list is created the following will be used to create # the UCF,TCL,SDC,etc. files. self.pattr = pattr
def tb_uart(): left_tx = myhdl.Signal(bool(1)) left_rx = myhdl.Signal(bool(1)) right_tx = myhdl.Signal(bool(1)) right_rx = myhdl.Signal(bool(1)) left = main(CLK, RST_X, left_rx, left_tx, 0) right = main(CLK, RST_X, right_rx, right_tx, 1) @myhdl.always_comb def assign(): right_rx.next = left_tx left_rx.next = right_tx @myhdl.always(myhdl.delay(CLK_PERIOD / 2)) def clkgen(): CLK.next = not CLK @myhdl.instance def stimulus(): RST_X.next = 0 yield myhdl.delay(RST_TIME) RST_X.next = 1 while (1): yield CLK.posedge return left, right, assign, clkgen, stimulus
def logistic_regression_convert(): reset = myhdl.Signal(bool(0)) clk = myhdl.Signal(bool(0)) LEN_THETA=3 NB_PIPELINE_STAGES = 5 DATAWIDTH=32 CHANNEL_WIDTH=1 INIT_DATA=0 #(0 for myhdl.intbv) # --- Pipeline Pars pars=LogisticRegressionPars() pars.NB_PIPELINE_STAGES=NB_PIPELINE_STAGES pars.DATAWIDTH=DATAWIDTH pars.CHANNEL_WIDTH=CHANNEL_WIDTH pars.INIT_DATA=INIT_DATA pars.LEN_THETA=LEN_THETA pars.CMD_FILE='tb/tests/mult_pipeline.list' lRIO=LogisticRegressionIo() lRIO(pars) lRModule=LogisticRegression() lRInst=lRModule.block_connect(pars, reset, clk, lRIO.pipe_inpA, lRIO.pipe_inpB, lRIO.pipe_out_activ ) lRInst.convert(hdl='Verilog', path = "converted_hdl", name="logistic_regression") lRInst.convert(hdl='VHDL', path = "converted_hdl", name="logistic_regression")
def convert(): Clk = myhdl.Signal(bool(0)) # Reset = myhdl.ResetSignal(0, active=1, async=True) Reset = None D = myhdl.Signal(myhdl.intbv(0)[WIDTH_D:]) Q = myhdl.Signal(myhdl.intbv(0)[WIDTH_Q:]) myhdl.toVHDL(sumbits, Clk, Reset, D, Q) myhdl.toVerilog(sumbits, Clk, Reset, D, Q)
def simFixPoint(self): """ Simulate filter in fix-point description """ # Setup the Testbench and run dlg = QFD(self) # instantiate file dialog object plt_types = "png (*.png);;svg (*.svg)" plt_file, plt_type = dlg.getSaveFileName_(caption="Save plots as", directory=dirs.save_dir, filter=plt_types) plt_file = str(plt_file) if plt_file != "": plt_file = os.path.normpath(plt_file) plt_type = str(plt_type) logger.info('Using plot filename "%s"', plt_file) plt_dir_name = os.path.dirname( plt_file) # extract the directory path if not os.path.isdir( plt_dir_name): # create directory if it doesn't exist os.mkdir(plt_dir_name) dirs.save_dir = plt_dir_name # make this directory the new default / base dir # plt_file_name = os.path.splitext(os.path.basename(plt_file))[0] # filename without suffix plt_file_name = os.path.basename(plt_file) logger.info('Creating plot file "{0}"'.format( os.path.join(plt_dir_name, plt_file_name))) self.setupHDL(file_name=plt_file_name, dir_name=plt_dir_name) logger.info("Fixpoint simulation setup") tb = self.flt.simulate_freqz(num_loops=3, Nfft=1024) clk = myhdl.Signal(False) ts = myhdl.Signal(False) x = myhdl.Signal( myhdl.intbv(0, min=-2**(self.W[0] - 1), max=2**(self.W[0] - 1))) y = myhdl.Signal( myhdl.intbv(0, min=-2**(self.W[0] - 1), max=2**(self.W[0] - 1))) try: sim = myhdl.Simulation(tb) logger.info("Fixpoint simulation started") sim.run() logger.info("Fixpoint plotting started") self.flt.plot_response() logger.info("Fixpoint plotting finished") except myhdl.SimulationError as e: logger.warning("Simulation failed:\n{0}".format(e))
def sumbits(Clk, Reset, D, Q): ''' a recursive pipelined implementation''' LWIDTH_D = len(D) sbs = [] if LWIDTH_D > 2: # recurse by splitting things up LWIDTH_L = LWIDTH_D - LWIDTH_D / 2 dupper, dlower = [ myhdl.Signal(myhdl.intbv(0)[LWIDTH_L:]) for _ in range(2) ] lql, lqu = [ myhdl.Signal(myhdl.intbv(0)[hdlutils.widthr(LWIDTH_L):]) for _ in range(2) ] # supper = sumbits(Clk, Reset, dupper, lqu) # slower = sumbits(Clk, Reset, dlower, lql) sbs.append(sumbits(Clk, Reset, dupper, lqu)) sbs.append(sumbits(Clk, Reset, dlower, lql)) @myhdl.always_comb def split(): ''' this will expand on the left in case the input data-size is uneven ''' dupper.next = D[:LWIDTH_L] dlower.next = D[LWIDTH_L:] sbs.append(split) @myhdl.always_seq(Clk.posedge, Reset) def rtlr(): ''' the result is the sum of the previous branches ''' Q.next = lqu + lql sbs.append(rtlr) # return supper, slower, split, rtlr # know when to stop else: @myhdl.always_seq(Clk.posedge, Reset) def rtl2(): ''' the result is the sum of the two (terminal) leaves ''' Q.next = D[1] + D[0] sbs.append(rtl2) # return rtl2 return sbs
def createSignal(init, width): """ Wrapper to create mydhl Signals. Args: - init: Initial value. - width: Signal width. """ assert width >= 1, "Invalid width = {0}".format(width) if width > 1: return hdl.Signal(hdl.modbv(init)[width:]) else: return hdl.Signal(True if init else False)
def tb_fifo(): inst = fifo(CLK, RST_X, ENQ, DEQ, DIN, DOUT, EMPTY, FULL) cycle = myhdl.Signal(myhdl.intbv(0)[WIDTH:]) @myhdl.always(myhdl.delay(CLK_PERIOD / 2)) def clkgen(): CLK.next = not CLK @myhdl.always_comb def assign(): ENQ.next = ((cycle < 20) and (not FULL)) DEQ.next = ((cycle % 2) and (not EMPTY)) DIN.next = cycle @myhdl.always(CLK.posedge) def cyclegen(): if not RST_X: cycle.next = 0 else: cycle.next = cycle + 1 @myhdl.instance def stimulus(): RST_X.next = 0 yield myhdl.delay(RST_TIME) RST_X.next = 1 while (cycle < HALT_CYCLE): yield CLK.posedge print "cycle(DIN): %10d DOUT: %10d ENQ: %d DEQ: %d EMPTY %d FULL %d" % ( cycle, DOUT, ENQ, DEQ, EMPTY, FULL) raise myhdl.StopSimulation return inst, clkgen, assign, cyclegen, stimulus
def uart_rx(clk_i, rst_i, rx_tick_i, rx_i, dat_o, ready_o): RXTICKX = 8 NBITSP = log2up(RXTICKX) NBITSTART = NBITSP - 1 rx_sync = createSignal(0b111, 3) rx_r = createSignal(1, 1) bit_spacing = createSignal(0, NBITSP) bit_start = createSignal(0, NBITSTART) nxt_bit = createSignal(0, 1) bit_cnt = createSignal(0, 3) dat_r = createSignal(0, 8) rx_state = hdl.enum('IDLE', 'DATA', 'STOP') state = hdl.Signal(rx_state.IDLE) @hdl.always_seq(clk_i.posedge, reset=rst_i) def rx_sync_proc(): if rx_tick_i: rx_sync.next = hdl.concat(rx_sync[2:0], rx_i) @hdl.always_comb def assign_proc(): rx_r.next = rx_sync == 0b111 or rx_sync == 0b011 or rx_sync == 0b101 or rx_sync == 0b110 dat_o.next = dat_r @hdl.always_seq(clk_i.posedge, reset=rst_i) def nxt_bit_proc(): nxt_bit.next = bit_spacing == RXTICKX - 1 if rx_tick_i and state != rx_state.IDLE: bit_spacing.next = bit_spacing + 1 @hdl.always_seq(clk_i.posedge, reset=rst_i) def start_bit_proc(): if state == rx_state.IDLE and not rx_r: bit_start.next = bit_start + rx_tick_i else: bit_start.next = 0 @hdl.always_seq(clk_i.posedge, reset=rst_i) def fsm_proc(): ready_o.next = False if rx_tick_i: if state == rx_state.IDLE: if not rx_r and bit_start == hdl.modbv(RXTICKX // 2 - 1)[NBITSTART:]: state.next = rx_state.DATA elif state == rx_state.DATA: if nxt_bit: dat_r.next = hdl.concat(rx_r, dat_r[8:1]) bit_cnt.next = bit_cnt + 1 if bit_cnt == 7: state.next = rx_state.STOP elif state == rx_state.STOP: if nxt_bit: state.next = rx_state.IDLE ready_o.next = True else: state.next = rx_state.IDLE return hdl.instances()
def get_hwgen_args(self): clock = myhdl.Signal(bool()) reset = myhdl.ResetSignal(bool(True), True, True) phase_step = myhdl.Signal(myhdl.intbv(0)[self.params.phase_acc_bits:]) BITS = self.params.out_bits cos_out = myhdl.Signal(myhdl.intbv(0, -2**(BITS - 1), 2**(BITS - 1))) sin_out = myhdl.Signal(myhdl.intbv(0, -2**(BITS - 1), 2**(BITS - 1))) # Constants samples = self.params.fft_samples args = (clock, reset, phase_step, cos_out, sin_out) kwargs = { 'PHASE_PRECISION': self.params.phase_bits, 'LUT_DEPTH': self.params.lut_depth, 'DITHER': self.params.phase_dither, 'CORDIC_STAGES': self.params.cordic_stages, } return nco.NCOCordic, args, kwargs
def test_rule30(): # We verify that both automata output the same 10 first states # Note that the bit order is reversed in the two, but that does not really # matter INITIAL_STATE = [1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0] UPDATE_RULE = [0, 1, 1, 1, 1, 0, 0, 0] reference = rule30_reference.CellularAutomata(UPDATE_RULE, INITIAL_STATE[::-1]) clock = myhdl.Signal(bool(False)) reset = myhdl.ResetSignal(True, True, True) state = myhdl.Signal(myhdl.intbv(0)[len(INITIAL_STATE):]) dut = rule30.Rule30(clock, reset, state, INITIAL_STATE, UPDATE_RULE) @myhdl.always(myhdl.delay(10 / 2)) def advance_clock(): clock.next = not clock @myhdl.instance def check_equality(): yield clock.posedge reset.next = False yield clock.posedge # Simply check the initial value and the first couple of transitions for i in range(10): ref_state = reference.state[::-1] for s, ref in zip(state, ref_state): assert s == ref yield clock.posedge reference.update_state() raise myhdl.StopSimulation() # Use all instances for simulation return myhdl.instances()
def check_crc_stream(serin, clk, crc_poly, dout): lc = len(crc_poly) inp_buf = myhdl.Signal(myhdl.intbv(0, _nrbits=lc)) out_buf = myhdl.Signal(myhdl.intbv(0, _nrbits=lc)) @myhdl.always(clk.posedge) def buf_input(): if inp_buf[lc - 1] == 1: out_buf.next = inp_buf ^ crc_poly else: out_buf.next = inp_buf inp_buf.next = myhdl.concat(out_buf[lc - 1:], serin) # print(myhdl.bin(inp_buf, lc)) # print(myhdl.bin(out_buf, lc)) @myhdl.always_comb def output_logic(): dout.next = out_buf[lc - 1:] return buf_input, output_logic
def uartRx(CLK, RST_X, RXD, DOUT, EN): # reg stage = myhdl.Signal(myhdl.intbv(0)[4:]) cnt = myhdl.Signal(myhdl.intbv(0)[21:]) # counter to latch D0, D1, ..., D7 cnt_detect_startbit = myhdl.Signal( myhdl.intbv(0)[20:]) # counter to detect the Start Bit @myhdl.always_comb def assign(): EN.next = (stage == SS_SER_DONE) @myhdl.always(CLK.posedge) def detect_startbit(): if not RST_X: cnt_detect_startbit.next = 0 else: cnt_detect_startbit.next = 0 if (RXD) else cnt_detect_startbit + 1 @myhdl.always(CLK.posedge) def main_proc(): if not RST_X: stage.next = SS_SER_WAIT cnt.next = 1 DOUT.next = 0 elif (stage == SS_SER_WAIT): stage.next = SS_SER_RCV0 if (cnt_detect_startbit == (SERIAL_WCNT >> 1)) else stage else: if (cnt != SERIAL_WCNT): cnt.next = cnt + 1 else: stage.next = SS_SER_WAIT if (stage == SS_SER_DONE) else stage + 1 DOUT.next = myhdl.ConcatSignal(RXD, DOUT[8:1]) cnt.next = 1 return assign, detect_startbit, main_proc
def setUp(self): self.clk = myhdl.Signal(bool(0)) self.rst = myhdl.Signal(bool(0)) self.data_tx_data = myhdl.Signal(myhdl.intbv()[256:]) self.data_tx_empty = myhdl.Signal(myhdl.intbv()[5:]) self.data_tx_channel = myhdl.Signal(myhdl.intbv()[2:]) self.data_tx_valid = myhdl.Signal(bool(0)) self.data_tx_startofpacket = myhdl.Signal(bool(0)) self.data_tx_endofpacket = myhdl.Signal(bool(0)) self.data_tx_ready = myhdl.Signal(bool(0)) # PCIe devices rc = pcie.RootComplex() ep = test_ep.FejkonEP(self.clk) dev = pcie.Device(ep) rc.make_port().connect(dev) sw = pcie.Switch() rc.make_port().connect(sw) self.rc = rc self.ep = ep self.sw = sw
def counter(CLK, RST_X, VALUE): cnt = myhdl.Signal(myhdl.intbv(0)[WIDTH:]) @myhdl.always(CLK.posedge) def main_proc(): if not RST_X: cnt.next = 0 else: cnt.next = cnt + 1 @myhdl.always_comb def combination(): VALUE.next = cnt return main_proc, combination
def uart_tx(clk_i, rst_i, tx_tick_i, dat_i, start_i, ready_o, tx_o): cnt = createSignal(0, 4) # Contará de 0 a 9 data = createSignal(0, 8) # Ancho del FIFO tx_state = hdl.enum('IDLE', 'TX') # 2 estados de la FSM state = hdl.Signal(tx_state.IDLE) # Estado inicial de estoy ocioso @hdl.always_seq(clk_i.posedge, reset=rst_i) def tx_state_m(): # 50MHz if state == tx_state.IDLE: ready_o.next = 1 if start_i: # Condición para cambiar de estado data.next = dat_i ready_o.next = 0 state.next = tx_state.TX else: tx_o.next = 1 elif state == tx_state.TX: if tx_tick_i: #Usando el divisor del clk_i #lectura de los 8 bits que nos impartan para el caracter if cnt >= 1 and cnt <= 8: tx_o.next = data[0] data.next = hdl.concat( False, data[8:1]) #Usando una logica similar al uart_rx cnt.next = cnt + 1 else: tx_o.next = 0 cnt.next = cnt + 1 #cuando termina de leer el ultimo bit del caracter, reinicia todo. if cnt == 9: tx_o.next = 1 ready_o.next = 1 state.next = tx_state.IDLE cnt.next = 0 else: state.next = tx_state.IDLE #Default return hdl.instances() # Local Variables: # flycheck-flake8-maximum-line-length: 200 # flycheck-flake8rc: ".flake8rc" # End:
def top(self, reset, clk, pipeST_i, pipeST_stage_o): # Reset value to incorporate float and intbv formats shiftEn = myhdl.Signal(bool(1)) # initialiting stage 0 outputs data = (conditional_wire_assign(pipeST_stage_o[0].data, shiftEn, pipeST_i.data, self.reset_val)) sop = (conditional_wire_assign(pipeST_stage_o[0].sop, shiftEn, pipeST_i.sop, 0)) eop = (conditional_wire_assign(pipeST_stage_o[0].eop, shiftEn, pipeST_i.eop, 0)) valid = (conditional_wire_assign(pipeST_stage_o[0].valid, shiftEn, pipeST_i.valid, 0)) channel = (conditional_wire_assign(pipeST_stage_o[0].channel, shiftEn, pipeST_i.channel, 0)) reg_stage_data_inst = [] reg_stage_sop_inst = [] reg_stage_eop_inst = [] reg_stage_valid_inst = [] reg_stage_channel_inst = [] # All other stage outputs for i in range(1, self.NB_PIPELINE_STAGES): reg_stage_data_inst.append( simple_reg_assign(reset, clk, pipeST_stage_o[i].data, self.reset_val, pipeST_stage_o[i - 1].data)) reg_stage_sop_inst.append( simple_reg_assign(reset, clk, pipeST_stage_o[i].sop, 0, pipeST_stage_o[i - 1].sop)) reg_stage_eop_inst.append( simple_reg_assign(reset, clk, pipeST_stage_o[i].eop, 0, pipeST_stage_o[i - 1].eop)) reg_stage_valid_inst.append( simple_reg_assign(reset, clk, pipeST_stage_o[i].valid, 0, pipeST_stage_o[i - 1].valid)) reg_stage_channel_inst.append( simple_reg_assign(reset, clk, pipeST_stage_o[i].channel, 0, pipeST_stage_o[i - 1].channel)) return myhdl.instances()
def main(CLK, RST_X, RXD, TXD, POSITION): # wire send_data = myhdl.Signal(myhdl.intbv(0)[8:]) ready = myhdl.Signal(bool(1)) recv_data = myhdl.Signal(myhdl.intbv(0)[8:]) en = myhdl.Signal(bool(1)) # reg we = myhdl.Signal(bool(1)) init_left = myhdl.Signal(bool(1)) init_done = myhdl.Signal(bool(1)) # module instance send = uartTx(CLK, RST_X, we, send_data, TXD, ready) recv = uartRx(CLK, RST_X, RXD, recv_data, en) @myhdl.always_comb def assign(): if ((not init_done) and we): send_data.next = 0x61 elif (we): send_data.next = recv_data + 1 else: send_data.next = 0 @myhdl.always(CLK.posedge) def logic(): if not RST_X: we.next = 0 init_left.next = 0 init_done.next = 0 elif (POSITION == 0 and (not init_left)): we.next = 1 init_left.next = 1 else: if not init_done: init_done.next = 1 if (recv_data == 0x7a): raise myhdl.StopSimulation we.next = (en and (not we) and ready) if (we): print "send data %x from" % send_data, if (POSITION == 0): print "left" if (POSITION == 1): print "right" return send, recv, assign, logic
def build_trace_generator(self): # need to build a mirror signal list, in order to trace the signals correctly # TODO: is really necessary a mirror signal? assert this. mirror_signals = {} for key, signalref in self.signal_objects.iteritems(): mirror_signals[key] = myhdl.Signal(signalref.val) def mirror_proc_gen(base, mirror): @myhdl.always_comb def mirror_proc(): mirror.next = base return mirror_proc procs = [] for key, sig in mirror_signals.iteritems(): procs.append(mirror_proc_gen(self.signal_objects[key], sig)) return procs
def __init__( self , DATAWIDTH = 32, CHANNEL_WIDTH = 1, INIT_DATA = 0, NB_ACCUMULATIONS = 3): self.DATAWIDTH = DATAWIDTH self.CHANNEL_WIDTH = CHANNEL_WIDTH self.INIT_DATA = INIT_DATA self.NB_ACCUMULATIONS = NB_ACCUMULATIONS # Io Signals self.reset_acc = myhdl.Signal ( bool ( 0 ) ) self.pipeST_i = PipelineST ( self.DATAWIDTH, self.CHANNEL_WIDTH, self.INIT_DATA ) self.pipeST_o = PipelineST ( self.DATAWIDTH, self.CHANNEL_WIDTH, self.INIT_DATA ) # Internal Signals self.accu = PipelineST ( self.DATAWIDTH, self.CHANNEL_WIDTH, self.INIT_DATA ) # Reset value to incorporate float and myhdl.intbv formats self.zero = 0.0 if ( isinstance ( self.INIT_DATA,float ) ) else 0
def uart_tx(clk_i, rst_i, tx_tick_i, dat_i, start_i, ready_o, tx_o): cnt = createSignal(0,4) # Contará de 0 a 9 data = createSignal(0,8) # Ancho del FIFO tx_state = hdl.enum('IDLE','TX') # 2 estados de la FSM state = hdl.Signal(tx_state.IDLE) # Estado inicial de estoy ocioso @hdl.always_seq(clk_i.posedge, reset=rst_i) def tx_state_m(): # 50MHz if state == tx_state.IDLE: ready_o.next = 1 if start_i: # Condición para cambiar de estado data.next = dat_i ready_o.next = 0 state.next = tx_state.TX else: tx_o.next = 1 elif state == tx_state.TX: if tx_tick_i: #Usando el divisor del clk_i if cnt >=1 and cnt <= 8: tx_o.next = data[0] data.next = hdl.concat(False, data[8:1]) cnt.next = cnt + 1 else: tx_o.next = 0 cnt.next = cnt + 1 if cnt == 9: tx_o.next = 1 ready_o.next = 1 state.next = tx_state.IDLE cnt.next = 0 else: state.next = tx_state.IDLE return hdl.instances()
def getset_internal_signal(self, signalname, newsignal_ref=None): """ Try to get a reference to a internal signal with name "signalname". If not found, optionally add a new signal with its reference in "newsignal_ref". Arguments: * signalname: * newsignal_ref: Returns: the MyHDL signal reference, or the contents of "newsignal_ref" """ if not hasattr(self, "internal_signals"): self._new_internal_signals() if signalname not in self.internal_signals: if newsignal_ref is not None: if isinstance(newsignal_ref, myhdl.SignalType): self.internal_signals[signalname] = newsignal_ref else: # build a new signal based on newsignal_ref self.internal_signals[signalname] = myhdl.Signal(newsignal_ref) else: raise ValueError("%s : Signal '%s' not found." % (repr(self), signalname)) return self.internal_signals[signalname]
def uart_tx(clk_i, rst_i, tx_tick_i, dat_i, start_i, ready_o, tx_o): dat_r = createSignal(0, 8) bit_cnt = createSignal(0, 3) tx_state = hdl.enum('IDLE', 'START', 'DATA', 'STOP') state = hdl.Signal(tx_state.IDLE) @hdl.always_seq(clk_i.posedge, reset=rst_i) def fsm_proc(): if state == tx_state.IDLE: ready_o.next = True if start_i: dat_r.next = dat_i state.next = tx_state.START ready_o.next = False else: tx_o.next = True elif state == tx_state.START: if tx_tick_i: tx_o.next = False state.next = tx_state.DATA elif state == tx_state.DATA: if tx_tick_i: tx_o.next = dat_r[0] dat_r.next = hdl.concat(False, dat_r[8:1]) bit_cnt.next = bit_cnt + 1 if bit_cnt == 7: state.next = tx_state.STOP elif state == tx_state.STOP: if tx_tick_i: state.next = tx_state.IDLE tx_o.next = True ready_o.next = True else: state.next = tx_state.IDLE return hdl.instances()
def fifo(CLK, RST_X, ENQ, DEQ, DIN, DOUT, EMPTY, FULL): # wire we = myhdl.Signal(bool(1)) re = myhdl.Signal(bool(1)) # reg mem = [myhdl.Signal(myhdl.intbv(0)[WIDTH:]) for i in range(DEPTH)] cnt = myhdl.Signal(myhdl.intbv(0)[W_CNT:]) head = myhdl.Signal(myhdl.intbv(0)[W_POS:]) tail = myhdl.Signal(myhdl.intbv(0)[W_POS:]) @myhdl.always_comb def assign(): EMPTY.next = (cnt == 0) FULL.next = (cnt == DEPTH) we.next = (ENQ and (not (cnt == DEPTH))) re.next = (DEQ and (not (cnt == 0))) @myhdl.always(CLK.posedge) def always(): if not RST_X: DOUT.next = 0 cnt.next = 0 head.next = 0 tail.next = 0 else: if we: mem[tail].next = DIN tail.next = 0 if (tail == DEPTH - 1) else tail + 1 if re: DOUT.next = mem[head] head.next = 0 if (head == DEPTH - 1) else head + 1 else: DOUT.next = 0 if (we and re): cnt.next = cnt elif we: cnt.next = cnt + 1 elif re: cnt.next = cnt - 1 return assign, always
def uartTx(CLK, RST_X, WE, DIN, TXD, READY): # reg cmd = myhdl.Signal(myhdl.intbv(0)[9:]) waitnum = myhdl.Signal(myhdl.intbv(0)[12:]) cnt = myhdl.Signal(myhdl.intbv(0)[4:]) ready = myhdl.Signal(bool(1)) startbit = myhdl.Signal(bool(1)) stopbit = myhdl.Signal(bool(1)) @myhdl.always_comb def assign(): READY.next = ready startbit.next = 0 stopbit.next = 1 @myhdl.always(CLK.posedge) def main_proc(): if not RST_X: TXD.next = 1 ready.next = 1 cmd.next = 0x1ff waitnum.next = 0 cnt.next = 0 elif (ready): TXD.next = 1 waitnum.next = 0 if (WE): ready.next = 0 cmd.next = myhdl.ConcatSignal(DIN, startbit) # set start bit # cmd.next = myhdl.concat(DIN, False) # set start bit cnt.next = 10 elif (waitnum >= SERIAL_WCNT): TXD.next = cmd[0] ready.next = (cnt == 1) cmd.next = myhdl.ConcatSignal(stopbit, cmd[9:1]) # cmd.next = myhdl.concat(True, cmd[9:1]) waitnum.next = 1 cnt.next = cnt - 1 else: waitnum.next = waitnum + 1 return assign, main_proc
BAUD_RATE=115200): tx_start = createSignal(0, 1) # entrada tx_start_i del UART tx_ready = createSignal(0, 1) # salida tx_ready_o del UART rx_ready = createSignal(0, 1) # salida rx_ready_o del UART rx_dat = createSignal( 0, 8) # salida rx_dat_o del UART y entrada dat_i del FIFO dequeue = createSignal(0, 1) # entrada dequeue_i del FIFO empty = createSignal(0, 1) #salida empty_o del FIFO full = createSignal(0, 1) # salida full_o del FIFO dat = createSignal(0, 8) # entrada dat_i del tx y salida dat_o del FIFO value = createSignal( 0, 11) # salida count_o del FIFO y entrada value_i del Driver7Seg l_state = hdl.enum( 'RX', 'TX') #Declaracion para dos estados, recibiendo y enviando. state = hdl.Signal(l_state.RX) uart = UART(clk_i=clk_i, rst_i=rst_i, tx_dat_i=dat, tx_start_i=tx_start, tx_ready_o=tx_ready, tx_o=tx_o, rx_dat_o=rx_dat, rx_ready_o=rx_ready, rx_i=rx_i, CLK_BUS=CLK_BUS, BAUD_RATE=BAUD_RATE) fifo = FIFO(clk_i=clk_i, rst_i=rst_i,
def __init__(self, parameters): assert parameters.nleds <= 8, 'You should use until 8 leds' self.leds = hdl.Signal( hdl.intbv(val=0, min=0, max=(2**parameters.nleds) - 1)) self.select = hdl.Signal(False)
segmentos_o, FIFO_DEPTH=1024, CLK_BUS=50_000_000, BAUD_RATE=115200): A_WIDTH = log2up(FIFO_DEPTH) tx_data = createSignal(0, 8) tx_start = createSignal(0, 1) tx_ready = createSignal(0, 1) rx_data = createSignal(0, 8) rx_ready = createSignal(0, 1) dequeue = createSignal(0, 1) f_count = createSignal(0, A_WIDTH + 1) f_empty = createSignal(0, 1) f_full_o = createSignal(0, 1) lb_state = hdl.enum('IDLE', 'SEND') state = hdl.Signal(lb_state.IDLE) uart = UART(clk_i=clk_i, rst_i=rst_i, tx_dat_i=tx_data, tx_start_i=tx_start, tx_ready_o=tx_ready, tx_o=tx_o, rx_dat_o=rx_data, rx_ready_o=rx_ready, rx_i=rx_i, CLK_BUS=CLK_BUS, BAUD_RATE=BAUD_RATE) # noqa fifo = FIFO(clk_i=clk_i, rst_i=rst_i, enqueue_i=rx_ready, dequeue_i=dequeue,
def simulation_thread(self): params = copy.copy(self.params) clock = myhdl.Signal(bool()) reset = myhdl.ResetSignal(bool(True), True, True) phase_step = myhdl.Signal(myhdl.intbv(0)[self.params.phase_acc_bits:]) BITS = self.params.out_bits cos_out = myhdl.Signal(myhdl.intbv(0, -2**(BITS - 1), 2**(BITS - 1))) sin_out = myhdl.Signal(myhdl.intbv(0, -2**(BITS - 1), 2**(BITS - 1))) # Constants samples = self.params.fft_samples dut = nco.NCOCordic(clock, reset, phase_step, cos_out, sin_out, PHASE_PRECISION=self.params.phase_bits, LUT_DEPTH=self.params.lut_depth, DITHER=self.params.phase_dither, CORDIC_STAGES=self.params.cordic_stages) output = [] @myhdl.always(myhdl.delay(1)) def clockgen(): clock.next = not clock @myhdl.instance def simulate(): # A couple of cycles to reset the circuit reset.next = True phase_step.next = 0 yield clock.negedge yield clock.negedge reset.next = False phase_step.next = self.params.phase_step # Flush the pipeline once for i in range(0, self.params.pipeline_length): yield clock.negedge # Now the first correct sample is at the output for sample in range(0, samples): time = sample / self.params.frequency theoretical_phase = (sample / self.params.frequency * self.params.actual_tone % 1.0) * 2 * np.pi # Save the result output.append((time, theoretical_phase, int(cos_out.val), int(sin_out.val))) self.emit('simulation_progress', sample / float(samples)) if self._thread_abort: raise myhdl.StopSimulation("Simulation Aborted") yield clock.negedge raise myhdl.StopSimulation myhdl.Simulation(dut, clockgen, simulate).run(None) simulation_result = np.array(output, dtype=np.float64) self.emit('simulation_done', simulation_result, params)