0

Tengo este código es una grilla de 3x3 con switches reed.

Lo que quiero es que al levantar un imán y llevarlo a la otra posición. se imprima en pantalla de donde lo tome y donde lo puse.

Me gustaría que dijera, por ejemplo b3c3.

Creo que esto se puede lograr si puedo guardar la variable "w" en algún lado, porque pienso se pierde su contenido cada vez que inicia el while. Luego si puedo guardar esta variable el tipo de respuesta b3c3 la puedo obtener de acá:

chcol[(w+2)%3], (int((w-1)/3))+1 

ahí obtendría por ejemplo "b3" y si logro guardar el segundo movimiento tendría "c3", por ejemplo.

Intenté guardar la "w" en otra variable pero no sé cómo hacerlo la verdad. No puedo diferenciarlo. Esto es lo que modifiqué en mi intento de guardar "w" en otra variable. Es decir, cree la variable "m". Pero si es como creo, cada vez que se inicia el while pierdo el primer valor.

for l in range(2):  #loops round both registers of MCP23017
    a = bus.read_byte_data(i2cadd,GPIOn[l])
    if a != mbrd[l]: # there has been a change
      c = a ^ mbrd[l]  # bitwise operation copies the bit if it is set in one operand but not both.
      dirx = "Close"
      y = math.frexp(c)[1]  # calculates integer part of log base 2, which is binary bit position
      m=y+l*8
      x =int((m-1)/3)+1   # anodes numbers starts 1
      y =  (2+m)%3   # cathodes number start 0
      if a > mbrd[l] : dirx = "Open"  # if the number gets bigger a 0 has changed to a 1
      y = math.frexp(c)[1]  # calculates integer part of log base 2, which is binary bit position
      w=y+l*8
      x =int((w-1)/3)+1   # anodes numbers starts 1
      y =  (2+w)%3   # cathodes number start 0
 
      if dirx == "Close":
        display.set_pixel(x, y, 1)  # switch on the LED
        lcd.lcd_clear()
        #lcd.message('Hello\nworld!')
        lcd.lcd_display_string('Square: ',2,)
        lcd.lcd_display_string(str(w),2,8)
 
 
      if dirx == "Open":
        display.set_pixel(x, y, 0)  # switch off the LED
        lcd.lcd_clear()
 
      display.write_display()
      print "square", w, " Reed Switch " , dirx    # chcol[(w+2)%3], (int((w-1)/3))+1
      print chcol[(m+2)%3], (int((m-1)/3))+1,chcol[(w+2)%3], (int((w-1)/3))+1
 
      mbrd[l]=a  # update the current state of the board
      time.sleep(0.1)

Esto da como resultado este tipo de respuesta

square 8 reed switch Close
B 3 B 3
square 8 reed switch Open
B 3 B 3
square 9 reed switch Close
C 3 C 3.

Gracias a todos

Este es el código original sin mis modificaciones.

# Test Module for NOX : Noughts and crosses / Tic Tac Toe Game
# lights LED when reed switch closes

import smbus
import time
import math
from Adafruit_LED_Backpack import Matrix8x8
import Adafruit_CharLCD as LCD

#Display and Keypad setup

# Initialize the LCD using the pins
lcd = LCD.Adafruit_CharLCDPlate()

# create some custom characters
lcd.create_char(1, [2, 3, 2, 2, 14, 30, 12, 0])
lcd.create_char(2, [0, 1, 3, 22, 28, 8, 0, 0])
lcd.create_char(3, [0, 14, 21, 23, 17, 14, 0, 0])
lcd.create_char(4, [31, 17, 10, 4, 10, 17, 31, 0])
lcd.create_char(5, [8, 12, 10, 9, 10, 12, 8, 0])
lcd.create_char(6, [2, 6, 10, 18, 10, 6, 2, 0])
lcd.create_char(7, [31, 17, 21, 21, 21, 21, 17, 31])
lcd.clear()
lcd.message('RPI NOX game\nWelcome')


#LED setup
# Create display instance on default I2C address (0x70) and bus number.
display = Matrix8x8.Matrix8x8(address=0x70, busnum=1)
# check using I2cdetect -y 1  to make sure the address is 70, if not edit the line above to change it
# the correct address

