/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... read the serial Flash ID.
 */

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

/*
 * Pins
 */
#define PIN_CSFLASH	0x800000		// P1.7
#define PIN_MS3		0x800000		// P2.7
#define PIN_PORT	0xff0000		// P3

/*
 * Initialize hardware.
 */
static void
init(void)
{
	/*
	 * Define I/Os, set all outputs hi.
	 */
	Intern_gp1dat |= PIN_CSFLASH<<8|PIN_CSFLASH;
	Intern_gp2dat |= PIN_MS3    <<8|PIN_MS3;
	Intern_gp3dat  = PIN_PORT   <<8|PIN_PORT;

	/*
	 * De-select SPImS
	 */
	Intern_gp2clr = PIN_MS3;
	Intern_gp2set = PIN_MS3;

	Intern_spicon  = 0x43;			// set master mode
	Intern_spidiv  = 3;			// SCK =cclk/2/4
	Intern_gp1con |= 0x2220000;		// enable SPI pins
}

/*
 * 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;
}

/*
 * Read and print the manufacturer/device codes.
 */
int
main(void)
{
	init();

	while (1) {
		puts("\nHit RETURN to read device ID..."), getchar();

		Intern_gp1clr = PIN_CSFLASH;	// CS lo
		spi_xfer(0x9f);			// RDID cmd

		printf("Manufacturer code   : %02x\n", spi_xfer(0));
		printf("      Device code 1 : %02x\n", spi_xfer(0));
		printf("      Device code 2 : %02x\n", spi_xfer(0));

		Intern_gp1set = PIN_CSFLASH;	// CS hi
	}
}

