[mw_shl_code=c,true]#include<reg52.h> //包含头文件,一般情况不需要改动,头文件包含特殊功能寄存器的定义
#include<intrins.h>
#include<math.h>
#include<stdio.h>
#include<absacc.h>
#include<ctype.h>
#include<stdlib.h>
#define MEAS 0x00 //测量模式
#define RWTR 0x08 //读写温度数据寄存器
#define STX 0x0E //x通道自检
#define STY 0x0F //Y通道自检
#define RDAX 0x10 //读X通道加速度值
#define RDAY 0x11 //读Y通道加速度值
sbit SCK=P1^7; //定义端口
sbit MISO=P1^6;
sbit MOSI=P1^5;
sbit CSB=P1^4;
unsigned int SPI_ReadBits(unsigned char n );
void SPI_WriteByte( unsigned char wdata );
void SPI_Start(void);
void SPI_Stop(void);
void SPI_Reset(void);
void SPI_Delay(unsigned char);
unsigned int SPI_GetX( void );
unsigned int SPI_GetY( void );
void SPI_Init( void );
sbit P0_0 = P0^0;
sbit P0_1 = P0^1;
sbit P0_2 = P0^2;
sbit P0_3 = P0^3;
sbit P0_4 = P0^4;
sbit P0_5 = P0^5;
sbit P0_6 = P0^6;
sbit P0_7 = P0^7;
sbit P1_0 = P1^0;
sbit P1_1 = P1^1;
sbit P1_2 = P1^2;
sbit P1_3 = P1^3;
sbit P1_4 = P1^4;
sbit P1_5 = P1^5;
sbit P1_6 = P1^6;
sbit P1_7 = P1^7;
sbit P2_0 = P2^0;
sbit P2_1 = P2^1;
sbit P2_2 = P2^2;
sbit P2_3 = P2^3;
sbit P2_4 = P2^4;
sbit P2_5 = P2^5;
sbit P2_6 = P2^6;
sbit P2_7 = P2^7;
sbit P3_0 = P3^0;
sbit P3_1 = P3^1;
sbit P3_2 = P3^2;
sbit P3_3 = P3^3;
sbit P3_4 = P3^4;
sbit P3_5 = P3^5;
sbit P3_6 = P3^6;
sbit P3_7 = P3^7;
void SPI_Stop( void )
{
SCK = 0;
CSB = 1;
SPI_Delay(10);
}
void SPI_Reset(void)
{
SPI_Stop();
}
void SPI_Delay(unsigned char n)
{
while(n--);
}
void SPI_Start(void)
{
SCK = 0;
CSB = 0;
SPI_Delay(10);
}
//主机写一个BYTE到器件
//最终状态:CLK = LOW
void SPI_WriteByte( unsigned char wdata )
{
unsigned char i;
for( i = 0 ; i < 8 ; ++i )
{
SCK = 0;
SPI_Delay(10);
MOSI = wdata & 0x80;
wdata = wdata << 1;
SPI_Delay(10);
SCK = 1;
SPI_Delay(10);
}
SCK = 0;
}
//主机读入N个比特
//n 限制为16及其以下
//结束状态 CLK = 0
unsigned int SPI_ReadBits( unsigned char n )
{
unsigned int rtemp,i;
MISO = 1;
for( i = 0 ; i < n ; ++i )
{
rtemp <<= 1 ;
SPI_Delay(10);
if( MISO == 1 ){
rtemp |= 0x0001;
}else{
rtemp &= 0xFFFE;
}
SCK = 1;
SPI_Delay(10);
SCK = 0;
SPI_Delay(10);
}
return rtemp;
}
unsigned int SPI_GetX( void )
{
unsigned int result;
SPI_Start();
SPI_WriteByte( RDAX );
result = SPI_ReadBits(11);
SPI_Stop();
return result;
}
unsigned int SPI_GetY( void )
{
unsigned int result;
SPI_Start();
SPI_WriteByte( RDAY );
result = SPI_ReadBits(11);
SPI_Stop();
return result;
}
void SPI_Init( void )
{
SPI_Start();
SPI_WriteByte( MEAS );
SPI_Stop();
}
main()
{
unsigned int result;
SPI_Reset();
SPI_Delay(1000);
SPI_Init();
SPI_Delay(1000);
while(1){
result = SPI_GetX();
}
}
[/mw_shl_code]
|