I2C.c
Zo stránky SensorWiki
<source lang="c"> /*
* I2C.c * * Created: 15.01.2013 19:05:05 * Author: Tomáš Statečný */
- include <inttypes.h>
- include <compat/twi.h>
- include "I2C.h"
- include "lcd.h"
//Zadefinovanie CPU fekvencie v Hz pokial nie je dana
- ifndef F_CPU
- define F_CPU 16000000UL
- endif
//Zadefinovanie I2C frekvencie v Hz
- define SCL_CLOCK 100000L
//Inicializacia I2C void i2c_init(void) {
TWSR = 0; //No prescaler TWBR = ((F_CPU/SCL_CLOCK)-16)/2; //must be > 10 for stable operation
}
//Zadefinovanie vstupov a vystupov
- define SDA_I (DDRC &= ~(1<<4)) //Nastavenie 4bit DDRC na citanie (SDA)
- define SCL_O (DDRC |= (1<<5)) //Nastavenie 5bit DDRC na zapis (SCL)
- define SDA_O (DDRC |= (1<<4)) //Nastavenie 4bit DDRC na zapis (SDA)
//Nastavovanie pinov
- define SETBIT_SCL (PORTC |= (1<<5)) //Zapis log.1 na pin 5 PORTC (SCL)
- define CLEARBIT_SCL (PORTC &= ~(1<<5)) //Zapis log.0 na pin 5 PORTC (SCL)
- define SETBIT_SDA (PORTC |= (1<<4)) //Zapis log.1 na pin 4 PORTC (SDA)
- define CLEARBIT_SDA (PORTC &= ~(1<<4)) //Zapis log.0 na pin 4 PORTC (SDA)
- define CHECKBIT_SDA (PORTC & (1<<4)) //Zistenie stavu na pin 4 PORTC (SDA)
//Funkcia na meranie teploty alebo vlhkosti pre snimac SHT11 unsigned Measure(char CMD){ char i; char j = 0x80; unsigned hodnot = 0;
SDA_O; SETBIT_SDA; _delay_us(5); SCL_O; CLEARBIT_SCL; _delay_ms(100);
//Reset merania for(i=0; i<10; i++){
SDA_O; SETBIT_SDA; _delay_us(5); SCL_pulse(); }
//Incializacia prenosu SDA_O; CLEARBIT_SDA; _delay_us(5);
SCL_O; SETBIT_SCL; _delay_ms(5); SCL_O; CLEARBIT_SCL; _delay_ms(5);
SDA_O;
CLEARBIT_SDA;
_delay_us(5);
SCL_pulse();
SDA_O; SETBIT_SDA; _delay_us(5);
SCL_O; SETBIT_SCL; _delay_ms(5); SCL_O; CLEARBIT_SCL; _delay_ms(5);
_delay_ms(20);
//Adresa prikazu for(i=0; i<8; i++){
SDA_O; if(!(j & CMD)) CLEARBIT_SDA;
else SETBIT_SDA;
_delay_us(5); SCL_pulse();
j >>= 1; }
//Overie ACK bitu SDA_I; SCL_pulse();
if(CHECKBIT_SDA) return 0;
SCL_O; CLEARBIT_SCL; _delay_ms(100);
SDA_I; while(!CHECKBIT_SDA);
//Pockaj, dokial sa neprenesu data SDA_I; while(CHECKBIT_SDA);
//Vycitanie prveho Byte for(i=0; i<8; i++){ hodnot <<= 1;
SDA_I; if(CHECKBIT_SDA){ hodnot |= 1; _delay_us(5); SCL_pulse(); } }
//Odoslanie ACK bitu SDA_O; CLEARBIT_SDA; _delay_us(5); SCL_pulse();
//Vycitanie druheho Byte for(i=0; i<8; i++){ hodnot <<= 1;
SDA_I; if(CHECKBIT_SDA){ hodnot |= 1; _delay_us(5); SCL_pulse(); } }
return hodnot; //Vrati hodnotu bez kontrolneho suctu }
//Zadefinovanie jednej periody SCL int SCL_pulse(){
SCL_O; CLEARBIT_SCL; _delay_ms(5); SCL_O; SETBIT_SCL; _delay_ms(5); return 0; }