Программа для PIC12F629, подогреватель кессона.
Re: Программа для PIC12F629, подогреватель кессона.
Не пойму смысла паузы в 1 минуту. Кессон кубовый? Сам датчик обладает известной инерцией. Ну секунду на все про все. Иначе закипит.
Лучше умному тупить, чем тупому умничать
- Реклама
- Аlex
- Модератор
- Сообщения: 4614
- Зарегистрирован: Чт мар 18, 2010 23:09:57
- Откуда: Планета Земля
- Контактная информация:
Re: Программа для PIC12F629, подогреватель кессона.
Сейчас просто секунда стоит.korob писал(а):Опрос только слишком часто.
Чуть позже выложу проект, немного прилижу, косячки уберу, ...
Добавлено after 9 minutes 34 seconds:
[uquote="korob",url="/forum/viewtopic.php?p=3380958#p3380958"]Что не так было? Формула пересчёта, или битность на датчике неверная была выставлена?[/uquote]Не знаю, у меня код свой, совсем другой
А тип датчика сам определяется. Можно и "B" подцеплять, и "S".
Это вы уже там потом с Олегом его код добьёте и выясните причину. Если, конечно, ему не лень будет
Добавлено after 5 minutes 27 seconds: Кот :
Спойлер
Код: Выделить всё
#include <xc.h>
/*************************************************************************************/
#pragma config MCLRE=ON
#pragma config CP=ON
#pragma config CPD=OFF
#pragma config BOREN=ON
#pragma config WDTE=OFF
#pragma config PWRTE=ON
#pragma config FOSC=INTRCIO
/*************************************************************************************/
#define _XTAL_FREQ 4000000UL
/*************************************************************************************/
#define WIRE1_PORT GP1
#define WIRE1_TRIS TRISIO1
#define SENSOR_POWER_PIN GP0
#define SENSOR_POWER_TRIS TRISIO0
#define OUT_PIN GP2
#define OUT_TRIS TRISIO2
/*************************************************************************************/
#define WIRE1_OUT(val) do{WIRE1_TRIS=val; WIRE1_PORT=val;}while(0)
/*************************************************************************************/
/*************************************************************************************/
unsigned char Wire_Reset(void){
WIRE1_OUT(0);
__delay_us(500);
WIRE1_OUT(1);
__delay_us(10);
if(!WIRE1_PORT) return 0;
__delay_us(100);
if(WIRE1_PORT) return 0;
__delay_us(200);
if(!WIRE1_PORT) return 0;
return 1;
}
/*************************************************************************************/
unsigned char Wire_Bit(unsigned char rx){
unsigned char ret;
WIRE1_OUT(0);
__delay_us(2);
WIRE1_OUT(rx);
__delay_us(3);
ret = WIRE1_PORT;
__delay_us(55);
WIRE1_OUT(1);
return ret;
}
/*************************************************************************************/
unsigned char Wire_Write(unsigned char byte){
unsigned char ret=0, i;
for(i=0;i<8;i++){
ret = ret>>1;
if(Wire_Bit(byte&1)) ret|=0x80;
byte = byte>>1;
}
return ret;
}
/*************************************************************************************/
const unsigned char crcval[256]={
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
};
/**************************************************************************/
unsigned char CRC(unsigned char *pArr, unsigned char len){
unsigned char ret=0;
do{
ret=crcval[ret^*pArr++];
}while(--len);
return ret;
}
/*************************************************************************************/
/*************************************************************************************/
unsigned char Is_Sensor(void){
unsigned char err_cnt;
err_cnt=0;
do{
__delay_ms(100);
}while(!Wire_Reset() && (++err_cnt<3));
__delay_ms(10);
return (err_cnt<3);
}
/*************************************************************************************/
/*************************************************************************************/
unsigned char Read_Sensor(unsigned char *pArr, unsigned char len, unsigned char cmd, unsigned char skip_rom){
unsigned char i, err_cnt;
err_cnt=0;
do{
if(!Is_Sensor()) return 0;
if(skip_rom) Wire_Write(0xCC);
Wire_Write(cmd);
for(i=0;i<len;i++) pArr[i]=Wire_Write(0xFF);
}while(CRC(pArr, len) && (++err_cnt<3));
return (err_cnt<3);
}
/*************************************************************************************/
/*************************************************************************************/
void main(void){
static unsigned char arr[9], dev_fam, i;
static signed int temp;
//------------------------------
CMCON = 0x07;
//------------------------------
SENSOR_POWER_TRIS=0;
SENSOR_POWER_PIN=0;
OUT_TRIS=0;
OUT_PIN=0;
//------------------------------
__delay_ms(1000);
//------------------------------
while(1){
//------------------------------
SENSOR_POWER_PIN=1;
__delay_ms(300);
//------------------------------
if(!Is_Sensor()){
OUT_PIN=0;
continue;
}
//------------------------------
Wire_Write(0xCC);
Wire_Write(0x44);
__delay_ms(800);
//------------------------------
if(!Read_Sensor(arr, 8, 0x33, 0)){
OUT_PIN=0;
continue;
}
//------------------------------
dev_fam=arr[0];
//------------------------------
if(!Read_Sensor(arr, 9, 0xBE, 1)){
OUT_PIN=0;
continue;
}
//------------------------------
temp = *(int*)arr * 10;
temp /= (dev_fam==0x10)?2:16;
//------------------------------
if(temp<=20) OUT_PIN=1;
if(temp>=40) OUT_PIN=0;
//------------------------------
SENSOR_POWER_PIN=0;
//------------------------------
for(i=0;i<60;i++) __delay_ms(1000);
//------------------------------
}
}
/*************************************************************************************/
- oleg110592
- Друг Кота
- Сообщения: 3832
- Зарегистрирован: Сб сен 10, 2011 17:46:25
Re: Программа для PIC12F629, подогреватель кессона.
глянул как протеус релиз делает - показалось странновато. Сделал проект в МплабХ - совпало по размеру
. Загрузил новый хекс в протеус - работает как и должно. Собрал код Alex-а, загрузил хекс в протеус - работает отлично
.
Прицепил в протеусе вместо DS18B20 DS18S20 - в моем случае сдвинулась температура срабатывания примерно, как говорилось, на порядок ~20..30С. Код Alex-а прекрасно работает.
Формула у Alex-а (t*10)/16, у меня (t*5)/8
з.ы. поищу - где-то должно быть в чулане несколько PIC12F629, по свободе на беспаечной соберу макет - там можно и пиккитом поотлаживать
.
Прицепил в протеусе вместо DS18B20 DS18S20 - в моем случае сдвинулась температура срабатывания примерно, как говорилось, на порядок ~20..30С. Код Alex-а прекрасно работает.
Формула у Alex-а (t*10)/16, у меня (t*5)/8
з.ы. поищу - где-то должно быть в чулане несколько PIC12F629, по свободе на беспаечной соберу макет - там можно и пиккитом поотлаживать
- musor
- Друг Кота
- Сообщения: 39197
- Зарегистрирован: Сб сен 13, 2014 16:27:32
- Откуда: СпиртоГонск созвездия Омега
Re: Программа для PIC12F629, подогреватель кессона.
выходит датчик у ТС фэйк? перетерка ис DS18S20 ???
опять продаваны надули
а считать DEV ID датчика
там разве невозможно перед замерами?? и выдать на ножку тест(светодиод) ошибку датчика 
опять продаваны надули
а считать DEV ID датчика
ZМудрость(Опыт и выдержка) приходит с годами.
Все Ваши беды и проблемы, от недостатка знаний.
Умный и у дурака научится, а дураку и ..
Алберт Ейнштейн не поможет и ВВП не спасет.и МЧС опаздает
Все Ваши беды и проблемы, от недостатка знаний.
Умный и у дурака научится, а дураку и ..
Алберт Ейнштейн не поможет и ВВП не спасет.и МЧС опаздает
- oleg110592
- Друг Кота
- Сообщения: 3832
- Зарегистрирован: Сб сен 10, 2011 17:46:25
Re: Программа для PIC12F629, подогреватель кессона.
У нас года 3 назад продавцы "терморегуляторов для инкубаторов" на ушах стояли - у закупленых тысячами DS18В20 по умолчанию 9-бит разрешение стояло, может и сейчас так продолжается. В последней прошивке для ТС делал проверку если разрешение 9-бит - исправляем на 12-бит.
- Реклама
Re: Программа для PIC12F629, подогреватель кессона.
Начиная отсюда
https://radiokot.ru/forum/viewtopic.php ... 8#p2565968
и собственно сам девайс с описанием (эквивалент DS1821 на основе DS18B20+PIC12F629)
https://radiokot.ru/forum/viewtopic.php ... 2#p2593182

