STM32使用C标准库time.h里面的时间时钟函数

STM32使用time.h库函数操作时间日期 iar,用STM32实现time.h中时间日期库函数,完全的标准时间库,有time.h实现统一强大的日期计算 立即下载
AI摘要

本文介绍如何在嵌入式系统中使用标准C库中的time.h进行时间管理,包括使用IAR Embedded Workbench进行时间计算的方法,以及在有无调试器情况下实现时间管理的具体实例。

标准C里面已经定义好时间日期库time.h,在嵌入式里面并没有被限制使用。下面我们看一下怎样在IAR中使用time.h库。

有四个与时间相关的类型:clock_t、time_t、size_t 和 tm。类型 clock_t、size_t 和 time_t 能够把系统时间和日期表示为某种整数。
可以通过宏定义(_DLIB_TIME_USES_LONG, _DLIB_TIME_USES_64),决定clock_t、time_t是使用32位还是64位数据类型。
Data types and constants
clock_t Data type for representing time 
time_t Data type for representing time
struct tm

Structure that holds the following data:
int tm_sec;// Sec. // 秒,正常范围从 0 到 59,但允许至 61
int tm_min;// Min // 分,范围从 0 到 59
int tm_hour;// Time // 小时,范围从 0 到 23
int tm_mday; // Day // 一月中的第几天,范围从 1 到 31
int tm_mon;// Month // 月,范围从 0 到 11
int tm_year;// Year // 自 1900 年起的年数
int tm_wday;// Day of the week // 一周中的第几天,范围从 0 到 6,从星期日算起,星期日表示为 0
int tm_yday; // Elapsed date Among from the start of the year // 一年中的第几天,范围从 0 到 365,从 1 月 1 日算起
int tm_isdst;// Season flag, such as daylight saving time // 夏令时

CLOCKS_PER_SEC The number of times an internal timing event occurs per second

Functions that operate on time
clock Returns the time elapsed since the program was started
time Returns the current time, as the elapsed time in seconds since 00:00:00, January 1, 1970.
difftime Returns the elapsed time between two times, as the difference in seconds.
Conversion functions
asctime Converts a tm object to a string representation
ctime Converts a time_t  object to a string representation
gmtime Converts from a time_t object to tm object
localtime Converts  from  current time to  local time
strftime Converts a tm object into a specified format
mktime Converts from a tm object to a time_t object 

How to use time.h in IAR Embedded Workbench

In embedded systems, you need to write code that calculates the date and time in order to use the time.h functions. We introduce two cases for how to use and implement the time library in IAR Embedded Workbench.

The first case is applicable when using the debugger.Time information is provided from the debugger. The information is not available when the debugger is detached from the target board. The second example shows how to manage the time without using the debugger.

Example 1: Managing time information during debugging

If the debugger is available, the application can use the data/time library, and you do not need to implement anything else in order to manage time information. Below are two code examples: one using clock() and the other using time().

You can get the elapsed time from the system start by using a clock in the following way:

clock_t clk_time;

clk_time = clock ();
printf ("clock time:% dsec \ n", clk_time / CLOCKS_PER_SEC);

 You can also use string display conversion to get the date and time:

time_t now;
struct tm * ts;
char buf [80];

now = time (NULL);
ts = localtime (& now);
strftime (buf, sizeof (buf), "% a% Y-% m-% d% H:% M:% S% Z", ts);
printf ("% s \ n", buf);

This is the result of the above code examples:

clock time: 234sec
Sat 2015-07-11 00:11:40
...
Example 2: Implementation without the debugger

Without the debugger, the application must implement the low-level implementation of the date and time library. If you are using an RTOS, similar functions might be provided and you can use those.

The below example is for an ARM Cortex-M device, which has a Systick timer. The timer makes it easy to implement data and time functions. In this example, SysTick generates an interrupt every 1 msec.

We define two variables for time and clock and define CLOCKS_PER_SEC as ticks in one second:

