/*------------------------------------------------------- * 读取转换后的温度值 * 我假定DS18B20一定是正确的,所以没有返回有关状态。当你故意把DS18B20从电路中拔下而能让程序告诉你出错时,你可以自己修 改这段代码! */ INT16U read_T(void) { INT16U value=0; if(ds18b20_reset()==SUCC) { // 如果复位成功 ds18b20_write(0xcc); // 跳过多器件识别 ds18b20_write(0xbe); // 读暂存器 value = (INT16U)ds18b20_read(); // 低字节 value += (INT16U)(ds18b20_read())<<8; // 高字节 } return(value); }
__task void CMDHandler(void) { uint8_t write_buf[128]={0}; uint8_t read_buf[128]={0}; uint8_t i=0; uint32_t err_count=0; uint32_t ok_count=0; unsigned short tmp=0; os_dly_wait(300); // // 10MS * 10 = 100 mS Serial_PutString("AT\r\n"); os_dly_wait(50); // // 10MS * 10 = 100 mS Serial_PutString("ATE1\r\n"); os_dly_wait(50); // // 10MS * 10 = 100 mS Serial_PutString("AT+CPIN?\r\n"); os_dly_wait(100); // // 10MS * 10 = 100 mS ds18b20_start(); while (1) { Serial_PutString("AT+CSQ\r\n"); ShowTime(); printf("ACC:%5.2f %5.2f %5.2f GYRO: %5.2f %5.2f %5.2f\r\n\r\n",Acc_Buffer[0],Acc_Buffer[1],Acc_Buffer[2], Gyro_Buffer[0],Gyro_Buffer[1],Gyro_Buffer[2]); printf("SLOAR: %d, CHARGE: %d, BAT: %d (ADC Value)\r\n",Adc1Result.Channel_8, Adc1Result.Channel_9, Adc1Result.Channel_15); for(i=0;i<128;i++) write_buf[i]=rand(); at25_write_page(0x00,128,write_buf); at25_read_page(0x00,128,read_buf); if(memcmp(read_buf,write_buf,128) == 0) { printf("> FRAM Write successed : %d\r\n" ,++ok_count); } else { printf("> FRAM Write failed: %d\r\n",++err_count); } tmp=ds18b20_read(); printf("> Tmp: %.1f (%d)\r\n",(tmp*0.0039),tmp); if(flag_usart3_rx==1) { flag_usart3_rx=0; printf("%s",UART3RecvBuf); printf("\r\n"); } printf("---------------------------------------------------------------------------\r\n\r\n"); os_dly_wait(100); // // 10MS * 10 = 100 mS } }
void main(){ int temp1, temp2,temp3; // Bien duoc do ra tu EEPROM int keypad[10],i, position; int B_ENTER, B_EXIT, E0; temp1 = read_eeprom(add_setup_temp_1); temp2 = read_eeprom(add_setup_temp_2); temp3 = read_eeprom(add_setup_temp_3); nhietdo_setup = temp1*10 + temp2 + temp3*0.1; //Gia tri nhiet do setup Output_low(LCD_RW); LCD_Init(); TRISB = 0xFF; TRISE = 0xFF; LCD_PutCmd(0x01); LCD_SetPosition(0x00); //Chuyen vi tri con tro sang dong 1 printf(lcd_putchar,"Setup: %.1f",nhietdo_setup); lcd_putchar(223); printf(lcd_putchar,"C"); while (true){ //Doc gia tri nhiet do tu cam bien DS18B20 temp_float = ds18b20_read(); LCD_SetPosition(0x40); //Chuyen vi tri con tro sang dong 2 printf(lcd_putchar,"Measure: %.1f",temp_float); lcd_putchar(223); printf(lcd_putchar,"C"); OF_RELAY(temp_float, nhietdo_setup); E0 = input(SETUP_EXIT); if (E0 == 0){ //while (input(SETUP_EXIT)==0) ; LCD_PutCmd(0x01); LCD_SetPosition(0x00); printf(lcd_putchar,"SETUP TEMP: "); delay_ms(1000); i = 0; position = 64; //Khi chua nhan nut EXIT hay ENTER B_EXIT = input(SETUP_EXIT); B_ENTER = input(ENTER); while ((B_ENTER==1) | (B_EXIT == 1)){ int value; B_EXIT = input(SETUP_EXIT); B_ENTER = input(ENTER); value = READ_BUTTON(); //Chi cho nhap va hien thi 3 so if ((value >= 0) && (value < 10) && (i<=2)){ LCD_SetPosition(position); printf(lcd_putchar,"%d",value); delay_ms(1000); keypad[i] = value; i++; position++; } else //Khi da nhap du 3 so va nhan nut ENTER if ((value == 100) && (i>=3)){ write_eeprom(add_setup_temp_1,keypad[0]); write_eeprom(add_setup_temp_2,keypad[1]); write_eeprom(add_setup_temp_3,keypad[2]); temp1 = read_eeprom(add_setup_temp_1); temp2 = read_eeprom(add_setup_temp_2); temp3 = read_eeprom(add_setup_temp_3); nhietdo_setup = temp1*10 + temp2 + temp3*0.1; //Gia tri nhiet do setup LCD_PutCmd(0x01); LCD_SetPosition(0x00); //Chuyen vi tri con tro sang dong 1 printf(lcd_putchar,"Setup: %.1f",nhietdo_setup); lcd_putchar(223); printf(lcd_putchar,"C"); temp_float = ds18b20_read(); LCD_SetPosition(0x40); //Chuyen vi tri con tro sang dong 2 printf(lcd_putchar,"Measure: %.1f",temp_float); lcd_putchar(223); printf(lcd_putchar,"C"); break; } else if (value == 50){ //Khi da nhan nut EXIT thi thoat khoi vong lap LCD_PutCmd(0x01); LCD_SetPosition(0x00); //Chuyen vi tri con tro sang dong 1 printf(lcd_putchar,"Setup: %.1f",nhietdo_setup); lcd_putchar(223); printf(lcd_putchar,"C"); temp_float = ds18b20_read(); LCD_SetPosition(0x40); //Chuyen vi tri con tro sang dong 2 printf(lcd_putchar,"Measure: %.1f",temp_float); lcd_putchar(223); printf(lcd_putchar,"C"); break; } } } } }
/* ******************************************************************** * MAIN PROGRAM * * Read the user option of the commandline and either print to stdout * or return the value over the socket. * * ******************************************************************** */ int main(int argc, char **argv) { int i,c; int errflg = 0; int repeats = 1; int temp = 0; int temp_int, temp_frac; // interger and fracture part for temperature char *hostname = "localhost"; // Default setting for our host == this host char *port = PORT; // default port, 5000 char snd_buf[256]; extern char *optarg; extern int optind, optopt; // ------------------------- COMMANDLINE OPTIONS SETTING ---------------------- // Valid options are: // -h <hostname> ; hostname or IP address of the daemon // -p <port> ; Portnumber for daemon socket // -v ; Verbose, Give detailed messages // while ((c = getopt(argc, argv, ":c:dh:p:r:stvx")) != -1) { switch(c) { case 'c': cflg = 1; // Checks checks = atoi(optarg); break; case 'd': // Daemon mode, cannot be together with test? dflg = 1; break; case 'h': // Socket communication dflg++; // Need daemon flag too, (implied) hostname = optarg; break; case 'p': // Port number port = optarg; dflg++; // Need daemon flag too, (implied) break; case 'r': // repeats repeats = atoi(optarg); break; case 's': // Statistics sflg = 1; break; case 't': // Test Mode, do debugging debug=1; break; case 'v': // Verbose, output long timing/bit strings verbose = 1; break; case ':': // -f or -o without operand fprintf(stderr,"Option -%c requires an operand\n", optopt); errflg++; break; case '?': fprintf(stderr, "Unrecognized option: -%c\n", optopt); errflg++; } } // -------------------- PRINT ERROR --------------------------------------- // Print error message if parsing the commandline // was not successful if (errflg) { fprintf(stderr, "usage: argv[0] (options) \n\n"); fprintf(stderr, "-d\t\t; Daemon mode. Codes received will be sent to another host at port 5000\n"); fprintf(stderr, "-s\t\t; Statistics, will gather statistics from remote\n"); fprintf(stderr, "-t\t\t; Test mode, will output received code from remote\n"); fprintf(stderr, "-v\t\t; Verbose, will output more information about the received codes\n"); exit (2); } // ------------------ PRINTING Parameters ------------------------------ // if (verbose == 1) { printf("The following options have been set:\n\n"); printf("-v\t; Verbose option\n"); if (statistics>0) printf("-s\t; Statistics option\n"); if (dflg>0) printf("-d\t; Daemon option\n"); if (debug) printf("-t\t; Test and Debug option"); printf("\n"); }//if verbose // If we are in daemon mode, initialize sockets etc. // if (dflg) { daemon_mode(hostname, port); } if (sflg) { fprintf(stderr,"init statistics\n"); init_statistics(statistics); // Make cells 0 } chdir (SPATH); // ------------------------ // MAIN LOOP // if (verbose) printf("\nRepeats: %d::\n",repeats); for (i=0; i<repeats; i++) { // For every directory found in SPATH DIR *dir; struct dirent *ent; if ((dir = opendir (SPATH)) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { if (verbose) printf ("%s\n", ent->d_name); // 28 is the prefix for ds18b20 if (strncmp(ent->d_name,"28",2) == 0) { temp = ds18b20_read(ent->d_name); temp_int = temp/1000; temp_frac = temp%1000; if (dflg) { // Daemon, output to socket sprintf(snd_buf, "{\"tcnt\":\"%d\",\"action\":\"weather\",\"brand\":\"ds18b20\",\"type\":\"json\",\"address\":\"%s\",\"channel\":\"%d\",\"temperature\":\"%d.%d\",\"humidity\":\"%d\",\"windspeed\":\"%d\",\"winddirection\":\"%d\"}", socktcnt%1000, ent->d_name, 0, temp_int, temp_frac, 0, 0, 0); // Do NOT use check_n_write_socket as weather stations will not // send too many repeating messages (1 or 2 will come in one trasmission) // if (write(sockfd, snd_buf, strlen(snd_buf)) == -1) { fprintf(stderr,"socket write error\n"); } socktcnt++; delay(200); if (verbose) printf("Buffer sent to Socket: %s\n",snd_buf); } else { // Commandline if (temp > 0) { printf("Temperature for dev %s: %d.%d\n", ent->d_name, temp/1000,temp%1000); } else { temp = -temp; printf("Temperature for dev %s: -%d.%d\n", ent->d_name, temp/1000,temp%1000); } } } } closedir (dir); } else { /* could not open directory */ perror ("No such directory "); return EXIT_FAILURE; } } delay(1500); // Should wait for confirmation of the daemon before closing exit(EXIT_SUCCESS); }
int main() { //! Инициализация портов для светодиодов. DDRF |= (1 << DDF0 | 1 << DDF1 | 1 << DDF2 | 1 << DDF3); //! Инициализация порта для пьезоизлучателя. DDRB |= (1 << DDB0); //! Инициализация портов для строк клавиатуры. Строки на ввод. DDRD &= ~(1 << DDD4 | 1 << DDD5 | 1 << DDD6 | 1 << DDD7); //! Инициализация портов для строк клавиатуры. Поддяжка к питанию. PORTD |= (1 << PD4 | 1 << PD5 | 1 << PD6 | 1 << PD7); //! Инициализация портов для столбцоы клавиатуры. столбцы на вывод. DDRG |= (1 << DDG0 | 1 << DDG1 | 1 << DDG2); //! Инициализация таймера для излучателя звука. TCCR3A = 0; TCCR3A = 0; TCCR3B = 0; TCCR3B_struct.cs3 = 0x01; // Предделитель: F_CPU/1 TIMSK3_struct.toie3 = 1; // Разрешаем прерывание по переполнению TCNT3 = -8000; // 8000 тактов центрального проессора ~ 500 мкс. //! Инициализация таймера для смены режимов. TCCR4A = 0; TCCR4A = 0; TCCR4B = 0; uint8_t key1, key2 = 0; //!< Переменные для хранения кода нажатых клавишь. uint8_t i; char tx_buff_str[16]; //! Структура для чтения времени. //! Перед первым использованием должна быть инициализирована. ds18b20_memory_t ds18b20_memory = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int16_t temper = 0; //! Структура для чтения времени. //! Перед первым использованием должна быть инициализирована. rtc_data_r_t time = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //rtc_data_w_t time_w = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //!< Структура для установки времени. uint8_t sec; I2C_Master_Initialise(); //!< Инициализация I2C интерфейса. ds18b20_convert(); //!< Запуск преобразование температуры. uart_init(); //!< Инициализируем UART. uart_set_input_cb(uart_rx_cb);// Устанавливаем функцию обратного вызова на прием байта по UART. printf("\n\rLESO laboratory (c) 2014\r\nDemo test program\r\n"); printf("LESO6 ATMEGA128RFA1\r\n"); fprintf(stderr, "stderr: NO ERRORS\r\n"); //! Массив с описанием символа градуса. uint8_t ch[8] = { 0x06, /*x x x 0 0 1 1 0*/ 0x09, /*x x x 0 1 0 0 1*/ 0x09, /*x x x 0 1 0 0 1*/ 0x06, /*x x x 0 0 1 1 0*/ 0x00, /*x x x 0 0 0 0 0*/ 0x00, /*x x x 0 0 0 0 0*/ 0x00, /*x x x 0 0 0 0 0*/ 0x00 /*x x x 0 0 0 0 0*/ }; //! Управлящая структура для ЖКИ. lcd_t lcd = { 0, 0, 0, 0, 0 }; lcdInit(&lcd); //!< Инициализируем ЖКИ; lcdCursor(&lcd, 0); //!< Выключаем курсор. lcdCursorBlink(&lcd, 0); //!< Выключаем мерцание курсора. sprintf(tx_buff_str, " LESO6 \n 2014%c ", 0xb4); lcdPuts(&lcd, tx_buff_str); lcdCharDef(&lcd, 1, ch); //!< Определяем новый символ. for (i = 0; i < 75; i++) _delay_ms(10); getTimeDS1338(&time); //!< Читаем время. ds18b20_read(&ds18b20_memory); //!< Читаем температуру. sec = time.Second; TIMSK3_struct.toie3 = 0;// Запрещаем прерывание при переполнении таймера 3. off(BIP); // Выключаем звук. lcdClear(&lcd); lcdCursor(&lcd, 1); lcdPuts(&lcd, "Text:\n"); while (1) { while (key_mode) // В режиме набора текст: { key1 = getKeyChar(); for(i=0; i<5; i++) _delay_ms(10); key2 = getKeyChar(); if (key1 == '\n') continue; else if (key1 != key2) continue; TCNT4 = 0; // Дополнительное время работы в этом режиме if((lcd.cx) == lcd.cols)// закончились символы в строке { lcdPuts(&lcd,"\r \r");// стираем строку, возвращаем курсор в начало printf("\r\033[0K");// стираем строку в терминале } lcdPutchar(&lcd, key1); LEDS &= ~0x0F; LEDS |= 0x0F&key1; putchar(key1); TIMSK3_struct.toie3 = 1; // пик for(i=0; i<20; i++) _delay_ms(10); TIMSK3_struct.toie3 = 0; } printf("\r\033[0K%02u:%02u:%02u",time.Hour, time.Minute ,time.Second); sprintf(tx_buff_str, "%02u:%02u:%02u\n",time.Hour, time.Minute ,time.Second); lcdHome(&lcd); lcdPuts(&lcd, tx_buff_str); if(ds18b20_crc8((uint8_t *)&ds18b20_memory, sizeof(ds18b20_memory))) fprintf(stderr,"ERROR read DS18B20\r\n"); else { temper = (ds18b20_memory.temper_MSB << 8) | ds18b20_memory.temper_LSB; printf(" T= %d.%u",temper>>4, ((temper&0xf)*1000)/(16)); sprintf(tx_buff_str,"%02d.%u%cC ",temper>>4, ((temper&0xf)*1000)/(16), 0x01); lcdPuts(&lcd, tx_buff_str); } ds18b20_convert(); // Запуск преобразование температуры. while(sec == time.Second) { if (getTimeDS1338(&time)) { fprintf(stderr,"ERROR: read date fail..!\n\r"); continue; } key1 = getKeyChar(); if (key1 != '\n') { key_mode = 1; lcdClear(&lcd); lcdCursor(&lcd, 1); lcdPuts(&lcd,"Text:\n"); TCCR4B_struct.cs4 = 0x04; // Предделитель: F_CPU/256 TIMSK4_struct.toie4 = 1;// Разрешаем прерывание по переполнению TCNT4 = 0; printf("\r\033[0K");// стираем строку в терминале break; } for(i=0; i<20; i++) _delay_ms(10); } sec = time.Second; ds18b20_read(&ds18b20_memory); if(ds18b20_crc8((uint8_t *)&ds18b20_memory, sizeof(ds18b20_memory))) fprintf(stderr,"ERROR read DS18B20\r\n"); } return 0; }