Commit da3bcf5a authored by Eric Duminil's avatar Eric Duminil
Browse files

Senseair S8 also works on ESP8266 now

parent 269b8b2f
Pipeline #6042 passed with stage
in 1 minute and 57 seconds
......@@ -18,17 +18,19 @@ namespace config {
}
#if defined(ESP8266)
// For ESP8266 : RX on GPIO3, TX on GPIO1
//TODO: Really not sure it works
# define S8_UART_PORT 0
# include "src/lib/EspSoftwareSerial/SoftwareSerial.h"
# define S8_RX_PIN 13 // GPIO13, a.k.a. D7, connected to S8 Tx pin.
# define S8_TX_PIN 15 // GPIO15, a.k.a. D8, connected to S8 Rx pin.
SoftwareSerial S8_serial(S8_RX_PIN, S8_TX_PIN);
#endif
#if defined(ESP32)
// For ESP32 : RX on GPIO17, TX on GPIO16
# define S8_UART_PORT 2
// GPIO16 connected to S8 Tx pin.
// GPIO17 connected to S8 Rx pin.
# define S8_UART_PORT 2
HardwareSerial S8_serial(S8_UART_PORT);
#endif
namespace sensor {
HardwareSerial S8_serial(S8_UART_PORT);
S8_UART *sensor_S8;
S8_sensor s8;
uint16_t co2 = 0;
......
This diff is collapsed.
# EspSoftwareSerial
## Implementation of the Arduino software serial library for the ESP8266 / ESP32 family
This fork implements interrupt service routine best practice.
In the receive interrupt, instead of blocking for whole bytes
at a time - voiding any near-realtime behavior of the CPU - only level
change and timestamp are recorded. The more time consuming phase
detection and byte assembly are done in the main code.
Except at high bitrates, depending on other ongoing activity,
interrupts in particular, this software serial adapter
supports full duplex receive and send. At high bitrates (115200bps)
send bit timing can be improved at the expense of blocking concurrent
full duplex receives, with the `SoftwareSerial::enableIntTx(false)` function call.
The same functionality is given as the corresponding AVR library but
several instances can be active at the same time. Speed up to 115200 baud
is supported. Besides a constructor compatible to the AVR SoftwareSerial class,
and updated constructor that takes no arguments exists, instead the `begin()`
function can handle the pin assignments and logic inversion.
It also has optional input buffer capacity arguments for byte buffer and ISR bit buffer.
This way, it is a better drop-in replacement for the hardware serial APIs on the ESP MCUs.
Please note that due to the fact that the ESPs always have other activities
ongoing, there will be some inexactness in interrupt timings. This may
lead to inevitable, but few, bit errors when having heavy data traffic
at high baud rates.
This library supports ESP8266, ESP32, ESP32-S2 and ESP32-C3 devices.
## Resource optimization
The memory footprint can be optimized to just fit the amount of expected
incoming asynchronous data.
For this, the `SoftwareSerial` constructor provides two arguments. First, the
octet buffer capacity for assembled received octets can be set. Read calls are
satisfied from this buffer, freeing it in return.
Second, the signal edge detection buffer of 32bit fields can be resized.
One octet may require up to to 10 fields, but fewer may be needed,
depending on the bit pattern. Any read or write calls check this buffer
to assemble received octets, thus promoting completed octets to the octet
buffer, freeing fields in the edge detection buffer.
Look at the swsertest.ino example. There, on reset, ASCII characters ' ' to 'z'
are sent. This happens not as a block write, but in a single write call per
character. As the example uses a local loopback wire, every outgoing bit is
immediately received back. Therefore, any single write call causes up to
10 fields - depending on the exact bit pattern - to be occupied in the signal
edge detection buffer. In turn, as explained before, each single write call
also causes received bit assembly to be performed, promoting these bits from
the signal edge detection buffer to the octet buffer as soon as possible.
Explaining by way of contrast, if during a a single write call, perhaps because
of using block writing, more than a single octet is received, there will be a
need for more than 10 fields in the signal edge detection buffer.
The necessary capacity of the octet buffer only depends on the amount of incoming
data until the next read call.
For the swsertest.ino example, this results in the following optimized
constructor arguments to spend only the minimum RAM on buffers required:
The octet buffer capacity (`bufCapacity`) is 95 (93 characters net plus two tolerance).
The signal edge detection buffer capacity (`isrBufCapacity`) is 11, as each
single octet can have up to 11 bits on the wire,
which are immediately received during the write, and each
write call causes the signal edge detection to promote the previously sent and
received bits to the octet buffer.
In a more generalized scenario, calculate the bits (use message size in octets
times 10) that may be asynchronously received to determine the value for
`isrBufCapacity` in the constructor. Also use the number of received octets
that must be buffered for reading as the value of `bufCapacity`.
The more frequently your code calls write or read functions, the greater the
chances are that you can reduce the `isrBufCapacity` footprint without losing data,
and each time you call read to fetch from the octet buffer, you reduce the
need for space there.
## SoftwareSerialConfig and parity
The configuration of the data stream is done via a `SoftwareSerialConfig`
argument to `begin()`. Word lengths can be set to between 5 and 8 bits, parity
can be N(one), O(dd) or E(ven) and 1 or 2 stop bits can be used. The default is
`SWSERIAL_8N1` using 8 bits, no parity and 1 stop bit but any combination can
be used, e.g. `SWSERIAL_7E2`. If using EVEN or ODD parity, any parity errors
can be detected with the `readParity()` and `parityEven()` or `parityOdd()`
functions respectively. Note that the result of `readParity()` always applies
to the preceding `read()` or `peek()` call, and is undefined if they report
no data or an error.
To allow flexible 9-bit and data/addressing protocols, the additional parity
modes MARK and SPACE are also available. Furthermore, the parity mode can be
individually set in each call to `write()`.
This allows a simple implementation of protocols where the parity bit is used to
distinguish between data and addresses/commands ("9-bit" protocols). First set
up SoftwareSerial with parity mode SPACE, e.g. `SWSERIAL_8S1`. This will add a
parity bit to every byte sent, setting it to logical zero (SPACE parity).
To detect incoming bytes with the parity bit set (MARK parity), use the
`readParity()` function. To send a byte with the parity bit set, just add
`MARK` as the second argument when writing, e.g. `write(ch, SWSERIAL_PARITY_MARK)`.
## Checking for correct pin selection / configuration
In general, most pins on the ESP8266 and ESP32 devices can be used by SoftwareSerial,
however each device has a number of pins that have special functions or require careful
handling to prevent undesirable situations, for example they are connected to the
on-board SPI flash memory or they are used to determine boot and programming modes
after powerup or brownouts. These pins are not able to be configured by this library.
The exact list for each device can be found in the
[ESP32 data sheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf)
in sections 2.2 (Pin Descriptions) and 2.4 (Strapping pins). There is a discussion
dedicated to the use of GPIO12 in this
[note about GPIO12](https://github.com/espressif/esp-idf/tree/release/v3.2/examples/storage/sd_card#note-about-gpio12).
Refer to the `isValidGPIOpin()`, `isValidRxGPIOpin()` and `isValidTxGPIOpin()`
functions for the GPIO restrictions enforced by this library by default.
The easiest and safest method is to test the object returned at runtime, to see if
it is valid. For example:
```
#include <SoftwareSerial.h>
#define MYPORT_TX 12
#define MYPORT_RX 13
SoftwareSerial myPort;
[...]
Serial.begin(115200); // Standard hardware serial port
myPort.begin(38400, SWSERIAL_8N1, MYPORT_RX, MYPORT_TX, false);
if (!myPort) { // If the object did not initialize, then its configuration is invalid
Serial.println("Invalid SoftwareSerial pin configuration, check config");
while (1) { // Don't continue with invalid configuration
delay (1000);
}
}
[...]
```
## Using and updating EspSoftwareSerial in the esp8266com/esp8266 Arduino build environment
EspSoftwareSerial is both part of the BSP download for ESP8266 in Arduino,
and it is set up as a Git submodule in the esp8266 source tree,
specifically in `.../esp8266/libraries/SoftwareSerial` when using a Github
repository clone in your Arduino sketchbook hardware directory.
This supersedes any version of EspSoftwareSerial installed for instance via
the Arduino library manager, it is not required to install EspSoftwareSerial
for the ESP8266 separately at all, but doing so has ill effect.
The responsible maintainer of the esp8266 repository has kindly shared the
following command line instructions to use, if one wishes to manually
update EspSoftwareSerial to a newer release than pulled in via the ESP8266 Arduino BSP:
To update esp8266/arduino SoftwareSerial submodule to lastest master:
Clean it (optional):
```shell
$ rm -rf libraries/SoftwareSerial
$ git submodule update --init
```
Now update it:
```shell
$ cd libraries/SoftwareSerial
$ git checkout master
$ git pull
```
/*
SoftwareSerial.cpp - Implementation of the Arduino software serial for ESP8266/ESP32.
Copyright (c) 2015-2016 Peter Lerup. All rights reserved.
Copyright (c) 2018-2019 Dirk O. Kaar. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SoftwareSerial.h"
#include <Arduino.h>
#ifndef ESP32
uint32_t SoftwareSerial::m_savedPS = 0;
#else
portMUX_TYPE SoftwareSerial::m_interruptsMux = portMUX_INITIALIZER_UNLOCKED;
#endif
inline void IRAM_ATTR SoftwareSerial::disableInterrupts()
{
#ifndef ESP32
m_savedPS = xt_rsil(15);
#else
taskENTER_CRITICAL(&m_interruptsMux);
#endif
}
inline void IRAM_ATTR SoftwareSerial::restoreInterrupts()
{
#ifndef ESP32
xt_wsr_ps(m_savedPS);
#else
taskEXIT_CRITICAL(&m_interruptsMux);
#endif
}
constexpr uint8_t BYTE_ALL_BITS_SET = ~static_cast<uint8_t>(0);
SoftwareSerial::SoftwareSerial() {
m_isrOverflow = false;
m_rxGPIOPullupEnabled = true;
}
SoftwareSerial::SoftwareSerial(int8_t rxPin, int8_t txPin, bool invert)
{
m_isrOverflow = false;
m_rxGPIOPullupEnabled = true;
m_rxPin = rxPin;
m_txPin = txPin;
m_invert = invert;
}
SoftwareSerial::~SoftwareSerial() {
end();
}
bool SoftwareSerial::isValidGPIOpin(int8_t pin) {
#if defined(ESP8266)
return (pin >= 0 && pin <= 16) && !isFlashInterfacePin(pin);
#elif defined(ESP32)
// Remove the strapping pins as defined in the datasheets, they affect bootup and other critical operations
// Remmove the flash memory pins on related devices, since using these causes memory access issues.
#ifdef CONFIG_IDF_TARGET_ESP32
// Datasheet https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf,
// Pinout https://docs.espressif.com/projects/esp-idf/en/latest/esp32/_images/esp32-devkitC-v4-pinout.jpg
return (pin == 1) || (pin >= 3 && pin <= 5) ||
(pin >= 12 && pin <= 15) ||
(!psramFound() && pin >= 16 && pin <= 17) ||
(pin >= 18 && pin <= 19) ||
(pin >= 21 && pin <= 23) || (pin >= 25 && pin <= 27) || (pin >= 32 && pin <= 39);
#elif CONFIG_IDF_TARGET_ESP32S2
// Datasheet https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf,
// Pinout https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/_images/esp32-s2_saola1-pinout.jpg
return (pin >= 1 && pin <= 21) || (pin >= 33 && pin <= 44);
#elif CONFIG_IDF_TARGET_ESP32C3
// Datasheet https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf,
// Pinout https://docs.espressif.com/projects/esp-idf/en/latest/esp32c3/_images/esp32-c3-devkitm-1-v1-pinout.jpg
return (pin >= 0 && pin <= 1) || (pin >= 3 && pin <= 7) || (pin >= 18 && pin <= 21);
#else
return true;
#endif
#else
return true;
#endif
}
bool SoftwareSerial::isValidRxGPIOpin(int8_t pin) {
return isValidGPIOpin(pin)
#if defined(ESP8266)
&& (pin != 16)
#endif
;
}
bool SoftwareSerial::isValidTxGPIOpin(int8_t pin) {
return isValidGPIOpin(pin)
#if defined(ESP32)
#ifdef CONFIG_IDF_TARGET_ESP32
&& (pin < 34)
#elif CONFIG_IDF_TARGET_ESP32S2
&& (pin <= 45)
#elif CONFIG_IDF_TARGET_ESP32C3
// no restrictions
#endif
#endif
;
}
bool SoftwareSerial::hasRxGPIOPullUp(int8_t pin) {
#if defined(ESP32)
return !(pin >= 34 && pin <= 39);
#else
(void)pin;
return true;
#endif
}
void SoftwareSerial::setRxGPIOPullUp() {
if (m_rxValid) {
pinMode(m_rxPin, hasRxGPIOPullUp(m_rxPin) && m_rxGPIOPullupEnabled ? INPUT_PULLUP : INPUT);
}
}
void SoftwareSerial::begin(uint32_t baud, SoftwareSerialConfig config,
int8_t rxPin, int8_t txPin,
bool invert, int bufCapacity, int isrBufCapacity) {
if (-1 != rxPin) m_rxPin = rxPin;
if (-1 != txPin) m_txPin = txPin;
m_oneWire = (m_rxPin == m_txPin);
m_invert = invert;
m_dataBits = 5 + (config & 07);
m_parityMode = static_cast<SoftwareSerialParity>(config & 070);
m_stopBits = 1 + ((config & 0300) ? 1 : 0);
m_pduBits = m_dataBits + static_cast<bool>(m_parityMode) + m_stopBits;
m_bitCycles = (ESP.getCpuFreqMHz() * 1000000UL + baud / 2) / baud;
m_intTxEnabled = true;
if (isValidRxGPIOpin(m_rxPin)) {
m_buffer.reset(new circular_queue<uint8_t>((bufCapacity > 0) ? bufCapacity : 64));
if (m_parityMode)
{
m_parityBuffer.reset(new circular_queue<uint8_t>((m_buffer->capacity() + 7) / 8));
m_parityInPos = m_parityOutPos = 1;
}
m_isrBuffer.reset(new circular_queue<uint32_t, SoftwareSerial*>((isrBufCapacity > 0) ?
isrBufCapacity : m_buffer->capacity() * (2 + m_dataBits + static_cast<bool>(m_parityMode))));
if (m_buffer && (!m_parityMode || m_parityBuffer) && m_isrBuffer) {
m_rxValid = true;
setRxGPIOPullUp();
}
}
if (isValidTxGPIOpin(m_txPin)) {
m_txValid = true;
if (!m_oneWire) {
pinMode(m_txPin, OUTPUT);
digitalWrite(m_txPin, !m_invert);
}
}
if (!m_rxEnabled) { enableRx(true); }
}
void SoftwareSerial::end()
{
enableRx(false);
m_txValid = false;
if (m_buffer) {
m_buffer.reset();
}
m_parityBuffer.reset();
if (m_isrBuffer) {
m_isrBuffer.reset();
}
}
uint32_t SoftwareSerial::baudRate() {
return ESP.getCpuFreqMHz() * 1000000UL / m_bitCycles;
}
void SoftwareSerial::setTransmitEnablePin(int8_t txEnablePin) {
if (isValidTxGPIOpin(txEnablePin)) {
m_txEnableValid = true;
m_txEnablePin = txEnablePin;
pinMode(m_txEnablePin, OUTPUT);
digitalWrite(m_txEnablePin, LOW);
}
else {
m_txEnableValid = false;
}
}
void SoftwareSerial::enableIntTx(bool on) {
m_intTxEnabled = on;
}
void SoftwareSerial::enableRxGPIOPullup(bool on) {
m_rxGPIOPullupEnabled = on;
setRxGPIOPullUp();
}
void SoftwareSerial::enableTx(bool on) {
if (m_txValid && m_oneWire) {
if (on) {
enableRx(false);
pinMode(m_txPin, OUTPUT);
digitalWrite(m_txPin, !m_invert);
}
else {
setRxGPIOPullUp();
enableRx(true);
}
}
}
void SoftwareSerial::enableRx(bool on) {
if (m_rxValid) {
if (on) {
m_rxLastBit = m_pduBits - 1;
// Init to stop bit level and current cycle
m_isrLastCycle = (ESP.getCycleCount() | 1) ^ m_invert;
if (m_bitCycles >= (ESP.getCpuFreqMHz() * 1000000UL) / 74880UL)
attachInterruptArg(digitalPinToInterrupt(m_rxPin), reinterpret_cast<void (*)(void*)>(rxBitISR), this, CHANGE);
else
attachInterruptArg(digitalPinToInterrupt(m_rxPin), reinterpret_cast<void (*)(void*)>(rxBitSyncISR), this, m_invert ? RISING : FALLING);
}
else {
detachInterrupt(digitalPinToInterrupt(m_rxPin));
}
m_rxEnabled = on;
}
}
int SoftwareSerial::read() {
if (!m_rxValid) { return -1; }
if (!m_buffer->available()) {
rxBits();
if (!m_buffer->available()) { return -1; }
}
auto val = m_buffer->pop();
if (m_parityBuffer)
{
m_lastReadParity = m_parityBuffer->peek() & m_parityOutPos;
m_parityOutPos <<= 1;
if (!m_parityOutPos)
{
m_parityOutPos = 1;
m_parityBuffer->pop();
}
}
return val;
}
int SoftwareSerial::read(uint8_t* buffer, size_t size) {
if (!m_rxValid) { return 0; }
int avail;
if (0 == (avail = m_buffer->pop_n(buffer, size))) {
rxBits();
avail = m_buffer->pop_n(buffer, size);
}
if (!avail) return 0;
if (m_parityBuffer) {
uint32_t parityBits = avail;
while (m_parityOutPos >>= 1) ++parityBits;
m_parityOutPos = (1 << (parityBits % 8));
m_parityBuffer->pop_n(nullptr, parityBits / 8);
}
return avail;
}
size_t SoftwareSerial::readBytes(uint8_t* buffer, size_t size) {
if (!m_rxValid || !size) { return 0; }
size_t count = 0;
auto start = millis();
do {
auto readCnt = read(&buffer[count], size - count);
count += readCnt;
if (count >= size) break;
if (readCnt) start = millis();
else optimistic_yield(1000UL);
} while (millis() - start < _timeout);
return count;
}
int SoftwareSerial::available() {
if (!m_rxValid) { return 0; }
rxBits();
int avail = m_buffer->available();
if (!avail) {
optimistic_yield(10000UL);
}
return avail;
}
void IRAM_ATTR SoftwareSerial::preciseDelay(bool sync) {
if (!sync)
{
// Reenable interrupts while delaying to avoid other tasks piling up
if (!m_intTxEnabled) { restoreInterrupts(); }
const auto expired = ESP.getCycleCount() - m_periodStart;
const int32_t remaining = m_periodDuration - expired;
const int32_t ms = remaining > 0 ? remaining / 1000L / static_cast<int32_t>(ESP.getCpuFreqMHz()) : 0;
if (ms > 0)
{
delay(ms);
}
else
{
optimistic_yield(10000UL);
}
}
while ((ESP.getCycleCount() - m_periodStart) < m_periodDuration) {}
// Disable interrupts again if applicable
if (!sync && !m_intTxEnabled) { disableInterrupts(); }
m_periodDuration = 0;
m_periodStart = ESP.getCycleCount();
}
void IRAM_ATTR SoftwareSerial::writePeriod(
uint32_t dutyCycle, uint32_t offCycle, bool withStopBit) {
preciseDelay(true);
if (dutyCycle)
{
digitalWrite(m_txPin, HIGH);
m_periodDuration += dutyCycle;
if (offCycle || (withStopBit && !m_invert)) preciseDelay(!withStopBit || m_invert);
}
if (offCycle)
{
digitalWrite(m_txPin, LOW);
m_periodDuration += offCycle;
if (withStopBit && m_invert) preciseDelay(false);
}
}
size_t SoftwareSerial::write(uint8_t byte) {
return write(&byte, 1);
}
size_t SoftwareSerial::write(uint8_t byte, SoftwareSerialParity parity) {
return write(&byte, 1, parity);
}
size_t SoftwareSerial::write(const uint8_t* buffer, size_t size) {
return write(buffer, size, m_parityMode);
}
size_t IRAM_ATTR SoftwareSerial::write(const uint8_t* buffer, size_t size, SoftwareSerialParity parity) {
if (m_rxValid) { rxBits(); }
if (!m_txValid) { return -1; }
if (m_txEnableValid) {
digitalWrite(m_txEnablePin, HIGH);
}
// Stop bit: if inverted, LOW, otherwise HIGH
bool b = !m_invert;
uint32_t dutyCycle = 0;
uint32_t offCycle = 0;
if (!m_intTxEnabled) {
// Disable interrupts in order to get a clean transmit timing
disableInterrupts();
}
const uint32_t dataMask = ((1UL << m_dataBits) - 1);
bool withStopBit = true;
m_periodDuration = 0;
m_periodStart = ESP.getCycleCount();
for (size_t cnt = 0; cnt < size; ++cnt) {
uint8_t byte = pgm_read_byte(buffer + cnt) & dataMask;
// push LSB start-data-parity-stop bit pattern into uint32_t
// Stop bits: HIGH
uint32_t word = ~0UL;
// inverted parity bit, performance tweak for xor all-bits-set word
if (parity && m_parityMode)
{
uint32_t parityBit;
switch (parity)
{
case SWSERIAL_PARITY_EVEN:
// from inverted, so use odd parity
parityBit = byte;
parityBit ^= parityBit >> 4;
parityBit &= 0xf;