简体   繁体   English

使用C代码在AVR微控制器中设置堆栈指针

[英]Setting the stack pointer in AVR microcontrollers with C code

It is known that in AVR microcontrollers the stack pointer decreases for each element added to the stack. 众所周知,在AVR微控制器中,堆栈指针对于添加到堆栈中的每个元素都会减少。 I want to reserve memory for a new task stack, and I use 我想为新任务堆栈保留内存,并且我使用

unsigned char *pS = (unsigned char*)malloc(64*sizeof(unsigned char));

This I think returns a pointer to the beginning of an area in SRAM followed by 64 bytes, therefore for setting the stack pointer at the new stack I use 我认为这会返回一个指向SRAM中某个区域的开头的指针,后跟64个字节,因此在我使用的新堆栈中设置堆栈指针

SP = (unsigned int)pS + 64

Is this correct? 这个对吗?

No it is not correct. 不,这是不正确的。

  • Using malloc on an AVR for any purpose is definitely incorrect, because it doesn't make any sense. 出于任何目的在AVR上使用malloc绝对是错误的,因为这没有任何意义。 See this . 看到这个 In addition, how does it even make sense to have the stack residing on the heap? 另外,将堆栈驻留在堆上甚至有什么意义呢?

  • If you need RTOS-like behavior, it means you already picked the wrong MCU for the task. 如果您需要类似RTOS的行为,则意味着您已经为该任务选择了错误的MCU。 8-bitters are just far too limited. 8位用户太受限制了。 At a minimum, use a Cortex-M0 for such programs. 至少要对此类程序使用Cortex-M0。

That being said, if you want to make your own simple task-switching OS just for the sake of learning, then you would reserve stack space at compile/link-time. 话虽如此,如果您只是为了学习而制作自己的简单任务切换OS,则可以在编译/链接时保留堆栈空间。 This is done through the linker files of your cross-compiler environment. 这是通过交叉编译器环境的链接器文件完成的。 Check how and where the ordinary stack was allocated and then create a custom memory segment of similar size. 检查普通堆栈的分配方式和位置,然后创建一个类似大小的自定义内存段。 You'll note that there is not a whole lot of RAM to play with at all. 您会注意到,根本没有太多的RAM可玩。

It is correct that your stack pointer would be at an offset of the stack size. 您的堆栈指针在堆栈大小的偏移量是正确的。 But if you are truly writing an OS, then you wouldn't be allocating the SP as some sort of C pointer, but rather you would let the CPU use the actual SP register. 但是,如果您确实是在编写OS,那么您就不会将SP分配为某种C指针,而是让CPU使用实际的SP寄存器。

Also note that setting the stack pointer is one of those things that simply can't be done in C. You must do so through assembler. 还要注意,设置堆栈指针是C中根本无法完成的事情之一。您必须通过汇编器来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM