accelerometer demo using flutter, pico, hc-19 ble, micropython, source in the description

99 Просмотры
Издатель
replace _GT_ with greater than symbol
replace _LT_ with less than symbol
youtube don't like angle brackets
formatted code in http://crus.in/codes/flutter_pico_accel.txt
flutter phone accelerometer pico ble hc-19 demo
# demo to receive uart ble
# expect 8 bytes from ble
# 4 bytes float x accelerometer value
# 4 bytes float y accelerometer value

from machine import UART
import struct
buffer = bytearray(8)
uart = UART(1, 115200) # gp4 and gp5 on pico to ble hc-19
while True:
if uart.any():
count = uart.readinto(buffer)
if count _GT_ 7:
# check if there's no negative value
# if there is then subtract from 256
# unpack don't like negative values
for i in range(8):
if buffer[i] _LT_ 0: buffer[i] = 256 - buffer[i]
print("front to back")
print(struct.unpack('_GT_f', buffer[4:8]))
print("side to side")
print(struct.unpack('_GT_f', buffer[0:4]))
print(" ")



// flutter create my_app
// cd my_app
// flutter pub add get
// flutter pub add sensors_plus
// flutter pub add flutter_reactive_ble
// add location permission to this app and turn on bluetooth on the phone
///////////////////// main.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sensors_plus/sensors_plus.dart';
import 'package:get/get.dart';
import './blecontroller.dart';

void main() { runApp(const MyApp()); }

class MyApp extends StatelessWidget {const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {return GetMaterialApp(
title: 'Accelerator demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: const MyHomePage(title: 'Accelerator demo'));}}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, this.title}) : super(key: key);

final String? title;

@override
_MyHomePageState createState() =_GT_ _MyHomePageState();}

class _MyHomePageState extends State_LT_MyHomePage_GT_ {
final BleController ble = Get.put(BleController());
final _streamSubscriptions = _LT_StreamSubscription_LT_dynamic_GT__GT_[];

double x = 0.0;
double y = 0.0;

@override
Widget build(BuildContext context) {
return Scaffold(

appBar: AppBar(title: const Text('Sensor Example')),

body: Column(children: _LT_Widget_GT_[

SizedBox(height:50.0),

ElevatedButton(onPressed: ble.connect,
child: Obx(() =_GT_ Text('${ble.status.value}'))),

SizedBox(height: 50.0),

Text('turn off autorate and leave phone in portrait mode'),

SizedBox(height: 50.0),

Text('front to back $y', style: TextStyle(fontSize: 60.0, fontWeight: FontWeight.bold)),

SizedBox(height: 50.0),

Text('side to side $x', style: TextStyle(fontSize: 60.0, fontWeight: FontWeight.bold)),]),);}

@override
void dispose() {
super.dispose();
for (final subscription in _streamSubscriptions) {subscription.cancel();}}

@override
void initState() {
super.initState();
_streamSubscriptions.add(
accelerometerEvents.listen(
(AccelerometerEvent event) {
setState(() {
x = double.parse((event.x).toStringAsFixed(2));
y = double.parse((event.y).toStringAsFixed(2));
if (ble.status.value == 'connected!') {ble.sendBle(x, y);}});}));}}



/////////////// filename: blecontroller.dart
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';
import 'dart:async';
import 'dart:typed_data';

class BleController {
final frb = FlutterReactiveBle();
late StreamSubscription _LT_ConnectionStateUpdate_GT_ c;
late QualifiedCharacteristic tx;
final devId = 'A4:DA:32:55:06:1E'; // use nrf connect from playstore to find id
var status = 'connect to bluetooth'.obs;


// https://stackoverflow.com/questions/68919369/convert-double-value-to-listint-in-dart
// second answer
// convert double to list int 4 bytes each
// combine two list int 4 bytes each total of 8 bytes
// send to ble (see python above extracting 2 floats from 8 bytes of list int)
void sendBle(double x, double y) async {
ByteData bytes = ByteData(4);
bytes.setFloat32(0, x);
List_LT_int_GT_ x_data = bytes.buffer.asInt8List().toList();
ByteData bytes1 = ByteData(4);
bytes1.setFloat32(0, y);
List_LT_int_GT_ y_data = bytes1.buffer.asInt8List().toList();
var bleData = [...x_data, ...y_data];
await frb.writeCharacteristicWithoutResponse(tx, value: bleData); }

void connect() async {
status.value = 'connecting...';
c = frb.connectToDevice(id: devId).listen((state){
if (state.connectionState == DeviceConnectionState.connected){
status.value = 'connected!';

tx = QualifiedCharacteristic(
serviceId: Uuid.parse("FFE0"),
characteristicId: Uuid.parse("FFE1"),
deviceId: devId);}});}}
Категория
Язык программирования Dart
Комментариев нет.