用51单片机编写个小程序

2024-12-26 06:33:03
推荐回答(3个)
回答1:

#include
#include "delay.h"
#include "lcd1602.h"

sbit SCK = P2^0;//sbit定义单片机的特殊功能寄存器变量
sbit SDA = P2^1;
bit ack = 0;//bit定义变量

void iic_start()
{
SDA = 1;
SCK = 1;
delay_us(1);
SDA = 0;
delay_us(1);

SCK = 0;//钳住总线,等待下次使用
}

void icc_stop()
{
SDA = 0;
SCK = 1;
delay_us(1);
SDA = 1;
delay_us(1);

SCK = 0;//钳住总线,等待下次使用
}

void iic_send_byte(unsigned char byte)
{
unsigned char i;
for(i = 0;i<8;i++)
{
SDA = byte & 0x80;//非0为1
SCK = 1;
delay_us(1);
SCK = 0;
byte <<=1;//左移一位
}
SDA = 1;
SCK = 1;
delay_us(1);
if(0 == SDA)//有应答
ack = 0;
else //无应答
ack =1;

SCK = 0;//钳住总线,等待下次使用
}

unsigned char iic_rcv_byte()
{
unsigned char i,temp;
SDA = 1;
for(i = 0;i < 8;i ++)
{
SCK = 0;
delay_us(1);
SCK = 1;
delay_us(1);
temp <<= 1;
if(SDA)
temp = temp+ 1;
}
SCK = 0;
return temp;
}

void iic_ack()
{
SDA = 0;
SCK = 1;
delay_us(1);

SCK = 0;
}
void iic_noack()
{
SDA = 1;
SCK = 1;
delay_us(1);

SCK = 0;
}

void AT_send_str(unsigned char deviceaddr,unsigned char romaddr,unsigned char *s,unsigned char num)
{
unsigned char i;
iic_start();

iic_send_byte(deviceaddr);
if(ack == 1)
return;
iic_send_byte(romaddr);
if(ack == 1)
return;
for(i = 0;i < num; i ++)
{
iic_send_byte(*s);
if(ack == 1)
return;
s++;
}
icc_stop();
}

void AT_rcv_str(unsigned char deviceaddr,unsigned char romaddr,unsigned char *s,unsigned char num )
{
unsigned char i;
//SDA = 1;
iic_start();

iic_send_byte(deviceaddr);
if(ack == 1)
return;
iic_send_byte(romaddr);
if(ack == 1)
return;
iic_start();
iic_send_byte(deviceaddr + 1);
if(ack == 1)
return;
for(i = 0;i < num - 1; i++)
{
*s = iic_rcv_byte();
iic_ack();//
s++;
}
*s = iic_rcv_byte();
iic_noack();
icc_stop();
}

void main()
{
unsigned char i;
unsigned char testbuf[20] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,16,17,18,19};
unsigned char rcvbuf[20];
lcd_init();
AT_send_str(0xae,0,testbuf,10);
delay_ms(200);
AT_rcv_str(0xae,0,rcvbuf,10);
for(i = 0;i < 10; i++)
{
display_lcd_char(i,0,rcvbuf[i]+0x30);
}
while(1);
}

回答2:

CLEAR:
MOV DPTR,#5000H
MOV R2,#0
LOOP:
CLR A
MOVX @DPTR,A
INC DPTR
DJNZ R2,LOOP
RET

回答3:

公交卡我西州北路