-
Notifications
You must be signed in to change notification settings - Fork 827
feat: Add support for SHT21 sensor #3024
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Inuth0603
wants to merge
3
commits into
fossasia:flutter
Choose a base branch
from
Inuth0603:feat/sht21-v2
base: flutter
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import 'dart:async'; | ||
| import '../peripherals/i2c.dart'; | ||
|
|
||
| class SHT21 { | ||
| // SHT21 Default I2C Address | ||
| static const int addr = 0x40; | ||
|
|
||
| // The I2C helper instance (passed in from the main app) | ||
| final I2C i2c; | ||
|
|
||
| // Constructor: Ask for the I2C object instead of trying to create a new empty one | ||
| SHT21(this.i2c); | ||
|
|
||
| // Commands (No Hold Master Mode) | ||
| static const int _triggerTempMeasure = 0xF3; | ||
| static const int _triggerHumMeasure = 0xF5; | ||
|
|
||
| /// Read Temperature in Celsius | ||
| Future<double> getTemperature() async { | ||
| // 1. Send the "Measure" command | ||
| // We use writeBulk because it sends the bytes directly to the address | ||
| await i2c.writeBulk(addr, [_triggerTempMeasure]); | ||
|
|
||
| // 2. Wait for measurement (Datasheet max ~85ms) | ||
| await Future.delayed(Duration(milliseconds: 100)); | ||
|
|
||
| // 3. Read 3 bytes (MSB, LSB, Checksum) | ||
| // simpleRead automatically handles the "Start Condition" + "Read" logic | ||
| List<int> data = await i2c.simpleRead(addr, 3); | ||
|
|
||
| if (data.length < 2) return 0.0; | ||
|
|
||
| // 4. Combine bytes & clear status bits | ||
| int rawValue = (data[0] << 8) | (data[1] & 0xFC); | ||
|
|
||
| // 5. Calculate Formula | ||
| return -46.85 + 175.72 * (rawValue / 65536.0); | ||
| } | ||
|
|
||
| /// Read Humidity in %RH | ||
| Future<double> getHumidity() async { | ||
| // 1. Send Measure Command | ||
| await i2c.writeBulk(addr, [_triggerHumMeasure]); | ||
|
|
||
| // 2. Wait | ||
| await Future.delayed(Duration(milliseconds: 100)); | ||
|
|
||
| // 3. Read | ||
| List<int> data = await i2c.simpleRead(addr, 3); | ||
| if (data.length < 2) return 0.0; | ||
|
|
||
| int rawValue = (data[0] << 8) | (data[1] & 0xFC); | ||
|
|
||
| // 4. Calculate | ||
| return -6.0 + 125.0 * (rawValue / 65536.0); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import 'dart:async'; | ||
| import 'package:flutter/foundation.dart'; | ||
| import '../communication/sensors/sht21.dart'; | ||
| import '../communication/peripherals/i2c.dart'; | ||
|
|
||
| class SHT21Provider with ChangeNotifier { | ||
| SHT21? _sensor; | ||
| bool isWorking = false; | ||
| double temp = 0.0; | ||
| double hum = 0.0; | ||
|
|
||
| // Initialize the sensor with the I2C connection | ||
| Future<void> init(I2C i2c) async { | ||
| // This fixes the lint warning you saw earlier | ||
| _sensor ??= SHT21(i2c); | ||
| } | ||
|
|
||
| // Start the loop to read data | ||
| Future<void> startDataLog() async { | ||
| if (_sensor == null) return; | ||
|
|
||
| isWorking = true; | ||
| notifyListeners(); | ||
|
|
||
| while (isWorking) { | ||
| // Fetch new values | ||
| temp = await _sensor!.getTemperature(); | ||
| hum = await _sensor!.getHumidity(); | ||
|
|
||
| // Update UI | ||
| notifyListeners(); | ||
|
|
||
| // Wait 1 second before next read | ||
| await Future.delayed(Duration(milliseconds: 1000)); | ||
| } | ||
| } | ||
|
|
||
| // Stop the loop | ||
| void stopDataLog() { | ||
| isWorking = false; | ||
| notifyListeners(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import 'package:flutter/material.dart'; | ||
| import 'package:provider/provider.dart'; | ||
| import 'package:pslab/communication/science_lab.dart'; | ||
| import 'package:pslab/communication/peripherals/i2c.dart'; // Import I2C class | ||
| import 'package:pslab/providers/locator.dart'; | ||
| import '../providers/sht21_provider.dart'; | ||
|
|
||
| class SHT21Screen extends StatefulWidget { | ||
| const SHT21Screen({super.key}); | ||
|
|
||
| @override | ||
| State<SHT21Screen> createState() => _SHT21ScreenState(); | ||
| } | ||
|
|
||
| class _SHT21ScreenState extends State<SHT21Screen> { | ||
| @override | ||
| void initState() { | ||
| super.initState(); | ||
| WidgetsBinding.instance.addPostFrameCallback((_) { | ||
| final sht21Provider = Provider.of<SHT21Provider>(context, listen: false); | ||
|
|
||
| // 1. Get the ScienceLab instance | ||
| final scienceLab = getIt<ScienceLab>(); | ||
|
|
||
| // 2. Check connection | ||
| if (scienceLab.isConnected()) { | ||
| // 3. MANUALLY create the I2C helper using the packet handler | ||
| // This fixes the "getter i2c not defined" error | ||
| I2C i2c = I2C(scienceLab.mPacketHandler); | ||
|
|
||
| // 4. Initialize the sensor provider | ||
| sht21Provider.init(i2c); | ||
| sht21Provider.startDataLog(); | ||
| } else { | ||
| ScaffoldMessenger.of(context).showSnackBar( | ||
| const SnackBar(content: Text('Device not connected')), | ||
| ); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| @override | ||
| void dispose() { | ||
| // Stop the data loop when leaving the screen | ||
| if (mounted) { | ||
| Provider.of<SHT21Provider>(context, listen: false).stopDataLog(); | ||
| } | ||
| super.dispose(); | ||
| } | ||
|
|
||
| @override | ||
| Widget build(BuildContext context) { | ||
| return Scaffold( | ||
| appBar: AppBar( | ||
| title: const Text('SHT21 Sensor'), | ||
| ), | ||
| body: Consumer<SHT21Provider>( | ||
| builder: (context, provider, child) { | ||
| return Padding( | ||
| padding: const EdgeInsets.all(16.0), | ||
| child: Column( | ||
| children: [ | ||
| _buildSensorCard( | ||
| title: "Temperature", | ||
| value: provider.temp.toStringAsFixed(2), | ||
| unit: "°C", | ||
| icon: Icons.thermostat, | ||
| color: Colors.redAccent, | ||
| ), | ||
| const SizedBox(height: 20), | ||
| _buildSensorCard( | ||
| title: "Humidity", | ||
| value: provider.hum.toStringAsFixed(2), | ||
| unit: "%", | ||
| icon: Icons.water_drop, | ||
| color: Colors.blueAccent, | ||
| ), | ||
| ], | ||
| ), | ||
| ); | ||
| }, | ||
| ), | ||
| ); | ||
| } | ||
|
|
||
| Widget _buildSensorCard({ | ||
| required String title, | ||
| required String value, | ||
| required String unit, | ||
| required IconData icon, | ||
| required Color color, | ||
| }) { | ||
| return Card( | ||
| elevation: 4, | ||
| child: Padding( | ||
| padding: const EdgeInsets.all(20.0), | ||
| child: Row( | ||
| children: [ | ||
| Icon(icon, size: 40, color: color), | ||
| const SizedBox(width: 20), | ||
| Column( | ||
| crossAxisAlignment: CrossAxisAlignment.start, | ||
| children: [ | ||
| Text(title, | ||
| style: const TextStyle(fontSize: 18, color: Colors.grey)), | ||
| Row( | ||
| children: [ | ||
| Text(value, | ||
| style: const TextStyle( | ||
| fontSize: 32, fontWeight: FontWeight.bold)), | ||
| const SizedBox(width: 5), | ||
| Text(unit, style: const TextStyle(fontSize: 20)), | ||
| ], | ||
| ), | ||
| ], | ||
| ), | ||
| ], | ||
| ), | ||
| ), | ||
| ); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.