I'm creating a car that uses a solenoid valve to move and a magnetometer to direct it self to a specific location . every time the solenoid fires it creates a magnetic field that gives a wrong reading for the magnetometer since its a compass. how can i stop the magnetometer from send values or the arduinos from recieving values from the magnetometer when the solinoid fires. this is my code.
#include <Servo.h>
#include <Wire.h>
#include <LSM303.h>
LSM303 compass;
Servo myservo;
int DISTANCE=0;
int servoPin = 3; // Pin that the servomotor is connected to
int solenoidPin = 2; // Pin that the mosfet is conected to
int switchPin = 4; // Pin that the switch is conected to
int pos = 0; // variable to store the servo position
int switchState;
int servoDir = 0;
int solenoidState = LOW;
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
myservo.attach(servoPin); // attaches the servo on pin 9 to the servo object
pinMode(solenoidPin, OUTPUT); //Sets the pin as an output
pinMode(switchPin, INPUT_PULLUP); //Sets the pin as an input_pullup
Serial.begin(9600); // starts serial communication @ 9600 bps
Wire.begin();
compass.init();
compass.enableDefault();
}
void loop() {
////////////// MAGNETOMETER ///////////////////////////////////////////////////
compass.read();
float heading = compass.heading();
////////////// SERVOMOTOR ///////////////////////////////////////////////////
if(heading>=230 && heading<=250)
{
pos=90;
}
if(heading>250)
{
pos=45;
}
if (heading<230)
{
pos=135;
}
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(10);
////////////// SOLENOID VALVE ///////////////////////////////////////////////////
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (solenoidState == LOW) {
solenoidState = HIGH;
} else {
solenoidState = LOW;
}
digitalWrite(solenoidPin, solenoidState); //Switch Solenoid ON/oFF
}
////////////// REED SWITCH ///////////////////////////////////////////////////
switchState = digitalRead(switchPin);
if (switchState==1)
{
DISTANCE=DISTANCE+10;
}
////////////// Distance ///////////////////////////////////////////////////////
////////////// Serial Print ///////////////////////////////////////////////////
Serial.print("Reed Switch: ");
Serial.print(switchState);
Serial.print(" Magnetometer: ");
Serial.println( heading );
//Serial.print(" Distance");
// Serial.println(DISTANCE);
delay(100);
}