def __init__(self, clock, aux_depth=(4, 4, 4)):

        """

         This interface is the internal interface modeled after
         the xapp495 internal audio interface

         Args:
             clock: pixel clock.
             aux_depth (optional): The bus width of the aux interface
                                          Default value: (4, 4, 4)

        Usage:
            aux_interface = AuxInterface()

        """

        self.clock = clock
        self.aux_depth = aux_depth

        # AUX data from audio source
        self.aux0 = Signal(intbv(0)[aux_depth[0]:])
        self.aux1 = Signal(intbv(0)[aux_depth[1]:])
        self.aux2 = Signal(intbv(0)[aux_depth[2]:])

        # Audio data enable
        self.ade = Signal(bool(0))
Example #2
0
    def gen(self):
        system = self.system
        bus = self.bus()

        insts = []

        bin_data = Signal(intbv(0)[(bus.data_width+1) / 2:])
        gray_data = Signal(intbv(0)[bus.data_width - len(bin_data):])

        @always_comb
        def bin_inst():
            bin_data.next = bus.ADDR & ((1<<len(bin_data))-1)
        insts.append(bin_inst)

        gray_inst = gray_encoder(bin_data, gray_data)
        insts.append(gray_inst)

        @always_seq(system.CLK.posedge, system.RST)
        def seq():
            if bus.RD and bus.ADDR < bus.addr_depth:
                bus.RD_DATA.next = bin_data | (gray_data << len(bin_data))
            else:
                bus.RD_DATA.next = 0

        insts.append(seq)

        return insts
Example #3
0
    def test_offset_corrector(self):
        correct_i = Signal(intbv(1, min=-2**9, max=2**9))
        correct_q = Signal(intbv(-1, min=-2**9, max=2**9))

        in_sign = Signature("in", True, bits=10)
        out_sign = Signature("out", True, bits=10)

        s = DSPSim(in_sign=in_sign, out_sign=out_sign)
        def test_offset_corrector():
            offset_corrector_0 = offset_corrector(s.clearn, s.clock,
                correct_i, correct_q,
                s.input, s.output)
            return offset_corrector_0

        in_t = np.arange(0, 10)
        in_i = np.zeros((10,))
        in_q = np.zeros((10,))
        
        out_i, out_q = s.simulate_quadrature(in_i, in_q, test_offset_corrector)
        out_t = np.arange(0, out_i.shape[0])
        
        assert in_t.shape == out_t.shape

        for i in range(out_t.shape[0]):
            assert out_i[i] == int(in_i[i]) + correct_i
            assert out_q[i] == int(in_q[i]) + correct_q

        f = plt.figure("test_offset_corrector")
        plt.title("test_offset_corrector")

        f_in = figure_discrete_quadrature("in", (2, 1, 1), f, in_sign, in_t, in_i, in_q)
        f_out = figure_discrete_quadrature("out", (2, 1, 2), f, out_sign, out_t, out_i, out_q)
        plt.savefig("test_offset_corrector.png")
Example #4
0
 def tx(self, decim=1):
     re = [intbv(i)[10:] for i in self.tx_i][::decim]
     re = [intbv(concat(not i[len(i)-1], i[len(i)-1:])).signed() for i in re]
     im = [intbv(q)[10:] for q in self.tx_q][::decim]
     im = [intbv(concat(not q[len(q)-1], q[len(q)-1:])).signed() for q in im]
     y = np.array([i + 1j * q for i, q in zip(re, im)])
     return y
Example #5
0
def led_peripheral(glbl, regbus, leds, base_address=0x8240):
    """ LED memory-map peripheral
    This (rather silly) core will select different LED
    displays based on the memory-mapped select register.
    """

    ndrv = 3  # the number of different drivers
    regfile.base_address = base_address 
    
    clock, reset = glbl.clock, glbl.reset
    rleds = Signal(intbv(0)[len(leds):])

    # assign the LED port to the local register
    assign(leds, rleds)

    # memory-mapped registers
    greg = regbus.add(regfile, 'led')

    # led bus from each driver
    dled = Signals(intbv(0)[len(leds):0], ndrv)

    # instantiate different LED drivers
    led_insts = [None for _ in range(ndrv)]
    led_insts[0] = led_stroby(clock, reset, dled[0])
    led_insts[1] = led_count(clock, reset, dled[1])
    led_insts[2] = led_dance(clock, reset, dled[2])

    @always_seq(clock.posedge, reset=reset)
    def beh():
        for ii in range(ndrv):
            idx = regfile.select
            rleds.next = dled[idx-1]

    return myhdl.instances()
Example #6
0
    def stimulus():
        for i in range(5):
            if random.random() > 0.25:
                clk.next = 1
            if random.random() > 0.75:
                rst.next = 1

            pc_adder_in.next, data1_in.next, data2_in.next, address32_in.next = [intbv(random.randint(-255, 255)) for i in range(4)]

            rs_in.next, rd_in.next, rt_in.next, func_in.next = [intbv(random.randint(0, 15)) for i in range(4)]

            RegDst_in.next, ALUop_in.next, ALUSrc_in.next = [random.randint(0, 1) for i in range(3)]
            Branch_in.next, MemRead_in.next, MemWrite_in.next = [random.randint(0, 1) for i in range(3)]
            RegWrite_in.next, MemtoReg_in.next = [random.randint(0, 1) for i in range(2)]

            yield delay(1)
            print "-" * 79
            print "%i %i %i | %i %i %i | %i | %i  %i  %i  %i  %i  %i  %i  %i " % (data1_in, data2_in, address32_in,
                                                                                  rs_in, rt_in, rd_in, func_in,
                                                                                  RegDst_in, ALUop_in, ALUSrc_in,
                                                                                  Branch_in, MemRead_in, MemWrite_in,
                                                                                  RegWrite_in, MemtoReg_in)
            print "clk: %i  rst: %i " % (clk, rst)

            print "%i %i %i | %i %i %i | %i | %i  %i  %i  %i  %i  %i  %i  %i " % (data1_out, data2_out, address32_out,
                                                                                  rs_out, rt_out, rd_out, func_out, RegDst_out, ALUop_out, ALUSrc_out,
                                                                                  Branch_out, MemRead_out, MemWrite_out,
                                                                                  RegWrite_out, MemtoReg_out)

            clk.next = 0
            rst.next = 0
            yield delay(1)
Example #7
0
    def __init__(self, name, signed, **kwargs):
        self.name = name
        self.signed = signed

        if 'bits' in kwargs:
            bits = self.bits = kwargs['bits']
            if signed:
                Q = 2**(bits-1)
                self.min = -Q
                self.max = Q
            else:
                Q = 2**bits
                self.min = 0
                self.max = Q

        elif 'min' in kwargs and 'max' in kwargs:
            self.min = kwargs['min']
            self.max = kwargs['max']
            self.bits = len(self.myhdl(0))

        else:
            raise AttributeError, "Must give bits or min & max"

        self.valid = kwargs.get('valid', Signal(bool(0)))
        self.last = kwargs.get('last', Signal(bool(0)))
        self.i = kwargs.get('i', Signal(intbv(0, min=self.min, max=self.max)))
        self.q = kwargs.get('q', Signal(intbv(0, min=self.min, max=self.max)))
Example #8
0
 def testSliceAssign(self):
     s = Signal(intbv(min=-24, max=34))
     for i in (-24, -2, 13, 33):
         for k in (6, 9, 10):
             s.next[:] = 0
             s.next[k:] = i
             self.assertEqual(s.next, i)
     for i in (-25, -128, 34, 35, 229):
         for k in (0, 9, 10):
             try:
                 s.next[k:] = i
                 # s._update()
             except ValueError:
                 pass
             else:
                 self.fail()
     s = Signal(intbv(5)[8:])
     for v in (0, 2**8-1, 100):
         s.next[:] = v
     for v in (-1, 2**8, -10, 1000):
         try:
             s.next[:] = v
             # s._update()
         except ValueError:
             pass
         else:
             self.fail()
Example #9
0
    def gen(self):
        idx = Signal(intbv(0, 0, self.parts))

        insts = []

        rd_parts = []
        for i in range(self.parts):
            s = Signal(intbv(0)[self.data_width:])
            insts.append(self.extract(s, i))
            rd_parts.append(s)

        @always_comb
        def comb():
            self.parent.RD.next = 0
            self.RD_DATA.next = rd_parts[idx]
            self.RD_EMPTY.next = self.parent.RD_EMPTY

            if self.RD and idx == self.parts - 1:
                self.parent.RD.next = 1

        @always_seq(self.RD_CLK.posedge, self.RD_RST)
        def seq():
            if self.RD:
                idx.next = 0
                if idx != self.parts - 1:
                    idx.next = idx + 1

        return instances()
Example #10
0
def convert():
    clock = Signal(bool(0))
    addr = Signal(intbv(0)[8:])
    datao = Signal(intbv(0)[16:])
    inst = romr(addr, clock, datao)
    inst.convert(hdl='Verilog', name='ROMR',
                 directory='output_files', testbench=False)
def serial_adder(R, load_en, clk, add_carry):
    '''
    adds the two numbers given in R and stores the sum in
    the lower significant half of R
    :param R: Two numbers of equal bit vector length
    :param load_en: when equal to 1 it parallel loads the value in R to the two internal shift registers
    :param clk:
    :param add_carry: will contain the final carry bit after adding the msbs
    '''
    out1 = Signal(intbv(0)[len(R)/2:])
    parallelin1 = R[len(R):len(R)/2]
    out2 = Signal(intbv(0)[len(R)/2:])
    parallelin2 = R[len(R)/2:]
    sum, cin, cout, inp1, inp2, a, b = [Signal(intbv(0)) for i in range(7)]
    shift1 = shift_reg(inp1, out1, clk, parallelin1, load_en)    #contains first number
    shift2 = shift_reg(inp2,out2,clk,parallelin2, load_en)       #contains second number initially and final result at the end of simulation
    adder = full_adder(a, b, cin, sum, cout, clk)
    @always_comb
    def connect():
        inp1.next = intbv(out1[0])[1:]
        inp2.next = sum
        a.next = intbv(out1[0])[1:]
        b.next = intbv(out2[0])[1:]
        add_carry.next = cout
    return connect, shift1, shift2, adder
