Kit STM32F4 Discovery – Bài 3: Timer hệ thống System Timer

85
1946

Giới thiệu

Trên tất cả các vi điều khiển ARM Cortex-M, bao gồm STM32F4, có tích hợp một timer nhỏ, gọi là timer hệ thống (System Timer), gọi tắt là SysTick. Timer này được tích hợp như một phần của bộ xử lý ngắt lồng nhau NVIC và có thể khởi tạo SysTick Exception (exception type #15). Bản chất của Systick là một timer  24-bit, thực hiện việc đếm xuống, nghĩa là nó thực hiện việc đếm từ một giá trị reload nào đó xuống đến 0 sau đó nạp lại giá trị reload trước khi lặp lại việc đếm xuống. Giá trị reload luôn nhỏ hơn 224. Nguồn tạo xung nhịp cho SysTick có thể là tần số xung nhịp hệ thống SYSCLC hoặc tần số xung nhịp hệ thống chia cho 8 (SYSCLK/8).

Trong các hệ điều hành hiện đại cần có một ngắt có tính chu kỳ để nhân hệ điều hành có thể gọi đến thường xuyên, chẳng hạn để phục vụ cho việc quản lý tác vụ hoặc chuyển ngữ cảnh. SysTick chính là công cụ được dùng để cung cấp xung nhịp cho hệ điều hành hoặc để tạo ra ngắt có tính chu kỳ phục vụ cho các tác vụ được lập lịch cũng như cho bất cứ công việc nào khác cần đến ngắt chu kỳ.

Sở dĩ SysTick được thiết kế ngay bên trong CPU của Cortex-M là để tạo ra tính khả chuyển cho phần mềm. Chính nhờ việc tất cả các vi xử lý Cortex-M có chung SysTick timer mà hệ điều hành được viết cho vi điều khiển Cortex-M này có thể chạy trên vi điều khiển Cortex-M khác. Khi không cần đến hệ điều hành nhúng cho ứng dụng, SysTick vẫn có thể được dùng như một thiết bị ngoại vi định thời đơn giản để khởi tạo ngắt chu kỳ, khởi tạo hàm delay hoặc dùng đo đếm thời gian. Để lập trình với SysTick chúng ta cần tác động lên các thanh ghi của timer này. Đối với ARM Cortex-M4, có 4 thanh ghi cho SysTick như sau:

Địa chỉKý hiệu trong CMSIS-CoreThanh ghi
0xE000E010SysTick->CTRLSysTick Control and Status Register
0xE000E014SysTick->LOADSysTick Reload Value Register
0xE000E018SysTick->VALSysTick Current Value Register
0xE000E01CSysTick->CALIBSysTick Calibration Register

Để khởi tạo ngắt SysTick có tính chu kỳ, cách đơn giản nhất là dùng hàm CMSIS-Core có tên là “SysTick_Config”:

uint32_t SysTick_Config(uint32_t ticks);

Hàm này được khai báo trong file core_cm4.h như sau:

__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{

/* Reload value impossible */
if (ticks > SysTick_LOAD_RELOAD_Msk)  return (1);     
       
/* set reload register */
SysTick->LOAD  = (ticks & SysTick_LOAD_RELOAD_Msk) - 1;      

/* set Priority for Systick Interrupt */
NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);  

/* Load the SysTick Counter Value */
SysTick->VAL   = 0;                                          

/* Enable SysTick IRQ and SysTick Timer */
SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
                   SysTick_CTRL_TICKINT_Msk   |
                   SysTick_CTRL_ENABLE_Msk;                    

/* Function successful */
return (0);		
}

Hàm SysTick_Config() cho phép thiết lập khoảng ngắt cho SysTick là “ticks” lần đếm, cho phép bộ đếm sử dụng bộ tạo xung của CPU và cho phép xảy ra ngắt SysTick với độ ưu tiên thấp nhất.
Ví dụ, tần số làm việc của bộ tạo xung nhịp hệ thống là 168MHz, chúng ta muốn tần suất xảy ra ngắt SysTick là 1 KHz (1000 lần / 1s) hay mỗi ms xảy ra ngắt 1 lần, chúng ta gọi hàm như sau:

SysTick_Config(SystemCoreClock / 1000);

Biến “SystemCoreClock” cần được thiết lập giá trị đúng là 168×106.
Nói cách khác, chúng ta có thể gọi trực tiếp như sau:

SysTick_Config(168000); // 1680MHz / 1000 = 168000

Hàm “SysTick_Handler(void)” khi đó sẽ tự động được gọi mỗi ms một lần.
Nếu giá trị tham số truyền vào cho hàm SysTick_Config không vừa với thanh ghi 24-bit reload value (lớn hơn 0xFFFFFF), hàm SysTick_Config trả về giá trị 1, ngược lại trả về giá trị 0.
Dưới đây là ví dụ ứng dụng SysTick để khởi tạo hàm delay:

Ví dụ

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"

/* Private typedef -----------------------------------------------------------*/
GPIO_InitTypeDef  GPIO_InitStructure;

