Sunday, March 3, 2024

i2c – Use class object inside an ISR


I’ve to simulate an ADC that behaves as an I2C slave. The simulated values that the ADC shall expose are despatched over serial, saved on an attribute and are requested by a grasp system over I2C.

A simplified resolution is the next. I’ve a struct ADC that describes the converter:

struct ADC 
{
  uint32_t register_1;
  void write(uint32_t knowledge){
    register_1 = knowledge;
  }

  uint8_t learn(){
    return register_1;
  }

  // another strategies to setup...
};

In loop(), I learn the serial as a way to replace the ADC::register worth and within the onRequest handler I finally ship the requested knowledge by accessing ADC::register:

ADC adc{};

void setup(){
  // setup adc, Wire and Serial right here
  Wire.onRequest(slaveTransmitterHandler)
}

void loop(){
  if (Serial.accessible() > 0)
  {
     // learn serial, parse obtained knowledge and examine them
     uint32_t knowledge = parse_serial(); // do something is required to examine knowledge...

     // replace adc attribute
     uint8_t oldSREG = SREG;
     noInterrupts(); // disable interrupts to replace uint32
     adc.write(knowledge);
     SREG = oldSREG;
  }
}

void slaveTransmitterHandler(){
  Wire.beginTransmission(ADDRESS);
  Wire.write(adc.learn());
  Wire.endTransmission();
}

I am unsure if I’ve to declare the adc object as unstable (this is able to imply to declare all ADC strategies and variables as unstable). Is it protected to make use of an object contained in the I2C handler known as by the I2C interrupt?

So far as I do know, it isn’t (I can discover no purpose why it needs to be completely different from non class variables), however I’ve at all times labored with non class variables and by no means with cpp objects. Additionally, I am unable to discover any details about this matter.

It may very well be doable that I am incorrect with the entire design, even when it appears to me to be very constant. I am open to alter it for one thing higher, so please if this design is nonsense, touch upon that! I am right here to study 🙂

Thanks.

Luca

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles