I want to write a class for a model bike.
For controlling the steering I use a DC motor with two encoders.
To get the steering angle stAng
of the bike, I attach a interrupt to the pin ST_ENC_A
where one of the encoders is connected to. This interrupt is attached when the bike is initialized with the function bike.begin()
. When the interrupt is triggerd, the increment-steering-angle-function incStAng
is triggerd.
Said function is member of the class Bike
. To make the whole code compile and upload I had to make the increment-steering-angle-function static void incStAng()
and the steering-angle-variable volatile static float stAng
static.
The code is running, there are no errors or warnings.
Now, when I provide pin ST_ENC_A
with 3.3V the interrupt should be triggerd and I should see the printed value of stAng
increse in the Serial Monitor. This is not the case. It stays at 0.00.
This is my first real class I am writing. I only want to create one instance of my bike so the static definition of stAng
and incStAng
should be no problem.
So far I found the following websites helpful for information on 'static' and ISR.
I would be glad if someone could help me and give me a hint why the steering angle is not increasing when I give said pin 3.3V!
Board: Arduino Nano RP2040 Connect
Below you will see the .ino, .h, .cpp files in this order.
// myBike.ino - main file
#include "Bike.h"
Bike bike;
void setup() {
Serial.begin(9600);
bike.begin();
}
void loop() {
float val = bike.getStAng();
Serial.println(val);
}
// Bike.h - header file for the Bike library
#ifndef Bike_h
#define Bike_h
#include "Arduino.h"
class Bike {
public:
Bike();
void begin();
float getStAng();
private:
volatile static float stAng;
static void incStAng();
};
#endif
// Bike.cpp - implementation file for the Bike library
#include "Bike.h"
#define ST_ENC_A 12
#define ST_ENC_B 11
#define DEG_PER_CNT 0.51428571428
Bike::Bike() {
pinMode(ST_ENC_A, INPUT);
pinMode(ST_ENC_B, INPUT);
}
void Bike::begin() {
attachInterrupt(digitalPinToInterrupt(ST_ENC_A),incStAng,RISING);
}
void Bike::incStAng() {
volatile float stAng;
int b = digitalRead(ST_ENC_B);
if(b==HIGH){
stAng = stAng - DEG_PER_CNT;
}else{
stAng = stAng - DEG_PER_CNT;
}
}
float Bike::getStAng() {
volatile float stAng;
return stAng;
}