zoukankan      html  css  js  c++  java
  • iic总线的机制

    iic总线相关知识是嵌入式开发软件、硬件必问的知识点。被卡死了几回,今天进行总结。

    特点:二线制,半双工,具有应答机制。其工作原理是scl、sda的开漏输出,因此必须接上拉电阻。通信速率略慢,0-3.4mHZ范围。

    时序图:

    2.其驱动程序:

    #include "pch.h"
    #include <iostream>
    #define NUMBER1 (60*60*24*365)
    
    
    void delay_us(int j)
    {
      int i,k;
      for (i = 0;i < 1000;i++)
    	  for (k = 0;k < j * 1000;k++);
    }
    
    
    int SDA = 1;
    int SCL = 1;
    //iic起始信号
    void start()
    {
    	delay_us(100);
    	SDA = 0;
    	SCL = 0;
    	delay_us(100);
    	SCL = 1;
    }
    
    //iic结束信号逻辑
    void end()
    {
    	SDA = 0;
    	SCL = 1;
    	delay_us(100);
    	SDA = 1;
    }
    
    void ack()
    {
    	SCL = 0;
    	SDA = 1;
    	int i=0;
    	SCL = 1;
    	delay_us(100);
    	while ((SDA == 1)& (i < 255))
    	{
    		i++;
    	}
    	SCL = 0;
    	//delay_us(100);
    	//SCL = 1;
    }
    
    
    //写数据时,要求在SCL=1时,数据保持稳定
    void write_byte(int data)
    {
    	int i,temp;
    	temp = data;
    	
    	for (i = 0;i < 8;i++)
    	{
    		SCL = 0;
    		if (temp & 0x80)
    		{
    			SDA = 1;
    		}
    		else
    			SDA = 0;
    		temp = temp << 1;
    		delay_us(100);
    		SCL = 1;
    		delay_us(100);
    	}
    	SCL = 0;
    }
    
    //读数据时,SCL=1时,进行读取
    int read_byte()
    {
    	int i,data;
    	SCL = 0;
    	delay_us(100);
    	for (i = 0;i < 8;i++)
    	{
    		SCL = 1;
    		delay_us(100);
    		if (SDA == 1) data=data++;
    		data = data << 1;
    		SCL = 0;
    		delay_us(100);	
    	}
    	return data;
    }
    
    
    void no_ack()
    {
    	SDA = 1;
    	SCL = 1;
    	delay_us(100);
    	SCL = 0;
    	delay_us(100);
    }
    
    void write_data(int addr,int addr1)
    {
    	start();
    	write_byte(addr);//写iic器件的物理地址
    	ack();
    	write_byte(addr1);//存储数据的地址
    }
    
    
    int read_data(int addr, int addr1)
    {
    	int data;
    	start();
    	write_byte(addr);
    	ack();
    	write_byte(addr1);
    	ack();
    	write_byte(addr + 1);//读操作
    	ack();
    	data = read_byte();
    	no_ack();
    	end();
    	return data;
    }
    
    int main()
    {
    	read_data(1, 2);
    }
    

      

  • 相关阅读:
    IDEA解决Cannot download sources的问题
    Swagger在Springboot项目中的使用
    ElasticSearch(10)—SpringBoot集成ES
    ElasticSearch(9)---Rest风格
    ElasticSearch(8)---IK分词器
    js显示原型和隐示原型
    通俗易懂讲解为什么设计稿都是750px
    关于rem和px全局设置问题
    PHP RSA密文过长加密解密 越过1024的解决代码
    使用https,$_SERVER['HTTPS']却不等于on?
  • 原文地址:https://www.cnblogs.com/xuehaiwuya0000/p/11791737.html
Copyright © 2011-2022 走看看