/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... use the SPI.
 */

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

/*
 * The SPI is setup as master.
 *
 * The SPI rate is cclk/2/(1+SPIDIV). SPIDIV must be >2. For
 * your application modify settings likep hase, polarity etc.
 * accordingly!
 */
static void
spi_init(void)
{
	Intern_gp1con |= 0x2220000;		// enable SPI pins
	Intern_spicon  = 0x43;			// set master mode
	Intern_spidiv  = 3;			// SCK =cclk/2/(x+1)
}

/*
 * SPI transfer
 *
 * Return received data.
 */
static int
spi_xfer(int c)
{
	Intern_spitx = c;			// start transfer
	while (!(Intern_spista&8)) ;		// wait for complete
	return Intern_spirx;
}

/*
 * Test the SPI in loopback mode, i.e.
 *
 *  MISO (=P1.5) connected to
 *  MOSI (=P1.6).
 *  (or set Bit11 in SPICON)
 *
 * Note: Applications with "real" SPI devices
 * need to select exactly ONE device prior to
 * starting transfers.
 */
int
main(void)
{
	/*
	 * Here:
	 * De-select all SPI devices!
	 */

	spi_init();				// initialize SPI
	while (1) {
		int sc, rc;			// send/receive char

		puts("Hit any key...");
		sc = getchar();

		/*
		 * Here:
		 * De-select all SPI devices!
		 * Select desired SPI device!
		 */

		printf("\nTransferring 0x%02x... ", sc);
		printf("received 0x%02x\n", rc = spi_xfer(sc));
		if (rc != sc) puts("Loopback FAILED!\7");
	}
}
