I have defined a c++ class (RpmDriver) and want to use attachInterrupt in the constructor to link an Arduino pin to its ISR (RpmInt) in the class. When I try this, I get:
error: cannot convert 'RpmDriver::RPMInt' from type 'void (RpmDriver::)()' to type 'void (*)()'
This is the cpp file:
#include "RpmDriver.h"
#include <Arduino.h>
int currentRpm;
long lastMillis;
int pin;
RpmDriver::RpmDriver(int Pins[])
{
pin=Pins[0];
currentRpm=0;
pinMode(pin,INPUT);
lastMillis = millis();
attachInterrupt(digitalPinToInterrupt(pin),RPMInt, RISING);
}
RpmDriver::~RpmDriver(void)
{}
bool RpmDriver::GetData(char* dest,char* format)
{
sprintf(dest,format,currentRpm);
}
void RpmDriver::RPMInt()
{
double RPMConstant=40000;
unsigned long newMillis=millis();
unsigned long t = newMillis-lastMillis;
t=100;//temp
currentRpm=(t==0)?0:(int)RPMConstant/t;
lastMillis=newMillis;
}
and the header file is
#pragma once
class RpmDriver
{
public:
RpmDriver(int pins[]);
~RpmDriver(void);
bool GetData(char*,char*);
private:
void RPMInt(void);
};
Any help much appreciated!
-
1See my post Calling an ISR from a classNick Gammon– Nick Gammon ♦2015年10月31日 03:27:41 +00:00Commented Oct 31, 2015 at 3:27
2 Answers 2
You can't.
Simply because a class member is not the right format of function for attachInterrupt.
You can only use normal functions with attachInterrupt, so the normal method is to have a normal function outside your class which then calls the member function within your class. How you arrange it so that it knows where your objects are is up to you.
- If you have only one object then assign it to a global pointer in your library using the constructor
- If you have lots of instances then create a linked list within your class in a static context and add each object to it in the constructor, then iterate through that list when the interrupt fires.
You should qualify RpmDriver::RPMInt()
as static
.
Static member functions are very much like plain functions, only using
their class as a sort of namespace. Obviously, you will not be able to
access any member data, but this should not be a problem as it seems
your class is not storing any data anyway.