pi2go - 将机器人移动90º或向前移动10厘米并停止?

时间:2016-03-06 21:14:47

标签: python raspberry-pi

我买了一台pi2go机器人,这太棒了,但我有一些问题,我想制作机器人

  1. 旋转左/右仅90º度并停止
  2. 移动Foward / Backward仅10厘米并停止
  3. 我想在python中执行4个脚本,就像left.pyforward.py一样。

    在pi2go帮助文件中有一个脚本,允许您使用键盘控制机器人,但我不希望我只想调用sudo python left.py一次并退出。

    以下是pi2go示例:

    import pi2go, time
    
    import sys
    import tty
    import termios
    
    UP = 0
    DOWN = 1
    RIGHT = 2
    LEFT = 3
    
    def readchar():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        if ch == '0x03':
            raise KeyboardInterrupt
        return ch
    
    def readkey(getchar_fn=None):
        getchar = getchar_fn or readchar
        c1 = getchar()
        if ord(c1) != 0x1b:
            return c1
        c2 = getchar()
        if ord(c2) != 0x5b:
            return c1
        c3 = getchar()
        return ord(c3) - 65  # 0=Up, 1=Down, 2=Right, 3=Left arrows
    
    speed = 30
    
    pi2go.init()
    
    try:
        while True:
            keyp = readkey()
            if keyp == 'w' or keyp == UP:
                pi2go.forward(speed)
                print 'Forward', speed
            elif keyp == 's' or keyp == DOWN:
                pi2go.reverse(speed)
                print 'Backward', speed
            elif keyp == 'd' or keyp == RIGHT:
                pi2go.spinRight(speed)
                print 'Spin Right', speed
            elif keyp == 'a' or keyp == LEFT:
                pi2go.spinLeft(speed)
                print 'Spin Left', speed
            elif keyp == '.' or keyp == '>':
                speed = min(100, speed+10)
                print 'Speed+', speed
            elif keyp == ',' or keyp == '<':
                speed = max (0, speed-10)
                print 'Speed-', speed
            elif keyp == ' ':
                pi2go.stop()
                print 'Stop'
            elif ord(keyp) == 3:
                break
    
    
        pi2go.cleanup()
    

    但是我想创建一个执行此操作并退出的脚本,例如:

    pi2go.spinLeft(100) 
    pi2go.stop()
    

2 个答案:

答案 0 :(得分:1)

我认为你的问题是你没有给马达任何时间转弯。如果我查看你的代码片段,你就会告诉电机向左旋转,然后立即停止电机。

尝试做类似的事情:

import time
import pi2go

pi2go.spinLeft(100)
time.sleep(1)
pi2go.stop()

让电机有时间去做他们的事情。

答案 1 :(得分:0)

您遗漏了初始化命令pi2go.init(),看起来您还遗漏了导入import模块的所有重要pi2go语句。

这应该有效:

import pi2go

pi2go.init()
pi2go.spinLeft(100) 
pi2go.stop()

pi2go.cleanup()

显然,我无法测试这段代码......除非你给我买机器人。 :)