添加智能灯固件代码

This commit is contained in:
kerwincui
2021-07-13 17:14:51 +08:00
parent 332f74dd17
commit ecc0b91b8b
2568 changed files with 229441 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(i2c-example)

View File

@@ -0,0 +1,9 @@
#
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
# project subdirectory.
#
PROJECT_NAME := i2c-example
include $(IDF_PATH)/make/project.mk

View File

@@ -0,0 +1,152 @@
# I2C Self-Test Example
(See the README.md file in the upper level 'examples' directory for more information about examples.)
## Overview
This example demonstrates basic usage of I2C driver by running two tasks on I2C bus:
1. Read external I2C sensor, here we take the BH1750 ambient light sensor (GY-30 module) for an example.
2. Use one of ESP32s I2C port (master mode) to read and write another I2C port (slave mode) in ESP32.
If you have a new I2C application to go (for example, read the temperature data from external sensor with I2C interface), try this as a basic template, then add your own code.
## How to use example
### Hardware Required
To run this example, you should have one ESP32 dev board (e.g. ESP32-WROVER Kit) or ESP32 core board (e.g. ESP32-DevKitC). Optionally, you can also connect an external sensor, here we choose the BH1750 just for an example. BH1750 is a digital ambient light sensor, for more information about it, you can read the [PDF](http://rohmfs.rohm.com/en/products/databook/datasheet/ic/sensor/light/bh1721fvc-e.pdf) of this sensor.
#### Pin Assignment:
**Note:** The following pin assignments are used by default, yout can change these in the `menuconfig` .
| | SDA | SCL |
| ---------------- | ------ | ------ |
| ESP32 I2C Master | GPIO18 | GPIO19 |
| ESP32 I2C Slave | GPIO4 | GPIO5 |
| BH1750 Sensor | SDA | SCL |
- slave:
- GPIO4 is assigned as the data signal of I2C slave port
- GPIO5 is assigned as the clock signal of I2C slave port
- master:
- GPIO18 is assigned as the data signal of I2C master port
- GPIO19 is assigned as the clock signal of I2C master port
- Connection:
- connect GPIO18 with GPIO4
- connect GPIO19 with GPIO5
- connect SDA/SCL of BH1750 sensor with GPIO18/GPIO19
**Note: ** Theres no need to add an external pull-up resistors for SDA/SCL pin, because the driver will enable the internal pull-up resistors.
### Configure the project
Open the project configuration menu (`idf.py menuconfig`). Then go into `Example Configuration` menu.
- In the `I2C Master` submenu, you can set the pin number of SDA/SCL according to your board. Also you can modify the I2C port number and freauency of the master.
- In the `I2C Slave` submenu, you can set the pin number of SDA/SCL according to your board. Also you can modify the I2C port number and address of the slave.
- In the `BH1750 Sensor` submenu, you can choose the slave address of BH1750 accroding to the pin level of ADDR pin (if the pin level of ADDR is low then the address is `0x23`, otherwise it is `0x5c`). Here you can also control the operation mode of BH1750, each mode has a different resolution and measurement time. For example, in the `One Time L-Resolution` mode, the resolution is 4 Lux and measurement time is typically 16ms (higher resolution means longer measurement time). For more information, you can consult the datasheet of BH1750.
### Build and Flash
Enter `idf.py -p PORT flash monitor` to build, flash and monitor the project.
(To exit the serial monitor, type ``Ctrl-]``.)
See the [Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) for full steps to configure and use ESP-IDF to build projects.
## Example Output
```bash
I (6495) i2c-example: TASK[1] test cnt: 1
*******************
TASK[1] MASTER READ SENSOR( BH1750 )
*******************
data_h: 01
data_l: d0
sensor val: 386.67 [Lux]
I (6695) i2c-example: TASK[0] test cnt: 2
*******************
TASK[0] MASTER READ SENSOR( BH1750 )
*******************
data_h: 01
data_l: d0
sensor val: 386.67 [Lux]
*******************
TASK[0] MASTER READ FROM SLAVE
*******************
====TASK[0] Slave buffer data ====
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f
30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f
40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f
50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f
60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f
70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f
====TASK[0] Master read ====
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f
30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f
40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f
50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f
60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f
70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f
*******************
TASK[1] MASTER READ FROM SLAVE
*******************
====TASK[1] Slave buffer data ====
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f
30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f
40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f
50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f
60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f
70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f
====TASK[1] Master read ====
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f
30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f
40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f
50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f
60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f
70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f
*******************
TASK[0] MASTER WRITE TO SLAVE
*******************
----TASK[0] Master write ----
0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19
1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29
2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39
3a 3b 3c 3d 3e 3f 40 41 42 43 44 45 46 47 48 49
4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59
5a 5b 5c 5d 5e 5f 60 61 62 63 64 65 66 67 68 69
6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79
7a 7b 7c 7d 7e 7f 80 81 82 83 84 85 86 87 88 89
----TASK[0] Slave read: [128] bytes ----
0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19
1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29
2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39
3a 3b 3c 3d 3e 3f 40 41 42 43 44 45 46 47 48 49
4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59
5a 5b 5c 5d 5e 5f 60 61 62 63 64 65 66 67 68 69
6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79
7a 7b 7c 7d 7e 7f 80 81 82 83 84 85 86 87 88 89
```
## Troubleshooting
- BH1750 has two I2C address, which is decided by the voltage level of `ADDR` pin at start up. Make sure to check your schemetic before run this example.
(For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you as soon as possible.)

View File

@@ -0,0 +1,2 @@
idf_component_register(SRCS "i2c_example_main.c"
INCLUDE_DIRS ".")

View File

