from machine import Pin
import time
di=Pin(12,Pin.IN,Pin.PULL_DOWN)
do=Pin(14,Pin.OUT, )
cs=Pin(27,Pin.OUT,) #PULL_UP
clk=Pin(26,Pin.OUT,)
#D0 16 dat=DI
#D2 04 cmd=DO
#D3 0 CS =CS
#D4 02 CLK=CLK
def DO_H():
do.value(1)
def DO_L():
do.value(0)
def CS_H ():
cs.value(1)
def CS_L():
cs.value(0)
def CLK_H ():
clk.value(1)
def CLK_L():
clk.value(0)
#These are our button constants
PSB_SELECT = 1
PSB_L3 = 2
PSB_R3 = 3
PSB_START = 4
PSB_PAD_UP = 5
PSB_PAD_RIGHT = 6
PSB_PAD_DOWN = 7
PSB_PAD_LEFT = 8
PSB_L2 = 9
PSB_R2 = 10
PSB_L1 = 11
PSB_R1 = 12
PSB_GREEN = 13
PSB_RED = 14
PSB_BLUE = 15
PSB_PINK = 16
PSB_TRIANGLE = 13
PSB_CIRCLE = 14
PSB_CROSS = 15
PSB_SQUARE = 26
PSS_RX = 5 #x
PSS_RY = 6
PSS_LX = 7
PSS_LY = 8
mask=[
PSB_SELECT,
PSB_L3,
PSB_R3 ,
PSB_START,
PSB_PAD_UP,
PSB_PAD_RIGHT,
PSB_PAD_DOWN,
PSB_PAD_LEFT,
PSB_L2,
PSB_R2,
PSB_L1,
PSB_R1 ,
PSB_GREEN,
PSB_RED,
PSB_BLUE,
PSB_PINK]
comd=[0x01,0x42]
data=[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
def ps2_init():
CLK_H()
DO_H()
time.sleep_ms(10)
def ps2_cmd(cmd):
global data
data[1]=0
for ref in (1,2,4,8,16,32,64,128):
if ( ref & cmd):
DO_H()
else:
DO_L()
CLK_H ()
time.sleep_us(50)
CLK_L()
time.sleep_us(50)
CLK_H ()
if(di.value()==1):
data[1]=ref|data[1]
def ps2_red():
global data
global comd
CS_L()
ps2_cmd(comd[0])
ps2_cmd(comd[1])
CS_H()
if(data[1]==57):
return 0#red light
else:
return 1#not red
def ps2_read():
global data
global comd
byte=0
ref=0x01
CS_L()
ps2_cmd(comd[0])
ps2_cmd(comd[1])
for byte in (2,3,4,5,6,7,8):
for ref in (1,2,4,8,16,32,64,128):
CLK_H ()
CLK_L()
time.sleep_us(50)
CLK_H ()
if(di.value()==1):
data[byte]= ref|data[byte]
time.sleep_us(50)
CS_H ()
def ps2_clear():#ok
global data
for i in range(0,9,1):
data[i]=0
def ps2_andata(button):
global data
return data[button]
def ps2_key():
global data
global mask
ps2_clear()
ps2_read()
handkey=(data[4]<<8)|data[3]
for index in (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15):
if (( handkey&(1<<(mask[index]-1)))==0):
return index+2
return 0