The Tricky Microcontroller Pointer Nuance

December 4, 2015


I have recently been playing around with my MSP430 dev kit and the DHT11 Temperature sensor. I did not want to use Energia because C is a better challenge and more useful to me. Having coded up my function to read from the dht11 I kept getting data timeouts for reasons unbeknownst to me. I debugged every part of what I wrote and even compared it to working code. However, after a few days of casual debugging I finally was able to find the problem. While storing the data bits in a C array, I was using indexing to access the value like so:

unsigned char raw[6];
unsigned char raw_index = 0;
...
...
raw[raw_index] |= 1;
...
++raw_index;
However, I found this tidbit on StackOverflow which led me to change the code to use a pointer to directly save the bits to specific elements instead:
unsigned char raw[6];
unsigned char raw_ptr = &raw[0];
const unsigned char raw_end = raw_ptr + 6;
...
...
raw_ptr |= 1;
...
++raw_ptr

Now it runs smoothly. So while this probably wouldn't matter in non-time intensive processes, in real time systems this is a big enough difference to crash the program.

You can see the full code here. Hope this helps someone!



comments powered by Disqus
  • Copyright 2013, Matthew Iannucci
  • Site created with web.py, version 0.3
  • Updated January 2015