1 | /*******************************************************************************
|
2 | ___________
|
3 | | _ |
|
4 | | | | |
|
5 | | | | |
|
6 | | | |-KISS | L-Kiss, gibb: Keep It Simple! - Stupid! :-))
|
7 | | | |_____ | © by ELEb 2003
|
8 | | |_______| |
|
9 | |___________|
|
10 |
|
11 | Projectname: TWI (Two Wire Interface)
|
12 |
|
13 | Filename: I2C.h
|
14 | Author: Bernhard Naegeli
|
15 | Version: 1.0
|
16 | Date: Mai 2007
|
17 |
|
18 | Funktion: Funktionen für die Ansteuerung des I2C-Bus
|
19 |
|
20 | *******************************************************************************/
|
21 |
|
22 | #ifndef _I2C_H_
|
23 | #define _I2C_H_
|
24 |
|
25 | #define CPU_CLOCK 8000000
|
26 | #define SCL_CLOCK 100000
|
27 |
|
28 | //Init I2C
|
29 | void i2c_init(void) {
|
30 | TWBR = ((CPU_CLOCK/SCL_CLOCK)-16)/2;
|
31 | TWSR = 0;
|
32 | TWCR = 4;
|
33 | }
|
34 |
|
35 | //Start I2C
|
36 | void i2c_start(void) {
|
37 | uint8_t i2c_start_count;
|
38 | TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
|
39 | for (i2c_start_count=0;i2c_start_count<=100;i2c_start_count++) {
|
40 | if (TWCR & (1<<TWINT)) {
|
41 | break;
|
42 | }
|
43 | delay_ms(1);
|
44 | }
|
45 | }
|
46 |
|
47 | //Send Data I2C
|
48 | void i2c_write(uint8_t Data) {
|
49 | uint8_t i;
|
50 | TWDR = Data;
|
51 | TWCR = (1<<TWINT)|(1<<TWEN);
|
52 | for (i=0;i<=100;i++) {
|
53 | if (TWCR & (1<<TWINT)) {
|
54 | break;
|
55 | }
|
56 | delay_ms(1);
|
57 | }
|
58 | }
|
59 |
|
60 | //Read Data I2c
|
61 | uint8_t i2c_read(uint8_t ACK) {
|
62 | uint8_t q;
|
63 | if (ACK == 1) {
|
64 | TWCR = (1<<TWINT)|(1<<TWEA)|(1<<TWEN);
|
65 | }
|
66 | else {
|
67 | TWCR = (1<<TWEN)|(1<<TWINT);
|
68 | }
|
69 | for (q=0;q<=250;q++) {
|
70 | if (TWCR & (1<<TWINT)) {
|
71 | break;
|
72 | }
|
73 | }
|
74 | return TWDR;
|
75 | }
|
76 |
|
77 |
|
78 | //Stop I2C
|
79 | void i2c_stop(void) {
|
80 | uint8_t i2c_stop_count;
|
81 | TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO);
|
82 | for (i2c_stop_count=0;i2c_stop_count<=250;i2c_stop_count++) {
|
83 | if (!(TWCR & (1<<TWSTO))) {
|
84 | return;
|
85 | }
|
86 | }
|
87 | }
|
88 |
|
89 | #endif
|