
/*
 * dials.c
 *
 *  Created on: 22 Jan 2016
 *      Author: Mike
 */
#include "stm32f1xx_hal.h"
#include "ap_math.h"
#include "font.h"
#include "SSD1306.h"

static uint16_t a1 = 90;
static uint8_t xo = 64;
static uint8_t yo = 64;
static uint8_t siz = 32;

/* percent is integer from 0 to 100 */
void
dial_draw_needle (uint16_t percent)
{
  int ang = ((percent - 50) * a1) / 50;

  int si = ap_sin (ang);
  int co = ap_cos (ang);

  /* calculate a shift for a second side of the needle */
  int xl = ap_sin (ang - 90);
  int yl = ap_cos (ang - 90);

  int si2 = siz + 2;
  int si3 = 2 * siz / 3;

  int xs,ys;
  // three parallel lines
  xs = -xl;
  ys = -yl;
  int step;
  for(step =0; step < 3; step++)
    {
    drawLine (AP_SCALE(si*si2-xs) + xo, yo - AP_SCALE(co * si2 - ys),

  AP_SCALE(si*si3-xs) + xo,
	    yo - AP_SCALE(co * si3 - ys), INVERT);
    xs+=xl;
    ys+=yl;
    }
 }

/* initialise */
void
dial_size (uint8_t size)
{
  siz = size;
}

void
dial_draw_scale (uint8_t low, uint8_t high, uint8_t width, uint8_t num_step)
{
  int sz;
  int ang;
  int step = 256 * a1 * 2 / (4 * (high - low));
  int t;
  ang = -a1 * 256;
  for (t = low * 4; t <= high * 4; t++)
    {
      int si = ap_sin (ang / 256);
      int co = ap_cos (ang / 256);

      int len;
      switch (t % 4)
	{
	case 0:
	  len = width;
	  break;
	case 1:
	case 3:
	  len = width / 4;
	  break;
	case 2:
	  len = width / 2;
	  break;
	}

      drawLine (AP_SCALE((siz)*si) + xo, yo - AP_SCALE((siz) * co),
      AP_SCALE((siz-len)*si) + xo,
		yo - AP_SCALE((siz - len) * co), 1);
      ang += step;
    }

  font_gotoxy (0, 7);
  int d = low / 10;
  if (d)
    {
      font_putchar (d + '0');
    }
  else
    {
      font_putchar (' ');
    }
  d = low % 10;
  font_putchar (d + '0');

  font_gotoxy (19, 7);
  d = high / 10;
  if (d)
    {
      font_putchar (d + '0');
    }
  else
    {
      font_putchar (' ');
    }
  d = high % 10;
  font_putchar (d + '0');

}

void
dial_origin (uint8_t x, uint8_t y)
{
  xo = x;
  yo = y;
}
