March 30, 2006

Unit Testing Embedded System Registers

How do you unit test embedded software that accesses hardware registers? For example, here is the code that runs on 68HC12 microprocessor:
unsigned char read_sensor(void)
{
    unsigned char sensor_value;
    
    SPI0CR1 = 0x50; // Enable SPI, master mode, CPOL = 0, CPHA = 0
    SPI0BR = 0x22;  // 1.024 MHz baud rate
    SPI0DR = 0; // write the "get flow" command to shift the data out of the DSP
    
    while( (SPI0SR & 0x80) == 0 ) {};
    sensor_value = SPI0DR; 
    
    return sensor_value;
}
The obvious problem is that the register SPI0DR is set to zero before being read, so we can NOT unit test it by running:
    unsigned char SPI0DR; // Simulate the register by a global variable
    ....
    SPI0DR=77;
    assert_equal(77, read_sensor(), "reading sensor");
For testing purposes, we need to set the register before reading, and read the register after writing. In order to splits reads and writes into separate variable, we use this definition:
extern unsigned char REG_read;
extern unsigned char REG_write;
 
#define REG          REG_read ; REG_write
 
//
//      REG = 7;      // resolves to:
//                    // REG_read ; REG_write = 7; 
//                    // ------- the first half is ignored
//
//      blood_flow = REG; // resolves to:
//                    // sensor_value = REG_read ; REG_write;
//                    // the 2nd half is ignored   ---------
//
Now we can test that correct register is read:
    SPI0DR_read=77;
    assert_equal(77, read_sensor(), "reading sensor");
Posted by laza at March 30, 2006 12:21 PM | TrackBack
Comments
Post a comment









Remember personal info?