pythonからscratchへデータ送信方法(pythonからのメッセージ内容に応じて分岐)
スポンサーリンク

pythonで得たセンサー情報をscratchへ送る方法
参考
- Communicating to Scratch via Python with a GUI
- Interfacing ROS with Scratch
- socket — Low-level networking interface
- Communicating to Scratch via Python
- Python in Scratch 2.0
- py-scratchモジュールでもできるみたい
1) Scratchの設定
以下の設定をする。左側の「遠隔センサーを有効にする」ってことろ。(右クリックででるよ)

OKを押す

2) pythonスクリプトの作成
ソース。テキストエディタで、program.pyで保存。
from array import array
import socket
import time
import sys
from Tkinter import Tk
from tkSimpleDialog import askstring
root = Tk()
root.withdraw()
PORT = 42001
#HOST = askstring('Scratch Connector', 'IP:')
HOST = 'localhost'
if not HOST:
sys.exit()
print("connecting...")
scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scratchSock.connect((HOST, PORT))
print("connected")
def sendScratchCommand(cmd):
n = len(cmd)
a = array('c')
a.append(chr((n >> 24) & 0xFF))
a.append(chr((n >> 16) & 0xFF))
a.append(chr((n >> 8) & 0xFF))
a.append(chr(n & 0xFF))
scratchSock.send(a.tostring() + cmd)
while True:
msg = askstring('Scratch Connector', 'Send Broadcast:')
if msg:
sendScratchCommand('broadcast "' + msg + '"')


