Skip to content

Instantly share code, notes, and snippets.

@bert
Forked from lambert/encoder.c
Created October 18, 2021 19:10
Show Gist options
  • Save bert/2a9da3b7387f90a3e61e458923263a5e to your computer and use it in GitHub Desktop.
Save bert/2a9da3b7387f90a3e61e458923263a5e to your computer and use it in GitHub Desktop.
8051 Encoder
/*!
* \file encoder.c
*
* Date: 22/01/2019
*/
#include <stdio.h>
#include <8052.h>
/*! \brief Encoder "absolute" position. */
int ABS_POS;
/* A limit switch should be used to set a zero position. */
/*!
* \brief Init serial port at 19200.
*/
void
initSio ()
{
TMOD &= 0x0F;
TMOD |= 0x20;
TCON = 0x41;
TH1 = 0xFD;
SCON = 0x50;
}
/*!
* \brief For SDCC printf.
*/
int
putchar (int c)
{
SBUF = c;
while (!TI);
TI = 0;
return 0;
}
/*!
* \bruief Enables interrupt on P3_2 falling edge transition.
*/
void
interruptSetupEx0 ()
{
EA = 1; /* Enable all interrupts. */
EX0 = 1; /* Enable interrupt on pin P3_2. */
IT0 = 1; /* Falling edge. */
}
/*!
* \brief ISR for external interrupt INT0.
*/
void
ISR_ex0 (void) __interrupt 0
{
if (P3_3 = 1) ABS_POS++;
else ABS_POS--;
//printf("called");
/* (P3_3 = 1 ? ABS_POS++: ABS_POS--); This doesn't work and I don't know why :-). */
}
void
main ()
{
P3_2 = 1; /* Input (interrupt trigger). */
P3_3 = 1; /* Input (direction detection). */
ABS_POS = 0;
initSio ();
interruptSetupEx0 (); /* From this point interrupt is enabled. */
while(1)
{
printf ("Position %d\n\r\f", ABS_POS);
for (unsigned int a = 0; a < 60000; a++) /* Delay. */
{
for (int b = 0; b < 10; b++);
}; /* Delay line. */
}
}
/* EOF */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment