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

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

#define RTC	0x9e				// RTC IIC bus address

/*
 * The RTC config register is a non-volatile
 * EEPROM register, and must be written only
 * once.
 *
 * The factory default value is 0xc0. Set to
 * 0x05 for minimal power requirement.
 */
int
main(void)
{
	iic_init();				// initialize IIC bus interface

	while (1) {
		int c;

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

			/*
			 * Buffer for access config cmd
			 * and config.
			 */
			static unsigned char cfg[1+1] = {0xac};

			char line[30];		// input buffer
			unsigned new;		// new config

		case '2': // write config register
			fputs("New config (0.. ff, or single RETURN to abort): ", stdout);
			if (*fgets(line, sizeof(line), stdin) == '\n') {
				puts("Aborted.");
				break;
			}
			if (sscanf(line, "%x", &new) != 1 || new > 0xff) {
				puts("Invalid value");
				break;
			}
			cfg[1] = new;
			if (iic_write(RTC, cfg, sizeof(cfg))) {
				puts("Writing config register failed!");
				break;
			}
			delay(100);
		case '1': // read config register
			if (iic_write(RTC  , cfg  , 1)
			 || iic_read (RTC|1, cfg+1, 1)) {
				puts("Reading config register failed!");
				break;
			}
			printf("Config register: %02x\n", cfg[1]);
			break;
		}
	}
}
