This commit is contained in:
2023-01-11 00:39:00 +01:00
commit 73633af366
41 changed files with 5143 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
set(COMPONENT_ADD_INCLUDEDIRS .)
set(COMPONENT_SRCS "cmd_system.c")
set(COMPONENT_REQUIRES console spi_flash)
register_component()
+173
View File
@@ -0,0 +1,173 @@
/* Console example — various system commands
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "esp_log.h"
#include "esp_attr.h"
#include "esp_console.h"
#include "esp_system.h"
#include "esp_sleep.h"
#include "esp_spi_flash.h"
#include "argtable3/argtable3.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "rom/uart.h"
#include "cmd_system.h"
#include "sdkconfig.h"
#ifdef CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS
#define WITH_TASKS_INFO 1
#endif
static const char *TAG = "cmd_system";
static void register_free();
static void register_heap();
static void register_version();
static void register_restart();
#if WITH_TASKS_INFO
static void register_tasks();
#endif
void console_register_system()
{
register_free();
register_heap();
register_version();
register_restart();
#if WITH_TASKS_INFO
register_tasks();
#endif
}
/* 'version' command */
static int get_version(int argc, char **argv)
{
esp_chip_info_t info;
esp_chip_info(&info);
printf("IDF Version:%s\r\n", esp_get_idf_version());
printf("Chip info:\r\n");
printf("\tmodel:%s\r\n", info.model == CHIP_ESP8266 ? "ESP8266" : "Unknow");
printf("\tcores:%d\r\n", info.cores);
printf("\tfeature:%s%s%s%s%d%s\r\n",
info.features & CHIP_FEATURE_WIFI_BGN ? "/802.11bgn" : "",
info.features & CHIP_FEATURE_BLE ? "/BLE" : "",
info.features & CHIP_FEATURE_BT ? "/BT" : "",
info.features & CHIP_FEATURE_EMB_FLASH ? "/Embedded-Flash:" : "/External-Flash:",
spi_flash_get_chip_size() / (1024 * 1024), " MB");
printf("\trevision number:%d\r\n", info.revision);
return 0;
}
static void register_version()
{
const esp_console_cmd_t cmd = {
.command = "version",
.help = "Get version of chip and SDK",
.hint = NULL,
.func = &get_version,
};
ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
}
/** 'restart' command restarts the program */
static int restart(int argc, char **argv)
{
ESP_LOGI(TAG, "Restarting");
esp_restart();
}
static void register_restart()
{
const esp_console_cmd_t cmd = {
.command = "restart",
.help = "Software reset of the chip",
.hint = NULL,
.func = &restart,
};
ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
}
/** 'free' command prints available heap memory */
static int free_mem(int argc, char **argv)
{
printf("%d\n", esp_get_free_heap_size());
return 0;
}
static void register_free()
{
const esp_console_cmd_t cmd = {
.command = "free",
.help = "Get the current size of free heap memory",
.hint = NULL,
.func = &free_mem,
};
ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
}
/* 'heap' command prints minumum heap size */
static int heap_size(int argc, char **argv)
{
uint32_t heap_size = heap_caps_get_minimum_free_size(MALLOC_CAP_32BIT);
ESP_LOGI(TAG, "min heap size: %u", heap_size);
return 0;
}
static void register_heap()
{
const esp_console_cmd_t heap_cmd = {
.command = "heap",
.help = "Get minimum size of free heap memory that was available during program execution",
.hint = NULL,
.func = &heap_size,
};
ESP_ERROR_CHECK( esp_console_cmd_register(&heap_cmd) );
}
/** 'tasks' command prints the list of tasks and related information */
#if WITH_TASKS_INFO
static int tasks_info(int argc, char **argv)
{
const size_t bytes_per_task = 40; /* see vTaskList description */
char *task_list_buffer = malloc(uxTaskGetNumberOfTasks() * bytes_per_task);
if (task_list_buffer == NULL) {
ESP_LOGE(TAG, "failed to allocate buffer for vTaskList output");
return 1;
}
fputs("Task Name\tStatus\tPrio\tHWM\tTask#", stdout);
#ifdef CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID
fputs("\tAffinity", stdout);
#endif
fputs("\n", stdout);
vTaskList(task_list_buffer);
fputs(task_list_buffer, stdout);
free(task_list_buffer);
return 0;
}
static void register_tasks()
{
const esp_console_cmd_t cmd = {
.command = "tasks",
.help = "Get information about running tasks",
.hint = NULL,
.func = &tasks_info,
};
ESP_ERROR_CHECK( esp_console_cmd_register(&cmd) );
}
#endif // WITH_TASKS_INFO
+20
View File
@@ -0,0 +1,20 @@
/* Console example — various system commands
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
// Register system functions
void console_register_system();
#ifdef __cplusplus
}
#endif
+10
View File
@@ -0,0 +1,10 @@
#
# Component Makefile
#
# This Makefile should, at the very least, just include $(SDK_PATH)/Makefile. By default,
# this will take the sources in the src/ directory, compile them and link them into
# lib(subdirectory_name).a in the build directory. This behaviour is entirely configurable,
# please read the SDK documents if you need to do this.
#
COMPONENT_ADD_INCLUDEDIRS := .
+5
View File
@@ -0,0 +1,5 @@
set(COMPONENT_ADD_INCLUDEDIRS .)
set(COMPONENT_SRCS "dht.c")
register_component()
+10
View File
@@ -0,0 +1,10 @@
#
# Component Makefile
#
# This Makefile should, at the very least, just include $(SDK_PATH)/Makefile. By default,
# this will take the sources in the src/ directory, compile them and link them into
# lib(subdirectory_name).a in the build directory. This behaviour is entirely configurable,
# please read the SDK documents if you need to do this.
#
COMPONENT_ADD_INCLUDEDIRS := .
+194
View File
@@ -0,0 +1,194 @@
/*
* Part of esp-open-rtos
* Copyright (C) 2016 Jonathan Hartsuiker (https://github.com/jsuiker)
* BSD Licensed as described in the file LICENSE
*
*/
#include "dht.h"
#include "FreeRTOS.h"
#include "string.h"
#include "task.h"
#include "driver/gpio.h"
// DHT timer precision in microseconds
#define DHT_TIMER_INTERVAL 2
#define DHT_DATA_BITS 40
//#define DEBUG_DHT
// #define DEBUG_DHT
#ifdef DEBUG_DHT
#define debug(fmt, ...) printf("%s" fmt "\n", "dht: ", ## __VA_ARGS__);
#else
#define debug(fmt, ...) /* (do nothing) */
#endif
/*
* Note:
* A suitable pull-up resistor should be connected to the selected GPIO line
*
* __ ______ _______ ___________________________
* \ A / \ C / \ DHT duration_data_low / \
* \_______/ B \______/ D \__________________________/ DHT duration_data_high \__
*
*
* Initializing communications with the DHT requires four 'phases' as follows:
*
* Phase A - MCU pulls signal low for at least 18000 us
* Phase B - MCU allows signal to float back up and waits 20-40us for DHT to pull it low
* Phase C - DHT pulls signal low for ~80us
* Phase D - DHT lets signal float back up for ~80us
*
* After this, the DHT transmits its first bit by holding the signal low for 50us
* and then letting it float back high for a period of time that depends on the data bit.
* duration_data_high is shorter than 50us for a logic '0' and longer than 50us for logic '1'.
*
* There are a total of 40 data bits transmitted sequentially. These bits are read into a byte array
* of length 5. The first and third bytes are humidity (%) and temperature (C), respectively. Bytes 2 and 4
* are zero-filled and the fifth is a checksum such that:
*
* byte_5 == (byte_1 + byte_2 + byte_3 + btye_4) & 0xFF
*
*/
/**
* Wait specified time for pin to go to a specified state.
* If timeout is reached and pin doesn't go to a requested state
* false is returned.
* The elapsed time is returned in pointer 'duration' if it is not NULL.
*/
static bool dht_await_pin_state(uint8_t pin, uint32_t timeout,
bool expected_pin_state, uint32_t *duration)
{
for (uint32_t i = 0; i < timeout; i += DHT_TIMER_INTERVAL) {
// need to wait at least a single interval to prevent reading a jitter
os_delay_us(DHT_TIMER_INTERVAL);
if (gpio_get_level(pin) == expected_pin_state) {
if (duration) {
*duration = i;
}
return true;
}
}
return false;
}
/**
* Request data from DHT and read raw bit stream.
* The function call should be protected from task switching.
* Return false if error occurred.
*/
static inline bool dht_fetch_data(dht_sensor_type_t sensor_type, uint8_t pin, bool bits[DHT_DATA_BITS])
{
uint32_t low_duration;
uint32_t high_duration;
// Phase 'A' pulling signal low to initiate read sequence
gpio_set_level(pin, 0);
os_delay_us(sensor_type == DHT_TYPE_SI7021 ? 500 : 20000);
gpio_set_level(pin, 1);
// Step through Phase 'B', 40us
if (!dht_await_pin_state(pin, 40, false, NULL)) {
debug("Initialization error, problem in phase 'B'\n");
return false;
}
// Step through Phase 'C', 88us
if (!dht_await_pin_state(pin, 88, true, NULL)) {
debug("Initialization error, problem in phase 'C'\n");
return false;
}
// Step through Phase 'D', 88us
if (!dht_await_pin_state(pin, 88, false, NULL)) {
debug("Initialization error, problem in phase 'D'\n");
return false;
}
// Read in each of the 40 bits of data...
for (int i = 0; i < DHT_DATA_BITS; i++) {
if (!dht_await_pin_state(pin, 65, true, &low_duration)) {
debug("LOW bit timeout\n");
return false;
}
if (!dht_await_pin_state(pin, 75, false, &high_duration)) {
debug("HIGHT bit timeout\n");
return false;
}
bits[i] = high_duration > low_duration;
}
return true;
}
/**
* Pack two data bytes into single value and take into account sign bit.
*/
static inline int16_t dht_convert_data(dht_sensor_type_t sensor_type, uint8_t msb, uint8_t lsb)
{
int16_t data;
if (sensor_type == DHT_TYPE_DHT22) {
data = msb & 0x7F;
data <<= 8;
data |= lsb;
if (msb & BIT(7)) {
data = 0 - data; // convert it to negative
}
}
else {
data = msb * 10;
}
return data;
}
bool dht_read_data(dht_sensor_type_t sensor_type, uint8_t pin, int16_t *humidity, int16_t *temperature)
{
bool bits[DHT_DATA_BITS];
uint8_t data[DHT_DATA_BITS/8] = {0};
bool result;
gpio_set_direction(pin, GPIO_MODE_OUTPUT_OD);
taskENTER_CRITICAL();
result = dht_fetch_data(sensor_type, pin, bits);
taskEXIT_CRITICAL();
if (!result) {
return false;
}
for (uint8_t i = 0; i < DHT_DATA_BITS; i++) {
// Read each bit into 'result' byte array...
data[i/8] <<= 1;
data[i/8] |= bits[i];
}
if (data[4] != ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
debug("Checksum failed, invalid data received from sensor\n");
return false;
}
*humidity = dht_convert_data(sensor_type, data[0], data[1]);
*temperature = dht_convert_data(sensor_type, data[2], data[3]);
debug("Sensor data: humidity=%d, temp=%d\n", *humidity, *temperature);
return true;
}
bool dht_read_float_data(dht_sensor_type_t sensor_type, uint8_t pin, float *humidity, float *temperature)
{
int16_t i_humidity, i_temp;
if (dht_read_data(sensor_type, pin, &i_humidity, &i_temp)) {
*humidity = (float)i_humidity / 10;
*temperature = (float)i_temp / 10;
return true;
}
return false;
}
+50
View File
@@ -0,0 +1,50 @@
/*
* Part of esp-open-rtos
* Copyright (C) 2016 Jonathan Hartsuiker (https://github.com/jsuiker)
* BSD Licensed as described in the file LICENSE
*
*/
#ifndef __DHT_H__
#define __DHT_H__
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Sensor type
*/
typedef enum
{
DHT_TYPE_DHT11 = 0, //!< DHT11
DHT_TYPE_DHT22, //!< DHT22
DHT_TYPE_SI7021 //!< Itead SI7021
} dht_sensor_type_t;
/**
* Read data from sensor on specified pin.
*
* Humidity and temperature is returned as integers.
* For example: humidity=625 is 62.5 %
* temperature=24.4 is 24.4 degrees Celsius
*
*/
bool dht_read_data(dht_sensor_type_t sensor_type, uint8_t pin, int16_t *humidity, int16_t *temperature);
/**
* Float version of dht_read_data.
*
* Return values as floating point values.
*/
bool dht_read_float_data(dht_sensor_type_t sensor_type, uint8_t pin, float *humidity, float *temperature);
#ifdef __cplusplus
}
#endif
#endif // __DHT_H__
+7
View File
@@ -0,0 +1,7 @@
set(COMPONENT_ADD_INCLUDEDIRS .)
set(COMPONENT_SRCS "onewire.c" "ds18b20.c")
#set(COMPONENT_REQUIRES console spi_flash)
register_component()
+14
View File
@@ -0,0 +1,14 @@
# Yet another one wire driver for the ESP8266
This is a port of a bit-banging one wire driver based on the implementation
from NodeMCU.
This, in turn, appears to have been based on the PJRC Teensy driver
(https://www.pjrc.com/teensy/td_libs_OneWire.html), by Jim Studt, Paul
Stoffregen, and a host of others.
The original code is licensed under the MIT license. The CRC code was taken
(at least partially) from Dallas Semiconductor sample code, which was licensed
under an MIT license with an additional clause (prohibiting inappropriate use
of the Dallas Semiconductor name). See the accompanying LICENSE file for
details.
+10
View File
@@ -0,0 +1,10 @@
#
# Component Makefile
#
# This Makefile should, at the very least, just include $(SDK_PATH)/Makefile. By default,
# this will take the sources in the src/ directory, compile them and link them into
# lib(subdirectory_name).a in the build directory. This behaviour is entirely configurable,
# please read the SDK documents if you need to do this.
#
COMPONENT_ADD_INCLUDEDIRS := .
+253
View File
@@ -0,0 +1,253 @@
#include "FreeRTOS.h"
#include "task.h"
#include "math.h"
#include "ds18b20.h"
#define DS18B20_WRITE_SCRATCHPAD 0x4E
#define DS18B20_READ_SCRATCHPAD 0xBE
#define DS18B20_COPY_SCRATCHPAD 0x48
#define DS18B20_READ_EEPROM 0xB8
#define DS18B20_READ_PWRSUPPLY 0xB4
#define DS18B20_SEARCHROM 0xF0
#define DS18B20_SKIP_ROM 0xCC
#define DS18B20_READROM 0x33
#define DS18B20_MATCHROM 0x55
#define DS18B20_ALARMSEARCH 0xEC
#define DS18B20_CONVERT_T 0x44
#define os_sleep_ms(x) vTaskDelay(((x) + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS)
#define DS18B20_FAMILY_ID 0x28
#define DS18S20_FAMILY_ID 0x10
#ifdef DS18B20_DEBUG
#define debug(fmt, ...) printf("%s" fmt "\n", "DS18B20: ", ## __VA_ARGS__);
#else
#define debug(fmt, ...)
#endif
uint8_t ds18b20_read_all(uint8_t pin, ds_sensor_t *result) {
onewire_addr_t addr;
onewire_search_t search;
uint8_t sensor_id = 0;
onewire_search_start(&search);
while ((addr = onewire_search_next(&search, pin)) != ONEWIRE_NONE) {
uint8_t crc = onewire_crc8((uint8_t *)&addr, 7);
if (crc != (addr >> 56)){
debug("CRC check failed: %02X %02X\n", (unsigned)(addr >> 56), crc);
return 0;
}
onewire_reset(pin);
onewire_select(pin, addr);
onewire_write(pin, DS18B20_CONVERT_T);
onewire_power(pin);
vTaskDelay(750 / portTICK_PERIOD_MS);
onewire_reset(pin);
onewire_select(pin, addr);
onewire_write(pin, DS18B20_READ_SCRATCHPAD);
uint8_t get[10];
for (int k=0;k<9;k++){
get[k]=onewire_read(pin);
}
//debug("\n ScratchPAD DATA = %X %X %X %X %X %X %X %X %X\n",get[8],get[7],get[6],get[5],get[4],get[3],get[2],get[1],get[0]);
crc = onewire_crc8(get, 8);
if (crc != get[8]){
debug("CRC check failed: %02X %02X\n", get[8], crc);
return 0;
}
uint8_t temp_msb = get[1]; // Sign byte + lsbit
uint8_t temp_lsb = get[0]; // Temp data plus lsb
uint16_t temp = temp_msb << 8 | temp_lsb;
float temperature;
temperature = (temp * 625.0)/10000;
//debug("Got a DS18B20 Reading: %d.%02d\n", (int)temperature, (int)(temperature - (int)temperature) * 100);
result[sensor_id].id = sensor_id;
result[sensor_id].value = temperature;
sensor_id++;
}
return sensor_id;
}
float ds18b20_read_single(uint8_t pin) {
onewire_reset(pin);
onewire_skip_rom(pin);
onewire_write(pin, DS18B20_CONVERT_T);
onewire_power(pin);
vTaskDelay(750 / portTICK_PERIOD_MS);
onewire_reset(pin);
onewire_skip_rom(pin);
onewire_write(pin, DS18B20_READ_SCRATCHPAD);
uint8_t get[10];
for (int k=0;k<9;k++){
get[k]=onewire_read(pin);
}
//debug("\n ScratchPAD DATA = %X %X %X %X %X %X %X %X %X\n",get[8],get[7],get[6],get[5],get[4],get[3],get[2],get[1],get[0]);
uint8_t crc = onewire_crc8(get, 8);
if (crc != get[8]){
debug("CRC check failed: %02X %02X", get[8], crc);
return 0;
}
uint8_t temp_msb = get[1]; // Sign byte + lsbit
uint8_t temp_lsb = get[0]; // Temp data plus lsb
uint16_t temp = temp_msb << 8 | temp_lsb;
float temperature;
temperature = (temp * 625.0)/10000;
return temperature;
//debug("Got a DS18B20 Reading: %d.%02d\n", (int)temperature, (int)(temperature - (int)temperature) * 100);
}
bool ds18b20_measure(int pin, ds18b20_addr_t addr, bool wait) {
if (!onewire_reset(pin)) {
return false;
}
if (addr == DS18B20_ANY) {
onewire_skip_rom(pin);
} else {
onewire_select(pin, addr);
}
taskENTER_CRITICAL();
onewire_write(pin, DS18B20_CONVERT_T);
// For parasitic devices, power must be applied within 10us after issuing
// the convert command.
onewire_power(pin);
taskEXIT_CRITICAL();
if (wait) {
os_sleep_ms(750);
onewire_depower(pin);
}
return true;
}
bool ds18b20_read_scratchpad(int pin, ds18b20_addr_t addr, uint8_t *buffer) {
uint8_t crc;
uint8_t expected_crc;
if (!onewire_reset(pin)) {
return false;
}
if (addr == DS18B20_ANY) {
onewire_skip_rom(pin);
} else {
onewire_select(pin, addr);
}
onewire_write(pin, DS18B20_READ_SCRATCHPAD);
for (int i = 0; i < 8; i++) {
buffer[i] = onewire_read(pin);
}
crc = onewire_read(pin);
expected_crc = onewire_crc8(buffer, 8);
if (crc != expected_crc) {
debug("CRC check failed reading scratchpad: %02x %02x %02x %02x %02x %02x %02x %02x : %02x (expected %02x)\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7], crc, expected_crc);
return false;
}
return true;
}
float ds18b20_read_temperature(int pin, ds18b20_addr_t addr) {
uint8_t scratchpad[8];
int16_t temp;
if (!ds18b20_read_scratchpad(pin, addr, scratchpad)) {
return NAN;
}
temp = (int16_t) ((uint16_t)scratchpad[0] | (uint16_t)(scratchpad[1] << 8));
if (temp == 0x0550) {
return NAN;
}
float res;
// this was wrong - commented out, nobody uses 18S20 anymore.
// if ((uint8_t)addr == DS18B20_FAMILY_ID) {
res = (float)temp * 0.0625f;
// }
// else {
// // 18S20?
// temp = ((temp & 0xfffe) << 3) + (16 - scratchpad[6]) - 4;
// res = ((float)temp * 625.0f)/10000 - 0.25f;
// }
return res;
}
float ds18b20_measure_and_read(int pin, ds18b20_addr_t addr) {
if (!ds18b20_measure(pin, addr, true)) {
return NAN;
}
return ds18b20_read_temperature(pin, addr);
}
bool ds18b20_measure_and_read_multi(int pin, ds18b20_addr_t *addr_list, int addr_count, float *result_list) {
if (!ds18b20_measure(pin, DS18B20_ANY, true)) {
for (int i=0; i < addr_count; i++) {
result_list[i] = NAN;
}
return false;
}
return ds18b20_read_temp_multi(pin, addr_list, addr_count, result_list);
}
int ds18b20_scan_devices(int pin, ds18b20_addr_t *addr_list, int addr_count) {
onewire_search_t search;
onewire_addr_t addr;
int found = 0;
onewire_search_start(&search);
while ((addr = onewire_search_next(&search, pin)) != ONEWIRE_NONE) {
uint8_t family_id = (uint8_t)addr;
if (family_id == DS18B20_FAMILY_ID || family_id == DS18S20_FAMILY_ID) {
if (found < addr_count) {
addr_list[found] = addr;
}
found++;
}
}
return found;
}
bool ds18b20_read_temp_multi(int pin, ds18b20_addr_t *addr_list, int addr_count, float *result_list) {
bool result = true;
for (int i = 0; i < addr_count; i++) {
result_list[i] = ds18b20_read_temperature(pin, addr_list[i]);
if (isnan(result_list[i])) {
result = false;
}
}
return result;
}
+158
View File
@@ -0,0 +1,158 @@
#ifndef DRIVER_DS18B20_H_
#define DRIVER_DS18B20_H_
#include "onewire.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @file ds18b20.h
*
* Communicate with the DS18B20 family of one-wire temperature sensor ICs.
*
*/
typedef onewire_addr_t ds18b20_addr_t;
/** An address value which can be used to indicate "any device on the bus" */
#define DS18B20_ANY ONEWIRE_NONE
/** Find the addresses of all DS18B20 devices on the bus.
*
* Scans the bus for all devices and places their addresses in the supplied
* array. If there are more than `addr_count` devices on the bus, only the
* first `addr_count` are recorded.
*
* @param pin The GPIO pin connected to the DS18B20 bus
* @param addr_list A pointer to an array of ds18b20_addr_t values. This
* will be populated with the addresses of the found
* devices.
* @param addr_count Number of slots in the `addr_list` array. At most this
* many addresses will be returned.
*
* @returns The number of devices found. Note that this may be less than,
* equal to, or more than `addr_count`, depending on how many DS18B20 devices
* are attached to the bus.
*/
int ds18b20_scan_devices(int pin, ds18b20_addr_t *addr_list, int addr_count);
/** Tell one or more sensors to perform a temperature measurement and
* conversion (CONVERT_T) operation. This operation can take up to 750ms to
* complete.
*
* If `wait=true`, this routine will automatically drive the pin high for the
* necessary 750ms after issuing the command to ensure parasitically-powered
* devices have enough power to perform the conversion operation (for
* non-parasitically-powered devices, this is not necessary but does not
* hurt). If `wait=false`, this routine will drive the pin high, but will
* then return immediately. It is up to the caller to wait the requisite time
* and then depower the bus using onewire_depower() or by issuing another
* command once conversion is done.
*
* @param pin The GPIO pin connected to the DS18B20 device
* @param addr The 64-bit address of the device on the bus. This can be set
* to ::DS18B20_ANY to send the command to all devices on the bus
* at the same time.
* @param wait Whether to wait for the necessary 750ms for the DS18B20 to
* finish performing the conversion before returning to the
* caller (You will normally want to do this).
*
* @returns `true` if the command was successfully issued, or `false` on error.
*/
bool ds18b20_measure(int pin, ds18b20_addr_t addr, bool wait);
/** Read the value from the last CONVERT_T operation.
*
* This should be called after ds18b20_measure() to fetch the result of the
* temperature measurement.
*
* @param pin The GPIO pin connected to the DS18B20 device
* @param addr The 64-bit address of the device to read. This can be set
* to ::DS18B20_ANY to read any device on the bus (but note
* that this will only work if there is exactly one device
* connected, or they will corrupt each others' transmissions)
*
* @returns The temperature in degrees Celsius, or NaN if there was an error.
*/
float ds18b20_read_temperature(int pin, ds18b20_addr_t addr);
/** Read the value from the last CONVERT_T operation for multiple devices.
*
* This should be called after ds18b20_measure() to fetch the result of the
* temperature measurement.
*
* @param pin The GPIO pin connected to the DS18B20 bus
* @param addr_list A list of addresses for devices to read.
* @param addr_count The number of entries in `addr_list`.
* @param result_list An array of floats to hold the returned temperature
* values. It should have at least `addr_count` entries.
*
* @returns `true` if all temperatures were fetched successfully, or `false`
* if one or more had errors (the temperature for erroring devices will be
* returned as NaN).
*/
bool ds18b20_read_temp_multi(int pin, ds18b20_addr_t *addr_list, int addr_count, float *result_list);
/** Perform a ds18b20_measure() followed by ds18b20_read_temperature()
*
* @param pin The GPIO pin connected to the DS18B20 device
* @param addr The 64-bit address of the device to read. This can be set
* to ::DS18B20_ANY to read any device on the bus (but note
* that this will only work if there is exactly one device
* connected, or they will corrupt each others' transmissions)
*
* @returns The temperature in degrees Celsius, or NaN if there was an error.
*/
float ds18b20_measure_and_read(int pin, ds18b20_addr_t addr);
/** Perform a ds18b20_measure() followed by ds18b20_read_temp_multi()
*
* @param pin The GPIO pin connected to the DS18B20 bus
* @param addr_list A list of addresses for devices to read.
* @param addr_count The number of entries in `addr_list`.
* @param result_list An array of floats to hold the returned temperature
* values. It should have at least `addr_count` entries.
*
* @returns `true` if all temperatures were fetched successfully, or `false`
* if one or more had errors (the temperature for erroring devices will be
* returned as NaN).
*/
bool ds18b20_measure_and_read_multi(int pin, ds18b20_addr_t *addr_list, int addr_count, float *result_list);
/** Read the scratchpad data for a particular DS18B20 device.
*
* This is not generally necessary to do directly. It is done automatically
* as part of ds18b20_read_temperature().
*
* @param pin The GPIO pin connected to the DS18B20 device
* @param addr The 64-bit address of the device to read. This can be set
* to ::DS18B20_ANY to read any device on the bus (but note
* that this will only work if there is exactly one device
* connected, or they will corrupt each others' transmissions)
* @param buffer An 8-byte buffer to hold the read data.
*
* @returns `true` if the data was read successfully, or `false` on error.
*/
bool ds18b20_read_scratchpad(int pin, ds18b20_addr_t addr, uint8_t *buffer);
// The following are obsolete/deprecated APIs
typedef struct {
uint8_t id;
float value;
} ds_sensor_t;
// Scan all ds18b20 sensors on bus and return its amount.
// Result are saved in array of ds_sensor_t structure.
uint8_t ds18b20_read_all(uint8_t pin, ds_sensor_t *result);
// This method is just to demonstrate how to read
// temperature from single dallas chip.
float ds18b20_read_single(uint8_t pin);
#ifdef __cplusplus
}
#endif
#endif /* DRIVER_DS18B20_H_ */
+453
View File
@@ -0,0 +1,453 @@
#include "onewire.h"
#include "string.h"
#include "task.h"
#include <driver/gpio.h>
#define ONEWIRE_SELECT_ROM 0x55
#define ONEWIRE_SKIP_ROM 0xcc
#define ONEWIRE_SEARCH 0xf0
// Waits up to `max_wait` microseconds for the specified pin to go high.
// Returns true if successful, false if the bus never comes high (likely
// shorted).
static inline bool _onewire_wait_for_bus(int pin, int max_wait) {
bool state;
for (int i = 0; i < ((max_wait + 4) / 5); i++) {
if (gpio_get_level(pin)) break;
os_delay_us(5);
}
state = gpio_get_level(pin);
// Wait an extra 1us to make sure the devices have an adequate recovery
// time before we drive things low again.
os_delay_us(1);
return state;
}
// Perform the onewire reset function. We will wait up to 250uS for
// the bus to come high, if it doesn't then it is broken or shorted
// and we return false;
//
// Returns true if a device asserted a presence pulse, false otherwise.
//
bool onewire_reset(int pin) {
bool r;
gpio_set_direction(pin, GPIO_MODE_OUTPUT_OD);
gpio_set_level(pin, 1);
// wait until the wire is high... just in case
if (!_onewire_wait_for_bus(pin, 250)) return false;
gpio_set_level(pin, 0);
os_delay_us(480);
taskENTER_CRITICAL();
gpio_set_level(pin, 1); // allow it to float
os_delay_us(70);
r = !gpio_get_level(pin);
taskEXIT_CRITICAL();
// Wait for all devices to finish pulling the bus low before returning
if (!_onewire_wait_for_bus(pin, 410)) return false;
return r;
}
static bool _onewire_write_bit(int pin, bool v) {
if (!_onewire_wait_for_bus(pin, 10)) return false;
if (v) {
taskENTER_CRITICAL();
gpio_set_level(pin, 0); // drive output low
os_delay_us(10);
gpio_set_level(pin, 1); // allow output high
taskEXIT_CRITICAL();
os_delay_us(55);
} else {
taskENTER_CRITICAL();
gpio_set_level(pin, 0); // drive output low
os_delay_us(65);
gpio_set_level(pin, 1); // allow output high
taskEXIT_CRITICAL();
}
os_delay_us(1);
return true;
}
static int _onewire_read_bit(int pin) {
int r;
if (!_onewire_wait_for_bus(pin, 10)) return -1;
taskENTER_CRITICAL();
gpio_set_level(pin, 0);
os_delay_us(2);
gpio_set_level(pin, 1); // let pin float, pull up will raise
os_delay_us(11);
r = gpio_get_level(pin); // Must sample within 15us of start
taskEXIT_CRITICAL();
os_delay_us(48);
return r;
}
// Write a byte. The writing code uses open-drain mode and expects the pullup
// resistor to pull the line high when not driven low. If you need strong
// power after the write (e.g. DS18B20 in parasite power mode) then call
// onewire_power() after this is complete to actively drive the line high.
//
bool onewire_write(int pin, uint8_t v) {
uint8_t bitMask;
for (bitMask = 0x01; bitMask; bitMask <<= 1) {
if (!_onewire_write_bit(pin, (bitMask & v))) {
return false;
}
}
return true;
}
bool onewire_write_bytes(int pin, const uint8_t *buf, size_t count) {
size_t i;
for (i = 0; i < count; i++) {
if (!onewire_write(pin, buf[i])) {
return false;
}
}
return true;
}
// Read a byte
//
int onewire_read(int pin) {
uint8_t bitMask;
int r = 0;
int bit;
for (bitMask = 0x01; bitMask; bitMask <<= 1) {
bit = _onewire_read_bit(pin);
if (bit < 0) {
return -1;
} else if (bit) {
r |= bitMask;
}
}
return r;
}
bool onewire_read_bytes(int pin, uint8_t *buf, size_t count) {
size_t i;
int b;
for (i = 0; i < count; i++) {
b = onewire_read(pin);
if (b < 0) return false;
buf[i] = b;
}
return true;
}
bool onewire_select(int pin, onewire_addr_t addr) {
uint8_t i;
if (!onewire_write(pin, ONEWIRE_SELECT_ROM)) {
return false;
}
for (i = 0; i < 8; i++) {
if (!onewire_write(pin, addr & 0xff)) {
return false;
}
addr >>= 8;
}
return true;
}
bool onewire_skip_rom(int pin) {
return onewire_write(pin, ONEWIRE_SKIP_ROM);
}
bool onewire_power(int pin) {
// Make sure the bus is not being held low before driving it high, or we
// may end up shorting ourselves out.
if (!_onewire_wait_for_bus(pin, 10)) return false;
gpio_set_direction(pin, GPIO_MODE_OUTPUT);
gpio_set_level(pin, 1);
return true;
}
void onewire_depower(int pin) {
gpio_set_direction(pin, GPIO_MODE_OUTPUT_OD);
}
void onewire_search_start(onewire_search_t *search) {
// reset the search state
memset(search, 0, sizeof(*search));
}
void onewire_search_prefix(onewire_search_t *search, uint8_t family_code) {
uint8_t i;
search->rom_no[0] = family_code;
for (i = 1; i < 8; i++) {
search->rom_no[i] = 0;
}
search->last_discrepancy = 64;
search->last_device_found = false;
}
// Perform a search. If the next device has been successfully enumerated, its
// ROM address will be returned. If there are no devices, no further
// devices, or something horrible happens in the middle of the
// enumeration then ONEWIRE_NONE is returned. Use OneWire::reset_search() to
// start over.
//
// --- Replaced by the one from the Dallas Semiconductor web site ---
//--------------------------------------------------------------------------
// Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing
// search state.
// Return 1 : device found, ROM number in ROM_NO buffer
// 0 : device not found, end of search
//
onewire_addr_t onewire_search_next(onewire_search_t *search, int pin) {
//TODO: add more checking for read/write errors
uint8_t id_bit_number;
uint8_t last_zero, search_result;
int rom_byte_number;
int8_t id_bit, cmp_id_bit;
onewire_addr_t addr;
unsigned char rom_byte_mask;
bool search_direction;
// initialize for search
id_bit_number = 1;
last_zero = 0;
rom_byte_number = 0;
rom_byte_mask = 1;
search_result = 0;
// if the last call was not the last one
if (!search->last_device_found) {
// 1-Wire reset
if (!onewire_reset(pin)) {
// reset the search
search->last_discrepancy = 0;
search->last_device_found = false;
return ONEWIRE_NONE;
}
// issue the search command
onewire_write(pin, ONEWIRE_SEARCH);
// loop to do the search
do {
// read a bit and its complement
id_bit = _onewire_read_bit(pin);
cmp_id_bit = _onewire_read_bit(pin);
// check for no devices on 1-wire
if ((id_bit < 0) || (cmp_id_bit < 0)) {
// Read error
break;
} else if ((id_bit == 1) && (cmp_id_bit == 1)) {
break;
} else {
// all devices coupled have 0 or 1
if (id_bit != cmp_id_bit) {
search_direction = id_bit; // bit write value for search
} else {
// if this discrepancy if before the Last Discrepancy
// on a previous next then pick the same as last time
if (id_bit_number < search->last_discrepancy) {
search_direction = ((search->rom_no[rom_byte_number] & rom_byte_mask) > 0);
} else {
// if equal to last pick 1, if not then pick 0
search_direction = (id_bit_number == search->last_discrepancy);
}
// if 0 was picked then record its position in LastZero
if (!search_direction) {
last_zero = id_bit_number;
}
}
// set or clear the bit in the ROM byte rom_byte_number
// with mask rom_byte_mask
if (search_direction) {
search->rom_no[rom_byte_number] |= rom_byte_mask;
} else {
search->rom_no[rom_byte_number] &= ~rom_byte_mask;
}
// serial number search direction write bit
_onewire_write_bit(pin, search_direction);
// increment the byte counter id_bit_number
// and shift the mask rom_byte_mask
id_bit_number++;
rom_byte_mask <<= 1;
// if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask
if (rom_byte_mask == 0) {
rom_byte_number++;
rom_byte_mask = 1;
}
}
} while (rom_byte_number < 8); // loop until through all ROM bytes 0-7
// if the search was successful then
if (!(id_bit_number < 65)) {
// search successful so set last_discrepancy,last_device_found,search_result
search->last_discrepancy = last_zero;
// check for last device
if (search->last_discrepancy == 0) {
search->last_device_found = true;
}
search_result = 1;
}
}
// if no device found then reset counters so next 'search' will be like a first
if (!search_result || !search->rom_no[0]) {
search->last_discrepancy = 0;
search->last_device_found = false;
return ONEWIRE_NONE;
} else {
addr = 0;
for (rom_byte_number = 7; rom_byte_number >= 0; rom_byte_number--) {
addr = (addr << 8) | search->rom_no[rom_byte_number];
}
//printf("Ok I found something at %08x%08x...\n", (uint32_t)(addr >> 32), (uint32_t)addr);
}
return addr;
}
// The 1-Wire CRC scheme is described in Maxim Application Note 27:
// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products"
//
#if ONEWIRE_CRC8_TABLE
// This table comes from Dallas sample code where it is freely reusable,
// though Copyright (C) 2000 Dallas Semiconductor Corporation
static const uint8_t dscrc_table[] = {
0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65,
157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220,
35,125,159,193, 66, 28,254,160,225,191, 93, 3,128,222, 60, 98,
190,224, 2, 92,223,129, 99, 61,124, 34,192,158, 29, 67,161,255,
70, 24,250,164, 39,121,155,197,132,218, 56,102,229,187, 89, 7,
219,133,103, 57,186,228, 6, 88, 25, 71,165,251,120, 38,196,154,
101, 59,217,135, 4, 90,184,230,167,249, 27, 69,198,152,122, 36,
248,166, 68, 26,153,199, 37,123, 58,100,134,216, 91, 5,231,185,
140,210, 48,110,237,179, 81, 15, 78, 16,242,172, 47,113,147,205,
17, 79,173,243,112, 46,204,146,211,141,111, 49,178,236, 14, 80,
175,241, 19, 77,206,144,114, 44,109, 51,209,143, 12, 82,176,238,
50,108,142,208, 83, 13,239,177,240,174, 76, 18,145,207, 45,115,
202,148,118, 40,171,245, 23, 73, 8, 86,180,234,105, 55,213,139,
87, 9,235,181, 54,104,138,212,149,203, 41,119,244,170, 72, 22,
233,183, 85, 11,136,214, 52,106, 43,117,151,201, 74, 20,246,168,
116, 42,200,150, 21, 75,169,247,182,232, 10, 84,215,137,107, 53};
#ifndef pgm_read_byte
#define pgm_read_byte(addr) (*(const uint8_t *)(addr))
#endif
//
// Compute a Dallas Semiconductor 8 bit CRC. These show up in the ROM
// and the registers. (note: this might better be done without to
// table, it would probably be smaller and certainly fast enough
// compared to all those delayMicrosecond() calls. But I got
// confused, so I use this table from the examples.)
//
uint8_t onewire_crc8(const uint8_t *data, uint8_t len) {
uint8_t crc = 0;
while (len--) {
crc = pgm_read_byte(dscrc_table + (crc ^ *data++));
}
return crc;
}
#else
//
// Compute a Dallas Semiconductor 8 bit CRC directly.
// this is much slower, but much smaller, than the lookup table.
//
uint8_t onewire_crc8(const uint8_t *data, uint8_t len) {
uint8_t crc = 0;
while (len--) {
uint8_t inbyte = *data++;
for (int i = 8; i; i--) {
uint8_t mix = (crc ^ inbyte) & 0x01;
crc >>= 1;
if (mix) crc ^= 0x8C;
inbyte >>= 1;
}
}
return crc;
}
#endif
// Compute the 1-Wire CRC16 and compare it against the received CRC.
// Example usage (reading a DS2408):
// // Put everything in a buffer so we can compute the CRC easily.
// uint8_t buf[13];
// buf[0] = 0xF0; // Read PIO Registers
// buf[1] = 0x88; // LSB address
// buf[2] = 0x00; // MSB address
// WriteBytes(net, buf, 3); // Write 3 cmd bytes
// ReadBytes(net, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16
// if (!CheckCRC16(buf, 11, &buf[11])) {
// // Handle error.
// }
//
// @param input - Array of bytes to checksum.
// @param len - How many bytes to use.
// @param inverted_crc - The two CRC16 bytes in the received data.
// This should just point into the received data,
// *not* at a 16-bit integer.
// @param crc - The crc starting value (optional)
// @return 1, iff the CRC matches.
bool onewire_check_crc16(const uint8_t* input, size_t len, const uint8_t* inverted_crc, uint16_t crc_iv) {
uint16_t crc = ~onewire_crc16(input, len, crc_iv);
return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1];
}
// Compute a Dallas Semiconductor 16 bit CRC. This is required to check
// the integrity of data received from many 1-Wire devices. Note that the
// CRC computed here is *not* what you'll get from the 1-Wire network,
// for two reasons:
// 1) The CRC is transmitted bitwise inverted.
// 2) Depending on the endian-ness of your processor, the binary
// representation of the two-byte return value may have a different
// byte order than the two bytes you get from 1-Wire.
// @param input - Array of bytes to checksum.
// @param len - How many bytes to use.
// @param crc - The crc starting value (optional)
// @return The CRC16, as defined by Dallas Semiconductor.
uint16_t onewire_crc16(const uint8_t* input, size_t len, uint16_t crc_iv) {
uint16_t crc = crc_iv;
static const uint8_t oddparity[16] =
{ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
uint16_t i;
for (i = 0; i < len; i++) {
// Even though we're just copying a byte from the input,
// we'll be doing 16-bit computation with it.
uint16_t cdata = input[i];
cdata = (cdata ^ crc) & 0xff;
crc >>= 8;
if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4])
crc ^= 0xC001;
cdata <<= 6;
crc ^= cdata;
cdata <<= 1;
crc ^= cdata;
}
return crc;
}
+244
View File
@@ -0,0 +1,244 @@
#ifndef __ONEWIRE_H__
#define __ONEWIRE_H__
#include "FreeRTOS.h"
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @file onewire.h
*
* Routines to access devices using the Dallas Semiconductor 1-Wire(tm)
* protocol.
*/
/** Select the table-lookup method of computing the 8-bit CRC
* by setting this to 1 during compilation. The lookup table enlarges code
* size by about 250 bytes. By default, a slower but very compact algorithm
* is used.
*/
#ifndef ONEWIRE_CRC8_TABLE
#define ONEWIRE_CRC8_TABLE 0
#endif
/** Type used to hold all 1-Wire device ROM addresses (64-bit) */
typedef uint64_t onewire_addr_t;
/** Structure to contain the current state for onewire_search_next(), etc */
typedef struct {
uint8_t rom_no[8];
uint8_t last_discrepancy;
bool last_device_found;
} onewire_search_t;
/** ::ONEWIRE_NONE is an invalid ROM address that will never occur in a device
* (CRC mismatch), and so can be useful as an indicator for "no-such-device",
* etc.
*/
#define ONEWIRE_NONE ((onewire_addr_t)(0xffffffffffffffffLL))
/** Perform a 1-Wire reset cycle.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
*
* @returns `true` if at least one device responds with a presence pulse,
* `false` if no devices were detected (or the bus is shorted, etc)
*/
bool onewire_reset(int pin);
/** Issue a 1-Wire rom select command to select a particular device.
*
* It is necessary to call onewire_reset() before calling this function.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
* @param addr The ROM address of the device to select
*
* @returns `true` if the "ROM select" command could be succesfully issued,
* `false` if there was an error.
*/
bool onewire_select(int pin, const onewire_addr_t addr);
/** Issue a 1-Wire "skip ROM" command to select *all* devices on the bus.
*
* It is necessary to call onewire_reset() before calling this function.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
*
* @returns `true` if the "skip ROM" command could be succesfully issued,
* `false` if there was an error.
*/
bool onewire_skip_rom(int pin);
/** Write a byte on the onewire bus.
*
* The writing code uses open-drain mode and expects the pullup resistor to
* pull the line high when not driven low. If you need strong power after the
* write (e.g. DS18B20 in parasite power mode) then call onewire_power() after
* this is complete to actively drive the line high.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
* @param v The byte value to write
*
* @returns `true` if successful, `false` on error.
*/
bool onewire_write(int pin, uint8_t v);
/** Write multiple bytes on the 1-Wire bus.
*
* See onewire_write() for more info.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
* @param buf A pointer to the buffer of bytes to be written
* @param count Number of bytes to write
*
* @returns `true` if all bytes written successfully, `false` on error.
*/
bool onewire_write_bytes(int pin, const uint8_t *buf, size_t count);
/** Read a byte from a 1-Wire device.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
*
* @returns the read byte on success, negative value on error.
*/
int onewire_read(int pin);
/** Read multiple bytes from a 1-Wire device.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
* @param buf A pointer to the buffer to contain the read bytes
* @param count Number of bytes to read
*
* @returns `true` on success, `false` on error.
*/
bool onewire_read_bytes(int pin, uint8_t *buf, size_t count);
/** Actively drive the bus high to provide extra power for certain operations
* of parasitically-powered devices.
*
* For parasitically-powered devices which need more power than can be
* provided via the normal pull-up resistor, it may be necessary for some
* operations to drive the bus actively high. This function can be used to
* perform that operation.
*
* The bus can be depowered once it is no longer needed by calling
* onewire_depower(), or it will be depowered automatically the next time
* onewire_reset() is called to start another command.
*
* Note: Make sure the device(s) you are powering will not pull more current
* than the ESP8266 is able to supply via its GPIO pins (this is especially
* important when multiple devices are on the same bus and they are all
* performing a power-intensive operation at the same time (i.e. multiple
* DS18B20 sensors, which have all been given a "convert T" operation by using
* onewire_skip_rom())).
*
* Note: This routine will check to make sure that the bus is already high
* before driving it, to make sure it doesn't attempt to drive it high while
* something else is pulling it low (which could cause a reset or damage the
* ESP8266).
*
* @param pin The GPIO pin connected to the 1-Wire bus.
*
* @returns `true` on success, `false` on error.
*/
bool onewire_power(int pin);
/** Stop forcing power onto the bus.
*
* You only need to do this if you previously called onewire_power() to drive
* the bus high and now want to allow it to float instead. Note that
* onewire_reset() will also automatically depower the bus first, so you do
* not need to call this first if you just want to start a new operation.
*
* @param pin The GPIO pin connected to the 1-Wire bus.
*/
void onewire_depower(int pin);
/** Clear the search state so that it will start from the beginning on the next
* call to onewire_search_next().
*
* @param search The onewire_search_t structure to reset.
*/
void onewire_search_start(onewire_search_t *search);
/** Setup the search to search for devices with the specified "family code".
*
* @param search The onewire_search_t structure to update.
* @param family_code The "family code" to search for.
*/
void onewire_search_prefix(onewire_search_t *search, uint8_t family_code);
/** Search for the next device on the bus.
*
* The order of returned device addresses is deterministic. You will always
* get the same devices in the same order.
*
* @returns the address of the next device on the bus, or ::ONEWIRE_NONE if
* there is no next address. ::ONEWIRE_NONE might also mean that the bus is
* shorted, there are no devices, or you have already retrieved all of them.
*
* It might be a good idea to check the CRC to make sure you didn't get
* garbage.
*/
onewire_addr_t onewire_search_next(onewire_search_t *search, int pin);
/** Compute a Dallas Semiconductor 8 bit CRC.
*
* These are used in the ROM address and scratchpad registers to verify the
* transmitted data is correct.
*/
uint8_t onewire_crc8(const uint8_t *data, uint8_t len);
/** Compute the 1-Wire CRC16 and compare it against the received CRC.
*
* Example usage (reading a DS2408):
* @code
* // Put everything in a buffer so we can compute the CRC easily.
* uint8_t buf[13];
* buf[0] = 0xF0; // Read PIO Registers
* buf[1] = 0x88; // LSB address
* buf[2] = 0x00; // MSB address
* onewire_write_bytes(pin, buf, 3); // Write 3 cmd bytes
* onewire_read_bytes(pin, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16
* if (!onewire_check_crc16(buf, 11, &buf[11])) {
* // TODO: Handle error.
* }
* @endcode
*
* @param input Array of bytes to checksum.
* @param len Number of bytes in `input`
* @param inverted_crc The two CRC16 bytes in the received data.
* This should just point into the received data,
* *not* at a 16-bit integer.
* @param crc_iv The crc starting value (optional)
*
* @returns `true` if the CRC matches, `false` otherwise.
*/
bool onewire_check_crc16(const uint8_t* input, size_t len, const uint8_t* inverted_crc, uint16_t crc_iv);
/** Compute a Dallas Semiconductor 16 bit CRC.
*
* This is required to check the integrity of data received from many 1-Wire
* devices. Note that the CRC computed here is *not* what you'll get from the
* 1-Wire network, for two reasons:
* 1. The CRC is transmitted bitwise inverted.
* 2. Depending on the endian-ness of your processor, the binary
* representation of the two-byte return value may have a different
* byte order than the two bytes you get from 1-Wire.
*
* @param input Array of bytes to checksum.
* @param len How many bytes are in `input`.
* @param crc_iv The crc starting value (optional)
*
* @returns the CRC16, as defined by Dallas Semiconductor.
*/
uint16_t onewire_crc16(const uint8_t* input, size_t len, uint16_t crc_iv);
#ifdef __cplusplus
}
#endif
#endif /* __ONEWIRE_H__ */