// ts8820relays.c
// c. Technologic Systems, Inc.  2014
// Written by Michael D Peters.
// Cycles each relay on the TS-8820-4700 once per quarter second in an infinite loop.
// Assumes ts-8820-4700.  Toggles relays.

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

int main(int argc, char* argv[])
{

  int i, fb, mem = 0;
  uint16_t *syscon = 0;
  
  static int rotation[4] = {0x100, 0x80, 0x40, 0x10};

  mem=open("/dev/mem", O_RDWR|O_SYNC);
  
  syscon = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, mem, 0x80004000);
  
  // Setup muxbus and turn on baseboard clock.  No harm if it's already done, just a wasted cpu cycle.
  syscon[0x4/2] = 0xF3FF; // TS-8820 needs as much delay as possible in muxbus configuration.
  i = syscon[0x34/2];
  syscon[0x34/2] = i | 0x1; // Bit 1 of 0x34 turns on baseboard clock.  We don't want to disturb the other bits in that register.
  
  syscon[0x18/2] = 0x1d0;

  for(;;){
    for(i = 0; i < 4; i++){
      syscon[0x10/2] = rotation[i];
      usleep(250000); // quarter second.
      }
    }
  return 0;
}
