summaryrefslogtreecommitdiff
path: root/bsp/stm32f429-apollo/drivers/drv_pcf8574.c
blob: 90f7793770997aa68e481273d87236985407baa9 (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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2017-06-09     tanek        first implementation.
 */
#include "drv_pcf8574.h"
#include <board.h>
#include <rthw.h>
#include <finsh.h>

//#define DEBUG

#ifdef DEBUG
#define DEBUG_PRINTF(...)   rt_kprintf(__VA_ARGS__)
#else
#define DEBUG_PRINTF(...)   
#endif

#define I2C_BUS_NAME	"i2c0"
#define PCF8574_ADDR 	0x20

static uint8_t rt_pcf8574_read_onebyte(void);
static void rt_pcf8574_write_onebyte(rt_uint8_t value);

static struct rt_i2c_bus_device * i2c_bus;

rt_err_t rt_pcf8574_init(void)
{
	rt_uint8_t buffer[] = { 0xFF };
	rt_off_t pos = PCF8574_ADDR;
	
	__HAL_RCC_GPIOB_CLK_ENABLE();

	i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(I2C_BUS_NAME);
	if (i2c_bus == RT_NULL)
	{
		DEBUG_PRINTF("\ni2c_bus %s for PCF8574 not found!\n", I2C_BUS_NAME);
		return -RT_ENOSYS;
	}

	if (rt_device_open(&i2c_bus->parent, RT_NULL) != RT_EOK)
	{
		DEBUG_PRINTF("\ni2c_bus %s for cs43l22 opened failed!\n", I2C_BUS_NAME);
		return -RT_EEMPTY;
	}

	rt_device_write(&i2c_bus->parent, pos, &buffer, 1);

	return RT_EOK;
}

static uint8_t rt_pcf8574_read_onebyte(void)
{
	rt_uint8_t value;

	rt_device_read(&i2c_bus->parent, PCF8574_ADDR, &value, 1);

	return value;
}


static void rt_pcf8574_write_onebyte(rt_uint8_t value)
{
	rt_device_write(&i2c_bus->parent, PCF8574_ADDR, &value, 1);
}


void rt_pcf8574_write_bit(rt_uint8_t bit, rt_uint8_t state)
{
	rt_uint8_t data;
	data = rt_pcf8574_read_onebyte();

	if (state == 0)
		data &= ~(1 << bit);
	else 
		data |= 1 << bit;

	rt_pcf8574_write_onebyte(data);
}


rt_uint8_t rt_pcf8574_read_bit(rt_uint8_t bit)
{
	rt_uint8_t data;
	data = rt_pcf8574_read_onebyte();

	if (data&(1 << bit))
		return 1;
	else
		return 0;
}