mirror of
https://github.com/cesanta/mongoose.git
synced 2026-12-03 21:48:22 +00:00
Full dashboard - make LEDs and graph overridable
This commit is contained in:
1 parent
364c979a1d
commit
37db92bfc2
7 files changed
+294
-69
No files matched your search
@@ -3,6 +3,43 @@
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
// Maps v from the lo..hi range to the real-time graph's 0..100. For example,
|
||||
// a signed 16-bit sensor reading: GRAPH_SCALE(v, -32768, 32767)
|
||||
#define GRAPH_SCALE(v, lo, hi) \
|
||||
((int) (((int64_t) (v) - (lo)) * 100 / ((int64_t) (hi) - (lo))))
|
||||
|
||||
// Board hooks. To wire the dashboard to real hardware, a board builds with
|
||||
// -DDASHBOARD_CONFIG and overrides them in its own dashboard_config.h, next
|
||||
// to its main.c. The defaults keep the built-in demo behaviour
|
||||
#ifdef DASHBOARD_CONFIG
|
||||
#include "dashboard_config.h"
|
||||
#endif
|
||||
|
||||
#ifndef LED1_READ
|
||||
#define LED1_READ() s_led1 // Returns the current LED1 state
|
||||
#endif
|
||||
#ifndef LED1_WRITE
|
||||
#define LED1_WRITE(on) (void) (on) // Turns LED1 on or off
|
||||
#endif
|
||||
#ifndef LED2_READ
|
||||
#define LED2_READ() s_led2
|
||||
#endif
|
||||
#ifndef LED2_WRITE
|
||||
#define LED2_WRITE(on) (void) (on)
|
||||
#endif
|
||||
#ifndef LED3_READ
|
||||
#define LED3_READ() s_led3
|
||||
#endif
|
||||
#ifndef LED3_WRITE
|
||||
#define LED3_WRITE(on) (void) (on)
|
||||
#endif
|
||||
#ifndef GRAPH_READ
|
||||
#define GRAPH_READ(v) graph_demo_read(v) // Fills int v[3]: x, y, z, 0..100
|
||||
#endif
|
||||
#ifndef GRAPH_PERIOD_MS
|
||||
#define GRAPH_PERIOD_MS 25 // How often to sample and send x, y, z
|
||||
#endif
|
||||
|
||||
static struct mg_dash s_dash;
|
||||
static int authenticate(char *user, size_t userlen, const char *pass);
|
||||
|
||||
@@ -34,6 +71,16 @@ static struct mg_field_set set_actions = {"actions", fields_actions, actions_fn,
|
||||
static bool s_led1, s_led2, s_led3;
|
||||
static bool leds_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
(void) u;
|
||||
if (op == MG_DASH_READ) {
|
||||
s_led1 = LED1_READ();
|
||||
s_led2 = LED2_READ();
|
||||
s_led3 = LED3_READ();
|
||||
}
|
||||
if (op == MG_DASH_WRITE) {
|
||||
LED1_WRITE(s_led1);
|
||||
LED2_WRITE(s_led2);
|
||||
LED3_WRITE(s_led3);
|
||||
}
|
||||
return op == MG_DASH_READ || op == MG_DASH_WRITE;
|
||||
}
|
||||
static struct mg_field fields_leds[] = {
|
||||
@@ -77,6 +124,7 @@ static int s_ota_interval = 30;
|
||||
static char s_ota_version[] = "1.1.2";
|
||||
static char s_ota_status[40] = "No scans yet";
|
||||
static char s_ota_url[100] = "https://my-product.com/ota.json";
|
||||
static bool s_graph_report = true; // Send real-time graph values
|
||||
|
||||
static bool settings_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
if (u->level < 3) return false;
|
||||
@@ -101,6 +149,7 @@ static struct mg_field fields_settings[] = {
|
||||
{"ota_status", MG_VAL_STR, &s_ota_status, sizeof(s_ota_status)},
|
||||
{"ota_url", MG_VAL_STR, &s_ota_url, sizeof(s_ota_url)},
|
||||
{"ota_interval", MG_VAL_INT, &s_ota_interval, sizeof(s_ota_interval)},
|
||||
{"graph_report", MG_VAL_BOOL, &s_graph_report, sizeof(s_graph_report)},
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
|
||||
@@ -152,41 +201,38 @@ static bool graph1_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
static struct mg_field_set set_graph1 = {"graph1", fields_graph1, graph1_fn,
|
||||
NULL, NULL};
|
||||
|
||||
#define NUM_POINTS_GRAPH2 100 // How many graph2 data points to send
|
||||
static char s_graph2_data[NUM_POINTS_GRAPH2 * 4 + 2 + 1];
|
||||
static bool s_graph2_report = true;
|
||||
// Real-time graph: the latest x, y, z values. The device sends each new
|
||||
// set, the browser keeps the rolling window, see GRAPH_WINDOW in the HTML
|
||||
static int s_graph[3];
|
||||
|
||||
// Adjust t += 7, i * 9, and i * 3
|
||||
void read_graph2(void) {
|
||||
static uint16_t t;
|
||||
size_t i, len = 0;
|
||||
len = mg_snprintf(s_graph2_data, sizeof(s_graph2_data), "[");
|
||||
t += 23;
|
||||
for (i = 0; i < NUM_POINTS_GRAPH2; i++) {
|
||||
uint16_t x = (uint16_t) (i * 7 + t);
|
||||
uint16_t y = (uint16_t) (i * 3 - t / 2);
|
||||
// Demo data source: x, y, z of a fake signal, each 3..97. Not static, so a
|
||||
// board that overrides GRAPH_READ gets no unused function warning
|
||||
void graph_demo_read(int *v) {
|
||||
static uint16_t n;
|
||||
int i;
|
||||
for (i = 0; i < 3; i++) {
|
||||
uint16_t t = (uint16_t) (n + i * 40); // Shift y and z along the signal
|
||||
uint16_t x = (uint16_t) (t * 7), y = (uint16_t) (t * 3);
|
||||
uint8_t a = (uint8_t) (x ^ (x >> 3)) & 255;
|
||||
uint8_t b = (uint8_t) (y ^ (y >> 4)) & 255;
|
||||
int v =
|
||||
70 + ((a < 128 ? a : 255 - a) >> 1) + ((b < 128 ? b : 255 - b) >> 2);
|
||||
len += mg_snprintf(s_graph2_data + len, sizeof(s_graph2_data) - len,
|
||||
"%s%hhu", i > 0 ? "," : "", (uint8_t) v);
|
||||
int s = ((a < 128 ? a : 255 - a) >> 1) + ((b < 128 ? b : 255 - b) >> 2);
|
||||
v[i] = GRAPH_SCALE(s, -3, 97); // s is 0..94, so 3..97, off the edges
|
||||
}
|
||||
len += mg_snprintf(s_graph2_data + len, sizeof(s_graph2_data) - len, "]");
|
||||
n++;
|
||||
}
|
||||
|
||||
static struct mg_field fields_graph2[] = {
|
||||
{"data", MG_VAL_RAW, s_graph2_data, sizeof(s_graph2_data)},
|
||||
{"report", MG_VAL_BOOL, &s_graph2_report, sizeof(s_graph2_report)},
|
||||
static struct mg_field fields_graph[] = {
|
||||
{"x", MG_VAL_INT, &s_graph[0], sizeof(s_graph[0])},
|
||||
{"y", MG_VAL_INT, &s_graph[1], sizeof(s_graph[1])},
|
||||
{"z", MG_VAL_INT, &s_graph[2], sizeof(s_graph[2])},
|
||||
{NULL, MG_VAL_INT, NULL, 0},
|
||||
};
|
||||
|
||||
static bool graph2_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
static bool graph_fn(enum mg_dash_op op, struct mg_dash_user *u) {
|
||||
(void) u;
|
||||
if (op == MG_DASH_READ) read_graph2();
|
||||
return op == MG_DASH_READ || op == MG_DASH_WRITE;
|
||||
return op == MG_DASH_READ; // Values are set in mg_dash_poll()
|
||||
}
|
||||
static struct mg_field_set set_graph2 = {"graph2", fields_graph2, graph2_fn,
|
||||
static struct mg_field_set set_graph = {"graph", fields_graph, graph_fn,
|
||||
NULL, NULL};
|
||||
|
||||
static int authenticate(char *user, size_t userlen, const char *pass) {
|
||||
@@ -238,7 +284,7 @@ void mg_dash_init(struct mg_mgr *mgr) {
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_metrics);
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_settings);
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_graph1);
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_graph2);
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_graph);
|
||||
MG_DASH_ADD_FIELD_SET(&s_dash, &set_actions);
|
||||
|
||||
#if MG_ARCH == MG_ARCH_UNIX
|
||||
@@ -262,8 +308,10 @@ void mg_dash_poll(struct mg_mgr *mgr) {
|
||||
if (mg_timer_expired(&timer1, 30000, mg_now())) {
|
||||
mg_dash_send_change(mgr, &set_metrics);
|
||||
}
|
||||
if (mg_timer_expired(&timer2, 120, mg_now()) && s_graph2_report) {
|
||||
mg_dash_send_change(mgr, &set_graph2);
|
||||
if (mg_timer_expired(&timer2, GRAPH_PERIOD_MS, mg_now()) && s_graph_report) {
|
||||
// Sample here, not in graph_fn(): that runs once per connected client
|
||||
GRAPH_READ(s_graph);
|
||||
mg_dash_send_change(mgr, &set_graph);
|
||||
}
|
||||
if (s_action2 == true && s_action2_timeout < mg_now()) {
|
||||
s_action2 = false;
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
auth: true,
|
||||
data: {
|
||||
graph1: {data: []},
|
||||
graph2: {data: [], report: true},
|
||||
graph: {x: 0, y: 0, z: 0},
|
||||
actions: { action1: false, action2: false },
|
||||
leds: { led1: true, led2: false, led3: false },
|
||||
settings: { volume: 12, log_level: 3, name: 'Galway', enable_login: true, ota_version: '1.2.3', ota_status: 'No checks yet', ota_url: 'http://my-product.com/ota.json', ota_interval: 30 },
|
||||
settings: { volume: 12, log_level: 3, name: 'Galway', enable_login: true, ota_version: '1.2.3', ota_status: 'No checks yet', ota_url: 'http://my-product.com/ota.json', ota_interval: 30, graph_report: true },
|
||||
metrics: { temperature: 1.2, cpu: 4, ram: 5, version: '1.2.3' },
|
||||
},
|
||||
});
|
||||
@@ -47,7 +47,7 @@
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
mkGraph(graphs.graph1);
|
||||
mkGraph(graphs.graph2);
|
||||
mkGraph(graphs.graph);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
document.getElementById('auth').style.display = yes ? '' : 'none';
|
||||
document.getElementById('app').style.display = yes ? 'none' : '';
|
||||
if (!yes) requestAnimationFrame(() => { // App is visible now: size graphs
|
||||
mkGraph(graphs.graph1), mkGraph(graphs.graph2);
|
||||
mkGraph(graphs.graph1), mkGraph(graphs.graph);
|
||||
});
|
||||
if (yes) {
|
||||
document.body.style.visibility = 'visible';
|
||||
@@ -122,6 +122,8 @@
|
||||
Dashboard.login().catch(err => showLogin(true));
|
||||
|
||||
// GRAPHS
|
||||
const GRAPH_WINDOW = 10; // Real-time graph span, seconds
|
||||
const GRAPH_GAP = 1; // No values for this long, seconds: break the line
|
||||
const graphs = {
|
||||
graph1: {
|
||||
el: document.getElementById("graph1"),
|
||||
@@ -139,17 +141,23 @@
|
||||
],
|
||||
},
|
||||
},
|
||||
graph2: {
|
||||
el: document.getElementById("graph2"),
|
||||
graph: {
|
||||
el: document.getElementById("graph"),
|
||||
plot: null,
|
||||
opts: {
|
||||
width: 10, height: 10,
|
||||
legend: { show: false },
|
||||
axes: [ { size: 25, gap: 2, }, { size: 40, gap: 2, }, ],
|
||||
scales: { x: { time: false }, y: { range: [50, 200] }, },
|
||||
axes: [
|
||||
{ size: 25, gap: 2, values: (u, splits) => splits.map(s => `${s}s`) },
|
||||
{ size: 40, gap: 2, },
|
||||
],
|
||||
// x is seconds before now, see drawGraph()
|
||||
scales: { x: { time: false, range: () => [-GRAPH_WINDOW, 0] }, y: { range: [0, 100] }, },
|
||||
series: [
|
||||
{},
|
||||
{stroke: '#058DC7FF', fill: '#058DC71A'}, // azure
|
||||
{stroke: '#058DC7FF'}, // azure, x
|
||||
{stroke: '#ED7E17FF'}, // orange, y
|
||||
{stroke: '#22C55EFF'}, // green, z
|
||||
],
|
||||
}
|
||||
},
|
||||
@@ -171,17 +179,36 @@
|
||||
]);
|
||||
};
|
||||
|
||||
function updateGraph2(data) {
|
||||
data && graphs.graph2.plot.setData([
|
||||
data.map((_, i) => i),
|
||||
data,
|
||||
]);
|
||||
// Real-time graph: the device pushes x, y, z one set at a time. Keep
|
||||
// the ones that arrived in the last GRAPH_WINDOW seconds, stamped
|
||||
// with their arrival time, as [time, x, y, z]
|
||||
const graphPoints = [];
|
||||
function addGraphPoint(v) {
|
||||
const now = Date.now() / 1000, last = graphPoints[graphPoints.length - 1];
|
||||
// Values stopped for a while: break the line instead of joining it
|
||||
if (last && now - last[0] > GRAPH_GAP) graphPoints.push([last[0] + 0.001, null, null, null]);
|
||||
graphPoints.push([now, v.x, v.y, v.z]);
|
||||
while (graphPoints.length && graphPoints[0][0] < now - GRAPH_WINDOW) graphPoints.shift();
|
||||
};
|
||||
|
||||
// Redraws the real-time graph every frame, so it keeps scrolling
|
||||
// even when no values arrive
|
||||
function drawGraph() {
|
||||
const plot = graphs.graph.plot, now = Date.now() / 1000;
|
||||
if (plot) plot.setData([
|
||||
graphPoints.map(p => p[0] - now),
|
||||
graphPoints.map(p => p[1]),
|
||||
graphPoints.map(p => p[2]),
|
||||
graphPoints.map(p => p[3]),
|
||||
]);
|
||||
requestAnimationFrame(drawGraph);
|
||||
};
|
||||
requestAnimationFrame(drawGraph);
|
||||
|
||||
// Intercept change notifications: re-plot graphs
|
||||
Dashboard.on('change', args => {
|
||||
args?.graph1?.data && updateGraph1(args?.graph1?.data);
|
||||
args?.graph2?.data && updateGraph2(args?.graph2?.data);
|
||||
args?.graph && addGraphPoint(args.graph);
|
||||
});
|
||||
|
||||
// File manager: served directly by the built-in mg_dash file manager
|
||||
@@ -325,12 +352,13 @@ a, a:visited, a:link { text-decoration: none; }
|
||||
.field-value { min-width: 0; color: #334155; font-size: 0.9rem; font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.file-size { color: #94a3b8; font-size: 0.8rem; font-weight: 700; text-align: right; white-space: nowrap; }
|
||||
.file-actions { display: flex; align-items: center; justify-content: flex-end; gap: 0.45rem; }
|
||||
#graph1, #graph2 { width: 100%; height: 100%; min-height: 10rem; }
|
||||
#graph1, #graph { width: 100%; height: 100%; min-height: 10rem; }
|
||||
.legend { display: flex; align-items: center; gap: 1rem; flex-shrink: 0; }
|
||||
.legend-item { display: flex; align-items: center; gap: 0.35rem; font-size: 0.75rem; color: #5d7088; font-weight: 600; }
|
||||
.legend-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
|
||||
.legend-dot-color2 { background: rgba(237, 126, 23, 1); }
|
||||
.legend-dot-color1 { background: rgba(5, 141, 199, 1); }
|
||||
.legend-dot-color3 { background: rgba(34, 197, 94, 1); }
|
||||
.toggle { position: relative; width: 2.75rem; height: 1.6rem; margin: 0; vertical-align: top; border: 1px solid transparent; background: #d1d5db; border-radius: 0.75rem; outline: none; cursor: pointer; -webkit-appearance: none; -moz-appearance: none; appearance: none; }
|
||||
.toggle::after { content: ""; position: absolute; left: 1px; top: 1px; width: 1.35rem; height: 1.35rem; background: #fff; border-radius: 50%; transition: all 0.3s; }
|
||||
.toggle:checked { background: #10B981; }
|
||||
@@ -527,12 +555,14 @@ a, a:visited, a:link { text-decoration: none; }
|
||||
<span>Real-Time Graph</span>
|
||||
<div class="legend">
|
||||
<small>autoupdate:</small>
|
||||
<input type="checkbox" data-bind="graph2.report" data-autosave="1" class="toggle" />
|
||||
<div class="legend-item"><span class="legend-dot legend-dot-color1"></span>Motor Voltage</div>
|
||||
<input type="checkbox" data-bind="settings.graph_report" data-autosave="1" class="toggle" />
|
||||
<div class="legend-item"><span class="legend-dot legend-dot-color1"></span>x</div>
|
||||
<div class="legend-item"><span class="legend-dot legend-dot-color2"></span>y</div>
|
||||
<div class="legend-item"><span class="legend-dot legend-dot-color3"></span>z</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div id="graph2"></div>
|
||||
<div id="graph"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -16,8 +16,9 @@ CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Inrfx/mdk
|
||||
CFLAGS += -DNRF52840_XXAA -D__STARTUP_CLEAR_BSS -D__START=main -D__HEAP_SIZE=0
|
||||
CFLAGS += -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16
|
||||
CFLAGS += $(CFLAGS_EXTRA)
|
||||
CFLAGS += -DDASHBOARD_CONFIG # Dashboard hooks in dashboard_config.h
|
||||
|
||||
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lm -lgcc
|
||||
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lgcc
|
||||
LDFLAGS += -Wl,--gc-sections -Wl,-Map=$@.map
|
||||
|
||||
SOURCES = hal.c main.c $(MGDIR)/mongoose.c
|
||||
@@ -25,7 +26,7 @@ SOURCES += $(MGDIR)/tutorials/device-dashboard/full/dashboard.c
|
||||
SOURCES += $(MGDIR)/tutorials/device-dashboard/full/file_data.c
|
||||
SOURCES += nrfx/mdk/system_nrf52840.c nrfx/mdk/gcc_startup_nrf52840.S
|
||||
|
||||
all build: firmware.hex
|
||||
all build: firmware.hex firmware.bin
|
||||
|
||||
firmware.elf: cmsis_core nrfx $(SOURCES) $(wildcard *.h) link.ld Makefile
|
||||
arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@
|
||||
@@ -34,6 +35,10 @@ firmware.elf: cmsis_core nrfx $(SOURCES) $(wildcard *.h) link.ld Makefile
|
||||
firmware.hex: firmware.elf
|
||||
arm-none-eabi-objcopy -O ihex $< $@
|
||||
|
||||
# Raw image, starts at the application address 0x27000, see link.ld
|
||||
firmware.bin: firmware.elf
|
||||
arm-none-eabi-objcopy -O binary $< $@
|
||||
|
||||
firmware.zip: firmware.hex
|
||||
$(NRFUTIL) dfu genpkg --dev-type 0x0052 --sd-req 0xFFFE --application $< $@
|
||||
|
||||
@@ -47,7 +52,7 @@ cmsis_core:
|
||||
nrfx:
|
||||
git clone -q -c advice.detachedHead=false --depth 1 -b v2.11.0 https://github.com/NordicSemiconductor/nrfx $@
|
||||
|
||||
$(MGDIR)/tutorials/device-dashboard/full/file_data.c:
|
||||
$(MGDIR)/tutorials/device-dashboard/full/file_data.c: $(MGDIR)/tutorials/device-dashboard/full/dashboard.html
|
||||
cd $(dir $@) && $(MAKE) $(notdir $@)
|
||||
|
||||
clean:
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Dashboard hooks, see tutorials/device-dashboard/full/dashboard.c
|
||||
// Used because the Makefile builds with -DDASHBOARD_CONFIG
|
||||
#pragma once
|
||||
#include "hal.h"
|
||||
|
||||
// LED1, LED2, LED3 are the red, green and blue parts of the RGB LED, which
|
||||
// are active low
|
||||
#define LED1_READ() (!hal_gpio_read(LED_RED))
|
||||
#define LED1_WRITE(on) hal_gpio_write(LED_RED, !(on))
|
||||
#define LED2_READ() (!hal_gpio_read(LED_GREEN))
|
||||
#define LED2_WRITE(on) hal_gpio_write(LED_GREEN, !(on))
|
||||
#define LED3_READ() (!hal_gpio_read(LED_BLUE))
|
||||
#define LED3_WRITE(on) hal_gpio_write(LED_BLUE, !(on))
|
||||
|
||||
// Real-time graph: X, Y, Z acceleration, the IMU's full +-2 g mapped to the
|
||||
// graph's 0..100, 40 mg per step
|
||||
static inline void graph_read(int *v) {
|
||||
int i;
|
||||
hal_imu_accel(v); // Raw counts, -32768..32767
|
||||
for (i = 0; i < 3; i++) v[i] = GRAPH_SCALE(v[i], -32768, 32767);
|
||||
}
|
||||
#define GRAPH_READ(v) graph_read(v)
|
||||
@@ -2,7 +2,6 @@
|
||||
// All rights reserved
|
||||
|
||||
#include "hal.h"
|
||||
#include <string.h>
|
||||
|
||||
static volatile uint64_t s_ticks; // Milliseconds since boot
|
||||
void SysTick_Handler(void) { // SysTick IRQ handler, triggered every 1ms
|
||||
@@ -13,20 +12,6 @@ uint64_t hal_get_tick(void) {
|
||||
return s_ticks;
|
||||
}
|
||||
|
||||
// Mongoose time source, see MG_ENABLE_CUSTOM_MILLIS
|
||||
uint64_t mg_millis(void) {
|
||||
return s_ticks;
|
||||
}
|
||||
|
||||
// Mongoose random source, see MG_ENABLE_CUSTOM_RANDOM
|
||||
bool mg_random(void *buf, size_t len) {
|
||||
for (size_t n = 0; n < len; n += sizeof(uint32_t)) {
|
||||
uint32_t r = hal_rng_read();
|
||||
memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Avoid pulling printf and friends in through assert()
|
||||
void __assert_func(const char *s, int line, const char *fn, const char *expr) {
|
||||
(void) s, (void) line, (void) fn, (void) expr;
|
||||
|
||||
@@ -8,7 +8,13 @@
|
||||
#define PIN(port, num) (((port) << 5) | (num))
|
||||
#define PINNO(pin) ((pin) & 31)
|
||||
#define PINPORT(pin) ((pin) >> 5)
|
||||
#define LED PIN(0, 26) // P0.26, red user LED, active low
|
||||
|
||||
#define LED_RED PIN(0, 26) // RGB user LED, each colour active low
|
||||
#define LED_GREEN PIN(0, 30)
|
||||
#define LED_BLUE PIN(0, 6)
|
||||
#define IMU_PWR PIN(1, 8) // LSM6DS3TR-C IMU power, active high (Sense only)
|
||||
#define IMU_SCL PIN(0, 27) // IMU I2C bus
|
||||
#define IMU_SDA PIN(0, 7)
|
||||
|
||||
uint64_t hal_get_tick(void);
|
||||
size_t hal_ram_used(void);
|
||||
@@ -18,6 +24,11 @@ static inline NRF_GPIO_Type *hal_gpio_bank(uint16_t pin) {
|
||||
return PINPORT(pin) == 0 ? NRF_P0 : NRF_P1;
|
||||
}
|
||||
|
||||
// Returns the pin's level. Works for outputs too, see hal_gpio_output()
|
||||
static inline int hal_gpio_read(uint16_t pin) {
|
||||
return hal_gpio_bank(pin)->IN & BIT(PINNO(pin)) ? 1 : 0;
|
||||
}
|
||||
|
||||
static inline void hal_gpio_write(uint16_t pin, bool val) {
|
||||
NRF_GPIO_Type *gpio = hal_gpio_bank(pin);
|
||||
if (val) {
|
||||
@@ -31,10 +42,11 @@ static inline void hal_gpio_toggle(uint16_t pin) {
|
||||
hal_gpio_write(pin, (hal_gpio_bank(pin)->OUT & BIT(PINNO(pin))) == 0);
|
||||
}
|
||||
|
||||
// Input buffer stays connected, so hal_gpio_read() returns the output level
|
||||
static inline void hal_gpio_output(uint16_t pin) {
|
||||
hal_gpio_bank(pin)->PIN_CNF[PINNO(pin)] =
|
||||
(GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) |
|
||||
(GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos);
|
||||
(GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos);
|
||||
}
|
||||
|
||||
// Vectors above the bootloader, 64 MHz crystal clock, 1 ms SysTick
|
||||
@@ -65,3 +77,105 @@ static inline uint32_t hal_rng_read(void) {
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Blocking I2C transfer on TWIM0: writes tx, then reads rxlen bytes into rx
|
||||
// if rxlen > 0. Buffers must be in RAM, for EasyDMA. Returns true on success
|
||||
static inline bool hal_i2c_xfer(uint8_t addr, uint8_t *tx, size_t txlen,
|
||||
uint8_t *rx, size_t rxlen) {
|
||||
NRF_TWIM_Type *twim = NRF_TWIM0;
|
||||
uint64_t deadline = hal_get_tick() + 5;
|
||||
bool ok = true;
|
||||
twim->ADDRESS = addr;
|
||||
twim->TXD.PTR = (uint32_t) tx;
|
||||
twim->TXD.MAXCNT = txlen;
|
||||
twim->RXD.PTR = (uint32_t) rx;
|
||||
twim->RXD.MAXCNT = rxlen;
|
||||
twim->SHORTS = rxlen ? TWIM_SHORTS_LASTTX_STARTRX_Msk | TWIM_SHORTS_LASTRX_STOP_Msk
|
||||
: TWIM_SHORTS_LASTTX_STOP_Msk;
|
||||
twim->ERRORSRC = twim->ERRORSRC; // Write 1s to clear
|
||||
twim->EVENTS_ERROR = 0;
|
||||
twim->EVENTS_STOPPED = 0;
|
||||
twim->TASKS_STARTTX = 1;
|
||||
while (!twim->EVENTS_STOPPED && hal_get_tick() < deadline) {
|
||||
if (twim->EVENTS_ERROR) { // E.g. NACK. The bus does not stop by itself
|
||||
twim->EVENTS_ERROR = 0;
|
||||
twim->TASKS_STOP = 1;
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
if (!twim->EVENTS_STOPPED) twim->TASKS_STOP = 1, ok = false; // Timed out
|
||||
return ok;
|
||||
}
|
||||
|
||||
// LSM6DS3TR-C IMU registers and values, see Seeed_Arduino_LSM6DS3
|
||||
#define IMU_WHO_AM_I 0x0f // Reads 0x6a for the TR-C, 0x69 for older parts
|
||||
#define IMU_CTRL1_XL 0x10 // Accelerometer control
|
||||
#define IMU_XL_104HZ_2G 0x40 // 104 Hz output rate, +-2 g full scale
|
||||
#define IMU_OUTX_L_XL 0x28 // X acceleration, low byte, then X high, Y, Z
|
||||
|
||||
// The IMU's I2C address lives in TWIM0's ADDRESS register, set by
|
||||
// hal_imu_init(), and TWIM0 is left disabled if there is no IMU. So this
|
||||
// header keeps no state, which would be one copy per file including it
|
||||
static inline bool hal_imu_found(void) {
|
||||
return NRF_TWIM0->ENABLE == (TWIM_ENABLE_ENABLE_Enabled << TWIM_ENABLE_ENABLE_Pos);
|
||||
}
|
||||
|
||||
// Reads one IMU register into val. Returns true on success
|
||||
static inline bool hal_imu_read_reg(uint8_t reg, uint8_t *val) {
|
||||
return hal_i2c_xfer((uint8_t) NRF_TWIM0->ADDRESS, ®, 1, val, 1);
|
||||
}
|
||||
|
||||
// Powers up the IMU, sets up its I2C bus and the accelerometer. Returns the
|
||||
// IMU's I2C address, or 0 if it does not answer
|
||||
static inline int hal_imu_init(void) {
|
||||
static const uint8_t addrs[] = {0x6a, 0x6b}; // Depends on the SDO pin
|
||||
uint64_t t;
|
||||
// The IMU is powered from this pin, so it needs high drive, as in Seeed's
|
||||
// LSM6DS3 driver. Standard drive may not supply enough current
|
||||
hal_gpio_bank(IMU_PWR)->PIN_CNF[PINNO(IMU_PWR)] =
|
||||
(GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) |
|
||||
(GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos) |
|
||||
(GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos);
|
||||
hal_gpio_write(IMU_PWR, true);
|
||||
t = hal_get_tick() + 10;
|
||||
while (hal_get_tick() < t) (void) 0; // Let the IMU power up
|
||||
for (unsigned i = 0; i < 2; i++) {
|
||||
uint16_t pin = i == 0 ? IMU_SCL : IMU_SDA;
|
||||
hal_gpio_bank(pin)->PIN_CNF[PINNO(pin)] =
|
||||
(GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) |
|
||||
(GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) |
|
||||
(GPIO_PIN_CNF_PULL_Pullup << GPIO_PIN_CNF_PULL_Pos) |
|
||||
(GPIO_PIN_CNF_DRIVE_S0D1 << GPIO_PIN_CNF_DRIVE_Pos);
|
||||
}
|
||||
NRF_TWIM0->PSEL.SCL = IMU_SCL; // PIN() matches the PSEL port/pin format
|
||||
NRF_TWIM0->PSEL.SDA = IMU_SDA;
|
||||
NRF_TWIM0->FREQUENCY = TWIM_FREQUENCY_FREQUENCY_K400
|
||||
<< TWIM_FREQUENCY_FREQUENCY_Pos;
|
||||
NRF_TWIM0->ENABLE = TWIM_ENABLE_ENABLE_Enabled << TWIM_ENABLE_ENABLE_Pos;
|
||||
for (size_t i = 0; i < sizeof(addrs); i++) {
|
||||
uint8_t id = 0, cmd[] = {IMU_CTRL1_XL, IMU_XL_104HZ_2G};
|
||||
NRF_TWIM0->ADDRESS = addrs[i]; // Used by hal_imu_read_reg()
|
||||
if (hal_imu_read_reg(IMU_WHO_AM_I, &id) && (id == 0x6a || id == 0x69) &&
|
||||
hal_i2c_xfer(addrs[i], cmd, sizeof(cmd), NULL, 0)) {
|
||||
return addrs[i];
|
||||
}
|
||||
}
|
||||
NRF_TWIM0->ENABLE = 0; // No IMU, see hal_imu_found()
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Fills raw with X, Y, Z acceleration as raw counts, -32768..32767, zeros if
|
||||
// there is no IMU. At +-2 g one count is 0.061 mg, so flat on a table Z reads
|
||||
// about +16400. Bytes are read one by one, not relying on register address
|
||||
// auto-increment
|
||||
static inline void hal_imu_accel(int *raw) {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
uint8_t reg = (uint8_t) (IMU_OUTX_L_XL + i * 2), lo = 0, hi = 0;
|
||||
raw[i] = 0;
|
||||
if (!hal_imu_found() || !hal_imu_read_reg(reg, &lo) ||
|
||||
!hal_imu_read_reg((uint8_t) (reg + 1), &hi)) {
|
||||
continue;
|
||||
}
|
||||
raw[i] = (int16_t) ((hi << 8) | lo);
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,34 @@
|
||||
static void blink_task(void) {
|
||||
static uint64_t blink_timer = 0;
|
||||
if (mg_timer_expired(&blink_timer, 500, mg_millis())) {
|
||||
hal_gpio_toggle(LED);
|
||||
hal_gpio_toggle(LED_RED);
|
||||
}
|
||||
}
|
||||
|
||||
// Mongoose time source, see MG_ENABLE_CUSTOM_MILLIS
|
||||
uint64_t mg_millis(void) {
|
||||
return hal_get_tick();
|
||||
}
|
||||
|
||||
// Mongoose random source, see MG_ENABLE_CUSTOM_RANDOM
|
||||
bool mg_random(void *buf, size_t len) {
|
||||
for (size_t n = 0; n < len; n += sizeof(uint32_t)) {
|
||||
uint32_t r = hal_rng_read();
|
||||
memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
hal_system_init();
|
||||
hal_rng_init();
|
||||
hal_gpio_write(LED, true); // Off
|
||||
hal_gpio_output(LED);
|
||||
hal_gpio_write(LED_RED, true); // RGB LED off, it is active low
|
||||
hal_gpio_write(LED_GREEN, true);
|
||||
hal_gpio_write(LED_BLUE, true);
|
||||
hal_gpio_output(LED_RED); // Dashboard LED1, LED2, LED3
|
||||
hal_gpio_output(LED_GREEN);
|
||||
hal_gpio_output(LED_BLUE);
|
||||
int imu = hal_imu_init(); // For the dashboard's real-time graph
|
||||
|
||||
struct mg_mgr mgr;
|
||||
mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h
|
||||
@@ -24,6 +43,8 @@ int main(void) {
|
||||
MG_INFO(("Initialised. CPU clock: %lu MHz", SystemCoreClock / 1000000));
|
||||
MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free()));
|
||||
MG_INFO(("USB Ethernet + serial"));
|
||||
if (imu) MG_INFO(("IMU at I2C address 0x%x", imu));
|
||||
if (!imu) MG_ERROR(("IMU not found, is this a XIAO nRF52840 Sense?"));
|
||||
|
||||
for (;;) {
|
||||
mg_mgr_poll(&mgr, 0);
|
||||
|
||||
Reference in new issue
Block a user