1

I need help with this code, I want to have a motor turn on for a given time and at the same time have an led light up to indicate it is on which will also turn of once the motor has stopped. It is controlled by A TECT5000 SENSOR, which acts like a switch to transfer a signal to the motor and LED.

At the moment, I can get the motor to turn on and off for a given time but not the LED. Every time I activate the circuit with the sensor it turns on and stays on or turns of and stays of. Here is the current code I am using.

// Program: Led drive using reflective optical sensor   
// Author: Arduino e Cia  

int outgoingsignal = 8 ; // Pin of led   
int pinsensor = 7 ;   // Connected to the "collector" pin of the optical sensor   
int reading;      // Stores information about sensor reading   
int statusled = 0 ;
int motorPin = 9;  // define the pin the motor is connected to
                   // (if you use pin 9,10,11 or 3you can also control speed)
                   // Stores led status (on / off)  

void setup ()  
{  
  pinMode (outgoingsignal, OUTPUT); // Defines the led pin as 
  pinMode (pinsensor, INPUT);   // Defines the sensor pin as input
   pinMode(motorPin, OUTPUT); 
}  

void loop ()  
{  
  // Le the sensor pin information
  reading = digitalRead (pinsensor);   
  if (reading != 1 ) // Checks if the object was detected  
  {  
    while (digitalRead (pinsensor)!= 1)  
    {  
     delay (100);  
    }  

    statusled =! statusled; 
    // Reverses the status of the led (on / off) 

    // Turns on or off the led as "statusled" 
    digitalWrite (outgoingsignal, statusled); 
  motorOnThenOffWithSpeed(); }  

}  
void motorOnThenOffWithSpeed(){

  int onSpeed = 255;  // a number between 0 (stopped) and 255 (full speed) 
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 0;  // a number between 0 (stopped) and 255 (full speed) 
  //int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
 // delay(offTime);                   // waits for offTime milliseconds 
}
1

If you just want the led on with the motor then put a couple of digitalWrite statements in your motorOnThenOffWithSpeed function to turn the led on and off at the same time you turn the motor on and off.

0

Easy three steps:

  1. Connect the led to the motor control pin (via some means to limit the current).

  2. Program your motor control pin to turn it on or off as you so desire.

  3. Sit back and enjoy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.