So like the title says, I want to control a motor with a light sensor.
I currently have the light sensor as an input, and then a DC motor connected to a h-bridge as an output(so I can control the direction of the motor).
As soon as the light level go over a certain value, I want the motor to turn clockwise (direction1) for 2 seconds exactly, and then stop.
And when the light level goes under a certain value, I want to the motor to turn counter clockwise (direction2) for 2 seconds and then stop.
I was trying to do this with the millis() function.
below is an example of what I tried to do, and it didn't seem to work.
Anybody have any ideas on how I could get this to work?
void loop()
{
lightlevel = analogRead(lightPin);
Serial.print(lightlevel);
Serial.print("\n");
delay(200);
timer = millis();
Serial.print(timer);
Serial.print("\t");
if (lightlevel > 800)
{
motortimer = timer + 2000
if (timer < motortimer)
{
digitalWrite(direction1, HIGH);
digitalWrite(direction2, LOW);
}
}
What is that delay(200) doing there, other than messing with your timing?
Two problems:
- you detect when the light level IS >800, not when it BECOMES >800 (this is called state checking).
- you never seem to switch off the motor.
You could do something like this in loop():
// Check for light level going higher than a certain level, and start the motor accordingly.
if (lightLevel > 800 && highLight == false) {
highLight = true;
motorStartTime = millis();
}
// Record when the light level is low - build in some hysteresis or if you're around 800 your motor is on all the time.
if (lightLevel < 700) {
highLight = false;
}
// Operate the motor: run it for 2000 ms from motorStartTime.
if (millis() - motorStartTime < 2000) {
// motor on.
}
else {
// motor off.
}
I don't know how your H-bridge is wired, but do make sure to switch it off completely before switching on the desired direction. This prevents shoot-through which can be pretty disastrous even if it happens for a very short time.
Hi,
Welcome to the forum.
Please read the first post in any forum entitled how to use this forum.
http://forum.arduino.cc/index.php/topic,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.
Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?
Thanks.. Tom... 