I am trying to set up a weather station, and I should just have the anemometer left. This code works fine (as far as I know).
// Pin definitions
const int reedSwitchPin = 2;
// Variables
volatile unsigned long lastRotationTime = 0;
volatile float windSpeed = 0.0;
const float windSpeedFactor = 2.4; // Factor to convert rotation time to wind speed
void setup() {
pinMode(reedSwitchPin, INPUT_PULLUP);
// attachInterrupt(digitalPinToInterrupt(reedSwitchPin), handleRotation, FALLING);
Serial.begin(9600);
Serial.println("hello world!");
}
void loop() {
// Test reed switch functionality
int reedState = digitalRead(reedSwitchPin);
if (reedState == HIGH) {
Serial.println("Reed switch triggered!");
}
// Calculate wind speed based on the time between rotations
unsigned long elapsedTime = micros() - lastRotationTime;
if (elapsedTime > 0) {
windSpeed = windSpeedFactor / (float)elapsedTime;
}
Serial.print("Wind Speed: ");
Serial.print(windSpeed);
Serial.println(" m/s");
delay(1000); // Delay for 1 second before measuring again
}
void handleRotation() {
// Record the time of the last rotation
lastRotationTime = micros();
}
But when I uncomment the following line: attachInterrupt(digitalPinToInterrupt(reedSwitchPin), handleRotation, FALLING);
it prints garbage characters on the serial monitor. Here is the full code:
// Pin definitions
const int reedSwitchPin = 2;
// Variables
volatile unsigned long lastRotationTime = 0;
volatile float windSpeed = 0.0;
const float windSpeedFactor = 2.4; // Factor to convert rotation time to wind speed
void setup() {
pinMode(reedSwitchPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(reedSwitchPin), handleRotation, FALLING);
Serial.begin(9600);
Serial.println("hello world!");
}
void loop() {
// Test reed switch functionality
int reedState = digitalRead(reedSwitchPin);
if (reedState == HIGH) {
Serial.println("Reed switch triggered!");
}
// Calculate wind speed based on the time between rotations
unsigned long elapsedTime = micros() - lastRotationTime;
if (elapsedTime > 0) {
windSpeed = windSpeedFactor / (float)elapsedTime;
}
Serial.print("Wind Speed: ");
Serial.print(windSpeed);
Serial.println(" m/s");
delay(1000); // Delay for 1 second before measuring again
}
void handleRotation() {
// Record the time of the last rotation
lastRotationTime = micros();
}