/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static __IO uint32_t TimingDelay;
/* Private function prototypes -----------------------------------------------*/
void Delay(__IO uint32_t nTime);
/* Private functions ---------------------------------------------------------*/

/**
  * @brief  GPIO pin toggle program
  * @param  None
  * @retval None
  */
int main(void)
{

  SystemInit();

  /* GPIOD Periph clock enable */
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

  /* Configure PD12, PD13, PD14 and PD15 in output pushpull mode */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13| GPIO_Pin_14| GPIO_Pin_15;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIOD, &GPIO_InitStructure);

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

  while (1)	
  {
    /* PD12 to be toggled */
    GPIO_SetBits(GPIOD, GPIO_Pin_12);

    /* Insert delay */
    Delay(500);

    /* PD13 to be toggled */
    GPIO_SetBits(GPIOD, GPIO_Pin_13);

    /* Insert delay */
    Delay(500);

    /* PD14 to be toggled */
    GPIO_SetBits(GPIOD, GPIO_Pin_14);

    /* Insert delay */
    Delay(500);

    /* PD15 to be toggled */
    GPIO_SetBits(GPIOD, GPIO_Pin_15);

    /* Insert delay */
    Delay(500);

    GPIO_ResetBits(GPIOD, GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15);

    /* Insert delay */
    Delay(1000);
  }
}

/**
  * @brief  Inserts a delay time.
  * @param  nTime: specifies the delay time length, in milliseconds.
  * @retval None
  */
void Delay(__IO uint32_t nTime)
{
  TimingDelay = nTime;

  while(TimingDelay != 0);
}

/**
  * @brief  Decrements the TimingDelay variable.
  * @param  None
  * @retval None
  */
void SysTick_Handler(void)
{
  if (TimingDelay != 0x00)
  {
    TimingDelay--;
  }
}

Hàm SysTick_Handler(void) là hàm phục vụ ngắt SysTick. Theo cài đặt trên thì cứ 1ms ngắt sẽ xảy ra 1 lần, mỗi lần ngắt xảy ra hàm phục vụ ngắt sẽ được gọi tự động. Với nội dung hàm Delay() và SysTick_Handler() như trên, ban đầu TimingDelay sẽ nhận giá trị tương ứng với số ms cần delay, mỗi 1ms sẽ xảy ra ngắt 1 lần và khi ngắt xảy ra nó sẽ giảm biến TimingDelay 1 đơn vị. Như vậy lời gọi hàm Delay(n) sẽ tương ứng với thực hiện giữ chậm n (ms).

