关闭

使用Scratch2和ROS进行机器人图形化编程学习

标签: ROSscratchpython人工智能机器人
958人阅读 评论(0) 收藏 举报
分类:

使用Scratch2和ROS进行机器人编程学习(适用于中小学机器人编程Scratch和ROS)

Scratch是一款由麻省理工学院(MIT)设计开发的少儿编程工具Python是近年来非常流行的机器人和人工智能编程语言ROS是机器人操作系统

参考JdeRobot的一篇详细介绍,就可以实现上述的功能,需要安装Scratch2、ROS Kinetic、Gazebo 7、JdeRobot、Python2.7等。

通过将Scratch2图形化编程语言转为Python,然后通过ROS消息机制控制Gazebo或实际机器人。

上海久牵志愿者服务社2017中国困境儿童关注日

~~信息化智能化时代下平等受教育的权利~~

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__ = "raules@gmail.com"
__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")


----


0
0
查看评论

TX1刷机ubuntu14.04 以及安装ros indigo

TX1刷机教程参考:http://blog.csdn.net/Jalong_Ma/article/details/52743923 如果需要安装ubuntu14.04 64位或32位请下载JetPack 2.2.1,安装ubuntu14.04 32位与64位都是下载这个文件,具体安装多少位的系统...
  • Start_From_Scratch
  • Start_From_Scratch
  • 2017-02-24 16:40
  • 801

ROS(indigo) 用于机器人控制的图形化编程工具--code_it robot_blockly

0 简介: 编程语言有汇编,高级语言,解释语言等,现在图形化编程也越来越流行。图形化编程简单易学。8年前,微软推出了VPL用于机器人程序设计,如Python和JavaScript都可以用图形化框图实现程序,有趣直观。 视频介绍教程,请参考:http://v.youku.com/v_show/...
  • roslei
  • roslei
  • 2016-12-04 10:30
  • 1984

ROS(indigo) 用于机器人控制的图形化编程工具--code_it robot_blockly

0 简介:编程语言有汇编,高级语言,解释语言等,现在图形化编程也越来越流行。图形化编程简单易学。8年前,微软推出了VPL用于机器人程序设计,如Python和JavaScript都可以用图形化框图实现程序,有趣直观。图1LiveBlox就是典型的一种,具体参考之前博客:http://blog.csdn...
  • ZhangRelay
  • ZhangRelay
  • 2016-11-03 14:50
  • 4792

ROS开发环境之Qt Creator

http://my.phirobot.com/blog/2013-12-ros_ide_qtcreator.html QtCreator安装 QtCreator安装方式很多,本文以Qt 5.2.0为例,我直接下载离线安装程序安装。 下载安装 从http://qt-project....
  • dxuehui
  • dxuehui
  • 2015-03-26 11:43
  • 8618

如何使用Qt插件在Qt中进行ROS开发

一、前言本文介绍一种Qt下进行ROS开发的完美方案,使用的是ros-industrial的Levi-Armstrong在2015年12月开发的一个Qt插件ros_qtc_plugin,这个插件使得Qt“新建项目”和“新建文件”选项中出现ROS的相关选项,让我们可以直接在Qt下创建、编译、调试ROS项...
  • u013453604
  • u013453604
  • 2016-08-11 20:43
  • 18729

如何用Qt对ROS项目进行调试及创建GUI界面

一、前言本文详细介绍了利用CMakeLists.txt文件把ROS项目导入到QtCreator进行代码编写和调试的过程,文末还介绍了ROS中使用Qt界面的方法 这种导入ROS项目到Qt的方法也适用于其他CMake创建的项目,这种方案缺点是导入项目后无法直接在Qt下面新建文件和package到项...
  • u013453604
  • u013453604
  • 2016-08-09 23:48
  • 12019

ros 安装 qt creator plugin

步骤一:安装好ros,新建工作空间,在测试ros可以正常使用的情况下进行下一步; 步骤二:安装qt creator ros plugin,详情请见开发者连接:https://ros-industrial.github.io/ros_qtc_plugin/index.html 步骤三:测试是否可以...
  • nicai41
  • nicai41
  • 2017-12-22 11:37
  • 82

How install Qt Creator for ubuntu 16.04

This tutorial was done with the following software versions: Ubuntu 16.04 LTSQt Creator 3.5.1Qt 5.5.1 Install Qt sudo apt-get install build-essential...
  • wuguangbin1230
  • wuguangbin1230
  • 2017-09-04 15:30
  • 443

基于Qt(Linux)的ROS开发环境配置

前言: 有多种IDE进行ROS开发:http://wiki.ros.org/IDEs 两种方式实现在Qt下开发ROS: Qt Creator Qt Creator Plugin for ROS本文测试环境 ROS版本:indigo Qt版本:5.7.0(Creator 4.0.2) ...
  • hzwwpgmwy
  • hzwwpgmwy
  • 2017-06-21 23:07
  • 460

Qt Creator 打开 catkin 工程之添加ROS环境变量

修改Qt Creator快捷方式,使从快捷方式启动Qt Creator的同时加载ROS环境变量。打开terminal,输入下面的命令:gedit ~/.local/share/applications/DigiaQtOpenSource-qtcreator.desktop这条命令将打开DigiaQt...
  • HERO_CJN
  • HERO_CJN
  • 2017-08-11 17:29
  • 325
    个人资料
    • 访问:895108次
    • 积分:11560
    • 等级:
    • 排名:第1590名
    • 原创:237篇
    • 转载:23篇
    • 译文:49篇
    • 评论:665条
    博客专栏
    最新评论