Ohh Robin.
Now I check that the PWM is not working on pin 7. And moove to pin 5 and now its OK.
The other I think last problem is how can I implement in a memory position moovement 2 speeds. First 255 and then (for example) 50 to run into target.
Here is the last version with cut out everything possible?
#include <Button.h>
#include <Encoder.h>
const int PWM0 = 6;
const int PWM1 = 5;
const int BTN_EXTEND = 4;
const int BTN_RETRACT = 5;
const int BTN_MEM_PIN[] = {8,9,10};
Encoder myEnc(2, 3);
long oldPosition = -999;
long targetPosition = 0;
#define ACCURACY 1
#define DEBOUNCE_MS 20
#define PULLUP true
#define INVERT true
#define motorSpeed 50
#define motorSpeed1 50
Button btnPos1(BTN_MEM_PIN[0], PULLUP, INVERT, DEBOUNCE_MS);
Button btnPos2(BTN_MEM_PIN[1], PULLUP, INVERT, DEBOUNCE_MS);
Button btnPos3(BTN_MEM_PIN[2], PULLUP, INVERT, DEBOUNCE_MS);
long memPosition[] = {0,0,0};
void setup() {
pinMode(PWM0, OUTPUT);
pinMode(PWM1, OUTPUT);
analogWrite(PWM0, 0);
analogWrite(PWM1, 0);
Serial.begin(9600);
}
void loop() {
memPosition[0] = 100;
memPosition[1] = -100;
memPosition[2] = 0;
btnPos1.read();
btnPos2.read();
btnPos3.read();
if(btnPos1.wasReleased()) {
Serial.println("btnPos1");
targetPosition = memPosition[0] ;
}
if(btnPos2.wasReleased()) {
Serial.println("btnPos2");
targetPosition = memPosition[1] ;
}
if(btnPos3.wasReleased()) {
Serial.println("btnPos3");
targetPosition = memPosition[2] ;
}
long newPosition = myEnc.read();
if (newPosition != oldPosition) {
oldPosition = newPosition;
Serial.println(newPosition);
}
if( newPosition != targetPosition) {
if(targetPosition < newPosition) {
retractActuator();
}
if(targetPosition > newPosition) {
extendActuator();
}
if( (targetPosition == newPosition) || abs(targetPosition - newPosition) <= ACCURACY) {
stopActuator();
}
}
}
void retractActuator() {
analogWrite(PWM0, 0);
analogWrite(PWM1, motorSpeed1);
}
void extendActuator() {
analogWrite(PWM0, motorSpeed);
analogWrite(PWM1, 0);
}
void stopActuator() {
analogWrite(PWM0, 0);
analogWrite(PWM1, 0);
delay(15);
}