首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

主从PIC单片机I2C通信主的程序为

主从PIC单片机I2C通信主的程序为

主从PIC单片机I2C通信主的程序为
#i nclude <18F4523.h>                             // PICF4523 header file
#device ADC=12                                   // 12 bits ADC
#use delay(clock=4000000)                       // for 4Mhz crystal
#fuses XT, NOWDT, NOPROTECT, NOLVP               // for debug mode
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, Parity=N, Bits=8, ERRORS)
#use i2c(Master, sda=PIN_C4, scl=PIN_C3,FORCE_HW)
void main()
{
        int8 data;
        int8 buffer[10];
        
//        putc( 0x11 );
//        putc( 0x22 );
//        putc( 0x33 );
//        putc( 0x44 );
//        putc( 0x55 );
//        putc( 0x66 );
        // Write the letter 'B' to the slave board.
        while(true)
        {
        i2c_start();
        i2c_write(0xa1);
        //i2c_write(0x00);
        //data=i2c_read(0);
        buffer[0] = i2c_read();
        buffer[1] = i2c_read();
        buffer[2] = i2c_read();
        buffer[3] = i2c_read();
        buffer[4] = i2c_read(0);
//        buffer[5] = i2c_read();
//        buffer[6] = i2c_read();
//        buffer[7] = i2c_read(0);
   
        i2c_stop();
        //lcd_putc(data);
        
        delay_ms(2);
        //printf("read %c \n\r", data);
        // putc( data );
        
        putc( buffer[0] );
        putc( buffer[1] );
        putc( buffer[2] );
        putc( buffer[3] );
        putc( buffer[4] );
//        putc( buffer[5] );
//        putc( buffer[6] );
//        putc( buffer[7] );
        
        delay_ms( 2000 );   
        }
        //while(1);   
}
从的程序为
#i nclude <16F877.h>
#fuses XT,NOWDT,NOPROTECT,NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)

#use i2c(SLAVE, SDA=PIN_C4, SCL=PIN_C3, address=0xa0)
//BYTE address;
BYTE buffer[10] = {0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99};
#INT_SSP
void ssp_interupt ()
{
   BYTE state,dummy;
   state = i2c_isr_state();
   if(state >= 0x80)                     //Master is requesting data
   {
      i2c_write(buffer[state - 0x80]);
   }
   else
   {
      dummy=i2c_read();    //this line is to avoid locking the bus in case of a write
   }
}
void main ()
{
   enable_interrupts(GLOBAL);
   enable_interrupts(INT_SSP);
   while (TRUE) {}
}
返回列表