test — ESP32 simulation

test

An interactive ESP32 circuit simulation you can run free in your browser on Velxio, by andrian25.

Components

Sketch code

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2c_master.h"
#include "esp_log.h"

#define I2C_SDA_IO   21
#define I2C_SCL_IO   22
#define I2C_FREQ_HZ  100000
#define MOTOR_ADDR   0x0F

static const char *TAG = "I2C_MOTOR";
static i2c_master_dev_handle_t dev_handle;

static esp_err_t i2c_master_init(void)
{
    i2c_master_bus_config_t bus_cfg = {
        .i2c_port = I2C_NUM_0,
        .sda_io_num = I2C_SDA_IO,
        .scl_io_num = I2C_SCL_IO,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true,
    };
    i2c_master_bus_handle_t bus;
    esp_err_t err = i2c_new_master_bus(&bus_cfg, &bus);
    if (err != ESP_OK) return err;

    i2c_device_config_t dev_cfg = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = MOTOR_ADDR,
        .scl_speed_hz = I2C_FREQ_HZ,
    };
    return i2c_master_bus_add_device(bus, &dev_cfg, &dev_handle);
}

static esp_err_t motor_write(const uint8_t *data, size_t len)
{
    return i2c_master_transmit(dev_handle, data, len, 1000);
}

static void motor_run(uint8_t dir_nibble, uint8_t speed1, uint8_t speed2)
{
    uint8_t dir[3] = { 0xAA, dir_nibble, 0x01 };
    uint8_t spd[3] = { 0x82, speed1, speed2 };
    esp_err_t r1 = motor_write(dir, sizeof(dir));
    esp_err_t r2 = motor_write(spd, sizeof(spd));
    if (r1 != ESP_OK || r2 != ESP_OK) {
        ESP_LOGE(TAG, "I2C error: %s / %s", esp_err_to_name(r1), esp_err_to_name(r2));
    }
}

void app_main(void)
{
    ESP_ERROR_CHECK(i2c_master_init());
    ESP_LOGI(TAG, "Driver I2C initializat.");

    while (1) {
        ESP_LOGI(TAG, "Motor inainte");
        motor_run(0x0A, 200, 200);      // clockwise
        vTaskDelay(pdMS_TO_TICKS(2000));

        ESP_LOGI(TAG, "Stop");
        motor_run(0x0A, 0, 0);
        vTaskDelay(pdMS_TO_TICKS(2000));

        ESP_LOGI(TAG, "Motor inapoi");
        motor_run(0x05, 200, 200);      // anticlockwise
        vTaskDelay(pdMS_TO_TICKS(2000));

        motor_run(0x05, 0, 0);
        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}