GPIO模拟IIC,读写AT24C04的代码
时间: 2023-04-10 08:00:35 浏览: 175
以下是GPIO模拟IIC,读写AT24C04的代码:
```c
#include <stdio.h>
#include <wiringPi.h>
#define SDA_PIN 0
#define SCL_PIN 1
void iic_start(void)
{
pinMode(SDA_PIN, OUTPUT);
pinMode(SCL_PIN, OUTPUT);
digitalWrite(SDA_PIN, HIGH);
digitalWrite(SCL_PIN, HIGH);
delayMicroseconds(5);
digitalWrite(SDA_PIN, LOW);
delayMicroseconds(5);
digitalWrite(SCL_PIN, LOW);
delayMicroseconds(5);
}
void iic_stop(void)
{
pinMode(SDA_PIN, OUTPUT);
pinMode(SCL_PIN, OUTPUT);
digitalWrite(SDA_PIN, LOW);
digitalWrite(SCL_PIN, HIGH);
delayMicroseconds(5);
digitalWrite(SDA_PIN, HIGH);
delayMicroseconds(5);
}
void iic_send_byte(unsigned char data)
{
int i;
pinMode(SDA_PIN, OUTPUT);
pinMode(SCL_PIN, OUTPUT);
for (i = 0; i < 8; i++) {
if (data & 0x80) {
digitalWrite(SDA_PIN, HIGH);
} else {
digitalWrite(SDA_PIN, LOW);
}
data <<= 1;
digitalWrite(SCL_PIN, HIGH);
delayMicroseconds(5);
digitalWrite(SCL_PIN, LOW);
delayMicroseconds(5);
}
}
unsigned char iic_recv_byte(void)
{
int i;
unsigned char data = 0;
pinMode(SDA_PIN, INPUT);
pinMode(SCL_PIN, OUTPUT);
for (i = 0; i < 8; i++) {
data <<= 1;
digitalWrite(SCL_PIN, HIGH);
delayMicroseconds(5);
if (digitalRead(SDA_PIN)) {
data |= 0x01;
}
digitalWrite(SCL_PIN, LOW);
delayMicroseconds(5);
}
return data;
}
void iic_write(unsigned char addr, unsigned char data)
{
iic_start();
iic_send_byte(0xa0);
iic_send_byte(addr);
iic_send_byte(data);
iic_stop();
}
unsigned char iic_read(unsigned char addr)
{
unsigned char data;
iic_start();
iic_send_byte(0xa0);
iic_send_byte(addr);
iic_start();
iic_send_byte(0xa1);
data = iic_recv_byte();
iic_stop();
return data;
}
int main(void)
{
wiringPiSetup();
iic_write(0x00, 0x55);
printf("Read data: 0x%02x\n", iic_read(0x00));
return 0;
}
```
注意:这个代码仅供参考,具体实现可能需要根据硬件平台和具体情况进行调整。
阅读全文