Package: pimoroni-ioexpander
IO ExpanderIO Expander Breakout uses a Nuvoton MS51 microcontroller and I2C to give you 14 additional input/output pins to connect things up to. Eight of the pins are hooked up to an Analog to Digital Converter and six of the pins can be used as (up to 16-bit) PWM outputs.This library is also used to power our other Nuvoton-based boards and breakouts!Where to buyHATsWeather HAT:https://shop.pimoroni.com/products/weather-hat-onlyInventor HAT Mini:https://shop.pimoroni.com/products/inventor-hat-miniBreakoutsIO Expander Breakout:https://shop.pimoroni.com/products/io-expanderRGB Potentiometer Breakout:https://shop.pimoroni.com/products/rgb-potentiometer-breakoutRGB Encoder Breakout:https://shop.pimoroni.com/products/rgb-encoder-breakoutMICS6814 3-in-1 Gas Sensor Breakout:https://shop.pimoroni.com/products/mics6814-gas-sensor-breakoutGetting the LibraryStable library only (no examples) from PyPi:Just runpython3 -m pip install pimoroni-ioexpanderIn some cases you may need to install pip with:sudo apt install python3-pipStable library, with latest examples from GitHub:git clone https://github.com/pimoroni/ioe-pythoncd ioe-python./install.shLatest/development library and examples from GitHub:git clone https://github.com/pimoroni/ioe-pythoncd ioe-python./install.sh --unstableConfiguring your Raspberry PiEnable I2CIn order to use the IO Expander, you need to enable the I2C interface of your Raspberry Pi. This can be done in the terminal by running:sudo raspi-config nonint do_i2c 0Alternatively, you can enable the I2C interface by:runningsudo raspi-configand enabling the option underInterfacing Options.opening the graphicalRaspberry Pi Configurationapplication from thePreferencesmenu.You may need to reboot after enabling I2C for the change to take effect.Examples and UsageThere are various examples to get you started with your IO Expander. With the library installed on your Raspberry Pi, these can be found in the~/Pimoroni/pimoroni-ioexpander/examplesdirectory.To take IO Expander further, the full API is described in thelibrary reference, with additional feature specific information found in thedocs folder.Removing the LibraryTo uninstall the library only (keeping all examples):Just runpython3 -m pip uninstall pimoroni-ioexpanderOr if you have grabbed the library from Github:cd ioe-python./uninstall.shReferencePinsIO ExpanderAll pins are capable as functioning as general purpose inputs and outputs, and reading rotary encoders, but may additionally function as a PWM output and/or ADC input.#PortADCPWMEncoder1P1.5[Ch 5]Ch 12P1.0[Ch 2]Ch 23P1.2[Ch 0]Ch 34P1.4[Ch 1]Ch 45P0.0[Ch 3]Ch 56P0.1[Ch 4]Ch 67P1.1[Ch 7]Ch 1Ch 78P0.3[Ch 6]Ch 5Ch 89P0.4[Ch 5]Ch 3Ch 910P3.0[Ch 1]Ch 1011P0.6[Ch 3]Ch 1112P0.5[Ch 4]Ch 2Ch 1213P0.7[Ch 2]Ch 1314P1.7[Ch 0]Ch 14[ ] = labelled pin functionsSuper IO Expander#PortADCPWMAlt PWMEncoder[1]P3.5Ch 14[2]P3.6Ch 153P0.6[Ch 3]Ch 114P0.7[Ch 2]Ch 135P1.7[Ch 0]Mod 3 Ch 06P3.0[Ch 1]Mod 2 Ch 1Ch 107P0.4[Ch 5]Mod 0 Ch 3Mod 2 Ch 1Ch 98P0.5[Ch 4]Mod 0 Ch 2Mod 2 Ch 09P1.3[Ch 13]Ch 010P2.5[Ch 15]11P1.1[Ch 7]Mod 0 Ch 1Mod 1 Ch 112P0.3[Ch 6]Mod 0 Ch 5Mod 3 Ch 1Ch 813P2.4[Ch 12]Ch 714P2.3[Ch 11]Mod 1 Ch 0Ch 615P3.3[Mod 0 Ch 0]16P0.1[Mod 0 Ch 4]Mod 3 Ch 017P1.5[Mod 0 Ch 5]Mod 3 Ch 1Ch 118P1.4Ch 14[Mod 0 Ch 1]Mod 1 Ch 1Ch 419P0.0[Mod 0 Ch 3]Mod 2 Ch 1Ch 520P1.0[Mod 0 Ch 2]Mod 2 Ch 0Ch 221P2.1Ch 9[Mod 2 Ch 0]22P2.2Ch 10[Mod 1 Ch 1]23P1.2Mod 0 Ch 0[Mod 1 Ch 0]Ch 324P3.2[Mod 3 Ch 0]25P3.4[Mod 3 Ch 1]26P3.1[Mod 2 Ch 1]Ch 12[ ] = labelled pin functionsFunctionsIn all cases you will need to create an instance of theIOEclass to manage your IO expander (or theSuperIOEif using a Super IO Expander board):importioexpander# For IO Expander boardsioe=ioexpander.IOE()# For Super IO Expander boardsioe=ioexpander.SuperIOE()General-purpose IOAll pins support general-purpose IO and can be configured either as a high-impedance input, quasi-bidirectional input with pull-up, open-drain output or push-pull output. These modes are applicable to different use-cases and we mention some basic examples below.High-impedance inputFor input pins you will usually useioexpander.INwhich sets pins to input-only, high-impedance mode. This mode does not support pull-ups on the pins, and is useful for reading logic levels which are asserted to a high/low value.To set a pin as a high-impedance input:ioe.set_mode(1,ioexpander.IN)And read its value:value=ioe.input(1)Input with pull-upFor reading buttons, or other inputs which sink the connected pin to ground (open drain IO pins for example) you should use theioexpander.IN_PUmode.In this mode the pin is set to a quasi-bidirectional input, and a pull-up resistor is asserted pulling the logic level weakly HIGH.ioe.set_mode(1,ioexpander.IN_PU)Wire a button between ground, and the IO pin and read its value:value=ioe.input(1)A value of 0 (LOW) corresponds to a pushed button.OutputFor output pins you may choose one of the following output modes:ioexpander.PIN_MODE_PP- Output, Push-Pull mode. Drives a pin either HIGH or LOW.ioexpander.PIN_MODE_OD- Output, Open-Drain mode. Drives low, or leaves the pin floatingPush-pull mode is non-inverting, and useful for controlling a connected device (such as a shift register or motor driver), or switching an NPN transistor.Open-drain mode effectively inverts the signal, since outputting a HIGH will connect the pin to Ground. Open-drain outputs are used in multi-drop protocols like i2c, but can also be used for devices or digital logic that requires an active low input.To set a pin as a push-pull output:ioe.set_mode(1,ioexpander.PIN_MODE_PP)And set its value:ioe.output(1,0)# Low (Floating in OD)ioe.output(1,1)# High (Low in OD)Or an open-drain output:ioe.set_mode(1,ioexpander.PIN_MODE_OD)And set its value:ioe.output(1,0)# High (High-impedance floating)ioe.output(1,1)# Low (Pulls to ground)Note: when using open-drain mode (PIN_MODE_OD), writing a1will pull the pin low and writing a0will leave the pin floating.Analog Inputs (ADC)Pins 7, 8, 9 10, 11, 12, 13, and 14 support analog input.IO Expander'sinputmethod will automatically give you a voltage for pins configured in ADC mode:ioe.set_mode(7,ioexpander.ADC)voltage=ioe.input(7)This is scaled against the ADC vref value, which can be read/set with:ioe.set_adc_vref(5)vref=ioe.get_adc_vref()For accurate analog readings, the vref value (which defaults to 3.3) should match the voltage at which the breakout is being powered. In most cases this will be either 3.3v or 5v.Pulse Width Modulation Outputs (PWM)Pins 1, 2, 4, 5, and 6 support PWM output as marked. Additionally pins 7, 8, 9 and 12 (marked as ADC on the IO expander) can be configured as PWM outputs.ioe.set_mode(1,ioexpander.PWM)PWM outputs can optionally be inverted which us useful where you might be driving inverting buffers or common-cathode LEDs:ioe.set_mode(1,ioexpander.PWM,invert=True)PWM, by default, uses the 24MHz FSYS clock and has  16bit period and duty-cycle registers.There are 8 dividers available to slow the clock input into the PWM generator:1/11/21/41/81/161/321/641/128These can be set withset_pwm_control:ioe.set_pwm_control(divider=8)In order to dial in the frequency you need, you must consider the 24MHz clock, the available divider options and the maximum value of the period register.For example, for a 50Hz servo frequency you would use a 1/8 divider, and a period of 60,000:24,000,000 / 8 / 60,000 = 50ioe.set_pwm_control(divider=8)ioe.set_pwm_period(60000)Then you can use duty-cycle values from 3000 to 6000 (1ms to 2ms) to create a servo control pulse.Rotary Encoder DecodingThe IO Expander supports decoding the waveform from up to four rotary encoders. The A and B pins must be specified and are configured as schmitt trigger inputs with a pull-up, if the C pin is specified then it's set to open-drain and driven low. For example:ENC_CHANNEL=1POT_ENC_A=12POT_ENC_B=3POT_ENC_C=11ioe.setup_rotary_encoder(ENC_CHANNEL,POT_ENC_A,POT_ENC_B,pin_c=POT_ENC_C)Each encoder channel has its own signed, 8bit count register which stores the continuous count of pulses as the encoder is rotated. This register is not reset between reads, and will overflow from 127 to -128 in one direction, and from -128 to 127 in the other.In order to maintain a count across reads, this overflow event should be used to increment/decrement an offset which is then added to the register value. This is all done inside the IO Expander library, so you can simply read a continuous value using:count=ioe.read_rotary_encoder(1)This value will correspond to the number of rotations of your rotary encoder dial, multiplied by the resolution of the encoder.The rotary encoder channels will assert an interrupt when a value is changed, in your program main loop you should check for this interrupt, read the encoder value and clear the interrupt flag:while True:
    if ioe.get_interrupt():
        count = ioe.read_rotary_encoder(1)
        ioe.clear_interrupt()Note: in order to track overflows you will need to ensure this interrupt code can run fast enough to catch them. In most cases - ie: a person turning a dial with a 24 step resolution - even 1-second intervals are fine, but for decoding a motor you will want to sample much faster. For example a motor running at 20k RPM with a 12 step resolution would need to be sampled around 31 times a second or approximately every 30ms.Super IO ChangesOn the Super IO Expander, encoder counting has been increased to 16 bit to remove the note above of requiring that motor encoders be read every 30ms to avoid an overflow. An overflow will still occur but now from 32767 to -32768 in one direction, and from -32768 to 32767 in the other.Configuring InterruptsIO Expander has an interrupt register to indicate a variety of state changes. On its own this interrupt register isn't much more useful than polling, but IO Expander can also generate an interrupt on its INT pin - connected to BCM 4 via Breakout Garden HAT - which you can then monitor with your GPIO library of choice.By default the interrupt output pin is not used, but you can enable it on setup like so:importioexpanderioe=ioexpander.IOE(interrupt_pin=4)In this instance4corresponds toBCM4on the Raspberry Pi. Specifying an interrupt pin will enable interrupt output on the IO Expander and set upRPi.GPIO.Alternatively you can handle the interrupt how you see fit by initialising the library and enabling the interrupt output manually:importioexpanderioe=ioexpander.IOE()ioe.enable_interrupt_out()In either case the current state of the interrupt register (and pin) can be read by running:ioe.get_interrupt()And cleared with:ioe.clear_interrupt()If you're using the IO Expander library to handle interrupts then you can bind a handler to the interrupt event:importioexpanderioe=ioexpander.IOE(interrupt_pin=4)defcallback(channel):# Handle interrupt hereioe.clear_interrupt()ioe.on_interrupt(callback)Function ReferenceHere is the complete list of functions common to both theIOEandSuperIOEclasses:i2c_read8(reg)i2c_read12(reg_l,reg_h)i2c_read16(reg_l,reg_h)i2c_write8(reg,value)i2c_write16(reg_l,reg_h,value)get_pin(pin)setup_switch_counter(pin,mode=IN_PU)read_switch_counter(pin)clear_switch_counter(pin)setup_rotary_encoder(channel,pin_a,pin_b,pin_c=None,count_microsteps=False)read_rotary_encoder(channel)clear_rotary_encoder(channel)set_bits(reg,bits)set_bit(reg,bit)clr_bits(reg,bits)clr_bit(reg,bit)get_bit(reg,bit)change_bit(reg,bit,state)enable_interrupt_out(pin_swap=False)disable_interrupt_out()get_interrupt()clear_interrupt()set_pin_interrupt(pin,enabled)on_interrupt(callback)set_i2c_addr(i2c_addr)set_adc_vref(vref)get_adc_vref()enable_adc()disable_adc()get_chip_id()get_version()reset()get_pwm_module(pin)pwm_load(pwm_module=0,wait_for_load=True)pwm_loading(pwm_module=0)pwm_clear(pwm_module=0,wait_for_clear=True)pwm_clearing(pwm_module=0)set_pwm_control(divider,pwm_module=0)set_pwm_period(value,pwm_module=0,load=True,wait_for_load=True)set_pwm_frequency(frequency,pwm_module=0,load=True,wait_for_load=True)get_mode(pin)set_mode(pin,mode,schmitt_trigger=False,invert=False)input(pin,adc_timeout=1)output(pin,value,load=True,wait_for_load=True)get_pwm_regs(pin)get_alt_pwm_regs(pin)get_pin_regs(pin)switch_pwm_to_alt(pin)Here is the initialiser for theIOEclass:IOE(i2c_addr=None,interrupt_timeout=1.0,interrupt_pin=None,interrupt_pull_up=False,gpio=None,skip_chip_id_check=False,perform_reset=False)Here is the initialise and additional functions for theSuperIOEclass:SuperIOE(i2c_addr=None,interrupt_timeout=1.0,interrupt_pin=None,interrupt_pull_up=False,gpio=None,skip_chip_id_check=False,perform_reset=False,is_super_io=True)activate_watchdog()deactivate_Watchdog()is_watchdog_active()reset_watchdog_counter()watchdog_timeout_occurred()clear_watchdog_timeout()set_watchdog_control(divider)i2c_multi_read(reg_base,count)read_rotary_encoders(start_channel,end_channel)Constants ReferenceHere is the list of constants on thepimoroni-ioexpandermodule:Pin Mode ConstantsIN=PIN_MODE_ININ_PULL_UP=PIN_MODE_PUIN_PU=PIN_MODE_PUOUT=PIN_MODE_PPPWM=PIN_MODE_PWMADC=PIN_MODE_ADCState ConstantsHIGH=1LOW=0PWM ConstantsCLOCK_FREQ=24000000MAX_PERIOD=(1 << 16) - 1MAX_DIVIDER=(1 << 7)Changelog0.0.5Improved readme and documentationLinting fixes0.0.4Add support for bigger nuvoton chipAdd wrappers for controlling motors, servos, and encoders0.0.3Add support for 7-bit switch/pulse counters0.0.2Call read/write in a single i2c_rdwr to maintain thread safety0.0.1Initial Release