@@ -0,0 +1,124 @@
menu "Example Configuration"
menu "I2C Master"
config I2C_MASTER_SCL
int "SCL GPIO Num"
default 19
help
GPIO number for I2C Master clock line.
config I2C_MASTER_SDA
int "SDA GPIO Num"
default 18
help
GPIO number for I2C Master data line.
config I2C_MASTER_PORT_NUM
int "Port Number"
default 1
help
Port number for I2C Master device.
config I2C_MASTER_FREQUENCY
int "Master Frequency"
default 100000
help
I2C Speed of Master device.
endmenu
menu "I2C Slave"
config I2C_SLAVE_SCL
int "SCL GPIO Num"
default 5
help
GPIO number for I2C Slave clock line.
config I2C_SLAVE_SDA
int "SDA GPIO Num"
default 4
help
GPIO number for I2C Slave data line.
config I2C_SLAVE_PORT_NUM
int "Port Number"
default 0
help
Port number for I2C Slave device.
config I2C_SLAVE_ADDRESS
hex "ESP Slave Address"
default 0x28
help
Hardware Address of I2C Slave Port.
endmenu
menu "BH1750 Sensor"
choice BH1750_ADDR
prompt "BH1750 I2C Address"
default BH1750_I2C_ADDRESS_LOW
help
Hardware address of BH1750, which is 2 types, and determined by ADDR terminal.
config BH1750_I2C_ADDRESS_LOW
bool "BH1750 I2C Address(ADDR=0)"
help
I2C Address of BH1750 Sensor according to your schemetic configuration.
config BH1750_I2C_ADDRESS_High
bool "BH1750 I2C Address(ADDR=1)"
help
I2C Address of BH1750 Sensor according to your schemetic configuration.
endchoice
config BH1750_ADDR
hex
default 0x5C if BH1750_I2C_ADDRESS_High
default 0x23 if BH1750_I2C_ADDRESS_LOW
choice BH1750_MODE
prompt "BH1750 Operation Mode"
default BH1750_ONETIME_L_RESOLUTION
help
Operation Mode of BH1750.
Different mode means different resolution and measurement time.
config BH1750_CONTINU_H_RESOLUTION
bool "Continuously H-Resolution Mode"
help
Resolution is 1lx, measurement time is typically 120ms.
config BH1750_CONTINU_H_RESOLUTION2
bool "Continuously H-Resolution Mode2"
help
Resolution is 0.5lx, measurement time is typically 120ms.
config BH1750_CONTINU_L_RESOLUTION
bool "Continuously L-Resolution Mode"
help
Resolution is 4lx, measurement time is typically 16ms.
config BH1750_ONETIME_H_RESOLUTION
bool "One Time H-Resolution Mode"
help
Resolution is 1lx, measurement time is typically 120ms.
It is automatically set to Power Down mode after measurement.
config BH1750_ONETIME_H_RESOLUTION2
bool "One Time H-Resolution Mode2"
help
Resolution is 0.5lx, measurement time is typically 120ms.
It is automatically set to Power Down mode after measurement.
config BH1750_ONETIME_L_RESOLUTION
bool "One Time L-Resolution Mode"
help
Resolution is 4lx, measurement time is typically 16ms.
It is automatically set to Power Down mode after measurement.
endchoice
config BH1750_OPMODE
hex
default 0x10 if BH1750_CONTINU_H_RESOLUTION
default 0x11 if BH1750_CONTINU_H_RESOLUTION2
default 0x13 if BH1750_CONTINU_L_RESOLUTION
default 0x20 if BH1750_ONETIME_H_RESOLUTION
default 0x21 if BH1750_ONETIME_H_RESOLUTION2
default 0x23 if BH1750_ONETIME_L_RESOLUTION
endmenu
endmenu

View File

@@ -0,0 +1,3 @@
#
# Main Makefile. This is basically the same as a component makefile.
#

View File

@@ -0,0 +1,287 @@
/* i2c - Example
For other examples please check:
https://github.com/espressif/esp-idf/tree/master/examples
See README.md file to get detailed usage of this example.
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "esp_log.h"
#include "driver/i2c.h"
#include "sdkconfig.h"
static const char *TAG = "i2c-example";
#define _I2C_NUMBER(num) I2C_NUM_##num
#define I2C_NUMBER(num) _I2C_NUMBER(num)
#define DATA_LENGTH 512 /*!< Data buffer length of test buffer */
#define RW_TEST_LENGTH 128 /*!< Data length for r/w test, [0,DATA_LENGTH] */
#define DELAY_TIME_BETWEEN_ITEMS_MS 1000 /*!< delay time between different test items */
#define I2C_SLAVE_SCL_IO CONFIG_I2C_SLAVE_SCL /*!< gpio number for i2c slave clock */
#define I2C_SLAVE_SDA_IO CONFIG_I2C_SLAVE_SDA /*!< gpio number for i2c slave data */
#define I2C_SLAVE_NUM I2C_NUMBER(CONFIG_I2C_SLAVE_PORT_NUM) /*!< I2C port number for slave dev */
#define I2C_SLAVE_TX_BUF_LEN (2 * DATA_LENGTH) /*!< I2C slave tx buffer size */
#define I2C_SLAVE_RX_BUF_LEN (2 * DATA_LENGTH) /*!< I2C slave rx buffer size */
#define I2C_MASTER_SCL_IO CONFIG_I2C_MASTER_SCL /*!< gpio number for I2C master clock */
#define I2C_MASTER_SDA_IO CONFIG_I2C_MASTER_SDA /*!< gpio number for I2C master data */
#define I2C_MASTER_NUM I2C_NUMBER(CONFIG_I2C_MASTER_PORT_NUM) /*!< I2C port number for master dev */
#define I2C_MASTER_FREQ_HZ CONFIG_I2C_MASTER_FREQUENCY /*!< I2C master clock frequency */
#define I2C_MASTER_TX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
#define I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
#define BH1750_SENSOR_ADDR CONFIG_BH1750_ADDR /*!< slave address for BH1750 sensor */
#define BH1750_CMD_START CONFIG_BH1750_OPMODE /*!< Operation mode */
#define ESP_SLAVE_ADDR CONFIG_I2C_SLAVE_ADDRESS /*!< ESP32 slave address, you can set any 7bit value */
#define WRITE_BIT I2C_MASTER_WRITE /*!< I2C master write */
#define READ_BIT I2C_MASTER_READ /*!< I2C master read */
#define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */
#define ACK_VAL 0x0 /*!< I2C ack value */
#define NACK_VAL 0x1 /*!< I2C nack value */
SemaphoreHandle_t print_mux = NULL;
/**
* @brief test code to read esp-i2c-slave
* We need to fill the buffer of esp slave device, then master can read them out.
*
* _______________________________________________________________________________________
* | start | slave_addr + rd_bit +ack | read n-1 bytes + ack | read 1 byte + nack | stop |
* --------|--------------------------|----------------------|--------------------|------|
*
*/
static esp_err_t i2c_master_read_slave(i2c_port_t i2c_num, uint8_t *data_rd, size_t size)
{
if (size == 0) {
return ESP_OK;
}
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (ESP_SLAVE_ADDR << 1) | READ_BIT, ACK_CHECK_EN);
if (size > 1) {
i2c_master_read(cmd, data_rd, size - 1, ACK_VAL);
}
i2c_master_read_byte(cmd, data_rd + size - 1, NACK_VAL);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
/**
* @brief Test code to write esp-i2c-slave
* Master device write data to slave(both esp32),
* the data will be stored in slave buffer.
* We can read them out from slave buffer.
*
* ___________________________________________________________________
* | start | slave_addr + wr_bit + ack | write n bytes + ack | stop |
* --------|---------------------------|----------------------|------|
*
*/
static esp_err_t i2c_master_write_slave(i2c_port_t i2c_num, uint8_t *data_wr, size_t size)
{
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (ESP_SLAVE_ADDR << 1) | WRITE_BIT, ACK_CHECK_EN);
i2c_master_write(cmd, data_wr, size, ACK_CHECK_EN);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
/**
* @brief test code to operate on BH1750 sensor
*
* 1. set operation mode(e.g One time L-resolution mode)
* _________________________________________________________________
* | start | slave_addr + wr_bit + ack | write 1 byte + ack | stop |
* --------|---------------------------|---------------------|------|
* 2. wait more than 24 ms
* 3. read data
* ______________________________________________________________________________________
* | start | slave_addr + rd_bit + ack | read 1 byte + ack | read 1 byte + nack | stop |
* --------|---------------------------|--------------------|--------------------|------|
*/
static esp_err_t i2c_master_sensor_test(i2c_port_t i2c_num, uint8_t *data_h, uint8_t *data_l)
{
int ret;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, BH1750_SENSOR_ADDR << 1 | WRITE_BIT, ACK_CHECK_EN);
i2c_master_write_byte(cmd, BH1750_CMD_START, ACK_CHECK_EN);
i2c_master_stop(cmd);
ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if (ret != ESP_OK) {
return ret;
}
vTaskDelay(30 / portTICK_RATE_MS);
cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, BH1750_SENSOR_ADDR << 1 | READ_BIT, ACK_CHECK_EN);
i2c_master_read_byte(cmd, data_h, ACK_VAL);
i2c_master_read_byte(cmd, data_l, NACK_VAL);
i2c_master_stop(cmd);
ret = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
/**
* @brief i2c master initialization
*/
static esp_err_t i2c_master_init(void)
{
int i2c_master_port = I2C_MASTER_NUM;
i2c_config_t conf;
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = I2C_MASTER_SDA_IO;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = I2C_MASTER_SCL_IO;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = I2C_MASTER_FREQ_HZ;
i2c_param_config(i2c_master_port, &conf);
return i2c_driver_install(i2c_master_port, conf.mode, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
}
/**
* @brief i2c slave initialization
*/
static esp_err_t i2c_slave_init(void)
{
int i2c_slave_port = I2C_SLAVE_NUM;
i2c_config_t conf_slave;
conf_slave.sda_io_num = I2C_SLAVE_SDA_IO;
conf_slave.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf_slave.scl_io_num = I2C_SLAVE_SCL_IO;
conf_slave.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf_slave.mode = I2C_MODE_SLAVE;
conf_slave.slave.addr_10bit_en = 0;
conf_slave.slave.slave_addr = ESP_SLAVE_ADDR;
i2c_param_config(i2c_slave_port, &conf_slave);
return i2c_driver_install(i2c_slave_port, conf_slave.mode, I2C_SLAVE_RX_BUF_LEN, I2C_SLAVE_TX_BUF_LEN, 0);
}
/**
* @brief test function to show buffer
*/
static void disp_buf(uint8_t *buf, int len)
{
int i;
for (i = 0; i < len; i++) {
printf("%02x ", buf[i]);
if ((i + 1) % 16 == 0) {
printf("\n");
}
}
printf("\n");
}
static void i2c_test_task(void *arg)
{
int i = 0;
int ret;
uint32_t task_idx = (uint32_t)arg;
uint8_t *data = (uint8_t *)malloc(DATA_LENGTH);
uint8_t *data_wr = (uint8_t *)malloc(DATA_LENGTH);
uint8_t *data_rd = (uint8_t *)malloc(DATA_LENGTH);
uint8_t sensor_data_h, sensor_data_l;
int cnt = 0;
while (1) {
ESP_LOGI(TAG, "TASK[%d] test cnt: %d", task_idx, cnt++);
ret = i2c_master_sensor_test(I2C_MASTER_NUM, &sensor_data_h, &sensor_data_l);
xSemaphoreTake(print_mux, portMAX_DELAY);
if (ret == ESP_ERR_TIMEOUT) {
ESP_LOGE(TAG, "I2C Timeout");
} else if (ret == ESP_OK) {
printf("*******************\n");
printf("TASK[%d] MASTER READ SENSOR( BH1750 )\n", task_idx);
printf("*******************\n");
printf("data_h: %02x\n", sensor_data_h);
printf("data_l: %02x\n", sensor_data_l);
printf("sensor val: %.02f [Lux]\n", (sensor_data_h << 8 | sensor_data_l) / 1.2);
} else {
ESP_LOGW(TAG, "%s: No ack, sensor not connected...skip...", esp_err_to_name(ret));
}
xSemaphoreGive(print_mux);
vTaskDelay((DELAY_TIME_BETWEEN_ITEMS_MS * (task_idx + 1)) / portTICK_RATE_MS);
//---------------------------------------------------
for (i = 0; i < DATA_LENGTH; i++) {
data[i] = i;
}
xSemaphoreTake(print_mux, portMAX_DELAY);
size_t d_size = i2c_slave_write_buffer(I2C_SLAVE_NUM, data, RW_TEST_LENGTH, 1000 / portTICK_RATE_MS);
if (d_size == 0) {
ESP_LOGW(TAG, "i2c slave tx buffer full");
ret = i2c_master_read_slave(I2C_MASTER_NUM, data_rd, DATA_LENGTH);
} else {
ret = i2c_master_read_slave(I2C_MASTER_NUM, data_rd, RW_TEST_LENGTH);
}
if (ret == ESP_ERR_TIMEOUT) {
ESP_LOGE(TAG, "I2C Timeout");
} else if (ret == ESP_OK) {
printf("*******************\n");
printf("TASK[%d] MASTER READ FROM SLAVE\n", task_idx);
printf("*******************\n");
printf("====TASK[%d] Slave buffer data ====\n", task_idx);
disp_buf(data, d_size);
printf("====TASK[%d] Master read ====\n", task_idx);
disp_buf(data_rd, d_size);
} else {
ESP_LOGW(TAG, "TASK[%d] %s: Master read slave error, IO not connected...\n",
task_idx, esp_err_to_name(ret));
}
xSemaphoreGive(print_mux);
vTaskDelay((DELAY_TIME_BETWEEN_ITEMS_MS * (task_idx + 1)) / portTICK_RATE_MS);
//---------------------------------------------------
int size;
for (i = 0; i < DATA_LENGTH; i++) {
data_wr[i] = i + 10;
}
xSemaphoreTake(print_mux, portMAX_DELAY);
//we need to fill the slave buffer so that master can read later
ret = i2c_master_write_slave(I2C_MASTER_NUM, data_wr, RW_TEST_LENGTH);
if (ret == ESP_OK) {
size = i2c_slave_read_buffer(I2C_SLAVE_NUM, data, RW_TEST_LENGTH, 1000 / portTICK_RATE_MS);
}
if (ret == ESP_ERR_TIMEOUT) {
ESP_LOGE(TAG, "I2C Timeout");
} else if (ret == ESP_OK) {
printf("*******************\n");
printf("TASK[%d] MASTER WRITE TO SLAVE\n", task_idx);
printf("*******************\n");
printf("----TASK[%d] Master write ----\n", task_idx);
disp_buf(data_wr, RW_TEST_LENGTH);
printf("----TASK[%d] Slave read: [%d] bytes ----\n", task_idx, size);
disp_buf(data, size);
} else {
ESP_LOGW(TAG, "TASK[%d] %s: Master write slave error, IO not connected....\n",
task_idx, esp_err_to_name(ret));
}
xSemaphoreGive(print_mux);
vTaskDelay((DELAY_TIME_BETWEEN_ITEMS_MS * (task_idx + 1)) / portTICK_RATE_MS);
}
vSemaphoreDelete(print_mux);
vTaskDelete(NULL);
}
void app_main(void)
{
print_mux = xSemaphoreCreateMutex();
ESP_ERROR_CHECK(i2c_slave_init());
ESP_ERROR_CHECK(i2c_master_init());
xTaskCreate(i2c_test_task, "i2c_test_task_0", 1024 * 2, (void *)0, 10, NULL);
xTaskCreate(i2c_test_task, "i2c_test_task_1", 1024 * 2, (void *)1, 10, NULL);
}

View File

@@ -0,0 +1,8 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/system/console/components)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(i2c-tools)

