-2

I am trying to get readings from 3 rotary encoders (KY-040) and send values via UART.

I am using Arduino-Mega 2560 board but due to requirements reason I am programming it in C.

But when I try to get the reading from encoder I get random numbers.

And it only works with every even number of rotation and program gets stuck at odd rotation. (it seems little odd)

Can anybody please suggest what is wrong with my code.

P.S. I am new working with micro controller.

#define F_CPU 16000000  //Clock Speed
#define UART_BAUD 9600

#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include "uart.h"
#include <stdlib.h>

volatile unsigned int encPosZ=0;

void sendEncValue(unsigned int value){
    char string[5];
    itoa(value, string, 10);
    uart_puts(string);      
}  

// main
int main(void)
{
    //disable all interrupts
    cli();      
    uart_init(UART_BAUD_SELECT(UART_BAUD,F_CPU));                   
    DDRE &=~ (1 << PE4);
    DDRE &=~ (1 << PE5);

    /* set pull-up enabled   */     
    PORTE |= (1 << PE4)|(1 << PE5);

    EIMSK |= (1 << INT4)|(1 << INT5);       

    /* INT4 - falling edge, INT5 - rising edge */       
    EICRB|= (1<<ISC41)|(1<<ISC51)|(1<<ISC50);

    // Enable the Global Interrupt Enable flag
    sei();          
    uart_puts("Started... "); 

    while(1)
    {
        _delay_ms(5);           
    }
    return 0;
}       

//INT4 interrupt
ISR(INT4_vect)
{
    if(!bit_is_clear(PINE, PE5)){
        encPosZ++;
    }else{
        encPosZ--;
    }
   sendEncValue(encPosZ);       
}

//INT5 interrupt
ISR(INT5_vect)
{
    if(bit_is_clear(PINE, PE4)){
        encPosZ++;
    }else{
        encPosZ--;
    }
    sendEncValue(encPosZ);  
}
sha09
  • 3
  • 3

1 Answers1

1

MCUCR is not used for the purpose you are using it. In fact, most of its bits are read-only.

Perhaps you meant to use EICRA and EICRB. These are the registers to set rising and falling edges.

UncleO
  • 8,299
  • 21
  • 29
  • Thank @UncleO for pointing it out. I was scratching the head the whole time. Now I am getting the values only incremented or only decremented together with lot of bouncing. Can you please suggest some feasible solution. – sha09 Sep 11 '16 at 14:27
  • You should modify your question or start a new one with the latest code and issues. – UncleO Sep 11 '16 at 18:21
  • @Uncle0 I did! Any suggestion about debouncing! – sha09 Sep 11 '16 at 20:18
  • the net is full of good debouncing routines ... I would choose one based on interrupts and not delays ... http://www.labbookpages.co.uk/electronics/debounce.html ... http://www.avrfreaks.net/projects/efficient-key-debounce?module=Freaks%20Academy&func=viewItem&item_id=1801&item_type=project – MikeD Sep 15 '16 at 12:41