This module supports different interfaces for communicating via I²C protocol. All interfaces can be assigned to arbitrary GPIOs for SCL and SDA and can be operated concurrently.
-`i2c.SW` software based bitbanging, master mode only, synchronous operation
This module supports 3 different interfaces for I²C communication on a ESP-32.
-`i2c.HW0` ESP32 hardware port 0, master or slave mode, synchronous or asynchronous operation
-`i2c.HW1` ESP32 hardware port 1, master or slave mode, synchronous or asynchronous operation
The hardware master interfaces differ from the SW interface as the commands (start, stop, read, write) are queued up to an internal command list. Actual I²C communication is initiated afterwards using the `i2c.transfer()` function. Commands for the `i2c.SW` interface are immediately effective on the I²C bus and read data is also instantly available.
The interface `id` can be
-`i2c.SW` software based bitbanging, master mode only, immediate execution, synchronous operation, maximum speed 100 KHz (Standard mode)
-`i2c.HW0` ESP32 hardware bus interface 0, master or slave mode, deferred execution, synchronous or asynchronous operation, maximum speed 1 MHz (Fast-mode Plus)
-`i2c.HW1` ESP32 hardware bus interface 1, master or slave mode, deferred execution, synchronous or asynchronous operation, maximum speed 1 MHz (Fast-mode Plus)
## i2c.address()
All interfaces can be used at the same time.
Send (`SW`) or queue (`HWx`) I²C address and read/write mode for the next transfer.
Interfaces can use arbitrary GPIOs for the clock (SCL) and data (SDA) lines.
The interfaces are not suitable for multi-master configurations.
In master mode, I²C communication is performed by combinations of 5 basic I²C operations, provided by the functions `i2c.start()`,`i2c.stop()`,`i2c.address()`,`i2c.write()`,`i2c.read()`.
The behaviour of these functions is quite different according to the type of interface.
For the software interface, these functions IMMEDIATELY perform the requested I²C operation and return on completion. For slow bus speeds and multi-byte reads or writes, this can tie up the CPU for a significant time.
However, any results returned reflect the effective outcome of the operation.
For the hardware interfaces, these functions do NOT trigger any immediate I²C activity but enqueue (store) a request for later, DEFERRED execution.
These functions return immediately as they do not have to wait for any I²C operation to complete.
As a consequence, any results returned do not reflect the effective outcome of the operation.
The function `i2c.transfer()` MUST be called to effectively execute the stored requests for operations.
Execution of the stored requests is performed by the hardware interface.
If `i2c.transfer()` is provided with a call-back function, it will return before completion of the enqueued I²C operations, freeing the CPU for other tasks.
#### Example using the software interface
```lua
-- check if chip is present and functional by reading a signature/chip id
-- i2c bus setup
sda=23-- pins as on Adafruit Huzzah32 silkscreen
scl=22
id=i2c.SW-- software interface
speed=i2c.SLOW
-- values for Bosch Sensortech BMP180 chip
bmpAddress=0x77
bmpIdRegister=0xD0
bmpChipSignature=0x55
-- initialize i2c software interface
i2c.setup(id,sda,scl,speed)
-- attempt to read chip id and compare against expected value
-`direction``i2c.TRANSMITTER` for writing mode , `i2c.RECEIVER` for reading mode
-`direction``i2c.TRANSMITTER` for write mode , `i2c.RECEIVER` for read mode
-`ack_check_en` enable check for slave ACK with `true` (default), disable with `false`
-`ack_check_en` enable check for slave ACK with `true` (default), disable check with `false`
This last, optional parameter is only relevant for for hardware interfaces `i2c.HW0` and `i2c.HW1` and defaults to `true'.
The I²C `address` operation is enqueued for later execution and this parameter will be used at that later time.
At that time, if NO slave device produces an ACK to the address operation, the default assumption is that the slave at that address is absent or not functional. Any remaining I²C operations in the queue will be ignored/flushed/discarded and the communication will be stopped.
This default queue flushing behaviour on slave NACK can be overridden by specifying `false`.
#### Returns
#### Returns
`true` if ack received (always for ids `i2c.HW0` and `i2c.HW1`), `false` if no ack received (only possible for `i2c.SW`).
for interface `i2c.SW`: returns `true` if ack received, `false` if no ack received. This value should be checked to decide whether to continue communication.
for interfaces `i2c.HW0` and `i2c.HW1`: always returns `true`.
#### See also
[i2c.read()](#i2cread)
## i2c.read()
## i2c.read()
Read (`SW`) or queue (`HWx`) data for variable number of bytes.
Perform (`SW`) or enqueue (`HWx`) a data read operation for a variable number of bytes.
#### Syntax
#### Syntax
`i2c.read(id, len)`
`i2c.read(id, len)`
#### Parameters
#### Parameters
-`id` interface id
- `id` I²C interface id
-`len` number of data bytes
- `len` number of data bytes to read
#### Returns
#### Returns
-`string` of received data for interface `i2c.SW`
- for software interface `i2c.SW` : returns `string` of received data
-`nil` for ids`i2c.HW0`and `i2c.HW1`
- for hardware interfaces id `i2c.HWx` : no value returned
#### Example
For the hardware interfaces, any values read from the bus will be returned by the `i2c.transfer()` function or the associated callback function.
```lua
For this reason, a sequence of enqueued operations may only contain one read request.
id=i2c.SW
sda=1
The value returned by a read operation is a string. Refer to the slave datasheet for multibyte reads/autoincrement capability, endianness and format details.
scl=2
-- initialize i2c, set pin1 as sda, set pin2 as scl
i2c.setup(id,sda,scl,i2c.SLOW)
-- user defined function: read from reg_addr content of dev_addr
- `pinSDA` IO index, see [GPIO Overview](gpio.md#gpio-overview)
- `pinSDA` IO index, see [GPIO Overview](gpio.md#gpio-overview)
- `pinSCL` IO index, see [GPIO Overview](gpio.md#gpio-overview)
- `pinSCL` IO index, see [GPIO Overview](gpio.md#gpio-overview)
-`speed` bit rate in Hz, positive integer
- `speed` bit rate in Hz, integer
-`i2c.SLOW` for 100000 Hz, max for `i2c.SW`
- `i2c.SLOW` for 100000 Hz (100 KHz a.k.a Standard Mode), this is the maximum allowed value for the `i2c.SW` interface
-`i2c.FAST` for 400000 Hz
- `i2c.FAST` for 400000 Hz (400 KHz a.k.a Fast Mode)
-`i2c.FASTPLUS` for 1000000 Hz
- `i2c.FASTPLUS` for 1000000 Hz (1 MHz, a.k.a. Fast-mode Plus), this is the maximum allowed value for `i2c.HWx`interfaces
- `stretchfactor` integer multiplier for timeout
The pins declared for SDA and SCL are configured with onchip pullup resistors. These are weak pullups.
The data sheets do not specify any specific value for the pullup resistors, but they are reported to be between 10KΩ and 100KΩ with a target value of 50 KΩ.
Additional pullups are recommended especialy for faster speeds, in doubt try 4.7 kΩ.
The `speed` constants are provided for convenience but any other integer value can be used.
The last, optional parameter `stretchfactor` is only relevant for the `HWx`interfaces and defaults to 1.
The hardware interfaces have a built-in timeout, designed to recover from abnormal I²C bus conditions.
The default timeout is defined as 8 I²C SCL clock cycles. With an 80 MHz CPU clock speed and a 100 KHz this means 8*80/0.1 = 6400 CPU clock cycles i.e. 80 µS.
A busy or slow slave device can request a temporary pause of communication by keeping the SCL line line low a.k.a. clock stretching.
This clock stretching may exceed the timeout value and cause (often intermittent) errors.
This can be avoided either by using a slower bit rate or by specifying a multiplier value for the timeout.
Calling setup on an already configured hardware interface will cause panic.
Note to wizards: The I²C specifications defines a High-Speed mode allowing communication up to 3.4 Mbits/s, with the added complexity of variable clock speed and current-source pullups. The Expressif documentation states that the I²C hardware interfaces support up to 5 MHz, constrained by SDA pull-up strength. This module will object to speeds higher than 1 MHz, but your experience and feedback is welcome !
#### Returns
#### Returns
`speed` the selected speed
for interface `i2c.SW`: returns `speed` the selected speed.
####See also
for interfaces `i2c.HW0` and `i2c.HW1`: returns `timeout` expressed as CPU clock cycles.
#### See also
[i2c.read()](#i2cread)
[i2c.read()](#i2cread)
## i2c.start()
## i2c.start()
Send (`SW`) or queue (`HWx`) an I²C start condition.
Perform (`SW`) or enqueue (`HWx`) an I²C start condition.
#### Syntax
#### Syntax
`i2c.start(id)`
`i2c.start(id)`
...
@@ -106,66 +226,77 @@ Send (`SW`) or queue (`HWx`) an I²C start condition.
...
@@ -106,66 +226,77 @@ Send (`SW`) or queue (`HWx`) an I²C start condition.
`id` interface id
`id` interface id
#### Returns
#### Returns
`nil`
no returned value
####See also
####See also
[i2c.read()](#i2cread)
[i2c.read()](#i2cread)
## i2c.stop()
## i2c.stop()
Send (`SW`) or queue (`HWx`) an I²C stop condition.
Perform (`SW`) or enqueue (`HWx`) an I²C stop condition.
#### Syntax
#### Syntax
`i2c.stop(id)`
`i2c.stop(id)`
####Parameters
####Parameters
`id` interface id
`id` interface id
#### Returns
#### Returns
`nil`
no returned value
####See also
####See also
[i2c.read()](#i2cread)
[i2c.read()](#i2cread)
## i2c.transfer()
## i2c.transfer()
Starts a transfer for the specified hardware module. Providing a callback function allows the transfer to be started asynchronously in the background and `i2c.transfer()` finishes immediately. Without a callback function, the transfer is executed synchronously and `i2c.transfer()` comes back when the transfer completed. Data from a read operation is returned from `i2c.transfer()` in this case.
Starts a transfer for the specified hardware module.
First argument to the callback is a string with data obtained from a read operation during the transfer or `nil`, followed by the ack flag (true = ACK received).
Providing a callback function allows the transfer to be started asynchronously in the background and `i2c.transfer()` finishes immediately, without returning any value.
Results from any data read will be provided to the callback function.
Without a callback function, the transfer is executed synchronously and `i2c.transfer()` returns when the transfer completes.
In this case, this function returns read values and an ACK flag.
#### Syntax
#### Syntax
`i2c.transfer(id[, cb_fn][, to_ms])`
`i2c.transfer(id[, callback] [, to_ms])`
#### Parameters
#### Parameters
-`id` interface id, `i2c.SW` not allowed
- `id` hardware interface id only , `i2c.SW` not allowed
-`cb_fn(data, ack)` function to be called when transfer finished
- `callback` optional callback function to be called when transfer finishes
-`to_ms` timeout for the transfer in ms, defaults to 0=infinite
- `to_ms` optional timeout for the synchronous transfer in ms, defaults to 0 (infinite)
The optional callback function should be defined to accept 2 arguments i.e. `function( data , ack )` where
- `data `is the string from a read operation during the transfer (`nil` if no read or failed ACK )
- `ack is a boolean (true = ACK received).
The optional timeout parameter defaults to 0 meaning infinite and is only relevant for synchronous mode. This can be used to define an upper bound to the execution time of `i2c.transfer()`.
It specifies the maximum delay in mS before `i2c.transfer()` returns, possibly before the complete I²C set of operations is executed.
This timeout should not be confused with the timeout specified in `i2c.setup`.
#### Returns
#### Returns
- synchronous operation:
-for synchronous operation i.e. without any callback function, two values are returned
-`data` string of received data (`nil` if no read or NACK)
-`data` string of received data (`nil` if no read or NACK)
-`ack` true if ACK received, false for NACK
-`ack` true if ACK received, false for NACK
-`nil`for asynchronous operation
- for asynchronous operation, i.e. with a callback function, no value is returned
## i2c.write()
## i2c.write()
Write (`SW`) or queue (`HWx`) data to I²C bus. Data items can be multiple numbers, strings or lua tables.
Perform (`SW`) or enqueue (`HWx`) data write to I²C bus.
Communication stops when the slave answers with NACK to a written byte. This can be avoided with parameter `ack_check_en` on `false`.