#define CLOCKS_PER_SEC (1000)
clock_t clk_count = 0;
time_t time_dat;

We create an interrupt handler for the SysTick. 64bit variable is recommended for clk_count to avoid overflow. When an interrupt is generated, clk_count is incremented and time_dat is incremented if one second passes:

void SysTick_Handler (void) {
clk_count ++;
if ((clk_count% 1000) == 0) {
time_dat ++;
}
}

Two functions are implemented using variables:

clock_t clock (void) {
return (clk_count);
}

time_t __time32 (time_t * p) {
return time_dat;
}

The variable "clk_count" is initialized to 0 since clock() returns the elapsed time. The variable, "time_dat" should be initialized to the current time. We can use a conversion function to initialize it. This example uses mktime for the conversion:

struct tm orig;
orig.tm_sec = 10;
orig.tm_min = 46;
orig.tm_hour = 9;
orig.tm_mday = 10;
orig.tm_mon = 6;
orig.tm_year = 115;
orig.tm_wday = 5;
orig.tm_yday = 19;
orig.tm_isdst = -1;
time_dat = mktime (& org);

This gives the date: Fri Jul 10 09:46:10 2015

As a result, every call of the SysTick handler updates the variables. By applying these low level implementations, you can use the clock and time functions on your application.

Conclusion

Standard C library date and time operations implemented in time.h can be used in IAR Embedded Workbench. You can use these functions without writing a low-level implementation by using information provided by the debugger. If you want to use the library without using the debugger, you can implement low-level code as described in this article in order to use the date and time functions.


为了使 __time32()、__time64()和data函数工作,必须要实现 clock, __time32, __time64, and __getzone函数。
实现这些函数,并不需要重新rebuild库,我们可以在 clock.c, time.c, time64.c, and getzone.c in the arm\src\lib directory找到相关函数的模板。__getzone()默认的时区为0时区。

下面是在STM32下的测试
#define CLOCKS_PER_SEC (1000)

/*
可以在项目设置中设置时间使用的变量类型计数范围
_DLIB_TIME_USES_LONG
_DLIB_TIME_USES_64
*/
clock_t clk_count = 0;//系统上电后运行时间计数,如果是32位,1ms周期下最大计时49.7天
time_t time_dat;//设置localtime相对于公元1970年1月1日0时0分0秒算起至今的UTC时间所经过的秒数

/* Private functions ---------------------------------------------------------*/
clock_t clock (void) {
    return (clk_count);
}

#if _DLIB_TIME_USES_64
time_t __time64 (time_t *p) {
    return time_dat;
}
#else
time_t __time32 (time_t *p) {
    return time_dat;
}
#endif

const char * __getzone(void)
{
    return ": GMT+8:GMT+9:+0800";
}

