import smbus WHICH_BUS = 0 # RPi Rev1 board ADDR = 0x5a # default MPR121 address (of 4 possible) # MPR121 registers MHD_R = 0x2b NHD_R = 0x2c NCL_R = 0x2d FDL_R = 0x2e MHD_F = 0x2f NHD_F = 0x30 NCL_F = 0x31 FDL_F = 0x32 ELE0_T = 0x41 ELE0_R = 0x42 ELE1_T = 0x43 ELE1_R = 0x44 ELE2_T = 0x45 ELE2_R = 0x46 ELE3_T = 0x47 ELE3_R = 0x48 ELE4_T = 0x49 ELE4_R = 0x4a ELE5_T = 0x4b ELE5_R = 0x4c ELE6_T = 0x4d ELE6_R = 0x4e ELE7_T = 0x4f ELE7_R = 0x50 ELE8_T = 0x51 ELE8_R = 0x52 ELE9_T = 0x53 ELE9_R = 0x54 ELE10_T = 0x55 ELE10_R = 0x56 ELE11_T = 0x57 ELE11_R = 0x58 AFE1 = 0x5c AFE2 = 0x5d ECR = 0x5e GPIO_CTL0 = 0x73 GPIO_CTL1 = 0x74 GPIO_DAT = 0x75 GPIO_DIR = 0x76 GPIO_EN = 0x77 GPIO_SET = 0x78 GPIO_CLR = 0x79 GPIO_TOG = 0x7a AUTO_CFG0 = 0x7b AUTO_CFG1 = 0x7c AUTO_USL = 0x7d AUTO_LSL = 0x7e AUTO_TL = 0x7f class MPR121(object): def __init__(self, which, addr=ADDR): self.bus = smbus.SMBus(which) self.addr = addr def write(self, reg, value): self.bus.write_byte_data(self.addr, reg, value) def read(self, reg): ### this doesn't work on MPR121. requires a REPEATED START. return self.bus.read_byte_data(self.addr, reg) def config(self): # ensure the MPR121 is in Stop Mode self.write(ECR, 0x00) self.write(MHD_R, 0x01) self.write(NHD_R, 0x01) self.write(NCL_R, 0x00) self.write(FDL_R, 0x00) self.write(MHD_F, 0x01) self.write(NHD_F, 0x01) self.write(NCL_F, 0xff) self.write(FDL_F, 0x02) self.write(ELE0_T, 0x0f) self.write(ELE0_R, 0x0a) self.write(ELE1_T, 0x0f) self.write(ELE1_R, 0x0a) self.write(ELE2_T, 0x0f) self.write(ELE2_R, 0x0a) self.write(ELE3_T, 0x0f) self.write(ELE3_R, 0x0a) self.write(ELE4_T, 0x0f) self.write(ELE4_R, 0x0a) self.write(ELE5_T, 0x0f) self.write(ELE5_R, 0x0a) self.write(AFE2, 0x04) # enable ELE11 as CMOS output, set to GND, then enable it self.write(GPIO_CTL0, 0x00) # CTL0 self.write(GPIO_CTL1, 0x00) # CTL1 self.write(GPIO_DIR, 0x80) # DIR self.write(GPIO_DAT, 0x00) # DAT self.write(GPIO_EN, 0x80) # EN # Set up the auto-config self.write(AUTO_USL, 0xc9) # for 3.3V operation self.write(AUTO_TL, 0xb5) # 90% of USL self.write(AUTO_LSL, 0x83) # 65% of USL self.write(AUTO_CFG0, 0x0b) # note: AFES == FFI self.write(AUTO_CFG1, 0x00) # Turn on first 11 electrodes, and run auto-config self.write(ECR, 0x0b) def reset(self): self.write(0x80, 0x63) def touches(self): try: return self.bus.read_word_data(self.addr, 0) except IOError: return 0x0000 def spin(self): import time while 1: print '0x%04x' % (self.touches(),) time.sleep(0.1) def run(): chip = MPR121(WHICH_BUS) chip.config() ### do something