Используй для энкодера нижеприведенный код
PHP код:
//http://compcar.ru
#define PIN 5 //номер аналогового порта
#define LIMIT 10 //предел погрешности сопротивления
#define encoder0PinA 2
#define encoder0PinB 3
byte bytes[4];
unsigned long math_time,old_time,real_time, res_dt1, res_d;
void setup()
{
pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH); // подключить подтягивающий резистор
pinMode(encoder0PinB, INPUT);
digitalWrite(encoder0PinB, HIGH); // подключить подтягивающий резистор
attachInterrupt(0, doEncoderA, FALLING); // настроить прерывание interrupt 0 на pin 2
attachInterrupt(1, doEncoderB, FALLING); // настроить прерывание interrupt 0 на pin 3
Serial.begin (115200);
}
void loop()
{
res_d = analogRead(PIN); // прочитать данные АЦП
if( res_d < LIMIT) res_d = LIMIT;
delay(10);
res_dt1 = analogRead(PIN); // прочитать данные АЦП
old_time = millis();
math_time = 0;
while(math_time < 200)
{
real_time = millis(); //получить реальное время
math_time = real_time - old_time; //считаем длительность нажатия
res_dt1 = analogRead(PIN); // прочитать данные АЦП
if(res_dt1 < res_d-LIMIT || res_dt1 > res_d+LIMIT)break;
}
if( math_time > 70) //если нет дребезга то короткое нажатие
{
bytes[0] = res_d & 0xFF; // преобразовать в 4-байта
bytes[1] = (res_d & 0xFF00) >> 8;
bytes[2] = (res_d & 0xFF0000) >> 16;
bytes[3] = (res_d & 0xFF000000) >> 24;
Serial.write( bytes,4); // отправить прочитаное значение компьютеру
}
}
void doEncoderA() // обработка прерывания
{
for(byte i=0; i<4; i++) bytes[i]=0;
if(digitalRead(encoder0PinB)==HIGH) bytes[1]=24; else bytes[1]=15;
Serial.write(bytes, 4);
}
void doEncoderB() // обработка прерывания
{
for(byte i=0; i<4; i++) bytes[i]=0;
if(digitalRead(encoder0PinA)==HIGH) bytes[1]=15; else bytes[1]=24;
Serial.write(bytes, 4);
}