Go Down

Topic: DHT11/Aosong AM2302 humidity + temperature sensor (Read 7743 times) previous topic - next topic


Jan 02, 2011, 09:13 pm Last Edit: Jan 02, 2011, 10:14 pm by 1Pats Reason: 1
Had found this great code:

It is much readable than original sample, works much stable etc.
However pls note - it contains an error

Array to hold the bytes sent from sensor is declared as 4 bytes long,
but code fills five:
//now ready for data reception... pick up the 5 bytes coming from
//   the sensor
for (i=0; i<5; i++)
  dht_dat = read_dht_dat();

In short
byte dht_dat[4];//Array to hold the bytes sent from sensor.
should be corrected to
byte dht_dat[5];


Jan 06, 2011, 08:19 pm Last Edit: Jan 06, 2011, 08:28 pm by 1Pats Reason: 1
looks like problem is deeper
Code: [Select]

byte dht_dat[4];
long lLong = 0L;
void setup(){
 int i;
 for (i=0; i<5; i++) dht_dat[i] = i;
 for (i=0; i<5; i++) Serial.print(char(65+i));
 Serial.print(lLong, DEC);
void loop (){}


lLong should be 0, is 4! Why?
adding extra byte after array declaration does not help;
Windows XP/32 AMD prcessor, I guess
nuelectronivs freduino Atmega 328


Jan 06, 2011, 09:04 pm Last Edit: Jan 06, 2011, 09:59 pm by 1Pats Reason: 1
one more test
Code: [Select]

byte bByte[4];
byte bTest = 'X';
long lLong = 0L;
void setup(){
   for(int i = 0; i < 5; bByte[i]= char(i+65),i++);  // change to i< 4 to see difference
   Serial.print(lLong, DEC);
void loop (){}

correct usage of array size gives correct result: i< 4 gives X0
code in a way how it is presented:  i < 5  gives X69

But looking on code here is one extra byte bTest which contains X, which formally should changed to  5th value- e.g.  65+4 from the loop.

it means that memory alignment is different, not just byte after byte, byte order for types more than 2 bytes are stored differently.
Lost track here.... Smbdy knows answer?


byte order for types more than 2 bytes are stored differently.

Also note that some (most?) compilers store multi-byte variables in even byte positions, so ints and floats always start at even addresses, even when that means skipping a byte in memory.

More complex objects like structures and classes will have internal padding, to, to keep multi-byte variables in even numbered address positions.
The art of getting good answers lies in asking good questions.


this is what i am mean, but alignment usually applies to types longer than one byte. Usually c compiler for byte-based-types (byte, char, "strings" ) put variable starting from next free memory address without any alignment.. This means that bTest, declared just after array of 4 bytes in my previous my example should be damaged by 5th loop. It is not!
For me it is also not clear what is byteorder on atmega chip, left aligned or right aligned (like sun or like intel?)

Go Up