View File

@@ -0,0 +1,11 @@
#
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
# project subdirectory.
#
PROJECT_NAME := i2c-tools
EXTRA_COMPONENT_DIRS = $(IDF_PATH)/examples/system/console/components
include $(IDF_PATH)/make/project.mk

View File

@@ -0,0 +1,204 @@
| Supported Targets | ESP32 |
| ----------------- | ----- |
# I2C Tools Example
(See the README.md file in the upper level 'examples' directory for more information about examples.)
## Overview
[I2C Tools](https://i2c.wiki.kernel.org/index.php/I2C_Tools) is a simple but very useful tool for developing I2C related applications, which is also famous in Linux platform. This example just implements some of basic features of [I2C Tools](https://i2c.wiki.kernel.org/index.php/I2C_Tools) based on [esp32 console component](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/console.html). As follows, this example supports five command-line tools:
1. `i2cconfig`: It will configure the I2C bus with specific GPIO number, port number and frequency.
2. `i2cdetect`: It will scan an I2C bus for devices and output a table with the list of detected devices on the bus.
3. `i2cget`: It will read registers visible through the I2C bus.
4. `i2cset`: It will set registers visible through the I2C bus.
5. `i2cdump`: It will examine registers visible through the I2C bus.
If you have some trouble in developing I2C related applications, or just want to test some functions of one I2C device, you can play with this example first.
## How to use example
### Hardware Required
To run this example, you should have one ESP32 dev board (e.g. ESP32-WROVER Kit) or ESP32 core board (e.g. ESP32-DevKitC). For test purpose, you should have a kind of device with I2C interface as well. Here we will take the CCS811 sensor as an example to show how to test the function of this sensor without writing any code (just use the command-line tools supported by this example). For more information about CCS811, you can consult the [online datasheet](http://ams.com/ccs811).
#### Pin Assignment:
**Note:** The following pin assignments are used by default, you can change them with `i2cconfig` command at any time.
| | SDA | SCL | GND | Other | VCC |
| ---------------- | ------ | ------ | ---- | ----- | ---- |
| ESP32 I2C Master | GPIO18 | GPIO19 | GND | GND | 3.3V |
| Sensor | SDA | SCL | GND | WAK | VCC |
**Note: ** Theres no need to add an external pull-up resistors for SDA/SCL pin, because the driver will enable the internal pull-up resistors itself.
### Configure the project
Open the project configuration menu (`idf.py menuconfig`). Then go into `Example Configuration` menu.
- You can choose whether or not to save command history into flash in `Store command history in flash` option.
### Build and Flash
Run `idf.py -p PORT flash monitor` to build and flash the project..
(To exit the serial monitor, type ``Ctrl-]``.)
See the [Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) for full steps to configure and use ESP-IDF to build projects.
## Example Output
### Check all supported commands and their usages
```bash
==============================================================
| Steps to Use i2c-tools on ESP32 |
| |
| 1. Try 'help', check all supported commands |
| 2. Try 'i2cconfig' to configure your I2C bus |
| 3. Try 'i2cdetect' to scan devices on the bus |
| 4. Try 'i2cget' to get the content of specific register |
| 5. Try 'i2cset' to set the value of specific register |
| 6. Try 'i2cdump' to dump all the register (Experiment) |
| |
==============================================================
esp32> help
help
Print the list of registered commands
i2cconfig [--port=<0|1>] [--freq=<Hz>] --sda=<gpio> --scl=<gpio>
Config I2C bus
--port=<0|1> Set the I2C bus port number
--freq=<Hz> Set the frequency(Hz) of I2C bus
--sda=<gpio> Set the gpio for I2C SDA
--scl=<gpio> Set the gpio for I2C SCL
i2cdetect
Scan I2C bus for devices
i2cget -c <chip_addr> [-r <register_addr>] [-l <length>]
Read registers visible through the I2C bus
-c, --chip=<chip_addr> Specify the address of the chip on that bus
-r, --register=<register_addr> Specify the address on that chip to read from
-l, --length=<length> Specify the length to read from that data address
i2cset -c <chip_addr> [-r <register_addr>] [<data>]...
Set registers visible through the I2C bus
-c, --chip=<chip_addr> Specify the address of the chip on that bus
-r, --register=<register_addr> Specify the address on that chip to read from
<data> Specify the data to write to that data address
i2cdump -c <chip_addr> [-s <size>]
Examine registers visible through the I2C bus
-c, --chip=<chip_addr> Specify the address of the chip on that bus
-s, --size=<size> Specify the size of each read
free
Get the current size of free heap memory
heap
Get minimum size of free heap memory that was available during program execu
tion
version
Get version of chip and SDK
restart
Software reset of the chip
deep_sleep [-t <t>] [--io=<n>] [--io_level=<0|1>]
Enter deep sleep mode. Two wakeup modes are supported: timer and GPIO. If no
wakeup option is specified, will sleep indefinitely.
-t, --time=<t> Wake up time, ms
--io=<n> If specified, wakeup using GPIO with given number
--io_level=<0|1> GPIO level to trigger wakeup
light_sleep [-t <t>] [--io=<n>]... [--io_level=<0|1>]...
Enter light sleep mode. Two wakeup modes are supported: timer and GPIO. Mult
iple GPIO pins can be specified using pairs of 'io' and 'io_level' arguments
. Will also wake up on UART input.
-t, --time=<t> Wake up time, ms
--io=<n> If specified, wakeup using GPIO with given number
--io_level=<0|1> GPIO level to trigger wakeup
tasks
Get information about running tasks
```
### Configure the I2C bus
```bash
esp32> i2cconfig --port=0 --sda=18 --scl=19 --freq=100000
```
* `--port` option to specify the port of I2C, here we choose port 0 for test.
* `--sda` and `--scl` options to specify the gpio number used by I2C bus, here we choose GPIO18 as the SDA and GPIO19 as the SCL.
* `--freq` option to specify the frequency of I2C bus, here we set to 100KHz.
### Check the I2C address (7 bits) on the I2C bus
```bash
esp32> i2cdetect
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- 5b -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
```
* Here we found the address of CCS811 is 0x5b.
### Get the value of status register
```bash
esp32> i2cget -c 0x5b -r 0x00 -l 1
0x10
```
* `-c` option to specify the address of I2C device (acquired from `i2cdetect` command).
* `-r` option to specify the register address you want to inspect.
* `-l` option to specify the length of the content.
* Here the returned value 0x10 means that the sensor is just in the boot mode and is ready to go into application mode. For more information about CCS811 you should consult the [official website](http://ams.com/ccs811).
### Change the working mode
```bash
esp32> i2cset -c 0x5b -r 0xF4
I (734717) cmd_i2ctools: Write OK
esp32> i2cset -c 0x5b -r 0x01 0x10
I (1072047) cmd_i2ctools: Write OK
esp32> i2cget -c 0x5b -r 0x00 -l 1
0x98
```
* Here we change the mode from boot to application and set a proper measure mode (by writing 0x10 to register 0x01)
* Now the status value of the sensor is 0x98, which means a valid data is ready to read
### Read the sensor data
```bash
esp32> i2cget -c 0x5b -r 0x02 -l 8
0x01 0xb0 0x00 0x04 0x98 0x00 0x19 0x8f
```
* The register 0x02 will output 8 bytes result, mainly including value of eCO~2~、TVOC and there raw value. So the value of eCO~2~ is 0x01b0 ppm and value of TVOC is 0x04 ppb.
## Troubleshooting
* I dont find any available address when running `i2cdetect` command.
* Make sure your wiring connection is right.
* Some sensor will have a “wake up” pin, via which user can put the sensor into a sleep mode. So make sure your sensor in **not** in the sleep state.
* Reset you I2C device, and then run `i2cdetect` again.
* I cant get the right content when running `i2cdump` command.
* Currently the `i2cdump` only support those who have the same content length of registers inside the I2C device. For example, if a device have three register addresses, and the content length at these address are 1 byte, 2 bytes and 4 bytes. In this case you should not expect this command to dump the register correctly.
(For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you as soon as possible.)

View File

@@ -0,0 +1,37 @@
from __future__ import print_function
import ttfw_idf
EXPECT_TIMEOUT = 20
@ttfw_idf.idf_example_test(env_tag='Example_I2C_CCS811_SENSOR')
def test_i2ctools_example(env, extra_data):
# Get device under test, flash and start example. "i2ctool" must be defined in EnvConfig
dut = env.get_dut('i2ctools', 'examples/peripherals/i2c/i2c_tools', dut_class=ttfw_idf.ESP32DUT)
dut.start_app()
dut.expect("i2c-tools>", timeout=EXPECT_TIMEOUT)
# Get i2c address
dut.write("i2cdetect")
dut.expect("5b", timeout=EXPECT_TIMEOUT)
# Get chip ID
dut.write("i2cget -c 0x5b -r 0x20 -l 1")
dut.expect("0x81", timeout=EXPECT_TIMEOUT)
# Reset sensor
dut.write("i2cset -c 0x5b -r 0xFF 0x11 0xE5 0x72 0x8A")
dut.expect("OK", timeout=EXPECT_TIMEOUT)
# Get status
dut.write("i2cget -c 0x5b -r 0x00 -l 1")
dut.expect_any("0x10", timeout=EXPECT_TIMEOUT)
# Change work mode
dut.write("i2cset -c 0x5b -r 0xF4")
dut.expect("OK", timeout=EXPECT_TIMEOUT)
dut.write("i2cset -c 0x5b -r 0x01 0x10")
dut.expect("OK", timeout=EXPECT_TIMEOUT)
# Get new status
dut.write("i2cget -c 0x5b -r 0x00 -l 1")
dut.expect_any("0x98", "0x90", timeout=EXPECT_TIMEOUT)
if __name__ == '__main__':
test_i2ctools_example()

View File

@@ -0,0 +1,3 @@
idf_component_register(SRCS "i2ctools_example_main.c"
"cmd_i2ctools.c"
INCLUDE_DIRS ".")

View File

@@ -0,0 +1,10 @@
menu "Example Configuration"
config EXAMPLE_STORE_HISTORY
bool "Store command history in flash"
default y
help
Linenoise line editing library provides functions to save and load
command history. If this option is enabled, initalizes a FAT filesystem
and uses it to store command history.
endmenu

View File

@@ -0,0 +1,409 @@
/* cmd_i2ctools.c
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "argtable3/argtable3.h"
#include "driver/i2c.h"
#include "esp_console.h"
#include "esp_log.h"
#define I2C_MASTER_TX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
#define I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
#define WRITE_BIT I2C_MASTER_WRITE /*!< I2C master write */
#define READ_BIT I2C_MASTER_READ /*!< I2C master read */
#define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */
#define ACK_VAL 0x0 /*!< I2C ack value */
#define NACK_VAL 0x1 /*!< I2C nack value */
static const char *TAG = "cmd_i2ctools";
static gpio_num_t i2c_gpio_sda = 18;
static gpio_num_t i2c_gpio_scl = 19;
static uint32_t i2c_frequency = 100000;
static i2c_port_t i2c_port = I2C_NUM_0;
static esp_err_t i2c_get_port(int port, i2c_port_t *i2c_port)
{
if (port >= I2C_NUM_MAX) {
ESP_LOGE(TAG, "Wrong port number: %d", port);
return ESP_FAIL;
}
switch (port) {
case 0:
*i2c_port = I2C_NUM_0;
break;
case 1:
*i2c_port = I2C_NUM_1;
break;
default:
*i2c_port = I2C_NUM_0;
break;
}
return ESP_OK;
}
static esp_err_t i2c_master_driver_initialize(void)
{
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = i2c_gpio_sda,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = i2c_gpio_scl,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = i2c_frequency
};
return i2c_param_config(i2c_port, &conf);
}
static struct {
struct arg_int *port;
struct arg_int *freq;
struct arg_int *sda;
struct arg_int *scl;
struct arg_end *end;
} i2cconfig_args;
static int do_i2cconfig_cmd(int argc, char **argv)
{
int nerrors = arg_parse(argc, argv, (void **)&i2cconfig_args);
if (nerrors != 0) {
arg_print_errors(stderr, i2cconfig_args.end, argv[0]);
return 0;
}
/* Check "--port" option */
if (i2cconfig_args.port->count) {
if (i2c_get_port(i2cconfig_args.port->ival[0], &i2c_port) != ESP_OK) {
return 1;
}
}
/* Check "--freq" option */
if (i2cconfig_args.freq->count) {
i2c_frequency = i2cconfig_args.freq->ival[0];
}
/* Check "--sda" option */
i2c_gpio_sda = i2cconfig_args.sda->ival[0];
/* Check "--scl" option */
i2c_gpio_scl = i2cconfig_args.scl->ival[0];
return 0;
}
static void register_i2cconfig(void)
{
i2cconfig_args.port = arg_int0(NULL, "port", "<0|1>", "Set the I2C bus port number");
i2cconfig_args.freq = arg_int0(NULL, "freq", "<Hz>", "Set the frequency(Hz) of I2C bus");
i2cconfig_args.sda = arg_int1(NULL, "sda", "<gpio>", "Set the gpio for I2C SDA");
i2cconfig_args.scl = arg_int1(NULL, "scl", "<gpio>", "Set the gpio for I2C SCL");
i2cconfig_args.end = arg_end(2);
const esp_console_cmd_t i2cconfig_cmd = {
.command = "i2cconfig",
.help = "Config I2C bus",
.hint = NULL,
.func = &do_i2cconfig_cmd,
.argtable = &i2cconfig_args
};
ESP_ERROR_CHECK(esp_console_cmd_register(&i2cconfig_cmd));
}
static int do_i2cdetect_cmd(int argc, char **argv)
{
i2c_driver_install(i2c_port, I2C_MODE_MASTER, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
i2c_master_driver_initialize();
uint8_t address;
printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\r\n");
for (int i = 0; i < 128; i += 16) {
printf("%02x: ", i);
for (int j = 0; j < 16; j++) {
fflush(stdout);
address = i + j;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (address << 1) | WRITE_BIT, ACK_CHECK_EN);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 50 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if (ret == ESP_OK) {
printf("%02x ", address);
} else if (ret == ESP_ERR_TIMEOUT) {
printf("UU ");
} else {
printf("-- ");
}
}
printf("\r\n");
}
i2c_driver_delete(i2c_port);
return 0;
}
static void register_i2cdectect(void)
{
const esp_console_cmd_t i2cdetect_cmd = {
.command = "i2cdetect",
.help = "Scan I2C bus for devices",
.hint = NULL,
.func = &do_i2cdetect_cmd,
.argtable = NULL
};
ESP_ERROR_CHECK(esp_console_cmd_register(&i2cdetect_cmd));
}
static struct {
struct arg_int *chip_address;
struct arg_int *register_address;
struct arg_int *data_length;
struct arg_end *end;
} i2cget_args;
static int do_i2cget_cmd(int argc, char **argv)
{
int nerrors = arg_parse(argc, argv, (void **)&i2cget_args);
if (nerrors != 0) {
arg_print_errors(stderr, i2cget_args.end, argv[0]);
return 0;
}
/* Check chip address: "-c" option */
int chip_addr = i2cget_args.chip_address->ival[0];
/* Check register address: "-r" option */
int data_addr = -1;
if (i2cget_args.register_address->count) {
data_addr = i2cget_args.register_address->ival[0];
}
/* Check data length: "-l" option */
int len = 1;
if (i2cget_args.data_length->count) {
len = i2cget_args.data_length->ival[0];
}
uint8_t *data = malloc(len);
i2c_driver_install(i2c_port, I2C_MODE_MASTER, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
i2c_master_driver_initialize();
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
if (data_addr != -1) {
i2c_master_write_byte(cmd, chip_addr << 1 | WRITE_BIT, ACK_CHECK_EN);
i2c_master_write_byte(cmd, data_addr, ACK_CHECK_EN);
i2c_master_start(cmd);
}
i2c_master_write_byte(cmd, chip_addr << 1 | READ_BIT, ACK_CHECK_EN);
if (len > 1) {
i2c_master_read(cmd, data, len - 1, ACK_VAL);
}
i2c_master_read_byte(cmd, data + len - 1, NACK_VAL);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if (ret == ESP_OK) {
for (int i = 0; i < len; i++) {
printf("0x%02x ", data[i]);
if ((i + 1) % 16 == 0) {
printf("\r\n");
}
}
if (len % 16) {
printf("\r\n");
}
} else if (ret == ESP_ERR_TIMEOUT) {
ESP_LOGW(TAG, "Bus is busy");
} else {
ESP_LOGW(TAG, "Read failed");
}
free(data);
i2c_driver_delete(i2c_port);
return 0;
}
static void register_i2cget(void)
{
i2cget_args.chip_address = arg_int1("c", "chip", "<chip_addr>", "Specify the address of the chip on that bus");
i2cget_args.register_address = arg_int0("r", "register", "<register_addr>", "Specify the address on that chip to read from");
i2cget_args.data_length = arg_int0("l", "length", "<length>", "Specify the length to read from that data address");
i2cget_args.end = arg_end(1);
const esp_console_cmd_t i2cget_cmd = {
.command = "i2cget",
.help = "Read registers visible through the I2C bus",
.hint = NULL,
.func = &do_i2cget_cmd,
.argtable = &i2cget_args
};
ESP_ERROR_CHECK(esp_console_cmd_register(&i2cget_cmd));
}
static struct {
struct arg_int *chip_address;
struct arg_int *register_address;
struct arg_int *data;
struct arg_end *end;
} i2cset_args;
static int do_i2cset_cmd(int argc, char **argv)
{
int nerrors = arg_parse(argc, argv, (void **)&i2cset_args);
if (nerrors != 0) {
arg_print_errors(stderr, i2cset_args.end, argv[0]);
return 0;
}
/* Check chip address: "-c" option */
int chip_addr = i2cset_args.chip_address->ival[0];
/* Check register address: "-r" option */
int data_addr = 0;
if (i2cset_args.register_address->count) {
data_addr = i2cset_args.register_address->ival[0];
}
/* Check data: "-d" option */
int len = i2cset_args.data->count;
i2c_driver_install(i2c_port, I2C_MODE_MASTER, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
i2c_master_driver_initialize();
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, chip_addr << 1 | WRITE_BIT, ACK_CHECK_EN);
if (i2cset_args.register_address->count) {
i2c_master_write_byte(cmd, data_addr, ACK_CHECK_EN);
}
for (int i = 0; i < len; i++) {
i2c_master_write_byte(cmd, i2cset_args.data->ival[i], ACK_CHECK_EN);
}
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if (ret == ESP_OK) {
ESP_LOGI(TAG, "Write OK");
} else if (ret == ESP_ERR_TIMEOUT) {
ESP_LOGW(TAG, "Bus is busy");
} else {
ESP_LOGW(TAG, "Write Failed");
}
i2c_driver_delete(i2c_port);
return 0;
}
static void register_i2cset(void)
{
i2cset_args.chip_address = arg_int1("c", "chip", "<chip_addr>", "Specify the address of the chip on that bus");
i2cset_args.register_address = arg_int0("r", "register", "<register_addr>", "Specify the address on that chip to read from");
i2cset_args.data = arg_intn(NULL, NULL, "<data>", 0, 256, "Specify the data to write to that data address");
i2cset_args.end = arg_end(2);
const esp_console_cmd_t i2cset_cmd = {
.command = "i2cset",
.help = "Set registers visible through the I2C bus",
.hint = NULL,
.func = &do_i2cset_cmd,
.argtable = &i2cset_args
};
ESP_ERROR_CHECK(esp_console_cmd_register(&i2cset_cmd));
}
static struct {
struct arg_int *chip_address;
struct arg_int *size;
struct arg_end *end;
} i2cdump_args;
static int do_i2cdump_cmd(int argc, char **argv)
{
int nerrors = arg_parse(argc, argv, (void **)&i2cdump_args);
if (nerrors != 0) {
arg_print_errors(stderr, i2cdump_args.end, argv[0]);
return 0;
}
/* Check chip address: "-c" option */
int chip_addr = i2cdump_args.chip_address->ival[0];
/* Check read size: "-s" option */
int size = 1;
if (i2cdump_args.size->count) {
size = i2cdump_args.size->ival[0];
}
if (size != 1 && size != 2 && size != 4) {
ESP_LOGE(TAG, "Wrong read size. Only support 1,2,4");
return 1;
}
i2c_driver_install(i2c_port, I2C_MODE_MASTER, I2C_MASTER_RX_BUF_DISABLE, I2C_MASTER_TX_BUF_DISABLE, 0);
i2c_master_driver_initialize();
uint8_t data_addr;
uint8_t data[4];
int32_t block[16];
printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f"
" 0123456789abcdef\r\n");
for (int i = 0; i < 128; i += 16) {
printf("%02x: ", i);
for (int j = 0; j < 16; j += size) {
fflush(stdout);
data_addr = i + j;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, chip_addr << 1 | WRITE_BIT, ACK_CHECK_EN);
i2c_master_write_byte(cmd, data_addr, ACK_CHECK_EN);
i2c_master_start(cmd);
i2c_master_write_byte(cmd, chip_addr << 1 | READ_BIT, ACK_CHECK_EN);
if (size > 1) {
i2c_master_read(cmd, data, size - 1, ACK_VAL);
}
i2c_master_read_byte(cmd, data + size - 1, NACK_VAL);
i2c_master_stop(cmd);
esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 50 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if (ret == ESP_OK) {
for (int k = 0; k < size; k++) {
printf("%02x ", data[k]);
block[j + k] = data[k];
}
} else {
for (int k = 0; k < size; k++) {
printf("XX ");
block[j + k] = -1;
}
}
}
printf(" ");
for (int k = 0; k < 16; k++) {
if (block[k] < 0) {
printf("X");
}
if ((block[k] & 0xff) == 0x00 || (block[k] & 0xff) == 0xff) {
printf(".");
} else if ((block[k] & 0xff) < 32 || (block[k] & 0xff) >= 127) {
printf("?");
} else {
printf("%c", block[k] & 0xff);
}
}
printf("\r\n");
}
i2c_driver_delete(i2c_port);
return 0;
}
static void register_i2cdump(void)
{
i2cdump_args.chip_address = arg_int1("c", "chip", "<chip_addr>", "Specify the address of the chip on that bus");
i2cdump_args.size = arg_int0("s", "size", "<size>", "Specify the size of each read");
i2cdump_args.end = arg_end(1);
const esp_console_cmd_t i2cdump_cmd = {
.command = "i2cdump",
.help = "Examine registers visible through the I2C bus",
.hint = NULL,
.func = &do_i2cdump_cmd,
.argtable = &i2cdump_args
};
ESP_ERROR_CHECK(esp_console_cmd_register(&i2cdump_cmd));
}
void register_i2ctools(void)
{
register_i2cconfig();
register_i2cdectect();
register_i2cget();
register_i2cset();
register_i2cdump();
}