int main(void)
{
  if (SysTick_Config(SystemCoreClock / 1000))
  {
    /* Capture error */ 
    while (1);
  }

  USART1_Config(115200);
  
  //设置时间,localtime
  {
      struct tm set_time;
      set_time.tm_sec = 10;
      set_time.tm_min = 0;
      set_time.tm_hour = 8;
      set_time.tm_mday = 13;
      set_time.tm_mon = 10-1;
      set_time.tm_year = 2017-1900;
      //set_time.tm_wday = 1;
      //set_time.tm_yday = 2;
      set_time.tm_isdst = -1;
      //C 库函数 time_t mktime(struct tm *timeptr) 把 timeptr 所指向的结构转换为一个依据本地时区的 time_t 值,根据当前时区设置。
      time_dat = mktime(&set_time);//mktime()用来将参数timeptr所指的tm结构数据转换成从公元1970年1月1日0时0分0 秒算起至今的UTC时间所经过的秒数。
  }
  
  //显示时间
  {
      time_t now;
      struct tm* ts;
      now = time(NULL);
      ts = localtime(&now);
      
      printf("localtime = %s\r\n", asctime(localtime(&now)));
      printf("gmtime    = %s\r\n", asctime(gmtime(&now)));
      
      printf("ts->tm_yesr   = %d\n", 1990 + ts->tm_year);
      printf("ts->tm_mon    = %d\n", 1 + ts->tm_mon);
      printf("ts->tm_mday   = %d\n", 0 + ts->tm_mday);
      printf("ts->tm_hour   = %d\n", 0 + ts->tm_hour);
      printf("ts->tm_min    = %d\n", 0 + ts->tm_min);
      printf("ts->tm_sec    = %d\n", 0 + ts->tm_sec);
      printf("ts->tm_wday   = %d\n", 0 + ts->tm_wday);
      printf("ts->tm_yday   = %d\n", 1 + ts->tm_yday);
      
      printf("ctime = %s\r\n", ctime(&now));
      
      char buf[80] = {0};
      strftime (buf, sizeof (buf), "%a %Y-%m-%d %H:%M:%S%Z", ts);
      printf ("%s \n", buf);
  }
  
  {
      clock_t clock_start, clock_end;
      printf("程序启动...\n");
      clock_start = clock();
      printf("休眠 5 秒...\n");
      sleep(5);
      clock_end = clock();
      double total_t = (double)(clock_end - clock_start) / CLOCKS_PER_SEC;
      printf("sleep(5) use times %f seconds\r\n", total_t);
  }
  
  {
      time_t time_start, time_end;
      printf("程序启动...\n");
      time(&time_start);
      printf("休眠 5 秒...\n");
      sleep(5);
      time(&time_end);
      double diff_t = difftime(time_end, time_start);
      printf("sleep(5) use times %f seconds\r\n", diff_t);
  }
  
  /* Display time in infinite loop */
  while (1)
  {
      time_t now;
      now = time(NULL);
      printf("localtime = %s\r\n", asctime(localtime(&now)));
      printf("gmtime    = %s\r\n", asctime(gmtime(&now)));
      sleep(5); 
  }
}

在系统中断中实现
void SysTick_Handler(void)
{
    extern clock_t clk_count;
    extern time_t time_dat;
    clk_count++;
    if ((clk_count % 1000) == 0) {
        time_dat++;
    }
}


============================================================================================================

clock.c
/* Copyright 1998-2010 IAR Systems AB. */


/*
 * This is the default implementation of the "clock" function of the
 * standard library.  It can be replaced with a system-specific
 * implementation.
 *
 * The "clock" function should return the processor time used by the
 * program from some implementation-defined start time.  The value
 * should be such that if divided by the macro CLOCKS_PER_SEC the
 * result should yield the time in seconds.
 *
 * The value "(clock_t)-1" means that the processor time is not
 * available.
 *
 */

#include <time.h>

_STD_BEGIN

#pragma module_name = "?clock"

clock_t (clock)(void)
{
  return ((clock_t) -1);
}

_STD_END


time.c
/*******************
 *
 * Copyright 1998-2010 IAR Systems AB. 
 *
 * This is the default implementation of the "time" function of the
 * standard library.  It can be replaced with a system-specific
 * implementation.
 *
 * The "time" function returns the current calendar time.  (time_t)-1
 * should be returned if the calendar time is not available.  The time
 * is measured in seconds since the first of January 1970.
 *
 ********************/

#include <time.h>

#pragma module_name = "?time"

__time32_t (__time32)(__time32_t *t)
{
  if (t)
  {
    *t = (__time32_t) -1;
  }
  return (__time32_t) -1;
}

time64.c
/*******************
 *
 * Copyright 1998-2010 IAR Systems AB. 
 *
 * This is the default implementation of the "time" function of the
 * standard library.  It can be replaced with a system-specific
 * implementation.
 *
 * The "time" function returns the current calendar time.  (time_t)-1
 * should be returned if the calendar time is not available.  The time
 * is measured in seconds since the first of January 1970.
 *
 ********************/

