class ST: def __init__(self): ol = Overlay("SCS_ST_TEST_wrapper.bit", 0) ol.download() self.DATA = MMIO(0x41200000, 0x10000) self.UTIL = MMIO(0x41210000, 0x10000) def wait_for_rdy(self): while (self.DATA.read(0x8) & 0b1) == 0: pass def read_time(self): ctime = self.DATA.read(0x0) / REF_CLK delvals = self.DATA.read(0x8) ctime = ctime + (((delvals & 0b111111110) >> 1) - ((delvals & 0b11111111000000000) >> 9)) * FTIME return ctime def uencode(self, val, length): cnt = 0 for i in range(length): if ((val >> i) & 0b1 == 1): cnt += 1 return cnt def read_proc(self): self.UTIL.write(0x0, 0x1) self.wait_for_rdy() timev = self.read_time() self.UTIL.write(0x0, 0x0) return timev
class ST: def __init__(self): ol = Overlay("TEST_wrapper.bit", 0) ol.download() self.DATA = MMIO(0x41200000, 0x10000) self.UTIL = MMIO(0x41210000, 0x10000) self.DEBUG = MMIO(0x41220000, 0x10000) def wait_for_rdy(self): while (self.UTIL.read(0x8)) == 0: pass def read_time(self): ctime = self.DATA.read(0x0) / REF_CLK finetimevalues = self.DATA.read(0x8) ftime0 = finetimevalues & 0xFF ftime1 = (finetimevalues & 0xFF00) >> 8 log.debug("FTIME0 -- " + bin(ftime0)) log.debug("FTIME1 -- " + bin(ftime1)) return ctime + (ftime0 - ftime1) * FTIME def read_proc(self): self.UTIL.write(0x0, 0x1) self.wait_for_rdy() timev = self.read_time() self.read_debug() self.UTIL.write(0x0, 0x0) return timev def read_debug(self): pt1 = self.DEBUG.read(0x0) lt1 = self.DEBUG.read(0x8) log.debug("CURRENT VECTOR -- " + format((lt1 << 4) | pt1, '#010b'))
class Coincidence_Timer: def __init__(self, mode): if mode == 0: self.PC_OV = Overlay("TDC/TDC_OVERLAY_wrapper.bit", 0) print("Loaded two channel coincidence rising edge TDC") elif mode == 1: self.PC_OV = Overlay("TDC/SC_TDC_OVERLAY.bit", 0) print("Loaded single channel inter rising edge TDC") else: print("What?") self.PC_OV = Overlay("TDC/TDC_OVERLAY_wrapper.bit", 0) print("Loaded two channel coincidence rising edge TDC") self.PC_OV.download() self.GPIO = MMIO(it_a_gpio_addr, axi_gpio_range) self.GPIO_INT = MMIO(it_a_gpioi_addr, axi_gpio_range) self.GPIO.write(ch1_dir, 0xFFFFFFFF) self.GPIO.write(ch2_dir, 0x0) self.GPIO_INT.write(ch1_dir, 0xFFFFFFFF) self.GPIO.write(ch2_data, 0x0) #Hold system in reset for now def arm_and_wait(self): self.GPIO.write(ch2_data, 0x1) op = 0 while (self.GPIO_INT.read(ch1_data) == 0x0): pass if (self.GPIO_INT.read(ch1_data) == 0x1): op = self.GPIO.read(ch1_data) self.GPIO.write(ch2_data, 0x0) return op def tval_to_time(self, tval): return tval * (1 / 450000000)
class ST: def __init__(self): self.ov = Overlay("TEST_wrapper.bit", 0) self.ov.download() self.DATA = MMIO(0x41200000, 0x10000) self.UTIL = MMIO(0x41210000, 0x10000) self.DELAY0 = MMIO(0x41220000, 0x10000) self.DELAY1 = MMIO(0x41230000, 0x10000) self.DEBUG = MMIO(0x41240000, 0x10000) self.DUTIL = MMIO(0x41250000, 0x10000) log.info("Ready") def wait_for_rdy(self): while (self.UTIL.read(0x8) == 0): pass def read_time(self): course_time = self.DATA.read(0x0) log.debug("CT: " + str(course_time)) finetimes = self.DATA.read(0x8) preftime = finetimes & 0xFF postftime = (finetimes & 0xFF00) >> 8 log.debug("PRE: " + str(preftime)) log.debug("POST: " + str(postftime)) timetoconv = preftime - postftime timetoconv *= FTIME time = course_time / COURSE_CLK + timetoconv return time def proc(self): self.DUTIL.write(0x0, 0x1) sleep(0.1) self.UTIL.write(0x0, 0x1) self.wait_for_rdy() self.read_debug() time = self.read_time() log.info("TIME: " + str(time * 1e9)) self.UTIL.write(0x0, 0x0) self.DUTIL.write(0x0, 0x0) return time def set_delays(self, dels): #self.DUTIL.write(0x0,0x1) self.DELAY0.write(0x0, int(dels[0])) self.DELAY0.write(0x8, int(dels[1])) self.DELAY1.write(0x0, int(dels[2])) self.DELAY1.write(0x8, int(dels[3])) #self.DUTIL.write(0x0,0x1) def read_debug(self): staten = self.DEBUG.read(0x0) for i in range(8): mask = 0xF log.debug("STATEN" + str(i) + ": " + format((staten >> (4 * i)) & mask, '#006b')) log.debug("STATENFULL: " + bin(staten)) log.debug("STATEL: " + bin(self.DEBUG.read(0x8)))
class PulseGen(): def __init__(self, GPIO_ADDRESS, GPIO_RANGE, DMA_ADDRESS, DMA_RANGE): self.gpio = MMIO(GPIO_ADDRESS, GPIO_RANGE) self.dma = MMIO(DMA_ADDRESS, DMA_RANGE) self.gpioDataOut = 0 return def setResetn(self, val): mask = 0b11111111111111111111111110 self.gpioDataOut = (self.gpioDataOut & mask) | (val << 0) self.gpio.write(0, self.gpioDataOut) return def setTrig(self, val): mask = 0b11111111111111111111111101 self.gpioDataOut = (self.gpioDataOut & mask) | (val << 1) self.gpio.write(0, self.gpioDataOut) return def setPulseWidth(self, val): mask = 0b00000000000000000000000011 self.gpioDataOut = (self.gpioDataOut & mask) | (val << 2) self.gpio.write(0, self.gpioDataOut) return def getState(self): return self.gpio.read(0x0008) & 0b111 def getStreamDownCounter(self): return (self.gpio.read(0x0008) >> 3) def dmaMM2SIsIdle(self): isIdle = bool(self.dma.read(0x4) & (1 << 1)) return isIdle def dmaMM2SConfig(self, bufferAddress): self.dma.write(0x18, bufferAddress) return def dmaMM2SRun(self, bufferBytesLen): self.dma.write(0x28, bufferBytesLen) return def dmaMM2SReset(self): self.dma.write(0x0, (1 << 2)) return def dmaMM2SHalt(self): self.dma.write(0x0, 0) return def dmaMM2SStart(self): self.dma.write(0x0, 1) return
class BmeDriver(HlsCore): """These define the 'reg' argument to the 'ctrlloop' HLS function. The memory space defined here is shared between the HLS core and the ARM PS. """ __IO_REG_OFF = 0x200 __IO_REG_LEN = 0x100 def __init__(self, description): super().__init__(description) self.__hls_reg = MMIO(self.mmio.base_addr + self.__IO_REG_OFF, self.__IO_REG_LEN) bindto = ['UCSD:hlsip:bmeDriver:1.0'] def launch(self): """ Start and detatch computation on the io HLS core Returns ------- Nothing """ self._launch() return def land(self): """ Re-Connect and Terminate Computation on the io HLS core Returns ------- The 4-bit value representing the value of the buttons. """ self._land() return self.__hls_reg.read(0) def run(self): """ Launch computation on the io HLS core Returns ------- The 4-bit value representing the value of the buttons. """ self._run() return self.__hls_reg.read(0)
class PulseAcq(): def __init__(self, GPIO_ADDRESS, GPIO_RANGE, DMA_ADDRESS, DMA_RANGE): self.gpio = MMIO(GPIO_ADDRESS, GPIO_RANGE) self.dma = MMIO(DMA_ADDRESS, DMA_RANGE) self.gpioDataOut = 0 return def setResetn(self, val): mask = 0b1111111111111111111111110 self.gpioDataOut = (self.gpioDataOut & mask) | (val << 0) self.gpio.write(0, self.gpioDataOut) return def setCounterMax(self, val): mask = 0b0000000000000000000000001 self.gpioDataOut = (self.gpioDataOut & mask) | (val << 1) self.gpio.write(0, self.gpioDataOut) return def getState(self): return self.gpio.read(0x0008) & 0b111 def getStreamUpCounter(self): return (self.gpio.read(0x0008) >> 3) def dmaS2MMIsIdle(self): isIdle = bool(self.dma.read(0x34) & (1 << 1)) return isIdle def dmaS2MMConfig(self, bufferAddress): self.dma.write(0x48, bufferAddress) return def dmaS2MMRun(self, bufferBytesLen): self.dma.write(0x58, bufferBytesLen) return def dmaS2MMReset(self): self.dma.write(0x30, (1 << 2)) return def dmaS2MMHalt(self): self.dma.write(0x30, 0) return def dmaS2MMStart(self): self.dma.write(0x30, 1) return
def execute_hardware(plan): dma = [] hw_switch.reset() ret_dma_base = PL.ip_dict[metadata.DMA_names[0]]["phys_addr"] ret_dma_mmio = MMIO(ret_dma_base, 256) ret_dma = overlay.axi_dma_0 ret_buf = xlnk.cma_array((8388607, ), dtype=np.uint8) prepare_execution(plan, dma, metadata.DMA[0][0][0]) hw_switch.commit() ## Timer Start start_time = time.process_time() ret_dma.recvchannel.start() ret_dma.recvchannel.transfer(ret_buf) for d in dma: d.transfer() for d in dma: d.wait() ## Timer End end_time = time.process_time() print("Elapsed Test Time: ", end_time - start_time) ret_dma.recvchannel.wait() bytes_read = ret_dma_mmio.read(0x58) view = np.frombuffer(ret_buf, np.uint8, count=bytes_read).copy() view.dtype = plan.dtype print(view.shape) ret_buf.freebuffer() return view
def execute_hardware(plan): dma = [] hw_switch.reset() ret_dma_base = int( PL.ip_dict["SEG_{0}_Reg".format(metadata.DMA_names[0])][0], 16) ret_dma_mmio = MMIO(ret_dma_base, 256) ret_dma = DMA(ret_dma_base, 1) ret_dma.create_buf(8388607) prepare_execution(plan, dma, metadata.DMA[0][0][0]) hw_switch.commit() ## Timer Start start_time = time.process_time() ret_dma.transfer(8388607, 1) for d in dma: d.transfer() for d in dma: d.wait() ## Timer End end_time = time.process_time() print("Elapsed Test Time: ", end_time - start_time) ret_dma.wait() bytes_read = ret_dma_mmio.read(0x58) ffi = pynq.drivers.dma.ffi buf = ffi.buffer(ret_dma.buf, bytes_read) view = np.frombuffer(buf, plan.dtype, -1).copy() return view
class CT: def __init__(self): #ol = Overlay("TEST_wrapper.bit",0) #ol.download() self.DATA = MMIO(0x43d40000, 0x10000) self.UTIL = MMIO(0x43d50000, 0x10000) pass def wait_for_rdy(self): while (self.UTIL.read(0x8) == 0): pass def read_time(self): coarse_time = self.DATA.read(0x0) / REF_CLK finetimeconcat = self.DATA.read(0x8) ftime0 = finetimeconcat & 0xFF ftime1 = (finetimeconcat & 0xFF00) >> 8 return coarse_time + (ftime0 - ftime1) * FTIME def line_select(self, sel): if (sel == LineSelectMode.DONTCARE): self.UTIL.write(0x0, self.UTIL.read(0x0) | 0b100) else: self.UTIL.write(0x0, self.UTIL.read(0x0) & 0b001) self.UTIL.write(0x0, self.UTIL.read(0x0) | (sel << 1)) def read_proc(self): self.UTIL.write(0x0, self.UTIL.read(0x0) | 0b1) self.wait_for_rdy() val = self.read_time() self.UTIL.write(0x0, self.UTIL.read(0x0) & 0b110) return val
class clock_gen: def __init__(self): self.PC_OV = Overlay("TDC/PG_OV_wrapper.bit", 0) self.PC_OV.download() self.CLK_WIZ = MMIO(BASE_ADDR, 0x10000) self.CLK_WIZ.write(CCON0, 0xA01) self.CLK_WIZ.write(CCON2, 0x5) while (self.CLK_WIZ.read(SR) == 0): pass self.CLK_WIZ.write(CCON23, 0x3)
def test_mmio(): """Test whether MMIO class is working properly. Generate random tests to swipe through the entire range: >>> mmio.write(all offsets, random data) Steps: 1. Initialize an instance with length in bytes 2. Write an integer to a given offset. 3. Write a number within the range [0, 2^32-1] into a 4-byte location. 4. Change to the next offset and repeat. """ mmio_base = mmio_range = None for ip in PL.ip_dict: if PL.ip_dict[ip]['type'] == "xilinx.com:ip:axi_bram_ctrl:4.0": mmio_base = PL.ip_dict[ip]['phys_addr'] mmio_range = PL.ip_dict[ip]['addr_range'] break if mmio_base is not None and mmio_range is not None: mmio = MMIO(mmio_base, mmio_range) for offset in range(0, min(100, mmio_range), 4): data1 = randint(0, pow(2, 32) - 1) mmio.write(offset, data1) sleep(0.1) data2 = mmio.read(offset) assert data1 == data2, \ 'MMIO read back a wrong random value at offset {}.'.format( offset) mmio.write(offset, 0) sleep(0.1) assert mmio.read(offset) == 0, \ 'MMIO read back a wrong fixed value at offset {}.'.format( offset) else: raise RuntimeError("No testable IP for MMIO class.")
def test_mmio(): """Test whether MMIO class is working properly. Generate random tests to swipe through the entire range: >>> mmio.write(all offsets, random data) Steps: 1. Initialize an instance with length in bytes 2. Write an integer to a given offset. 3. Write a number within the range [0, 2^32-1] into a 4-byte location. 4. Change to the next offset and repeat. """ ol = Overlay('base.bit') ol.download() sleep(0.2) mmio_base = int(ol.get_ip_addr_base('SEG_mb_bram_ctrl_1_Mem0'),16) mmio_range = int(ol.get_ip_addr_range('SEG_mb_bram_ctrl_1_Mem0'),16) mmio = MMIO(mmio_base, mmio_range) for offset in range(0, 100, general_const.MMIO_WORD_LENGTH): data1 = randint(0, pow(2,32)-1) mmio.write(offset, data1) sleep(0.02) data2 = mmio.read(offset) assert data1==data2, \ 'MMIO read back a wrong random value at offset {}.'.format(offset) mmio.write(offset, 0) sleep(0.02) assert mmio.read(offset)==0, \ 'MMIO read back a wrong fixed value at offset {}.'.format(offset) del ol
def test_mmio(): """Test whether MMIO class is working properly. Generate random tests to swipe through the entire range: >>> mmio.write(all offsets, random data) Steps: 1. Initialize an instance with length in bytes 2. Write an integer to a given offset. 3. Write a number within the range [0, 2^32-1] into a 4-byte location. 4. Change to the next offset and repeat. """ ol = Overlay('base.bit') ol.download() sleep(0.2) mmio_base = ol.ip_dict['SEG_mb_bram_ctrl_1_Mem0'][0] mmio_range = ol.ip_dict['SEG_mb_bram_ctrl_1_Mem0'][1] mmio = MMIO(mmio_base, mmio_range) for offset in range(0, 100, general_const.MMIO_WORD_LENGTH): data1 = randint(0, pow(2,32)-1) mmio.write(offset, data1) sleep(0.02) data2 = mmio.read(offset) assert data1==data2, \ 'MMIO read back a wrong random value at offset {}.'.format(offset) mmio.write(offset, 0) sleep(0.02) assert mmio.read(offset)==0, \ 'MMIO read back a wrong fixed value at offset {}.'.format(offset) del ol
class Miner(object): IP_NAME = "bitcoin_miner_ip_0" def __init__(self, bitstream_path): ol = Overlay(bitstream_path) ol.download() phys_addr = PL.ip_dict[self.IP_NAME]['phys_addr'] addr_range = PL.ip_dict[self.IP_NAME]['addr_range'] self._mmio = MMIO(phys_addr, addr_range) def write_words(self, offset, data): for pos in range(0, len(data), 4): d = int.from_bytes(data[pos:pos+4], byteorder='big') self._mmio.write(offset + pos, d) def write_first_block_hash(self, hash): self.write_words(0x00, hash) def write_second_block(self, block): self.write_words(0x20, block) def write_target(self, target): self.write_words(0x30, target) def start(self): self._mmio.write(0x54,0x01) self._mmio.write(0x54,0x00) def wait_stop(self): while self._mmio.read(0x54) & 0x01: pass def is_found(self): return bool(self._mmio.read(0x54) & 0x02) def read_nonce(self): return self._mmio.read(0x58)
class GPIOModulesCTL: def __init__(self): self.overlay = Overlay("SerDesTestOverlay/design_1_wrapper.bit", 0) self.overlay.download() #Multicolor LEDs self.axi_gpio_0_h = MMIO(axi_gpio_0_addr, axi_gpio_range) self.axi_gpio_0_h.write(0x4, 0x0) self.axi_gpio_0_h.write(0x0, 0x0) #SelectIO Interface self.axi_gpio_1_h = MMIO(axi_gpio_1_addr, axi_gpio_range) self.axi_gpio_1_h.write(0x4, 0xFFFFFFFF) #PLL lock indicators self.axi_gpio_2_h = MMIO(axi_gpio_2_addr, axi_gpio_range) self.axi_gpio_2_h.write(0x4, 0xFFFFFFFF) def gpio_0_write(self, val): self.axi_gpio_0_h.write(0x0, val) def gpio_1_read(self): return self.axi_gpio_1_h.read(0x0) def gpio_2_read(self): return self.axi_gpio_2_h.read(0x0)
def continuous_capture(capture_count): mmio_stream = MMIO(capture_address, 256) cap_list = [([]) for i in range(4)] for _ in range(capture_count): motor.stream_capture(capture_address) for i in range(4, 260, 4): stream = mmio_stream.read(i - 4, 4) highbits, lowbits = bytesplit(stream) if (i % 8 != 0): cap_list[0].extend([(np.int16(lowbits))]) cap_list[1].extend([(np.int16(highbits))]) else: cap_list[2].extend([(np.int16(lowbits))]) cap_list[3].extend([(np.int16(highbits))]) return cap_list
class SCH: def __init__(self): ol = Overlay("DDR_SCH_TEST_wrapper.bit",0) ol.download() self.DATA = MMIO(0x41200000,0x10000) self.UTIL = MMIO(0x41210000,0x10000) self.UTIL.write(0x0,0x0) def wait_for_rdy(self): while((0b001&self.DATA.read(0x8))==0): pass def read_time(self): ctime = self.DATA.read(0x0) ctime = ctime * (1/CLK_FREQ) sstate = (self.DATA.read(0x8)&0b10)>>1 estate = (self.DATA.read(0x8)&0b100)>>2 ctime += estate * (0.5/CLK_FREQ) ctime -= sstate * (0.5/CLK_FREQ) return ctime def read_proc(self): self.UTIL.write(0x0,0x1) self.wait_for_rdy() val = self.read_time() self.UTIL.write(0x0,0x0) return val
class CT: def __init__(self): ol = Overlay("DDR_CT_TEST_OV_wrapper.bit", 0) ol.download() self.DATA = MMIO(0x41200000, 0x10000) self.UTIL = MMIO(0x41210000, 0x10000) self.DEBUG = MMIO(0x41220000, 0x10000) self.UTIL.write(0x0, 0x0) self.UTIL.write(0x8, 0b0) def wait_for_rdy(self): while ((0b0001 & self.DATA.read(0x8)) == 0): #print("aDRDY: " + bin(self.DATA.read(0x8) & 0b0001)) pass def read_time(self): ctime = self.DATA.read(0x0) ctime = ctime / REF_CLK sstate = (self.DATA.read(0x8) & 0b10) >> 1 estate = (self.DATA.read(0x8) & 0b100) >> 2 ctime += estate / (2 * REF_CLK) ctime -= sstate / (2 * REF_CLK) return ctime def ct_proc(self): self.UTIL.write(0x0, 0x1) print("pDRDY: " + bin(self.DATA.read(0x8) & 0b0001)) self.wait_for_rdy() print("aDRDY: " + bin(self.DATA.read(0x8) & 0b0001)) val = self.read_time() self.read_debug() print("Inval: " + str(self.read_inval())) self.UTIL.write(0x0, 0x0) return val def read_inval(self): return (self.DATA.read(0x8) & 0b1000) >> 3 def read_debug(self): print("DDR: " + bin(self.DEBUG.read(0x0))) print("LDDR: " + bin(self.DEBUG.read(0x8)))
def shutdown(self): """Shutdown the AXI connections to the PL in preparation for reconfiguration """ from pynq import MMIO ip = self.ip_dict for name, details in ip.items(): if details['type'] == 'xilinx.com:ip:pr_axi_shutdown_manager:1.0': mmio = MMIO(details['phys_addr'], device=self) # Request shutdown mmio.write(0x0, 0x1) i = 0 while mmio.read(0x0) != 0x0F and i < 16000: i += 1 if i >= 16000: warnings.warn("Timeout for shutdown manager. It's likely " "the configured bitstream and metadata " "don't match.")
class TT: def __init__(self): ol = Overlay("TEST_wrapper.bit",0) ol.download() self.DELAY = MMIO(0x41200000,0x10000) self.CTIME0 = MMIO(0x41210000,0x10000) self.CTIME1 = MMIO(0x41220000,0x10000) self.O_UTIL = MMIO(0x41230000,0x10000) self.I_UTIL = MMIO(0x41240000,0x10000) def set_timeout(self,seconds): self.O_UTIL.write(0x0,int(seconds*REF_CLK)) def start(self): self.O_UTIL.write(0x8,0x1) def stop(self): self.O_UTIL.write(0x8,0x0) def read_drdy(self): return self.I_UTIL.read(0x0) def wait_for_rdy(self): if((self.read_drdy())==1): while((self.read_drdy())==1): pass else: while (self.read_drdy() == 0): pass def read_timeouts(self): return self.I_UTIL.read(0x8) def read_times(self): T1 = self.CTIME0.read(0x0)/REF_CLK T2 = self.CTIME0.read(0x8)/REF_CLK T3 = self.CTIME1.read(0x0) / REF_CLK T4 = self.CTIME1.read(0x8) / REF_CLK DELAY = self.DELAY.read(0x0) D0 = self.DELAY.read(0x8)*FTIME D1 = (DELAY&0xFF)*FTIME D2 = ((DELAY&0xFF00)>>8)*FTIME D3 = ((DELAY & 0xFF0000) >> 16)*FTIME D4 = ((DELAY & 0xFF000000) >> 24)*FTIME return [D0-D1 + T1,D0-D2 + T2,D0-D3 + T3,D0-D4 + T4] def proc(self): self.wait_for_rdy() times = self.read_times() timeouts = self.read_timeouts() print("T1 (ns): " + str(times[0] * 1e9)) print("T2 (ns): " + str(times[1] * 1e9)) print("T3 (ns): " + str(times[2] * 1e9)) print("T4 (ns): " + str(times[3] * 1e9)) print("TIMEOUTS: " + bin(timeouts)) return times
class PynqMicroblaze: """This class controls the active Microblaze instances in the system. Attributes ---------- ip_name : str The name of the IP corresponding to the Microblaze. rst_name : str The name of the reset pin for the Microblaze. mb_program : str The absolute path of the Microblaze program. state : str The status (IDLE, RUNNING, or STOPPED) of the Microblaze. reset_pin : GPIO The reset pin associated with the Microblaze. mmio : MMIO The MMIO instance associated with the Microblaze. interrupt : Event An asyncio.Event-like class for waiting on and clearing interrupts. """ def __init__(self, mb_info, mb_program, force=False): """Create a new Microblaze object. It looks for active instances on the same Microblaze, and prevents users from silently reloading the Microblaze program. Users are notified with an exception if a program is already running on the selected Microblaze, to prevent unwanted behavior. Two cases: 1. No previous Microblaze program loaded in the system, or users want to request another instance using the same program. No exception will be raised in this case. 2. There is a previous Microblaze program loaded in the system. Users want to request another instance with a different program. An exception will be raised. Note ---- When a Microblaze program is already loaded in the system, and users want to instantiate another object using a different Microblaze program, users are in danger of losing existing objects. Parameters ---------- mb_info : dict A dictionary storing Microblaze information, such as the IP name and the reset name. mb_program : str The Microblaze program loaded for the processor. Raises ------ RuntimeError When another Microblaze program is already loaded. Examples -------- The `mb_info` is a dictionary storing Microblaze information: >>> mb_info = {'ip_name': 'mb_bram_ctrl_1', 'rst_name': 'mb_reset_1', 'intr_pin_name': 'iop1/dff_en_reset_0/q', 'intr_ack_name': 'mb_1_intr_ack'} """ ip_dict = PL.ip_dict gpio_dict = PL.gpio_dict intr_dict = PL.interrupt_pins # Check program path if not os.path.isfile(mb_program): raise ValueError('{} does not exist.'.format(mb_program)) # Get IP information ip_name = mb_info['ip_name'] if ip_name not in ip_dict.keys(): raise ValueError("No such IP {}.".format(ip_name)) addr_base = ip_dict[ip_name]['phys_addr'] addr_range = ip_dict[ip_name]['addr_range'] ip_state = ip_dict[ip_name]['state'] # Get reset information rst_name = mb_info['rst_name'] if rst_name not in gpio_dict.keys(): raise ValueError("No such reset pin {}.".format(rst_name)) gpio_uix = gpio_dict[rst_name]['index'] # Get interrupt pin information if 'intr_pin_name' in mb_info: intr_pin_name = mb_info['intr_pin_name'] if intr_pin_name not in intr_dict.keys(): raise ValueError( "No such interrupt pin {}.".format(intr_pin_name)) else: intr_pin_name = None # Get interrupt ACK information if 'intr_ack_name' in mb_info: intr_ack_name = mb_info['intr_ack_name'] if intr_ack_name not in gpio_dict.keys(): raise ValueError( "No such interrupt ACK {}.".format(intr_ack_name)) intr_ack_gpio = gpio_dict[intr_ack_name]['index'] else: intr_ack_gpio = None # Set basic attributes self.ip_name = ip_name self.rst_name = rst_name self.mb_program = mb_program self.state = 'IDLE' self.reset_pin = GPIO(GPIO.get_gpio_pin(gpio_uix), "out") self.mmio = MMIO(addr_base, addr_range) # Check to see if Microblaze in user if (ip_state is not None) and (ip_state != mb_program): if force: self.reset() else: raise RuntimeError( 'Another program {} already running.'.format(ip_state)) # Set optional attributes if (intr_pin_name is not None) and (intr_ack_gpio is not None): self.interrupt = MBInterruptEvent(intr_pin_name, intr_ack_gpio) else: self.interrupt = None # Reset, program, and run self.program() def run(self): """Start the Microblaze to run program loaded. This method will update the status of the Microblaze. Returns ------- None """ self.state = 'RUNNING' self.reset_pin.write(0) def reset(self): """Reset the Microblaze to stop it from running. This method will update the status of the Microblaze. Returns ------- None """ self.state = 'STOPPED' self.reset_pin.write(1) def program(self): """This method programs the Microblaze. This method is called in __init__(); it can also be called after that. It uses the attribute `self.mb_program` to program the Microblaze. Returns ------- None """ self.reset() PL.load_ip_data(self.ip_name, self.mb_program) if self.interrupt: self.interrupt.clear() self.run() def write(self, offset, data): """This method write data into the shared memory of the Microblaze. Parameters ---------- offset : int The beginning offset where data are written into. data : int/list A list of 32b words to be written. Returns ------- None """ if type(data) is int: self.mmio.write(offset, data) elif type(data) is list: for i, word in enumerate(data): self.mmio.write(offset + 4 * i, word) else: raise ValueError('Type of write data has to be int or lists.') def read(self, offset, length=1): """This method reads data from the shared memory of Microblaze. Parameters ---------- offset : int The beginning offset where data are read from. length : int The number of data (32-bit int) to be read. Returns ------- int/list An int of a list of data read from the shared memory. """ if length == 1: return self.mmio.read(offset) elif length > 1: return [self.mmio.read(offset + 4 * i) for i in range(length)] else: raise ValueError('Length of read data has to be 1 or more.')
class SP_TOOLS: def __init__(self): self.OV = Overlay("Single_Photons/SP_OVERLAY.bit", 0) self.OV.download() ##Initialize pulse counter axi_offset = 0 #Initialize data channels self.PC_DAT = [] global axi_range for i in range(4): self.PC_DAT.append(MMIO(axi_base_addr + (i * axi_range), axi_range)) self.PC_DAT[i].write(ch1_dir, agpi) #ch1 is counts self.PC_DAT[i].write(ch2_dir, agpo) #Ch2 is window self.PC_DAT[i].write(ch2_data, 0xFFFFFFFF) #Initialize utility channels axi_offset = 4 self.PC_UTIL = [] for i in range(4): self.PC_UTIL.append( MMIO(axi_base_addr + ((i + axi_offset) * axi_range), axi_range)) self.PC_UTIL[i].write(ch1_dir, agpo) #Reset self.PC_UTIL[i].write(ch1_data, 0x0) #Hold in reset self.PC_UTIL[i].write(ch2_dir, agpi) #Ready #Initialize trigger controller self.T_UTIL = MMIO(0x41200000, 0x10000) self.T_UTIL.write(ch2_dir, 0x0) self.T_UTIL.write(ch2_data, 0x0) self.T_RDY_UTIL = MMIO(0x41210000, 0x10000) self.T_RDY_UTIL.write(ch1_dir, 0x1) ##Initialize single channel inter-rising_edge detection axi_offset = 8 self.ST_DAT = MMIO(axi_base_addr + axi_offset * axi_range, axi_range) self.ST_DAT.write(ch1_dir, agpi) self.ST_DAT.write(ch2_dir, agpo) self.ST_DAT.write(ch2_data, 0x0) #Hold in reset self.ST_RDY = MMIO(axi_base_addr + (axi_offset + 1) * axi_range, axi_range) self.ST_RDY.write(ch1_dir, agpi) ##Initialize interchannel coincidence timer axi_offset = 10 self.CT_DAT = MMIO(axi_base_addr + axi_offset * axi_range, axi_range) self.CT_DAT.write(ch1_dir, agpi) self.CT_DAT.write(ch2_dir, agpo) self.CT_DAT.write(ch2_data, 0x0) #Hold in reset self.CT_RDY = MMIO(axi_base_addr + (axi_offset + 1) * axi_range, axi_range) self.CT_RDY.write(ch1_dir, agpi) ##Initialize Pulse generator axi_offset = 12 iDC = 0.5 iFREQ = 440.0 ph0, ph1 = self.encode_phase_inc(iFREQ) iDCenc = self.calc_dc_lim(iFREQ, iDC) self.PG_PH = [] self.PG_AUX = [] self.chfreqs = [440.0, 440.0, 440.0, 440.0] self.chdcs = [0.5, 0.5, 0.5, 0.5] self.chdelays = [0, 0, 0, 0] for i in range(4): #Phase increments tap = MMIO(axi_base_addr + (axi_offset * axi_range), axi_range) tap.write(ch1_dir, agpo) tap.write(ch2_dir, agpo) tap.write(ch1_data, ph0) tap.write(ch2_data, ph1) self.PG_PH.append(tap) axi_offset += 1 self.chfreqs[i] = 440.0 for i in range(4): #Duty length and delay tdc = MMIO(axi_base_addr + (axi_offset * axi_range), axi_range) tdc.write(ch1_dir, agpo) tdc.write(ch1_data, iDCenc) tdc.write(ch2_dir, agpo) tdc.write(ch2_data, 0x0) self.PG_AUX.append(tdc) axi_offset += 1 self.chdcs[i] = 0.5 self.PG_UTIL = MMIO(0x43D40000, 0x10000) #increment load and master reset self.PG_UTIL.write(ch1_dir, agpo) self.PG_UTIL.write(ch2_dir, agpo) self.PG_UTIL.write(ch1_data, 0x0) #SEt loader to 0 self.PG_UTIL.write(ch2_data, 0x0) #Hold in reset #Routine to write initial phase increments self.PG_UTIL.write(ch2_data, 0x1) self.PG_UTIL.write(ch1_data, 0xF) sleep(slt) self.PG_UTIL.write(ch1_data, 0x0) #Channel enable controller self.T_UTIL.write(ch1_dir, 0x0) self.T_UTIL.write(ch1_data, 0xF) #SEt all channels to high impedance axi_offset += 1 self.pg_ch_stat = 0xF #self.PG_UTIL.write(ch2_data,0x0) ##Initialize Time Tagger #initialize detector MMIOs self.TT_DET = [] for i in range(4): temp = MMIO(axi_base_addr + (axi_offset * axi_range), axi_range) temp.write(ch1_dir, 0xFFFFFFFF) temp.write(ch2_dir, 0xFFFFFFFF) self.TT_DET.append(temp) axi_offset += 1 #Initialize timeout MMIO self.TT_TIME_OUT = MMIO(axi_base_addr + (axi_offset * axi_range), axi_range) self.TT_TIME_OUT.write(ch1_dir, 0x0) self.TT_TIME_OUT.write(ch2_dir, 0x0) self.TT_TIME_OUT.write(ch1_data, 0xFFFFFFFF) self.TT_TIME_OUT.write(ch2_data, 0xFFFF) axi_offset += 1 #Initialize utility print(hex(axi_base_addr + (axi_offset * axi_range))) print(hex(axi_range)) self.TT_UTIL = MMIO(axi_base_addr + (axi_offset * axi_range), axi_range) self.TT_UTIL.write(ch1_dir, 0x0) self.TT_UTIL.write(ch2_dir, 0xFFFFFFFF) self.TT_UTIL.write(ch1_data, 0x0) #Hold system in reset axi_offset += 1 ##Initialize IDELAY self.iDD_DATA = [] self.iDD_UTIL = [] for i in range(6): tempdel = MMIO(axi_base_addr + (axi_offset * axi_range), axi_range) tempdel.write(ch1_data, 0x0) tempdel.write(ch2_data, 0x0) self.iDD_DATA.append(tempdel) axi_offset += 1 for i in range(6): temputil = MMIO(axi_base_addr + (axi_offset * axi_range), axi_range) temputil.write(ch1_data, 0x1) temputil.write(ch2_data, 0x1) self.iDD_UTIL.append((temputil)) axi_offset += 1 ####------------------PHOTON COUNTER---------------------------------------------------#### def pc_set_window( self, window, channels): #Channels is 4 bit integer, window is in seconds m = 0B0001 wval = int(window * TIMER_CLK) if (wval > 0xFFFFFFFF or wval <= 0): print( "Window must be between 34.35973836s and 0, cannot be 0 seconds" ) return for i in range(4): if ((0B0001 << i) & channels) != 0: self.PC_DAT[i].write(ch2_data, wval) def pc_wait_for_rdy(self, channel, mode): if mode == 0: if (self.PC_UTIL[channel].read(ch2_data) == 0): while (self.PC_UTIL[channel].read(ch2_data) == 0): pass else: while (self.PC_UTIL[channel].read(ch2_data) == 1): pass else: if (self.T_RDY_UTIL.read(ch1_data) == 0): while (self.T_RDY_UTIL.read(ch1_data) == 0): pass def pc_ex_triggered(self, window): self.pc_set_window(window, 0xF) self.T_UTIL.write(ch2_data, 0x1) self.pc_wait_for_rdy(0, 0) retval = [] for i in range(4): retval.append(self.pc_read_counts(i)) self.T_UTIL.write(ch2_data, 0x0) return retval def pc_ex_trig_stop(self): self.T_UTIL.write(ch2_data, 0x3) for i in range(4): self.PC_DAT[i].write(ch2_data, 0xFFFFFFFF) self.pc_wait_for_rdy(0, 1) retval = [] for i in range(4): retval.append(self.pc_read_counts(i)) self.T_UTIL.write(ch2_data, 0x0) return retval def pc_enable_channels(self, channels): #channels a 4 bit integer for i in range(4): if ((0B0001 << i) & channels) != 0: self.PC_UTIL[i].write(ch1_data, 0x1) def pc_disable_channels(self, channels): #Channels a 4 bit integer for i in range(4): if ((0B0001 << i) & channels) != 0: self.PC_UTIL[i].write(ch1_data, 0x0) def pc_read_counts(self, channel): return self.PC_DAT[channel].read(ch1_data) ####----------------------------------------------------------------------------------#### ####------------------Single line inter-rising_edge timer-----------------------------#### def st_arm_and_wait(self): self.ST_DAT.write(ch2_data, 0x1) #Enable op = 0 while (self.ST_RDY.read(ch1_data) == 0x0): #Wait for ready pass if (self.ST_RDY.read(ch1_data) == 0x1): op = self.ST_DAT.read(ch1_data) #Read time self.ST_DAT.write(ch2_data, 0x0) return op * (1 / REF_CLK) ####----------------------------------------------------------------------------------#### ####------------------Two channel photon coincidence timer----------------------------#### def ct_arm_and_wait(self): self.CT_DAT.write(ch2_data, 0x1) # Enable op = 0 #print("Armed") while (self.CT_RDY.read(ch1_data) == 0x0): # Wait for ready pass #print("Triggered") if (self.CT_RDY.read(ch1_data) == 0x1): #print("Reading") op = self.CT_DAT.read(ch1_data) # Read time self.CT_DAT.write(ch2_data, 0x0) return op * (1 / REF_CLK) ####---------------------Signal generator---------------------------------------------#### def pg_disable(self): self.PG_UTIL.write(ch2_data, 0x0) def pg_enable(self): self.PG_UTIL.write(ch2_data, 0x1) def pg_enable_channel(self, channel): self.pg_ch_stat = ~(~self.pg_ch_stat | (0B0001 << channel)) self.T_UTIL.write(ch1_data, self.pg_ch_stat) def pg_disable_channel(self, channel): self.pg_ch_stat = self.pg_ch_stat | (0b0001 << channel) self.T_UTIL.write(ch1_data, self.pg_ch_stat) def pg_set_channel_freq(self, channel, freq): nenc = self.encode_phase_inc(2 * freq) self.PG_PH[channel].write(ch1_data, nenc[0]) self.PG_PH[channel].write(ch2_data, nenc[1]) self.PG_UTIL.write(ch1_data, 0xF) sleep(slt) self.PG_UTIL.write(ch1_data, 0x0) newdc = self.calc_dc_lim(freq, self.chdcs[channel]) self.PG_UTIL.write(ch2_data, 0x0) self.PG_AUX[channel].write(ch1_data, newdc) self.PG_AUX[channel].write(ch2_data, self.calc_delay(self.chdelays[channel])) self.PG_UTIL.write(ch2_data, 0x1) self.chfreqs[channel] = freq def pg_set_dc(self, channel, dc): #Dc from 0 to 1 dcenc = self.calc_dc_lim(self.chfreqs[channel], dc) self.PG_UTIL.write(ch2_data, 0x0) self.PG_AUX[channel].write(ch1_data, dcenc) self.PG_UTIL.write(ch2_data, 0x1) self.chdcs[channel] = dc def pg_set_pw(self, channel, pw): pwv = self.calc_delay(pw / 1000) self.PG_UTIL.write(ch2_data, 0x0) self.PG_AUX[channel].write(ch1_data, pwv) self.PG_UTIL.write(ch2_data, 0x1) tlim = REF_CLK / self.chfreqs[channel] self.chdcs[channel] = pwv / tlim def pg_set_delay(self, channel, delay): #Delay in seconds delv = self.calc_delay(delay) self.PG_UTIL.write(ch2_data, 0x0) self.PG_AUX[channel].write(ch2_data, delv) self.chdelays[channel] = delay self.PG_UTIL.write(ch2_data, 0x1) def encode_phase_inc(self, freq): enc = int((freq * 2**PHASE_BIT_DEPTH) / REF_CLK) lsb = enc & 0xFFFFFFFF msb = (enc >> 32) & 0xFFFF return [lsb, msb] def calc_dc_lim(self, freq, dc): #dc from 0 to 1 dc_t = int(REF_CLK / freq) return int(dc_t * dc) def calc_delay(self, delay): return int(delay * REF_CLK) def TT_concat48(self, lsb, msb): retval = (lsb & 0xFFFFFFFF) | ((msb & 0xFFFF) << 32) return retval def TT_slice48(self, xsl): lsb = xsl & 0xFFFFFFFF msb = (xsl >> 32) & 0xFFFF return [lsb, msb] def TT_set_timeout(self, time): tval = time * REF_CLK lsb, msb = self.TT_slice48(int(tval)) self.TT_TIME_OUT.write(ch1_data, lsb) self.TT_TIME_OUT.write(ch2_data, msb) def TT_reset(self): self.TT_UTIL.write(ch1_data, 0b0) def TT_activate(self, timeout): self.TT_set_timeout(timeout) self.TT_UTIL.write(ch1_data, 0b1) def TT_read_times(self): retvals = [] for i in range(4): lsb = self.TT_DET[i].read(ch1_data) msb = self.TT_DET[i].read(ch2_data) retvals.append(self.TT_concat48(lsb, msb)) return retvals def TT_read_states(self): return self.TT_UTIL.read(ch2_data) & 0xF def TT_read_rdy(self): return (self.TT_UTIL.read(ch2_data) >> 4) & 0x1 def TT_proc(self): print("Waiting for data") if (self.TT_read_rdy() == 0): print("1") while (self.TT_read_rdy() == 0): pass else: print("0") while (self.TT_read_rdy() == 1): pass vals = self.TT_read_times() states = self.TT_read_states() return { 'T1': vals[0] * (1 / REF_CLK), 'T2': vals[1] * (1 / REF_CLK), 'T3': vals[2] * (1 / REF_CLK), 'T4': vals[3] * (1 / REF_CLK), 'T1s': (states & 1), 'T2s': ((states >> 1) & 0b1), 'T3s': ((states >> 2) & 0b1), 'T4s': ((states >> 3) & 0b1) } def DD_idelay(self, channel, tap, stage): print("Setting input delay on channel " + str(channel) + " dline tap of " + str(tap) + " with " + str(stage) + " stage(s).") self.iDD_UTIL[channel].write(ch1_data, 0x0) sleep(slt) self.iDD_UTIL[channel].write(ch1_data, 0x1) self.iDD_DATA[channel].write(ch1_data, tap) self.iDD_DATA[channel].write(ch2_data, stage)
class TT: def __init__(self): ol = Overlay("SCS_TT_TEST_wrapper.bit", 0) ol.download() self.UTIL = MMIO(0x41200000, 0x10000) self.UTIL.write(0x8, int(REF_CLK)) self.DATA0 = MMIO(0x41210000, 0x10000) self.DATA1 = MMIO(0x41220000, 0x10000) self.DATA_UTIL = MMIO(0x41230000, 0x10000) self.DEBUG0 = MMIO(0x41240000, 0x10000) self.DEBUG1 = MMIO(0x41250000, 0x10000) def uencode(self, val, length): cnt = 0 for i in range(length): if ((val >> i) & 0b1 == 1): cnt += 1 return cnt def set_timeout(self, seconds): self.UTIL.write(0x8, int(REF_CLK * seconds)) def start(self): self.UTIL.write(0x0, 0x1) def stop(self): self.UTIL.write(0x0, 0x0) def wait_for_rdy(self): if ((self.read_drdy()) == 1): while ((self.read_drdy()) == 1): pass else: while (self.read_drdy() == 0): pass def read_debug(self): deb0 = self.DEBUG0.read(0x0) deb1 = self.DEBUG0.read(0x8) deb2 = self.DEBUG1.read(0x0) rawdel0 = deb2 rawdel1 = (deb0 & 0xFFFF) rawdel2 = (deb0 & 0xFFFF0000) >> 16 rawdel3 = (deb1 & 0xFFFF) rawdel4 = (deb1 & 0xFFFF0000) >> 16 log.debug("T0D: " + bin(rawdel0)) log.debug("T1D: " + bin(rawdel1)) log.debug("T2D: " + bin(rawdel2)) log.debug("T3D: " + bin(rawdel3)) log.debug("T4D: " + bin(rawdel4)) def read_drdy(self): return (self.DATA_UTIL.read(0x8) & 0B0000100000000) >> 8 def read_times(self): rawtime0 = self.DATA0.read(0x0) rawtime1 = self.DATA0.read(0x8) rawtime2 = self.DATA1.read(0x0) rawtime3 = self.DATA1.read(0x8) log.debug("T0: " + str(rawtime0)) log.debug("T1: " + str(rawtime1)) log.debug("T2: " + str(rawtime2)) log.debug("T3: " + str(rawtime3)) self.read_debug() ctime0 = rawtime0 / REF_CLK ctime1 = rawtime1 / REF_CLK ctime2 = rawtime2 / REF_CLK ctime3 = rawtime3 / REF_CLK #print("CTIME0: "+str(ctime0)) #print("CTIME1: " + str(ctime1)) #print("CTIME2: " + str(ctime2)) #print("CTIME3: " + str(ctime3)) del0 = self.DATA_UTIL.read(0x0) del1 = self.DATA_UTIL.read(0x8) & 0B11111111 #print("DELAYS: "+bin(del0)) rawdel0 = (del1 & 0xFF) rawdel1 = (del0 & 0xFF) rawdel2 = ((del0 & 0xFF00) >> 8) rawdel3 = ((del0 & 0xFF0000) >> 16) rawdel4 = ((del0 & 0xFF000000) >> 24) log.debug("RT: " + str(rawdel0)) log.debug("R1: " + str(rawdel1)) log.debug("R2: " + str(rawdel2)) log.debug("R3: " + str(rawdel3)) log.debug("R4: " + str(rawdel4)) t0del = rawdel0 * FTIME t2del = rawdel2 * FTIME t3del = rawdel3 * FTIME t4del = rawdel4 * FTIME t1del = rawdel1 * FTIME ctime0 = ctime0 + t0del - t1del ctime1 = ctime1 + t0del - t2del ctime2 = ctime2 + t0del - t3del ctime3 = ctime3 + t0del - t4del return [ctime0, ctime1, ctime2, ctime3] def read_timeouts(self): return (self.DATA_UTIL.read(0x8) & 0B1111000000000) >> 9 def proc(self): self.wait_for_rdy() times = self.read_times() timeouts = self.read_timeouts() print("T1 (ns): " + str(times[0] * 1e9)) print("T2 (ns): " + str(times[1] * 1e9)) print("T3 (ns): " + str(times[2] * 1e9)) print("T4 (ns): " + str(times[3] * 1e9)) print("TIMEOUTS: " + bin(timeouts)) return times
class ioOverlay(Overlay): """A simple Physical IO Overlay for PYNQ. This overlay is implemented with a single CtrlLoop core connected directly to the ARM Core AXI interface. """ __RESET_VALUE = 0 __NRESET_VALUE = 1 """ For convenince, we define register offsets that are scraped from the HLS implementation header files. """ __IO_AP_CTRL_OFF = 0x00 __IO_AP_CTRL_START_IDX = 0 __IO_AP_CTRL_DONE_IDX = 1 __IO_AP_CTRL_IDLE_IDX = 2 __IO_AP_CTRL_READY_IDX = 3 __IO_AP_CTRL_AUTORESTART_IDX = 7 __IO_GIE_OFF = 0x04 __IO_IER_OFF = 0x08 __IO_ISR_OFF = 0x0C """These define the 'reg' argument to the 'io' HLS function. The memory space defined here is shared between the HLS core and the ARM PS. """ __IO_REG_OFF = 0x200 __IO_REG_LEN = 0x100 def __init__(self, bitfile, **kwargs): """Initializes a new ioOverlay object. """ # The following lines do some path searching to enable a # PYNQ-Like API for Overlays. For example, without these # lines you cannot call ioOverlay('io.bit') because # io.bit is not on the bitstream search path. The # following lines fix this for any non-PYNQ Overlay # # You can safely reuse, and ignore the following lines # # Get file path of the current class (i.e. /opt/python3.6/<...>/stream.py) file_path = os.path.abspath(inspect.getfile(inspect.currentframe())) # Get directory path of the current class (i.e. /opt/python3.6/<...>/stream/) dir_path = os.path.dirname(file_path) # Update the bitfile path to search in dir_path bitfile = os.path.join(dir_path, bitfile) # Upload the bitfile (and parse the colocated .tcl script) super().__init__(bitfile, **kwargs) # Manually define the GPIO pin that drives reset self.__resetPin = GPIO(GPIO.get_gpio_pin(0), "out") # Define a Register object at address 0x0 of the IO address space # We will use this to set bits and start the core (see start()) # Do NOT write to __ap_ctrl unless __resetPin has been set to __NRESET_VALUE self.nreset() self.__ap_ctrl = Register(self.ioCore.mmio.base_addr, 32) self.__hls_reg = MMIO(self.ioCore.mmio.base_addr + self.__IO_REG_OFF, self.__IO_REG_LEN) def __set_autorestart(self): """ Set the autorestart bit of the HLS core """ self.__ap_ctrl[self.__IO_AP_CTRL_AUTORESTART_IDX] = 1 def __clear_autorestart(self): """ Clear the autorestart bit """ self.__ap_ctrl[self.__IO_AP_CTRL_AUTORESTART_IDX] = 0 def __start(self): """Raise AP_START and enable the HLS core """ self.__ap_ctrl[self.__IO_AP_CTRL_START_IDX] = 1 def __stop(self): """Lower AP_START and disable the HLS core """ self.__ap_ctrl[self.__IO_AP_CTRL_START_IDX] = 0 def nreset(self): """Set the reset pin to self.__NRESET_VALUE to place the core into not-reset (usually run) """ self.__resetPin.write(self.__NRESET_VALUE) def reset(self): """Set the reset pin to self.__RESET_VALUE to place the core into reset """ self.__resetPin.write(self.__RESET_VALUE) def launch(self): """ Start and detatch computation on the io HLS core Returns ------- Nothing """ self.__set_autorestart() self.__start() return def land(self): """ Re-Connect and Terminate Computation on the io HLS core Returns ------- The 4-bit value representing the value of the buttons. """ self.__clear_autorestart() while(not self.__ap_ctrl[self.__IO_AP_CTRL_DONE_IDX]): pass self.__stop() return self.__hls_reg.read(0) def run(self): """ Launch computation on the io HLS core Returns ------- The 4-bit value representing the value of the buttons. """ self.__start() while(not self.__ap_ctrl[self.__IO_AP_CTRL_DONE_IDX]): pass self.__stop() return self.__hls_reg.read(0)
class ST: def __init__(self): ol = Overlay("TEST_wrapper.bit", 0) ol.download() self.DATA = MMIO(0x43c00000, 0x10000) self.UTIL = MMIO(0x43c10000, 0x10000) self.loaded_data = [] for i in range(FIFO_BUFFER): self.loaded_data.append(0) self.loaded_count = 0 def calc_time(self, coarse, finet): ctime = coarse / REF_CLK finetimevalues = finet ftime0 = finetimevalues & 0xFF ftime1 = (finetimevalues & 0xFF00) >> 8 #log.debug("FTIME0 -- "+bin(ftime0)) #log.debug("FTIME1 -- " + bin(ftime1)) return ctime + (ftime0 - ftime1) * FTIME def start(self): self.set_mreset(1) def stop(self): self.set_mreset(0) def flush_buffer(self): for i in range(FIFO_BUFFER): self.loaded_data[i] = 0 self.loaded_count = 0 def proc(self): self.read2048() return {"MOD": "ST", "LEN": self.loaded_count, "DAT": self.loaded_data} def read2048(self): if (self.read_empty() == 1): return for i in range(FIFO_BUFFER): if (self.read_empty() == 1): self.loaded_count = i return self.set_dreset(1) self.set_req(1) while (self.read_drdy() == 0): pass self.loaded_data[i] = self.read_coarse() | self.read_fine() << 32 #print(self.loaded_data[i]&0xFFFFFFFF) self.set_req(0) self.set_dreset(0) self.loaded_count = FIFO_BUFFER def read_coarse(self): return self.DATA.read(0x0) def read_fine(self): return self.DATA.read(0x8) def read_drdy(self): return self.UTIL.read(0x8) & 0b1 def read_empty(self): return (self.UTIL.read(0x8) & 0b10) >> 1 def read_full(self): return (self.UTIL.read(0x8) & 0b100) >> 1 def set_mreset(self, val): lastval = self.UTIL.read(0x0) & 0b110 self.UTIL.write(0x0, lastval | (val & 0b1)) def set_req(self, val): lastval = self.UTIL.read(0x0) & 0b101 self.UTIL.write(0x0, lastval | ((val << 1) & 0b10)) def set_dreset(self, val): lastval = self.UTIL.read(0x0) & 0b011 self.UTIL.write(0x0, lastval | ((val << 2) & 0b100))
def solve(boardstr, seed=12345, zero_padding=False): print('boardstr:') print(boardstr) print('seed:') print(seed) print('') # ボード文字列から X, Y, Z を読んでくる size_x = (ord(boardstr[1]) - ord('0')) * 10 + (ord(boardstr[2]) - ord('0')) size_y = (ord(boardstr[4]) - ord('0')) * 10 + (ord(boardstr[5]) - ord('0')) size_z = (ord(boardstr[7]) - ord('0')) # Overlay 読み込み OL = Overlay('pynqrouter.bit') OL.download() print(OL.ip_dict) print('Overlay loaded!') # MMIO 接続 (pynqrouter) mmio = MMIO(int(PL.ip_dict[IP][0]), int(PL.ip_dict[IP][1])) # MMIO 接続 & リセット (LED) mmio_led = MMIO(int(PL.ip_dict[IP_LED][0]), int(PL.ip_dict[IP_LED][1])) mmio_led.write(0, 0) # 入力データをセット imem = pack(boardstr) for i in range(len(imem)): mmio.write(OFFSET_BOARD + (i * 4), imem[i]) mmio.write(OFFSET_SEED, seed) # スタート # ap_start (0 番地の 1 ビット目 = 1) mmio.write(0, 1) print('Start!') time_start = time.time() # ap_done (0 番地の 2 ビット目 = 2) が立つまで待ってもいいが # done は一瞬だけ立つだけのことがあるから # ap_idle (0 番地の 3 ビット目 = 4) を待ったほうが良い iteration = 0 while (mmio.read(0) & 4) == 0: # 動いてるっぽく見えるようにLチカさせる iteration += 1 if iteration == 10000: mmio_led.write(0, 3) elif 20000 <= iteration: mmio_led.write(0, 12) iteration = 0 # 完了の確認 print('Done!') print('control:', mmio.read(0)) time_done = time.time() elapsed = time_done - time_start print('elapsed:', elapsed) print('') # 状態の取得 status = int(mmio.read(OFFSET_STATUS)) print('status:', status) if status != 0: # 解けなかったらLEDを消す mmio_led.write(0, 0) sys.stderr.write('Cannot solve it!\n') return {'solved': False, 'solution': '', 'elapsed': -1.0} print('Solved!') # 解けたらLEDを全部つける mmio_led.write(0, 15) # 出力 omem = [] for i in range(len(imem)): omem.append(mmio.read(OFFSET_BOARD + (i * 4))) boards = unpack(omem) # 回答の生成 solution = ('SIZE ' + str(size_x) + 'X' + str(size_y) + 'X' + str(size_z) + '\n') for z in range(size_z): solution += ('LAYER ' + str(z + 1) + '\n') for y in range(size_y): for x in range(size_x): if x != 0: solution += ',' i = ((x * MAX_X + y) << BITWIDTH_Z) | z if zero_padding: solution += '{0:0>2}'.format(boards[i]) # 2桁の0詰め else: solution += str(boards[i]) # 普通に表示 solution += '\n' return {'solved': True, 'solution': solution, 'elapsed': elapsed}
class DevMode(object): """Control an IO processor running the developer mode program. This class will wait for Python to send commands to Pmod / Arduino IO, IIC, or SPI. Attributes ---------- if_id : int The interface ID (1,2,3) corresponding to (PMODA,PMODB,ARDUINO). iop : _IOP IO processor instance used by DevMode. iop_switch_config :list IO processor switch configuration (8 or 19 integers). mmio : MMIO Memory-mapped IO instance to read and write instructions and data. """ def __init__(self, if_id, switch_config): """Return a new instance of a DevMode object. Parameters ---------- if_id : int The interface ID (1,2,3) corresponding to (PMODA,PMODB,ARDUINO). switch_config : list IO Processor switch configuration (8 or 19 integers). """ if not if_id in [PMODA, PMODB, ARDUINO]: raise ValueError("No such IOP for DevMode.") self.if_id = if_id self.iop = request_iop(if_id, iop_const.MAILBOX_PROGRAM) self.iop_switch_config = list(switch_config) self.mmio = MMIO(self.iop.mmio.base_addr + iop_const.MAILBOX_OFFSET, \ iop_const.MAILBOX_SIZE) def start(self): """Start the IO Processor. The IOP instance will start automatically after instantiation. This method will: 1. zero out mailbox CMD register; 2. load switch config; 3. set IOP status as "RUNNING". """ self.iop.start() self.mmio.write(iop_const.MAILBOX_PY2IOP_CMD_OFFSET, 0) self.load_switch_config(self.iop_switch_config) def stop(self): """Put the IO Processor into Reset. This method will set IOP status as "STOPPED". """ self.iop.stop() def load_switch_config(self, config=None): """Load the IO processor's switch configuration. This method will update switch config. Parameters ---------- config: list A switch configuration list of integers. Raises ---------- TypeError If the config argument is not of the correct type. """ if self.if_id in [PMODA, PMODB]: if config == None: config = iop_const.PMOD_SWCFG_DIOALL elif not len(config) == iop_const.PMOD_SWITCHCONFIG_NUMREGS: raise TypeError('Invalid switch config {}.'.format(config)) # Build switch config word self.iop_switch_config = config sw_config_word = 0 for ix, cfg in enumerate(self.iop_switch_config): sw_config_word |= (cfg << ix*4) # Disable, configure, enable switch self.write_cmd(iop_const.PMOD_SWITCHCONFIG_BASEADDR + 4, 0) self.write_cmd(iop_const.PMOD_SWITCHCONFIG_BASEADDR, \ sw_config_word) self.write_cmd(iop_const.PMOD_SWITCHCONFIG_BASEADDR + 7, \ 0x80, dWidth=1) elif self.if_id in [ARDUINO]: if config == None: config = iop_const.ARDUINO_SWCFG_DIOALL elif not len(config) == iop_const.ARDUINO_SWITCHCONFIG_NUMREGS: raise TypeError('Invalid switch config {}.'.format(config)) # Build switch config word self.iop_switch_config = config sw_config_words = [0, 0, 0, 0] for ix, cfg in enumerate(self.iop_switch_config): if ix < 6: sw_config_words[0] |= (cfg << ix*2) elif ix == 6: sw_config_words[0] |= (cfg << 31) elif 7 <= ix < 11: sw_config_words[1] |= (cfg << (ix-7)*4) elif 11 <= ix < 15: sw_config_words[2] |= (cfg << (ix-11)*4) else: sw_config_words[3] |= (cfg << (ix-15)*4) # Configure switch for i in range(4): self.write_cmd(iop_const.ARDUINO_SWITCHCONFIG_BASEADDR + \ 4*i, sw_config_words[i]) else: raise ValueError("Cannot load switch for unknown IOP.") def status(self): """Returns the status of the IO processor. Parameters ---------- None Returns ------- str The IOP status ("IDLE", "RUNNING", or "STOPPED"). """ return self.iop.state def write_cmd(self, address, data, dWidth=4, dLength=1, timeout=10): """Send a write command to the mailbox. Parameters ---------- address : int The address tied to IO processor's memory map. data : int 32-bit value to be written (None for read). dWidth : int Command data width. dLength : int Command burst length (currently only supporting dLength 1). timeout : int Time in milliseconds before function exits with warning. Returns ------- None """ return self._send_cmd(iop_const.WRITE_CMD, address, data, dWidth=dWidth, timeout=timeout) def read_cmd(self, address, dWidth=4, dLength=1, timeout=10): """Send a read command to the mailbox. Parameters ---------- address : int The address tied to IO processor's memory map. dWidth : int Command data width. dLength : int Command burst length (currently only supporting dLength 1). timeout : int Time in milliseconds before function exits with warning. Returns ------- list A list of data returned by MMIO read. """ return self._send_cmd(iop_const.READ_CMD, address, None, dWidth=dWidth, timeout=timeout) def is_cmd_mailbox_idle(self): """Check whether the IOP command mailbox is idle. Parameters ---------- None Returns ------- bool True if IOP command mailbox idle. """ mb_cmd_word = self.mmio.read(iop_const.MAILBOX_PY2IOP_CMD_OFFSET) return (mb_cmd_word & 0x1) == 0 def get_cmd_word(self, cmd, dWidth, dLength): """Build the command word. Note ---- The returned command word has the following format: Bit [0] : valid bit. Bit [2:1] : command data width. Bit [3] : command type (read or write). Bit [15:8] : command burst length. Bit [31:16] : unused. Parameters ---------- cmd : int Either 1 (read IOP register) or 0 (write IOP register). dWidth : int Command data width. dLength : int Command burst length (currently only supporting dLength 1). Returns ------- int The command word following a specific format. """ word = 0x1 # cmd valid word = word | (dWidth-1) << 1 # cmd dataWidth (3->4B, 1->2B, 0->1B) word = word | (cmd) << 3 # cmd type (1->RD, 0->WR) word = word | (dLength) << 8 # cmd burst length (1->1 word) word = word | (0) << 16 # unused return word def _send_cmd(self, cmd, address, data, dWidth=4, dLength=1, timeout=10): """Send a command to the IO processor via mailbox. Note ---- User should avoid to call this method directly. Use the read_cmd() or write_cmd() instead. Example: >>> _send_cmd(1, 4, None) # Read address 4. Parameters ---------- cmd : int Either 1 (read IOP Reg) or 0 (write IOP Reg). address : int The address tied to IO processor's memory map. data : int 32-bit value to be written (None for read). dWidth : int Command data width. dLength : int Command burst length (currently only supporting dLength 1). timeout : int Time in milliseconds before function exits with warning. Raises ------ LookupError If it takes too long to receive the ACK from the IOP. """ self.mmio.write(iop_const.MAILBOX_PY2IOP_ADDR_OFFSET, address) if data != None: self.mmio.write(iop_const.MAILBOX_PY2IOP_DATA_OFFSET, data) # Build the write command cmd_word = self.get_cmd_word(cmd, dWidth, dLength) self.mmio.write(iop_const.MAILBOX_PY2IOP_CMD_OFFSET, cmd_word) # Wait for ACK in steps of 1ms cntdown = timeout while not self.is_cmd_mailbox_idle() and cntdown > 0: time.sleep(0.001) cntdown -= 1 # If ACK is not received, alert users. if cntdown == 0: raise LookupError("DevMode _send_cmd() not acknowledged.") # Return data if expected from read, otherwise return None if cmd == iop_const.WRITE_CMD: return None else: return self.mmio.read(iop_const.MAILBOX_PY2IOP_DATA_OFFSET)
xlnk.xlnk_reset() cma_recv = xlnk.cma_array((size, ), dtype=np.uint8) result = xlnk.cma_array((size, ), dtype=np.uint8) for i in range(200): cma_send = hdmi_in.readframe() rgb2yuv.write(0x04, cma_send.physical_address) rgb2yuv.write(0x08, cma_recv.physical_address) rgb2yuv.write(0x0c, 1088) rgb2yuv.write(0x10, 1920) rgb2yuv.write(0x14, 1920 * 1088) rgb2yuv.write(0x00, 1) rgb2yuv.write(0x00, 0) while rgb2yuv.read(0x18) == 1: pass while rgb2yuv.read(0x18) == 0: pass h264.write(0x04, 0x00004377) # length 1088*1920 h264.write(0x08, 0) h264.write(0x14, cma_recv.physical_address) h264.write(0x18, result.physical_address) h264.write(0x00, 1) while h264.read(0x24) == 1: pass while h264.read(0x24) == 0: pass h264_size = h264.read(0x1c)
class BooleanGenerator: """Class for the Boolean generator. This class can implement any combinational function. Since each LUT5 takes 5 inputs, the basic function that users can implement is 5-input, 1-output boolean function. However, by concatenating multiple LUT5 together, users can implement complex boolean functions. There are 16 5-LUTs, so users can implement at most 16 basic boolean functions at a specific time. Attributes ---------- expressions : list/dict The boolean expressions, each expression being a string. input_pins : list A list of input pins used by the generator. output_pins : list A list of output pins used by the generator. """ def __init__(self, intf_spec_name='BG_SPECIFICATION'): """Return a new Boolean generator object. The available input pins are data pins DIN0 - DIN15, The available output pins can be DOUT0-DOUT15. The input boolean expression can be of the following format: `DOUT4 = DIN0 & DIN1 | DIN2`. If no input boolean expression is specified, the default function implemented is `DIN0 & DIN1 & DIN2 & DIN3`. Parameters ---------- No parameters are required """ if type(intf_spec_name) is str: self.intf_spec = eval(intf_spec_name) elif type(intf_spec_name) is dict: self.intf_spec = intf_spec_name else: raise ValueError("Interface specification has to be str or dict.") self.bg_mmio = MMIO(0x43c00000, (4 * 64)) self.bg_sel_mmio = MMIO(0x41200000) # Parameters to be cleared at reset self.expressions = dict() self.output_pins = list() self.input_pins = list() def setup(self, expressions): """Configure CFGLUTs with new boolean expression. Parameters ---------- expressions : list/dict The boolean expression to be configured. """ if isinstance(expressions, list): for i in range(len(expressions)): self.expressions['Boolean expression {}'.format(i)] = \ deepcopy(expressions[i]) elif isinstance(expressions, dict): self.expressions = deepcopy(expressions) else: raise ValueError("Expressions must be list or dict.") mailbox_addr = self.bg_mmio.base_addr mailbox_regs = [ Register(addr) for addr in range(mailbox_addr, mailbox_addr + 4 * 64, 4) ] for offset in range(0, 32, 2): mailbox_regs[offset][31:0] = 0x1FFFFFF for index in range(0, 32): self.bg_mmio.write((index * 4), mailbox_regs[index][31:0]) self.bg_mmio.write((62 * 4), 0x0000ffff) self.bg_mmio.write((63 * 4), (0x0000ffff | 0x80000000)) self.bg_mmio.write((63 * 4), 0) # was 0x0000ffff) for expr_label, expression in self.expressions.items(): if not isinstance(expression, str): raise TypeError("Boolean expression has to be a string.") if "=" not in expression: raise ValueError( "Boolean expression must have form Output = Function.") # Parse boolean expression into output & input string expr_out, expr_in = expression.split("=") expr_out = expr_out.strip() if expr_out in self.output_pins: raise ValueError("The same output pin should not be driven by " "multiple expressions.") self.output_pins.append(expr_out) if expr_out in self.intf_spec['output_pins']: output_pin_num = self.intf_spec['output_pins'][expr_out] else: raise ValueError("Invalid output pin {}.".format(expr_out)) # Parse the used pins preserving the order non_unique_inputs = re.sub("\W+", " ", expr_in).strip().split(' ') unique_input_pins = list(OrderedDict.fromkeys(non_unique_inputs)) if not 1 <= len(unique_input_pins) <= 5: raise ValueError("Expect 1 - 5 inputs for each LUT.") input_pins_with_dontcares = unique_input_pins[:] self.input_pins += unique_input_pins self.input_pins = list(set(self.input_pins)) # Need 5 inputs - any unspecified inputs will be don't cares for i in range(len(input_pins_with_dontcares), 5): expr_in = '(({0}) & X{1})|(({0}) & ~X{1})'.format(expr_in, i) input_pins_with_dontcares.append('X{}'.format(i)) # Map to truth table p0, p1, p2, p3, p4 = map(exprvar, input_pins_with_dontcares) expr_p = expr_in # Use regular expression to match and replace whole word only for orig_name, p_name in zip(input_pins_with_dontcares, ['p{}'.format(i) for i in range(5)]): expr_p = re.sub(r"\b{}\b".format(orig_name), p_name, expr_p) truth_table = expr2truthtable(eval(expr_p)) # Parse truth table to send truth_list = str(truth_table).split("\n") truth_num = 0 for i in range(32, 0, -1): truth_num = (truth_num << 1) + int(truth_list[i][-1]) # Get current boolean generator bit enables bit_enables = self.bg_mmio.read(62 * 4) cfg_enables = self.bg_mmio.read(63 * 4) # Generate the input selects based on truth table and bit enables truth_table_inputs = [str(inp) for inp in truth_table.inputs] for i in range(5): lsb = i * 5 msb = (i + 1) * 5 - 1 if truth_table_inputs[i] in unique_input_pins: if truth_table_inputs[i] in self.intf_spec[ 'input_pins'] and truth_table_inputs[i] \ in self.intf_spec['input_pins']: input_pin_ix = self.intf_spec['input_pins'][ truth_table_inputs[i]] else: raise ValueError("Invalid input pin " "{}.".format(truth_table_inputs[i])) else: input_pin_ix = 0x1f mailbox_regs[output_pin_num * 2][msb:lsb] = input_pin_ix mailbox_regs[output_pin_num * 2 + 1][31:0] = truth_num mailbox_regs[62][31:0] = bit_enables mailbox_regs[62][output_pin_num] = 0 mailbox_regs[63][31:0] = cfg_enables mailbox_regs[63][output_pin_num] = 1 int_to_write_62 = int(mailbox_regs[62][31:0]) int_to_write_63 = int(mailbox_regs[63][31:0]) for index in range(0, 32): self.bg_mmio.write((index * 4), (mailbox_regs[index][31:0])) self.bg_mmio.write((62 * 4), int_to_write_62) self.bg_mmio.write((63 * 4), (int_to_write_63 | 0x80000000)) self.bg_mmio.write((63 * 4), int_to_write_63) def read(self, regnum): """Read Boolean Generator memory mapped registers. Parameters ---------- regnum : integer """ if type(regnum) is int: self.reg_num = regnum else: raise ValueError("Register number must be integer") if regnum not in range(0, 64): raise ValueError("Register number must be in range of 0-63") return (self.bg_mmio.read(self.reg_num * 4)) def clear(self, expressions): """Clear output pins so new function on same pin can be defined. Parameters ---------- expressions : list/dict Clear output pins so previosly configured output pins can be used. """ if isinstance(expressions, list): for i in range(len(expressions)): self.expressions['Boolean expression {}'.format(i)] = \ deepcopy(expressions[i]) elif isinstance(expressions, dict): self.expressions = deepcopy(expressions) else: raise ValueError("Expressions must be list or dict.") self.output_pins = list()
# DDR4 MMIO ddr4 = ovl.ddr4_0.mmio ddr4_array = ddr4.array # numpy array of uint32 print("size = {} words".format(ddr4_array.size)) # AXI-Lite hls access regs = ovl.ip_dict["resnet18_2_0"] base_addr_snd = regs["phys_addr"] addr_range_snd = regs["addr_range"] print("snd:base_addr = 0x{:X}".format(base_addr_snd)) print("snd:addr_range = {}".format(addr_range_snd)) mmio_hls = MMIO(base_addr_snd, addr_range_snd) n = mmio_axi32.read(OFFSET_ID_VERSION) print("ID_VERSION = 0x{:X}".format(n)) bid = mmio_axi32.read(OFFSET_STATUS) print("Board ID = 0x{:X}".format(bid)) mmio_axi32.write(OFFSET_LED, 0x80 | bid) time.sleep(1) mmio_axi32.write(OFFSET_EXT_ADDR, 0xfff8) mmio_axi32.write(OFFSET_EXT_DATA, 0x2) mcubecluster.settbl(mmio_axi32) # set ddr data ddr = np.loadtxt('../params/ddr2.txt', dtype='uint32') ddr4_array[0:len(ddr)] = ddr print('DDRSIZE: ' + str(len(ddr) * 2))
class Trace_Buffer: """Class for the trace buffer, leveraging the sigrok libraries. This trace buffer class gets the traces from DMA and processes it using the sigrok commands. Note ---- The `sigrok-cli` library has to be installed before using this class. Attributes ---------- protocol : str The protocol the sigrok decoder are using. trace_csv: str The absolute path of the trace file `*.csv`. trace_sr: str The absolute path of the trace file `*.sr`, translated from `*.csv`. trace_pd : str The absolute path of the decoded file by sigrok. probes : list The list of probes used for the trace. dma : DMA The DMA object associated with the trace buffer. ctrl : MMIO The MMIO class used to control the DMA. samplerate: int The samplerate of the traces. data : cffi.FFI.CData The pointer to the starting address of the trace data. """ def __init__(self, if_id, protocol, trace=None, data=None, samplerate=500000): """Return a new trace buffer object. Users have to specify the location of the traces, even if no trace has been imported from DMA yet. This method will construct the trace from the DMA data. The maximum sample rate is 100MHz. Note ---- The probes selected by `mask` does not include any tristate probe. Parameters ---------- if_id : int The interface ID (PMODA, PMODB, ARDUINO). protocol : str The protocol the sigrok decoder are using. trace: str The relative/absolute path of the trace file. data : cffi.FFI.CData The pointer to the starting address of the data. samplerate : int The rate of the samples. """ if os.geteuid() != 0: raise EnvironmentError('Root permissions required.') if not isinstance(protocol, str): raise TypeError("Protocol name has to be a string.") if data != None: if not isinstance(data, cffi.FFI.CData): raise TypeError("Data pointer has wrong type.") if not isinstance(samplerate, int): raise TypeError("Sample rate has to be an integer.") if not 1 <= samplerate <= 100000000: raise ValueError("Sample rate out of range.") if if_id in [PMODA, PMODB]: dma_base = int(PL.ip_dict["SEG_axi_dma_0_Reg"][0],16) ctrl_base = int(PL.ip_dict["SEG_trace_cntrl_0_Reg2"][0],16) ctrl_range = int(PL.ip_dict["SEG_trace_cntrl_0_Reg2"][1],16) elif if_id in [ARDUINO]: dma_base = int(PL.ip_dict["SEG_axi_dma_0_Reg1"][0],16) ctrl_base = int(PL.ip_dict["SEG_trace_cntrl_0_Reg"][0],16) ctrl_range = int(PL.ip_dict["SEG_trace_cntrl_0_Reg"][1],16) else: raise ValueError("No such IOP for instrumentation.") self.dma = DMA(dma_base, direction=1) self.ctrl = MMIO(ctrl_base, ctrl_range) self.samplerate = samplerate self.protocol = protocol self.data = data self.probes = [] self.trace_pd = '' if trace != None: if not isinstance(trace, str): raise TypeError("Trace path has to be a string.") if not os.path.isfile(trace): trace_abs = os.getcwd() + '/' + trace else: trace_abs = trace if not os.path.isfile(trace_abs): raise ValueError("Specified trace file does not exist.") _, format = os.path.splitext(trace_abs) if format == '.csv': self.trace_csv = trace_abs self.trace_sr = '' elif format == '.sr': self.trace_sr = trace_abs self.trace_csv = '' else: raise ValueError("Only supporting csv or sr files.") def __del__(self): """Destructor for trace buffer object. Parameters ---------- None Returns ------- None """ del(self.dma) def start(self, timeout=10): """Start the DMA to capture the traces. Parameters ---------- timeout : int The time in number of milliseconds to wait for DMA to be idle. Return ------ None """ # Create buffer self.dma.create_buf(MAX_NUM_SAMPLES*8) self.dma.transfer(MAX_NUM_SAMPLES*8, direction=1) # Wait for DMA to be idle timer = timeout while (self.ctrl.read(0x00) & 0x04)==0: sleep(0.001) timer -= 1 if (timer==0): raise RuntimeError("Timeout when waiting DMA to be idle.") # Configuration self.ctrl.write(TRACE_LENGTH_OFFSET, MAX_NUM_SAMPLES) self.ctrl.write(TRACE_SAMPLE_RATE_OFFSET, \ int(MAX_SAMPLE_RATE / self.samplerate)) self.ctrl.write(TRACE_CMP_LSW_OFFSET, 0x00000) self.ctrl.write(TRACE_CMP_MSW_OFFSET, 0x00000) # Start the DMA self.ctrl.write(TRACE_CTRL_OFFSET,0x01) self.ctrl.write(TRACE_CTRL_OFFSET,0x00) def stop(self): """Stop the DMA after capture is done. Note ---- There is an internal timeout mechanism in the DMA class. Parameters ---------- None Return ------ None """ # Wait for the DMA self.dma.wait() # Get 64-bit samples from DMA self.data = self.dma.get_buf(64) def show(self): """Show information about the specified protocol. Parameters ---------- None Return ------ None """ if os.system("sigrok-cli --protocol-decoders " + \ self.protocol+" --show"): raise RuntimeError('Sigrok-cli show failed.') def csv2sr(self): """Translate the `*.csv` file to `*.sr` file. The translated `*.sr` files can be directly used in PulseView to show the waveform. Note ---- This method also modifies the input `*.csv` file (the comment header, usually 3 lines, will be removed). Parameters ---------- None Return ------ None """ name, _ = os.path.splitext(self.trace_csv) self.trace_sr = name + ".sr" temp = name + ".temp" if os.system("rm -rf " + self.trace_sr): raise RuntimeError('Trace sr file cannot be deleted.') in_file = open(self.trace_csv, 'r') out_file = open(temp, 'w') # Copy only the contents; ignore comments for i, line in enumerate(in_file): if not line.startswith(';'): out_file.write(line) in_file.close() out_file.close() os.remove(self.trace_csv) os.rename(temp, self.trace_csv) command = "sigrok-cli -i " + self.trace_csv + \ " -I csv -o " + self.trace_sr if os.system(command): raise RuntimeError('Sigrok-cli csv to sr failed.') def sr2csv(self): """Translate the `*.sr` file to `*.csv` file. The translated `*.csv` files can be used for interactive plotting. It is human readable. Note ---- This method also removes the redundant header that is generated by sigrok. Parameters ---------- None Return ------ None """ name, _ = os.path.splitext(self.trace_sr) self.trace_csv = name + ".csv" temp = name + ".temp" if os.system("rm -rf " + self.trace_csv): raise RuntimeError('Trace csv file cannot be deleted.') command = "sigrok-cli -i " + self.trace_sr + \ " -O csv > " + temp if os.system(command): raise RuntimeError('Sigrok-cli sr to csv failed.') in_file = open(temp, 'r') out_file = open(self.trace_csv, 'w') # Copy only the contents; ignore comments for i, line in enumerate(in_file): if not line.startswith(';'): out_file.write(line) in_file.close() out_file.close() os.remove(temp) def decode(self, decoded_file, options=''): """Decode and record the trace based on the protocol specified. The `decoded_file` contains the name of the output file. The `option` specifies additional options to be passed to sigrok-cli. For example, users can use option=':wordsize=9:cpol=1:cpha=0' to add these options for the SPI decoder. The decoder will also ignore the pin collected but not required for decoding. Note ---- The output file will have `*.pd` extension. Note ---- The decoded file will be put into the specified path, or in the working directory in case the path does not exist. Parameters ---------- decoded_file : str The name of the file recording the outputs. options : str Additional options to be passed to sigrok-cli. Return ------ None """ if not isinstance(decoded_file, str): raise TypeError("File name has to be a string.") if self.probes == []: raise ValueError("Cannot decode without metadata.") if os.path.isdir(os.path.dirname(decoded_file)): decoded_abs = decoded_file else: decoded_abs = os.getcwd() + '/' + decoded_file name, _ = os.path.splitext(self.trace_sr) temp_file = name + '.temp' if os.system('rm -rf ' + temp_file): raise RuntimeError("Cannot remove temporary file.") self.trace_pd = '' if os.system('rm -rf ' + decoded_abs): raise RuntimeError("Cannot remove old decoded file.") pd_annotation = '' for i in self.probes: if not i=='NC': # Ignore pins not connected to device pd_annotation += (':'+i.lower()+'='+i) command = "sigrok-cli -i " + self.trace_sr + " -P " + \ self.protocol + options + pd_annotation + (' > ' + temp_file) if os.system(command): raise RuntimeError('Sigrok-cli decode failed.') f_decoded = open(decoded_abs, 'w') f_temp = open(temp_file, 'r') j = 0 for line in f_temp: m = re.search('([0-9]+)-([0-9]+) (.*)', line) if m: while (j < int(m.group(1))): f_decoded.write('\n') j += 1 while (j <= int(m.group(2))): f_decoded.write(m.group(3) + '\n') j += 1 f_temp.close() f_decoded.close() self.trace_pd = decoded_abs if os.system('rm -rf ' + temp_file): raise RuntimeError("Cannot remove temporary file.") if os.path.getsize(self.trace_pd)==0: raise RuntimeError("No transactions and decoded file is empty.") def set_metadata(self, probes): """Set metadata for the trace. A `*.sr` file directly generated from `*.csv` will not have any metadata. This method helps to set the sample rate, probe names, etc. The list `probes` depends on the protocol. For instance, the I2C protocol requires a list of ['SDA','SCL']. Parameters ---------- probes : list A list of probe names. Return ------ None """ if not isinstance(probes, list): raise TypeError("Probes have to be in a list.") # Convert csv file to sr file, if necessary if self.trace_sr == '': self.csv2sr() self.probes = probes name, _ = os.path.splitext(self.trace_sr) if os.system("rm -rf " + name): raise RuntimeError('Directory cannot be deleted.') if os.system("mkdir " + name): raise RuntimeError('Directory cannot be created.') if os.system("unzip -q "+ self.trace_sr + " -d " + name): raise RuntimeError('Unzip sr file failed.') metadata = open(name + '/metadata', 'r') temp = open(name + '/temp', 'w') pat = "samplerate=0 Hz" subst = "samplerate=" + str(self.samplerate) +" Hz" j = 0 for i, line in enumerate(metadata): if line.startswith("probe"): # Set the probe names temp.write("probe"+str(j+1)+"="+probes[j]+'\n') j += 1 else: # Set the sample rate temp.write(line.replace(pat, subst)) metadata.close() temp.close() if os.system("rm -rf "+ name + '/metadata'): raise RuntimeError('Cannot remove metadata folder.') if os.system("mv " + name + '/temp ' + name + '/metadata'): raise RuntimeError('Cannot rename metadata folder.') if os.system("cd "+ name +"; zip -rq " + \ self.trace_sr + " * ; cd .."): raise RuntimeError('Zip sr file failed.') if os.system("rm -rf " + name): raise RuntimeError('Cannnot remove temporary folder.') def parse(self, parsed, start=0, stop=MAX_NUM_SAMPLES, mask=MASK_ALL, tri_sel=[], tri_0=[], tri_1=[]): """Parse the input data and generate a `*.csv` file. This method can be used along with the DMA. The input data is assumed to be 64-bit. The generated `*.csv` file can be then used as the trace file. To extract certain bits from the 64-bit data, use the parameter `mask`. Note ---- The probe pins selected by `mask` does not include any tristate probe. To specify a set of tristate probe pins, e.g., users can set tri_sel = [0x0000000000000004], tri_0 = [0x0000000000000010], and tri_1 = [0x0000000000000100]. In this example, the 3rd probe from the LSB is the selection probe; the 5th probe is selected if selection probe is 0, otherwise the 9th probe is selected. There can be multiple sets of tristate probe pins. Note ---- The parsed file will be put into the specified path, or in the working directory in case the path does not exist. Parameters ---------- parsed : str The file name of the parsed output. start : int The first 64-bit sample of the trace. stop : int The last 64-bit sample of the trace. mask : int A 64-bit mask to be applied to the 64-bit samples. tri_sel : list The list of tristate selection probe pins. tri_0 : list The list of probe pins selected when the selection probe is 0. tri_1 : list The list probe pins selected when the selection probe is 1. Return ------ None """ if not isinstance(parsed, str): raise TypeError("File name has to be an string.") if not isinstance(start, int): raise TypeError("Sample number has to be an integer.") if not isinstance(stop, int): raise TypeError("Sample number has to be an integer.") if not 1 <= (stop-start) <= MAX_NUM_SAMPLES: raise ValueError("Data length has to be in [1,{}]."\ .format(MAX_NUM_SAMPLES)) if not isinstance(mask, int): raise TypeError("Data mask has to be an integer.") if not 0<=mask<=MASK_ALL: raise ValueError("Data mask out of range.") if not isinstance(tri_sel, list): raise TypeError("Selection probe pins have to be in a list.") if not isinstance(tri_0, list) or not isinstance(tri_1, list): raise TypeError("Data probe pins have to be in a list.") if not len(tri_sel)==len(tri_0)==len(tri_1): raise ValueError("Inconsistent length for tristate lists.") for element in tri_sel: if not isinstance(element, int) or not 0<element<=MASK_ALL: raise TypeError("Selection probe has to be an integer.") if not (element & element-1)==0: raise ValueError("Selection probe can only have 1-bit set.") if not (element & mask)==0: raise ValueError("Selection probe has be excluded from mask.") for element in tri_0: if not isinstance(element, int) or not 0<element<=MASK_ALL: raise TypeError("Data probe has to be an integer.") if not (element & element-1)==0: raise ValueError("Data probe can only have 1-bit set.") if not (element & mask)==0: raise ValueError("Data probe has be excluded from mask.") for element in tri_1: if not isinstance(element, int) or not 0<element<=MASK_ALL: raise TypeError("Data probe has to be an integer.") if not (element & element-1)==0: raise ValueError("Data probe can only have 1-bit set.") if not (element & mask)==0: raise ValueError("Data probe has be excluded from mask.") if os.path.isdir(os.path.dirname(parsed)): parsed_abs = parsed else: parsed_abs = os.getcwd() + '/' + parsed if os.system('rm -rf ' + parsed_abs): raise RuntimeError("Cannot remove old parsed file.") with open(parsed_abs, 'w') as f: for i in range(start, stop): raw_val = self.data[i] & MASK_ALL list_val = [] for j in range(63,-1,-1): if (mask & 1<<j)>>j: list_val.append(str((raw_val & 1<<j)>>j)) else: for selection in tri_sel: idx = tri_sel.index(selection) if (selection & 1<<j)>>j: if ((raw_val & 1<<j)>>j)==0: log = tri_0[idx].bit_length()-1 list_val.append( str((raw_val & 1<<log)>>log)) else: log = tri_1[idx].bit_length()-1 list_val.append( str((raw_val & 1<<log)>>log)) temp = ','.join(list_val) f.write(temp + '\n') self.trace_csv = parsed_abs self.trace_sr = '' def display(self, start_pos, stop_pos): """Draw digital waveforms in ipython notebook. It utilises the wavedrom java script library, documentation for which can be found here: https://code.google.com/p/wavedrom/. Note ---- Only use this method in Jupyter notebook. Note ---- WaveDrom.js and WaveDromSkin.js are required under the subdirectory js. Example of the data format to draw waveform: >>> data = {'signal': [ {'name': 'clk', 'wave': 'p.....|...'}, {'name': 'dat', 'wave': 'x.345x|=.x', 'data': ['D','A','T','A']}, {'name': 'req', 'wave': '0.1..0|1.0'}, {}, {'name': 'ack', 'wave': '1.....|01.'} ]} Parameters ---------- start_pos : int The starting sample number (relative to the trace). stop_pos : int The stopping sample number (relative to the trace). Returns ------- None """ if self.probes == []: raise ValueError("Cannot display without metadata.") if not isinstance(start_pos, int): raise TypeError("Start position has to be an integer.") if not 1 <= start_pos <= MAX_NUM_SAMPLES: raise ValueError("Start position out of range.") if not isinstance(stop_pos, int): raise TypeError("Stop position has to be an integer.") if not 1 <= stop_pos <= MAX_NUM_SAMPLES: raise ValueError("Stop position out of range.") # Copy the javascript to the notebook location if os.system("cp -rf " + \ os.path.dirname(os.path.realpath(__file__)) + \ '/js' + ' ./'): raise RuntimeError('Cannnot copy wavedrom javascripts.') # Convert sr file to csv file, if necessary if self.trace_csv == '': self.sr2csv() # Read csv trace file with open(self.trace_csv, 'r') as data_file: csv_data = list(csv.reader(data_file)) # Read decoded file with open(self.trace_pd, 'r') as pd_file: pd_data = list(csv.reader(pd_file)) # Construct the decoded transactions data = {} data['signal']=[] if self.trace_pd != '': temp_val = {'name': '', 'wave': '', 'data': []} for i in range(start_pos, stop_pos): if i==start_pos: ref = pd_data[i] if not ref: temp_val['wave'] += 'x' else: temp_val['wave'] += '4' temp_val['data'].append(''.join(pd_data[i])) else: if pd_data[i] == ref: temp_val['wave'] += '.' else: ref = pd_data[i] if not ref: temp_val['wave'] += 'x' else: temp_val['wave'] += '4' temp_val['data'].append(''.join(pd_data[i])) data['signal'].append(temp_val) # Construct the jason format data for signal_name in self.probes: index = self.probes.index(signal_name) temp_val = {'name': signal_name, 'wave': ''} for i in range(start_pos, stop_pos): if i==start_pos: ref = csv_data[i][index] temp_val['wave'] += str(csv_data[i][index]) else: if csv_data[i][index] == ref: temp_val['wave'] += '.' else: ref = csv_data[i][index] temp_val['wave'] += str(csv_data[i][index]) data['signal'].append(temp_val) # Construct the sample numbers and headers head = {} head['text'] = ['tspan', {'class':'info h4'}, \ 'Protocol decoder: ' + self.protocol + \ '; Sample rate: ' + str(self.samplerate) + ' samples/s'] head['tock'] = '' for i in range(start_pos, stop_pos): if i%2: head['tock'] += ' ' else: head['tock'] += (str(i)+' ') data['head'] = head htmldata = '<script type="WaveDrom">' + json.dumps(data) + '</script>' IPython.core.display.display_html(IPython.core.display.HTML(htmldata)) jsdata = 'WaveDrom.ProcessAll();' IPython.core.display.display_javascript( IPython.core.display.Javascript( data=jsdata, \ lib=['files/js/WaveDrom.js', 'files/js/WaveDromSkin.js']))
parser.add_argument('-M', '--mode', type=str, help='mode of the camera') args = parser.parse_args() print(args) if (args.mode): set_values(args.mode, args.width, args.height) width = args.width * 4 #vdma needs data in to bytes not into words,each pixel is 4 bytes so width * 4 in_cma = xlnk.cma_array(shape=(width * args.height, ), dtype=np.uint8) print('Created cma') print("size of input arr", in_cma.size) in_physical_addr = in_cma.physical_address print("the physical address is = ", in_physical_addr) vdma.write(status, 0xffffffff) vdma.write(0x30, 0x8b) print("cr = ", vdma.read(0x30)) vdma.write(frame_delay, width) print("frame_delay = ", vdma.read(frame_delay)) vdma.write(vsize, args.height) print("vsize = ", vdma.read(vsize)) vdma.write(hsize, width) print("hsize = ", vdma.read(hsize)) vdma.write(s2m_start, in_physical_addr) print("s2m = ", vdma.read(s2m_start)) print("vdma programming is done") gpio_en_pin.write(fifo, 0x0)