Devices & Components
Arduino Nano
10 jumper wires 150mm male
Robojax BMP280
4GB Micro SD Card
Breadboard 100x160
MicroSD card reader/writer
Software & Tools
Arduino IDE
Project description
Code
Altimeter with SD Card
cpp
Code with comments and serial debugging.
1#include <Wire.h> 2#include <SPI.h> 3#include <SD.h> 4#include <Adafruit_BMP280.h> 5 6Adafruit_BMP280 bmp; 7 8float newAlt; 9float alt; 10float origAlt; 11float temp; 12 13const int chipSelect = 10; // Change if your CS pin is different 14unsigned long lastLogTime = 0; 15 16void setup() { 17 Serial.begin(9600); 18 while (!Serial); // wait for serial on some boards 19 20 Serial.println("Initializing BMP280..."); 21 if (!bmp.begin(0x76, 0x60)) { 22 Serial.println("Error: BMP280 not found at 0x76"); 23 while (1); // halt 24 } 25 26 bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, 27 Adafruit_BMP280::SAMPLING_X2, 28 Adafruit_BMP280::SAMPLING_X16, 29 Adafruit_BMP280::FILTER_X16, 30 Adafruit_BMP280::STANDBY_MS_500); 31 32 origAlt = bmp.readAltitude(1013.25); // baseline altitude 33 34 Serial.println("Initializing SD card..."); 35 if (!SD.begin(chipSelect)) { 36 Serial.println("Error: SD init failed"); 37 while (1); 38 } 39 40 // Create or clear the log file at start 41 File logFile = SD.open("altlog.txt", FILE_WRITE); 42 if (logFile) { 43 logFile.println("Altitude(ft)"); 44 logFile.close(); 45 Serial.println("SD card ready, logging started."); 46 } else { 47 Serial.println("Error: Can't create log file"); 48 } 49} 50 51void loop() { 52 temp = bmp.readTemperature(); 53 newAlt = bmp.readAltitude(1013.25); 54 55 if (newAlt > alt) { 56 alt = newAlt; 57 } 58 59 float feet = (alt - origAlt) * 3.281; 60 61 // Log altitude to SD every second 62 if (millis() - lastLogTime >= 1000) { 63 lastLogTime = millis(); 64 65 File logFile = SD.open("altlog.txt", FILE_WRITE); 66 if (logFile) { 67 logFile.println(feet, 2); 68 logFile.close(); 69 } else { 70 Serial.println("Error: Can't open altlog.txt for writing"); 71 } 72 } 73}
Comments
Only logged in users can leave comments