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

#define CSFLASH		0x800000		// FLASH chip select (=P0.23)

/*
 * The SPI is setup as master at max. speed, CPOL =CPHA =0.
 *
 * Note: A pullup is needed for slave select (=P0.7), when
 * in master mode!
 */
static void
spi_init(void)
{
	Intern_pinsel0 |= 0x5500;		// enable SPI pins
	Intern_spcr     = 0x20;			// set master mode
	Intern_spccr    = 8;			// SCK =pclk/8
}

/*
 * SPI transfer (no error check!)
 *
 * Return received data.
 */
static int
spi_xfer(int c)
{
	Intern_spdr = c;			// start transfer

	/*
	 * Wait for transfer complete or error
	 * (mask the reserved bits 0, 1 and 2).
	 */
	while (!(Intern_spsr&0xf8)) ;

	return Intern_spdr;
}

/*
 * Read and print the manufacturer/device codes.
 */
int
main(void)
{
	Intern_ioset  = CSFLASH;		// CS hi
	Intern_iodir |= CSFLASH;		// CS is output
	spi_init();

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

		Intern_ioclr = CSFLASH;		// CS lo
		spi_xfer(0x9f);			// RDID cmd

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

		Intern_ioset = CSFLASH;		// CS hi
	}
}
