Created
July 11, 2014 05:53
-
-
Save brightcloudy/c6406738c2b12e751271 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <avr/io.h> | |
#include <avr/interrupt.h> | |
#include <avr/sleep.h> | |
#include "init.h" | |
static inline void initializeI2C(void); | |
void sendCommand(uint8_t data); | |
uint8_t readReply(void); | |
uint8_t readAck(void); | |
void start(void); | |
void stop(void); | |
void ack(void); | |
void nack(void); | |
void clearNack(void); | |
static inline void initializeI2C(void) { | |
DDRA |= (1 << 4) | (1 << 6) | (1 << 3); | |
// pa4 scl pa6 sda | |
PORTA |= (1 << 4) | (1 << 6); | |
PORTA &= ~(1 << 3); | |
} | |
void sendCommand(uint8_t data) { | |
volatile uint8_t i = 0; | |
for (i = 0; i < 8; i++) { | |
if (data & (1 << (7 - i))) { | |
PORTA |= (1 << 6); | |
} else { | |
PORTA &= ~(1 << 6); | |
} | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
timer0_wait(); | |
} | |
PORTA |= (1 << 6); | |
} | |
uint8_t readReply(void) { | |
DDRA &= ~(1 << 6); | |
PORTA |= (1 << 6); | |
volatile uint8_t i = 0, data = 0; | |
for (i = 0; i < 8; i++) { | |
if (PINA & (1 << 6)) { | |
data |= (1 << (7 - i)); | |
} | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
timer0_wait(); | |
} | |
DDRA |= (1 << 6); | |
return data; | |
} | |
uint8_t readAck(void) { | |
uint8_t ack = 2; | |
DDRA &= ~(1 << 6); | |
PORTA |= (1 << 6); // release sda | |
PORTA |= (1 << 4); | |
ack = PINA & (1 << 6); | |
PORTA &= ~(1 << 4); | |
PORTA |= (1 << 6); | |
DDRA |= (1 << 6); | |
if (ack != 0) { | |
PORTA |= (1 << 3); | |
return 1; | |
} | |
return 0; | |
} | |
void start(void) { | |
PORTA |= (1 << 6); | |
timer0_wait(); | |
PORTA |= (1 << 4); | |
timer0_wait(); | |
PORTA &= ~(1 << 6); | |
timer0_wait(); | |
PORTA &= ~(1 << 4); | |
} | |
void stop(void) { | |
PORTA &= ~(1 << 6); | |
timer0_wait(); | |
PORTA |= (1 << 4); | |
timer0_wait(); | |
PORTA |= (1 << 6); | |
} | |
void ack(void) { | |
PORTA &= ~(1 << 6); | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
PORTA |= (1 << 6); | |
} | |
void nack(void) { | |
uint8_t status = (PORTA & (1 << 3)); | |
PORTA |= ~(1 << 6); | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
timer0_wait(); | |
PORTA ^= (1 << 4); | |
if (!status) { PORTA &= ~(1 << 3); }; | |
} | |
void clearNack(void) { | |
PORTA &= ~(1 << 3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment