/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... use the ZigBee module as transmitter.
 *
 * Note: This program is derived from a ZigBee demo
 * program from "mikroElektronika" (www.mikroe.com).
 */

#include <stdio.h>
#include "zb1.h"

#define PID	 1				// choose PAN ID
#define ADR	 1				//        address
#define CHN	12				//        channel

#define DPID	1				//    dst PAN ID
#define DADR	2				//        address

/*
 * SPIMS (SPI Made Simple) chip selects
 */
#define CS0	0x10000				// P0.16
#define CS1	0x20000				// P0.17
#define CS2	0x40000				// P0.18
#define CS3	0x80000				// P0.19

#define HLEN	11				// header length

/*
 * The SPI is setup as master (CPOL =0, CPHA =0).
 */
static void
spi_init(void)
{
	Intern_pinsel0 |= 0x5500;		// enable SPI pins
	Intern_spcr     = 0x20;			// MSTR
	Intern_spccr    = 8;			// SCK =pclk/8
}

int
main(void)
{
	int i;

	/*
	 * De-select all SPImS devices.
	 */
	Intern_ioset  = CS0|CS1|CS2|CS3;
	Intern_iodir |= CS0|CS1|CS2|CS3;

	spi_init();				// initialize SPI
	zb_init(PID, ADR, CHN);			//            ZB module

	zb_wl( 0, HLEN);
	zb_wl( 1, HLEN+1);			// header + data length
	zb_wl( 2, 0x01);			// control frame
	zb_wl( 3, 0x88);
	zb_wl( 5, DPID);			// dst PAN ID
	zb_wl( 6, DPID>>8);
	zb_wl( 7, DADR);			//     address
	zb_wl( 8, DADR>>8);
	zb_wl( 9, PID);				// PAN ID
	zb_wl(10, PID>>8);
	zb_wl(11, ADR);				// address
	zb_wl(12, ADR>>8);

	printf("\n"
	       "ZB1 ZigBee transmitter\n"
	       "======================\n\n"
	       "  PAN ID : %d\n"
	       " Address : %d\n"
	       " Channel : %d\n\n", PID, ADR, CHN
	);

	for (i = 0;; i++) {
		zb_wl(HLEN+2, i);		// data to send
		zb_ws(ZB_TXNCON, 1);		// send...

		printf("Sent to (PAN ID/address) %d/%d: %d\n", DPID, DADR, (unsigned char)i);

		delay(3000);
	}
}

