Chinaunix首页 | 论坛 | 博客
  • 博客访问: 259120
  • 博文数量: 128
  • 博客积分: 65
  • 博客等级: 民兵
  • 技术积分: 487
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-24 17:43
个人简介

人生境界:明智、中庸、诚信、谦逊

文章分类

全部博文(128)

文章存档

2014年(12)

2013年(116)

我的朋友

分类: 嵌入式

2013-04-28 16:58:11

点击(此处)折叠或打开

  1. void delay(void)
  2. {
  3.     unsigned char i, j;
  4.     for(i = 0; i < 255; i++)
  5.         for(j = 0; j < 255; j++);
  6. }

  7. void i2c_init(void)
  8. {
  9.     WDTCTL = WDTPW + WDTHOLD; // Stop WDT
  10.     P3SEL |= 0x06; // Assign I2C pins to USCI_B0
  11.     UCB0CTL1 |= UCSWRST; // Enable SW reset
  12.     UCB0CTL0 = UCMST + UCMODE_3 + UCSYNC; // I2C Master, synchronous mode
  13.     UCB0CTL1 = UCSSEL_2 + UCSWRST; // Use SMCLK, keep SW reset
  14.     UCB0BR0 = 11; // fSCL = SMCLK/11 = 95.3kHz
  15.     UCB0BR1 = 0;
  16.     UCB0CTL1 &= ~UCSWRST; // Clear SW reset, resume operation
  17. }

  18. void wr_at24c02(unsigned char slave_addr, unsigned char addr, unsigned char *buf, unsigned char len)
  19. {
  20.     int i,j;

  21.     UCB0I2CSA = slave_addr;
  22.     UCB0CTL1 |= (UCTXSTT | UCTR);
  23.     while(!(IFG2 & UCB0TXIFG));
  24.     UCB0TXBUF = addr;
  25.     while(UCB0CTL1 & UCTXSTT);
  26.     while(!(IFG2 & UCB0TXIFG));
  27.     
  28.     
  29.     for(i = 0; i < len; i++) {
  30.         UCB0TXBUF=buf[i];
  31.         if(i != len-1)
  32.          while(!(IFG2 & UCB0TXIFG));
  33.         if(i == len-2) {
  34.             UCB0CTL1 |= UCTXSTP;
  35.         }
  36.     }
  37.     
  38.     delay();
  39. }

  40. void rd_at24c02(unsigned char slave_addr, unsigned char addr, unsigned char *buf, unsigned char len)
  41. {
  42.     int i,j;

  43.     UCB0I2CSA = slave_addr;
  44.     UCB0CTL1 |= (UCTXSTT | UCTR);

  45.     while(!(IFG2 & UCB0TXIFG));
  46.     UCB0TXBUF = addr;

  47.     while(UCB0CTL1 & UCTXSTT);
  48.     while(!(IFG2 & UCB0TXIFG));

  49.     UCB0I2CSA = slave_addr;
  50.     UCB0CTL1 &= ~UCTR;
  51.     UCB0CTL1 |=UCTXSTT;
  52.     while(UCB0CTL1 & UCTXSTT);
  53.     for(i = 0; i < len; i++) {
  54.         while(!(IFG2 & UCB0RXIFG));
  55.         buf[i] = UCB0RXBUF;
  56.         if(i == len-2) {
  57.             UCB0CTL1 |= UCTXSTP;
  58.         }
  59.     }
  60.     
  61.     delay();
  62. }

  63. unsigned char a[8];
  64. unsigned char b[8]={0,1,2,3,4,5,6,7};
  65. int main()
  66. {
  67.      i2c_init();
  68.      wr_at24c02(0x50, 0x00, b, 8);
  69.      rd_at24c02(0x50, 0x00, a, 8);
  70.      while(1);
  71. }


阅读(1923) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~