// ts8820 pulse counter demo
// c. Technologic Systems, Inc.  2015
// Written by Michael D Peters.
// 
// Required materials:
// TS-8820
// TS-47xx
// 2 jumper wires about 10 inches long.
// 1 100k ohm leaded resistor
//
// Setup:
// Connect Relay 1's COM pin (P8 pin 2) to IN_14.
// Connect NC (P8 pin 3) to VIN using the 100K ohm resistor.
// Connect NO (P8 pin 1) to GND (any, P4 pin 12 works).
//
// This program toggles relay 1 and watches the pulse counter
// register for input 14, displaying rising edges coming from
// relay 1.
// 
// Basically, the program provides a bounce count on the relay
//  toggle.  Expect lots of bounce.  Relays are noisy.

#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdint.h>

#define RELAY_REGISTER 0x10
#define PULSE_COUNTER_14 0x3a

enum TS8820_RELAYS {
  RELAYS_OFF = 0x0000,
  RELAY4 = 0X10,
  RELAY3 = 0X40,
  RELAY2 = 0X80,
  RELAY1 = 0x100
};

int main(int argc, char* argv[])
{
  int i, fb, mem = 0;
  uint16_t *syscon = 0;
  uint16_t *baseboard = 0;

  // memory setup
  mem=open("/dev/mem", O_RDWR|O_SYNC);
  syscon = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, mem, 0x80004000);
  baseboard = mmap(0, getpagesize(), PROT_WRITE|PROT_READ, MAP_SHARED, mem, 0x80008000);
  
  // set muxbus speed to really slow (high delay).
  syscon[0x4/2] = 0xf3ff;

  // set dio direction to output for the relays.
  syscon[0x18/2] = 0x1d0;

  for(;;){ // forever loop starts here.  
    syscon[RELAY_REGISTER/2] = (uint16_t)RELAY1;
    printf("RELAY1 is ON\n");
    i = baseboard[PULSE_COUNTER_14/2];
    printf("Pulse counter 14 at %d\n", i);
    usleep(125000); // 1/8 second.
    syscon[RELAY_REGISTER/2] = (uint16_t)RELAYS_OFF;
    printf("Relays are OFF\n");
    i = baseboard[PULSE_COUNTER_14/2];
    printf("Pulse counter 14 at %d\n", i);
    usleep(125000); // 1/8 second.
  }

  return 0;
}
