Hello, we are trying to make a LED light up when the magnetic field strength detected by our magnetometer MAG3110 passes a certain threshold. Our code compiles and downloaded into our Arduino UNO Board, but when the magnetic field shown on the serial plotter passes the threshold, our LED does not light up. We are wondering which variable we should use to show the data collected by the magnetometer. Currently we are using mag_read_value. Any help is greatly appreciated.
#include <Wire.h>
#include <Wire.h> // Import wire library
#define MAG_ADDR 0x0E //i2C Address 7Bit address
void setup()
{
Wire.begin(); // Start i2c bus this optional for master
Serial.begin(9600);
config(); // Start MAG3110 on
}
void loop()
{
print_values();
delay(5);
int MYLED = 13;
if (mag_read_value > -1940)
{
digitalWrite(MYLED, HIGH);
}
else if (mag_read_value < -2040)
{
digitalWrite(MYLED, HIGH);
}
else
{
digitalWrite(MYLED, LOW);
}
}
void config(void)
{
Wire.beginTransmission(MAG_ADDR); // Transmit to i2c device 0x0E
Wire.write(0x11); // control the register 2
Wire.write(0x80); // set to write 0x80 to enable auto resets
Wire.endTransmission(); // set to stop transmitting
delay(15);
Wire.beginTransmission(MAG_ADDR); // set to transmit i2c device 0x0E
Wire.write(0x10); // control register 1
Wire.write(1); // set to write 0x01 to enable active mode
Wire.endTransmission(); // set tp stop transmitting
}
void print_values(void)
{
Serial.print("--------- 14CORE | MAG3110 3-AXIS TEST CODE ----------")
;Serial.println("======================================================")
;Serial.println("Starting... ")
;Serial.println("")
;Serial.print("X = ");
Serial.print(read_x());
Serial.println("--------------");
Serial.print(" Y = ");
Serial.print(read_y());
Serial.println("----------------");
Serial.print("Z = ");
Serial.println(read_z());
}
int mag_read_register(int reg)
{
int reg_val;
Wire.beginTransmission(MAG_ADDR); //start transmit to i2c device address 0x0E
Wire.write(reg);
Wire.endTransmission();
delayMicroseconds(2); //Delay for 1.3 to start and stop
Wire.requestFrom(MAG_ADDR, 1); // set to request 1 byte
while(Wire.available()) // set the slave may write less than requested
{
reg_val = Wire.read(); // starting reading the byte
}
return reg_val;
}
int mag_read_value(int msb_reg, int lsb_reg)
{
int val_low, val_high; //set variable to define the MSB and LSB
val_high = mag_read_register(msb_reg);
delayMicroseconds(2);
val_low = mag_read_register(lsb_reg);
int out = (val_low|(val_high << 8)); //concatenate the MSB and LSB
return out;
}
int read_x(void)
{
return mag_read_value(0x01, 0x02);
}
int read_y(void)
{
return mag_read_value(0x03, 0x04);
}
int read_z(void)
{
return mag_read_value(0x05, 0x06);
}