#define cs 2 //CS1180片选,低电平有效
#define sdi 3 //CS1180数据输入
#define sdo 4 //CS1180数据输出
#define sclk 5 //CS1180时钟
#define drdy 6 //CS1180数据准备就绪,低电平有效
//写一个字节
void WriteSPI_CS1180(unsigned char DData)
{
unsigned char i;
//sclk=HIGH;
digitalWrite(sclk,HIGH);
for(i=8;i>0;i--)
{
//sdi=(bit)(DData & 0x80);
digitalWrite(sdi,highByte(DData & 0x80));
DData<<=1;
//sclk=LOW;
digitalWrite(sclk,LOW);
//Delay5us();
delayMicroseconds(5);
//sclk=HIGH;
digitalWrite(sclk,HIGH);
//Delay5us();
delayMicroseconds(5);
}
}
//读一个字节
unsigned char ReadSPI_CS1180(void)
{
unsigned char tempdata=0;
unsigned char i=0;
//sclk=HIGH;
digitalWrite(sclk,HIGH);
for(i=8;i>0;i--)
{
tempdata<<=1;
//sclk=LOW;
digitalWrite(sclk,LOW);
//Delay5us();
delayMicroseconds(5);
tempdata |=digitalRead(sdo);
//sclk=HIGH;
digitalWrite(sclk,HIGH);
//Delay5us();
delayMicroseconds(5);
}
return tempdata;
}
//初始化CS1180
void init_CS1180()
{
//cs=0;
digitalWrite(cs,LOW);
WriteSPI_CS1180(0xfe); //发送芯片复位指令
//Delay5ms();
delay(5);
WriteSPI_CS1180(0x50); //写寄存器首地址
WriteSPI_CS1180(0x02); //写入寄存器的数量为2+1=3
//WriteSPI_CS1180(0x52);
WriteSPI_CS1180(0x06); //增益64
WriteSPI_CS1180(0x01); //正常使用,配置01
WriteSPI_CS1180(0x24); //双极性
//Delay5ms();
delay(5);
//while(drdy);
//while(drdy);
while(digitalRead(drdy)==HIGH);
while(digitalRead(drdy)==HIGH);
ReadSPI_CS1180(); //空读一次,做抛弃处理,因为第一次读数不正确
//Delay5ms();
delay(5);
}
//读AD值
void GetAD_CS1180()
{
unsigned char ad[3];
//while(drdy);
while(digitalRead(drdy)==HIGH);
WriteSPI_CS1180(0x01);
//Delay5us();
delayMicroseconds(5);
ad[0]=ReadSPI_CS1180();
ad[1]=ReadSPI_CS1180();
ad[2]=ReadSPI_CS1180();
//ad[3]=PINSWITCH;
/*
sendChar(0x0C);
sendChar(0x55);
sendChar(ad[0]); //High byte
sendChar(ad[1]); //Middle byte
sendChar(ad[2]); //Low byte
sendChar(ad[3]); //Low byte
sendChar((0x0C+0x55+ad[0]+ad[1]+ad[2]+ad[3]) & 0xff);
*/
Serial.println((ad[0]<<16)+(ad[1]<<8)+ad[2]);
// Serial.println(ad[1]);
//Serial.println(ad[2]);
}
void setup()
{
pinMode(cs,OUTPUT);
pinMode(drdy,INPUT);
pinMode(sclk,OUTPUT);
pinMode(sdi,OUTPUT);
pinMode(sdo,INPUT);
init_CS1180();
Serial.begin(9600);
}
void loop()
{
GetAD_CS1180();
}
本文出自 “拖泥蟹” 博客,请务必保留此出处http://novelcrab.blog.51cto.com/10186204/1641493
原文地址:http://novelcrab.blog.51cto.com/10186204/1641493