chipKIT® Development Platform

Inspired by Arduino™

Coding Guidelines

Created Sun, 31 Jul 2011 15:22:29 +0000 by avenue33


avenue33

Sun, 31 Jul 2011 15:22:29 +0000

Hi!

Switching from Arduino to chipKIT raises questions about variables, for many reasons:

  • Arduino is 8-bits while chipKIT is 32-bits
  • different type names sets exist, some of them not fully standard

I spent a couple of hours figuring out why a calculation based on int behaves differently on Arduino and chipKIT.

int i // => error ; int16_t => fine
  i= 32000;
  Serial.println(i, DEC);
  
  i += 2000;
  Serial.println(i, DEC);

  // Arduino = 32000 ; -31536
  // chipKIT = 32000 ; 34000

Recommendation is to use [u]int[8|16|32]_t types from stdint.h

  • int8_t instead of byte
  • int16_t instead of (signed) int
  • uint16_t instead of word or unsigned int
  • int32_t instead of long
  • uint32_t instead of unsigned long

For constant like 0x5A,

  • add suffix u to obtain 0x5Au

or

  • prefix uint8_t to obtain (uint8_t)0x5A.

ricklon

Sun, 31 Jul 2011 18:32:53 +0000

This is a really good thoughtful post. I've run into these kinds of issues converting existing Arduino code over. With some discussion this would become a good wiki entry.


avenue33

Sun, 31 Jul 2011 18:38:06 +0000

You're welcome :)

I hope pouring more contributions from chipKIT users will help everyone :!:


ron.dunn

Sun, 31 Jul 2011 23:34:20 +0000

Do you think this is good coding practice?

I wonder if it would be better NOT to depend on this style of code, and to use the appropriate limits.h definitions to govern the logic.

Ron.


ron.dunn

Mon, 01 Aug 2011 03:15:43 +0000

Disregard my last post.

A few hours' thought on the subject, and a quick look at the relevant standard, and I think Avenue33's recommendation is best.

Ron.


avenue33

Mon, 01 Aug 2011 04:07:08 +0000

I still have an issue with values like 0x5A.

They are considered as int and not as uint8_t :(

Any idea :?:

Thanks.


WestfW

Mon, 01 Aug 2011 04:11:31 +0000

I still have an issue with values like 0x5A. They are considered as int and not as uint8_t :(

This is part of the C standard. All constants that aren't otherwise specified are "int", and all intermediate results/calculations happen with ints.


jumpin_jack

Mon, 01 Aug 2011 19:38:10 +0000

I still have an issue with values like 0x5A.

If you need an unsigned constant, you can use the 'u' suffix. (e.g. 0x5Au)


avenue33

Mon, 01 Aug 2011 20:07:09 +0000

Thanks :)

I update my first post.

Another possibility to explore is turning default int type into another type from stdint.h to avoid confusion. But that's beyond my reach.