# 라즈베리파이로 조이스틱 컨트롤하기
# -*- coding: utf-8 -*-
import time
import spidev
delay = 0.5
sw_channel=0
vrx_channel=1
vry_channel=2
spi=spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz=100000
def readadc(adcnum):
if adcnum > 7 or adcnum < 0:
return -1
r = spi.xfer([1,8+adcnum<<4,0])
data=((r[1]&3)<<8)+r[2]
return data
while True:
vrx_pos = readadc(vrx_channel)
vry_pos = readadc(vry_channel)
sw_val = readadc(sw_channel)
print("x:{} Y:{} SW:{}".format(vrx_pos, vry_pos, sw_val))
time.sleep(delay)
# 조이스틱으로 웹사이트 게임 컨트롤하기
파이썬 코드 :
import paho.mqtt.client as mqtt
import pyautogui #pip install pyautogui
msg1 = ""
msg2 = ""
def on_message(client, userdata, message):
global msg1, msg2
print("message : ", str(message.payload.decode("utf-8")))
msg1 = message.payload.decode("utf-8")
print("msg1 : ", msg1)
if msg1 != msg2:
print(msg1 + " " + msg2)
if msg1 == "up":
pyautogui.press("up")
elif msg1 == "down":
pyautogui.press("down")
elif msg1 == "left":
pyautogui.press("left")
elif msg1 == "right":
pyautogui.press("right")
msg2 = msg1
broker_address = "[본인 아이피]"
client1 = mqtt.Client("minji", transport='websockets')
client1.connect(broker_address, 9001)
client1.subscribe("minji")
client1.on_message = on_message
client1.loop_forever()
라즈베리파이 코드
# -*- coding: utf-8 -*-
import time
import spidev
import paho.mqtt.client as mqtt
mqttc = mqtt.Client("client", transport='websockets')
mqttc.connect("[설정한 IP]", 9001)
mqttc.publish("minji", "minji", 1)
delay = 0.5
sw_channel = 0
vrx_channel = 1
vry_channel = 2
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 100000
def readadc(adcnum):
if adcnum > 7 or adcnum < 0:
return -1
r = spi.xfer([1, 8 + adcnum << 4, 0])
data = ((r[1] & 3) << 8) + r[2]
return data
qos = 1
up = False
down = False
left = False
right = False
i = 0
# 무한루프
while True:
vrx_pos = readadc(vrx_channel)
vry_pos = readadc(vry_channel)
sw_val = readadc(sw_channel)
if vrx_pos > 920:
if right == False:
print("right")
mqttc.publish("minji", "right", qos)
up = False
down = False
left = False
right = True
i += 1
if vrx_pos < 100:
if left == False:
print("left")
mqttc.publish("minji", "left", qos)
up = False
down = False
left = True
right = False
i += 1
if vry_pos > 920:
if up == False:
print("up")
mqttc.publish("minji", "up", qos)
up = True
down = False
left = False
right = False
i += 1
if vry_pos < 100:
if down == False:
print("down")
mqttc.publish("minji", "down", qos)
up = False
down = True
left = False
right = False
i += 1
time.sleep(0.1)
print("x:{} Y:{} SW:{}".format(vrx_pos, vry_pos, sw_val))