Using a library that needs a TwoWire pointer - Testato/SoftwareWire GitHub Wiki
With version 1.6.0 in 2021, the inheritance from the TwoWire
class was removed from the SoftwareWire library
because the TwoWire
class cannot be used polymorphically.
(See #28 and #32.)
When a library is used that needs a TwoWire
pointer, the source code of that library has to be edited.
-
Bring the library files into the project. Rename them to avoid confusion with the original files. Each file has a separate tab in the Arduino IDE.
-
Remove all the
#include <Wire.h>
from all the files (check every *.ino, *.h and *.cpp file). -
Create the SoftwareWire object
Wire
in the sketch (the most important *.ino file is in the most left tab):
#include <SoftwareWire.h>
SoftwareWire Wire( A4, A5);
- Add a file
WireGlue.h
and put these lines in it:
#include <SoftwareWire.h>
#define TwoWire SoftwareWire
extern SoftwareWire Wire;
Instead of the #define TwoWire SoftwareWire
, the class alias using TwoWire = SoftwareWire;
may also be used.
- Add
#include "WireGlue.h
to the library *.h files. Sometimes it needs to be included in the *.cpp files as well.
If the Arduino Wire library is included somewhere, then the source code of the library has to be edited more. The SoftwareWire object may no longer be called Wire
, and all the Wire
and TwoWire
references in the library has to be changed to the SoftwareWire object and the SoftwareWire class.
Here is an example with libraries files that are changed: https://wokwi.com/arduino/projects/307886580731740737?dark=1 The steps to change it for the SofwareWire and isolate the library files from the rest are:
- Copy the library files into the project and give them an other name to avoid a conflict.
- Rename the class and object as well, to avoid a conflict
- Change a TwoWire pointer to a SoftwareWire pointer, or add that to the class if it does not exist.
- Use a SoftwareWire pointer as parameter in the constructor and copy it to the member in the constructor function.
- Change all the function calls in the class that use a 'Wire' function, so they use the SoftwareWire pointer.
- If there are too many I2C buses and too many library objects, then an array of pointers can be used which can be filled in the setup() function.