Sunday, June 17, 2018

implement system call in stm8 via trap instruction.

There is 'trap' instruction in stm8 mcu.
This instruction has (maybe) same purpose with svc instruction in ARM.

The purpose is perform some function without awareness of the function pointer.
(Anyway, in the APU level, the svc instruction has more mission (ie. protect the process memory space), this article is only for low level mcu)


Below is the code.
======================
#include ...
#include ...

#define BIT(x)  (1<<(x))
#define ON      (0x11)
#define OFF     (0x22)

//INTERRUPT_HANDLER_TRAP(TRAP_IRQHandler)
#pragma vector = 1
 __interrupt void (trap_handler) (void)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
  char param = 0x11;

  asm("ld a, xl");
  
  switch(param)
  {
  case ON:
    PB_ODR |= BIT(5);
    break;
  case OFF:
    PB_ODR &= ~BIT(5);
    break;
  default:
    break;
  }
}

void delay(unsigned int n)
{
    while (n-- > 0);
}

void sys_call(char id)
{
  asm("ld xl, a");
  __trap();
}

//main entry point
int main( void )
{
  PB_ODR = 0; //Turn off all pins
  PB_DDR = BIT(5);
  PB_CR1 = BIT(5);

//  __enable_interrupt();
  while (1)
  {
    delay(30000);
    sys_call(ON);
    delay(30000);
    sys_call(OFF);
  }
}
 ===========================

the code enters system call via trap instruction.
and to pass the operation code, it uses XL register.

This code is checked in IAR, but has some special configurations.
the configuration is 'optimize off(none)'.

Because if optimizing is on, the compiler remove some code include that needed system call.

Finally,
To perfect implementation, we need to known 'C & assembly mixing'
And next time, I will introduce it if possible.

No comments: