Created
September 12, 2021 00:18
-
-
Save ScienceElectronicsFun/28726cebfb7a78f0cfaf0bf78a0dd666 to your computer and use it in GitHub Desktop.
Pmod Joystick code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import machine | |
import utime | |
import ustruct | |
import sys | |
from machine import Pin | |
#PMOD2 Joystick | |
#4 pins | |
led_up = Pin(13, Pin.OUT) | |
led_down = Pin(15, Pin.OUT) | |
led_right = Pin(12, Pin.OUT) | |
led_left = Pin(14, Pin.OUT) | |
led_up.value(0) | |
led_right.value(0) | |
led_down.value(0) | |
led_left.value(0) | |
cs = machine.Pin(17, machine.Pin.OUT) | |
spi = machine.SPI(0, | |
baudrate= 10000, | |
bits = 8, | |
firstbit=machine.SPI.MSB, | |
sck=machine.Pin(18), | |
mosi=machine.Pin(19), | |
miso=machine.Pin(16)) | |
def getPosition(spi, cs): | |
msg = bytearray() | |
msg.append(0xC0) | |
msg.append(0x00) | |
msg.append(0x00) | |
msg.append(0x00) | |
msg.append(0x00) | |
cs.value(0) | |
spi.write(msg) | |
cs.value(1) | |
utime.sleep_us(25) | |
cs.value(0) | |
spi.write(msg) | |
data = spi.read(5) | |
cs.value(1) | |
return data | |
while 1: | |
data = getPosition(spi, cs) | |
print (data) | |
print (data[0]) | |
print (data[1]) | |
if data[0] > 225: | |
print ('RIGHT') | |
led_right.value(1) | |
else: | |
led_right.value(0) | |
if data[0] < 50: | |
print ('LEFT') | |
led_left.value(1) | |
else: | |
led_left.value(0) | |
if data[1] > 225: | |
print ('DOWN') | |
led_down.value(1) | |
else: | |
led_down.value(0) | |
if data[1] < 55: | |
print ('UP') | |
led_up.value(1) | |
else: | |
led_up.value(0) | |
utime.sleep(0.05) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment