gpt4 book ai didi

c - 请向我描述以下代码如何读取传感器的输出

转载 作者:行者123 更新时间:2023-11-30 19:08:39 26 4
gpt4 key购买 nike

以下代码从传感器读取 5、8 位数据。我想我理解了其中的大部分内容,除了“将每个位插入存储字节”的部分是 <<= 和 |= 实现了这一点,如果是这样怎么办?

#include <wiringPi.h> 
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAXTIMINGS 85
#define DHTPIN 7
int dht11_dat[5] = { 0, 0, 0, 0, 0 };

void read_dht11_dat()
{
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
float f; /* fahrenheit */

dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;

/* pull pin down for 18 milliseconds */
pinMode( DHTPIN, OUTPUT );
digitalWrite( DHTPIN, LOW );
delay( 18 );
/* then pull it up for 40 microseconds */
digitalWrite( DHTPIN, HIGH );
delayMicroseconds( 40 );
/* prepare to read the pin */
pinMode( DHTPIN, INPUT );

/* detect change and read data */
for ( i = 0; i < MAXTIMINGS; i++ )
{
counter = 0;
while ( digitalRead( DHTPIN ) == laststate )
{
counter++;
delayMicroseconds( 1 );
if ( counter == 255 )
{
break;
}
}
laststate = digitalRead( DHTPIN );

if ( counter == 255 )
break;

/* ignore first 3 transitions */
if ( (i >= 4) && (i % 2 == 0) )
{
/* shove each bit into the storage bytes */
dht11_dat[j / 8] <<= 1;
if ( counter > 16 )
dht11_dat[j / 8] |= 1;
j++;
}
}

/*
* check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
* print it out if data is good
*/
if ( (j >= 40) &&
(dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) )
{
f = dht11_dat[2] * 9. / 5. + 32;
printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
}else {
printf( "Data not good, skip\n" );
}
}

int main( void )
{
printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" );

if ( wiringPiSetup() == -1 )
exit( 1 );

while ( 1 )
{
read_dht11_dat();
delay( 1000 ); /* wait 1sec to refresh */
}

return(0);
}

最佳答案

理解这一点的另一个关键在于变量 j .

dht11_dat[j / 8] <<= 1;

相当于

dht11_dat[0] <<= 1;

这相当于

dht11_dat[0] = dht11_dat[0] << 1;

对于 j 的值由于整数除法,从 0 到 7(含)。后来,当j增加到 8 或更大,则变为

dht11_dat[1] <<= 1;

等等。然而,if状况&& (i % 2 == 0)意味着这个 if block 只会在 i 时执行是一个数>= 4,我不清楚其原因。这可以解释吗?

返回<< 1机制:

例如说 dht11_dat[0]具有位模式 00000001其中,<< 1将位模式左移为 00000010 。这样,<< 1的后续申请通过将位向左推向最高有效位,并在最右边的位中保留零,具有将当前值加倍的效果(1 变为 2、2 变为 4 等)。

然后填写最右边的位, |=1运算的效果是在最低有效位加一。因此,如果位模式为 00000010左移后,下一个读取 DHTPIN为高电平,则操作|= 1给出

00000010 value = 2
00000001 1
=========== OR
00000011 now it is 3

然后每隔一段时间重复该过程 i时间,从右侧插入位(当 DHTPIN 为低时为 0,当为高时为 1),直到完成。这更有意义吗?

关于c - 请向我描述以下代码如何读取传感器的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44751655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com