Hi there, I am very new to the arduino, coding, circuits, and all this stuff in general, so sorry if this is rudimentary stuff I am asking about. I am trying to make an automatic sliding drawer for my robotics class. I basically used an arduino with two motors and a light sensor, so when the light turns on, the drawer gets pulled out, and when off, it gets pulled back in. The problem I am having is that I can't figure out how to get the motor to stop running. So if I turn on the light, the drawer will pull out and the motor just goes forever. I have used a basic if/else statement to activate the motors, does anybody have any suggestions on how to make the motors turn on for only a set time? Here is my code:
const int sensor = A0; //light sensor
const int motor1 = 9; //motor 1
const int motor2 = 10; //motor 2
int lightLevel;
void setup(){
Serial.begin(9600); }
void loop()
{
lightLevel = analogRead(sensor);
Serial.println(lightLevel);
if (lightLevel < 630)
{analogWrite(motor1, 255);}
else
{analogWrite(motor1, 0);}
if (lightLevel > 640)
{analogWrite(motor2, 255);}
else
{analogWrite(motor2, 0);}
}
See "time" in reference section. e.g. millis()
Or add end switches.
Or a motor current detector (motors draw more current when blocked).
Or a combination of those.
Leo..
the simplest way if youre not looking for the arduino to perform any other tasks is to simply put
delay(1000);
or however long it takes to open your drawer then turn the motor off in the statement ie
analoglWrite(motor1, 0);
you'll also need to set some sort of state variable so the motor knows whether the draw is open. you can include this in your open statment so say:
drawerState = 1;
and in the close statement
drawerState = 0;
include the logic for this in your if statements so you check the light level and drawerState by putting
if(lightlevel < 630 && drawerState == 0) for example.
Using time, you can arrange for the motors to slow when the drawer gets near to the end of its travel, so that it doesn't 'bang' shut or open, shaking the contents. End switches don't allow for this.
Well, you can set up your switches so that they switch upon contact but don't necessarily hinder further movement - the idea is then that they say 'ramp down nicely to a stop starting now' as opposed to 'stop now'.
1:1:
Well, you can set up your switches so that they switch upon contact but don't necessarily hinder further movement - the idea is then that they say 'ramp down nicely to a stop starting now' as opposed to 'stop now'.
Except that it's likely to be much more difficult to place the switches a cm or two before the end of travel to give them time to slow, than it would be to place them at the end of the rails. But it of courses depends on the physical characteristics of the drawer, the rails and the switches.
But more optimal solutions result in a system where you can position the switches how far along you like, you've also got really good resolution in your ramp down options (in code).