Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 5 of 5

Thread: Calling attachInterrupt() inside a C++ class

  1. #1

    Calling attachInterrupt() inside a C++ class

    I'm trying to write a C++ class which a attachInterrupt() is called but it won't compile and giving me an error message of :

    /var/folders/6s/w7v5ds1s2hb0f3g_z9fb0ftc0000gn/T/arduino_build_39910/sketch/lin.cpp: In member function 'void lin::slave_init()':
    lin.cpp:16: error: invalid use of non-static member function
    attachInterrupt(digitalPinToInterrupt(rx_pin),rxIS R,CHANGE);
    ^
    invalid use of non-static member function

    How can I fix this ?

    isr_test.ino
    Code:
    #include "lin.h"
    
    lin linslave(1);
    
    void setup() {
      // put your setup code here, to run once:
    
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
    
    }
    lin.cpp
    Code:
    #include "lin.h"
    
    lin::lin(uint8_t Rx_pin)
    {
     rx_pin = Rx_pin;
    }
    
    void lin::rxISR(void)
    {
      uint8_t i;
      
    }
    void lin::slave_init(void)
    {
      
      attachInterrupt(digitalPinToInterrupt(rx_pin),rxISR,CHANGE);  // <- This line won't compile
      
    }
    lin.h
    Code:
    #include <Arduino.h>
    
    class lin
    {
      
      public:
      lin(uint8_t Rx_pin);
      void rxISR(void);
      void slave_init(void);
     
      private:
      uint8_t rx_pin;
      
    };
    This compiles ok if I don't use class and put everything in the .ino file but making a class would be more useful to others.

  2. #2
    Senior Member+ Frank B's Avatar
    Join Date
    Apr 2014
    Location
    Germany NRW
    Posts
    5,254
    Why is it more useful? You can use the interrupt vector only one time.

  3. #3
    More useful to others, as in people by making a class in a library.

  4. #4
    Senior Member
    Join Date
    Feb 2017
    Posts
    247
    You can't get a pointer to a member function the same way as a regular function. See: https://isocpp.org/wiki/faq/pointers-to-members

  5. #5
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    19,248
    This line in the class definition is the problem.

    Code:
      void rxISR(void);
    Functions called from attachInterrupt must be static.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •