モータードライバー(TA7291P)、デュアルモーター、単三乾電池、ラズパイの4つをブレッドボード経由で配線します。
最初に[readchar]をインストールします。$ sudo pip install readchar
下記のプログラムを実行します。保存したファイル名がtank.pyの場合は、ターミナルのコマンドで $ python tank.py で実行します。
#!/usr/bin/env python # -*- coding: utf-8 -*- import RPi.GPIO as GPIO # GPIOを使う準備 import sys # Linuxコマンドを使う準備 import time # 時間系のコマンドを使う準備 import readchar # キーボード入力を調べる準備 constLeftPWM = 17 # GPIO番号 constLeftIN1 = 27 constLeftIN2 = 22 constRightPWM = 16 constRightIN1 = 20 constRightIN2 = 21 GPIO.setwarnings( False ) # 警告を表示させない(過去にGPIOを使っていると警告表示される) GPIO.setmode( GPIO.BCM ) # GPIO番号で命令する GPIO.setup( constLeftPWM, GPIO.OUT ) # GPIO17を出力モードにする GPIO.setup( constLeftIN1, GPIO.OUT ) # GPIO27 〃 (以下同じ) GPIO.setup( constLeftIN2, GPIO.OUT ) GPIO.setup( constRightPWM, GPIO.OUT ) GPIO.setup( constRightIN1, GPIO.OUT ) GPIO.setup( constRightIN2, GPIO.OUT ) pwmLeft = GPIO.PWM( constLeftPWM, 50 ) #50Hz pwmLeft.start( 0.0 ) pwmRight = GPIO.PWM( constRightPWM, 50 ) #50Hz pwmRight.start( 0.0 ) def moveForward(): GPIO.output( constLeftIN1, 1 ) GPIO.output( constLeftIN2, 0 ) GPIO.output( constRightIN1, 1 ) GPIO.output( constRightIN2, 0 ) def speedSlow(): pwmLeft.ChangeDutyCycle( 50 ) pwmRight.ChangeDutyCycle( 50 ) def speedHigh(): pwmLeft.ChangeDutyCycle( 100 ) pwmRight.ChangeDutyCycle( 100 ) def moveBack(): GPIO.output( constLeftIN1, 0 ) GPIO.output( constLeftIN2, 1 ) GPIO.output( constRightIN1, 0 ) GPIO.output( constRightIN2, 1 ) def moveLeft(): GPIO.output( constLeftIN1, 0 ) GPIO.output( constLeftIN2, 1 ) GPIO.output( constRightIN1, 1 ) GPIO.output( constRightIN2, 0 ) def moveRight(): GPIO.output( constLeftIN1, 1 ) GPIO.output( constLeftIN2, 0 ) GPIO.output( constRightIN1, 0 ) GPIO.output( constRightIN2, 1 ) def moveStop(): GPIO.output( constLeftIN1, 0 ) GPIO.output( constLeftIN2, 0 ) GPIO.output( constRightIN1, 0 ) GPIO.output( constRightIN2, 0 ) def end(): pwmLeft.stop() pwmRight.stop() GPIO.cleanup() sys.exit(0) ###################################### # メインルーチン ###################################### if __name__ == '__main__': try: while 1: kb = readchar.readchar() sys.stdout.write(kb) if kb == 'w': speedHigh() moveForward() if kb == 'z': speedSlow() moveBack() if kb == 'a': speedSlow() moveLeft() if kb == 's': speedSlow() moveRight() if kb == 'x': moveStop() if kb == 'q': end() #time.sleep(3) except KeyboardInterrupt: moveStop() end()
プログラムの実行は python [ファイル名] だよ。
$ python tank.py [w]キーで進む [x]キーでストップ
動かすときは電源をオンにしますが、しまっておく時は電源をオフにしてください。