Example #12
0
    def mux_test():

        sel    = Signal(bool(0))
        q      = Signal(intbv(0))
        a      = Signal(intbv(0))
        b      = Signal(intbv(0))

        mux = mux2(q, a, b, sel)

        DELAY = delay(PERIOD // 2)

        @instance
        def stimulus():
            for step in range(STEPS):
                print "STEP %02d:" % step,

                a.next = step
                b.next = step << 8

                if step % 2 == 0:
                    sel.next = not sel

                yield DELAY
                print "%d q %s a %s b %s" % (sel, bin(q, 16), bin(a, 16), bin(b, 16))
                if sel % 2 == 0:
                    assert q == a
                else:
                    assert q == b

            raise StopSimulation

        return mux, stimulus
Example #13
0
 def __init__(self, color_space=(8, 8, 8)):
     """An red-green-blue interface """
     assert len(color_space) == 3
     rbits, gbits, bbits = color_space
     self.red = Signal(intbv(0)[rbits:0])
     self.green = Signal(intbv(0)[gbits:0])
     self.blue = Signal(intbv(0)[rbits:0])
Example #14
0
def convert():
    q = Signal(intbv(0)[1:0])
    d = Signal(intbv(0)[1:0])
    wr, rst = [Signal(bool(0)) for i in range(2)]

    toVerilog(dff, q, d, wr, rst)
    toVHDL(dff, q, d, wr, rst)
Example #15
0
def icestick_blinky_host(clock, led, pmod, uart_tx, uart_rx, uart_dtr, uart_rts):
    """
    This example is similar to the other examples in this directory but
    the LEDs are controlled externally via command packets sent from a
    host via the UART on the icestick.

    Ports:
      clock:
      led:
      pmod:
      uart_tx:
      uart_rx:
    """

    glbl = Global(clock, None)
    ledreg = Signal(intbv(0)[8:])

    # create the timer tick instance
    tick_inst = glbl_timer_ticks(glbl, include_seconds=True)

    # create the interfaces to the UART
    fbustx = FIFOBus(width=8, size=4)
    fbusrx = FIFOBus(width=8, size=4)

    # create the memmap (CSR) interface
    memmap = Barebone(glbl, data_width=32, address_width=32)

    # create the UART instance.
    uart_inst = uartlite(glbl, fbustx, fbusrx, uart_rx, uart_tx)

    # create the packet command instance
    cmd_inst = memmap_command_bridge(glbl, fbusrx, fbustx, memmap)

    @always_seq(clock.posedge, reset=None)
    def beh_led_control():
        memmap.done.next = not (memmap.write or memmap.read)
        if memmap.write and memmap.mem_addr == 0x20:
            ledreg.next = memmap.write_data

    @always_comb
    def beh_led_read():
        if memmap.read and memmap.mem_addr == 0x20:
            memmap.read_data.next = ledreg
        else:
            memmap.read_data.next = 0

    # blink one of the LEDs
    tone = Signal(intbv(0)[8:])

    @always_seq(clock.posedge, reset=None)
    def beh_assign():
        if glbl.tick_sec:
            tone.next = (~tone) & 0x1
        led.next = ledreg | tone[5:]

        pmod.next = 0

    # @todo: PMOD OLED memmap control

    return (tick_inst, uart_inst, cmd_inst, beh_led_control, beh_led_read, beh_assign)
Example #16
0
    def gen_internal(self):
        self.cur_count = Signal(intbv(0, 0, self.count + 1))
        self.cur_skip = Signal(intbv(0, 0, self.skip + 1))

        self.new_count = Signal(intbv(0, 0, self.count + 1))
        self.new_skip = Signal(intbv(0, 0, self.skip + 1))

        @always_comb
        def comb():
            self.new_count.next = self.cur_count
            self.new_skip.next = self.cur_skip

            if self.cur_skip != 0:
                self.new_skip.next = self.cur_skip - 1

            elif self.cur_count != self.count:
                if self.strobe:
                    self.new_count.next = self.cur_count + 1
                    self.new_skip.next = self.skip

        @always_seq(self.clk.posedge, self.rst)
        def seq():
            self.cur_count.next = self.new_count
            self.cur_skip.next = self.new_skip

        @always_comb
        def busy_comb():
            self.busy.next = 1
            if self.new_count != self.count and self.new_skip == 0:
                self.busy.next = 0

        return instances()
Example #17
0
    def __init__(self, glbl=None, data_width=8, address_width=16, name=None):
        """ AvalonMM bus object
        Parameters (kwargs):
        --------------------
        :param glbl: system clock and reset
        :param data_width: data bus width
        :param address_width: address bus width
        :param name: name for the bus
        """
        super(AvalonMM, self).__init__(data_width=data_width,
                                       address_width=address_width)
        if glbl is None:
            self.clk = Clock(0)
        else:
            self.clk = glbl.clock

        if glbl.reset is None:
            self.reset = Reset(0, active=1, async=False)
        else:
            self.reset = glbl.reset

        self.address = Signal(intbv(0)[address_width:])
        self.byteenable = Signal(intbv(0)[2:])
        self.read = Signal(bool(0))
        self.write = Signal(bool(0))
        self.waitrequest = Signal(bool(0))
        self.readdatavalid = Signal(bool(0))
        self.readdata = Signal(intbv(0)[data_width:])
        self.writedata = Signal(intbv(0)[data_width:])
        self.response = Signal(intbv(0)[2:])

        self._readdata = []
        self._readdatavalid = []
        self._waitrequest = []
Example #18
0
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
Example #19
0
    def __init__(self, size=16, width=8):
        """
        """
        self.name = "fifobus{0}".format(_fb_num)

        # @todo: add write clock and read clock to the interface!
        # @todo: use longer names read, read_valid, read_data,
        # @todo: write, write_data, etc.!

        # all the data signals are from the perspective
        # of the FIFO being interfaced to.        
        self.clear = Signal(bool(0))           # fifo clear
        #self.wclk = None                      # write side clock
        self.wr = Signal(bool(0))              # write strobe to fifo
        self.wdata = Signal(intbv(0)[width:])  # fifo data in

        #self.rclk = None                      # read side clock
        self.rd = Signal(bool(0))              # fifo read strobe
        self.rdata = Signal(intbv(0)[width:])  # fifo data out
        self.rvld = Signal(bool(0))
        self.empty = Signal(bool(1))           # fifo empty
        self.full = Signal(bool(0))            # fifo full
        self.count = Signal(intbv(0, min=0, max=size+1))

        self.width = width
        self.size = size

        _add_bus(self, self.name)
Example #20
0
def video_memory(glbl, vidmem_write, vidmem_read):
    """
    """
    assert vidmem_write.width == vidmem_read.width
    vmem = vidmem_write
    res = vmem.resolution
    mem = [Signal(intbv(0)[vmem.width:]) for _ in range(vmem.size)]

    clock, reset = glbl.clock, glbl.reset

    # address translation
    waddr = Signal(intbv(0, min=0, max=vmem.size))

    @always_comb
    def beh_addr():
        # @todo: this will be expensive, shortcut/hack ???
        waddr.next = vmem.hpxl + (vmem.vpxl * vmem.resolution[0])

    # write
    @always(clock.posedge)
    def beh_write():
        if vidmem_write.wr:
            mem[waddr].next = concat(vmem.red, vmem.green, vmem.blue)

    return myhdl.instances()
Example #21
0
 def __init__(self, data_width=24, neg=False):
     if(neg):
         self.data_range = 2**data_width
         self.data_out = Signal(intbv(0, min=-self.data_range, max=self.data_range))
     else:
         self.data_width = data_width
         self.data_out = Signal(intbv(0)[data_width:])
Example #22
0
 def __init__(self, nbits=8):
     """member variables initialize"""
     self.nbits = nbits
     self.red = Signal(intbv(0)[nbits:])
     self.green = Signal(intbv(0)[nbits:])
     self.blue = Signal(intbv(0)[nbits:])
     self.data_valid = Signal(bool(0))
Example #23
0
def c_testbench_three():
    """
    this will test the use of constants in an inteface
    as well as top-level interface conversion.
    """
    clock = Signal(bool(0))
    reset = ResetSignal(0, active=0, isasync=True)
    x = Signal(intbv(3, min=-5000, max=5000))
    y = Signal(intbv(4, min=-200, max=200))
    intf = IntfWithConstant2()

    tbdut = top_const(clock, reset, x, y, intf)
    
    @instance
    def tbclk():
        clock.next = False
        while True:
            yield delay(3)
            clock.next = not clock
        
    @instance
    def tbstim():
        reset.next = reset.active
        yield delay(33)
        reset.next = not reset.active
        yield clock.posedge
        yield clock.posedge
        print("x: %d" % (x,))
        print("y: %d" % (y,))
        assert x == 0
        assert y == 0
        raise StopSimulation

    return tbdut, tbclk, tbstim
Example #24
0
    def op_add_sub():

        if __debug__:
            if debug:
                print("inside alu", acc, opd)
        if dec.add_sub == 0:
            res_arith.next = intbv(acc + opd)[16:]
            if __debug__:
                if debug:
                    print(res_arith.next, acc + opd, acc, opd)
        else:
            res_arith.next = intbv(acc - opd)[16:]

    # for the logical operations
    # @always_comb
    # def op_logical():

        if alu_op == alu_op_type.LD:
            # LOAD
            res_log.next = opd

        elif alu_op == alu_op_type.AND:
            # AND
            res_log.next = acc & opd

        elif alu_op == alu_op_type.OR:
            # OR
            res_log.next = acc | opd

        elif alu_op == alu_op_type.XOR:
            # XOR
            res_log.next = acc ^ opd
Example #25
0
def SquareGenerator(freq, duty, dout, clk, reset):

    # freq.max = FS / 2
    # freq.min = 0Hz

    M = len(freq)       # Bits
    CLK_MULT = FS_MODE * CLK_FREQ
    HALF_HZ_CYCLES = CLK_MULT * FS
    extra_bits = log(CLK_MULT, 2)

    assert M > extra_bits

    count = Signal(intbv(0, _nrbits=M + extra_bits))
    count_max = Signal(intbv(0, _nrbits=M + extra_bits))

    @always(clk.posedge)
    def set_freq():
        count_max.next = ((freq << (extra_bits - M)) + CLK_MULT) << (freq // M)

    @always(clk.posedge)
    def counting():
        if count < count_max - 1:
            count.next += 1
        else:
            count.next = 0
            dout.next = not dout

    return set_freq, counting
Example #26
0
File: axi4st.py Project: gbin/rhea
    def __init__(self, data_width=32,  address_width=4, response_width=2):
        self.data_width = data_width
        self.address_width = address_width
        self.response_width = response_width
        # currently top-level port interfaces can't contain multiple
        # levels (nested).  This will be enhanced in the future.

        self.awvalid = Signal(bool(0))
        self.awdata = Signal(intbv(15)[address_width:])
        self.awaccept = Signal(bool(1))

        self.wvalid = Signal(bool(0))
        self.wdata = Signal(intbv(0xE6)[data_width:])
        self.waccept = Signal(bool(1))

        self.arvalid = Signal(bool(0))
        self.ardata = Signal(intbv(15)[address_width:])
        self.araccept = Signal(bool(1))

        self.rvalid = Signal(bool(0))
        self.rdata = Signal(intbv(0xE8)[data_width:])
        self.raccept = Signal(bool(1))

        self.bvalid = Signal(bool(0))
        self.bdata = Signal(intbv(3)[response_width:])
        self.baccept = Signal(bool(1))
Example #27
0
def emit_connect():
    from myhdl import toVerilog

    bus = DdrBus(2, 12, 2)
    rename_interface(bus, 'bus')

    soc_clk = Signal(False)
    soc_clk_b = Signal(False)

    soc_cs = Signal(False)
    soc_ras = Signal(False)
    soc_cas = Signal(False)
    soc_we = Signal(False)
    soc_ba = Signal(False)
    soc_a = Signal(False)

    soc_dqs = Signal(intbv(0)[bus.d_width:])
    soc_dm = Signal(intbv(0)[bus.d_width:])
    soc_dq = Signal(intbv(0)[bus.d_width * 8:])

    toVerilog(ddr_connect, bus, soc_clk, soc_clk_b, None,
              soc_cs, soc_ras, soc_cas, soc_we, soc_ba, soc_a,
              soc_dqs, soc_dm, soc_dq)

    print
    print open('ddr_connect.v', 'r').read()
Example #28
0
def device_serdes_input_prim(serdes):
    """
    """
    assert isinstance(serdes, SERDESInterface)

    nbits = serdes.number_of_bits
    hbits = nbits//2
    serial_in = serdes.serial
    sclk, pclk, data = serdes.get_signals()

    bcnt = Signal(intbv(0, min=0, max=nbits))
    input_reg = Signal(intbv(0)[nbits:])
    capture_reg = Signal(intbv(0)[nbits:])
    _pclk = Signal(bool(0))

    # get the serial input from the diff signals
    # g = serdes.input_buffer(serial_in)
    # mods.append(g)

    # capture the input serial stream
    @always(sclk.posedge)
    def rtl_input_capture():
        input_reg.next = concat(input_reg[nbits-1:1], serial_in)
        if bcnt == nbits-1:
            bcnt.next = 0
            capture_reg.next = input_reg
            _pclk.next = True
        elif bcnt == hbits:
            _pclk.next = False

    @always(pclk.posedge)
    def rtl_data():
        data.next = capture_reg

    return rtl_input_capture, rtl_data
Example #29
0
    def gen(self):
        system = self.system
        bus = self.bus()

        mem = [ Signal(intbv(0)[self.accumulator_width:])
                for _ in range(1<<self.sample_width) ]

        inc = Signal(False)
        inc_idx = Signal(intbv(0)[self.sample_width:])
        inc_val = Signal(intbv(0)[self.accumulator_width:])

        @always_seq(system.CLK.posedge, system.RST)
        def contributions_inst():
            bus.RD_DATA.next = 0

            if bus.WR:
                mem[bus.ADDR].next = bus.WR_DATA
            elif inc:
                inc.next = 0
                mem[inc_idx].next = inc_val

            if bus.RD:
                bus.RD_DATA.next = mem[bus.ADDR]
            elif self.STROBE:
                inc.next = 1
                inc_idx.next = self.SAMPLE
                inc_val.next = mem[self.SAMPLE].next + 1

        return instances()
Example #30
0
def main_simulate():
    resetn = Signal(bool(1))
    system_clock = Signal(bool(0))
    paddr = Signal(intbv(0, 0, 2**32))
    psel = Signal(bool(0))
    penable = Signal(bool(0))
    pwrite = Signal(bool(1))
    pwdata = Signal(intbv(0, 0, 2**32))
    pready = Signal(bool(0))
    prdata = Signal(intbv(0, 0, 2**32))
    pslverr = Signal(bool(0))
    apb3_bus_signals = [system_clock, resetn, paddr, psel, penable, pwrite,
                        pwdata, pready, prdata, pslverr]

    SYSTEM_CLOCK_FREQ = 10e6
    SYSTEM_CLOCK_PERIOD_IN_NS = int(1.0 / SYSTEM_CLOCK_FREQ * 1e9)

    def testbench():
        clock = drive_system_clock(system_clock, SYSTEM_CLOCK_PERIOD_IN_NS)
        reset = drive_reset(resetn)
        master = apb3_master_mock([(0x40050400, 0xffffffff),
                                   (0x40050400, 0xffff7fff)],
                                  *apb3_bus_signals)
        slave = fluidsp_controller(*(apb3_bus_signals))
        return clock, reset, slave, master

    traced_testbench = traceSignals(testbench)
    sim = Simulation(traced_testbench)
    sim.run(SYSTEM_CLOCK_PERIOD_IN_NS * 100)
 def add(
 ):  # this simple block adds the the calculated jump value shifted to the left by 1
     jump = intbv((imm << 1), min=-1024, max=1024)
     result.next = PC + jump  # assigning the next value to the result
Example #32
0
 def __init__(self, width_data=12, width_addr=6):
     self.data_in = Signal(intbv(0)[width_data:].signed())
     self.read_addr = Signal(modbv(0)[width_addr:])
     self.buffer_sel = Signal(bool(0))
Example #33
0
def Controller(spec,
               clk,
               reset,
               rx_msg,
               rx_next,
               rx_ready,
               tx_msg,
               tx_next,
               tx_ready,
               exp_addr,
               exp_data_write,
               exp_data_read,
               exp_wen,
               exp_reset,
               exp_clk_en,
               exp_reset_active=False):
    '''
    spec
        the controller specification
    clk
        Clock input
    reset
        Reset input
    rx_*
        rx_signals
    tx_*
        tx signals
    exp_addr
        Output signal setting the address for the experiment to be operated on
    exp_data_write
        Output signal setting the value to write to the experiment 
    exp_data_read
        Input signal containing the data that is read from the experiment
    exp_wen
        Output pulse signal indicating to the experiment that the current 
        operation is a write operation
    exp_reset
        Output signal indicating to the experiment that it is to be reset to 
        its initial state
    exp_clk_en
        Output clock enable signal for the experiment

    '''

    # Pipeline registers
    ex_res_opcode_res_reg = Signal(intbv(0)[spec.width_opcode:0])
    ex_res_opcode_res_next = Signal(intbv(0)[spec.width_opcode:0])
    ex_res_nop_reg = Signal(True)
    ex_res_nop_next = Signal(True)
    ex_res_cycle_count_reg = Signal(intbv(0)[spec.width_value:0])
    ex_res_cycle_count_next = Signal(intbv(0)[spec.width_value:0])
    ex_res_addr_reg = Signal(intbv(0)[spec.width_addr:0])
    ex_res_addr_next = Signal(intbv(0)[spec.width_addr:0])

    #internal signals
    cycle_autonomous = Signal(False)
    cycle_start = Signal(False)
    cycle_pause = Signal(False)
    cycle_step = Signal(False)

    cmd_message = rx_msg
    cmd_opcode = Signal(intbv(0)[spec.width_opcode:0])
    cmd_addr = Signal(intbv(0)[spec.width_addr:0])
    cmd_data = Signal(intbv(0)[spec.width_data:0])

    # EX stage instances
    control = ControllerControl(spec=spec,
                                opcode_cmd=cmd_opcode,
                                reset=reset,
                                opcode_res=ex_res_opcode_res_next,
                                rx_ready=rx_ready,
                                cycle_autonomous=cycle_autonomous,
                                rx_next=rx_next,
                                tx_ready=tx_ready,
                                nop=ex_res_nop_next,
                                exp_wen=exp_wen,
                                exp_reset=exp_reset,
                                cycle_start=cycle_start,
                                cycle_pause=cycle_pause,
                                cycle_step=cycle_step,
                                exp_reset_active=exp_reset_active)

    cycle_control = ControllerCycleControl(spec=spec,
                                           clk=clk,
                                           reset=reset,
                                           start=cycle_start,
                                           pause=cycle_pause,
                                           step=cycle_step,
                                           cycle_autonomous=cycle_autonomous,
                                           cycle_count=ex_res_cycle_count_next,
                                           exp_clk_en=exp_clk_en)

    # RES stage instances
    res_compose = ControllerResponseCompose(spec=spec,
                                            opcode_res=ex_res_opcode_res_reg,
                                            addr=ex_res_addr_reg,
                                            data=exp_data_read,
                                            nop=ex_res_nop_reg,
                                            cycle_count=ex_res_cycle_count_reg,
                                            tx_ready=tx_ready,
                                            tx_next=tx_next,
                                            tx_msg=tx_msg)

    @always_seq(clk.posedge, reset)
    def pipeline_register_logic():
        ex_res_opcode_res_reg.next = ex_res_opcode_res_next
        ex_res_nop_reg.next = ex_res_nop_next
        ex_res_cycle_count_reg.next = ex_res_cycle_count_next
        ex_res_addr_reg.next = ex_res_addr_next

    @always_comb
    def pipeline_next_state_logic():
        ex_res_addr_next.next = cmd_addr

    @always_comb
    def experiment_setup_connections():
        exp_addr.next = cmd_addr
        exp_data_write.next = cmd_data

    @always_comb
    def split_cmd():
        cmd_opcode.next = cmd_message[spec.index_opcode_high +
                                      1:spec.index_opcode_low]
        cmd_addr.next = cmd_message[spec.index_addr_high +
                                    1:spec.index_addr_low]
        cmd_data.next = cmd_message[spec.index_data_high +
                                    1:spec.index_data_low]

    return (control, cycle_control, res_compose, split_cmd,
            experiment_setup_connections, pipeline_register_logic,
            pipeline_next_state_logic)
Example #34
0
def motor(clock, CS, SYNC, din, dout, SClk1, SClk2, reset):
    """
    clock: in std_logic; --spartan 6
    CS:    out st_logic
    din:   in std_logic  --ADC
    dout:  out std_logic --DAC
    SClk:  out std_logic --ADC
    SClk2: out std_logic --DAC

    function is documentated with Tutorial 15 - ADC's and DAC's
    on the Spartan 3E Starter Board
    """
    state_type = enum("IDLE", "READ", "FUNC", "WRITE")
    state = Signal(state_type.READ)
    data = Signal(intbv(0)[12:0])
    cnt = Signal(intbv(0, min=0, max=20))
    clkdiv = Signal(intbv(0, min=0, max=6))
    newclk = Signal(bool(0))

    @always_comb
    def sync_clocks():
        SClk1.next = newclk
        SClk2.next = newclk

    @always_seq(clock.posedge, reset)
    def FSM():
        if clkdiv == 5 and newclk == 1:
            if state == state_type.IDLE:
                CS.next = 1
                SYNC.next = 1
                if cnt == 15:
                    cnt.next = 0
                    state.next = state_type.READ
                else:
                    cnt.next = cnt + 1
                    state.next = state_type.IDLE
            elif state == state_type.READ:
                CS.next = 0
                SYNC.next = 1
                cnt.next = cnt + 1
                if cnt < 4:
                    cnt.next = cnt + 1
                    state.next = state_type.READ
                elif cnt > 3 and cnt < 16:
                    cnt.next = cnt + 1
                    data.next[15-cnt] = din
                    state.next = state_type.READ
                elif cnt == 16:
                    cnt.next = 0
                    state.next = state_type.FUNC
            elif state == state_type.FUNC:
                CS.next = 1
                SYNC.next = 1
                cnt.next = 0
                # NOTE: different operation than example
                data.next = (data.max-1)-data
                state.next = state_type.WRITE
            elif state == state_type.WRITE:
                CS.next = 1
                SYNC.next = 0
                if cnt < 4:
                    cnt.next = cnt + 1
                    dout.next = 0
                    state.next = state_type.WRITE
                elif cnt > 3 and cnt < 16:
                    cnt.next = cnt + 1
                    dout.next = data[15-cnt]
                    state.next = state_type.WRITE
                elif cnt == 16:
                    cnt.next = 0
                    state.next = state_type.IDLE

            else:
                raise ValueError("Undefined State")

    @always_seq(clock.posedge, reset)
    def clock_divider():
        if clkdiv == 5:
            # a.next = not a equals a.next = a^1
            newclk.next = not newclk
            clkdiv.next = 0
        else:
            clkdiv.next = clkdiv + 1
    return instances()
Example #35
0
        def shifter():
            if slave.ACK_O or slave.ERR_O:
                if rd:
                    data.next = slave.DAT_O
                addr.next = addr + 1

                rd.next = 0
                wr.next = 0

            elif slave.RTY_O:
                # Leave rd/wr as is and retry
                pass

            if not spi.CS:
                addr_mode.next = 1
                r_w.next = 0
                bit.next = 0
                oe.next = 0

            else:
                if spi.SCK and not last_sck:
                    if r_w:
                        spi.SD_O.next = data[self.data_width - bit - 1]
                        oe.next = 1

                        if bit == self.data_width - 1:
                            bit.next = 0
                            rd.next = 1

                        else:
                            bit.next = bit + 1

                elif not spi.SCK and last_sck:
                    if addr_mode:
                        data.next[self.addr_width - bit - 1] = spi.SD_I

                        if bit == self.addr_width - 1:
                            bit.next = 0

                            addr_mode.next = 0
                            addr.next = data[len(addr):1]

                            if spi.SD_I:
                                rd.next = 1
                                r_w.next = 1
                                data.next = intbv(~0)[len(data):]
                            else:
                                r_w.next = 0

                        else:
                            bit.next = bit + 1

                    elif not r_w:
                        data.next[self.data_width - bit - 1] = spi.SD_I

                        if bit == self.data_width - 1:
                            bit.next = 0
                            wr.next = 1

                        else:
                            bit.next = bit + 1

            last_sck.next = spi.SCK
 def add():
     increament = intbv(4, -1024, 1024)
     result.next = PC + increament
Example #37
0
    def gen(self, spi, slave):
        if self.addr_width is None:
            self.addr_width = len(slave.ADR_I)
            # one extra bit for the direction bit
            self.addr_width += 1
            # round up to a byte
            self.addr_width = (self.addr_width + 7) & ~7

        if self.data_width is None:
            self.data_width = max(len(slave.DAT_I), len(slave.DAT_O))
            # round up to a byte
            self.data_width = (self.data_width + 7) & ~7

        width = max(self.addr_width, self.data_width)

        print "SpiSlave", self.addr_width, self.data_width, width

        addr = Signal(intbv(0)[len(slave.ADR_I):])

        bit = Signal(intbv(0, 0, width))
        data = Signal(intbv(0)[width:])

        rd = Signal(False)
        wr = Signal(False)

        addr_mode = Signal(False)
        r_w = Signal(False)

        last_sck = Signal(False)

        oe = Signal(False)

        @always_comb
        def comb():
            slave.CYC_I.next = 0
            slave.STB_I.next = 0
            slave.WE_I.next = 0
            slave.ADR_I.next = 0
            slave.DAT_I.next = 0
            slave.SEL_I.next = intbv(~0)[len(slave.SEL_I):]

            if rd or wr:
                slave.CYC_I.next = 1
                slave.STB_I.next = 1
                slave.ADR_I.next = addr

                if wr:
                    slave.WE_I.next = 1
                    slave.DAT_I.next = data

            spi.SD_OE.next = oe and spi.CS

        @always_seq(slave.CLK_I.posedge, slave.RST_I)
        def shifter():
            if slave.ACK_O or slave.ERR_O:
                if rd:
                    data.next = slave.DAT_O
                addr.next = addr + 1

                rd.next = 0
                wr.next = 0

            elif slave.RTY_O:
                # Leave rd/wr as is and retry
                pass

            if not spi.CS:
                addr_mode.next = 1
                r_w.next = 0
                bit.next = 0
                oe.next = 0

            else:
                if spi.SCK and not last_sck:
                    if r_w:
                        spi.SD_O.next = data[self.data_width - bit - 1]
                        oe.next = 1

                        if bit == self.data_width - 1:
                            bit.next = 0
                            rd.next = 1

                        else:
                            bit.next = bit + 1

                elif not spi.SCK and last_sck:
                    if addr_mode:
                        data.next[self.addr_width - bit - 1] = spi.SD_I

                        if bit == self.addr_width - 1:
                            bit.next = 0

                            addr_mode.next = 0
                            addr.next = data[len(addr):1]

                            if spi.SD_I:
                                rd.next = 1
                                r_w.next = 1
                                data.next = intbv(~0)[len(data):]
                            else:
                                r_w.next = 0

                        else:
                            bit.next = bit + 1

                    elif not r_w:
                        data.next[self.data_width - bit - 1] = spi.SD_I

                        if bit == self.data_width - 1:
                            bit.next = 0
                            wr.next = 1

                        else:
                            bit.next = bit + 1

            last_sck.next = spi.SCK

        return (comb, shifter)
Example #38
0
class Mojo(FPGA):
    vendor = 'xilinx'
    family = 'spartan6'
    device = 'XC6SLX9'
    package = 'TQG144'
    speed = '-2'
    version = 3
    _name = 'mojov'
    no_startup_jtag_clock = True

    default_clocks = {
        # clk in documentation (?)
        'clock': dict(frequency=50e6, pins=(56, ), iostandard='LVTTL')
    }

    default_resets = {
        # rst_n in documentation
        'reset': dict(active=0, isasync=True, pins=(38, ), iostandard='LVTTL')
    }

    default_ports = {
        # on-board led
        'led':
        dict(pins=(
            134,
            133,
            132,
            131,
            127,
            126,
            124,
            123,
        ),
             iostandard='LVTTL'),
        'cclk':
        dict(pins=(70, ), iostandard='LVTTL'),
        'spi_mosi':
        dict(pins=(44, ), iostandard='LVTTL'),
        'spi_miso':
        dict(pins=(45, ), iostandard='LVTTL'),
        'spi_ss':
        dict(pins=(48, ), iostandard='LVTTL'),
        'spi_sck':
        dict(pins=(43, ), iostandard='LVTTL'),
        'spi_channel':
        dict(pins=(
            46,
            61,
            62,
            65,
        ),
             sigtype=TristateSignal(intbv(0)[4:]),
             iostandard='LVTTL'),
        'avr_tx':
        dict(pins=(55, ), iostandard='LVTTL'),
        'avr_rx':
        dict(pins=(59, ), iostandard='LVTTL'),
        'avr_tx_busy':
        dict(pins=(39, ), iostandard='LVTTL'),
    }

    def get_flow(self, top=None):
        return ISE(brd=self, top=top)