1. 程式人生 > >使用Scratch2和ROS進行機器人圖形化程式設計學習

使用Scratch2和ROS進行機器人圖形化程式設計學習

使用Scratch2和ROS進行機器人程式設計學習(適用於中小學機器人程式設計Scratch和ROS)

參考JdeRobot的一篇詳細介紹,就可以實現上述的功能,需要安裝Scratch2、ROS Kinetic、Gazebo 7、JdeRobot、Python2.7等。

通過將Scratch2圖形化程式語言轉為Python,然後通過ROS訊息機制控制Gazebo或實際機器人。

~~資訊化智慧化時代下平等受教育的權利~~

1 先看如下一個簡單的示例

1.1 新建hiros.bz2,如下:


1.2 通過下面命令將其轉為Python:

$ python scratch2python.py hiros.sb2
Stringify:
when @greenFlag clicked
repeat 10
    say 'Hello,ROS Kinetic!'
end
[WARN] Block <when @greenFlag clicked> not included yet

-------------------
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import config
import sys
import comm
import os
import yaml

from drone import Drone
from robot import Robot

def execute(robot):
    try:
        
        for i in range(10):
            print('Hello,ROS Kinetic!')
        
    except KeyboardInterrupt:
        raise

if __name__ == '__main__':
    if len(sys.argv) == 2:
        path = os.getcwd()
        open_path = path[:path.rfind('src')] + 'cfg/'
        filename = sys.argv[1]

    else:
        sys.exit("ERROR: Example:python my_generated_script.py cfgfile.yml")

    # loading the ICE and ROS parameters
    cfg = config.load(open_path + filename)
    stream = open(open_path + filename, "r")
    yml_file = yaml.load(stream)

    for section in yml_file:
        if section == 'drone':
            #starting comm
            jdrc = comm.init(cfg,'drone')

            # creating the object
            robot = Drone(jdrc)

            break
        elif section == 'robot':
            #starting comm
            jdrc = comm.init(cfg,'robot')

            # creating the object
            robot = Robot(jdrc)

            break
    # executing the scratch program
    execute(robot)


-------------------



2 控制機器人示例






是不是比較有趣,在不需購買任何裝置的情況下,就可以用Scratch2進行ROS機器人程式設計。小學用Scratch2學習簡單程式設計,中學用Python學習簡單程式設計,大學用Python和C++學習複雜機器人程式設計,無縫銜接。

