今天复习了I2C,SPI
I2C:同步半双工通讯。分主从。主发送脉冲。数据传输某一时刻只能一个方向。
两根线:SCK(时钟)、SDA(信号)
I2C同时可以挂多个器件,与SPI不同,I2C通过通讯时地址编码选择应答,然后继续通讯。SPI通过片选电位。
I2C闲时两根线同为高电位。(通过上拉电阻,电阻越小通讯速度越快)
开始:主先把SDA拉低,SCK工作。
主向从发出器件编码(7位),方向(0写,1读)。
写入:
Wire.beginTransmission(七位器件编码);默认方向为0............................................发送第一个字节
Wire.write(写入寄存器地址);
Wire.write(写入数据);
Wire.endTransmission();实际发送
读出:
Wire.requestFrom(七位器件编码, 读取字节个数);默认方向为1.
A=Wire.read(读取寄存器地址);//A为返回值
TC74为例:
#include<Wire.h>
int A = 3;
#define qishi 0b1001000
void setup() {
Wire.begin();
Serial.begin(9600);
}
void loop() {
Wire.beginTransmission(qishi);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(qishi, 1);
A = Wire.read();
if( ((A&0b10000000)>>7)==0)
Serial.println(A);
if( ((A&0b10000000)>>7)==1)
Serial.println(-(257+~A));
}
SPI mcp23s08 I2C mcp23008
#include"Adafruit_MCP23008.h"
#include<Wire.h>
#include<SPI.h>
int A;
class Adafruit_MCP23008 u1;
class Adafruit_MCP23008 u2;
void setup() {
pinMode (10, OUTPUT);
digitalWrite(10, HIGH);
SPI.begin();
Serial.begin(9600);
u1.begin(0x00000000);
u2.begin(0x00000001);
u1.pinMode(0, OUTPUT);
u1.pullUp(7, INPUT);
u2.pinMode(0, OUTPUT);
u2.pinMode(1, OUTPUT);
u2.pinMode(2, OUTPUT);
u2.pinMode(3, OUTPUT);
u2.pinMode(4, OUTPUT);
u2.pinMode(5, OUTPUT);
u2.pinMode(6, OUTPUT);
u2.pinMode(7, OUTPUT);
u1.digitalWrite(0, HIGH);
}
void loop() {
if (u1.digitalRead(7) == 0)
u1.digitalWrite(0, LOW);
else
u1.digitalWrite(0, HIGH);
for (int i = 0; i <= 7; i++)
{ u2.digitalWrite(i, HIGH);
delay(50);
u2.digitalWrite(i, LOW);
}
digitalWrite(10, LOW);//配置
SPI.transfer(0b01000000);
SPI.transfer(0x00);
SPI.transfer(0b11110000);
digitalWrite(10,HIGH);
digitalWrite(10, LOW);//输入
SPI.transfer(0b01000001);
SPI.transfer(0x09);
A= SPI.transfer(0);
digitalWrite(10,HIGH);
digitalWrite(10, LOW);//输出
SPI.transfer(0b01000000);
SPI.transfer(0x0A);
SPI.transfer((A>>4)&(0b11111111));
digitalWrite(10,HIGH);
}
网友评论