Skip to content

Instantly share code, notes, and snippets.

@madex
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madex/cf7e4df2733f43ec5f63 to your computer and use it in GitHub Desktop.
Save madex/cf7e4df2733f43ec5f63 to your computer and use it in GitHub Desktop.
universal software i2c for microcontrollers
// example for xmega256d3
// bit delay
static void delay(void) {
__no_operation();
__no_operation();
__no_operation();
__no_operation();
__no_operation();
__no_operation();
__no_operation();
__no_operation();
__no_operation();
__no_operation();
}
// Basefunctions
// set SDA Pin to value (0 or 1)
static void setSDA(uint8_t value) {
if (value)
PORTE.OUTSET = 1;
else
PORTE.OUTCLR = 1;
}
// set SCL Pin to value (0 or 1)
static void setSCL(uint8_t value) {
if (value)
PORTE.OUTSET = 2;
else
PORTE.OUTCLR = 2;
}
// configure SDA Pin as Input
static void setREAD(void) {
PORTE.DIRCLR = 1;
PORTE.OUTCLR = 1;
}
// configure SDA Pin as OUTPUT
static void setWRITE(void) {
PORTE.DIRSET = 1;
}
// read SDA Pin
static uint8_t readSDA(void) {
return PORTE.IN & 1;
}
// higher level functions
// send Startcondition
void i2cSoft_Start() {
setSDA(1);
setWRITE();
setSCL(1);
delay();
setSDA(0);
delay();
setSCL(0);
delay();
}
// send Stopcondition
void i2cSoft_Stop() {
setWRITE();
setSCL(0);
setSDA(0);
delay();
setSCL(1);
delay();
delay();
setSDA(1);
delay();
setREAD();
}
// write ic2 address or data and returns a recieved ack
uint8_t i2cSoft_Write(uint8_t data) {
uint8_t index;
setWRITE();
for (index = 0; index < 8; index++) {
setSCL(0);
setSDA(data & 0x80);
delay();
setSCL(1);
delay();
data <<= 1;
}
setSCL(0);
delay();
setREAD();
__no_operation();
__no_operation();
setSCL(1);
delay();
index = readSDA();
__no_operation();
__no_operation();
setSCL(0);
return index;
}
// read ic2 data with or without acknoglege depending on ack
uint8_t i2cSoft_Read(uint8_t ack) {
uint8_t i;
uint16_t data = 0;
setREAD();
setSDA(0);
for (i = 0; i < 8; i++) {
setSCL(1);
data <<= 1;
data |= readSDA();
delay();
setSCL(0);
delay();
}
setWRITE();
setSDA(!ack);
__no_operation();
__no_operation();
setSCL(1);
delay();
setSCL(0);
delay();
setSDA(0);
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment