嗨,我正在研究一个使用Arduino点亮房屋灯的项目。
我让它以基本形式工作,现在我想存储灯开关的先前状态。我使用的数组存储了交换机的当前状态,因此可以在下一个循环中进行比较。我有7个开关,我已经创建了它,因此如果需要,一个开关可以打开许多灯。
我需要存储以前的状态,因为下一部分是介绍Web控件的测试项目已经写好了
奇怪的是 区域7/8完美无缺 。其他区域打开,但不要关闭。当我打开另一个开关时,如果它的开关处于关闭位置,灯可能会熄灭。
如果删除前一状态的条件,请检查所有开关是否正常。
const int zone2[] = {8,13,0};
const int zone3[] = {11,0};
const int zone4[] = {7,0};
const int zone5[] = {9,0};
const int zone6[] = {12,0};
const int zone7[] = {6,0};
const int zone8[] = {14,0};
const int * zones[]={zone2,zone3,zone4,zone5,zone6,zone7,zone8};
int buttonState[] = {0,0}; // variable for reading the pushbutton status
int previousState[]={0,0,0,0,0,0,0,0}; // array for holding the previous state of the input button
void setup()
{
//initialize the output pins that will control lights
pinMode(6,OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9,OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13,OUTPUT);
pinMode(14,OUTPUT);
// initialize the pushbutton pin as an input:
//set all light switches to the same block ie pins 30 - 35
byte i;
//this loop sets all the 30-35pins as inputs
for (i=30;i< 37;i++) {
pinMode(i, INPUT);
digitalWrite(i,HIGH); // this makes it connect to the internal resistor
}
}
void loop()
{
int arrayPosition;
for (int z = 0; z < 7; ++z)//zero based array needs to be as many as there are zones!!!
{
buttonState[z] = digitalRead(z+30);
for (arrayPosition = 0;zones[z][arrayPosition] ; arrayPosition++)
{
if ((buttonState[z] == HIGH) ) && (previousState[z] == LOW )) {
// turn LED on:
digitalWrite(zones[z][arrayPosition],HIGH);
}
else if ((buttonState[z] == LOW) && (previousState[z] == HIGH )) {
// turn LED off;
digitalWrite(zones[z][arrayPosition],LOW);
}
}
//each light assigned to the zone has been turned on or off, now set previousstate
//the statement is here the inner loop has finsihed turning lights on or off that belong to that zone
previousState[z] = buttonState[z];
}
}
答案 0 :(得分:0)
您为数组buttonState
分配了两个元素,但是您正在访问七个元素:
[…]
int buttonState[] = {0,0};
[…]
for (int z = 0; z < 7; ++z)
{
buttonState[z] = digitalRead(z+30);
[…]
您应该将buttonState
数组中的元素数量增加到实际需要的数量。
最好在一个地方定义数组的大小:
#define NUM_ZONES (7)
[…]
const int * zones[NUM_ZONES]={zone2,zone3,zone4,zone5,zone6,zone7,zone8};
int buttonState[NUM_ZONES] = {0,0,0,0,0,0,0};
int previousState[NUM_ZONES]={0,0,0,0,0,0,0};
[…]
for (int z = 0; z < NUM_ZONES; ++z)
[…]
这也会显示您的previousState
数组大于所需数组(编译器会抱怨您为该数组提供了太多初始化程序)。然后重要的是在任何地方重复使用该常量,而不是编写幻数 7
。