https://radiokot.ru/forum/viewtopic.php ... 8#p2565968
и собственно сам девайс с описанием (эквивалент DS1821 на основе DS18B20+PIC12F629)
https://radiokot.ru/forum/viewtopic.php ... 2#p2593182
Re: Программа для PIC12F629, подогреватель кессона.
Неа.musor писал(а):выходит датчик у ТС фэйк? перетерка ис DS18S20 ???
Самый что ни на есть настоящий DS18B20 на ядре C4. В проекте STH0024 v.3 у меня эти датчики прекрасно работают в 12-ти битном режиме (18S20 так не может
BOB51
Я уже здесь жаловался на поиск, естественно сначала искал, но видимо что-то пошло не так...
Добавлено after 2 hours 59 minutes 17 seconds:
Погонял прошивку от Alex.
Собственно мои хотелки реализованы в полном объёме.
Явных багов не замечено, на предмет наличия скрытых ещё погоняю, но уже и так ясно - всё работает как положено.
Всем кто принимал участие низкий поклон.
Последний раз редактировалось korob Вс май 20, 2018 13:19:10, всего редактировалось 1 раз.
Большой опыт, порой, не даёт находить/видеть нам простые и очевидные решения. 
Всегда с уважением, Александр.
Всегда с уважением, Александр.
- oleg110592
- Друг Кота
- Сообщения: 3832
- Зарегистрирован: Сб сен 10, 2011 17:46:25
Re: Программа для PIC12F629, подогреватель кессона.
Однако!
Попробую ещё разок прошивку с проверкой CRC, может коряво залилась
Ну а остальные у Вас тоже нормально работают?
Большой опыт, порой, не даёт находить/видеть нам простые и очевидные решения. 
Всегда с уважением, Александр.
Всегда с уважением, Александр.
- oleg110592
- Друг Кота
- Сообщения: 3832
- Зарегистрирован: Сб сен 10, 2011 17:46:25
Re: Программа для PIC12F629, подогреватель кессона.
лучше пробовать эту:
тогда как раз пытался заставить протеус компилировать main.c в мной выбранной папке, но он (протеус) наплевал - могли быть глюки
Re: Программа для PIC12F629, подогреватель кессона.
Перепроверил: так и есть, в прошивке с проверкой CRC опрос датчика идёт, и больше ничего не происходит ни при каких температурах в диапазоне 0...60°С.
[uquote="oleg110592",url="/forum/viewtopic.php?p=3381589#p3381589"]лучше пробовать эту[/uquote]ОК, пока лёд не потаял сейчас проверю. 

Добавлено after 16 minutes 42 seconds:
Странно. 
korob писал(а):Ну а остальные у Вас тоже нормально работают?
Добавлено after 16 minutes 42 seconds:
Ведёт себя точно так же как и с проверкой CRC (не работает).oleg110592 писал(а):лучше пробовать эту:
Большой опыт, порой, не даёт находить/видеть нам простые и очевидные решения. 
Всегда с уважением, Александр.
Всегда с уважением, Александр.
- oleg110592
- Друг Кота
- Сообщения: 3832
- Зарегистрирован: Сб сен 10, 2011 17:46:25
Re: Программа для PIC12F629, подогреватель кессона.
нет наверное смысла пробовать - не помню в каком релизе начал игры с протеусом, надо было сразу в Мплабе делать. Попробую на досуге еще поразбираться.
- ARV
- Ум, честь и совесть. И скромность.
- Сообщения: 18571
- Зарегистрирован: Чт дек 28, 2006 08:19:56
- Откуда: Новочеркасск
- Контактная информация:
Re: Программа для PIC12F629, подогреватель кессона.
Есть микросхема DS1620, готовый термостат, микроконтроллер не нужен, программирование на любом языке тоже не требуется. Прошивается по протоколу SPI, т.е. можно прошить простейшим программатором "5 проводков". Стоит, если поискать, рублей 200. Если не найдете - обращайтесь, у меня есть лишние. Могу и прошить сразу.
если рассматривать человека снизу, покажется, что мозг у него глубоко в жопе
при взгляде на многих сверху ничего не меняется...
Мой уютный бложик... заходите!
при взгляде на многих сверху ничего не меняется...
Мой уютный бложик... заходите!
- oleg110592
- Друг Кота
- Сообщения: 3832
- Зарегистрирован: Сб сен 10, 2011 17:46:25
Re: Программа для PIC12F629, подогреватель кессона.
поэксперементировал - взял код работы с DS18B20 от производителя самого датчика (Application Note 162: Interfacing the DS18x20/DS1822 1- Wire Temperature Sensor in a Microcontroller Environment), скопипастил в протеусный проект. Повысил температуру срабатывания, чтоб со льдом не мучиться - если temperature >= 30.0С то GP2=0, если temperature <= 28.0С GP2=1. Нагрев легко осуществляется всего двумя пальцами.
Минутную задержку закоментировал. В протеусе работает, в железе тоже.
Спойлер
Код: Выделить всё
#include <xc.h>
#pragma config MCLRE=OFF
#pragma config CP=ON
#pragma config CPD=OFF
#pragma config BOREN=ON
#pragma config WDTE=ON
#pragma config PWRTE=ON
#pragma config FOSC=INTRCIO
#ifndef _XTAL_FREQ
// Unless already defined assume 4MHz system frequency
// This definition is required to calibrate __delay_us() and __delay_ms()
#define _XTAL_FREQ 4000000U
#endif
#define DQ GP1
#define DQ_TRIS TRISIO1
#define CONVERT_TEMP 0x44
#define WRITE_SCRATCHPAD 0x4E
#define READ_SCRATCHPAD 0xBE
#define COPY_SCRATCHPAD 0x48
#define RECALL_E2 0xB8
#define READ_POWER_SUPPLY 0xB4
#define SKIP_ROM 0xCC
int temperature;
unsigned char ds18b20[9];
const unsigned char crc_array[256] =
{
0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83,
0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41,
0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e,
0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc,
0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0,
0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62,
0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d,
0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff,
0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5,
0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07,
0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58,
0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a,
0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6,
0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24,
0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b,
0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9,
0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f,
0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd,
0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92,
0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50,
0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c,
0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee,
0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1,
0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73,
0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49,
0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b,
0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4,
0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16,
0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a,
0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8,
0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7,
0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35,
};
unsigned char Count_crc_dallas(unsigned char *buf, unsigned char size)
{
unsigned char crc = 0;
for (; size > 0; size--)
{
crc = crc_array[(*buf) ^ crc];
buf++;
}
return (crc);
}
//Application Note 162: Interfacing the DS18x20/DS1822 1- Wire Temperature Sensor in a Microcontroller Environment
//////////////////////////////////////////////////////////////////////////////
// OW_RESET - performs a reset on the one-wire bus and
// returns the presence detect. Reset is 480us, so delay
// value is 480. Presence checked,
// another 70us later.
//
unsigned char ow_reset(void)
{
unsigned char presence;
DQ = 0; //pull DQ line low
DQ_TRIS = 0;
__delay_us(480); // leave it low for 480us
DQ_TRIS = 1; // allow line to return high
__delay_us(70); // wait for presence
presence = DQ; // get presence signal
__delay_us(440); // wait for end of timeslot
return(presence); // presence signal returned
} // 0=presence, 1 = no part
//////////////////////////////////////////////////////////////////////////////
// READ_BIT - reads a bit from the one-wire bus. The delay
// required for a read is 15us, so the DELAY routine won't work.
// We put our own delay function in this routine in the form of a
// for() loop.
//
unsigned char read_bit(void)
{
DQ = 0; // pull DQ low to start timeslot
DQ_TRIS = 0;
__delay_us(2);
DQ_TRIS = 1; // then return high
__delay_us(15); // delay 15us from start of timeslot
return(DQ); // return value of DQ line
}
//////////////////////////////////////////////////////////////////////////////
// WRITE_BIT - writes a bit to the one-wire bus, passed in bitval.
//
void write_bit(char bitval)
{
DQ = 0; // pull DQ low to start timeslot
DQ_TRIS = 0;
if(bitval==1) DQ_TRIS = 1; // return DQ high if write 1
__delay_us(104); // hold value for remainder of timeslot
DQ_TRIS = 1;
}// Delay provides = 104us
//////////////////////////////////////////////////////////////////////////////
// READ_BYTE - reads a byte from the one-wire bus.
//
unsigned char read_byte(void)
{
unsigned char i;
unsigned char value = 0;
for (i=0;i<8;i++)
{
if(read_bit()) value|=0x01<<i; // reads byte in, one byte at a time and then
// shifts it left
__delay_us(120); // wait for rest of timeslot
}
return(value);
}
//////////////////////////////////////////////////////////////////////////////
// WRITE_BYTE - writes a byte to the one-wire bus.
//
void write_byte(char val)
{
unsigned char i;
unsigned char temp;
for (i=0; i<8; i++) // writes byte, one bit at a time
{
temp = val>>i; // shifts val right 'i' spaces
temp &= 0x01; // copy that bit to temp
write_bit(temp); // write bit in temp into
}
__delay_us(104);
}
void main(void)
{
unsigned char i;
GPIO = 0x00;
CMCON = 0x07;
TRISIO = 0x00;
CLRWDT();
PS0 = 1; // :128 – 2.3 sec
PS1 = 1;
PS2 = 1;
PSA = 1; // WDT
while (1)
{
CLRWDT();
GP0=1;
__delay_ms(300);
ow_reset();
write_byte(SKIP_ROM);
write_byte(CONVERT_TEMP);
__delay_ms(1000);
ow_reset();
write_byte(SKIP_ROM);
write_byte(READ_SCRATCHPAD);
ds18b20[0] = read_byte();
ds18b20[1] = read_byte();
ds18b20[2] = read_byte();
ds18b20[3] = read_byte();
ds18b20[4] = read_byte();
ds18b20[5] = read_byte();
ds18b20[6] = read_byte();
ds18b20[7] = read_byte();
ds18b20[8] = read_byte();
temperature=ds18b20[0];
temperature+=(unsigned int)ds18b20[1]<<8;
if((ds18b20[1] & (1<<7))==0)
{
temperature*=5;
temperature>>=3;
}
else
{
temperature=-temperature;
temperature*=5;
temperature>>=3;
temperature=-temperature;
}
GP0=0;
//if(presence)
if(Count_crc_dallas(ds18b20, 8) == ds18b20[8])
{
if(temperature >= 300) GP2=0;
if(temperature <= 280) GP2=1;
}
else
GP2=0;
// for (i = 0; i < 60; i++)
// {
// CLRWDT();
// __delay_ms(1000);
// }
}
}-
vk696
- Нашел транзистор. Понюхал.
- Сообщения: 152
- Зарегистрирован: Пн мар 06, 2017 18:53:23
- Откуда: Казань.
Re: Программа для PIC12F629, подогреватель кессона.
Если делать лень, купи у китайцев что то вроде этого. датчик температуры там уже есть, термопара.
https://ru.aliexpress.com/item/90-250V1 ... 33edOGCxb3
если уж так хочешь ibuttion, то лучше купить защищенный от влаги и ударов
https://ru.aliexpress.com/item/15937-Fr ... 33edID8Nbl
Надежность DS18B20 спорная, бывают вылетают.
код с умом нужно писать, с защитой от сбоев, да и схему питания стоит сделать надежную.
Если действительно хочешь сам наваять, могу поделиться функциями работы с DS18B20 на Си. все работает 100%
https://ru.aliexpress.com/item/90-250V1 ... 33edOGCxb3
если уж так хочешь ibuttion, то лучше купить защищенный от влаги и ударов
https://ru.aliexpress.com/item/15937-Fr ... 33edID8Nbl
Надежность DS18B20 спорная, бывают вылетают.
код с умом нужно писать, с защитой от сбоев, да и схему питания стоит сделать надежную.
Если действительно хочешь сам наваять, могу поделиться функциями работы с DS18B20 на Си. все работает 100%
- Аlex
- Модератор
- Сообщения: 4614
- Зарегистрирован: Чт мар 18, 2010 23:09:57
- Откуда: Планета Земля
- Контактная информация:
Re: Программа для PIC12F629, подогреватель кессона.
Почему бы Вам не поделиться ими со всеми, выложив его сюда ? Ну, или в соответствующую тему - https://radiokot.ru/forum/viewtopic.php?f=61&t=64022vk696 писал(а):Если действительно хочешь сам наваять, могу поделиться функциями работы с DS18B20 на Си. все работает 100%
-
vk696
- Нашел транзистор. Понюхал.
- Сообщения: 152
- Зарегистрирован: Пн мар 06, 2017 18:53:23
- Откуда: Казань.
Re: Программа для PIC12F629, подогреватель кессона.
[uquote="Аlex",url="/forum/viewtopic.php?p=3396133#p3396133"]Почему бы Вам не поделиться ими со всеми[/uquote]
Действительно, а почему бы и нет.
Заголовок
#define DALLAS PORTDbits.RD0 //
struct FLAG_DS {
unsigned ERR_DS : 1; // error reset
unsigned DS_ON : 1;
unsigned minus_C : 1;
unsigned Zmin : 1;
unsigned b4 : 1;
unsigned b5 : 1;
unsigned b6 : 1;
unsigned b7 : 1;
} FLAG_DS;
unsigned char BUFF_DS [10];
//unsigned char DS_BYTE;
unsigned char T10_D0; // low bytes temperature in decimal notation
unsigned char T10_D1; // hi bytes temperature in decimal notation
unsigned char D4, D3, D2, D1; // for display in-14 tube
//char crc;
unsigned int celsius;
//int temperatura;
char RESET_dallas (void); //RESET
void TR_BYTE_dallas (unsigned char); // TRANSIVE 8 BIT
char RC_BYTE_dallas (void); // RECIVE 8 BIT
//char CRC_Bits (int data); // calculation crc
void DS_9b_temp (void);
void init_DS_9b (void);
void convert_T (void); // convert T to degree
Функции
// 8 bit femely code (1 byte), 48 bit unique adres (6 byte), 8 bit crc (1 byte) = 64 bit (8 byte)
// CRC-8-Dallas/Maxim. polinome x^8 + x^5 + x^4 +1. represent 0x31 / 0x8C / 0x98
#include <xc.h>
#include "header_pr.h"
#include "DS18D20.h"
//#define _XTAL_FREQ 20000000 // specify the frequency of the processor for the delay functions
/*unsigned char var,bitno,mask;
#define bitset(var,bitno) ((var)|=1<<(bitno))
#define bitclr(var,bitno) ((var)&=~(1<<(bitno)))
#define testbit(var,bitno) ((var>>bitno)&0x01) // chek 1
#define testbit_0(var,bitno) (!((var>>bitno))&0x01) // chek 0
#define bits_on (var, mask) var |= mask //
#define bits_off (var, mask) var &= ~ 0 ^ mask
///////////////////////////////////////////////////////////////////////////////
*/
char RESET_dallas (void) {
char ERR_LINE; // var ERROR RESET
char i;
DALLAS=0;
TRISDAL=0;
__delay_us(500); // wait 500us
GIE=0; // dis interrupt
ERR_LINE=0;//
TRISDAL=1;
// wait "0" present impulse
__delay_us(15);
i=0;
while (ERR_LINE==0&&DALLAS==1)
{
if(++i>120)ERR_LINE=1; // wait 240 us, obryv
}
// wait "1" present impulse
i=0;
while (ERR_LINE==0&&DALLAS==0)
{
if(++i>120)ERR_LINE=2; //wait 240 us, kz
}
GIE=1; // en interrupt
__delay_us(500); // wait 500us
return ERR_LINE;
}
void TR_BYTE_dallas (unsigned char DS_BYTE) {
unsigned char j;
j=0;
for (j=0; j<=0x07; j++ ) {
////////////////////////////////////// time slot
GIE=0; // dis interrupt
DALLAS=0;
TRISDAL=0;
__delay_us(10);
if (testbit (DS_BYTE,j)) TRISDAL=1;
__delay_us(60);
TRISDAL=1;
GIE=1; // en interrupt
/////////////////////////////////////
}
}
char RC_BYTE_dallas (void) {
unsigned char TEMP;
TEMP=0x00;
unsigned char j;
for (j=0; j<=0x07; j++ ) {
GIE=0; // dis interrupt
DALLAS=0;
TRISDAL=0;
__delay_us(1);
TRISDAL=1;
__delay_us(10);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
else bitclr (TEMP,j);
GIE=1; // en interrupt
__delay_us(60);
}
return TEMP;
}
void init_DS_9b (void){
unsigned char i,j;
FLAG_DS.ERR_DS=0;
i=RESET_dallas ();
if (i!=0) {FLAG_DS.ERR_DS=1;
return;}
TR_BYTE_dallas (0xCC); // skip ROM
TR_BYTE_dallas (0x4E); // write SRAM
TR_BYTE_dallas (0x00); // Th
TR_BYTE_dallas (0xFF); // Lh
TR_BYTE_dallas (0x1F); // config 9bit
}
void DS_9b_temp (void){
unsigned char i,j,k;
i=RESET_dallas ();
if (i!=0) {FLAG_DS.ERR_DS=1;
return;}
TR_BYTE_dallas (0xCC); // skip ROM
TR_BYTE_dallas (0x44); // convert
__delay_ms(100);
i=RESET_dallas ();
if (i!=0) {FLAG_DS.ERR_DS=1;
return;}
TR_BYTE_dallas (0xCC); // skip ROM
TR_BYTE_dallas (0xBE); // read SRAM
for (j=0; j<9; j++) {
k=RC_BYTE_dallas (); // begin read ROM;
*(BUFF_DS+j)=k; }
}
void convert_T (void) {
unsigned int degree=0x0000;
//unsigned char D4, D3, D2, D1;
//GIE=0; // dis interrupt
// highByte lowByte
degree=(BUFF_DS[1]<<8) | BUFF_DS[0]; //Convert the two bytes of the temperature in the 16-bit integer
if (testbit (BUFF_DS[1],7)) {FLAG_DS.minus_C=1; // minus test
degree=(degree^0xFFFF)+1; } // Invert the bits, if the sign is negative and adds one
else FLAG_DS.minus_C=0;
/*
* With positive (S=0) temperature is necessary to obtain these meanings divide by 16, and then converted to a decimal representation.
* In subzero (S=1) temperatures it is necessary to invert these meanings produced bit by bit and add 1,
* then divide by 16, and then converted to a decimal representation.
*/
degree=degree>>4; // divide by 16
//HEX to DEC
D1 = degree % 0x0A; // discharge indicator 1
D2 = (degree / 0x0A) % 0x0A; // discharge indicator 2
D3 = ((degree / 0x0A) / 0x0A) % 0x0A; // discharge indicator 3
D4 = (((degree / 0x0A) / 0x0A) / 0x0A) % 0x0A; // discharge indicator 4
degree=0x00;
//put a decimal value to a variable int
degree = degree | D4;
degree = degree<<4;
degree = degree | D3;
degree = degree<<4;
degree = degree | D2;
degree = degree<<4;
degree = degree | D1;
celsius=degree;
T10_D0 = D1;
T10_D1= D2;
}
/*
//crc_bits
char CRC_BITS (int data)
{
int i = (data ^ crc) & 0xff;
crc = 0;
if(i & 0b00000001)crc ^= 0x5e;
if(i & 0b00000010)crc ^= 0xbc;
if(i & 0b00000100)crc ^= 0x61;
if(i & 0b00001000)crc ^= 0xc2;
if(i & 0b00010000)crc ^= 0x9d;
if(i & 0b00100000)crc ^= 0x23;
if(i & 0b01000000)crc ^= 0x46;
if(i & 0b10000000)crc ^= 0x8c;
return crc;
}//---------------------------------------------------------------------------------------
*/
Действительно, а почему бы и нет.
Заголовок
Спойлер
#define TRISDAL TRISD0 //#define DALLAS PORTDbits.RD0 //
struct FLAG_DS {
unsigned ERR_DS : 1; // error reset
unsigned DS_ON : 1;
unsigned minus_C : 1;
unsigned Zmin : 1;
unsigned b4 : 1;
unsigned b5 : 1;
unsigned b6 : 1;
unsigned b7 : 1;
} FLAG_DS;
unsigned char BUFF_DS [10];
//unsigned char DS_BYTE;
unsigned char T10_D0; // low bytes temperature in decimal notation
unsigned char T10_D1; // hi bytes temperature in decimal notation
unsigned char D4, D3, D2, D1; // for display in-14 tube
//char crc;
unsigned int celsius;
//int temperatura;
char RESET_dallas (void); //RESET
void TR_BYTE_dallas (unsigned char); // TRANSIVE 8 BIT
char RC_BYTE_dallas (void); // RECIVE 8 BIT
//char CRC_Bits (int data); // calculation crc
void DS_9b_temp (void);
void init_DS_9b (void);
void convert_T (void); // convert T to degree
Спойлер
// structure ROM DS18d20// 8 bit femely code (1 byte), 48 bit unique adres (6 byte), 8 bit crc (1 byte) = 64 bit (8 byte)
// CRC-8-Dallas/Maxim. polinome x^8 + x^5 + x^4 +1. represent 0x31 / 0x8C / 0x98
#include <xc.h>
#include "header_pr.h"
#include "DS18D20.h"
//#define _XTAL_FREQ 20000000 // specify the frequency of the processor for the delay functions
/*unsigned char var,bitno,mask;
#define bitset(var,bitno) ((var)|=1<<(bitno))
#define bitclr(var,bitno) ((var)&=~(1<<(bitno)))
#define testbit(var,bitno) ((var>>bitno)&0x01) // chek 1
#define testbit_0(var,bitno) (!((var>>bitno))&0x01) // chek 0
#define bits_on (var, mask) var |= mask //
#define bits_off (var, mask) var &= ~ 0 ^ mask
///////////////////////////////////////////////////////////////////////////////
*/
char RESET_dallas (void) {
char ERR_LINE; // var ERROR RESET
char i;
DALLAS=0;
TRISDAL=0;
__delay_us(500); // wait 500us
GIE=0; // dis interrupt
ERR_LINE=0;//
TRISDAL=1;
// wait "0" present impulse
__delay_us(15);
i=0;
while (ERR_LINE==0&&DALLAS==1)
{
if(++i>120)ERR_LINE=1; // wait 240 us, obryv
}
// wait "1" present impulse
i=0;
while (ERR_LINE==0&&DALLAS==0)
{
if(++i>120)ERR_LINE=2; //wait 240 us, kz
}
GIE=1; // en interrupt
__delay_us(500); // wait 500us
return ERR_LINE;
}
void TR_BYTE_dallas (unsigned char DS_BYTE) {
unsigned char j;
j=0;
for (j=0; j<=0x07; j++ ) {
////////////////////////////////////// time slot
GIE=0; // dis interrupt
DALLAS=0;
TRISDAL=0;
__delay_us(10);
if (testbit (DS_BYTE,j)) TRISDAL=1;
__delay_us(60);
TRISDAL=1;
GIE=1; // en interrupt
/////////////////////////////////////
}
}
char RC_BYTE_dallas (void) {
unsigned char TEMP;
TEMP=0x00;
unsigned char j;
for (j=0; j<=0x07; j++ ) {
GIE=0; // dis interrupt
DALLAS=0;
TRISDAL=0;
__delay_us(1);
TRISDAL=1;
__delay_us(10);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
if (DALLAS==1) bitset (TEMP,j);
else bitclr (TEMP,j);
GIE=1; // en interrupt
__delay_us(60);
}
return TEMP;
}
void init_DS_9b (void){
unsigned char i,j;
FLAG_DS.ERR_DS=0;
i=RESET_dallas ();
if (i!=0) {FLAG_DS.ERR_DS=1;
return;}
TR_BYTE_dallas (0xCC); // skip ROM
TR_BYTE_dallas (0x4E); // write SRAM
TR_BYTE_dallas (0x00); // Th
TR_BYTE_dallas (0xFF); // Lh
TR_BYTE_dallas (0x1F); // config 9bit
}
void DS_9b_temp (void){
unsigned char i,j,k;
i=RESET_dallas ();
if (i!=0) {FLAG_DS.ERR_DS=1;
return;}
TR_BYTE_dallas (0xCC); // skip ROM
TR_BYTE_dallas (0x44); // convert
__delay_ms(100);
i=RESET_dallas ();
if (i!=0) {FLAG_DS.ERR_DS=1;
return;}
TR_BYTE_dallas (0xCC); // skip ROM
TR_BYTE_dallas (0xBE); // read SRAM
for (j=0; j<9; j++) {
k=RC_BYTE_dallas (); // begin read ROM;
*(BUFF_DS+j)=k; }
}
void convert_T (void) {
unsigned int degree=0x0000;
//unsigned char D4, D3, D2, D1;
//GIE=0; // dis interrupt
// highByte lowByte
degree=(BUFF_DS[1]<<8) | BUFF_DS[0]; //Convert the two bytes of the temperature in the 16-bit integer
if (testbit (BUFF_DS[1],7)) {FLAG_DS.minus_C=1; // minus test
degree=(degree^0xFFFF)+1; } // Invert the bits, if the sign is negative and adds one
else FLAG_DS.minus_C=0;
/*
* With positive (S=0) temperature is necessary to obtain these meanings divide by 16, and then converted to a decimal representation.
* In subzero (S=1) temperatures it is necessary to invert these meanings produced bit by bit and add 1,
* then divide by 16, and then converted to a decimal representation.
*/
degree=degree>>4; // divide by 16
//HEX to DEC
D1 = degree % 0x0A; // discharge indicator 1
D2 = (degree / 0x0A) % 0x0A; // discharge indicator 2
D3 = ((degree / 0x0A) / 0x0A) % 0x0A; // discharge indicator 3
D4 = (((degree / 0x0A) / 0x0A) / 0x0A) % 0x0A; // discharge indicator 4
degree=0x00;
//put a decimal value to a variable int
degree = degree | D4;
degree = degree<<4;
degree = degree | D3;
degree = degree<<4;
degree = degree | D2;
degree = degree<<4;
degree = degree | D1;
celsius=degree;
T10_D0 = D1;
T10_D1= D2;
}
/*
//crc_bits
char CRC_BITS (int data)
{
int i = (data ^ crc) & 0xff;
crc = 0;
if(i & 0b00000001)crc ^= 0x5e;
if(i & 0b00000010)crc ^= 0xbc;
if(i & 0b00000100)crc ^= 0x61;
if(i & 0b00001000)crc ^= 0xc2;
if(i & 0b00010000)crc ^= 0x9d;
if(i & 0b00100000)crc ^= 0x23;
if(i & 0b01000000)crc ^= 0x46;
if(i & 0b10000000)crc ^= 0x8c;
return crc;
}//---------------------------------------------------------------------------------------
*/
- КРАМ
- Друг Кота
- Сообщения: 25283
- Зарегистрирован: Чт янв 10, 2008 22:01:02
- Откуда: Московская область, Фрязино
Re: Программа для PIC12F629, подогреватель кессона.
Если честно, то мне не нравятся блокирующие функции.
Их первый признак - бесконечные delay. Оно канешна заманчиво, но не куртуазно. Ибо не масштабируется в иные проекты совершенно.
Хотя многих привлекают простотой.
Их первый признак - бесконечные delay. Оно канешна заманчиво, но не куртуазно. Ибо не масштабируется в иные проекты совершенно.
Хотя многих привлекают простотой.
Re: Программа для PIC12F629, подогреватель кессона.
Крам , дма+усарт ...


