Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- This code turns on and off each output of the MCP23017 I2C 16-bit I/O expander one by one, with a 500ms delay between each output change.
- Connect the MCP23017 I2C 16-bit I/O expander to the Arduino as follows:
- VCC pin to 5V (or 3.3V, depending on your module's voltage level)
- GND pin to GND
- SDA pin to the SDA pin on your Arduino (A4 on the Uno, Leonardo, or Nano; pin 20 on the Mega)
- SCL pin to the SCL pin on your Arduino (A5 on the Uno, Leonardo, or Nano; pin 21 on the Mega)
- If you have a different I2C address for your MCP23017, you can change the mcp23017Address constant accordingly.
- Please note that you may need to use pull-up resistors (typically 4.7kΩ) for the SDA and SCL lines. Some MCP23017 modules might already have pull-up resistors on board; in that case, you don't need to add external ones.
- */
- #include <Arduino.h>
- #include <Wire.h>
- const byte mcp23017Address = 0x20; // I2C address of the MCP23017
- // MCP23017 register addresses
- const byte IODIRA = 0x00;
- const byte IODIRB = 0x01;
- const byte GPIOA = 0x12;
- const byte GPIOB = 0x13;
- void setup() {
- Wire.begin();
- Serial.begin(9600);
- Serial.println("MCP23017 I2C 16-bit I/O Expander Example");
- // Set all pins as outputs
- writeRegister(mcp23017Address, IODIRA, 0x00);
- writeRegister(mcp23017Address, IODIRB, 0x00);
- }
- void loop() {
- // Turn on and off each output one by one
- for (byte output = 0; output < 16; output++) {
- setOutput(output, HIGH);
- delay(500);
- setOutput(output, LOW);
- delay(500);
- }
- }
- void setOutput(byte output, byte state) {
- byte registerAddress;
- byte bitPosition;
- if (output < 8) {
- registerAddress = GPIOA;
- bitPosition = output;
- } else {
- registerAddress = GPIOB;
- bitPosition = output - 8;
- }
- static byte portAStates = 0;
- static byte portBStates = 0;
- if (registerAddress == GPIOA) {
- if (state == HIGH) {
- portAStates |= (1 << bitPosition);
- } else {
- portAStates &= ~(1 << bitPosition);
- }
- writeRegister(mcp23017Address, GPIOA, portAStates);
- } else {
- if (state == HIGH) {
- portBStates |= (1 << bitPosition);
- } else {
- portBStates &= ~(1 << bitPosition);
- }
- writeRegister(mcp23017Address, GPIOB, portBStates);
- }
- }
- void writeRegister(byte deviceAddress, byte registerAddress, byte data) {
- Wire.beginTransmission(deviceAddress);
- Wire.write(registerAddress);
- Wire.write(data);
- Wire.endTransmission();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement