Go Down

Topic: Code Help (Read 652 times) previous topic - next topic

Malikdbuseck

Hello Im currently working on an arduino uno project and I want my servo and photo resistor to work at the same time. I can only ever get one to work. Either the servo or the light and photo sensor. Please help me with my code if you can! c: THANKS

Quote
const int sensorPin = 0;
const int ledPin = 9;
const int Servol = 3;

int lightLevel, high = 0, low = 1023;

#include <Servo.h>
Servo servo1;
 
void setup()
{
servo1.attach(3); 
  pinMode(ledPin, OUTPUT);
}

void loop()
{
int position;
  servo1.write(90);   
  delay(1000);         
  servo1.write(180);   
  delay(1000);         
  servo1.write(0);     
  delay(1000);         
  for(position = 0; position < 180; position += 2)
 
  {
    servo1.write(position);
    delay(20);
  }
    for(position = 180; position >= 0; position -= 1)
  {                               
    servo1.write(position); 
    delay(20);
  lightLevel = analogRead(sensorPin);

 
  analogWrite(ledPin, lightLevel); 
}
}

void manualTune()
{
  lightLevel = map(lightLevel, 0, 1023, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255); 
}

void autoTune()
{

  if (lightLevel < low)
  {
    low = lightLevel;
  }
 
  if (lightLevel > high)
  {
    high = lightLevel;
  }

  lightLevel = map(lightLevel, low+30, high-30, 0, 255);
  lightLevel = constrain(lightLevel, 0, 255); 
}


codelectron

You need to map the analogRead value to analogWrite either using map function or like this analogWrite(ledPin, val / 4); Since analogWrite takes input from 0 to 255 you need to scale down the analogRead value. http://arduino.cc/en/Reference/analogWrite . Your code looks fine, If you describe about what you are trying to achieve then its  possible to find a fix.

Krishna

Simpson_Jr

You're using the delay()-function with quite large numbers, It probably is best to study the "blink without delay" example.

Problem is that arduino  doesn't do anything except waiting until the delay()-function is finished.

By storing  the result of the millis()  function in a variable, you can check "how late it is" before you  set your servo in a position and continue the loop (do other things). By checking  millis() continuously in the loop as well, you can compare it with the first value and once it's 1000 milliseconds larger,  perform the next step in your servo-routine.

Instead of waiting at one function using delay(), using millis() your  arduino will continuously perform tasks in your loop until it's time for the next  step and you can  do other things while it's not time yet.

Go Up