def test_rgbleds_write(): """Test for the RGBLED class and its wrapper functions. Control the two RGBLED objects, requesting user confirmation. """ base = BaseOverlay("base.bit") rgbleds = base.rgbleds[4:6] for rgbled in rgbleds: rgbled.off() assert rgbled.read() == 0, 'Wrong state for RGBLED.' print("\nShowing 7 colors of RGBLED. Press enter to stop...", end="") color = 0 while True: color = (color + 1) % 8 for rgbled in rgbleds: rgbled.write(color) assert rgbled.read() == color, 'Wrong state for RGBLED.' sleep(0.5) if sys.stdin in select.select([sys.stdin], [], [], 0)[0]: termios.tcflush(sys.stdin, termios.TCIOFLUSH) break for rgbled in rgbleds: rgbled.off() assert rgbled.read() == 0, 'Wrong state for RGBLED.' assert user_answer_yes("RGBLEDs showing 7 colors during the test?")
def __init__(self): base = BaseOverlay("base.bit") print("Base Initialized") self.pmod_up = Pmod_IO(base.PMODA, 0, 'out') print("pmod A Initialized") self.pmod_down = Pmod_IO(base.PMODB, 2, 'out') print("pmod B Initialized") frame_out_w = 1920 frame_out_h = 1080 #Mode_in = VideoMode(frame_out_w, frame_out_h,24) Mode_out = VideoMode(frame_out_w, frame_out_h, 8) self.hdmi_in = base.video.hdmi_in self.hdmi_in.configure() print(self.hdmi_in.mode) self.hdmi_in.start() print("HDMI In Initialized") self.hdmi_out = base.video.hdmi_out #self.hdmi_out.configure(Mode_out,PIXEL_RGB) self.hdmi_out.configure(Mode_out, PIXEL_GRAY) self.hdmi_out.start() #print(self.hdmi_in.mode) print(self.hdmi_out.mode) print("HDMI Out Initialized") #self.hdmi_in.tie(self.hdmi_out) self.flag = 1 print("Game start") self.jump() self.flag = 0 self.bitwise_mode = 0
def test_audio_playback(): """Test the functionality of handling pdm files. Test whether the `*.pdm` file can be handled properly. There are 2 steps in this test: 1. Load and play a pre-stored pdm file. 2. Record a pdm file and play it back. """ base = BaseOverlay("base.bit") audio_t = base.audio welcome_audio_path = "/home/xilinx/pynq/lib/tests/pynq_welcome.pdm" record_audio_path = "/home/xilinx/pynq/lib/tests/recorded.pdm" print("\nPlaying an audio file...") audio_t.load(welcome_audio_path) audio_t.play() assert user_answer_yes("Heard welcome message?") print("Speaking into the MIC for 5 seconds...") audio_t.record(5) audio_t.save(record_audio_path) input("Audio file saved. Hit enter to play back...") audio_t.load(record_audio_path) audio_t.play() assert user_answer_yes("Heard recorded sound?") os.remove(record_audio_path) del audio_t
def __init__(self): # Motor stuff self.base = BaseOverlay("base.bit") self.ardu = Arduino_Ardumoto(self.base.ARDUINO) self.ardu.configure_pins(self.ardu.defaultpins) self.ardu.configure_polarity(self.ardu.motorB, self.ardu.pol_reverse) self.ardu.configure_polarity(self.ardu.motorA, self.ardu.pol_reverse)
def test_rgbleds_index(): """Test for the RGBLED class and its wrapper functions. Test whether the corresponding RGBLED objects exist. """ base = BaseOverlay("base.bit") rgbleds = base.rgbleds rgbled_valid_index = [4, 5] for index, rgbled in enumerate(rgbleds): if index not in rgbled_valid_index: assert rgbled is None else: assert rgbled is not None
def test_btn_read(): """Test for the Button class and its wrapper functions. Read button index 0 ~ 3, requesting user confirmation. """ base = BaseOverlay("base.bit") print("") for index in range(4): assert base.buttons[index].read() == 0, \ "Button {} reads wrong values.".format(index) for index in range(4): input("Hit enter while pressing Button {0} (BTN{0})...".format(index)) assert base.buttons[index].read() == 1, \ "Button {} reads wrong values.".format(index)
def test_leds_on_off(): """Test for the LED class and its wrapper functions. Control the LED objects, requesting user confirmation. """ base = BaseOverlay("base.bit") leds = base.leds for led in leds: led.off() led = leds[0] led.on() assert user_answer_yes("\nOnboard LED 0 on?") led.off() assert user_answer_yes("Onboard LED 0 off?")
def test_audio_out(): """Test whether audio out works properly. Test whether sound can be heard from the audio out jack. Record a 5-second sample and play it back. """ base = BaseOverlay("base.bit") audio_t = base.audio print("\nSpeaking into the MIC for 5 seconds...") audio_t.record(5) input("Hit enter to play back...") audio_t.play() assert user_answer_yes("Heard playback on AUDIO OUT?") del audio_t
def test_switch_read(): """Test for the Switch class and its wrapper functions. Read the 2 Switch objects, requesting user confirmation. A time delay is added when reading the values from the switches. This is to compensate the delay for asyncio read. """ base = BaseOverlay("base.bit") print("\nSet the 2 switches (SW0 ~ SW1) off (lower position).") input("Then hit enter...") switches = base.switches for index, switch in enumerate(switches): assert switch.read() == 0, \ "Switch {} reads wrong values.".format(index) input("Now switch them on (upper position) and hit enter...") for index, switch in enumerate(switches): assert switch.read() == 1, \ "Switch {} reads wrong values.".format(index)
def test_leds_toggle(): """Test for the LED class and its wrapper functions. Control the LED objects, requesting user confirmation. """ base = BaseOverlay("base.bit") leds = base.leds print("\nToggling onboard LEDs. Press enter to stop toggling...", end='') for i in range(4): leds[i].write(i % 2) while True: for led in leds: led.toggle() sleep(0.1) if sys.stdin in select.select([sys.stdin], [], [], 0)[0]: termios.tcflush(sys.stdin, termios.TCIOFLUSH) break for led in leds: led.off() assert user_answer_yes("LEDs toggling during the test?")
def show(img): base = BaseOverlay("base.bit") # camera (input) configuration frame_in_w = 1280 frame_in_h = 720 # monitor configuration: 640*480 @ 60Hz Mode = VideoMode(frame_in_w,frame_in_h,24) hdmi_out = base.video.hdmi_out hdmi_out.configure(Mode,PIXEL_BGR) hdmi_out.start() print("HDMI Initialized") # initialize camera from OpenCV img = cv2.resize(img,(frame_in_w,frame_in_h)) while True: outframe = hdmi_out.newframe() outframe[:,:] = img[:,:] hdmi_out.writeframe(outframe) if(base.buttons[2].read()==1): break hdmi_out.stop() del hdmi_out
from pynq.overlays.base import BaseOverlay from pynq.lib.arduino import Arduino_IO base = BaseOverlay("base.bit") class PynqIO(object): def __init__(self): self.__light_pin = Arduino_IO(base.ARDUINO, 0, 'out') self.__switch = base.switches[0] self.__rgbled = base.rgbleds[4] def turn_on_light(self): self.__light_pin.write(1) def turn_off_light(self): self.__light_pin.write(0) def read_switch(self): return False if self.__switch.read() == 0 else True def set_alarm(self): base.rgbleds[4].write(4) base.rgbleds[5].write(4) def clear_alarm(self): base.rgbleds[4].write(4) base.rgbleds[5].write(4)
rate = rospy.Rate(10) while not rospy.is_shutdown(): lock.acquire() try: self.update_odom() except: print('Update odometry error!') traceback.print_exc() lock.release() self.pub.publish(self.odom) rate.sleep() def vel_callback(self, msg): print(msg.linear.x, msg.angular.z) lock.acquire() v1 = self.linear_coef * msg.linear.x v1 -= self.angular_coef * msg.angular.z v2 = self.linear_coef * msg.linear.x v2 += self.angular_coef * msg.angular.z self.set_speed(v1, v2) lock.release() if __name__ == '__main__': rospy.init_node('Pynq_Car') Robot = BaseOverlay("Robot.bit") PINS = [5, 6, 4, 7, 3, 2, 9, 8, 11, 10, 13, 12] motor = Automoto(Robot.ARDUINO, PINS) Car_driver = CarDriver(motor) Car_driver.set_speed(0, 0) Car_driver.run()
def main(): base = BaseOverlay("base.bit") print("载入overlay成功.....") hdmi_out = base.video.hdmi_out videoIn = cv2.VideoCapture(0) init(hdmi_out, videoIn) ret, frame = videoIn.read() print("获取前两帧图像并舍弃.....") disp_mode = 0 while videoIn.isOpened(): ret, frame = videoIn.read() if (ret): img = frame if (base.buttons[3].read() == 1 and disp_mode == 0): disp_mode = 1 elif (base.buttons[3].read() == 1 and disp_mode == 1): disp_mode = 0 if (disp_mode == 0): rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) outframe = hdmi_out.newframe() outframe[:] = rgb hdmi_out.writeframe(outframe) else: counter, img_ig, img2 = detect_pai(img) if (counter == 0): outframe = hdmi_out.newframe() outframe[:] = img2 hdmi_out.writeframe(outframe) while True: if (base.buttons[1].read() == 1): disp_mode = 0 break else: rgb = cv2.cvtColor(img_ig, cv2.COLOR_BGR2RGB) outframe = hdmi_out.newframe() outframe[:] = rgb hdmi_out.writeframe(outframe) while True: if (base.buttons[2].read() == 1): break rgb = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) outframe = hdmi_out.newframe() outframe[:] = rgb hdmi_out.writeframe(outframe) while True: if (base.buttons[1].read() == 1): disp_mode = 0 break else: raise RuntimeError("Error while reading from camera.") if (base.buttons[0].read() == 1): break print("测试结束.....") videoIn.release() hdmi_out.stop() del hdmi_out print('this message is from main function')
# This material can be used for academic purposes only. Any commerical use is prohibited. # # Contact: Alexandros Kouris ([email protected]), Ph.D. Candidate, Imperial College London # In[11]: from pynq import Overlay, Xlnk from pynq.overlays.base import BaseOverlay allocator = Xlnk() #Load customised version of Base-Overlay,that included the custom hardware block, instead of using BaseOverlay("base.bit") #------------------------------------------------------------------------------------------------------------------------ #ol = Overlay("eie_v25.bit") #Grayscale, full-frame (33fps) #ol = Overlay("eie_v25_2.bit") #Grayscale, half-frame (33fps) ol = BaseOverlay("170519_plswork.bit" ) #Vertical Edge-Detector, half-frame (33fps) - EIE2019 # In[12]: from pynq.lib.video import * hdmi_in = ol.video.hdmi_in hdmi_out = ol.video.hdmi_out hdmi_in.configure(PIXEL_RGBA) hdmi_out.configure(hdmi_in.mode, PIXEL_RGBA) # In[13]: hdmi_in.start() hdmi_out.start()
from pynq.overlays.base import BaseOverlay from pynq.lib import Pmod_OLED base_overlay = BaseOverlay("base.bit") pmod_oled = Pmod_OLED(base_overlay.PMODA) from pynq import Overlay import wave pAudio = base_overlay.audio pAudio.select_microphone() pAudio.bypass(5) def Wait(): while base_overlay.buttons[0].read() == 0: pass def record(name): pAudio.record(5) pAudio.save(name + '.wav') def vedio(name): pAudio.load(name + '.wav') pAudio.play() from train import train from test import test import numpy as np import matplotlib import matplotlib.pyplot as plt
# config log __log_format = '%(asctime)s-%(process)d-%(thread)d - %(name)s:%(module)s:%(funcName)s - %(levelname)s - %(message)s' logging.basicConfig(format=__log_format) lock_state = 0 #锁状态 app_ctrl = 0 #APP控制标志位 #登录服务器 lk = linkkit.LinkKit(host_name="cn-shanghai", product_key="a1cBjoQ7X6m", device_name="pynq", device_secret="86sbHtelVFqxH4k00QxknrA2O4EivlPs") lk.enable_logger(logging.DEBUG) #************ FPGA ******** base = BaseOverlay( "/usr/local/lib/python3.6/dist-packages/pynq/overlays/base/base_wrapper.bit" ) io = pmod_io.Pmod_IO(base.PMODA, 1, 'out') pAudio = base.audio pAudio.load("recording_1.wav") #********** NCS ************ network = FaceRecognize() IMAGE_SAVE_PATH = "images/" KNOWN_FACES_PICKLE_PATH = "known_peoples.pkl" FACE_MATCH_THRESHOLD = 0.75 #font = cv2.FONT_HERSHEY_SIMPLEX font = cv2.FONT_HERSHEY_COMPLEX known_peoples = {} #******** 人脸识别 ********** face_detect = FaceDetect()
# coding: utf-8 # In[1]: from pynq.overlays.base import BaseOverlay base = BaseOverlay('base.bit') # In[2]: from pynq.lib.pmod import * # In[3]: sensors = [ Grove_PIR(base.PMODA, port) for port in (PMOD_GROVE_G1, PMOD_GROVE_G2) ] bar = Grove_LEDbar(base.PMODB, PMOD_GROVE_G4) # In[ ]: while True: display = 0 for m, s in zip([0b1111100000, 0b0000011111], sensors): display |= s.read() and m bar.write_binary(display)
def on_message(self, mqtt, userdata, message): asyncio.set_event_loop(asyncio.new_event_loop()) m_decode = str(message.payload.decode("utf-8")) print("\n" + "message recieved= " + m_decode) print("message topic=", message.topic) print("message qos=", message.qos) print("message retain flag=", message.retain) m_in = json.loads(m_decode) if message.topic == "microscope/light_sheet_microscope/UI/laser/445nm": print("LED 0 flashing") base = BaseOverlay("base.bit") led0 = base.leds[0] for i in range(20): led0.toggle() time.sleep(.1) if message.topic == "microscope/light_sheet_microscope/UI/laser/488nm": print("LED 0 flashing") base = BaseOverlay("base.bit") led0 = base.leds[0] for i in range(20): led0.toggle() time.sleep(.1) if message.topic == "microscope/light_sheet_microscope/UI/laser/515nm": print("LED 0 flashing") base = BaseOverlay("base.bit") led0 = base.leds[0] for i in range(20): led0.toggle() time.sleep(.1) if message.topic == "microscope/light_sheet_microscope/UI/laser/561nm": base = BaseOverlay("base.bit") led0 = base.leds[0] for i in range(20): led0.toggle() time.sleep(.1) if message.topic == "microscope/light_sheet_microscope/UI/laser/594nm": print("LED 0 flashing") base = BaseOverlay("base.bit") led0 = base.leds[0] for i in range(20): led0.toggle() time.sleep(.1) if message.topic == "microscope/light_sheet_microscope/UI/laser/638nm": print("LED 0 flashing") base = BaseOverlay("base.bit") led0 = base.leds[0] for i in range(20): led0.toggle() time.sleep(.1) if message.topic == "microscope/light_sheet_microscope/UI/laser" and m_in[ "payload"]["cmd"] == "device turning off": print("Laser turning off") client.loop_stop() if message.topic == "microscope/light_sheet_microscope/UI/laser/445nm" and m_in[ "payload"]["cmd"] == "set intensity of laser": dac = Pmod_DAC(base.PMODA) dac.write(0.6)
class OneWireBus: """ Singleton """ # OVERLAY = None ## Pynq Overlay instance currently installed in the fabric OVERLAY = BaseOverlay( const.OVERLAY_PATH ) #, download=(not OVERLAY_NAME == PL.bitfile_name.split('/')[-1])) # ## # ^ Skipping the re-download will break 1-Wire search ROMAD_SIZE = 20 ## Large enough to hold 10 temp. sensor ROM IDs __instance = None __bus_initialized = False search_complete = False @staticmethod def get_instance(overlay_path=const.OVERLAY_PATH): base_address = const.AXI_OW_ADDR(OneWireBus.OVERLAY) address_range = const.AXI_OW_RANGE(OneWireBus.OVERLAY) if OneWireBus.__instance is None: OneWireBus(base_addr=base_address, addr_range=address_range) return OneWireBus.__instance def __init__(self, base_addr=const._DEFAULT_AXI_OW_ADDR, addr_range=const._DEFAULT_AXI_OW_RANGE): """ Virtually private constructor for singleton OneWire class. """ if OneWireBus.__instance is None: self.axi_addr = base_addr self.axi_range = addr_range self.bram = MMIO(base_addr, addr_range) self.device_addresses = [None] OneWireBus.num_roms = 0 OneWireBus.set_clk( ) ## Set the PL function clock tied to the ow_master IP to 33 MHz OneWireBus.search_complete = True OneWireBus.__bus_initialized = True OneWireBus.__instance = self print( f"\n[__init__] New '{self.__class__.__name__}' singleton instance has been instantiated.\n" ) @property def initialized(self): return self.__bus_initialized @staticmethod def initialized(): return OneWire.__bus_initialized ## --------------------------------------------------------------------------------------------- @staticmethod def set_clk(mhz=const.CLK_MHZ, idx=const.OW_FCLK_IDX): if idx == 3: cur_freq = Clocks.fclk3_mhz elif idx == 2: cur_freq = Clocks.fclk2_mhz elif idx == 1: cur_freq = Clocks.fclk1_mhz elif idx == 0: cur_freq = Clocks.fclk0_mhz else: print( f"[set_clk] Invalid PL clock index: idx={idx} (must be value in range [0, 3])" ) return print(f"[set_clk] Clocks.fclk{idx}_mhz = {cur_freq}MHz") if abs(cur_freq - mhz ) > 1: ## Tests approximate equality to prevent call redundancy print(f"[set_clk] Setting fclk{idx} to {mhz}MHz") Clocks.set_pl_clk(idx, clk_mhz=mhz) def write(self, reg_addr, cmd): self.bram.write(reg_addr, cmd) def read(self, reg_addr): return self.bram.read(reg_addr) def read_status(self): return self.read(const.bram_registers['STATUS']) def read_num_found_roms(self): return self.read(const.bram_registers['FOUND']) def write_command(self, cmd): self.write(const.bram_registers['COMMAND'], cmd) def write_control(self, cmd): self.write(const.bram_registers['CONTROL'], cmd) def serialize_command(self): self.write_control(const.bus_commands['SERIALIZE']) def reset(self): """ RESET Master sends a reset pulse (by pulling the 1-Wire bus low for at least 8 time slots) and any/all [DS18B20] devices respond with a presence pulse. NOTE: This MUST be called prior to any ROM commands/device functions as a part of the necessary initialization process (exceptions to this are Search ROM and Search Alarms, for which both must re-initialize after executing) """ self.write_control(const.bus_commands['RESET_PULSE']) r_status = self.read_status() & const.bitmasks['STA_RSD'] count = 0 while r_status == 0: r_status = self.read_status() & const.bitmasks['STA_RSD'] count += 1 if count > 20: print('No presence pulse detected thus no devices on the bus!') return False timeout() return True ## --------------------------------------------------------------------------------------------- ## Polls the bus for devices & returns number of slaves # def search(self, SensorClass, search_cmd): def search(self, search_cmd=const.bus_commands['SEARCH_ROM']): """ SEARCH ROM [F0h] The master learns the ROM codes through a process of elimination that requires the master to perform a Search ROM cycle as many times as necessary to identify all of the slave devices. Returns the count of all device IDs discovered on the bus. This function has been configured so that an ALARM SEARCH [ECh] command and an alarms_array may be passed in to only collect ROMs of slaves with a set alarm flag. """ while OneWireBus.search_complete == False: print('.', end='') timeout() OneWireBus.search_complete = False ## Lock the bus while performing search ## Write search command to the command register, then serialize onto the bus to begin search self.write_command(search_cmd) self.serialize_command() r_status = self.read_status() # print(f"r_status = {hex(r_status)}") x = r_status & const.bitmasks['STA_SRD'] miss_count = 0 while x != 1 and miss_count < 30: r_status = self.read_status() # print(f"r_status = {hex(r_status)}") x = r_status & const.bitmasks['STA_SRD'] timeout() miss_count += 1 if r_status & const.bitmasks['STA_SER']: print( 'SEARCH PROTOCOL ERROR : SEARCH INCOMPLETE DUE TO ONE WIRE PROTOCOL ERROR\n' ) return None elif r_status & const.bitmasks['STA_SME']: print( 'SEARCH MEMORY ERROR : NOT ENOUGH FPGA MEMORY ALLOCATED FOR # of OW DEVICES FOUND\n' ) return None self.num_roms = self.read_num_found_roms() print(f'# ROMS FOUND = {self.num_roms}') # new_size = self.num_roms * 2 # if new_size > self.ROMAD_SIZE: # self.ROMAD_SIZE = new_size # self.device_addresses = [0] * self.ROMAD_SIZE # self.device_addresses = [None] * self.num_roms if self.num_roms > len(self.device_addresses): self.device_addresses.extend( [None] * (self.num_roms - len(self.device_addresses))) for i in range(self.num_roms): rom_lo = self.read((const.bram_registers['ROM_ID0'] + (i << 3))) rom_hi = self.read((const.bram_registers['ROM_ID1'] + (i << 3))) rom_long = (rom_hi << 32) + rom_lo print(f"\nROM {i} ID: {hex(rom_long)}") # self.device_addresses[i * 2] = rom_lo # self.device_addresses[(i * 2) + 1] = rom_hi # new_device = SensorClass(rom_hi, rom_lo, onewire_index=index) # yield new_device discovered_new_rom = True # if self.device_addresses[i] is not None and self.device_addresses[i].rom == rom_long: for device in self.device_addresses: if device is not None and device.rom == rom_long: ## Device has already been discovered on bus print( f"[OneWireBus.search]\tRe-discovered ROM: {hex(rom_long)}" ) discovered_new_rom = False break if discovered_new_rom: new_device = OneWireAddress(rom_long) print( f"[OneWireBus.search]\tDiscovered new device ROM on bus: {new_device}" ) j = i while j < len(self.device_addresses ) and self.device_addresses[j] is not None: j += 1 self.device_addresses[j % len(self.device_addresses)] = new_device OneWireBus.search_complete = True ## Unlock the 1-Wire bus after search is completed # return list(self.device_addresses) return [addr for addr in self.device_addresses if addr is not None] def match_rom(self, address): """ MATCH ROM [55h] The match ROM command allows to address a specific slave device on a multidrop or single-drop bus. Only the slave that exactly matches the 64-bit ROM code sequence will respond to the function command issued by the master; all other slaves on the bus will wait for a reset pulse. """ assert (isinstance(address, OneWireAddress)) self.reset() self.write_command(const.bus_commands['MATCH_ROM']) self.write(const.bram_registers['WR_SIZE'], const.TRANSMIT_BITS) self.write(const.bram_registers['WR_DATA0'], address.rom_lo) self.write(const.bram_registers['WR_DATA1'], address.rom_hi) self.write_control(const.bus_commands['EXEC_WO_PULLUP']) count = 0 while self.read_status() & const.bitmasks['STA_WRD'] == 0: count += 1 if (count > 20): print('[match_rom] Desired ROM address not matched') return False timeout() return True
def __init__(self): base = BaseOverlay("base.bit") self.leds = base.leds