View File

@@ -0,0 +1,20 @@
/* cmd_i2ctools.h
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
void register_i2ctools(void);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,3 @@
#
# Main Makefile. This is basically the same as a component makefile.
#

View File

@@ -0,0 +1,71 @@
/* i2c-tools example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>
#include "sdkconfig.h"
#include "esp_log.h"
#include "esp_console.h"
#include "esp_vfs_fat.h"
#include "cmd_system.h"
#include "cmd_i2ctools.h"
static const char *TAG = "i2c-tools";
#if CONFIG_EXAMPLE_STORE_HISTORY
#define MOUNT_PATH "/data"
#define HISTORY_PATH MOUNT_PATH "/history.txt"
static void initialize_filesystem(void)
{
static wl_handle_t wl_handle;
const esp_vfs_fat_mount_config_t mount_config = {
.max_files = 4,
.format_if_mount_failed = true
};
esp_err_t err = esp_vfs_fat_spiflash_mount(MOUNT_PATH, "storage", &mount_config, &wl_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
return;
}
}
#endif // CONFIG_EXAMPLE_STORE_HISTORY
void app_main(void)
{
esp_console_repl_t *repl = NULL;
esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
esp_console_dev_uart_config_t uart_config = ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT();
#if CONFIG_EXAMPLE_STORE_HISTORY
initialize_filesystem();
repl_config.history_save_path = HISTORY_PATH;
#endif
repl_config.prompt = "i2c-tools>";
// init console REPL environment
ESP_ERROR_CHECK(esp_console_new_repl_uart(&uart_config, &repl_config, &repl));
register_i2ctools();
register_system();
printf("\n ==============================================================\n");
printf(" | Steps to Use i2c-tools |\n");
printf(" | |\n");
printf(" | 1. Try 'help', check all supported commands |\n");
printf(" | 2. Try 'i2cconfig' to configure your I2C bus |\n");
printf(" | 3. Try 'i2cdetect' to scan devices on the bus |\n");
printf(" | 4. Try 'i2cget' to get the content of specific register |\n");
printf(" | 5. Try 'i2cset' to set the value of specific register |\n");
printf(" | 6. Try 'i2cdump' to dump all the register (Experiment) |\n");
printf(" | |\n");
printf(" ==============================================================\n\n");
// start console REPL
ESP_ERROR_CHECK(esp_console_start_repl(repl));
}

View File

@@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size, Flags
# Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 1M,
storage, data, fat, , 1M,
1 # Name, Type, SubType, Offset, Size, Flags
2 # Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
3 nvs, data, nvs, 0x9000, 0x6000,
4 phy_init, data, phy, 0xf000, 0x1000,
5 factory, app, factory, 0x10000, 1M,
6 storage, data, fat, , 1M,

View File

@@ -0,0 +1,17 @@
# Reduce bootloader log verbosity
CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y
CONFIG_BOOTLOADER_LOG_LEVEL=2
# Increase main task stack size
CONFIG_ESP_MAIN_TASK_STACK_SIZE=7168
# Enable filesystem
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_example.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_example.csv"
# Enable FreeRTOS stats formatting functions, needed for 'tasks' command
CONFIG_FREERTOS_USE_TRACE_FACILITY=y
CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS=y
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y