// Written by: Mohamed Soliman
// This code is for controlling servo motor with IR remote control
// When clicking at any of two buttons the motor is toggling between the rotation and stop
#include <Wire.h>
#include "rgb_lcd.h"
#include <IRremote.h> //must copy IRremote library to arduino libraries
#include <Servo.h>
#define minus 0xFFE01F //clockwise rotation button
#define plus 0xFFA857 //counter clockwise rotation button
rgb_lcd lcd;
const int colorR = 100;
const int colorG = 100;
const int colorB = 100;
int RECV_PIN = 2; //IR receiver pin
Servo servo;
int val; //rotation angle
bool cwRotation, ccwRotation; //the states of rotation
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
servo.attach(9); //servo pin
lcd.begin(16, 2);// LCD 16 colonnes 2 lignes
lcd.setRGB(0, 255, 0);
lcd.setCursor(2,0);
lcd.print("portail 4eme");// écrit un message sur l'écran LCD.
lcd.setCursor(5,1);// écrit un message sur la ligne 1.
lcd.print("ready");
}
void loop()
{
if (irrecv.decode(&results))
{
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
if (results.value == plus)
{cwRotation = !cwRotation; //toggle the rotation value
ccwRotation = false; //no rotation in this direction
}
if (results.value == minus)
{ccwRotation = !ccwRotation; //toggle the rotation value
cwRotation = false; //no rotation in this direction
}
else
lcd.setRGB(0, 255, 0);
lcd.setCursor(2,0);
lcd.print("portail 4eme");// écrit un message sur la ligne 1.
lcd.setCursor(5,1);
lcd.print("ready");
}
if (cwRotation && (val != 90)) //for colockwise button
{ val++;
lcd.clear();
lcd.setRGB(237, 127, 16);
lcd.setCursor(3,1);
lcd.print("ouverture");
}
if (ccwRotation && (val != 0)) //for counter colockwise button
{ val--;
lcd.clear();
lcd.setRGB(237, 127, 16);
lcd.setCursor(3,1);
lcd.print("fermeture");
}
servo.write(val);
delay(50); //General speed
}
bool cwRotation, ccwRotation; //the states of rotation
You have two booleans so you can have it rotate both directions at the same time?
I just asked to rotate 90deg ....
You didn't. You ask it to rotate one more degree each time that the remote is clicked. You KNOW when it gets to 0 or when it gets to 90 (or at least when you tell it to go to 0 or to go to 90; presumably some short time later it will actually get there).
Separate your if statements.
if(cwRotation)
{
if(val < 90)
{
val++;
// move the servo and print "Opening"
}
else
{
// don't move the servo but print "Fully Open"
}
}
else // The only other option is to rotate ccw
{
if(val > 0)
{
val--;
// move the servo and print "Closing"
}
else
{
// don't move the servo but print "Fully Closed"
}
}