|
发表于 2012-5-3 09:46:01
|
显示全部楼层
#include<16F917.h>
#device ADC=10
#include<math.h>
#define MCP3421_SDA PIN_C7
#define MCP3421_SCL PIN_C6
#define CS PIN_C0
#define CLK PIN_C1
#define DIN PIN_C2
#define addo (2.048/32767.0)
#fuses INTRC_IO , NOWDT , PROTECT , NOPUT
#use delay(clock=1000000,restart_wdt)
#use i2c(master , sda=MCP3421_SDA , scl=MCP3421_SCL)
int8 LedNum[] = {1,2,3,4,5,6,7,8};
int32 MCP3421_READ()
{
int read_value_a,read_value_b,read_value_c,read_value_d,read_value_e,ERROR;
int32 value_adc=0x00;
output_float(MCP3421_SCL);
output_float(MCP3421_SDA);
i2c_start();
if (i2c_write(0B11010000)==0)
if (i2c_write(0B10001000)==0)
i2c_stop();
delay_ms(10);
read_value_a=0;
read_value_b=0;
read_value_c=0;
read_value_d=0;
read_value_e=0;
i2c_start();
if (i2c_write(0B11010001)==0)
{
read_value_a=i2c_read(1);
value_adc=value_adc+read_value_a;
value_adc=value_adc<<8;
read_value_b=i2c_read(1);
value_adc=value_adc+read_value_b;
read_value_c=i2c_read(1);
read_value_d=i2c_read(1);
read_value_e=i2c_read(0);
i2c_stop();
read_value_a=ERROR;
}
return(value_adc);
}
void Port_Initial(void)
{
set_tris_c(0xF0);
}
void WriteByte(int8 dat)
{
int8 i;
for(i=0;i<8;i++)
{
if(((dat<<i)&0x80))
{
output_high(DIN);
}
else
{
output_low(DIN);
}
output_low(CLK);
#asm
nop
#endasm
output_high(CLK);
#asm
nop
#endasm
}
}
void MAX7221_WRITE(int8 addr,int8 dat)
{
output_low(CS);
WriteByte(addr);
WriteByte(dat);
output_high(CS);
}
void MAX7221_Initial(void)
{
MAX7221_WRITE(0x0A,0x07);
MAX7221_WRITE(0x0B,0x07);
MAX7221_WRITE(0x0C,0x01);
MAX7221_WRITE(0x0D,0x00);
MAX7221_WRITE(0x09,0xFF);
}
void Display(int8 *str)
{
int8 i;
for(i=0;i<8;i++)
{
MAX7221_WRITE(i+1,str[i]);
}
}
void HEXTOBCD(void)
{
int32 temp;
temp = (int32)(MCP3421_READ()*addo*1000);
if(temp<=1864)
{
Temp = (int32)(sqrt(((1.8639-(MCP3421_READ()*addo))/3.88)+2.1962)*1000-1481.96);
LedNum[0] = temp/1000;
LedNum[1] = temp%1000/100;
LedNum[2] = temp%100/10;
LedNum[3] = (temp%10)|0x80;
LedNum[4] = 0;
LedNum[5] = 15;
LedNum[6] = 15;
LedNum[7] = 15;
}
else
{
temp = (int32)(-sqrt(2.1962-(((MCP3421_READ()*addo)-1.8639)/3.88))*1000+1481.96);
LedNum[0] = 10;
LedNum[1] = temp/1000;
LedNum[2] = temp%1000/100;
LedNum[3] = temp%100/10;
LedNum[4] = (temp%10)|0x80;
LedNum[5] = 0;
LedNum[6] = 15;
LedNum[7] = 15;
}
/*
LedNum[0] = (temp/1000)|0x80;
LedNum[1] = temp%1000/100;
LedNum[2] = temp%100/10;
LedNum[3] = temp%10;
LedNum[4] = 15;
LedNum[5] = 15;
LedNum[6] = 15;
LedNum[7] = 15;
*/
}
void main()
{
Port_Initial();
delay_us(10);
MAX7221_Initial();
delay_us(10);
while(1)
{
HEXTOBCD();
delay_ms(20);
Display(LedNum);
delay_ms(20);
}
}
|
|