// rp-mcp3008-v2.c		basic program listing analogue values

// 26-May-2018 JST Lawrence V1.0 Initial program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wiringPi.h>
#include <signal.h>

#include <mcp3004.h>
#include <wiringPiSPI.h>

#define BASE 100
#define SPI_CHAN 0

// Foreground colours
	char *BlackFG="\033[0;30m";
	char *RedFG="\033[0;31m";
	char *GreenFG="\033[0;32m";
	char *YellowFG="\033[0;33m";
	char *BlueFG="\033[0;34m";
	char *MagentaFG="\033[0;35m";
	char *CyanFG="\033[0;36m";
	char *WhiteFG="\033[0;37m";
// Background colours
	char *BlackBG="\033[0;40m";
	char *RedBG="\033[0;41m";
	char *GreenBG="\033[0;42m";
	char *YellowBG="\033[0;43m";
	char *BlueBG="\033[0;44m";
	char *MagentaBG="\033[0;45m";
	char *CyanBG="\033[0;46m";
	char *WhiteBG="\033[0;47m";
// Reset to default
	char *Default="\033[0m";
// Move cursor
	char *UpLines="\033[%dA";   // Usage: printf(UpLines,number_of_lines);
	char *DownLines="\033[%dB"; // Usage: printf(DownLines,number_of_lines);
	char *HideCursor="\033[?25l";
	char *ShowCursor="\033[?25h";

	int i;

// Function to trap <CTRL>C
void CatchCTRLC()
{
	printf("%s",ShowCursor);
	printf(DownLines,8);

// Entirely optional - insert code here to tidy up before exiting...

	exit(0);
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min + 1) / (in_max - in_min + 1) + out_min;
}

int main (int argc, char *argv[])
{
	int j,result;
	unsigned char data[3]={1};
	
// Initialisers need to be cast to the correct type!
//	double Correction[8]={(double)1023/(double)800,1,1,1,1,1,1,1};
	double Correction[8]={1,1,1,1,1,1,1,1};
	
// Set up to catch <CTRL>C - should be using sigaction really!
	signal(SIGINT,CatchCTRLC);
	
	printf(HideCursor);
	printf("wiringPiSPISetup RC=%d\n",wiringPiSPISetup(0,500000));
//	wiringPiSetupGpio();
	mcp3004Setup(BASE,SPI_CHAN);

// Do until CTRL-C
	while(1)
	{	for(i=0;i<8;i++)
		{	
// Read analogue value
			result=analogRead(BASE+i)*Correction[i];
// Print out rubric
			printf("Channel %d: value=%4d ",i,result);
// Map 0-1023 to 0-20
			result=map(result,0,1023,0,20);
			printf("%s",GreenFG);
			for(j=1;j<=result;j++)
			{	
				if(j>15)printf("%s",YellowFG);
				if(j>18)printf("%s",RedFG);
				printf("X");
			}
// Overwite a previously longer line
			for(j=result+1;j<=20;j++)printf(" ");
			printf("%s\n",WhiteFG);
		}
// Move cursor back to top of output
		printf(UpLines,8);
// Sleep for 100ms
		usleep(100000);
	}
}
































