"""Test the IO Board using a Raspberry Pi.""" try: import RPi.GPIO as GPIO except RuntimeError: print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script") import time import spidev spi = spidev.SpiDev() spi.open(0, 0) GPIO.setmode(GPIO.BOARD) if GPIO.getmode() == 11: mux_channels = [5, 6, 13] inp_channel = 19 relay_channels = [21, 20, 16, 12, 25, 24, 23, 18] else: mux_channels = [29, 31, 33] inp_channel = 35 relay_channels = [40, 38, 36, 32, 22, 18, 16, 12] GPIO.setup(mux_channels, GPIO.OUT) GPIO.setup(relay_channels, GPIO.OUT) GPIO.setup(inp_channel, GPIO.IN) input_mux = [ [], [0, 0, 0], # Input 1 [1, 0, 0], # Input 2 [0, 1, 0], # Input 3 [1, 1, 0], # Input 4 [0, 0, 1], # Input 5 [1, 0, 1], # Input 6 [0, 1, 1], # Input 7 [1, 1, 1], # Input 8 ] GPIO_mux = [ (), (GPIO.LOW, GPIO.LOW, GPIO.LOW), # 1 (GPIO.HIGH, GPIO.LOW, GPIO.LOW), # 2 (GPIO.LOW, GPIO.HIGH, GPIO.LOW), # 3 (GPIO.HIGH, GPIO.HIGH, GPIO.LOW), # 4 (GPIO.LOW, GPIO.LOW, GPIO.HIGH), # 5 (GPIO.HIGH, GPIO.LOW, GPIO.HIGH), # 6 (GPIO.LOW, GPIO.HIGH, GPIO.HIGH), # 7 (GPIO.HIGH, GPIO.HIGH, GPIO.HIGH) # 8 ] def relay_write(relay_number, status): """Write the specified status to the relay at the relay_number.""" write_val = GPIO.HIGH if status >= 1 else GPIO.LOW if relay_number <= 8 and relay_number >= 1: GPIO.output(relay_channels[relay_number - 1], write_val) return True else: print("CANNOT WRITE TO A RELAY THAT DOES NOT EXIST: {}".format(relay_number)) return False def relay_loop(): """Set all relays to 1 sequentially, then set all relays to 0 sequentially.""" for i in range(1, 9): relay_write(i, 1) time.sleep(1) for i in range(1, 9): relay_write(i, 0) time.sleep(1) def read_dig_in(io_port): """Read IO Board digital input.""" if io_port == 0 or io_port > 8: print("CANNOT READ A PORT THAT DOES NOT EXIST: {}".format(io_port)) return False GPIO.output(mux_channels, GPIO_mux[io_port]) return GPIO.input(inp_channel) == 0 def dig_in_loop(): """Read all digital inputs.""" for i in range(1, 9): print("DIGIN {} = {}".format(i, read_dig_in(i))) def read_analog_in(io_port, verbose=False): """Read IO Board digital input.""" global spi_bus if io_port < 1 or io_port > 4: print("CANNOT READ A PORT THAT DOES NOT EXIST: {}".format(io_port)) return False GPIO.output(mux_channels, GPIO_mux[io_port]) ok_status = False tries = 0 while (ok_status is False) and (tries < 5): GPIO.output(mux_channels, GPIO_mux[io_port]) x = spi.xfer2(bytearray([0, 0, 0])) if verbose: print((x[0], x[1], x[2])) c_bin = format(x[2], '#010b')[2:] if c_bin[-3:] == "101": ok_status = True if verbose: print("OK: {}, Status: {}".format(ok_status, c_bin)) print(x[0] * 256 + x[1]) if ok_status: return x[0] * 256 + x[1] time.sleep(0.25) tries += 1 if __name__ == '__main__': # led_flash(10) # relay_loop() dig_in_loop() for x in range(0, 10): for i in range(1, 5): print("Analog {}".format(i)) print(read_analog_in(i)) GPIO.cleanup()