现在在尝试做一个四线电阻屏的控制器,计划用tiny44+ADS7843。
用m16的硬件SPI能成功与ADS7843通信,但由于tiny44的硬件SPI只有3或2线模式,ADS7843要用4线模式,所以想用IO口模拟SPI。然后就尝试用m16模拟SPI,但试了很久也不明白为什么自己写的程序不能与ADS7843通信,请求各位大侠帮助
*******M16硬件SPI成功的程序*******
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h> /* for _delay_ms() */
/*------宏定义------*/
#define uchar unsigned char
#define uint unsigned int
#define NOP() asm("nop")
#define KOU PORTB
#define SB(bitn) (KOU |=(1<<(bitn)))
#define CB(bitn) (KOU&=~(1<<(bitn)))
#define GB(bitn) (KOU &(1<<(bitn)) )
#define SCK 7//DCLK
#define SS 4//CS
#define MOSI 5//DIN
#define BUSY 0//
#define MISO 6//DOUT
#define IQR 1//
unsigned char duanma[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x76,0x6e};
//unsigned char test1,test2,test3;
/*------函数定义------*/
void Display(unsigned int TX,unsigned int TY)
{
unsigned char i;
unsigned char num[9];
DDRA=0xff;
DDRC=0xff;
num[1]=TX/1000;
num[2]=(TX%1000)/100;
num[3]=(TX%100)/10;
num[4]=TX%10;
num[5]=TY/1000;
num[6]=(TY%1000)/100;
num[7]=(TY%100)/10;
num[8]=TY%10;
for(i=0;i<8;i++)
{
PORTA=0;
PORTC=i;
PORTA=duanma[num[i+1]];
_delay_ms(1);
}
}
//------------------------------------------------------------------------
void SPI_MasterInit(void)
{
DDRB=0b10110000;//SCK、MOSI、SS置输出,MISO置输入
SB(MISO);//MISO、SS使用上拉电阻
SB(SS);
//SPIE SPE DORD MSTR CPOL CPHA SPR1 SPR0
/* Enable SPI, Master, set clock rate fck/128 */
SPCR=0b01010011;
}
void SPI_MasterSent(uchar cData)
{
SPDR = cData;
while(!(SPSR & (1<<SPIF)));
//test1=SPSR & (1<<SPIF);
}
uint SPI_MasterRead(void)//功能:使用SPI接收AD转换的值
{
uint temp=0,thig=0,tlow=0;
SPDR = 0x00;
while(!(SPSR & (1<<SPIF)));
//test2=SPSR & (1<<SPIF);
thig=SPDR;//对SPDR操作后,SPI中断位变0。AD转换值的高8位存在thig的低8位
SPDR = 0x00;
while(!(SPSR & (1<<SPIF)));
//test3=SPSR & (1<<SPIF);
tlow=SPDR;//AD转换值的低4位存在tlow的5-8位
tlow=tlow&0x00f0;//将没用位清0
thig=thig&0x00ff;
temp = (thig<<4)+(tlow>>4);
return temp;
}
void SPI_Start(void)
{
CB(SS);NOP();NOP();
//_delay_us(100);
}
void SPI_Stop(void)
{
SB(SS);
}
//----------------------------------------------------------
//主函数
int main(void)
{
uint X=0,Y=0,zux[7],zuy[7];
SPI_MasterInit();
while(1)
{
if(!(PINB &(1<<(1))))//有点击时
{
SPI_Start();
SPI_MasterSent(0X90);
X=SPI_MasterRead();
SPI_Stop();
SPI_Start();
SPI_MasterSent(0XD0);
Y=SPI_MasterRead();
SPI_Stop();
}
Display(X,Y);
}
} |