📄 复件 master.c
字号:
/*
master :
main.c
芯艺 2004-09-02 ---------- 2004
*/
#include <avr/io.h>
#include <avr/delay.h>
#include <avr/twi.h>
#define uint unsigned int
#define uchar unsigned char
#define SET_RED_LED cbi(PORTB,1)
#define CLR_RED_LED sbi(PORTB,1)
#define SET_GRN_LED cbi(PORTB,2)
#define CLR_GRN_LED sbi(PORTB,2)
#define SET_YEL_LED cbi(PORTB,0)
#define CLR_YEL_LED sbi(PORTB,0)
#define LEFT_KEY 0X08
#define RIGHT_KEY 0X04
#define FREQ 4
#define TWI_ADDRESS 0X32
void DelayMs(uint ms)
{
uint i;
for(i=0;i<ms;i++)
_delay_loop_2(FREQ *250);
}
/*************主模式TWI操作部分*************开始**************/
//总线上起动停止条件
void twi_stop(void)
{
TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN);
}
//总线上起动开始条件
void twi_start(void)
{
uchar trycount=0;
TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);
while ((TWCR & _BV(TWINT)) == 0) ;
SET_GRN_LED;
return TW_STATUS;
}
//写一字节
void twi_writebyte(uchar c)
{
TWDR = c;
TWCR = _BV(TWINT) | _BV(TWEN);
while ((TWCR & _BV(TWINT)) == 0);
return TW_STATUS;
}
//读一字节 ack: true时发ACK,false时发NACK
uchar twi_readbyte(uchar *c ,uchar ack)
{
uchar tmp=_BV(TWINT)|_BV(TWEN);
if(ack)
tmp|=_BV(TWEA);
TWCR=tmp;
while ((TWCR & _BV(TWINT)) == 0) ;
*c=TWDR;
return TW_STATUS;
}
/*************主模式IIC操作部分*************结束**************/
uchar WaitKeyDown(void)
{
uchar key;
while(1)
{
key=PIND & 0x0c;
if( key!=0x0c)
{
DelayMs(30);
key=PIND & 0x0c;
if(key!=0x0c)
break;
}
DelayMs(1);
}
if(key & LEFT_KEY)
SET_YEL_LED;
else if(key & RIGHT_KEY)
SET_RED_LED;
while((PIND & 0X0C)!=0X0C)
DelayMs(10);
CLR_RED_LED;
CLR_YEL_LED;
return key;
}
int main(void)
{
uchar i,j;
DDRB=0XFF;
PORTB=0XFF;
DDRC=0;
PORTC=0X30;
DDRD=0;
PORTD=0;
TWBR=73;
SET_GRN_LED;
while(1)
{
i=WaitKeyDown();
if( i== LEFT_KEY )
{
twi_start();
DelayMs(100);
twi_writebyte(TWI_ADDRESS|TW_WRITE);
DelayMs(100);
for(j=0;j<10;j++)
{
twi_writebyte(j);
DelayMs(100);
}
twi_stop();
}
else if(i==RIGHT_KEY)
{
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -