I am using the Arduino Uno and i have a tactile bump sensor with me. I would like to program it so that when the sensor is activated at first, the LEDs would turn on and stay on, when it is pressed second time, it would slowly fade until it reach like a small amount of light and third time it would stop (no light). Initially, it should be off.
here is my code which needs improvement. this would just turn on the LEDs but i do not know how to count the number of times the sensor is activated.
int E1 = 6;
int M1 = 7;
int E2 = 5;
int M2 = 4;
void setup() {
pinMode(M1, OUTPUT); //LED 1
pinMode(M2, OUTPUT); //LED 2
pinMode(2, INPUT); //sensor
}
int direction = HIGH;
void loop() {
int Out = digitalRead(2);
if (Out == 0) {
digitalWrite(M1,direction);
digitalWrite(M2, direction);
analogWrite(E1, 255); //PWM Speed Control
analogWrite(E2, 255); //PWM Speed Control
delay(100);
}
and by the way i am also using L298P shield.
I have a plan though of making a variable called count = 0. and whenever the sensor is pressed it would increment. However, i have no idea how to implement this. I actually tried a couple of times but failed.
I am confused as to what you are trying to accomplish. The first code you posted accomplishes a different thing than the second code. Your code will not work because when the loop is cycled through twice (while you are hitting the button), the variable is immediately greater than 1, so neither of your if cases will work. Please explain what m1, e1, e2, and m2are connected to. Based on your original code, here is code that will do (what I think) you want to do:
int pin = 13;
volatile int state = LOW;
volatile int laststate = LOW;
int E1 = 6;
int M1 = 7;
int E2 = 5;
int M2 = 4;
int presses = 0;
bool motordir = HIGH;
int value;
void setup()
{
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
pinMode(2, INPUT);
digitalWrite(2, HIGH);
pinMode(pin, OUTPUT);
attachInterrupt(0, changestate, RISING);
}
void loop()
{
if (laststate != state)
{
if (presses % 2 == 0) {
for(value = 0 ; value <= 255; value+=5) {
digitalWrite(M1,motordir);
digitalWrite(M2, motordir);
analogWrite(E1, value); //PWM Speed Control
analogWrite(E2, value); //PWM Speed Control
delay(100);
}
} else {
for(value = 255 ; value <= 255; value-=5) {
digitalWrite(M1,motordir);
digitalWrite(M2, motordir);
analogWrite(E1, value); //PWM Speed Control
analogWrite(E2, value); //PWM Speed Control
delay(100);
}
}
}
}
void changestate()
{
laststate = state;
state = !state;
presses++;
}