-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathi2c-scan.c
88 lines (76 loc) · 2.52 KB
/
i2c-scan.c
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
/*
i2c-scan is a library that scans the i2c bus
Copyright (C) 2019 Ronald Sutherland
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <avr/pgmspace.h>
#include <stdio.h>
#include <stdlib.h>
#include "../lib/parse.h"
#include "../lib/twi.h"
#include "i2c-scan.h"
static uint8_t address;
static uint8_t start_address;
static uint8_t end_address;
static uint8_t found_addresses;
static uint8_t returnCode;
/* Scan the I2C bus between addresses from_addr and to_addr.
On each address, call the callback function with the address and result.
If result==0, address was found, otherwise, address wasn't found
can use result to potentially get other status off the I2C bus, see twi.c */
void I2c_scan(void)
{
if (command_done == 10)
{
start_address = 0x8; // 0-0x7 is reserved (e.g. general call, CBUS, Hs-mode...)
end_address = 0x77; // 0x78-0x7F is reserved (e.g. 10-bit...)
address = start_address;
found_addresses = 0;
printf_P(PSTR("{\"scan\":[")); // start of JSON
command_done = 11;
}
else if (command_done == 11)
{
uint8_t data = 0;
uint8_t length = 0;
uint8_t wait = 1;
uint8_t sendStop = 1;
returnCode = twi_writeTo(address, &data, length, wait, sendStop);
if ( (returnCode == 0) && (found_addresses > 0) )
{
printf_P(PSTR(","));
}
if (returnCode == 0)
{
printf_P(PSTR("{\"addr\":\"0x%X\"}"),address);
found_addresses += 1;
}
if (address >= end_address)
{
command_done = 12;
}
else
{
address += 1;
}
}
else if ( (command_done == 12) )
{
printf_P(PSTR("]}\r\n"));
initCommandBuffer();
}
else
{
initCommandBuffer();
}
}