This project turns an ESP32 and Adafruit BNO085 9-DOF IMU into a Wi-Fi-enabled NMEA 0183 heading and motion sensor. The BNO085 measures orientation, rotation, and acceleration, which the ESP32 converts to standard NMEA sentences and broadcasts over Wi-Fi via UDP and TCP/IP. A web dashboard displays real-time heading, roll, pitch, and rotation rates.
The guide provides a complete wiring diagram, parts list, and step-by-step assembly instructions for connecting the BNO085 via SPI, configuring the ESP32 firmware, and calibrating the sensor. Once deployed, the system acts as a wireless NMEA server that multiple devices—such as a Raspberry Pi 5—can connect to and receive navigation data without requiring an internet connection.
Wiring diagram

Gather all the parts
Assemble it in 6 steps
1. Replace the sensor with power disconnected
Unplug USB and remove the ICM-20948 and its wires. Use the Adafruit BNO085 breakout for this wiring; other breakouts can have different labels. Keep the ESP32 and Wi-Fi receiver unchanged.
2. Connect power and select SPI mode
Connect VIN to 3V3 (power), GND to GND (shared ground), and both P0 and P1 to 3V3 (select SPI before startup). Leave BT and 3Vo unconnected. Do not use 5V.
3. Wire the SPI connection
Connect SCL to GPIO12 (clock), SDA to GPIO13 (sensor data to ESP32), DI to GPIO11 (ESP32 data to sensor), CS to GPIO10 (select sensor), INT to GPIO14 (data ready), and RST to GPIO15 (reset). The old GPIO8 and GPIO9 wires are no longer used. Keep wires short. Firmware handles active-low reset and initialization through the maker library.
4. Deploy and calibrate
Plug in USB and press Deploy. Join Motion-Dashboard with password motion20948 and open http://192.168.4.1. Click Calibrate compass and rotate slowly in all directions for 60 seconds away from magnets and metal. The BNO085 performs internal calibration; saving requires high magnetic accuracy and reports whether the sensor acknowledged the save. Old ICM compass offsets are not reused. Click Zero pitch/roll at the new neutral position; the ESP32 saves this zero across restarts.
5. Verify mounting and measurements
Mount X forward, Y port, Z up using the breakout axis markings. Compass remains level-only within 10 degrees. The dashboard and HDT show approximate true north using the Netherlands correction; HDM remains magnetic. Verify pitch, roll, turn direction and heading against independent references. Zeroing tilt does not change the physical level check. Rotation values are angular speed, not absolute angle.
- Experimental project only; not suitable for navigation, autopilot control or safety use.
6. Receive on the Raspberry Pi 5
Power the Pi separately and join Motion-Dashboard. Run nmea_tcp.py on Raspberry Pi OS for TCP from 192.168.4.1 port 10110, or keep nmea_udp.py for UDP broadcast on port 10110. The ESP32 is the NMEA 0183 sender; both receivers receive checksummed XDR, ROT, HDM and HDT. No wired NMEA or Pi GPIO connection is used. Output requires fresh sensor reports; heading also requires adequate magnetic accuracy and physical level. UDP delivery is not guaranteed; slow TCP readers are disconnected and should reconnect. See src/raspberry_pi_receiver.md.
Review all connections
1. Connections between "motion" and "ESP32"
Deploy the firmware
// ESP32 NMEA 0183 Wi-Fi sender with a BNO085 IMU
// Web page showing heading, Roll, pitch and rotating speed x-y-z.
// UDP and TCP/IP
// Web dashboard: http://192.168.4.1
// NMEA TCP server: 192.168.4.1:10110 (4 listeners)
// NMEA UDP broadcast: 192.168.4.255:10110
#include <Arduino.h>
#include <SPI.h>
#include <Preferences.h>
#include <WiFi.h>
#include <WiFiUdp.h>
#include <WebServer.h>
#include <Adafruit_BNO08x.h>
#include <math.h>
// Approximate Netherlands declination: Amsterdam, November 2026, WMM2025.
// East is positive: true heading = magnetic heading + declination.
// Location and date matter; this is not a precision navigation correction.
constexpr float MAGNETIC_DECLINATION_DEG = 2.8f;
float trueHeading(float magnetic) {
return fmodf(magnetic + MAGNETIC_DECLINATION_DEG + 360.0f, 360.0f);
}
constexpr uint32_t NMEA_INTERVAL_MS = 1000;
uint32_t lastNmea = 0;
// Broadcast to listeners on the dashboard hotspot. No internet is required.
// Configure the receiving app for NMEA 0183 UDP input on port 10110.
constexpr uint16_t NMEA_UDP_PORT = 10110;
const IPAddress NMEA_UDP_DESTINATION(192, 168, 4, 255);
WiFiUDP nmeaUdp;
bool udpReady = false;
// TCP receivers connect to the ESP32; up to four simultaneous listeners.
constexpr uint16_t NMEA_TCP_PORT = 10110;
constexpr size_t MAX_TCP_CLIENTS = 4;
WiFiServer nmeaTcp(NMEA_TCP_PORT);
WiFiClient tcpClients[MAX_TCP_CLIENTS];
void serviceNmeaTcp() {
if (!nmeaTcp.hasClient()) return;
WiFiClient incoming = nmeaTcp.available();
for (size_t i = 0; i < MAX_TCP_CLIENTS; ++i) {
if (!tcpClients[i] || !tcpClients[i].connected()) {
tcpClients[i].stop();
tcpClients[i] = incoming;
tcpClients[i].setNoDelay(true);
return;
}
}
incoming.stop(); // All slots occupied; do not interrupt existing listeners.
}
constexpr int SENSOR_CS = 10, SENSOR_INT = 14, SENSOR_RESET = 15;
constexpr uint32_t SAMPLE_INTERVAL_MS = 1000;
constexpr uint32_t CALIBRATION_DURATION_MS = 60000;
// Sensor, flash settings, and dashboard state are shared by the web handlers.
Adafruit_BNO08x imu(SENSOR_RESET);
Preferences prefs;
uint8_t magneticAccuracy = 0;
uint32_t gravityTime=0, gyroTime=0, magTime=0;
float gravity[3]={0,0,0};
bool calibrated=false, calibrating=false, sensorReady=false;
uint32_t calStart=0, lastSample=0;
float zeroRoll=0, zeroPitch=0, currentRoll=0, currentPitch=0;
bool haveSample=false, storageReady=false;
float magneticRaw[3]={0,0,0};
WebServer web(80);
float rotationSpeed[3]={
0,0,0
}, compassHeading=0;
String actionMessage="Ready";
// The legacy row number is retained; messages now go to the USB serial log.
void row(int, String text) {
Serial.println(text);
}
// Start a nonblocking sweep: sampling and the webpage remain responsive.
bool startCompass() {
if(!sensorReady) {
actionMessage="Sensor unavailable";
return false;
}
if(calibrating) {
actionMessage="Calibration already running";
return false;
}
if(sh2_setCalConfig(SH2_CAL_ACCEL | SH2_CAL_GYRO | SH2_CAL_MAG)!=SH2_OK) {
actionMessage="Could not start sensor calibration";
return false;
}
calibrating=true;
calStart=millis();
actionMessage="Rotate sensor in all directions for 60 seconds";
row(7,"Compass calibration started");
return true;
}
// Save the current gravity-based tilt as neutral; read it back before applying it.
bool zeroTilt() {
if(!sensorReady||!haveSample) {
actionMessage="No sensor reading yet";
return false;
}
if(!storageReady) {
actionMessage="Storage unavailable - zero not saved";
return false;
}
float tilt[2]={
currentRoll,currentPitch
}, verify[2];
if(!isfinite(tilt[0]) || !isfinite(tilt[1])) {
actionMessage="Invalid tilt reading";
return false;
}
bool saved=prefs.putBytes("tiltZero",tilt,sizeof(tilt))==sizeof(tilt);
saved &= prefs.getBytes("tiltZero",verify,sizeof(verify))==sizeof(verify);
if(saved) saved=memcmp(tilt,verify,sizeof(tilt))==0;
if(!saved) {
actionMessage="Storage failed - pitch/roll zero not saved";
row(7,actionMessage);
return false;
}
zeroRoll=tilt[0];
zeroPitch=tilt[1];
actionMessage="Pitch/roll zero saved";
row(7,actionMessage);
return true;
}
// Embedded dashboard: polling reads live data; POST requests change settings.
const char webpage[] PROGMEM=R"HTML(<!doctype html>
<html><head><meta name="viewport" content="width=device-width,initial-scale=1"><title>Motion and heading dashboard</title>
<style>body{font:14px system-ui;background:#101827;color:#eef;margin:24px;max-width:650px}button{padding:14px;margin:6px;border:0;border-radius:8px;background:#2574da;color:white;font-size:14px}pre{line-height:1.3;white-space:pre-wrap}#status{color:#8edaff}</style></head>
<body><h1>Motion and Heading</h1><p><strong>NMEA 0183 sender: ESP32Heading</strong><br>UDP broadcast: 192.168.4.255 port 10110<br>TCP receivers connect to: 192.168.4.1 port 10110<br>Sends pitch/roll (XDR), turn rate (ROT), magnetic heading (HDM) and true heading (HDT) once per second when valid. Heading requires calibration and a level sensor. No wired NMEA output.</p><pre id="data">Connecting...</pre>
<button type="button" id="calibrate" onclick="act('calibrate')">Calibrate compass</button><button type="button" id="zero" onclick="act('zero')">Zero pitch/roll</button>
<p id="status"></p><p>When compass calibration is running: slowly rotate in all directions for 60 seconds.</p><p>Heading is shown in degrees clockwise from true north (approximate Netherlands correction: 2.8 degrees east, Amsterdam November 2026): 0 north, 90 east, 180 south, 270 west. It is level-only.</p>
<script>
let commandBusy=false, feedbackUntil=0;
async function update(){if(commandBusy)return;try{const r=await fetch('/data',{cache:'no-store'});const d=await r.json();
document.getElementById('data').textContent=!d.sensor?'Sensor unavailable':!d.sample?'Waiting for sensor reading':
`Heading (true north): ${d.calibrating?'Calibrating: '+d.remaining+'s':!d.calibrated?'Not calibrated':!d.level?'Hold sensor level':(Math.round(d.heading*10)/10%360).toFixed(1)+'°'}\nRoll: ${d.roll.toFixed(1)} deg\nPitch: ${d.pitch.toFixed(1)} deg\nRotation speed (deg/s)\nX: ${d.x.toFixed(1)} Y: ${d.y.toFixed(1)} Z: ${d.z.toFixed(1)}\nMagnetic field (uT): ${d.mx.toFixed(1)}, ${d.my.toFixed(1)}, ${d.mz.toFixed(1)}`;
if(!commandBusy && Date.now()>feedbackUntil)document.getElementById('status').textContent=d.message;
}catch(e){document.getElementById('status').textContent='Connection lost. Check ESP32 Wi-Fi.'}}
async function act(name){
if(commandBusy)return;
commandBusy=true;
const status=document.getElementById('status');
const buttons=document.querySelectorAll('button');
buttons.forEach(b=>b.disabled=true);
status.textContent='Sending command...';
const controller=new AbortController();
const timeout=setTimeout(()=>controller.abort(),8000);
try{
const r=await fetch('/'+name,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'action='+encodeURIComponent(name),cache:'no-store',signal:controller.signal});
const message=await r.text();
status.textContent=(r.ok?'':'Command not accepted: ')+message;
}catch(e){status.textContent='No response from ESP32. Check Motion-Dashboard Wi-Fi, then try again.'}
finally{clearTimeout(timeout);feedbackUntil=Date.now()+5000;commandBusy=false;buttons.forEach(b=>b.disabled=false)}
}
update();setInterval(update,500);
</script></body></html>)HTML";
// Host a local Wi-Fi access point; no internet connection is required.
void startWeb() {
WiFi.setHostname("ESP32Heading");
WiFi.mode(WIFI_AP);
WiFi.softAP("Motion-Dashboard","motion20948");
Serial.print("Web dashboard: http://");
Serial.println(WiFi.softAPIP());
web.on("/",HTTP_GET,[] {
web.send_P(200,"text/html",webpage);
});
web.on("/calibrate",HTTP_POST,[] {
bool ok=startCompass(); web.send(ok?200:409,"text/plain",actionMessage);
});
web.on("/zero",HTTP_POST,[] {
bool ok=zeroTilt(); web.send(ok?200:409,"text/plain",actionMessage);
});
web.on("/data",HTTP_GET,[] {
String j="{\"sensor\":"+String(sensorReady?"true":"false")+",\"sample\":"+String(haveSample?"true":"false"); j+=",\"roll\":"+String(remainderf(currentRoll-zeroRoll,360),2)+",\"pitch\":"+String(currentPitch-zeroPitch,2); j+=",\"x\":"+String(rotationSpeed[0],2)+",\"y\":"+String(rotationSpeed[1],2)+",\"z\":"+String(rotationSpeed[2],2); j+=",\"mx\":"+String(magneticRaw[0],2)+",\"my\":"+String(magneticRaw[1],2)+",\"mz\":"+String(magneticRaw[2],2); j+=",\"heading\":"+String(trueHeading(compassHeading),2)+",\"magneticHeading\":"+String(compassHeading,2)+",\"declination\":"+String(MAGNETIC_DECLINATION_DEG,1)+",\"calibrated\":"+String(calibrated?"true":"false"); j+=",\"calibrating\":"+String(calibrating?"true":"false")+",\"remaining\":"+String(calibrating?max(0,60-int((millis()-calStart)/1000)):0); j+=",\"level\":"+String(fabsf(currentRoll)<=10&&fabsf(currentPitch)<=10?"true":"false")+",\"message\":\""+actionMessage+"\"}"; web.sendHeader("Cache-Control","no-store"); web.send(200,"application/json",j);
});
web.begin();
nmeaTcp.begin();
nmeaTcp.setNoDelay(true);
Serial.println("NMEA TCP server: 192.168.4.1:10110 (4 listeners)");
udpReady = nmeaUdp.begin(NMEA_UDP_PORT) == 1;
Serial.println(udpReady ? "NMEA UDP broadcast: 192.168.4.255:10110"
: "NMEA UDP socket unavailable; output disabled");
}
// NMEA 0183: XOR only the payload; frame with $, *HH and CR/LF.
// USB debug text is never included in NMEA network messages.
void sendNmeaSentence(const char *payload) {
uint8_t checksum = 0;
for (const char *p = payload; *p; ++p) checksum ^= uint8_t(*p);
char sentence[83];
int length = snprintf(sentence, sizeof(sentence), "$%s*%02X\r\n", payload, checksum);
if (length <= 0 || length >= int(sizeof(sentence))) return;
// TCP is a byte stream; CR/LF separates sentences, not packet boundaries.
// Drop slow readers rather than hold up sampling and web controls.
for (size_t i = 0; i < MAX_TCP_CLIENTS; ++i) {
WiFiClient &client = tcpClients[i];
if (!client || !client.connected()) { client.stop(); continue; }
if (client.availableForWrite() < length ||
client.write((const uint8_t *)sentence, length) != size_t(length)) {
client.stop();
}
}
// One complete checksummed sentence per datagram, over Wi-Fi.
// UDP is best-effort: a successful send does not confirm receiver delivery.
if (udpReady && WiFi.softAPgetStationNum() > 0 &&
nmeaUdp.beginPacket(NMEA_UDP_DESTINATION, NMEA_UDP_PORT) == 1) {
nmeaUdp.write((const uint8_t *)sentence, length);
nmeaUdp.endPacket();
}
}
// Send only a newly read, finite sample. Output is limited to 1 Hz.
// Assumed mounting: X forward, Y port, Z up. Positive Z gyro is port turn,
// so ROT reverses its sign and converts degrees/second to degrees/minute.
void sendMotionNmea() {
if (millis() - lastNmea < NMEA_INTERVAL_MS) return;
lastNmea = millis();
char payload[76];
if (isfinite(currentPitch) && isfinite(currentRoll)) {
snprintf(payload, sizeof(payload), "IIXDR,A,%.1f,D,PTCH,A,%.1f,D,ROLL",
currentPitch-zeroPitch, currentRoll-zeroRoll);
sendNmeaSentence(payload);
}
if (isfinite(rotationSpeed[2])) {
snprintf(payload, sizeof(payload), "IIROT,%.1f,A", -rotationSpeed[2]*60.0f);
sendNmeaSentence(payload);
}
// HDM has no validity flag: omit it rather than claiming invalid heading.
if (calibrated && !calibrating && fabsf(currentPitch)<=10 && fabsf(currentRoll)<=10 &&
isfinite(compassHeading) && isfinite(magneticRaw[0]) && isfinite(magneticRaw[1]) &&
hypotf(magneticRaw[0], magneticRaw[1])>1) {
float rounded = roundf(compassHeading*10)/10;
if (rounded>=360) rounded=0;
snprintf(payload, sizeof(payload), "IIHDM,%.1f,M", rounded);
sendNmeaSentence(payload);
// Keep HDM magnetic for existing receivers; HDT explicitly means true north.
rounded = roundf(trueHeading(compassHeading)*10)/10;
if (rounded>=360) rounded=0;
snprintf(payload, sizeof(payload), "IIHDT,%.1f,T", rounded);
sendNmeaSentence(payload);
}
}
bool enableReports();
// Restore tilt zero, start Wi-Fi, then initialize SPI and reset the BNO085.
void setup() {
Serial.begin(115200);
storageReady=prefs.begin("motion",false);
if(!storageReady) actionMessage="Settings storage unavailable";
if(storageReady && prefs.isKey("tiltZero")) {
float tilt[2];
if(prefs.getBytes("tiltZero",tilt,sizeof(tilt))==sizeof(tilt) && isfinite(tilt[0]) && fabsf(tilt[0])<=180 && isfinite(tilt[1]) && fabsf(tilt[1])<=90) {
zeroRoll=tilt[0];
zeroPitch=tilt[1];
actionMessage="Saved pitch/roll zero restored";
}
else actionMessage="Invalid saved tilt zero - set zero again";
}
startWeb();
SPI.begin(12,13,11,SENSOR_CS);
sensorReady=imu.begin_SPI(SENSOR_CS,SENSOR_INT,&SPI);
if(!sensorReady) {
actionMessage="Sensor unavailable - check SPI wiring and P0/P1 high";
Serial.println(actionMessage);
return;
}
sensorReady=enableReports();
}
// SH-2 produces independent reports; use only fresh reports for network output.
bool enableReports() {
bool ok=imu.enableReport(SH2_GRAVITY,100000);
ok &= imu.enableReport(SH2_GYROSCOPE_CALIBRATED,100000);
ok &= imu.enableReport(SH2_MAGNETIC_FIELD_CALIBRATED,100000);
return ok;
}
// The BNO085 calibrates internally. Save only when its magnetic accuracy
// is high and a current report is available; never apply old ICM offsets.
void updateCompassCalibration() {
if(!calibrating || millis()-calStart<CALIBRATION_DURATION_MS) return;
calibrating=false;
if(magneticAccuracy<3 || millis()-magTime>1000) {
actionMessage="Magnetic accuracy not high - calibration not saved; try another sweep away from metal";
} else {
bool saved=sh2_saveDcdNow()==SH2_OK;
actionMessage=saved?"BNO085 calibration save acknowledged":"BNO085 calibration save failed";
}
Serial.println(actionMessage);
}
void loop() {
web.handleClient();
serviceNmeaTcp();
if(!sensorReady) { delay(2); return; }
if(imu.wasReset()) {
haveSample=false;
calibrated=false;
gravityTime=gyroTime=magTime=0;
magneticAccuracy=0;
calibrating=false;
sensorReady=enableReports();
}
sh2_SensorValue_t event;
if(imu.getSensorEvent(&event)) {
switch(event.sensorId) {
case SH2_GRAVITY:
gravity[0]=event.un.gravity.x;
gravity[1]=event.un.gravity.y;
gravity[2]=event.un.gravity.z;
currentRoll=atan2f(gravity[1],gravity[2])*180/PI;
currentPitch=atan2f(-gravity[0],hypotf(gravity[1],gravity[2]))*180/PI;
gravityTime=millis();
break;
case SH2_GYROSCOPE_CALIBRATED:
rotationSpeed[0]=event.un.gyroscope.x*180/PI;
rotationSpeed[1]=event.un.gyroscope.y*180/PI;
rotationSpeed[2]=event.un.gyroscope.z*180/PI;
gyroTime=millis();
break;
case SH2_MAGNETIC_FIELD_CALIBRATED:
magneticRaw[0]=event.un.magneticField.x;
magneticRaw[1]=event.un.magneticField.y;
magneticRaw[2]=event.un.magneticField.z;
magneticAccuracy=event.status & 3;
magTime=millis();
// Level-only magnetic heading for X forward, Y port, Z up.
compassHeading=fmodf(atan2f(-magneticRaw[1],magneticRaw[0])*180/PI+360,360);
break;
default: break;
}
}
haveSample=gravityTime && gyroTime && magTime &&
millis()-gravityTime<1000 && millis()-gyroTime<1000 && millis()-magTime<1000;
calibrated=magneticAccuracy>=2 && magTime && millis()-magTime<1000;
updateCompassCalibration();
if(haveSample) sendMotionNmea();
delay(1);
}Remix this project
Make it yours in one click
Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.




