/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... read/write the external RTC memory.
 */

#include <stdio.h>
#include "../iic.h"

#define RTC	0x9e				// RTC IIC bus address
#define SIZE	32				//     memory size

/*
 * The RTC memory is a 32 bytes non-volatile
 * (battery-buffered) SRAM array.
 *
 * Write some data then cycle power and read.
 */
int
main(void)
{
	iic_init();				// initialize IIC bus interface

	while (1) {
		int c;

		fputs("\n"
		      " (1) Read from memory\n"
		      " (2) Write to  memory\n\n"
		      "Select... ", stdout
		);
		c = getchar();				// get selection
		puts("\n");
		switch (c) {

			/*
			 * Buffer for access memory cmd, addr 0
			 * and memory data.
			 */
			static unsigned char buf[2+SIZE+1] = {0x17, 0};

			int i;

		case '2': // write to memory
			fputs("Enter data (max. 32 chars, or single RETURN to abort): ", stdout);
			if (*fgets(buf+2, sizeof(buf)-2, stdin) == '\n') {
				puts("Aborted.");
				break;
			}
			putchar('\n');
			if (iic_write(RTC, buf, SIZE+2)) {
				puts("Writing memory failed!");
				break;
			}
		case '1': // read from memory
			if (iic_write(RTC  , buf  , 2)
			 || iic_read (RTC|1, buf+2, SIZE)) {
				puts("Reading memory failed!");
				break;
			}
			puts("Memory data:\n");
			for (i = 2; i < SIZE+2; i++) {
				if (buf[i] > 0x1f && buf[i] < 0x7f) putchar(buf[i]);
				else printf("\\x%02x", buf[i]);
			}
			putchar('\n');
			break;
		}
	}
}