3 scratch2python.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = "Raul Perula-Martinez"
__copyright__ = "JdeRobot project"
__credits__ = ["Raul Perula-Martinez"]
__license__ = "GPL v3"
__version__ = "0.0.0"
__maintainer__ = "Raul Perula-Martinez"
__email__ = "
[email protected]
" __status__ = "Development" import kurt import os import sys from difflib import SequenceMatcher from parse import parse, compile from termcolor import cprint GENERAL = [ ['end', ''], ['forever', 'while True:'], ['if {} then', 'if %s:'], ['else', 'else:'], ['repeat {}', 'for i in range(%s):'], ['say {}', 'print(%s)'], ['set {} to {}', '%s = %s'], ['wait {} secs', 'time.sleep(%s)'], ] ROBOTICS = [ ['move robot {}', 'robot.move("%s")'], ['move drone {}', 'robot.move("%s")'], ['move robot {} speed {}', 'robot.move("%s", %s)'], ['stop robot-drone', 'robot.stop()'], ['turn robot-drone {}', 'robot.turn("%s")'], ['turn robot {} speed {}', 'robot.turn("%s", %s)'], ['take off drone', 'robot.take_off()'], ['land drone', 'robot.land()'], ['frontal laser distance', 'robot.get_laser_distance()'], ] def is_conditional(sentence): """ Returns if a sentence is conditional or not. @param sentence: The sentence to check. @return: True if it has a conditional, False otherwise. """ if "if" in sentence: return True return False def similar(a, b): """ Returns the ratio value comparing two sentences. @param a: First sentence. @param b: Second sentence. @return: The ratio of the similarity. """ return SequenceMatcher(None, a, b).ratio() def sentence_mapping(sentence, threshold=None): """ Maps a sentence and returns the original and the mapped. @param sentence: The sentence to map. @return: The original sentence and the mapped sentence. """ found = False options = [] original = None translation = None # first look for general blocks for elem in GENERAL: if elem[0][:3] == sentence.replace(' ', '')[:3]: options.append(elem) found = True # then look for robotics blocks for elem in ROBOTICS: if elem[0][:3] == sentence.replace(' ', '').replace('(', '')[:3]: options.append(elem) found = True if found: # select the option that better fits l = [(m[0], m[1], similar(sentence, m[0])) for m in options] original, translation, score = max(l, key=lambda item: item[2]) if threshold and score < threshold: return None, None # extract arguments p = compile(original) args = p.parse(sentence.replace(' ', '')) if args: args_aux = list(args) # look for more blocks for idx in range(len(args_aux)): new_ori, new_trans = sentence_mapping(args_aux[idx]) #sentence_mapping(args_aux[idx],0.8) --old if new_trans != None: args_aux[idx] = args_aux[idx].replace(new_ori, new_trans) #replace(args_aux[idx], new_trans) translation = translation % tuple(args_aux) return original, translation if __name__ == "__main__": # get current working directory path = os.getcwd() open_path = path[:path.rfind('scripts')] + 'data/' save_path = path[:path.rfind('scripts')] + 'src/scratch2jderobot/' if len(sys.argv) == 2: # template creation template = "\ #!/usr/bin/env python\n\ # -*- coding: utf-8 -*-\n\n\ import time\n\ import config\n\ import sys\n\ import comm\n\ import os\n\ import yaml\n\n\ from drone import Drone\n\ from robot import Robot\n\n\ def execute(robot):\n\ \ttry:\n\ \t%s\ except KeyboardInterrupt:\n\ \t\traise\n\n\ if __name__ == '__main__':\n\ \tif len(sys.argv) == 2:\n\ \t\tpath = os.getcwd()\n\ \t\topen_path = path[:path.rfind('src')] + 'cfg/'\n\ \t\tfilename = sys.argv[1]\n\n\ \telse:\n\ \t\tsys.exit(\"ERROR: Example:python my_generated_script.py cfgfile.yml\")\n\n\ \t# loading the ICE and ROS parameters\n\ \tcfg = config.load(open_path + filename)\n\ \tstream = open(open_path + filename, \"r\")\n\ \tyml_file = yaml.load(stream)\n\n\ \tfor section in yml_file:\n\ \t\tif section == 'drone':\n\ \t\t\t#starting comm\n\ \t\t\tjdrc = comm.init(cfg,'drone')\n\n\ \t\t\t# creating the object\n\ \t\t\trobot = Drone(jdrc)\n\n\ \t\t\tbreak\n\ \t\telif section == 'robot':\n\ \t\t\t#starting comm\n\ \t\t\tjdrc = comm.init(cfg,'robot')\n\n\ \t\t\t# creating the object\n\ \t\t\trobot = Robot(jdrc)\n\n\ \t\t\tbreak\n\ \t# executing the scratch program\n\ \texecute(robot)\n\n\ " # load the scratch project p = kurt.Project.load(open_path + sys.argv[1]) # show the blocks included for scriptable in p.sprites + [p.stage]: for script in scriptable.scripts: # exclude definition scripts if "define" not in script.blocks[0].stringify(): s = script print("Stringify:") sentences = [] for b in s.blocks: print(b.stringify()) sentences += b.stringify().split('\n') tab_seq = "\t" python_program = "" for s in sentences: # count number of tabs num_tabs = s.replace(' ', tab_seq).count(tab_seq) python_program += tab_seq * (num_tabs + 1) # pre-processing if there is a condition (operators and types) if is_conditional(s): s = s.replace("'", "").replace("=", "==") # mapping original, translation = sentence_mapping(s) # set the code if translation != None: python_program += translation else: cprint("[WARN] Block <%s> not included yet" % s, 'yellow') python_program += "\n" + tab_seq # join the template with the code and replace the tabs file_text = template % python_program file_text = file_text.replace(tab_seq, ' ' * 4) print("\n-------------------") cprint(file_text, 'green') print("-------------------\n") # save the code in a python file with the same name as sb2 file file_name = sys.argv[1].replace('.sb2','.py') f = open(save_path + file_name, "w") f.write(file_text) f.close() else: print( "ERROR: Number of parameters incorrect. Example:\n\tpython scratch2python.py hello_world.sb2")


----

相關推薦

使用Scratch2ROS進行機器人圖形程式設計學習

使用Scratch2和ROS進行機器人程式設計學習(適用於中小學機器人程式設計Scratch和ROS)參考JdeRobot的一篇詳細介紹,就可以實現上述的功能,需要安裝Scratch2、ROS Kinetic、Gazebo 7、JdeRobot、Python2.7等。通過將S

ROS(indigo) 用於機器人控制的圖形程式設計工具--code_it robot_blockly

0 簡介: 程式語言有彙編,高階語言,解釋語言等,現在圖形化程式設計也越來越流行。圖形化程式設計簡單易學。8年前,微軟推出了VPL用於機器人程式設計,如Python和JavaScript都可以用圖形化框圖實現程式,有趣直觀。 當然也可以用Matlab的Simulink

ROSGazebo進行機器人模擬(二)

一.在Gazebo中使用ROS控制器 在本節中,我們將討論如何在Gazebo中讓機器人的每個關節運動。 為了讓關節動起來,我們需要分配一個ROS控制器,尤其是,我們需要為每個關節連上一個與transmission標籤內指定的硬體介面相容的控制器。 ROS控制器主要由一套反饋機構組成,可以接受某一設定點,並用執

使用pyplotseaborn進行可視

nbsp 只需要 高層 例子 port 目標 很多 觀察 pcl pyplot的一些知識 matplotlab中的對象: matplotlib是面向對象的,在畫圖的時候我們了解一些對象,對我們畫圖是有幫助的。繪圖的對象大致分為三層: backend_bases.Figur

從Python的turtle繪圖開始學習圖形程式設計

Turtle python2.6版本中後引入的一個簡單的繪圖工具,叫做海龜繪圖(Turtle Graphics),turtle庫是python的內部庫,使用匯入即可 :  import turtle 畫布 畫布就是turtle為我們展開用於繪圖區域, 我們可以設定它的

python圖形程式設計

例一,利用turtle庫(畫筆工具進行一個奧運五環的繪製) import turtle#海龜畫圖奧運五環 turtle.width(10)#確定畫筆寬度 turtle.color('blue') turtle.circle(50) turtle.penup() #類似 畫畫中擡筆的動作

Python 圖形程式設計例項

# coding=utf-8 import Tkinter as tk import time def processButton(): if v1.get() == 1: #print text.get("0.0", "end")

scratch圖形程式設計操作硬體

一,簡介 scratch是一款又麻省理工開發的圖形化程式設計軟體,這款軟體提供了可以使用javascript與scratch互動的介面,同時提供了一個socket埠和一系列的命令與應用程式互動,這裡我們講解如何通過python與scratch互動 二,說明

Digitalocean VPS centos 7安裝圖形介面KDEVNC實現遠端圖形操作

VPS遠端操作用的最多的是SSH,有時候一些特殊需求也要用到遠端圖形化操作,比如使用在VPS上使用瀏覽器訪問網站。本文以Digitalocean VPS為例分享如何安裝KDE和VNC實現遠端圖形介面訪問。如果要購買Digitalocean VPS,建議使用Digit

JVM 監控工具調優工具[圖形]

之前有總結過JVM監控和調優的工具JVM 監控工具和調優工具 不過這些都是命令列和設定JVM引數的方式,現在來總結歸納下一些圖形化的工具 JConsole JConsole 是一個基於JMX 的圖形監控工具,用於連線正在執行的JVM,可以以圖表化的形式顯示各

快速排序歸併排序 使用圖形介面的方式

2.8.1題目描述 使用圖形化介面的方式,顯示快速排序和歸併排序的效果。 2.8.2程式使用說明 Java version: 1.8.0_111 IDE:eclipse 歸併排序演示,Eclipse開啟MergeSortDemonstration.java檔案,右鍵run,

android圖形程式設計_計算BMI值

  第一次在android平臺上做圖形化程式設計,特做筆記,以便加深印象及後續查閱。此程式來自《深入淺出android》 1、              新建工程,file—new—android project,輸入工程名helloandroid01,package名稱為

使用 C++ MFC 進行多執行緒程式設計

程序是應用程式的執行例項。例如,雙擊“記事本”圖示時,將啟動執行“記事本”的程序。 執行緒是程序內的執行路徑。啟動“記事本”時,作業系統建立程序並開始執行該程序的主執行緒。此執行緒終止時,程序也終止。啟動程式碼以函式地址的形式將此主執行緒提供給作業系統。通常是所提供的main 函式或 WinMain 函式

processing圖形程式設計例項:打飛機遊戲

接上篇面向物件程式設計的思想寫一個考試的遊戲例項:打飛機 要求:地上一個可平動的加農炮,可發射數量有限的炮彈。天上有個random高度的飛機,以恆定速度迴圈飛。當炮彈擊中飛機時,加5發炮彈,加100分。炮彈耗光後遊戲結束。 首先進行面向物件分析,分析實體個數,實體包含的屬性

十分鐘學會Scratch圖形程式設計

一、概要 Scratch是麻省理工學院開發的供兒童或者初學者學習程式設計的開發平臺。其通過點選並拖拽的方式,完成程式設計,可以使兒童或者成人程式設計初學者學習程式設計基礎概念等。Scratch是一款積木式圖形程式設計軟體。 授權協議:GPLv2 開發語言:C/C++ 官網地址:https://scratch

圖形程式設計學習日誌01

1.obj檔案的讀取 #include<sstream> #include <string> #include <stdio.h> #include <stdlib.h> #include <math.h> #i

程式設計珠璣》程式碼之路6:將邏輯程式碼分離----編碼形式圖形輸出字母

好啦比如字母I,輸出為: xxxxxxxxx xxxxxxxxx xxxxxxxxx      xxx           xxx          &nb

Mysql的安裝圖形界面的使用

blog 由於 登錄 我的博客 目錄 服務 str img 應該 訪問mysql網址:https://dev.mysql.com/                     下面需要登錄你的oracle賬號進行下載就好~   下載之後是一解壓包形式存在的~   解壓之後的文件

springboot學習(三)————使用HttpMessageConverter進行http序列反序列

http 同時 服務 基本上 err cat rod nio decode 以下內容,如有問題,煩請指出,謝謝! 對象的序列化/反序列化大家應該都比較熟悉:序列化就是將object轉化為可以傳輸的二進制,反序列化就是將二進制轉化為程序內部的對象。序列化/反序列化主要體現在

aria2下載工具命令行圖形界面使用

ipa -o size alt ads 完成後 1-1 今天 none 如圖是搭建好圖形化界面下載軟件的一個截圖,可以看到界面很是熟悉的感覺。下面就開始我們今天的教程吧。Question?這是個啥東西?命令行怎麽用?圖形化怎麽用? Answer:aria2就是個下載軟件,具