Добавлена терминалка от андрея, +проект вынесен в отдельную папку
This commit is contained in:
555
py_project/Core/Dallas/dallas_tools.c
Normal file
555
py_project/Core/Dallas/dallas_tools.c
Normal file
@@ -0,0 +1,555 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file dallas_tools.c
|
||||
* @brief Драйвер для работы с датчиками температуры DS18B20
|
||||
* @author MicroTechnics (microtechnics.ru)
|
||||
******************************************************************************
|
||||
@details
|
||||
Этот файл содержит реализацию функций для работы с датчиком DS18B20
|
||||
через интерфейс 1-Wire. Он предоставляет функции для чтения и записи
|
||||
конфигурации, выполнения измерений и обработки полученных данных.
|
||||
*****************************************************************************/
|
||||
|
||||
|
||||
/* Includes ----------------------------------------------------------------*/
|
||||
|
||||
#include "dallas_tools.h"
|
||||
#include "string.h"
|
||||
|
||||
|
||||
/* Declarations and definitions --------------------------------------------*/
|
||||
DALLAS_HandleTypeDef hdallas1;
|
||||
|
||||
/* Functions ---------------------------------------------------------------*/
|
||||
/**
|
||||
* @brief Функция для нахождения нового датчика на место потерянного
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_ReplaceLostedSensor(DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
|
||||
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
result = Dallas_IsConnected(sensor);
|
||||
|
||||
if(sensor->isLost)
|
||||
{
|
||||
if(DS18B20_Search(sensor->hdallas->ds_devices, sensor->hdallas->onewire) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
if(sensor->Init.init_func(sensor->hdallas, sensor) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
else
|
||||
{
|
||||
return HAL_BUSY; // датчик не потерян
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Функция для иниицализации нового датчика в структуре
|
||||
* @param hdallas Указатель на хендл для общения с датчиками
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_AddNewSensors(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
|
||||
if(hdallas == NULL)
|
||||
return HAL_ERROR;
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
sensor->hdallas = hdallas;
|
||||
|
||||
result = sensor->Init.init_func(hdallas, sensor);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @brief Инициализирует структуру датчика по ROM
|
||||
* @param hdallas Указатель на хендл для общения с датчиками
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_SensorInitByROM(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
|
||||
if(hdallas == NULL)
|
||||
return HAL_ERROR;
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint8_t ROM[8] = {0};
|
||||
ROM[0] = (sensor->Init.InitParam >> (7*8)) & 0xFF;
|
||||
ROM[1] = (sensor->Init.InitParam >> (6*8)) & 0xFF;
|
||||
ROM[2] = (sensor->Init.InitParam >> (5*8)) & 0xFF;
|
||||
ROM[3] = (sensor->Init.InitParam >> (4*8)) & 0xFF;
|
||||
ROM[4] = (sensor->Init.InitParam >> (3*8)) & 0xFF;
|
||||
ROM[5] = (sensor->Init.InitParam >> (2*8)) & 0xFF;
|
||||
ROM[6] = (sensor->Init.InitParam >> (1*8)) & 0xFF;
|
||||
ROM[7] = (sensor->Init.InitParam >> (0*8)) & 0xFF;
|
||||
|
||||
if(DS18B20_IsValidAddress(ROM) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint8_t comparebytes = DALLAS_ROM_SIZE;
|
||||
int ROM_ind = 0;
|
||||
for(int i = 0; i < hdallas->onewire->RomCnt; i++)
|
||||
{
|
||||
comparebytes = DALLAS_ROM_SIZE;
|
||||
for(int rom_byte = 0; rom_byte < DALLAS_ROM_SIZE; rom_byte++)
|
||||
{
|
||||
if(hdallas->ds_devices->DevAddr[i][rom_byte] == ROM[rom_byte])
|
||||
comparebytes--;
|
||||
}
|
||||
if(comparebytes == 0)
|
||||
{
|
||||
ROM_ind = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Проверка присутствует ли выбранный датчик на линии */
|
||||
if(comparebytes == 0)
|
||||
{
|
||||
|
||||
result = Dallas_SensorInit(hdallas, sensor, &hdallas->ds_devices->DevAddr[ROM_ind]);
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
return HAL_ERROR;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @brief Инициализирует структуру датчика по пользовательским байтам
|
||||
* @param hdallas Указатель на хендл для общения с датчиками
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_SensorInitByUserBytes(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
|
||||
if(hdallas == NULL)
|
||||
return HAL_ERROR;
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint8_t UserByte1 = sensor->Init.InitParam & 0xFF;
|
||||
uint8_t UserByte2 = sensor->Init.InitParam >> 8;
|
||||
uint8_t UserByte3 = (sensor->Init.InitParam >> 16) & 0xFF;
|
||||
uint8_t UserByte4 = (sensor->Init.InitParam >> 16) >> 8;
|
||||
uint8_t UserByte12Cmp = 0;
|
||||
uint8_t UserByte34Cmp = 0;
|
||||
|
||||
for(int i = 0; i < hdallas->onewire->RomCnt; i++)
|
||||
{
|
||||
/* Проверка присутствует ли выбранный датчик на линии */
|
||||
result = DS18B20_ReadScratchpad(hdallas->onewire, (uint8_t *)&hdallas->ds_devices->DevAddr[i], (uint8_t *)&hdallas->scratchpad);
|
||||
if (result != HAL_OK)
|
||||
return result;
|
||||
|
||||
/* Сравнение UserByte1 и UserByte2, если они не равны нулю */
|
||||
if((sensor->Init.InitParam & 0xFFFF) != NULL)
|
||||
{
|
||||
if( (hdallas->scratchpad.tHighRegister == UserByte1) &&
|
||||
(hdallas->scratchpad.tLowRegister == UserByte2))
|
||||
{
|
||||
UserByte12Cmp = 1;
|
||||
}
|
||||
}/* Если сравнение UserByte1 и UserByte2 не выбрано, то считаем что они совпадают */
|
||||
else
|
||||
{
|
||||
UserByte12Cmp = 1;
|
||||
}
|
||||
/* Сравнение UserByte3 и UserByte4, если они не равны нулю */
|
||||
if((sensor->Init.InitParam & 0xFFFF0000) != NULL)
|
||||
{
|
||||
if( (hdallas->scratchpad.UserByte3 == UserByte3) &&
|
||||
(hdallas->scratchpad.UserByte4 == UserByte4))
|
||||
{
|
||||
UserByte34Cmp = 1;
|
||||
}
|
||||
}/* Если сравнение UserByte3 и UserByte4 не выбрано, то считаем что они одинаковые */
|
||||
else
|
||||
{
|
||||
UserByte34Cmp = 1;
|
||||
}
|
||||
/* Если нашли нужный датчик - завершаем поиск */
|
||||
if(UserByte12Cmp && UserByte34Cmp)
|
||||
{
|
||||
// sensor->isInitialized = 1;
|
||||
// sensor->Init.init_func = (HAL_StatusTypeDef (*)())Dallas_SensorInitByUserBytes;
|
||||
result = Dallas_SensorInit(hdallas, sensor, &hdallas->ds_devices->DevAddr[i]);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
sensor->sensROM = 0;
|
||||
/* Возвращаем ошибку если не нашли */
|
||||
return HAL_ERROR;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Инициализирует структуру датчика по порядковому номеру
|
||||
* @param hdallas Указатель на хендл для общения с датчиками
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
* @details Порядковый номер датчика в списке найденных.
|
||||
* Т.е. каким по счету этот датчик был найден
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_SensorInitByInd(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
|
||||
if(hdallas == NULL)
|
||||
return HAL_ERROR;
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
result = Dallas_SensorInit(hdallas, sensor, &hdallas->ds_devices->DevAddr[sensor->Init.InitParam]);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Инициализирует датчик для работы
|
||||
* @param hdallas Указатель на хендл для общения с датчиками
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @param ROM ROM датчика, который надо инициализировать
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_SensorInit(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor, uint8_t (*ROM)[DALLAS_ROM_SIZE])
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
if(hdallas == 0)
|
||||
return HAL_ERROR;
|
||||
|
||||
sensor->hdallas = hdallas;
|
||||
sensor->sensROM = 0;
|
||||
sensor->sensROM = *(uint64_t *)(ROM);
|
||||
// for(int i = 0; i < DALLAS_ROM_SIZE; i++)
|
||||
// sensor->sensROM |= ((uint64_t)(*ROM)[i] << (56 - 8*i));
|
||||
|
||||
/* Проверка присутствует ли выбранный датчик на линии */
|
||||
result = Dallas_ReadScratchpad(sensor);
|
||||
if (result == HAL_OK)
|
||||
{
|
||||
/* Установка разрешения */
|
||||
result = DS18B20_SetResolution(hdallas->onewire, (uint8_t *)ROM, sensor->Init.Resolution);
|
||||
if (result == HAL_OK)
|
||||
{
|
||||
sensor->isInitialized = 1;
|
||||
return HAL_OK;
|
||||
}
|
||||
else
|
||||
{
|
||||
sensor->isInitialized = 0;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sensor->isInitialized = 0;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Деинициализирует структуру датчика
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_SensorDeInit(DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
memset(&sensor->f, 0, sizeof(sensor->f));
|
||||
sensor->isConnected = 0;
|
||||
sensor->isInitialized = 0;
|
||||
sensor->isLost = 0;
|
||||
sensor->temperature = 0;
|
||||
sensor->sensROM = 0;
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Запускает измерение температуры на всех датчиках
|
||||
* @param hdallas Указатель на хендл для общения с датчиками
|
||||
* @param waitCondition Условие ожидания завершения преобразования
|
||||
* @param dallas_delay_ms Время ожидания окончания конверсии
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_StartConvertTAll(DALLAS_HandleTypeDef *hdallas, DALLAS_WaitConvertionTypeDef waitCondition, uint8_t dallas_delay_ms)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
uint8_t rxDummyData;
|
||||
|
||||
if(hdallas == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
// Отправка команды начала преобразования температуры
|
||||
result = DS18B20_StartConvTAll(hdallas->onewire);
|
||||
if(result != HAL_OK)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
// // Проверка что преобразование началось
|
||||
// if(OneWire_ReadBit(onewire) == 1)
|
||||
// return HAL_ERROR;
|
||||
|
||||
// Ожидание завершения преобразования, путем проверки шины
|
||||
if (waitCondition == DALLAS_WAIT_BUS)
|
||||
{
|
||||
result = DS18B20_WaitForEndConvertion(hdallas->onewire);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Ожидание завершения преобразования, путем задержки
|
||||
if (waitCondition == DALLAS_WAIT_DELAY)
|
||||
{
|
||||
uint32_t delayValueMs = 0;
|
||||
|
||||
switch (dallas_delay_ms)
|
||||
{
|
||||
case DALLAS_CONFIG_9_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_9_BITS;
|
||||
break;
|
||||
|
||||
case DALLAS_CONFIG_10_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_10_BITS;
|
||||
break;
|
||||
|
||||
case DALLAS_CONFIG_11_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_11_BITS;
|
||||
break;
|
||||
|
||||
case DALLAS_CONFIG_12_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_12_BITS;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
HAL_Delay(delayValueMs);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Измеряет температуру на датчике
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @param waitCondition Условие ожидания завершения преобразования
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_ConvertT(DALLAS_SensorHandleTypeDef *sensor, DALLAS_WaitConvertionTypeDef waitCondition)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
uint8_t rxDummyData;
|
||||
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
if(sensor->isInitialized == 0)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Проверка присутствует ли выбранный датчик на линии */
|
||||
result = Dallas_IsConnected(sensor);
|
||||
if (result != HAL_OK)
|
||||
return result;
|
||||
|
||||
// Отправка команды начала преобразования температуры
|
||||
result = DS18B20_StartConvT(sensor->hdallas->onewire, (uint8_t *)&sensor->sensROM);
|
||||
if(result != HAL_OK)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
// Ожидание завершения преобразования, путем проверки шины
|
||||
if (waitCondition == DALLAS_WAIT_BUS)
|
||||
{
|
||||
result = DS18B20_WaitForEndConvertion(sensor->hdallas->onewire);
|
||||
if(result == HAL_TIMEOUT)
|
||||
{
|
||||
sensor->f.timeout_convertion_cnt++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Ожидание завершения преобразования, путем задержки
|
||||
if (waitCondition == DALLAS_WAIT_DELAY)
|
||||
{
|
||||
uint32_t delayValueMs = 0;
|
||||
|
||||
switch (sensor->hdallas->scratchpad.ConfigRegister)
|
||||
{
|
||||
case DALLAS_CONFIG_9_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_9_BITS;
|
||||
break;
|
||||
|
||||
case DALLAS_CONFIG_10_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_10_BITS;
|
||||
break;
|
||||
|
||||
case DALLAS_CONFIG_11_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_11_BITS;
|
||||
break;
|
||||
|
||||
case DALLAS_CONFIG_12_BITS:
|
||||
delayValueMs = DALLAS_DELAY_MS_12_BITS;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
HAL_Delay(delayValueMs);
|
||||
}
|
||||
|
||||
/* Не считываем температуру, если не выбрано ожидание окончания преобразования */
|
||||
if(waitCondition != DALLAS_WAIT_NONE)
|
||||
{
|
||||
result = Dallas_ReadTemperature(sensor);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Читает измеренную датчиком температуру
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_ReadTemperature(DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
if(sensor->isInitialized == 0)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Проверка присутствует ли выбранный датчик на линии */
|
||||
result = Dallas_IsConnected(sensor);
|
||||
if (result != HAL_OK)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
result = DS18B20_CalcTemperature(sensor->hdallas->onewire, (uint8_t *)&sensor->sensROM, (uint8_t *)&sensor->hdallas->scratchpad, &sensor->temperature);
|
||||
|
||||
if (result != HAL_OK)
|
||||
{
|
||||
sensor->f.read_temperature_err_cnt++;
|
||||
return result;
|
||||
}
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Проверяет подключен ли датчик (чтение scratchpad)
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @retval HAL Status
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_IsConnected(DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
result = Dallas_ReadScratchpad(sensor);
|
||||
|
||||
if (result == HAL_OK)
|
||||
{
|
||||
sensor->isConnected = 1;
|
||||
sensor->isLost = 0;
|
||||
return HAL_OK;
|
||||
}
|
||||
else
|
||||
{
|
||||
sensor->temperature = 0;
|
||||
if(sensor->isConnected == 1)
|
||||
{
|
||||
sensor->f.disconnect_cnt++;
|
||||
}
|
||||
sensor->isLost = 1;
|
||||
sensor->isConnected = 0;
|
||||
|
||||
// Dallas_ReplaceLostedSensor(sensor);
|
||||
return HAL_BUSY; // использую busy, чтобы отличать ситуацию от HAL_ERROR
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Записывает пользовательские байты
|
||||
* @param sensor Указатель на структуру датчика
|
||||
* @param UserBytes12 Пользовательские байты 1 и 2
|
||||
* @param UserBytes34 Пользовательские байты 3 и 4
|
||||
* @param UserBytesMask Маска, какие байты записывать, а какие нет
|
||||
* @retval HAL Status
|
||||
* @details старший байт - UserByte4/UserByte2, младший - UserByte3/UserByte1.
|
||||
*/
|
||||
HAL_StatusTypeDef Dallas_WriteUserBytes(DALLAS_SensorHandleTypeDef *sensor, uint16_t UserBytes12, uint16_t UserBytes34, uint8_t UserBytesMask)
|
||||
{
|
||||
HAL_StatusTypeDef result;
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
if(sensor->isInitialized == 0)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Проверка присутствует ли выбранный датчик на линии */
|
||||
result = Dallas_IsConnected(sensor);
|
||||
if (result != HAL_OK)
|
||||
return result;
|
||||
|
||||
result = DS18B20_WriteUserBytes(sensor->hdallas->onewire, (uint8_t *)&sensor->sensROM, UserBytes12, UserBytes34, UserBytesMask);
|
||||
if (result != HAL_OK)
|
||||
{
|
||||
sensor->f.write_err_cnt++;
|
||||
return result;
|
||||
}
|
||||
result = Dallas_ReadScratchpad(sensor);
|
||||
if (result != HAL_OK)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
HAL_StatusTypeDef Dallas_ReadScratchpad(DALLAS_SensorHandleTypeDef *sensor)
|
||||
{
|
||||
if(sensor == NULL)
|
||||
return HAL_ERROR;
|
||||
return DS18B20_ReadScratchpad(sensor->hdallas->onewire, (uint8_t *)&sensor->sensROM, (uint8_t *)&sensor->hdallas->scratchpad);
|
||||
}
|
||||
148
py_project/Core/Dallas/dallas_tools.h
Normal file
148
py_project/Core/Dallas/dallas_tools.h
Normal file
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file dallas_tools.h
|
||||
* @brief Драйвер датчиков температуры DALLAS
|
||||
******************************************************************************
|
||||
* Этот файл предоставляет объявления и определения для работы с датчиками
|
||||
* температуры DS18B20. Он включает структуры данных, макросы и прототипы
|
||||
* функций для инициализации, чтения температуры
|
||||
* и управления датчиками.
|
||||
*
|
||||
* Работа с датчиками ведётся через протокол OneWire.
|
||||
*****************************************************************************/
|
||||
|
||||
#ifndef DALLAS_TOOLS_H
|
||||
#define DALLAS_TOOLS_H
|
||||
|
||||
|
||||
|
||||
/* Includes -----------------------------------------------------------------*/
|
||||
#include "ds18b20_driver.h"
|
||||
#include "onewire.h"
|
||||
|
||||
/* Определения пользовательских байтов для записи чтения */
|
||||
#define DALLAS_USER_BYTE_1 (1<<0) ///< Первый пользовательский байт
|
||||
#define DALLAS_USER_BYTE_2 (1<<1) ///< Второй пользовательский байт
|
||||
#define DALLAS_USER_BYTE_3 (1<<2) ///< Третий пользовательский байт
|
||||
#define DALLAS_USER_BYTE_4 (1<<3) ///< Четвёртый пользовательский байт
|
||||
|
||||
#define DALLAS_USER_BYTE_12 (DALLAS_USER_BYTE_1|DALLAS_USER_BYTE_2) ///< Первые два байта
|
||||
#define DALLAS_USER_BYTE_34 (DALLAS_USER_BYTE_3|DALLAS_USER_BYTE_4) ///< Вторые два байта
|
||||
#define DALLAS_USER_BYTE_ALL (DALLAS_USER_BYTE_12|DALLAS_USER_BYTE_34) ///< Все пользовательские байты
|
||||
|
||||
/* Declarations and definitions ---------------------------------------------*/
|
||||
#define DALLAS_ROM_SIZE 8
|
||||
|
||||
#define DALLAS_CONFIG_9_BITS 0x1F
|
||||
#define DALLAS_CONFIG_10_BITS 0x3F
|
||||
#define DALLAS_CONFIG_11_BITS 0x5F
|
||||
#define DALLAS_CONFIG_12_BITS 0x7F
|
||||
|
||||
#define DALLAS_DELAY_MS_9_BITS 94
|
||||
#define DALLAS_DELAY_MS_10_BITS 188
|
||||
#define DALLAS_DELAY_MS_11_BITS 375
|
||||
#define DALLAS_DELAY_MS_12_BITS 750
|
||||
#define DALLAS_DELAY_MS_MAX DALLAS_DELAY_MS_12_BITS
|
||||
|
||||
/** @brief Структура Scratchpad датчика DALLAS */
|
||||
typedef struct
|
||||
{
|
||||
uint8_t TemperatureLSB; ///< Младший байт температуры
|
||||
uint8_t TemperatureMSB; ///< Старший байт температуры
|
||||
uint8_t tHighRegister; ///< Верхний температурный порог
|
||||
uint8_t tLowRegister; ///< Нижний температурный порог
|
||||
uint8_t ConfigRegister; ///< Конфигурационный регистр
|
||||
uint8_t reserved; ///< Зарезервировано
|
||||
uint8_t UserByte3; ///< Пользовательский байт 3
|
||||
uint8_t UserByte4; ///< Пользовательский байт 4
|
||||
uint8_t ScratchpadCRC; ///< Контрольная сумма
|
||||
}DALLAS_ScratchpadTypeDef;
|
||||
|
||||
/** @brief Структура флагов ошибок датчиков DALLAS */
|
||||
typedef struct
|
||||
{
|
||||
uint8_t disconnect_cnt; ///< Счетчик отключений датчика
|
||||
uint8_t read_temperature_err_cnt; ///< Счетчик ошибок чтения температуры
|
||||
uint8_t timeout_convertion_cnt; ///< Счетчик ошибок таймаута конвертации
|
||||
uint8_t write_err_cnt; ///< Счетчик других ошибок
|
||||
}DALLAS_FlagsTypeDef;
|
||||
|
||||
|
||||
/** @brief Структура инициализации датчика DALLAS */
|
||||
typedef struct __packed
|
||||
{
|
||||
uint64_t InitParam; ///< Параметр для инициализации: ROM/UserBytes/Индекс
|
||||
uint8_t Resolution; ///< Разрешение датчика
|
||||
HAL_StatusTypeDef (*init_func)(); ///< Функция инициализации
|
||||
} DALLAS_InitStructTypeDef;
|
||||
|
||||
|
||||
|
||||
/** @brief Cтруктура обработчика DALLAS для общения с датчиком*/
|
||||
typedef struct
|
||||
{
|
||||
OneWire_t *onewire;
|
||||
DS18B20_Drv_t *ds_devices;
|
||||
DALLAS_ScratchpadTypeDef scratchpad;
|
||||
}DALLAS_HandleTypeDef;
|
||||
extern DALLAS_HandleTypeDef hdallas1;
|
||||
|
||||
/** @brief Основная структура обработчика датчика DALLAS */
|
||||
typedef struct
|
||||
{
|
||||
unsigned isConnected:1; ///< Флаг соединения
|
||||
unsigned isInitialized:1; ///< Флаг инициализации
|
||||
unsigned isLost:1; ///< Флаг потери связи
|
||||
|
||||
DALLAS_HandleTypeDef *hdallas;
|
||||
uint64_t sensROM; ///< ROM-код датчика
|
||||
|
||||
float temperature; ///< Текущая температура
|
||||
|
||||
DALLAS_InitStructTypeDef Init; ///< Структура инициализации
|
||||
DALLAS_FlagsTypeDef f; ///< Флаги
|
||||
} DALLAS_SensorHandleTypeDef;
|
||||
|
||||
|
||||
|
||||
/** @brief Варианты ожидания окончания конверсии */
|
||||
typedef enum
|
||||
{
|
||||
DALLAS_WAIT_NONE = 0x00, ///< Без ожидания окончания конверсии
|
||||
DALLAS_WAIT_BUS = 0x01, ///< Ожидание окончания конверсии по шине (опрос датчиков - чтение бита)
|
||||
DALLAS_WAIT_DELAY = 0x02, ///< Без ожидания окончания через задержку (максимальная задержка для заданной разрядности)
|
||||
} DALLAS_WaitConvertionTypeDef;
|
||||
|
||||
|
||||
|
||||
/* Functions ---------------------------------------------------------------*/
|
||||
|
||||
/* Функция для нахождения нового датчика на место потерянного */
|
||||
HAL_StatusTypeDef Dallas_ReplaceLostedSensor(DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Функция для иниицализации нового датчика в структуре */
|
||||
HAL_StatusTypeDef Dallas_AddNewSensors(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Инициализирует структуру датчика по ROM */
|
||||
HAL_StatusTypeDef Dallas_SensorInitByROM(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Инициализирует структуру датчика по пользовательским байтам */
|
||||
HAL_StatusTypeDef Dallas_SensorInitByUserBytes(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Инициализирует структуру датчика по порядковому номеру */
|
||||
HAL_StatusTypeDef Dallas_SensorInitByInd(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Инициализирует датчик для работы */
|
||||
HAL_StatusTypeDef Dallas_SensorInit(DALLAS_HandleTypeDef *hdallas, DALLAS_SensorHandleTypeDef *sensor, uint8_t (*ROM)[DALLAS_ROM_SIZE]);
|
||||
/* Деинициализирует структуру датчика */
|
||||
HAL_StatusTypeDef Dallas_SensorDeInit(DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Запускает измерение температуры на всех датчиках */
|
||||
HAL_StatusTypeDef Dallas_StartConvertTAll(DALLAS_HandleTypeDef *hdallas, DALLAS_WaitConvertionTypeDef waitCondition, uint8_t dallas_delay_ms);
|
||||
/* Измеряет температуру на датчике */
|
||||
HAL_StatusTypeDef Dallas_ConvertT(DALLAS_SensorHandleTypeDef *sensor, DALLAS_WaitConvertionTypeDef waitCondition);
|
||||
/* Читает измеренную датчиком температуру */
|
||||
HAL_StatusTypeDef Dallas_ReadTemperature(DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Проверяет подключен ли датчик (чтение scratchpad) */
|
||||
HAL_StatusTypeDef Dallas_IsConnected(DALLAS_SensorHandleTypeDef *sensor);
|
||||
/* Записывает пользовательские байты */
|
||||
HAL_StatusTypeDef Dallas_WriteUserBytes(DALLAS_SensorHandleTypeDef *sensor, uint16_t UserBytes12, uint16_t UserBytes34, uint8_t UserBytesMask);
|
||||
/* Записывает пользовательские байты */
|
||||
HAL_StatusTypeDef Dallas_ReadScratchpad(DALLAS_SensorHandleTypeDef *sensor);
|
||||
|
||||
|
||||
#endif // #ifndef DALLAS_TOOLS_H
|
||||
607
py_project/Core/Dallas/ds18b20_driver.c
Normal file
607
py_project/Core/Dallas/ds18b20_driver.c
Normal file
@@ -0,0 +1,607 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file ds18b20_driver.c
|
||||
* @brief This file includes the HAL/LL driver for DS18B20 1-Wire Digital
|
||||
* Thermometer
|
||||
******************************************************************************
|
||||
*/
|
||||
#include "ds18b20_driver.h"
|
||||
|
||||
DS18B20_Drv_t *DS;
|
||||
OneWire_t OW;
|
||||
|
||||
/**
|
||||
* @brief The function is used to check valid DS18B20 ROM
|
||||
* @retval Return in OK = 1, Failed = 0
|
||||
* @param ROM Pointer to ROM number
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_IsValidAddress(uint8_t *ROM)
|
||||
{
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint8_t check_family = (*ROM == DS18B20_FAMILY_CODE);
|
||||
/* Calculate CRC */
|
||||
uint8_t crc = OneWire_CRC8(ROM, 7);
|
||||
uint8_t check_crc = (crc == ROM[7]);
|
||||
/* Checks if first byte is equal to DS18B20's family code */
|
||||
if(check_family && check_crc)
|
||||
return HAL_OK;
|
||||
else
|
||||
return HAL_ERROR;
|
||||
}
|
||||
/**
|
||||
* @brief The function is used to check valid DS18B20 ROM
|
||||
* @retval Return in OK = 1, Failed = 0
|
||||
* @param ROM Pointer to ROM number
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_IsValid(uint8_t *ROM)
|
||||
{
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
if(*ROM == DS18B20_FAMILY_CODE)
|
||||
return HAL_OK;
|
||||
else
|
||||
return HAL_ERROR;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to get resolution
|
||||
* @retval Return value in 9 - 12
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to ROM number
|
||||
*/
|
||||
uint8_t DS18B20_GetResolution(OneWire_t* OW, uint8_t *ROM) {
|
||||
uint8_t conf;
|
||||
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Check valid ROM */
|
||||
if (DS18B20_IsValid(ROM) != HAL_OK)
|
||||
return 0;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Read scratchpad command by onewire protocol */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_READSCRATCHPAD);
|
||||
|
||||
/* Ignore first 4 bytes */
|
||||
OneWire_ReadByte(OW);
|
||||
OneWire_ReadByte(OW);
|
||||
OneWire_ReadByte(OW);
|
||||
OneWire_ReadByte(OW);
|
||||
|
||||
/* 5th byte of scratchpad is configuration register */
|
||||
conf = OneWire_ReadByte(OW);
|
||||
|
||||
/* Return 9 - 12 value according to number of bits */
|
||||
return ((conf & 0x60) >> 5) + 9;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used as set resolution
|
||||
* @retval status in OK = 1, Failed = 0
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to ROM number
|
||||
* @param Resolution Resolution in 9 - 12
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_SetResolution(OneWire_t* OW, uint8_t *ROM,
|
||||
DS18B20_Res_t Resolution)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint8_t th, tl, conf;
|
||||
|
||||
/* Check valid ROM */
|
||||
if (DS18B20_IsValid(ROM) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Read scratchpad command by onewire protocol */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_READSCRATCHPAD);
|
||||
|
||||
/* Ignore first 2 bytes */
|
||||
OneWire_ReadByte(OW);
|
||||
OneWire_ReadByte(OW);
|
||||
|
||||
th = OneWire_ReadByte(OW);
|
||||
tl = OneWire_ReadByte(OW);
|
||||
conf = OneWire_ReadByte(OW);
|
||||
|
||||
/* Set choosed resolution */
|
||||
conf = Resolution;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Write scratchpad command by onewire protocol, only th, tl and conf
|
||||
* register can be written */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_WRITESCRATCHPAD);
|
||||
|
||||
/* Write bytes */
|
||||
OneWire_WriteByte(OW, th);
|
||||
OneWire_WriteByte(OW, tl);
|
||||
OneWire_WriteByte(OW, conf);
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Copy scratchpad to EEPROM of DS18B20 */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_COPYSCRATCHPAD);
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used as start selected ROM device
|
||||
* @retval status in OK = 1, Failed = 0
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to ROM number
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_StartConvT(OneWire_t* OW, uint8_t *ROM)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Check if device is DS18B20 */
|
||||
if(DS18B20_IsValid(ROM) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Start temperature conversion */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_CONVERT);
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
/**
|
||||
* @brief The function is used as start all ROM device
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_StartConvTAll(OneWire_t* OW)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Reset pulse */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Skip rom */
|
||||
OneWire_WriteByte(OW, ONEWIRE_CMD_SKIPROM);
|
||||
|
||||
/* Start conversion on all connected devices */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_CONVERT);
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used as read temreature from device and store in selected
|
||||
* destination
|
||||
* @retval status in OK = 1, Failed = 0
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to ROM number
|
||||
* @param Destination Pointer to return value
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_CalcTemperature(OneWire_t* OW, uint8_t *ROM, uint8_t *Scratchpad, float *Destination)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
if(Scratchpad == NULL)
|
||||
return HAL_ERROR;
|
||||
if(Destination == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint16_t temperature;
|
||||
uint8_t resolution;
|
||||
int8_t digit, minus = 0;
|
||||
float decimal;
|
||||
|
||||
/* Check if device is DS18B20 */
|
||||
if (DS18B20_IsValid(ROM) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* First two bytes of scratchpad are temperature values */
|
||||
temperature = Scratchpad[0] | (Scratchpad[1] << 8);
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Check if temperature is negative */
|
||||
if (temperature & 0x8000) {
|
||||
/* Two's complement, temperature is negative */
|
||||
temperature = ~temperature + 1;
|
||||
minus = 1;
|
||||
}
|
||||
|
||||
/* Get sensor resolution */
|
||||
resolution = Scratchpad[4];
|
||||
|
||||
/* Store temperature integer digits and decimal digits */
|
||||
digit = temperature >> 4;
|
||||
digit |= ((temperature >> 8) & 0x7) << 4;
|
||||
|
||||
/* Store decimal digits */
|
||||
switch (resolution) {
|
||||
case DS18B20_RESOLUTION_9BITS: {
|
||||
decimal = (temperature >> 3) & 0x01;
|
||||
decimal *= (float)DS18B20_DECIMAL_STEP_9BIT;
|
||||
} break;
|
||||
case DS18B20_RESOLUTION_10BITS: {
|
||||
decimal = (temperature >> 2) & 0x03;
|
||||
decimal *= (float)DS18B20_DECIMAL_STEP_10BIT;
|
||||
} break;
|
||||
case DS18B20_RESOLUTION_11BITS: {
|
||||
decimal = (temperature >> 1) & 0x07;
|
||||
decimal *= (float)DS18B20_DECIMAL_STEP_11BIT;
|
||||
} break;
|
||||
case DS18B20_RESOLUTION_12BITS: {
|
||||
decimal = temperature & 0x0F;
|
||||
decimal *= (float)DS18B20_DECIMAL_STEP_12BIT;
|
||||
} break;
|
||||
default: {
|
||||
*Destination = 0;
|
||||
return HAL_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
/* Check for negative part */
|
||||
decimal = digit + decimal;
|
||||
if (minus) {
|
||||
decimal = 0 - decimal;
|
||||
}
|
||||
|
||||
/* Set to pointer */
|
||||
*Destination = decimal;
|
||||
|
||||
/* Return HAL_OK, temperature valid */
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief The function is used as read scratchpad from device
|
||||
* @retval status in OK = 1, Failed = 0
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to ROM number
|
||||
* @param Destination Pointer to Scratchpad array
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_ReadScratchpad(OneWire_t* OW, uint8_t *ROM, uint8_t *Scratchpad)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
if(Scratchpad == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Read scratchpad command by onewire protocol */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_READSCRATCHPAD);
|
||||
|
||||
/* Get data */
|
||||
for (int i = 0; i < 9; i++) {
|
||||
/* Read byte by byte */
|
||||
Scratchpad[i] = OneWire_ReadByte(OW);
|
||||
}
|
||||
|
||||
/* Calculate CRC */
|
||||
uint8_t crc = OneWire_CRC8(Scratchpad, 8);
|
||||
|
||||
/* Check if CRC is ok */
|
||||
if (crc != Scratchpad[8]) {
|
||||
/* CRC invalid */
|
||||
return HAL_ERROR;
|
||||
}
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief The function is used to wait for end of convertion
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_WaitForEndConvertion(OneWire_t* OW)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
uint32_t tickstart = HAL_GetTick();
|
||||
|
||||
/* Wait until line is released, then coversion is completed */
|
||||
while(OneWire_ReadBit(OW) == 0)
|
||||
{
|
||||
if(HAL_GetTick() - tickstart > DS18B20_DELAY_MS_MAX)
|
||||
return HAL_TIMEOUT; // end of convertion has not come
|
||||
}
|
||||
return HAL_OK; // convertion done
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief The function is used to wait for end of convertion without blocking
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_WaitForEndConvertion_NonBlocking(OneWire_t* OW)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* If line is pull down - conversion is ongoing */
|
||||
if(OneWire_ReadBit(OW) == 0)
|
||||
return HAL_BUSY;
|
||||
else
|
||||
return HAL_OK; // convertion done
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief The function is used as set temperature alarm range on
|
||||
* selected device
|
||||
* @retval status in OK = 1, Failed = 0
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to ROM number
|
||||
* @param Low Low temperature alarm, value > -55, 0 = reset
|
||||
* @param High High temperature alarm,, value < 125, 0 = reset
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_SetTempAlarm(OneWire_t* OW, uint8_t *ROM, int8_t Low,
|
||||
int8_t High)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint8_t tl, th, conf;
|
||||
|
||||
/* Check if device is DS18B20 */
|
||||
if (DS18B20_IsValid(ROM) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
Low = ((Low < -55) || (Low == 0)) ? -55 : Low;
|
||||
High = ((High > 125) || (High == 0)) ? 125 : High;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Read scratchpad command by onewire protocol */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_READSCRATCHPAD);
|
||||
|
||||
/* Ignore first 2 bytes */
|
||||
OneWire_ReadByte(OW);
|
||||
OneWire_ReadByte(OW);
|
||||
|
||||
th = OneWire_ReadByte(OW);
|
||||
tl = OneWire_ReadByte(OW);
|
||||
conf = OneWire_ReadByte(OW);
|
||||
|
||||
th = (uint8_t)High;
|
||||
tl = (uint8_t)Low;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Write scratchpad command by onewire protocol, only th, tl and conf
|
||||
* register can be written */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_WRITESCRATCHPAD);
|
||||
|
||||
/* Write bytes */
|
||||
OneWire_WriteByte(OW, th);
|
||||
OneWire_WriteByte(OW, tl);
|
||||
OneWire_WriteByte(OW, conf);
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Copy scratchpad to EEPROM of DS18B20 */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_COPYSCRATCHPAD);
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used as set user bytes with mask
|
||||
* @retval status in OK = 1, Failed = 0
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to ROM number
|
||||
* @param UserBytes12 First 2 User Bytes (tHigh and tLow)
|
||||
* @param UserBytes34 Second 2 User Bytes
|
||||
* @param UserBytesMask Which User Bytes write, and which ignore
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_WriteUserBytes(OneWire_t* OW, uint8_t *ROM, int16_t UserBytes12,
|
||||
int16_t UserBytes34, uint8_t UserBytesMask)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
if(ROM == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
uint8_t ub1, ub2, conf, ub3, ub4;
|
||||
uint8_t UserByte1 = UserBytes12 & 0xFF;
|
||||
uint8_t UserByte2 = UserBytes12 >> 8;
|
||||
uint8_t UserByte3 = UserBytes34 & 0xFF;
|
||||
uint8_t UserByte4 = UserBytes34 >> 8;
|
||||
|
||||
/* Check if device is DS18B20 */
|
||||
if (DS18B20_IsValid(ROM) != HAL_OK)
|
||||
return HAL_ERROR;
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Read scratchpad command by onewire protocol */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_READSCRATCHPAD);
|
||||
|
||||
/* Ignore first 2 bytes */
|
||||
OneWire_ReadByte(OW);
|
||||
OneWire_ReadByte(OW);
|
||||
|
||||
ub1 = OneWire_ReadByte(OW);
|
||||
ub2 = OneWire_ReadByte(OW);
|
||||
conf = OneWire_ReadByte(OW);
|
||||
OneWire_ReadByte(OW);
|
||||
ub3 = OneWire_ReadByte(OW);
|
||||
ub4 = OneWire_ReadByte(OW);
|
||||
|
||||
/* If user bytes in mask */
|
||||
if(UserBytesMask & (1<<0))
|
||||
{
|
||||
ub1 = UserByte1;
|
||||
}
|
||||
if(UserBytesMask & (1<<1))
|
||||
{
|
||||
ub2 = UserByte2;
|
||||
}
|
||||
if(UserBytesMask & (1<<2))
|
||||
{
|
||||
ub3 = UserByte3;
|
||||
}
|
||||
if(UserBytesMask & (1<<3))
|
||||
{
|
||||
ub4 = UserByte4;
|
||||
}
|
||||
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Write scratchpad command by onewire protocol, only th, tl and conf
|
||||
* register can be written */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_WRITESCRATCHPAD);
|
||||
|
||||
/* Write bytes */
|
||||
OneWire_WriteByte(OW, ub1);
|
||||
OneWire_WriteByte(OW, ub2);
|
||||
OneWire_WriteByte(OW, conf);
|
||||
OneWire_WriteByte(OW, ub3);
|
||||
OneWire_WriteByte(OW, ub4);
|
||||
|
||||
/* Reset line */
|
||||
OneWire_Reset(OW);
|
||||
|
||||
/* Select ROM number */
|
||||
OneWire_MatchROM(OW, ROM);
|
||||
|
||||
/* Copy scratchpad to EEPROM of DS18B20 */
|
||||
OneWire_WriteByte(OW, DS18B20_CMD_COPYSCRATCHPAD);
|
||||
|
||||
return HAL_OK;
|
||||
}
|
||||
|
||||
|
||||
///**
|
||||
// * @brief The function is used as search device that had temperature alarm
|
||||
// * triggered and store it in DS18B20 alarm data structure
|
||||
// * @retval status of search, OK = 1, Failed = 0
|
||||
// * @param DS DS18B20 HandleTypedef
|
||||
// * @param OW OneWire HandleTypedef
|
||||
// */
|
||||
//uint8_t DS18B20_AlarmSearch(DS18B20_Drv_t *DS, OneWire_t* OW)
|
||||
//{
|
||||
// uint8_t t = 0;
|
||||
|
||||
// /* Reset Alarm in DS */
|
||||
// for(uint8_t i = 0; i < OW->RomCnt; i++)
|
||||
// {
|
||||
// for(uint8_t j = 0; j < 8; j++)
|
||||
// {
|
||||
// DS->AlmAddr[i][j] = 0;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /* Start alarm search */
|
||||
// while (OneWire_Search(OW, DS18B20_CMD_ALARM_SEARCH))
|
||||
// {
|
||||
// /* Store ROM of device which has alarm flag set */
|
||||
// OneWire_GetDevRom(OW, DS->AlmAddr[t]);
|
||||
// t++;
|
||||
// }
|
||||
// return (t > 0) ? 1 : 0;
|
||||
//}
|
||||
|
||||
/**
|
||||
* @brief The function is used to initialize the DS18B20 sensor, and search
|
||||
* for all ROM along the line. Store in DS18B20 data structure
|
||||
* @retval Rom detect status, OK = 1, No Rom detected = 0
|
||||
* @param DS DS18B20 HandleTypedef
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
HAL_StatusTypeDef DS18B20_Search(DS18B20_Drv_t *DS, OneWire_t *OW)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return HAL_ERROR;
|
||||
|
||||
|
||||
OW->RomCnt = 0;
|
||||
/* Search all OneWire devices ROM */
|
||||
while(1)
|
||||
{
|
||||
/* Start searching for OneWire devices along the line */
|
||||
if(OneWire_Search(OW, ONEWIRE_CMD_SEARCHROM) != 1) break;
|
||||
|
||||
/* Get device ROM */
|
||||
OneWire_GetDevRom(OW, DS->DevAddr[OW->RomCnt]);
|
||||
|
||||
OW->RomCnt++;
|
||||
}
|
||||
for(int i = OW->RomCnt; i < DS18B20_DEVICE_AMOUNT; i++)
|
||||
{
|
||||
for(int j = 0; j < 8; j++)
|
||||
DS->DevAddr[i][j] = 0;
|
||||
}
|
||||
|
||||
|
||||
if(OW->RomCnt > 0)
|
||||
return HAL_OK;
|
||||
else
|
||||
return HAL_BUSY;
|
||||
}
|
||||
105
py_project/Core/Dallas/ds18b20_driver.h
Normal file
105
py_project/Core/Dallas/ds18b20_driver.h
Normal file
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file ds18b20_driver.h
|
||||
* @brief This file contains all the constants parameters for the DS18B20
|
||||
* 1-Wire Digital Thermometer
|
||||
******************************************************************************
|
||||
* @attention
|
||||
* Usage:
|
||||
* Uncomment LL Driver for HAL driver
|
||||
*
|
||||
******************************************************************************
|
||||
*/
|
||||
/* Define to prevent recursive inclusion -------------------------------------*/
|
||||
#ifndef DS18B20_H
|
||||
#define DS18B20_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "onewire.h"
|
||||
|
||||
/* I/O Port ------------------------------------------------------------------*/
|
||||
#define DS_Pin GPIO_PIN_0
|
||||
#define DS_GPIO_Port GPIOB
|
||||
|
||||
/* Data Structure ------------------------------------------------------------*/
|
||||
#define DS18B20_DEVICE_AMOUNT 30
|
||||
|
||||
/* Register ------------------------------------------------------------------*/
|
||||
#define DS18B20_CMD_CONVERT 0x44
|
||||
#define DS18B20_CMD_ALARM_SEARCH 0xEC
|
||||
#define DS18B20_CMD_READSCRATCHPAD 0xBE
|
||||
#define DS18B20_CMD_WRITESCRATCHPAD 0x4E
|
||||
#define DS18B20_CMD_COPYSCRATCHPAD 0x48
|
||||
/* Data Structure ------------------------------------------------------------*/
|
||||
#define DS18B20_FAMILY_CODE 0x28
|
||||
|
||||
|
||||
#define DS18B20_SERIAL_NUMBER_LEN_BYTES 6
|
||||
#define DS18B20_SERIAL_NUMBER_OFFSET_BYTES 1
|
||||
|
||||
#define DS18B20_SCRATCHPAD_T_LSB_BYTE_IDX 0
|
||||
#define DS18B20_SCRATCHPAD_T_MSB_BYTE_IDX 1
|
||||
#define DS18B20_SCRATCHPAD_T_LIMIT_H_BYTE_IDX 2
|
||||
#define DS18B20_SCRATCHPAD_T_LIMIT_L_BYTE_IDX 3
|
||||
#define DS18B20_SCRATCHPAD_CONFIG_BYTE_IDX 4
|
||||
#define DS18B20_SCRATCHPAD_USER_BYTE_3_IDX 6
|
||||
#define DS18B20_SCRATCHPAD_USER_BYTE_4_IDX 7
|
||||
#define DS18B20_SCRATCHPAD_CRC_IDX 8
|
||||
|
||||
/* Bits locations for resolution */
|
||||
#define DS18B20_RESOLUTION_R1 6
|
||||
#define DS18B20_RESOLUTION_R0 5
|
||||
|
||||
#define DS18B20_DECIMAL_STEP_12BIT 0.0625
|
||||
#define DS18B20_DECIMAL_STEP_11BIT 0.125
|
||||
#define DS18B20_DECIMAL_STEP_10BIT 0.25
|
||||
#define DS18B20_DECIMAL_STEP_9BIT 0.5
|
||||
|
||||
#define DS18B20_DELAY_MS_9_BITS 94
|
||||
#define DS18B20_DELAY_MS_10_BITS 188
|
||||
#define DS18B20_DELAY_MS_11_BITS 375
|
||||
#define DS18B20_DELAY_MS_12_BITS 750
|
||||
#define DS18B20_DELAY_MS_MAX DS18B20_DELAY_MS_12_BITS
|
||||
|
||||
|
||||
/* DS18B20 Resolutions */
|
||||
typedef enum {
|
||||
DS18B20_RESOLUTION_9BITS = 0x1F,
|
||||
DS18B20_RESOLUTION_10BITS = 0x3F,
|
||||
DS18B20_RESOLUTION_11BITS = 0x5F,
|
||||
DS18B20_RESOLUTION_12BITS = 0x7F
|
||||
} DS18B20_Res_t;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
uint8_t DevAddr[DS18B20_DEVICE_AMOUNT][8];
|
||||
} DS18B20_Drv_t;
|
||||
extern DS18B20_Drv_t *DS;;
|
||||
extern OneWire_t OW;
|
||||
|
||||
/* External Function ---------------------------------------------------------*/
|
||||
HAL_StatusTypeDef DS18B20_Search(DS18B20_Drv_t *DS, OneWire_t *OW);
|
||||
HAL_StatusTypeDef DS18B20_StartConvT(OneWire_t* OW, uint8_t *ROM);
|
||||
HAL_StatusTypeDef DS18B20_StartConvTAll(OneWire_t* OW);
|
||||
HAL_StatusTypeDef DS18B20_CalcTemperature(OneWire_t* OW, uint8_t *ROM, uint8_t *Scratchpad, float *destination);
|
||||
HAL_StatusTypeDef DS18B20_ReadScratchpad(OneWire_t* OW, uint8_t *ROM, uint8_t *Scratchpad);
|
||||
HAL_StatusTypeDef DS18B20_WaitForEndConvertion(OneWire_t* OW);
|
||||
HAL_StatusTypeDef DS18B20_WaitForEndConvertion_NonBlocking(OneWire_t* OW);
|
||||
HAL_StatusTypeDef DS18B20_SetTempAlarm(OneWire_t* OW, uint8_t *ROM, int8_t Low,
|
||||
int8_t High);
|
||||
HAL_StatusTypeDef DS18B20_WriteUserBytes(OneWire_t* OW, uint8_t *ROM, int16_t UserBytes12,
|
||||
int16_t UserBytes34, uint8_t UserBytesMask);
|
||||
uint8_t DS18B20_AlarmSearch(DS18B20_Drv_t *DS, OneWire_t* OW);
|
||||
|
||||
HAL_StatusTypeDef DS18B20_SetResolution(OneWire_t* OW, uint8_t *ROM,
|
||||
DS18B20_Res_t Resolution);
|
||||
HAL_StatusTypeDef DS18B20_IsValidAddress(uint8_t *ROM);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* DS18B20_H */
|
||||
58
py_project/Core/Dallas/dwt.c
Normal file
58
py_project/Core/Dallas/dwt.c
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file dwt.c
|
||||
* @brief This file includes the utilities for DWT
|
||||
******************************************************************************
|
||||
*/
|
||||
#include "dwt.h"
|
||||
|
||||
static uint32_t SysCClk, start;
|
||||
|
||||
/**
|
||||
* @brief Initialize DWT
|
||||
*/
|
||||
void DwtInit(void)
|
||||
{
|
||||
SysCClk = (SystemCoreClock / 1000000); // Calculate in us
|
||||
DWT_LAR |= DWT_LAR_UNLOCK;
|
||||
DEM_CR |= (uint32_t)DEM_CR_TRCENA;
|
||||
DWT_CYCCNT = (uint32_t)0u; // Reset the clock counter
|
||||
DWT_CR |= (uint32_t)DWT_CR_CYCCNTENA;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Start DWT Counter
|
||||
*/
|
||||
void DwtStart(void)
|
||||
{
|
||||
start = DWT_CYCCNT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculate Interval Base On Previous Start Time
|
||||
* @retval Interval in us
|
||||
*/
|
||||
float DwtInterval(void)
|
||||
{
|
||||
return (float)(DWT_CYCCNT - start) / SysCClk;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Function to delay in microsecond
|
||||
* @param usec Period in microsecond
|
||||
*/
|
||||
inline void DwtDelay_us(uint32_t usec)
|
||||
{
|
||||
start = DWT_CYCCNT;
|
||||
while(((DWT_CYCCNT - start) / SysCClk) < usec) {};
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Function to delay in millisecond
|
||||
* @param msec Period in millisecond
|
||||
*/
|
||||
inline void DwtDelay_ms(uint32_t msec)
|
||||
{
|
||||
start = DWT_CYCCNT;
|
||||
while(((DWT_CYCCNT - start) / SysCClk) < (msec * 1000)) {};
|
||||
}
|
||||
39
py_project/Core/Dallas/dwt.h
Normal file
39
py_project/Core/Dallas/dwt.h
Normal file
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file dwt.h
|
||||
* @brief This file contains all the constants parameters for the dwt delay
|
||||
******************************************************************************
|
||||
*/
|
||||
/* Define to prevent recursive inclusion -------------------------------------*/
|
||||
#ifndef DWT_H
|
||||
#define DWT_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "py32f0xx_hal.h"
|
||||
|
||||
/* Custom Define -------------------------------------------------------------*/
|
||||
#define DWT_LAR_UNLOCK (uint32_t)0xC5ACCE55
|
||||
#define DEM_CR_TRCENA (1 << 24)
|
||||
#define DWT_CR_CYCCNTENA (1 << 0)
|
||||
#define DWT_CR *(volatile uint32_t *)0xE0001000
|
||||
#define DWT_LAR *(volatile uint32_t *)0xE0001FB0
|
||||
#define DWT_CYCCNT *(volatile uint32_t *)0xE0001004
|
||||
#define DEM_CR *(volatile uint32_t *)0xE000EDFC
|
||||
|
||||
|
||||
/* External Function ---------------------------------------------------------*/
|
||||
void DwtInit(void);
|
||||
void DwtStart(void);
|
||||
float DwtInterval(void);
|
||||
void DwtDelay_us(uint32_t usec);
|
||||
void DwtDelay_ms(uint32_t msec);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* DWT_H */
|
||||
379
py_project/Core/Dallas/onewire.c
Normal file
379
py_project/Core/Dallas/onewire.c
Normal file
@@ -0,0 +1,379 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file onewire.c
|
||||
* @brief This file includes the HAL/LL driver for OneWire devices
|
||||
******************************************************************************
|
||||
*/
|
||||
#include "onewire.h"
|
||||
|
||||
/**
|
||||
* @brief The internal function is used to write bit
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param bit bit in 0 or 1
|
||||
*/
|
||||
void OneWire_WriteBit(OneWire_t* OW, uint8_t bit)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return;
|
||||
#ifndef ONEWIRE_UART_H
|
||||
__disable_irq();
|
||||
if(bit)
|
||||
{
|
||||
/* Set line low */
|
||||
OneWire_Pin_Level(OW, 0);
|
||||
OneWire_Pin_Mode(OW, Output);
|
||||
|
||||
/* Forming pulse */
|
||||
OneWire_Delay_uw(ONEWIRE_WRITE_1_US);
|
||||
|
||||
/* Release line (pull up line) */
|
||||
OneWire_Pin_Mode(OW, Input);
|
||||
|
||||
/* Wait for 55 us and release the line */
|
||||
OneWire_Delay_uw(ONEWIRE_COMMAND_SLOT_US - ONEWIRE_WRITE_1_US);
|
||||
OneWire_Pin_Mode(OW, Input);
|
||||
}else{
|
||||
/* Set line low */
|
||||
OneWire_Pin_Level(OW, 0);
|
||||
OneWire_Pin_Mode(OW, Output);
|
||||
|
||||
/* Forming pulse */
|
||||
OneWire_Delay_uw(ONEWIRE_WRITE_0_US);
|
||||
|
||||
/* Release line (pull up line) */
|
||||
OneWire_Pin_Mode(OW, Input);
|
||||
|
||||
/* Wait for 5 us and release the line */
|
||||
OneWire_Delay_uw(ONEWIRE_COMMAND_SLOT_US - ONEWIRE_WRITE_0_US);
|
||||
OneWire_Pin_Mode(OW, Input);
|
||||
}
|
||||
__enable_irq();
|
||||
#else
|
||||
OneWireUART_ProcessBit(onewire_uart, bit);
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to read bit
|
||||
* @retval bit
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
uint8_t OneWire_ReadBit(OneWire_t* OW)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return 0;
|
||||
|
||||
__disable_irq();
|
||||
uint8_t bit = 0;
|
||||
#ifndef ONEWIRE_UART_H
|
||||
/* Line low */
|
||||
OneWire_Pin_Level(OW, 0);
|
||||
OneWire_Pin_Mode(OW, Output);
|
||||
OneWire_Delay_uw(ONEWIRE_READ_CMD_US);
|
||||
|
||||
/* Release line */
|
||||
OneWire_Pin_Mode(OW, Input);
|
||||
OneWire_Delay_uw(ONEWIRE_READ_DELAY_US);
|
||||
|
||||
/* Read line value */
|
||||
bit = OneWire_Pin_Read(OW);
|
||||
|
||||
/* Wait 50us to complete 60us period */
|
||||
OneWire_Delay_uw(ONEWIRE_COMMAND_SLOT_US - ONEWIRE_READ_CMD_US - ONEWIRE_READ_DELAY_US);
|
||||
__enable_irq();
|
||||
#else
|
||||
bit = OneWireUART_ProcessBit(onewire_uart, 1);
|
||||
#endif
|
||||
/* Return bit value */
|
||||
return bit;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to write byte
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param byte byte to write
|
||||
*/
|
||||
void OneWire_WriteByte(OneWire_t* OW, uint8_t byte)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return;
|
||||
|
||||
#ifndef ONEWIRE_UART_H
|
||||
uint8_t bit = 8;
|
||||
/* Write 8 bits */
|
||||
while (bit--) {
|
||||
/* LSB bit is first */
|
||||
OneWire_WriteBit(OW, byte & 0x01);
|
||||
byte >>= 1;
|
||||
}
|
||||
#else
|
||||
OneWireUART_ProcessByte(onewire_uart, byte);
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to read byte
|
||||
* @retval byte from device
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
uint8_t OneWire_ReadByte(OneWire_t* OW)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return 0;
|
||||
|
||||
uint8_t byte = 0;
|
||||
#ifndef ONEWIRE_UART_H
|
||||
uint8_t bit = 8;
|
||||
while (bit--) {
|
||||
byte >>= 1;
|
||||
byte |= (OneWire_ReadBit(OW) << 7);
|
||||
}
|
||||
#else
|
||||
byte = OneWireUART_ProcessByte(onewire_uart, 0xFF);
|
||||
#endif
|
||||
|
||||
return byte;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to reset device
|
||||
* @retval respond from device
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
uint8_t OneWire_Reset(OneWire_t* OW)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return 1;
|
||||
|
||||
#ifndef ONEWIRE_UART_H
|
||||
/* Line low, and wait 480us */
|
||||
OneWire_Pin_Level(OW, 0);
|
||||
OneWire_Pin_Mode(OW, Output);
|
||||
OneWire_Delay_uw(ONEWIRE_RESET_PULSE_US);
|
||||
|
||||
/* Release line and wait for 70us */
|
||||
OneWire_Pin_Mode(OW, Input);
|
||||
OneWire_Delay_uw(ONEWIRE_PRESENCE_WAIT_US);
|
||||
|
||||
/* Check bit value */
|
||||
uint8_t rslt = OneWire_Pin_Read(OW);
|
||||
|
||||
/* Delay for 410 us */
|
||||
OneWire_Delay_uw(ONEWIRE_PRESENCE_DURATION_US);
|
||||
#else
|
||||
|
||||
uint8_t rslt = 0;
|
||||
if(OneWireUART_Reset(onewire_uart) == HAL_OK)
|
||||
rslt = 0;
|
||||
else
|
||||
rslt = 1;
|
||||
#endif
|
||||
|
||||
return rslt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to search device
|
||||
* @retval Search result
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
uint8_t OneWire_Search(OneWire_t* OW, uint8_t Cmd)
|
||||
{
|
||||
if(OW == NULL)
|
||||
return 0;
|
||||
|
||||
uint8_t id_bit_number = 1;
|
||||
uint8_t last_zero = 0;
|
||||
uint8_t rom_byte_number = 0;
|
||||
uint8_t search_result = 0;
|
||||
uint8_t rom_byte_mask = 1;
|
||||
uint8_t id_bit, cmp_id_bit, search_direction;
|
||||
|
||||
/* if the last call was not the last one */
|
||||
if (!OW->LastDeviceFlag)
|
||||
{
|
||||
if (OneWire_Reset(OW))
|
||||
{
|
||||
OW->LastDiscrepancy = 0;
|
||||
OW->LastDeviceFlag = 0;
|
||||
OW->LastFamilyDiscrepancy = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// issue the search command
|
||||
OneWire_WriteByte(OW, Cmd);
|
||||
|
||||
// loop to do the search
|
||||
do {
|
||||
// read a bit and its complement
|
||||
id_bit = OneWire_ReadBit(OW);
|
||||
cmp_id_bit = OneWire_ReadBit(OW);
|
||||
|
||||
// check for no devices on 1-wire
|
||||
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 < OW->LastDiscrepancy)
|
||||
{
|
||||
search_direction = ((OW->RomByte[rom_byte_number] & rom_byte_mask) > 0);
|
||||
} else {
|
||||
// if equal to last pick 1, if not then pick 0
|
||||
search_direction = (id_bit_number == OW->LastDiscrepancy);
|
||||
}
|
||||
|
||||
// if 0 was picked then record its position in LastZero
|
||||
if (search_direction == 0)
|
||||
{
|
||||
last_zero = id_bit_number;
|
||||
|
||||
// check for Last discrepancy in family
|
||||
if (last_zero < 9)
|
||||
{
|
||||
OW->LastFamilyDiscrepancy = last_zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* set or clear the bit in the ROM byte rom_byte_number
|
||||
* with mask rom_byte_mask */
|
||||
if (search_direction == 1)
|
||||
{
|
||||
OW->RomByte[rom_byte_number] |= rom_byte_mask;
|
||||
} else {
|
||||
OW->RomByte[rom_byte_number] &= ~rom_byte_mask;
|
||||
}
|
||||
|
||||
// serial number search direction write bit
|
||||
OneWire_WriteBit(OW, 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 LastDiscrepancy, LastDeviceFlag,
|
||||
* search_result */
|
||||
OW->LastDiscrepancy = last_zero;
|
||||
// check for last device
|
||||
if (OW->LastDiscrepancy == 0) {
|
||||
OW->LastDeviceFlag = 1;
|
||||
}
|
||||
search_result = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* if no device found then reset counters so next 'search' will be like a
|
||||
* first */
|
||||
if (!search_result || !OW->RomByte[0])
|
||||
{
|
||||
OW->LastDiscrepancy = 0;
|
||||
OW->LastDeviceFlag = 0;
|
||||
OW->LastFamilyDiscrepancy = 0;
|
||||
search_result = 0;
|
||||
}
|
||||
|
||||
return search_result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used get ROM full address
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to device ROM
|
||||
*/
|
||||
void OneWire_GetDevRom(OneWire_t* OW, uint8_t *ROM)
|
||||
{
|
||||
for (uint8_t i = 0; i < 8; i++) {
|
||||
*(ROM + i) = OW->RomByte[i];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to initialize OneWire Communication
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
void OneWire_Init(OneWire_t* OW)
|
||||
{
|
||||
OneWire_Pin_Mode(OW, Output);
|
||||
OneWire_Pin_Level(OW, 1);
|
||||
OneWire_Delay_uw(1000);
|
||||
OneWire_Pin_Level(OW, 0);
|
||||
OneWire_Delay_uw(1000);
|
||||
OneWire_Pin_Level(OW, 1);
|
||||
OneWire_Delay_uw(2000);
|
||||
|
||||
/* Reset the search state */
|
||||
OW->LastDiscrepancy = 0;
|
||||
OW->LastDeviceFlag = 0;
|
||||
OW->LastFamilyDiscrepancy = 0;
|
||||
OW->RomCnt = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used selected specific device ROM
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param ROM Pointer to device ROM
|
||||
*/
|
||||
void OneWire_MatchROM(OneWire_t* OW, uint8_t *ROM)
|
||||
{
|
||||
OneWire_WriteByte(OW, ONEWIRE_CMD_MATCHROM);
|
||||
|
||||
for (uint8_t i = 0; i < 8; i++)
|
||||
{
|
||||
OneWire_WriteByte(OW, *(ROM + i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used to access to all ROM
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
void OneWire_Skip(OneWire_t* OW)
|
||||
{
|
||||
OneWire_WriteByte(OW, ONEWIRE_CMD_SKIPROM);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The function is used check CRC
|
||||
* @param Addr Pointer to address
|
||||
* @param ROM Number of byte
|
||||
*/
|
||||
uint8_t OneWire_CRC8(uint8_t *Addr, uint8_t Len)
|
||||
{
|
||||
uint8_t crc = 0;
|
||||
uint8_t inbyte, i, mix;
|
||||
|
||||
while (Len--)
|
||||
{
|
||||
inbyte = *Addr++;
|
||||
|
||||
for (i = 8; i; i--)
|
||||
{
|
||||
mix = (crc ^ inbyte) & 0x01;
|
||||
crc >>= 1;
|
||||
crc ^= (mix) ? 0x8C : 0;
|
||||
inbyte >>= 1;
|
||||
}
|
||||
}
|
||||
return crc;
|
||||
}
|
||||
77
py_project/Core/Dallas/onewire.h
Normal file
77
py_project/Core/Dallas/onewire.h
Normal file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file onewire.h
|
||||
* @brief This file contains all the constants parameters for the OneWire
|
||||
******************************************************************************
|
||||
*/
|
||||
/* Define to prevent recursive inclusion -------------------------------------*/
|
||||
#ifndef ONEWIRE_H
|
||||
#define ONEWIRE_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "ow_port.h"
|
||||
|
||||
/* Driver Selection ----------------------------------------------------------*/
|
||||
//#define LL_Driver
|
||||
#define CMSIS_Driver
|
||||
/* OneWire Timings -----------------------------------------------------------*/
|
||||
#define ONEWIRE_RESET_PULSE_US 480 // Длительность импульса сброса
|
||||
#define ONEWIRE_PRESENCE_WAIT_US 70 // Ожидание ответа от датчика
|
||||
#define ONEWIRE_PRESENCE_DURATION_US 410 // Длительность сигнала присутствия
|
||||
|
||||
#define ONEWIRE_WRITE_1_US 8 // Длительность записи "1"
|
||||
#define ONEWIRE_WRITE_0_US 57 // Длительность записи "0"
|
||||
#define ONEWIRE_READ_CMD_US 2 // Время комманды чтения бита
|
||||
#define ONEWIRE_READ_DELAY_US 6 // Задержка перед считыванием бита
|
||||
#define ONEWIRE_COMMAND_SLOT_US 58 // Общее время комманды OneWire
|
||||
#define ONEWIRE_RECOVERY_TIME_US 1 // Восстановление перед следующим слотом
|
||||
/* Common Register -----------------------------------------------------------*/
|
||||
#define ONEWIRE_CMD_SEARCHROM 0xF0
|
||||
#define ONEWIRE_CMD_READROM 0x33
|
||||
#define ONEWIRE_CMD_MATCHROM 0x55
|
||||
#define ONEWIRE_CMD_SKIPROM 0xCC
|
||||
|
||||
/* Data Structure ------------------------------------------------------------*/
|
||||
typedef enum
|
||||
{
|
||||
Input,
|
||||
Output
|
||||
} PinMode;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
uint8_t LastDiscrepancy;
|
||||
uint8_t LastFamilyDiscrepancy;
|
||||
uint8_t LastDeviceFlag;
|
||||
uint8_t RomByte[8];
|
||||
uint8_t RomCnt;
|
||||
uint16_t DataPin;
|
||||
GPIO_TypeDef *DataPort;
|
||||
} OneWire_t;
|
||||
|
||||
/* External Function ---------------------------------------------------------*/
|
||||
void OneWire_Init(OneWire_t* OW);
|
||||
uint8_t OneWire_Search(OneWire_t* OW, uint8_t Cmd);
|
||||
void OneWire_GetDevRom(OneWire_t* OW, uint8_t *dev);
|
||||
uint8_t OneWire_Reset(OneWire_t* OW);
|
||||
uint8_t OneWire_ReadBit(OneWire_t* OW);
|
||||
uint8_t OneWire_ReadByte(OneWire_t* OW);
|
||||
void OneWire_WriteByte(OneWire_t* OW, uint8_t byte);
|
||||
void OneWire_MatchROM(OneWire_t* OW, uint8_t *Rom);
|
||||
void OneWire_Skip(OneWire_t* OW);
|
||||
uint8_t OneWire_CRC8(uint8_t *addr, uint8_t len);
|
||||
|
||||
void OneWire_Pin_Mode(OneWire_t* OW, PinMode Mode);
|
||||
void OneWire_Pin_Level(OneWire_t* OW, uint8_t Level);
|
||||
uint8_t OneWire_Pin_Read(OneWire_t* OW);
|
||||
void OneWire_WriteBit(OneWire_t* OW, uint8_t bit);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* ONEWIRE_H */
|
||||
109
py_project/Core/Dallas/ow_port.c
Normal file
109
py_project/Core/Dallas/ow_port.c
Normal file
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file ow_port.c
|
||||
* @brief This file includes the driver for port for OneWire purposes
|
||||
******************************************************************************
|
||||
*/
|
||||
#include "ow_port.h"
|
||||
#include "onewire.h"
|
||||
#include "tim.h"
|
||||
|
||||
/**
|
||||
* @brief The internal function is used as gpio pin mode
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param Mode Input or Output
|
||||
*/
|
||||
void OneWire_Pin_Mode(OneWire_t* OW, PinMode Mode)
|
||||
{
|
||||
#ifdef CMSIS_Driver
|
||||
if(Mode == Input)
|
||||
{
|
||||
OW->DataPort->MODER &= ~((GPIO_MODER_MODE0_Msk) << 0);
|
||||
OW->DataPort->MODER |= (GPIO_MODE_INPUT << (0+2));
|
||||
}else{
|
||||
OW->DataPort->MODER &= ~((GPIO_MODER_MODE0_Msk) << 0);
|
||||
OW->DataPort->MODER |= (GPIO_MODE_OUTPUT_PP << 0);
|
||||
}
|
||||
#else
|
||||
#ifdef LL_Driver
|
||||
if(Mode == Input)
|
||||
{
|
||||
LL_GPIO_SetPinMode(OW->DataPort, OW->DataPin, LL_GPIO_MODE_INPUT);
|
||||
}else{
|
||||
LL_GPIO_SetPinMode(OW->DataPort, OW->DataPin, LL_GPIO_MODE_OUTPUT);
|
||||
}
|
||||
#else
|
||||
GPIO_InitTypeDef GPIO_InitStruct = {0};
|
||||
GPIO_InitStruct.Pin = OW->DataPin;
|
||||
if(Mode == Input)
|
||||
{
|
||||
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
|
||||
}else{
|
||||
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
|
||||
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
|
||||
}
|
||||
HAL_GPIO_Init(OW->DataPort, &GPIO_InitStruct);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The internal function is used as gpio pin level
|
||||
* @param OW OneWire HandleTypedef
|
||||
* @param Mode Level: Set/High = 1, Reset/Low = 0
|
||||
*/
|
||||
void OneWire_Pin_Level(OneWire_t* OW, uint8_t Level)
|
||||
{
|
||||
#ifdef CMSIS_Driver
|
||||
if (Level != GPIO_PIN_RESET)
|
||||
{
|
||||
OW->DataPort->BSRR = OW->DataPin;
|
||||
}
|
||||
else
|
||||
{
|
||||
OW->DataPort->BSRR = (uint32_t)OW->DataPin << 16u;
|
||||
}
|
||||
#else
|
||||
#ifdef LL_Driver
|
||||
if(Level == 1)
|
||||
{
|
||||
LL_GPIO_SetOutputPin(OW->DataPort, OW->DataPin);
|
||||
}else{
|
||||
LL_GPIO_ResetOutputPin(OW->DataPort, OW->DataPin);
|
||||
}
|
||||
#else
|
||||
HAL_GPIO_WritePin(OW->DataPort, OW->DataPin, Level);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief The internal function is used to read data pin
|
||||
* @retval Pin level status
|
||||
* @param OW OneWire HandleTypedef
|
||||
*/
|
||||
uint8_t OneWire_Pin_Read(OneWire_t* OW)
|
||||
{
|
||||
#ifdef CMSIS_Driver
|
||||
return ((OW->DataPort->IDR & OW->DataPin) != 0x00U) ? 1 : 0;
|
||||
#else
|
||||
#ifdef LL_Driver
|
||||
return ((OW->DataPort->IDR & OW->DataPin) != 0x00U) ? 1 : 0;
|
||||
#else
|
||||
return HAL_GPIO_ReadPin(OW->DataPort, OW->DataPin);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
uint16_t start;
|
||||
uint16_t end;
|
||||
uint32_t tim_1us_period = 24;
|
||||
void OneWire_Delay_uw(uint32_t us)
|
||||
{
|
||||
// start = htim1.Instance->CNT;
|
||||
// end = start + us*tim_1us_period;
|
||||
TIM1->CNT = 0;
|
||||
end = us*tim_1us_period;
|
||||
|
||||
while(TIM1->CNT < end) {};
|
||||
}
|
||||
17
py_project/Core/Dallas/ow_port.h
Normal file
17
py_project/Core/Dallas/ow_port.h
Normal file
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
******************************************************************************
|
||||
* @file ow_port.h
|
||||
* @brief This file includes the driver for port for OneWire purposes
|
||||
******************************************************************************
|
||||
*/
|
||||
/* Define to prevent recursive inclusion -------------------------------------*/
|
||||
#ifndef ONEWIRE_PORT_H
|
||||
#define ONEWIRE_PORT_H
|
||||
|
||||
|
||||
/* Includes ------------------------------------------------------------------*/
|
||||
#include "py32f0xx_hal.h"
|
||||
/* OneWire Timings -----------------------------------------------------------*/
|
||||
void OneWire_Delay_uw(uint32_t us);
|
||||
/* Common Register -----------------------------------------------------------*/
|
||||
#endif /* ONEWIRE_PORT_H */
|
||||
Reference in New Issue
Block a user