#include "stm32f4_discovery.h"
#include "stm32f4xx_conf.h" // again, added because ST didn't put it here ?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include "usart.h"
#include "delay.h"
#include "lcd.h"
#include "i2c.h"


//I2C connected MLX90614

/*
void MLX_i2c_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;

  //Enable the GPIOs for the SCL/SDA Pins
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIO_SCL | RCC_AHB1Periph_GPIO_SDA, ENABLE);
  
  //Configure and initialize the GPIOs
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_SCL;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; 
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIO_SCL, &GPIO_InitStructure);
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_SDA;
  GPIO_Init(GPIO_SDA, &GPIO_InitStructure);

GPIO_WriteBit(GPIO_SCL,GPIO_Pin_SCL,Bit_RESET);
delay_ms(5);
GPIO_WriteBit(GPIO_SCL,GPIO_Pin_SCL,Bit_SET);
delay_ms(1);
}
*/

void MLX_setup(void)
{
//factory default seems OK
}


#define EMISIVITY 0x24
void store_emisivity(float e)
{
uint16_t ee = 65535.*e;
SMBUS_write_word(0,EMISIVITY,ee);
}

float read_emisivity(void)
{
uint16_t emis=SMBUS_read_word(0,EMISIVITY);
float                e = emis;
                e /= 65535.;
return e;
}



int main(void)
{

/* enable FPU */
    SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2));

usart2_init(115200);
lcd_init();

print(USART2, "pyrometer reset\n"); 
//MLX_i2c_init(); print(USART2, "pyrometer switched to i2c\n");
I2C_LowLevel_Init();
print(USART2, "i2c initialized\n");

MLX_setup();
print(USART2, "pyrometer initialized\n");

#if 0
while(1)
{
float emisivity = read_emisivity();
printf("E = %f\n",emisivity);
if(1!=scanf("%f",&emisivity)) break;
store_emisivity(emisivity);
}
#endif

while (1)
  {
  uint16_t ta,t1; 
  float tasum=0;
  float t1sum=0;
  uint8_t i;
  for(i=0; i<10; ++i)
  {
  ta= SMBUS_read_word(0,6);
  t1= SMBUS_read_word(0,7);
  if(ta&0x8000 || t1&0x8000) print(USART2, "temperature error\n");
  else
	{
	tasum += .02 * ta;
	t1sum += .02 * t1;
	}
  }
  float taf=tasum/10. -273.15;
  float t1f=t1sum/10. -273.15;
	char c[128];
	sprintf(c,"A=%6.2f\nO=%6.2f\n", taf, t1f); 
	fputs(c,stdout); 
	lcd_cursor(0,0);lcd_print(c);
  delay_ms(300);  
  }
}

