Thanks for replying. I have included my code which is the buttons working on their own, it doesn't have the LDR part in it as with this code I have never managed to make it work properly, but this is the code I want to add it too. I tired using the same idea as the buttons when I did try to make it work. PWA is the pulse width modulation pin for the motor (Motor A on the arduino motor shield). The set button is so I can set the encoder position so I can adjust the blinds without having to take the hardware apart to adjust its start point.
#define UPbutton 5
#define DOWNbutton 6
#define SETbutton 7
#define PWA 3
#define DIRA 12
int up = 0;
int old_up = 0;
int down = 0;
int old_down = 0;
int set = 0;
int state = 0;
//encoder
const int encoderPinA = 4;
const int encoderPinB = 2;
const int encoderStepsPerRevolution=200;
int angle = 0;
int val;
int encoderPos = 0;
boolean encoderALast = LOW; // remembers the previous pin state
//encoder end
void setup()
{
pinMode(UPbutton, INPUT);
pinMode(DOWNbutton, INPUT);
pinMode(SETbutton, INPUT);
pinMode(PWA, OUTPUT);
pinMode(DIRA, OUTPUT);
//encoder
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
digitalWrite(encoderPinA, HIGH);
digitalWrite(encoderPinB, HIGH);
Serial.begin (9600);
//encoder end
}
void loop()
{
up = digitalRead(UPbutton);
down = digitalRead(DOWNbutton);
set = digitalRead(SETbutton);
if((up == HIGH) && (old_up == LOW))
{
state = 1 - state;
delay(10);
}
if((down == HIGH) && (old_down == LOW))
{
state = 2 - state;
delay(10);
}
old_up = up;
old_down = down;
if(state == 0)
{
digitalWrite(DIRA, LOW);
analogWrite(PWA, 0);
}
//state 1 is upward motion
if(state == 1)
{
digitalWrite(DIRA, HIGH);
analogWrite(PWA, 255);
}
//state 2 is downward motion
if(state == 2)
{
digitalWrite(DIRA, LOW);
analogWrite(PWA, 255);
}
//autostop bit
if((encoderPos < 10) && (state == 1 ))
{
state = 0;
}
if((encoderPos > 600) && (state == 2))
{
state = 0;
}
//autostop bit end
//encoder
boolean encoderA = digitalRead(encoderPinA);
if ((encoderALast == HIGH) && (encoderA == LOW))
{
if (digitalRead(encoderPinB) == LOW)
{
encoderPos++;
}
else
{
encoderPos--;
}
angle=encoderPos;
Serial.print (state); //only new bit
Serial.print (encoderPos);
Serial.print (" ");
Serial.println (angle);
}
encoderALast = encoderA;
//encoder end
if(set == HIGH)
{
encoderPos = 20;
}
}