#include <OpenWire.h>// Create an OpenWire object on Serial (UART) OpenWire wire(&Serial);
int sensorValue = 0;
void setup() Serial.begin(115200); // High baudrate for binary data wire.begin(); // Initialize OpenWire
void loop() sensorValue = analogRead(A0);
// Send as a 16-bit integer (command ID 0x01) wire.write(0x01, (uint8_t*)&sensorValue, sizeof(sensorValue));
delay(100);
Now that OpenWire.h is installed, let's write a basic send/receive example. openwire.h library download arduino
Let’s apply OpenWire in a practical scenario: an RC car with nRF24L01 modules.
Transmitter (Arduino Nano + Joystick):
#include <SPI.h> #include <RF24.h> #include <OpenWire.h>RF24 radio(9, 10); OpenWire wire(&radio); // Yes, OpenWire works with RF24!
void setup() radio.begin(); wire.begin();
void loop() int x = analogRead(A1); int y = analogRead(A2); wire.write(0x10, (uint8_t*)&x, 2); wire.write(0x11, (uint8_t*)&y, 2); delay(20);
Receiver (Arduino Uno + Motor Driver):
#include <RF24.h> #include <OpenWire.h>RF24 radio(9, 10); OpenWire wire(&radio); int leftSpeed, rightSpeed;
void handleMotor(byte id, byte* data, byte len) if(id == 0x10) memcpy(&leftSpeed, data, 2); if(id == 0x11) memcpy(&rightSpeed, data, 2); analogWrite(5, leftSpeed/4); // Scale 0-1023 to 0-255 analogWrite(6, rightSpeed/4);
void setup() radio.begin(); wire.begin(); wire.setCallback(handleMotor);
void loop() wire.process();
This example demonstrates how OpenWire.h abstracts the underlying transport (UART, SPI, or even nRF24), allowing you to focus on application logic.
Yes. The library uses pure C++ and standard Arduino Streams. It works on any board supported by Arduino core (ESP32, ESP8266, SAMD, STM32). However, check the GitHub README for platform-specific notes on hardware serial buffers. #include <OpenWire
Let’s build a minimal example to read a Modbus-like sensor using OpenWire’s framing.
Hardware: Arduino Uno + MAX485 module + any RS485 soil moisture sensor.
#include <openwire.h>// Define serial port for RS485 (use Serial1 on Mega, SoftwareSerial on Uno) #define RS485 Serial
OpenWire bus; // create bus instance
void setup() RS485.begin(9600); bus.attach(&RS485); // attach to hardware serial bus.setTimeout(100); // 100ms response timeout
void loop() byte request[] = 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x31, 0xCA; byte response[20];
if (bus.transaction(request, sizeof(request), response, sizeof(response))) response[4]; Serial.print("Moisture: "); Serial.println(soilMoisture); else Serial.println("No response or CRC error"); delay(2000);void loop() sensorValue = analogRead(A0); // Send as
If you are trying to connect a 1-Wire temperature sensor or similar device, you need the OneWire library.