-
Notifications
You must be signed in to change notification settings - Fork 19
/
i2csoft.c
147 lines (94 loc) · 1.78 KB
/
i2csoft.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/**********************************************************
Software I2C Library for AVR Devices.
Copyright 2008-2012
eXtreme Electronics, India
www.eXtremeElectronics.co.in
**********************************************************/
#include <avr/io.h>
#include <util/delay.h>
#include "i2csoft.h"
#define Q_DEL _delay_loop_2(3)
#define H_DEL _delay_loop_2(5)
void SoftI2CInit(void)
{
SDAPORT&=(1<<SDA);
SCLPORT&=(1<<SCL);
SOFT_I2C_SDA_HIGH;
SOFT_I2C_SCL_HIGH;
}
void SoftI2CStart(void)
{
SOFT_I2C_SCL_HIGH;
H_DEL;
SOFT_I2C_SDA_LOW;
H_DEL;
}
void SoftI2CStop(void)
{
SOFT_I2C_SDA_LOW;
H_DEL;
SOFT_I2C_SCL_HIGH;
Q_DEL;
SOFT_I2C_SDA_HIGH;
H_DEL;
}
uint8_t SoftI2CWriteByte(uint8_t data)
{
uint8_t i;
for(i=0;i<8;i++)
{
SOFT_I2C_SCL_LOW;
Q_DEL;
if(data & 0x80)
SOFT_I2C_SDA_HIGH;
else
SOFT_I2C_SDA_LOW;
H_DEL;
SOFT_I2C_SCL_HIGH;
H_DEL;
while((SCLPIN & (1<<SCL))==0);
data=data<<1;
}
//The 9th clock (ACK Phase)
SOFT_I2C_SCL_LOW;
Q_DEL;
SOFT_I2C_SDA_HIGH;
H_DEL;
SOFT_I2C_SCL_HIGH;
H_DEL;
uint8_t ack=!(SDAPIN & (1<<SDA));
SOFT_I2C_SCL_LOW;
H_DEL;
return ack;
}
uint8_t SoftI2CReadByte(uint8_t ack)
{
uint8_t data=0x00;
uint8_t i;
for(i=0;i<8;i++)
{
SOFT_I2C_SCL_LOW;
H_DEL;
SOFT_I2C_SCL_HIGH;
H_DEL;
while((SCLPIN & (1<<SCL))==0);
if(SDAPIN &(1<<SDA))
data|=(0x80>>i);
}
SOFT_I2C_SCL_LOW;
Q_DEL; //Soft_I2C_Put_Ack
if(ack)
{
SOFT_I2C_SDA_LOW;
}
else
{
SOFT_I2C_SDA_HIGH;
}
H_DEL;
SOFT_I2C_SCL_HIGH;
H_DEL;
SOFT_I2C_SCL_LOW;
H_DEL;
return data;
}