summaryrefslogtreecommitdiff
path: root/ports/stm32f4/src/stream_i2c.c
blob: 8c6c65b03c5a66df05e36d01be95ab09e765e67e (plain)
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
#include "stream_i2c.h"
#include "port.h"
#include "stream.h"

int i2c_read(uint8_t* buf, size_t count, void **vptr, void *sptr)
{
    p_stream_t *stream = (p_stream_t*)sptr;
    I2C_HandleTypeDef dev = *(I2C_HandleTypeDef*)stream->props[0];
    
    uint16_t addr         = *(uint16_t*)vptr[0];
    uint32_t timeout      = *(uint32_t*)vptr[1];
    uint16_t AF_limit     = *(uint32_t*)vptr[2];
    
    int error, AF_counter = 0; 
    while (HAL_I2C_Master_Receive(&dev, addr, buf, count, timeout) != HAL_OK) {
	if ((error = HAL_I2C_GetError(&dev)) != HAL_I2C_ERROR_AF) {
	    return error;
	}
	else if (++AF_counter > AF_limit) {
	    return HAL_I2C_ERROR_AF;
	}
    }
    return 0;
}

int i2c_write(uint8_t* buf, size_t count, void **vptr, void *sptr)
{
    p_stream_t *stream = (p_stream_t*)sptr;
    I2C_HandleTypeDef dev = *(I2C_HandleTypeDef*)stream->props[0];
    uint16_t addr         = *(uint16_t*)vptr[1];
    uint32_t timeout      = *(uint32_t*)vptr[2];
    
    while (HAL_I2C_Master_Transmit(&dev, addr, buf, count, timeout) != HAL_OK) {
	return HAL_I2C_GetError(&dev);
    }    
    return 0;
}