/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... decode signals from a quadrature encoder.
 */

#include <stdio.h>
#include <target.h>

#define POS	((short)INTERN.tpu.c[2].p[1])	/* QDEC pos count */

/*
 * The Quadrature Decoder (QDEC) is a position
 * counter, which counts up or down, depending
 * on two signals, usually called A and B from
 * an encoder used in motor control.
 *
 * TP2/3 are used as primary/secondary channel
 * for the QDEC function.
 *
 * Connect A, B from the encoder to TP2, TP3.
 */
int
main(void)
{
	int last = 0x8000;			/* last pos */

	INTERN.tpu.tmcr	     = 0;		/* enable TPU */
	INTERN.tpu.c[2].p[4] = 0x36;		/* TP2/3 corresponding */
	INTERN.tpu.c[2].p[5] = 0x21;		/*        channel */
	INTERN.tpu.c[3].p[4] = 0x26;		/*        parameter */
	INTERN.tpu.c[3].p[5] = 0x21;		/*        addresses */
	INTERN.tpu.cfsr3 |= 0x6600;		/*       QDEC function (CFS =  6) */
	INTERN.tpu.hsqr1 |= 0x40;		/*       primary ch    (HSQ =%01) */
	INTERN.tpu.hsrr1 |= 0xf0;		/*       initialize    (HSR =%11) */
	INTERN.tpu.cpr1	 |= 0xf0;		/*       high priority (CPR =%11) */

	POS = 0;				/* start with pos zero */

	/*
	 * Read the position and display changes.
	 */
	while (1) if (POS != last) printf("Pos: %d\n", last = POS);
}