# Initialize the display. Must be called once before using the display.
display.begin()
display.clear()
display.write_display()
# MCP23017  setup
# this program scans both registers one device, giving 2 x 8 = 16 inputs, only 9 of these are used in the NOX program 
#bus = smbus.SMBus(0)  # Rev 1 Pi uses 0
bus = smbus.SMBus(1) # Rev 2 Pi uses 1
# this program scans both the A and B registers of one MCP23017 port exapander and returns changes 
mbrd = [0xFF,0xFF]   # mbrd is the noughts and crosses board  this sets them to 11111111 : open w
chcol =["A","B","C"]  # column labels
i2cadd=0x21 # the I2c Device address of the MCP23017s (A0-A2)
GPIOn = [0x12, 0x13]
IODIRA = 0x00 # APin direction register for first 8 ie 1 = input or 2= output
IODIRB = 0x01 # B Pin direction register
GPIOA  = 0x12 # Register for inputs
GPIOB  = 0x13 # B Register for inputs
GPPUA= 0x0C  # Register for Pull ups A
GPPUB= 0x0D  # Register for Pull ups B

# Set all A 8 GPA pins as  input. ie set them to 1 oXFF = 11111111
bus.write_byte_data(i2cadd,IODIRA,0xFF)
# Set pull up on GPA pins .ie from default of 0 to 11111111
bus.write_byte_data(i2cadd,GPPUA,0xFF)
# Set all B 8 GPB pins as  input. ie set them to 1 oXFF = 11111111
bus.write_byte_data(i2cadd,IODIRB,0xFF)
# Set pull up on GPB pins .ie from default of 0 to 11111111
bus.write_byte_data(i2cadd,GPPUB,0xFF)

print "starting"
# now look for a change

# Loop until user presses CTRL-C
while True:
  # read the 8 registers

  for l in range(2):  #loops round both registers of MCP23017
    a = bus.read_byte_data(i2cadd,GPIOn[l])
    if a != mbrd[l]: # there has been a change
      c = a ^ mbrd[l]  # bitwise operation copies the bit if it is set in one operand but not both.
      dirx = "Close"
      if a > mbrd[l] : dirx = "Open"  # if the number gets bigger a 0 has changed to a 1
      y = math.frexp(c)[1]  # calculates integer part of log base 2, which is binary bit position
      w=y+l*8
      x =int((w-1)/3)+1   # anodes numbers starts 1
      y =  (2+w)%3   # cathodes number start 0
      
      if dirx == "Close":
        display.set_pixel(x, y, 1)  # switch on the LED
        lcd.clear()
        #lcd.message('Hello\nworld!')
        lcd.message('Square: \n')
        lcd.message(str(w))
                  
      if dirx == "Open":
        display.set_pixel(x, y, 0)  # switch off the LED
        lcd.clear()
        
      display.write_display()
      print "square", w, " Reed Switch " , dirx    # chcol[(w+2)%3], (int((w-1)/3))+1
      
      mbrd[l]=a  # update the current state of the board
      time.sleep(0.1)
3
  • 9acca9 si quieres eliminar tu pregunta puedes hacerlo previa eliminación de tu respuesta. Pero no debes editarla para vandalizarla, eso no está permitido en el sitio.
    – Pikoh
    el 25 ago. 2020 a las 8:01
  • 9acca9 he eliminado tu otra pregunta. Probablemente no podías eliminarla si no te has registrado en el sitio correctamente. En ese caso, puedes reportarnos a los moderadores para que, si se cumplen las condiciones para que sea eliminada, la eliminemos nosotros. Un saludo.
    – Pikoh
    el 26 ago. 2020 a las 6:23
  • @Pikoh Hola. Muchas gracias. Podrías eliminar todas mis preguntas? En cuanto a el registro, sí, la verdad que no sé por qué quedó truncado... lo intenté varias veces pero me aparece todo el tiempo como que no está completo el registro (la verdad que no entiendo por qué). Muchas gracias.
    – 9acca9
    el 29 ago. 2020 a las 3:50

1 respuesta 1

0

logré obtener lo que deseaba de la siguiente manera. Por cierto, si alguien quiere criticarlo, se agradece.

Primero hice una lista vacía:

lst=[]

luego una variable como esta

move = chcol[(w+2)%3] + str(int((w-1)/3)+1)

y salvo la variable en la lista

lst.append(move)

Agregé un nuevo if para imprimir en pantalla y borrar el contenido de la lista:

if len(lst)== 2: 
      print(''.join(lst))
      lst.pop(0)
      lst.pop(0)

De esta manera cuando tiene dos valores, primero los imprime y luego vacía la lista.

Esto funciona, pero será correcto? habrá una manera "más correcta" de hacerlo?

Este es el código en su totalidad, por si no se entiende el contexto de los pedacitos de código:

# lights LED when reed switch closes

import smbus
import time
import math
from Adafruit_LED_Backpack import Matrix8x8
    
#LED setup
# Create display instance on default I2C address (0x70) and bus number.
display = Matrix8x8.Matrix8x8(address=0x70, busnum=1)
# check using I2cdetect -y 1  to make sure the address is 70, if not edit the line above to change it
# the correct address

# Initialize the display. Must be called once before using the display.
display.begin()
display.clear()
display.write_display()
# MCP23017  setup
# this program scans both registers one device, giving 2 x 8 = 16 inputs, only 9 of these are used in the NOX program 
#bus = smbus.SMBus(0)  # Rev 1 Pi uses 0
bus = smbus.SMBus(1) # Rev 2 Pi uses 1
# this program scans both the A and B registers of one MCP23017 port exapander and returns changes 
mbrd = [0xF8,0xFF]   # mbrd is the noughts and crosses board  this sets them to 11111111 : open w
chcol =["a","b","c"]  # column labels
i2cadd=0x21 # the I2c Device address of the MCP23017s (A0-A2)
GPIOn = [0x12, 0x13]
IODIRA = 0x00 # APin direction register for first 8 ie 1 = input or 2= output
IODIRB = 0x01 # B Pin direction register
GPIOA  = 0x12 # Register for inputs
GPIOB  = 0x13 # B Register for inputs
GPPUA= 0x0C  # Register for Pull ups A
GPPUB= 0x0D  # Register for Pull ups B

# Set all A 8 GPA pins as  input. ie set them to 1 oXFF = 11111111
bus.write_byte_data(i2cadd,IODIRA,0xFF)
# Set pull up on GPA pins .ie from default of 0 to 11111111
bus.write_byte_data(i2cadd,GPPUA,0xFF)
# Set all B 8 GPB pins as  input. ie set them to 1 oXFF = 11111111
bus.write_byte_data(i2cadd,IODIRB,0xFF)
# Set pull up on GPB pins .ie from default of 0 to 11111111
bus.write_byte_data(i2cadd,GPPUB,0xFF)

lst=[]


print "starting"
# now look for a change

# Loop until user presses CTRL-C
while True:
  # read the 8 registers

  for l in range(2):  #loops round both registers of MCP23017
    a = bus.read_byte_data(i2cadd,GPIOn[l])
    if len(lst)== 2: 
      print(''.join(lst))
      lst.pop(0)
      lst.pop(0)
  
    if a != mbrd[l]: # there has been a change
      c = a ^ mbrd[l]  # bitwise operation copies the bit if it is set in one operand but not both.
      dirx = "Close"
    
    if a > mbrd[l] : dirx = "Open"  # if the number gets bigger a 0 has changed to a 1
      y = math.frexp(c)[1]  # calculates integer part of log base 2, which is binary bit position
      w=y+l*8
      x =int((w-1)/3)+1   # anodes numbers starts 1
      y =  (2+w)%3   # cathodes number start 0
      
      if dirx == "Close":
        display.set_pixel(x, y, 1)  # switch on the LED
        lcd.clear()
        #lcd.message('Hello\nworld!')
        lcd.message('Square: \n')
        lcd.message(str(w))
                  
      if dirx == "Open":
        display.set_pixel(x, y, 0)  # switch off the LED
        lcd.clear()
        
      display.write_display()
      #print "square", w, " Reed Switch " , dirx    
      
      move = chcol[(w+2)%3] + str(int((w-1)/3)+1)
      
      lst.append(move)
      mbrd[l]=a  # update the current state of the board
      time.sleep(0.1)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.