arduino / arduino/ArduinoCore-API

API Improvement - Wire Library

Abierto
#244 0 comentarios 0 reacciones 0 asignados Ver en GitHub
enhancement
Lenguaje dominante
C++
Estrellas
306
Forks
150
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

### API component

There should be consideration for improving the Wire library.

### Description

I propose a lower-level version of the Wire library that is more tethered to what's actually happening on the hardware.
The current implementation imposes unnecessary buffering and busy-loops, that it's not usable in any situation where timing is critical.
I propose supplementing the Arduino Core with a new I2C interface, which the Wire library can use as a HAL component.

My suggestion is this (roughly):

```c++
enum class I2CStatus {
Ready, // Ready for the next operation
Busy, // Currently processing
Error, // An error occurred
Completed // Operation completed successfully
};

class I2C {
public:
virtual ~I2C() = default;

// Start the I2C communication (generate START condition)
virtual void start(uint8_t address, bool write) = 0;

// Stop the I2C communication (generate STOP condition)
virtual void stop() = 0;

// Write a single byte to the I2C bus
virtual void writeByte(uint8_t byte) = 0;

// Send ack to respond to an incoming byte
virtual void sendAck(bool ack) = 0;

// Check the current status of the I2C bus
virtual I2CStatus getStatus() const = 0;

// Polling mechanism or ISR-driven handling will manage the progress
virtual void process() = 0;

// Returns 1 if a byte has been read
virtual int available() = 0;

// Returns a byte that has been read or a -1
virtual int read() = 0;
};
```

In regards to the ISR functions, you would have one for start conditions, stop conditions, reads, write,s etc. I didn't include them in this code example, but you'd probably want to add those as well.

### Is this a breaking change?

It doesn't have to be. This can be implemented as a lower-level I2C library, and utilized in the Wire library. I noticed in both the SAMD core an the AVR code, a lot of the buffering logic in the Wire library is duplicated. Having this lower-level platform abstraction could potentially reduce some of that by making the Wire library a higher level library. Although I think the Wire library should be deprecated, it would still be good to have it for backwards compatibility. Here's what I mean:

```c++
class TwoWire final
{
public:
TwoWire(I2C* bus)
: bus_(bus)
{}
int endTransmission()
{
bus_->start(); // send start condition
// This polling/blocking behavior would be kept for compatibility, but the user's of the lower level library would be able to bypass it.
while (bus_->getStatus() != I2CStatus::Busy) {
busy_->process();
}
// error checking would go here
// write start address with R/W bit
// poll again, as shown above
// perform the write operations
return 0; // success
}
private:
I2C* bus_{};
};
```

I've left out some detail out because I think the code gets the point across.
However if that's not true, I can elaborate more.

### Additional information

The reason this is important to me is because I see Arduino as a good framework for cross-platform embedded programming (specifically when it comes to prototyping). The I2C busy loops are an issue for me because they make it more difficult to get deterministic timing. The reason why deterministic timing is important for Arduino (as a user):
- Data acquisition - if I'm trying to gather data reliably at 1 KHz (for example) on multiple sensors, I need to make sure the deadlines are getting hit for each transaction. Currently the API performs all the transactions at `endTransmission`, which is problematic.
- Motion Control - There are a lot of devices coming out that use I2C, due to the Qwiic and STEMMA QT interfaces made by SparkFun and Adafruit.

These companies are providing drivers for the I2C boards they're making, but they're limited in their quality due to the `Wire` API.
Because of the success and widespread adoption of Arduino and the popularity of I2C boards in rapid-prototyping boards, the I2C API needs a more robust, lower level standard.

If you're concerned about the user-friendliness:
- You can keep the `Wire` library, and even have it implemented by the new lower level HAL
- Most Arduino users aren't writing I2C drivers, the board manufactures are. The developers for the board manufactures are usually seasoned professionals.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Línea de trabajo

Comienza comparando la lógica de búfer duplicada en las implementaciones de Wire para SAMD y AVR, y después revisa cómo podría exponer la Arduino Core API la abstracción I2C de más bajo nivel propuesta. Evalúa los requisitos de estado, polling e ISR frente a las necesidades de temporización determinista. Para darlo por terminado se requerirían un diseño de API acordado y una implementación completa que preserve la compatibilidad con Wire.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
cpp
Área
api, embedded-iot
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.