#include <time.h>

#pragma module_name = "?time"

#if _DLIB_TIME_ALLOW_64
__time64_t (__time64)(__time64_t *t)
{
  if (t)
  {
    *t = (__time64_t) -1;
  }
  return (__time64_t) -1;
}
#endif

getzone.c
/*******************
 *
 * Copyright 2003-2010 IAR Systems AB.  
 *
 * This is the default implementation of the __getzone. It returns
 * the current time-zone, i.e. UTC.
 *
 *
 *
 *
 * The return value should be a string on the following form:
 *
 * :[XXX[:YYY[:NNN[:DST[:DST ...]]]]]
 *
 * Where XXX is the standard time-zone name, YYY is the daylight
 * savings time-zone name, NNN is the time zone offset, and the DSTs
 * are the daylight savings time rules. Daylight savings time will add
 * one hour to the normal time. (The names are only used in the 'Z'
 * formatter in the strftime library function.)
 *
 * The time zone offset NNN is specified as a number relative to UTC,
 * possibly negative (east is positive), on the format HHMM, where HH
 * is hours and MM is minutes.
 *
 * The DSTs specifes a set of rules for how daylight savings time is
 * applied. The rules must be sorted in increasing date order starting
 * from the earliest date. The first rule for a specific year will
 * enable DST, the next will disable it, and so on. Each rule is on
 * the following form:
 *
 *   [(YYYY)]MMDD[HH][-W|+W]
 *
 *    (YYYY) is the first year the daylight savings rule was applied.
 *       It is optional. If not specified it will default to the same
 *       year as the previous rule or zero if no previous rule.
 *    MM is the month number (1-12).  
 *    DD is the day of the month (1-31).  
 *    HH is the hour number in a 24-hour day (optional, defaults to
 *       0).  
 *    +/-W specifies the day of the week the rule takes effect (where
 *       Sunday = 0, Monday = 1, etc). +W means that the rule applies
 *       to the first such day on or after the specified date and -W
 *       strictly before the date. If this is not specified, the rule
 *       will take effect on the exact date, regardless of the day of
 *       the week.
 *
 * On the northern hemisphere the DST rules normally comes in pairs, a
 * start, Aprilish, and an end, Octoberish. On the southern hemisphere
 * one normally has to use three rules: enabling DST from start of
 * year, disabling it in Aprilish, and then enabling it again in
 * Octoberish.
 *
 * Example:
 *
 *   :GMT:GMT+1:0060:(1990)040102-0:100102-0
 *
 *   Here, the time zone is GMT and under daylight savings time the
 *   time zone is named GMT+1. The time zone offset is 0060, i.e. 60
 *   minutes from UTC. As of the year 1990, daylight savings time
 *   started on the Sunday before (but not on) 1:st of April at 2am
 *   and ends on the first Sunday before (but not on) the first of
 *   October.
 *
 *   :GMT+10:GMT+11:0900:(1990)010100-0:040102-0:100102-0
 *
 *   Tasmania is on UTC+10 hours, with daylight savings time from
 *   first Sunday in October until first Sunday in April. Note, the
 *   first DST rule is for enabling from start of the year.
 *
 ********************/

#include <yfuns.h>

_STD_BEGIN

char const * __getzone()
{
  return ":";
}

_STD_END



【STM32】HAL库-RTC实数时钟-使用C库函数time.h-内部时钟LSI-待机模式 采用STM32F103C8T6单片机,KeilMDK5.32版本 使用LSI作为时钟源 采用time.h库函数,可通过串口助手上位机修改RTC当前计数值 串口与上位机进行通信,串口发送设置为DMA单次模式发送(仿printf) 串口接收设置为DMA循环串口空闲接收,接收到用户数据并修改RTC CNT寄存器后进入待机模式 通过PA0来唤醒单片机 PC13控制LED灯,LED亮灭指示程序正在运行 立即下载

相关推荐

C 标准库 – time.h

C 标准库 – 简介 time.h 头文件定义了四个变量类型、两个宏和各种操作日期和时间的函数。 库变量 下面是头文件 time.h 中定义的变量类型: 序号 变量 & 描述 1 size_t 是无符号整数类型,它是 sizeof 关键字的结果。 2 clock_t 这是一个适合存储处理器时间的类型。 3 time_t is 这是一个适合存储日历时间类型。 4 struct tm 这是一个用来保存时间和日期的结构。 tm 结构的定义如下: struct tm { int tm_sec; /* 秒,范围从 0 到 59        */

STM32启用 time.h 弥补RTC的不足

由于STM32F103系列 内部的RTC只是普通的定时器 无法作为断电保存使用,这里将演示一种低成本高兼容性的解决方案,重定向启用time.h头文件,将规范工程结构 节省大量时间

蒙蒙plus 2694

淘宝扫码登录避坑指南:如何避免异地登录风控并稳定获取Cookie(附Python代码)

本文深入解析了淘宝扫码登录的风控机制,提供了从环境仿真到代码实现的完整避坑指南。通过精细化伪装请求头、管理会话与IP策略,并附上Python示例代码,帮助开发者稳定获取Cookie,有效避免异地登录风控,实现自动化流程的可靠集成。

l6m7n8的博客 603

STM32中time.h文件详解

STM32的time.h文件有时间结构体的定义和时间转化的相关函数。 struct tm { int tm_sec; /* seconds after the minute, 0 to 60 (0 - 60 allows for the occasional leap second) */ int tm_min; /* min

夜风的博客 1万+

树莓派使用 OLED 屏显示图片及文字

树莓派默认是不带显示屏的,如果想要查看系统的一些信息,需要使用电脑登录到树莓派,或者通过 HDMI 连接外接显示器查看。这样做总是有点麻烦,我们可以通过外接一个 OLED 屏来显示一些关键参数或者图片。本文将详细介绍操作方法。 OLED 模组介绍 OLED 屏主要有两种:128×32 和 128×64 ,主要颜色是白、黄、蓝。OLED 屏的特点是功耗低,价格便宜,使用 I2C 接口与主机连接。本文所使用的是 128×64 尺寸的屏幕,外形如下: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直

码到成功 3750

Warning-[INFL_DELTA] Too many events zero delay loop

项目场景: 运用VCS工具执行仿真的时候,遇到如下错误提示,但仿真还在继续。 Warning-[INFL_DELTA] Too many events Possible zero delay loop. Too many events in the simulation at time 0 fs. 问题描述: 为什么会有这个问题; 什么导致了这个问题; 原因分析: 1、为什么会有这个问题 由于竞争条件或编码风格不明确,可能会产生零延时回路,导致仿真挂起或仿真时间无限。 2、什么导致了这个问题 举

hh199203的博客 1万+

STM32标准库的部署和FreeRTOS的移植(适用各类开发板)

从stm32的标准库下载开始到keil部署标准库,再到下载FreeRTOS源文件,源文件的移植,以及对工程文件的处理都有详细的过程

APP_xinyonghu_li的博客 8104

立创开源TinyAWG:基于ZYNQ7010的35MHz带宽200MSa/s任意波形发生器设计与实现

本文详细解析了立创开源TinyAWG的设计与实现,这是一款基于ZYNQ7010芯片的低成本高性能任意波形发生器。项目实现了35MHz带宽和200MSa/s采样率,核心采用ARM+FPGA协同架构,FPGA负责高速DDS信号生成,ARM运行Linux并搭载LVGL图形界面。文章涵盖了硬件选型、电路设计、软件逻辑及性能测试,为复刻和学习ZYNQ系统设计、高速DAC应用提供了完整参考。

weixin_42576467的博客 445

STM32基于标准库软件I2C方式操作AT24C32+DS1307时钟模块

STM32基于标准库软件I2C方式操作AT24C32+DS1307时钟模块

perseverance51博客 2979

实战教程:用YOLOv11+PyQt5打造工地安全帽检测系统(附完整数据集)

本文提供了一份完整的实战指南,详细介绍了如何利用YOLOv11目标检测模型与PyQt5界面库,从零开始构建一个智能工地安全帽检测桌面应用。内容涵盖高质量数据集的准备与标注、YOLOv11模型训练与调优,以及如何使用PyQt5开发流畅、专业的图形用户界面,最终实现一个可实际部署的AI安全监控系统。

plum99的博客 746

从零到一:揭秘BlueROV2机械爪背后的Pixhawk舵机控制艺术

本文详细解析了如何基于Pixhawk飞控系统为BlueROV2水下机器人构建可靠的舵机控制系统。从硬件选型、ArduSub固件配置到供电安全与故障排除,全面揭秘机械爪背后的控制艺术,为水下机器人爱好者提供实用指南。

ol78901234的博客 249

【STM32】STM32学习笔记-Unix时间戳(41)

当原子钟计时一天的时间与地球自转一周的时间相差超过0.9秒时,UTC会执行闰秒来保证其计时与地球自转的协调一致。•GMT(Greenwich Mean Time)格林尼治标准时间是一种以地球自转为基础的时间计量系统。•Unix 时间戳(Unix Timestamp)定义为从UTC/GMT的1970年1月1日0时0分0秒开始所经过的秒数,不考虑闰秒。C语言的time.h模块提供了时间获取和时间戳转换的相关函数,可以方便地进行秒计数器、日期时间和字符串之间的转换。C 标准库

Print World的专栏 5039

2026华为OD面试手撕代码真题目录

一般面试的时候每一轮技术面都会出一到两个手撕代码题,这些题的特点就是,非常短小,易于理解。不可能会再出阅读理解一样的机试题的。但是这些题目也非常注意基本功,很注意细节的处理,一般都是easy+medium题目。但是大家一定要注意,因为大部分面试官上面一开始就会让你做题,直接看你所有的做题过程(防止有人水平一般,机试就网上找的答案的蒙混过关),手撕代码题会给你后面的面试定一个基调。

MISAYAONE的博客 9万+

STM32标准库——(18)Unix时间戳、BKP备份寄存器、RTC实时时钟

32位有符号数所能表示的最大数字是2^32/2-1这个数是21亿多,这其实是有溢出风险的,因为目前到2023年时间戳已经计到16亿了,32位有符号数的时间戳会在2038年的1月19号溢出,64位的时间戳能存储的时间范围非常非常的大,看下手册STM32它核心的计时部分,是一个32位的可编程计数器,这说明我们这款stm32 ,它的时间戳是32位的数据类型,这表示我们这个stm32也会在2038年出现bug吗,实际上并不会啊,因为根据我的研究,这个时间戳在stm32程序中定义的其实是无符号。

2301_78772787的博客 2243

数据权限设计

随着IT新技术不断完善成熟,企业数字化建设得到全面的发展,数据将成为一个创造财富的重要来源,并且越来越多地被视为一项值得重视的企业资产。未来,很多企业之间的竞争,其实也是资源和数据竞争。那么针对数据资产,如何保障它的安全性呢?数据的权限管理无疑是必不可少的。数据权限从数据源来控制不同的用户能够查看、使用和授权不同的数据表数据(其实就是数据表行列的管控),就如同筑起了一道道护城墙,为数据安全提供了保障。

qq_40664711的博客 1万+

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

【STM32】RTC实时时钟

【STM32】RTC实时时钟

2502_90565057的博客 2290

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【STM32】HAL库-RTC实时时钟-使用C库函数time.h-外部时钟LSE-周期性唤醒

【STM32】HAL库-RTC实时时钟-使用C库函数time.h-外部时钟LSE-周期性唤醒 去发现同类优质开源项目:https://gitcode.com/ 简介 本项目是基于STM32F103C8T6单片机,使用Keil MDK 5.32版本的HAL库开发,实现了一个利用外部时钟LSE(Low Speed External)作为时钟源的RTC(Real-Time Clock,实时时钟)功能。项...

gitblog_06784的博客 967

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

stm32学习笔记-12 RTC实时时钟

介绍并应用STM32中的RTC实时时钟!

UmMaa的博客 1872

STM32的入门——CM3芯片STM32F103VET6的使用和相关外设

入门知识汇总,较全

星星与你在此刻对视 1万+

STM32——RTC实时时钟

BKP(Backup Registers)备份寄存器【需要VBAT引脚供电才能维持,掉电会清零,即使主电源掉电、系统复位也不会清零】【本质是RAM存储器,掉电丢失】BKP可用于存储用户应用程序数据。当VDD(2.0~3.6V)电源被切断,他们仍然由VBAT(1.8~3.6V)维持供电。当系统在待机模式下被唤醒,或系统复位或电源复位时,他们也不会被复位【VBAT和VDD共地即可】TAMPER引脚产生的侵入事件【电平检测】将所有备份寄存器BKP内容清除,会申请中断【VDD断电也会工作】RTC引脚。

NRWHF的博客 2723

别再手动算时间了!用C标准库time.h玩转STM32 RTC日期时间转换

本文介绍了如何利用C标准库time.h在STM32 RTC模块中优雅处理日期时间转换,替代传统手动计算方法。通过详细代码示例,展示了从32位秒计数器到人类可读格式的高效转换,包括硬件配置、时区处理和高级应用场景,显著提升开发效率和准确性。

weixin_26873711的博客 225

RTC/BKP_STM32

BKP(Backup Registers)备份寄存器,用于存储用户应用程序数据。特性:BKP本质上位RAM存储器,但当VDD(2.0-3.6V)电源被切断,他们仍然由备用电源VBAT(1.8-3.6V)维持供电。当系统在待机模式下被唤醒,或系统复位或电源复位时,他们也不会被复位。防拆功能:BKP的TAMPER引脚产生的侵入事件会将所有备份寄存器内容清除。时钟输出功能:BKP的RTC引脚可以输出RTC校准时钟、RTC闹钟脉冲或者秒脉冲。时钟误差校准功能:有RTC时钟校准寄存器。

Blank_3的博客 1199

嵌入式时间魔术师:STM32 RTC与C语言时间库的完美协奏

本文深入探讨了STM32 RTC硬件时钟模块与C语言time.h时间库的协同工作,为嵌入式系统提供精准可靠的时间管理方案。内容涵盖RTC时钟源选择、低功耗时间维护、时间戳存储恢复及网络时间同步,并结合实战案例展示其在多时区数据处理中的完美应用。

earth的博客 474

STM32标准库学习笔记

个人stm32标准库学习轨迹记录

C语言、数据结构、单片机、嵌入式实时操作系统、C++ 学习路径记录 1303

从Unix时间戳到现实时间:STM32 RTC与时间库的跨界对话

本文深入探讨了如何在STM32嵌入式系统中实现Unix时间戳与硬件RTC模块的高效集成,涵盖时区转换、网络时间同步(NTP)和低功耗时间管理等关键技术。通过详细的代码示例,展示了如何构建可靠的时间管理系统,解决物联网设备和工业应用中的时间同步难题。

ol789012345的博客 974

STM32 标准库函数讲解

STM32F103C8T6 的 EXTI(External Interrupt/Event Controller)共有。STM32F103C8T6 的每个 GPIO 引脚可通过软件配置为。(Preemption Priority)和。Cortex-M3 内核的中断优先级分为。

a2026_2_14的博客 915
上一篇: virtual method but non-virtual destructor
下一篇: linux下tar、zip、rar解压缩命令使用
makeWorks
博客等级 码龄10年 27粉丝 21原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址