Hello all,
I’m having a usage fault error
From what I’ve read on it, its something to do with data lying between addressable locations due to the 32-bit architecture… I have a feeling that bitshifting might be a cause of this. Maybe somebody could have a gander at my code and see what the issue might be?
Note that my code is done sort of object-oriented, which hasn’t been an issue with any of my other classes. /Also please excuse me arguing with myself in the comments/
#ifndef OPT3001_LUX_H
#define OPT3001_LUX_H
#include <math.h>
#include "application.h"
#include "Sensor.cpp"
class OPT3001_LUX : public Sensor
{
private:
double lux = 0; // stores temperature in celsius
bool error = false;
public:
OPT3001_LUX(byte address) //default constructor
{
this -> sampleNum = 0;
this -> sampleCount = 0;
this -> sampleTotal = 0;
this -> previousMillis = 0;
this -> reading = 0;
this -> unit = "lux";
this -> name = "Light Sensor"; //code for ADC slot 1
this -> i2cAddress = address; //address of sensor/ADC //should be 0x44
}
void init() //Initialisation - anything time-sensitive should go here and not in the constructor
{
previousMillis = millis();
}
void sample() //Sampling means adding an extra sample to the value and incrementing samplecount
{
//do nothing, this sensor only provides one read and does not average
//what to do here then??
}//end sample()
double convert(double input, boolean printDebug, int adcMax) //Function to convert raw reading to input value
{
return input/2;
}
int writeData(byte command)
{
Wire.beginTransmission(i2cAddress);
Wire.write(command);
return(Wire.endTransmission(true));
}
double read() //Function to average the sampled values, reset the sample counter and return the raw reading
{
this -> previousMillis = millis(); //Reset timer
int error = writeData(0); //write 0 to the chip (requests data reading)
if (error == 0) {
lux = 0; //load struct's .lux with 0
int reading = readData(); //error = address of er... rawdata //pointer operations my son
if (reading > 0) //if there is no immediate error in the reading
lux = 0.01*pow(2, 4) * reading; //result of lux = 0.01 ( two to the power of ) error exponent? * error . result... is this a shitty float converter?
else
return -1; //else result error
return lux; //return entire OPT3001 struct
}
else
{
return -1;
}
}
void writeCommand(uint16_t cmd)
{
Wire.beginTransmission(i2cAddress);
Wire.write(cmd >> 8);
Wire.write(cmd & 0xFF);
Wire.endTransmission();
}
uint16_t readData() //read data from i2c bus
{
byte lsb;
byte msb;
Wire.requestFrom(i2cAddress, 2);
int counter = 0;
//ALL THIS MSB AND LSB STUFF MIGHT WELL NEED SWAPPING
while(Wire.available() <2)
{
if ((lsb > 0) && (msb > 0))
{
uint16_t output = (msb << 8) | lsb;
return output;
}
else if (lsb>0)
{
msb = Wire.read();
counter ++;
}//end if
else
{
lsb = Wire.read();
counter++;
}//end else
}//end while
}//end readData()
};//end class
#endif // OPT3001_LUX