85 COMMENTS

  1. Hi there! I know this is somewhat off-topic however I had to
    ask. Does managing a well-established website such as yours require a large
    amount of work? I’m completely new to running a blog however I do write in my diary
    everyday. I’d like to start a blog so I can easily
    share my experience and thoughts online. Please let me know if you have any kind of ideas or tips for new aspiring blog owners.
    Appreciate it!

  2. Defіnitely beliedѵe thᥙat which yoou said. Your favorite reason appeared to be on tһe net tһe simplest thing to be aware of.
    I say to you, I definitely geet annoyed while
    peoplе think aЬout worries that thеy plwinly do not know about.
    You managed to hit the nail upon the top as well as defined out the whole thing wijthout having
    sidee effect , peoрle can takе a signal. Will likely Ьe back
    to get more. Thanks

    Check out my Ьlog post; FUNERAL

  3. Great blog here! Additionally your web site lots up fast!

    What web host are you the use of? Can I am getting your associate
    link on your host? I wish my website loaded up as quickly as yours lol

  4. I really like your blog.. very nice colors & theme. Did you design this website yourself
    or did you hire someone to do it for you? Plz respond as I’m
    looking to create my own blog and would like to know where u got this
    from. thanks a lot

  5. An intriguing discussion is definitely worth comment. I do think that
    you need to write more about this subject matter, it may
    not be a taboo subject but generally people don’t speak about such
    topics. To the next! Best wishes!!

  6. You are so awesome! I do not think I have read something like this before.
    So wonderful to find someone with original thoughts on this subject.
    Seriously.. thank you for starting this up. This web site is something that’s needed on the internet, someone
    with some originality!

    my web page: Karolyn

  7. I know this if off topic but I’m looking into starting my own weblog and was curious what
    all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny?

    I’m not very web smart so I’m not 100% sure. Any recommendations
    or advice would be greatly appreciated. Cheers

  8. Great goods from you, man. I’ve understand your stuff previous to and you’re
    just too magnificent. I actually like what you’ve
    acquired here, certainly like what you’re saying and the way in which you say
    it. You make it enjoyable and you still take care
    of to keep it sensible. I can not wait to read much more from you.
    This is really a wonderful website.

  9. Hey there! Ꮪomeone in my Facebook group shared
    this website with us so I came to give it a look. I’m definitely loⲟѵing the information. I’m booқ-mаrking and
    will be tweeting this to my followers! Excellent blog and outstanding desiɡn and style.

    Here iss my homepage missing person

  10. Definitely imagine that that you stated. Your favorite
    justification appeared to be on the internet the simplest factor to be
    aware of. I say to you, I definitely get annoyed even as other
    folks consider worries that they plainly don’t realize about.

    You controlled to hit the nail upon the top as neatly as outlined out
    the whole thing without having side effect , folks could take a signal.
    Will probably be back to get more. Thank you

    Visit my webpage https://mlmfamily.com/user/profile/962187

  11. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my
    blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like
    this. Please let me know if you run into anything.

    I truly enjoy reading your blog and I look forward to your new updates.

    Here is my web blog :: totalnabiologia.org

  12. Hey would you mind sharing which blog platform you’re working
    with? I’m looking to start my own blog soon but I’m having a difficult
    time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different
    then most blogs and I’m looking for something completely unique.
    P.S My apologies for being off-topic but I had to ask!

    Feel free to visit my site – http://gallerychoi.com/

  13. Excellent goods from you, man. I’ve understand your stuff previous to and you’re just too great.

    I actually like what you’ve acquired here, certainly like what you’re
    stating and the way in which you say it. You make it entertaining and you still care for to keep it sensible.
    I can not wait to read much more from you. This is really a wonderful web site.

    My web blog: poker pulsa

  14. It is the best time to make some plans for the future and it is time to be happy.
    I have read this post and if I could I wish to suggest you some interesting things or suggestions.
    Perhaps you could write next articles referring to this article.
    I desire to read more things about it!

    My web-site: sharontalon.com

  15. hello there and thank you for your info – I’ve certainly picked
    up anything new from right here. I did however expertise some technical issues using this website,
    as I experienced to reload the website lots of times previous to I could get
    it to load correctly. I had been wondering if your
    web host is OK? Not that I’m complaining, but slow loading instances
    times will very frequently affect your placement in google and could damage your high quality
    score if ads and marketing with Adwords. Anyway I’m adding this RSS to my email and could look out for much more of your respective
    exciting content. Ensure that you update this again very soon.

  16. Hello! This post could not be written any better!
    Reading through this post reminds me of my old room
    mate! He always kept chatting about this. I will forward this write-up to him.
    Fairly certain he will have a good read. Many thanks
    for sharing!

  17. Great blog right here! Additionally your web site
    quite a bit up fast! What host are you the usage of?
    Can I get your associate hyperlink to your host?
    I want my website loaded up as quickly as yours lol

  18. It’s perfect time to make some plans for the future and it is time to be happy.
    I’ve read this post and if I could I wish to suggest you few interesting things or tips.
    Maybe you can write next articles referring to this article.
    I wish to read even more things about it!

    Here is my page – deposit pulsa

  19. Definitely believe that which you stated. Your
    favorite justification appeared to be on the net the easiest thing to be aware of.
    I say to you, I certainly get irked while people think about worries that they just don’t know about.
    You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects ,
    people can take a signal. Will probably
    be back to get more. Thanks

    Here is my blog – https://pathta.jp/user/profile/8302675

  20. Having read this I believed it was really enlightening.
    I appreciate you taking the time and energy to put this short article together.
    I once again find myself personally spending way too much time both reading and commenting.
    But so what, it was still worthwhile!

  21. I do believe all the ideas you have offered for your post.
    They’re really convincing and can certainly work. Nonetheless, the posts are too brief for newbies.
    Could you please extend them a little from subsequent time?
    Thank you for the post.

  22. You’ve made some decent points there. I looked on the web for additional information about the issue and found most individuals will go along with
    your views on this web site.

  23. I’ve been surfing online more than 3 hours today,
    yet I by no means discovered any attention-grabbing article like yours.
    It’s beautiful value sufficient for me. Personally, if all webmasters and
    bloggers made excellent content material as you probably did, the internet will likely
    be a lot more helpful than ever before.

    my web page – ayam-sabung.com

  24. I loved as much as you’ll receive carried out right here.
    The sketch is tasteful, your authored material
    stylish. nonetheless, you command get got an nervousness over that you wish
    be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.

  25. It’s a pity you don’t have a donate button! I’d most
    certainly donate to this outstanding blog! I suppose for now i’ll settle for book-marking and adding your RSS
    feed to my Google account. I look forward to new updates and
    will share this website with my Facebook group.
    Talk soon!

    Also visit my webpage; game mega88

  26. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the
    same comment. Is there any way you can remove people from that service?
    Thanks a lot!

  27. Hi, Neat post. There is a problem along with your web site in web explorer,
    could check this? IE still is the market chief and a huge component of other folks will
    omit your magnificent writing due to this problem.

  28. Attractive component to content. I just stumbled upon your site and in accession capital
    to assert that I get actually loved account your weblog posts.

    Anyway I will be subscribing in your augment or even I achievement you get
    right of entry to consistently quickly.

    my blog – kabarutama.net

  29. Great post. I was checking continuously this weblog and I’m
    impressed! Very helpful info particularly the closing section 🙂 I care
    for such information much. I used to be looking for this certain info for a long time.

    Thanks and best of luck.

    Here is my web blog kode trik xe88

LEAVE A REPLY

Please enter your comment!
Please enter your name here