def run_lesson1(self): self.print_lesson(1, "Making MODI") self.print_wrap('First, you should import modi. Type import modi') self.check_response('import modi') import modi self.print_wrap("Great! Now you can use all the features of modi\n") self.print_wrap("To control the modules, make a MODI object that " "contains all the connected modules. Once you create " "it, it will automatically find all the modules " "connected. When creating the MODI object, you should " "specify the number of modules currently connected to" " the network module.\n") input("\nPress ENTER") self.clear() self.print_wrap("\nNow, prepare real MODI modules. Connect a network " "module to your device. Then, connect a Button module " "and an Led module.\nSince you have 2 module connected" " to the network module, make a MODI object by typing " "bundle = modi.MODI(2)") self.check_response('bundle = modi.MODI(2)') bundle = modi.MODI(2) print() self.print_wrap('Great! The "bundle" is your MODI object. With it, ' 'you can control all the modules connected to your ' 'device.') input("\nYou have completed this lesson.\nPress ENTER") self.bundle = bundle
def run_lesson1(self): self.print_lesson(1, "Making MODI") self.print_wrap('First, you should import modi. Type "import modi"') self.check_user_input('import modi') import modi print("\nGreat! Now you can use all the features of MODI!\n") self.print_wrap(""" To control the modules, make a MODI object that contains all the connected modules. Once you create it, it will automatically find all the modules connected to the network module. """) input("\nPress ENTER") self.clear() self.print_wrap(""" Now, prepare real MODI modules. Connect a network module to your computing device. Then, connect a Button module and an Led module. Make a MODI bundle object by typing bundle = modi.MODI() """) self.check_user_input('bundle = modi.MODI()') bundle = modi.MODI() self.print_wrap(""" Great! The "bundle" is your MODI object. With it, you can control all the modules connected to your device. """) input("\nYou have completed this lesson. Press ENTER to continue.") self.bundle = bundle self.run_lesson2()
def main(): bundle = modi.MODI() car = Car() mot = bundle.motors[0] ir1 = bundle.irs[0] ir2 = bundle.irs[1]
def run_introduction(self): self.clear() print("=" * self.row_len) print(f"= {'Welcome to the PyMODI Tutor':^{self.row_len - 4}} =") print("=" * self.row_len) self.print_wrap(""" PyMODI is a very powerful tool that can control the MODI modules using python scripts. As long as you learn how to use built-in functions of PyMODI, you can easily control MODI modules. This interactive CUI tutorial will guide you through the world of PyMODI. """) selection = dedent(""" Tutorial includes: 1. Making MODI 2. Accessing Modules 3. Controlling Modules 4. Your First PyMODI Project """) print(selection) lesson_nb = int(input("Enter the lesson number and press ENTER: ")) self.clear() if not (0 < lesson_nb < 5): print("ERROR: lesson_nb must be one of 1, 2, 3 or 4") os._exit(0) # Skip lesson 1 if lesson_nb > 1: print("=" * self.row_len) print(f"= {'Preparing the modi object...':^{self.row_len - 4}} =") print("=" * self.row_len) import modi self.print_wrap(""" In order to skip the first lesson, we need to set-up the prerequisites. Thus, connect button and led module to your device. """) input("\nif the modules are ready, press ENTER to continue: ") print() self.bundle = modi.MODI() # Skip lesson 2 if lesson_nb > 2: self.button = self.bundle.buttons[0] self.led = self.bundle.leds[0] run_selected_lesson = { 1: self.run_lesson1, 2: self.run_lesson2, 3: self.run_lesson3, 4: self.run_lesson4, }.get(lesson_nb) run_selected_lesson()
def run_inspection(self): self.clear() print("=" * self.row_len) print(f"= {'This is PyMODI Module Inspector':^{self.row_len - 4}} =") print("=" * self.row_len) self.print_wrap(""" PyMODI provides a number of tools that can be utilized in different purpose. One of them is the STM32 module (all modules but network) inspector which diagnoses any malfunctioning MODI module. """) nb_modules = int( input( dedent(""" Connect network module to your local machine, attach other modi modules to the network module. When attaching modi modules, make sure that you provide sufficient power to the modules. Using modi battery module is a good way of supplying the power to the modules. Type the number of modi modules (integer value) that are connected to the network module (note that the maximum number of modules is 20) and press ENTER: """.rstrip() + " "))) self.clear() if not (1 <= nb_modules <= 20): print(f"ERROR: {nb_modules} is invalid for the number of modules") os._exit(0) print("Importing modi package and creating a modi bundle object...\n") import modi self.bundle = modi.MODI() stm32_modules = \ [m for m in self.bundle.modules if m.module_type != "Network"] nb_modules_detected = len(stm32_modules) if nb_modules != nb_modules_detected: self.print_wrap(f""" You said that you have attached {nb_modules} modules but PyMODI detects only {nb_modules_detected} number of modules! Look at the printed log above regarding module connection and check which modules have not been printed above. """) os._exit(0) input( dedent(""" It looks like all stm modules have been initialized properly! Let's diagnose each module, one by one! Press ENTER to continue: """.rstrip() + " ")) self.clear() # Let's inspect each stm module! for i, module in enumerate(stm32_modules): self.inspect(module, i, nb_modules)
def main(): bundle = modi.MODI(3) gyro = bundle.gyros[0] btn = bundle.buttons[0] i = 1 dg = DataGathering() while True: df = dg.record_motion(btn, gyro) filename = '../data/new.csv' # go 를 모을 데이터 명으로 바꾼 다음 실행 with open(filename, 'a') as f: f.write('\n') df.to_csv(filename, mode='a', header=False) i += 1 print("collected data : ", i)
def main(): bundle = modi.MODI(3) gyro = bundle.gyros[0] btn = bundle.buttons[0] mot = bundle.motors[0] dg = DetectGesture() while True: time.sleep(0.1) if btn.double_clicked: print("start!") #mot.speed = 25, -25 time.sleep(0.1) while True: if btn.clicked: pred = dg.predict(gyro, btn) time.sleep(0.1) print("prediction : ", pred) # 사용자 코드 영역 # ======================================================= if pred == 'back': #mot.speed = -23,23 time.sleep(0.1) print('car : back!') elif pred == 'go': #mot.speed = 23, -23 time.sleep(0.1) print('car : go!') elif pred == 'left': #mot.speed = 23, 23 time.sleep(0.1) print('car : left!') elif pred == 'right': #mot.speed = -23, -23 time.sleep(0.1) print('car : right!') #======================================================= time.sleep(0.1) if btn.double_clicked: print("stop!") mot.speed = 0, 0 time.sleep(0.1) break
def main(): bundle = modi.MODI() #print(bundle.motors, bundle.irs) #if len(bundle.motors) is not 1 or len(bundle.irs) is not 1: # print("Unstable Connection! Exit and execute again.") # return #else: global motor0 global ir0 motor0 = bundle.motors[0] #motor1=bundle.motors[1] ir0 = bundle.irs[0] turnLeft() moveForward() moveForward() moveForward() moveForward() moveBack() for j in range(n): if j % 2 == 0: for i in range(-1, n): if i == n - 1: #이미 차가 마지막 위치에 있으면 for문을 끝내버림 continue # st = [i, j] en = [i + 1, j] if arr[en[0]][en[1]]: #만약 목표 위치가 장애물이 있음이 이미 확인되었으면 다음 칸으로 넘김 continue while move(ch_ptod(BFS(loc, en), wat), en): #차가 목표 위치에 도달할 때 까지 계속 돌림 continue elif j % 2 == 1: for k in range(n, -1, -1): #n부터 1까지 역순으로 숫자 생성 if k == 0: continue en = [k - 1, j] if arr[en[0]][en[1]]: continue while move(ch_ptod(BFS(loc, en), wat), en): continue for i in arr: print(i)
def init_game(): global gamepad, clock, jet, background, enemies, targets, bullets bundle = modi.MODI(4) pygame.init() gamepad = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("PyMODI rox") jet = pygame.image.load(os.path.join(here, 'img/jet.png')) enemies, targets, bullets = [], [], [] enemies.append(pygame.image.load(os.path.join(here, 'img/enemy1.png'))) enemies.append(pygame.image.load(os.path.join(here, 'img/enemy2.png'))) background = pygame.image.load(os.path.join(here, 'img/background.png')) clock = pygame.time.Clock() start_back = pygame.image.load(os.path.join(here, './img/start.png')) gamepad.blit(start_back, (0, 0)) pygame.display.update() run_game(bundle)
def main(): car = AutonomousCar() bundle = modi.MODI() mot = bundle.motors[0] btn = bundle.buttons[0] # Indicator for ready mot.speed = 60, -60 time.sleep(0.3) mot.speed = 0, 0 # car.start_car(mot, btn) while True: time.sleep(0.01) if btn.double_clicked: print("클릭") time.sleep(0.01) car.start_car(mot, btn)
def __enter__(self): self.bundle = modi.MODI() print("----------------------------------------------------------") if len(self.bundle.modules) == self.length: print("Modules are connected:") for module in self.bundle.modules: print(type(module)) print(self) else: print("Modules are not connected properly!") print("Number of connected Modules: {self.length}") print("----------------------------------------------------------") self.__exit__(self, None, None) print("----------------------------------------------------------") return self.bundle
def start(self): # Intro self.clear() print("=" * self.row) print(f"= {'Welcome to the PyMODI Tutor':^{self.row - 4}} =") print("=" * self.row) self.print_wrap("\nPyMODI is a very powerful tool that can control " "the MODI modules using python scripts. As long as you" " learn how to use built-in functions of PyMODI, you " "can easily control MODI modules. This interactive CUI" " tutorial will guide you through the " "marvelous world of PyMODI.") print("Tutorial includes:\n" "1. Making MODI\n" "2. Accessing Modules\n" "3. Controlling Modules\n" "4. Your First PyMODI Project") lesson_nb = int(input("\nEnter the lesson number and press ENTER: ")) self.clear() if lesson_nb > 1: import modi print("Preparing the MODI module...") input("Connect buttton and led module to your device and press " "ENTER") self.bundle = modi.MODI(2) if lesson_nb > 2: self.led = self.bundle.leds[0] self.button = self.bundle.buttons[0] if lesson_nb <= 1: self.run_lesson1() if lesson_nb <= 2: self.run_lesson2() if lesson_nb <= 3: self.run_lesson3() if lesson_nb <= 4: self.run_lesson4()
import modi import keyboard if __name__ == '__main__': bundle = modi.MODI(conn_mode='ble', uuid="YOUR_NETWORK_MODULE_UUID") motor = bundle.motors[0] network = bundle.networks[0] while True: if keyboard.is_pressed('down'): motor.speed = 100, -100 elif keyboard.is_pressed('up'): motor.speed = -100, 100 elif keyboard.is_pressed('left'): motor.speed = 100, 100 elif keyboard.is_pressed('right'): motor.speed = -100, -100 else: motor.speed = 0, 0
import modi """ This example explains the convention that pymodi uses when multiple modules with the same type are connected. When multiple modules are connected, the modules are sorted in ascending order based on the position relative to the network module. 1. Distance from the network module 2. Left to Right 3. Top to Bottom """ # Let say you run the code below, then one of the four cases below will occur if __name__ == "__main__": bundle = modi.MODI() led1 = bundle.leds[0] led2 = bundle.leds[1] bundle.print_topology_map(print_id=True) """ Case 1: <<MODI Topology Map>> ================================================================= Network:67 Dial:2821 Button:2766 Led:1600 Led:3712 In this case, since Led:3712 is closer to the network module, led1 is Led:3712 and led2 is Led:1600. Case 2:
az = [] # Gyro X, Y Z gx = [] gy = [] gz = [] # Roll, Pitch, Yaw roll = [] pitch = [] yaw = [] # Time tick tick = [] bundle = md.MODI() time.sleep(5) gyro = bundle.gyros[0] print("start log\n") # Read the 6-DOF Gryo-Accel-RPY value at every 50mS filename = "" filename = "log" + str(time.time()) + ".csv" for i in range(1, 20): tick.append(time.time()) ax.append(gyro.acceleration_x()) ay.append(gyro.acceleration_y())
def main(): bundle = modi.MODI() code = [] # 코드가 담길 배열 sentence = '버튼 누르면 불 켜줘' #sentence = '버튼 누를때만 불켜줘' print('기본 형태소 분석', tagger.pos(sentence)) # 0. if 해당 형태소를 기준으로 chunk1 과 chunk2를 나눔 # 0-1.if 해당 형태소 추출 index = '' pos = tagger.pos(sentence) for elem in pos: try: x = cond_dic[elem[0]] if x == 'if': # if 하나만 넣어도 되는 경우 index = elem[0] elif x == 'else': # else까지 암묵적으로 넣어줘야하는 경우 index = elem[0] except: pass print("인덱스 : ", index) # 0-2.조건문 if 해당 형태소를 기준으로 chunk 1,2 분할 sen = sentence.split(index) chunk1 = sen[0] chunk2 = sen[1] print(chunk1) print(chunk2) # 1. 각 chunk에 대하여 명사(모듈)만 추출하여 선언 (ex: motor = bundle.motors[0]) nouns = tagger.nouns(sentence) # 명사 형태소 추출 print(nouns) for noun in nouns: if noun in module_dic: module = find_dic(noun) tmp = module + ' = bundle.' + module + 's[0]' code.append(tmp + '\n') # 2. 각 chunk에 대해 명사와 동사(모듈과 동작)만 추출하여 pair를 만듦 (ex: led.on() ) tag_noun = ['NNP', 'NNG'] tag_verb = ['VV'] #chunk1 n1 = find_dic(get_morph(chunk1, tag_noun)[0]) v1 = find_dic(get_morph(chunk1, tag_verb)[0]) #chunk2 n2 = find_dic(get_morph(chunk2, tag_noun)[0]) v2 = find_dic(get_morph(chunk2, tag_verb)[0]) # case에 따라 append 되도록 해야하며, 들여쓰기를 유의해야 함. # 위에서 else로 들어갈 경우, else문도 새로 만들어서 추가하도록 할 것. ind = cond_dic[index] code.append('while True:\n') if ind == 'if' or ind == 'else': code.append(add_indent('if ' + n1 + v1 + ':', 1)) code.append(add_indent(n2 + v2, 2)) if ind == 'else': code.append(add_indent('else:', 1)) code.append(add_indent(n2 + module_dic[n2], 2)) else: code.append(add_indent(n2 + v2, 0)) code.append(add_indent('time.sleep(0.01)', 1)) code = ''.join(code) print(code) exec(code)
import modi import keyboard if __name__ == '__main__': bundle = modi.MODI(conn_mode='ble', uuid="You network module's uuid") motor = bundle.motors[0] network = bundle.networks[0] while True: if keyboard.is_pressed('down'): motor.speed = 100, -100 elif keyboard.is_pressed('up'): motor.speed = -100, 100 elif keyboard.is_pressed('left'): motor.speed = 100, 100 elif keyboard.is_pressed('right'): motor.speed = -100, -100 else: motor.speed = 0, 0
import socket import time import modi SERVER_IP = '192.168.1.189' SERVER_PORT = 5050 SIZE = 1024 SERVER_ADDR = (SERVER_IP, SERVER_PORT) m_r = 1 robot = modi.MODI() motor1 = robot.motors[0] motor2 = robot.motors[1] motorp1 = robot.motors[2] motorp2 = robot.motors[3] pen = 0 t = 30 d = 70 def pen_move(motor1, motor2, motor3, motor4, Color, Up_Down): global pen if Up_Down == 'U': t = -1 elif Up_Down == 'D': t = 1 if Color == 'R': if pen == 0: backward(motor3, motor4, 30, 850) elif pen == -1: backward(motor3, motor4, 30, 1700) elif pen == 1: pass pen = 1
# Print help page if check_option('-h', '--help'): print(help_page) os._exit(0) # Start interactive pymodi tutorial if check_option('-t', '--tutorial'): pymodi_tutor = Tutor() pymodi_tutor.run_introduction() os._exit(0) # Time message transfer between local machine and network module if check_option('-p', '--performance'): print("[PyMODI Performance Test]" + "\n" + "=" * 25) init_time = time.time() bundle = modi.MODI() fin_time = time.time() took = (fin_time - init_time) * 100 // 1 / 100 print("Hard waiting for topology data to be initialized...") time.sleep(0.5 * len(bundle.modules)) bundle.print_topology_map(True) print(f"Took {took} seconds to initialize") req_tp_msg = parse_message(0x2A, 0, bundle.networks[0].id) print(f"sending request message... {req_tp_msg}") bundle._exe_thrd.close() init_time = time.perf_counter() bundle.send(req_tp_msg) msg = None while True: msg = bundle.recv() if not msg:
import modi import keyboard if __name__ == '__main__': bundle = modi.MODI( conn_type='ble', network_uuid="YOUR_NETWORK_MODULE_UUID" ) motor = bundle.motors[0] network = bundle.networks[0] while True: if keyboard.is_pressed('down'): motor.speed = 100, -100 elif keyboard.is_pressed('up'): motor.speed = -100, 100 elif keyboard.is_pressed('left'): motor.speed = 100, 100 elif keyboard.is_pressed('right'): motor.speed = -100, -100 else: motor.speed = 0, 0
import sounddevice as sd import soundfile as sf from multiprocessing import Process wav_path = '/home/pi/workspace/ai-contents-gyro-car/src/img/' def play_beep(wavfile): # data, fs = sf.read('/usr/src/rpi-daemon-py/sound/beep.wav', dtype="float32") data, fs = sf.read(wav_path + wavfile, dtype="float32") sd.play(data, fs) sd.wait() if __name__ == "__main__": # 네트워크 모듈의 uuid를 확인해주세요. bundle_ble = modi.MODI(conn_mode="ble", uuid="5BCAF0B0") # 예시(uuid="ABCD1234") gyro = bundle_ble.gyros[0] btn = bundle_ble.buttons[0] bundle_can = modi.MODI() mot = bundle_can.motors[0] dg = DetectGesture() p = Process(target=play_beep, args=('sound01.wav',)) p.start() # play_beep('sound01.wav') while True: