67b73333
amoreau
Ajout du squelette
|
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
|
/************************
* i2c minimal library *
************************/
#include <stdint.h>
#include <avr/io.h>
#include "iic.h"
// Initialize i2c
void TWI_init(void)
{
//set SCL to 400kHz
TWSR = 0x00;
TWBR = 0x0C;
//enable TWI
TWCR = (1<<TWEN);
}
// Send start signal
static void TWI_start(void)
{
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while ((TWCR & (1<<TWINT)) == 0);
}
// Send stop signal
static void TWI_stop(void)
{
TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}
// Get i2c bus status
static uint8_t TWIGetStatus(void)
{
uint8_t status;
//mask status
status = TWSR & 0xF8;
return status;
}
// Write single byte to bus
static void TWI_writebyte(uint8_t u8data)
{
TWDR = u8data;
TWCR = (1<<TWINT)|(1<<TWEN);
while ((TWCR & (1<<TWINT)) == 0);
}
// Write i2c minimal message (command)
uint8_t TWI_writecmd(uint8_t address,uint8_t com_add)
{
TWI_start();
if (TWIGetStatus() != 0x08)
return ERROR;
TWI_writebyte(address<<1);
if (TWIGetStatus() != 0x18)
return ERROR;
TWI_writebyte(com_add);
if (TWIGetStatus() != 0x28)
return ERROR;
TWI_stop();
return SUCCESS;
}
// Write i2c message (with a single data byte)
uint8_t TWI_writedata(uint8_t address,uint8_t com_add,uint8_t data)
{
TWI_start();
if (TWIGetStatus() != 0x08)
return ERROR;
TWI_writebyte(address<<1);
if (TWIGetStatus() != 0x18)
return ERROR;
TWI_writebyte(com_add);
if (TWIGetStatus() != 0x28)
return ERROR;
TWI_writebyte(data);
if (TWIGetStatus() != 0x28)
return ERROR;
TWI_stop();
return SUCCESS;
}
|