Dart开发:如何利用距离传感器触发函数?
Hey there! Awesome idea using a distance sensor to trigger functions with a hand wave in Dart—let’s walk through exactly how to pull this off, step by step.
1. Pick Your Hardware & Dart-Compatible Tools
First, you’ll need to match your setup to the device you’re using Dart on:
- Embedded devices (Raspberry Pi, ESP32):
- Go for a cheap, easy-to-use sensor like the HC-SR04 (ultrasonic) or VL53L0X (laser for higher precision)
- Use Dart libraries like
dart_periphery(supports GPIO/I2C for Raspberry Pi) oresp32dart(built for ESP32) to interface with hardware
- Flutter mobile apps:
- Phones don’t have distance sensors suitable for gesture detection, but you can either:
- Use the camera + Google ML Kit for on-device gesture recognition, or
- Connect a Bluetooth-enabled distance sensor and use
flutter_blue_plusto read its data
- Phones don’t have distance sensors suitable for gesture detection, but you can either:
2. Core Logic: What Counts as a "Wave"?
A wave translates to quick, repeated distance changes: far → near → far (or a few cycles of this). Your code will need to:
- Continuously read distance values from the sensor
- Track recent readings to spot these rapid fluctuations
- Trigger your target function when the pattern matches a wave
3. Example Implementation (Raspberry Pi + HC-SR04)
Let’s put this into code with the dart_periphery library:
First, add the dependency to your pubspec.yaml:
dependencies: dart_periphery: ^1.4.0
Then the main code:
import 'dart:async'; import 'package:dart_periphery/dart_periphery.dart'; // Define sensor pins (adjust to your wiring) const trigPin = 23; const echoPin = 24; // Store recent distances to detect patterns List<double> recentDistances = []; const maxRecentEntries = 3; // Your target function to run when a wave is detected void onWaveDetected() { print("Wave detected! Executing target function..."); // Add your custom logic here } // Read distance from HC-SR04 (returns cm) Future<double> readDistance() async { final gpioTrig = GPIO(trigPin, GPIOdirection.GPIO_OUT); final gpioEcho = GPIO(echoPin, GPIOdirection.GPIO_IN); // Send trigger signal await gpioTrig.write(0); await Future.delayed(Duration(microseconds: 2)); await gpioTrig.write(1); await Future.delayed(Duration(microseconds: 10)); await gpioTrig.write(0); // Measure echo duration while (await gpioEcho.read() == 0); final start = DateTime.now().microsecondsSinceEpoch; while (await gpioEcho.read() == 1); final end = DateTime.now().microsecondsSinceEpoch; // Calculate distance (speed of sound = 0.0343 cm/μs, divide by 2 for round trip) final distance = ((end - start) * 0.0343) / 2; gpioTrig.dispose(); gpioEcho.dispose(); return distance; } // Start monitoring for wave gestures void startWaveDetection() { Timer.periodic(Duration(milliseconds: 100), (timer) async { final distance = await readDistance(); // Filter out invalid readings (e.g., too far/close) if (distance < 10 || distance > 100) return; recentDistances.add(distance); if (recentDistances.length > maxRecentEntries) { recentDistances.removeAt(0); } // Check for wave pattern: middle reading is significantly closer than first/last if (recentDistances.length == maxRecentEntries) { final first = recentDistances[0]; final middle = recentDistances[1]; final last = recentDistances[2]; if ((middle < first - 10) && (middle < last - 10)) { onWaveDetected(); // Reset to avoid duplicate triggers recentDistances.clear(); } } }); } void main() async { print("Starting wave detection..."); startWaveDetection(); // Keep the program running await Future.delayed(Duration(days: 1)); }
4. Pro Tips for Better Detection
- Calibrate sensitivity: Adjust the distance threshold (the
10in the example) and sampling rate (100ms) to fit your space - Filter noise: Smooth readings by taking averages of multiple samples to reduce false triggers
- Save power: If using a battery-powered device, lower the sampling frequency when idle
- Mobile alternative: For Flutter apps, use ML Kit’s gesture recognition to detect waves via the camera instead of a hardware sensor
内容的提问来源于stack exchange,提问作者Alex East
相关产品推荐
相关产品推荐

