Here is my program, I want to:
-
The microcontroller, Arduino UNO R3 sends 3.3V to the sensor, Accelerometer, MMA7361
-
The sensor turns on and send signal to the microcontroller.
-
When I move the sensor and if the voltage becomes more than 2V, the microcontroller sends 1.5V to the Transistor. Otherwise send 0V.
int outputPin1 = 3; // Pin D3
int outputPin2 = 5; // Pin D5
int analogPin = 0; // Input Pin A0
void setup()
{
pinMode (outputPin1, OUTPUT);
pinMode (outputPin2, OUTPUT);
Serial.begin(9600);
}
void loop()
{
int volts = 170; // send signals of 3.3v
analogWrite(outputPin1, volts); // to Accelerometer
int reading = analogRead(analogPin); // receive signal
delay(1000); // delay 5sec.
if (volts >= 100) // Input voltage is more than 2.0V
{
int volts = 77; // send signals of 1.5V
analogWrite(outputPin2, volts); // to Transistor
}
else
{
int volts = 0;
analogWrite(outputPin2, volts); // to Transistor
}
}
When I measure with Digital Multi Meter, it keeps showing 1.5V even it doesn't change the position of the sensor.
I guess there's some problem in the if, else line.
Best Answer
You are not using the
reading
variable in the if statement. Your if statement is checkingvolts
, and this never gets changed, it will always be at 170 (it will change to 77 for a few clock cycles, then back to 170.)Also you shouldn't declare your variables in the loop. And your delay is set to one second not 5. You should add a delay after
analogWrite(outputPin1, volts);
so the Accelerometer has time to power up.Here is what the code is doing now (assuming your voltage math is correct):
outputPin1
powers to ~3.3vanalogPin
reading >= 100
power outputPin2 to ~1.5v else 0vTo be more efficient, you don't need the variable
volts
andreading
.outputPin1
doesn't need to be in the loop. I also put the delay before youanalogRead(analogPin)
, so your if statement executes immediately after the reading, and on power up it allows your accelerometer time to power up. I also removed theSerial.begin(9600);
since you weren't using it. Your entire code could look like this:For future reference, you should use the serial
Serial.println("helpfull info");
to help you debug your code. Take a look at this example. Every time it takes a reading it transmits the reading back to the computer so you can see what is going on.Edit
Upload this and use a serial terminal to see what happens when you move the accelerometer.