#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"

// I2C defines
// This example will use I2C0 on GPIO8 (SDA) and GPIO9 (SCL) running at 400KHz.
// Pins can be changed, see the GPIO function select table in the datasheet for information on GPIO assignments
#define I2C_PORT i2c0
#define I2C_SDA 0
#define I2C_SCL 1

// I2C reserves some addresses for special purposes. We exclude these from the scan.
// These are any addresses of the form 000 0xxx or 111 1xxx
bool reserved_addr(uint8_t addr)
{
    return (addr & 0x78) == 0 || (addr & 0x78) == 0x78;
}

int main()
{
    stdio_init_all();

    // I2C Initialisation. Using it at 400Khz.
    i2c_init(I2C_PORT, 400 * 1000);

    gpio_set_function(I2C_SDA, GPIO_FUNC_I2C);
    gpio_set_function(I2C_SCL, GPIO_FUNC_I2C);
    gpio_pull_up(I2C_SDA);
    gpio_pull_up(I2C_SCL);

    int error, address;
    uint8_t data;
    int nDevices;

    sleep_ms(5000);

    while (1)
    {

        printf("Escaneando bus I2C\n");
        printf("===================\n");

        nDevices = 0;

        for (address = 1; address < 127; address++)
        {

            if (reserved_addr(address))
                error = PICO_ERROR_GENERIC;
            else
                error = i2c_read_blocking(I2C_PORT, address, &data, 1, false);

            if (error >= 0)
            {
                printf("Dispositivo I2C encontrado en 0x%02x \n", address);
                nDevices = nDevices + 1;
            }
        }
        printf("Encontrados %2x dispositivos I2C\n", nDevices);
        printf("===================\n");
        printf("\n");
        printf("\n");
        printf("\n");
        printf("\n");

        sleep_ms(5000);
    }

    return 0;
}
