Krolyxon
Commit 1d55752

Branches

Tags

Refs →

orion-rf.piolibdepsesp32-s3-n16r8Adafruit BusIOexamplesgenericdevice_uarttestgenericdevice_uarttest.ino

98 lines · 2.6 KB

1/*
2 Abstracted transport for reading and writing data from a UART-based
3 device such as a TMC2209
4
5 Written with help by Claude!
6 https://claude.ai/chat/335f50b1-3dd8-435e-9139-57ec7ca26a3c (at this time
7 chats are not shareable :(
8*/
9
10#include "Adafruit_GenericDevice.h"
11
12/**
13 * Basic UART device class that demonstrates using GenericDevice with a Stream
14 * interface. This example shows how to wrap a Stream (like HardwareSerial or
15 * SoftwareSerial) with read/write callbacks that can be used by BusIO's
16 * register functions.
17 */
18class UARTDevice {
19public:
20 UARTDevice(Stream *serial) : _serial(serial) {}
21
22 // Static callback for writing data to UART
23 // Called by GenericDevice when data needs to be sent
24 static bool uart_write(void *thiz, const uint8_t *buffer, size_t len) {
25 UARTDevice *dev = (UARTDevice *)thiz;
26 dev->_serial->write(buffer, len);
27 return true;
28 }
29
30 // Static callback for reading data from UART
31 // Includes timeout and will return false if not enough data available
32 static bool uart_read(void *thiz, uint8_t *buffer, size_t len) {
33 UARTDevice *dev = (UARTDevice *)thiz;
34 uint16_t timeout = 100;
35 while (dev->_serial->available() < len && timeout--) {
36 delay(1);
37 }
38 if (timeout == 0) {
39 return false;
40 }
41 for (size_t i = 0; i < len; i++) {
42 buffer[i] = dev->_serial->read();
43 }
44 return true;
45 }
46
47 // Create a GenericDevice instance using our callbacks
48 Adafruit_GenericDevice *createDevice() {
49 return new Adafruit_GenericDevice(this, uart_read, uart_write);
50 }
51
52private:
53 Stream *_serial; // Underlying Stream instance (HardwareSerial, etc)
54};
55
56void setup() {
57 Serial.begin(115200);
58 while (!Serial)
59 ;
60 delay(100);
61
62 Serial.println("Generic Device test!");
63
64 // Initialize UART for device communication
65 Serial1.begin(115200);
66
67 // Create UART wrapper and BusIO device
68 UARTDevice uart(&Serial1);
69 Adafruit_GenericDevice *device = uart.createDevice();
70 device->begin();
71
72 // Test write/read cycle
73 uint8_t write_buf[4] = {0x5, 0x0, 0x0, 0x48};
74 uint8_t read_buf[8];
75
76 Serial.println("Writing data...");
77 if (!device->write(write_buf, 4)) {
78 Serial.println("Write failed!");
79 return;
80 }
81
82 Serial.println("Reading response...");
83 if (!device->read(read_buf, 8)) {
84 Serial.println("Read failed!");
85 return;
86 }
87
88 // Print response bytes
89 Serial.print("Got response: ");
90 for (int i = 0; i < 8; i++) {
91 Serial.print("0x");
92 Serial.print(read_buf[i], HEX);
93 Serial.print(" ");
94 }
95 Serial.println();
96}
97
98void loop() { delay(1000); }