Skip to content

Instantly share code, notes, and snippets.

@yubeneko
Created October 31, 2019 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yubeneko/f6f9162e29dcf3eb94a46aa3e975b4e8 to your computer and use it in GitHub Desktop.
Save yubeneko/f6f9162e29dcf3eb94a46aa3e975b4e8 to your computer and use it in GitHub Desktop.
Unityから送られてくる角度データ受信し、Arduinoに送信するスクリプト。
#coding:utf-8
import threading
import time
import signal
import sys
import serial
from socket import socket, AF_INET, SOCK_DGRAM
HOST = ''
PORT = 60000
is_running = True
angle_data = bytes(b'')
# UDP通信部
sock = socket(AF_INET, SOCK_DGRAM)
def udp_communication ():
global is_running
global sock
global angle_data
sock.bind((HOST, PORT))
try:
while is_running:
msg, address = sock.recvfrom(64) # 64はバッファのサイズ
print(f"message: {msg}\nfrom: {address}")
angle_data = msg
except KeyboardInterrupt:
print ("Keyboard Interrupt Exception")
# シリアル通信部
ser = serial.Serial('/dev/ttyACM0', 115200, timeout=None)
def serial_communication ():
global is_running
global ser
global angle_data
interbal = 0.03
try:
while is_running:
ser.write(angle_data)
time.sleep(interbal)
except KeyboardInterrupt:
print ("Keyboard Interrupt Exception")
def interuppt_handler(signum, frame):
global is_running
global sock
global ser
print ("Signal handler!!!")
is_running = False
ser.close()
sock.close()
sys.exit(-1)
signal.signal(signal.SIGINT, interuppt_handler)
if __name__ == "__main__":
threads = [threading.Thread(target=serial_communication),
threading.Thread(target=udp_communication)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment