claude-opus-4-20250514-thinking-16k· Anthropic LMArena Human Preference 140K
How waveshare esp32 lcd 1-.28 no touch with the qmi8568 or so . brauche software für den…
- User
How waveshare esp32 lcd 1-.28 no touch with the qmi8568 or so . brauche software für den micrcontroller die zulässt über bluetooth die sampling rate der IMU einzustellen und das display ein und aus zu machen und die daten iwie über ble auf den pc bekommen
- Assistant
I'll help you create software for your Waveshare ESP32 1.28" LCD with QMI8568 IMU that allows Bluetooth control of sampling rate, display on/off, and data transmission to PC.
Here's a complete Arduino sketch for your ESP32:
#include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> #include <Wire.h> #include <TFT_eSPI.h> #include <SPI.h> #include "QMI8658.h" // BLE UUIDs #define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" #define IMU_CHAR_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" #define CONTROL_CHAR_UUID "1c95d5e3-d8f7-413a-bf3d-7a2e5d7be87e" // Display pins (adjust according to your wiring) #define TFT_MISO 12 #define TFT_MOSI 13 #define TFT_SCLK 14 #define TFT_CS 15 #define TFT_DC 2 #define TFT_RST 4 #define TFT_BL 27 // IMU I2C pins #define SDA_PIN 21 #define SCL_PIN 22 TFT_eSPI tft = TFT_eSPI(); QMI8658 imu; BLECharacteristic *pImuCharacteristic; BLECharacteristic *pControlCharacteristic; bool deviceConnected = false; bool displayOn = true; int samplingRate = 100; // Hz unsigned long lastSampleTime = 0; class ServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; BLEDevice::startAdvertising(); } }; class ControlCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { std::string value = pCharacteristic->getValue(); if (value.length() > 0) { String command = String(value.c_str()); if (command.startsWith("RATE:")) { samplingRate = command.substring(5).toInt(); Serial.println("Sampling rate set to: " + String(samplingRate) + " Hz"); } else if (command == "DISPLAY:ON") { displayOn = true; digitalWrite(TFT_BL, HIGH); Serial.println("Display ON"); } else if (command == "DISPLAY:OFF") { displayOn = false; digitalWrite(TFT_BL, LOW); Serial.println("Display OFF"); } } } }; void setup() { Serial.begin(115200); // Initialize I2C for IMU Wire.begin(SDA_PIN, SCL_PIN); // Initialize IMU if (imu.begin() != QMI8658_OK) { Serial.println("Failed to initialize QMI8658!"); while(1); } // Configure IMU imu.configAccelerometer(ACC_RANGE_4G, ACC_ODR_100Hz, LPF_MODE_0); imu.configGyroscope(GYR_RANGE_512DPS, GYR_ODR_100Hz, LPF_MODE_0); imu.enableAccelerometer(); imu.enableGyroscope(); // Initialize display pinMode(TFT_BL, OUTPUT); digitalWrite(TFT_BL, HIGH); tft.init(); tft.setRotation(0); tft.fillScreen(TFT_BLACK); tft.setTextColor(TFT_WHITE, TFT_BLACK); tft.setTextSize(2); // Initialize BLE BLEDevice::init("ESP32-IMU"); BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new ServerCallbacks()); BLEService *pService = pServer->createService(SERVICE_UUID); // IMU data characteristic (notify) pImuCharacteristic = pService->createCharacteristic( IMU_CHAR_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY ); pImuCharacteristic->addDescriptor(new BLE2902()); // Control characteristic (write) pControlCharacteristic = pService->createCharacteristic( CONTROL_CHAR_UUID, BLECharacteristic::PROPERTY_WRITE ); pControlCharacteristic->setCallbacks(new ControlCallbacks()); pService->start(); BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); pAdvertising->addServiceUUID(SERVICE_UUID); pAdvertising->setScanResponse(true); pAdvertising->setMinPreferred(0x06); BLEDevice::startAdvertising(); Serial.println("BLE device ready!"); } void loop() { unsigned long currentTime = millis(); if (currentTime - lastSampleTime >= (1000 / samplingRate)) { lastSampleTime = currentTime; // Read IMU data float acc[3], gyro[3]; imu.getAccelerometer(&acc[0], &acc[1], &acc[2]); imu.getGyroscope(&gyro[0], &gyro[1], &gyro[2]); // Create data packet String dataPacket = String(currentTime) + "," + String(acc[0], 3) + "," + String(acc[1], 3) + "," + String(acc[2], 3) + "," + String(gyro[0], 3) + "," + String(gyro[1], 3) + "," + String(gyro[2], 3); // Send via BLE if connected if (deviceConnected) { pImuCharacteristic->setValue(dataPacket.c_str()); pImuCharacteristic->notify(); } // Update display if on if (displayOn) { tft.setCursor(10, 10); tft.println("IMU Data"); tft.setCursor(10, 40); tft.print("Ax: "); tft.println(acc[0], 2); tft.setCursor(10, 60); tft.print("Ay: "); tft.println(acc[1], 2); tft.setCursor(10, 80); tft.print("Az: "); tft.println(acc[2], 2); tft.setCursor(10, 110); tft.print("Rate: "); tft.print(samplingRate); tft.println(" Hz"); tft.setCursor(10, 130); tft.print("BLE: "); tft.println(deviceConnected ? "Connected" : "Waiting"); } } }For the PC side, here's a Python script to receive and log the data:
import asyncio from bleak import BleakClient, BleakScanner import datetime # BLE UUIDs (must match ESP32) SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b" IMU_CHAR_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8" CONTROL_CHAR_UUID = "1c95d5e3-d8f7-413a-bf3d-7a2e5d7be87e" class IMUDataLogger: def __init__(self): self.client = None self.log_file = None async def notification_handler(self, sender, data): """Handle incoming IMU data""" try: data_str = data.decode('utf-8') timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] log_entry = f"{timestamp},{data_str}\n" print(f"Data: {data_str}") if self.log_file: self.log_file.write(log_entry) self.log_file.flush() except Exception as e: print(f"Error handling notification: {e}") async def send_command(self, command): """Send control command to ESP32""" if self.client and self.client.is_connected: await self.client.write_gatt_char(CONTROL_CHAR_UUID, command.encode()) print(f"Sent command: {command}") async def connect_and_log(self): """Main connection and logging function""" print("Scanning for ESP32-IMU...") devices = await BleakScanner.discover() esp32_device = None for device in devices: if device.name == "ESP32-IMU": esp32_device = device break if not esp32_device: print("ESP32-IMU not found!") return print(f"Found ESP32-IMU: {esp32_device.address}") # Open log file filename = f"imu_data_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.csv" self.log_file = open(filename, 'w') self.log_file.write("timestamp,millis,acc_x,acc_y,acc_z,gyro_x,gyro_y,gyro_z\n") async with BleakClient(esp32_device.address) as client: self.client = client print("Connected!") # Start notifications await client.start_notify(IMU_CHAR_UUID, self.notification_handler) # Interactive command loop print("\nCommands:") print(" rate <hz> - Set sampling rate (e.g., 'rate 200')") print(" display on/off - Turn display on/off") print(" quit - Exit program") try: while True: command = await asyncio.get_event_loop().run_in_executor(None, input, "> ") if command.lower() == 'quit': break elif command.lower().startswith('rate '): rate = command.split()[1] await self.send_command(f"RATE:{rate}") elif command.lower() == 'display on': await self.send_command("DISPLAY:ON") elif command.lower() == 'display off': await self.send_command("DISPLAY:OFF") else: print("Unknown command") except KeyboardInterrupt: print("\nStopping...") finally: await client.stop_notify(IMU_CHAR_UUID) if self.log_file: self.log_file.close() print(f"Data saved to {filename}") async def main(): logger = IMUDataLogger() await logger.connect_and_log() if __name__ == "__main__": asyncio.run(main())Installation requirements:
For ESP32 (Arduino IDE):
- Install ESP32 board support
- Install libraries:
- TFT_eSPI (configure User_Setup.h for your display)
- QMI8658 library
For PC (Python):
pip install bleak asyncioUsage:
- Upload the ESP32 code
- Run the Python script on your PC
- The script will automatically find and connect to the ESP32
- Use commands to control sampling rate and display
- Data is automatically logged to a CSV file
The system allows you to:
- Set IMU sampling rate via Bluetooth (e.g., "rate 200" for 200Hz)
- Turn display on/off to save power
- Stream IMU data continuously to PC
- Log all data with timestamps to CSV file