Arduino系统给一个箱子浇水。使用:
电磁阀湿度传感器
它编译了,所以我假设它能工作(但我目前还没有arduino的权限)
我的问题是..。如果我试图将其缩放到4个框,这是否是一个简单的复制/粘贴,是否应该改变设置的基本原理?有什么地方我应该调查。
// Box 1 sensor binding.
int MoistSensorBox1 = A0; // Binding a fugtighedssensor x.
int MoistValueBox1; // Fugtighedsvaerdi.
unsigned long Box1WaterCooldownTime = 0; // Cooldown til at vande.
const int SolenoidWaterBox1 = 5; // Solenoid til at vande.
// general time var.
unsigned long time;
void setup()
{
Serial.begin(300);
pinMode(SolenoidWaterBox1, OUTPUT); // set the SolenoidWaterBox1 pin as output
}
void loop()
{
// read box 1, moist sensor
MoistValueBox1 = analogRead(MoistSensorBox1);
MoistValueBox1 = map(MoistValueBox1, 550, 10, 0, 100); // 0-100% og upper = 550, lower = 10
// Time right now.
time = millis();
// Watering loop for Box 1
if (MoistValueBox1 < 50 && Box1WaterCooldownTime < time) // If moisture is less than 50%
{
digitalWrite(SolenoidWaterBox1, HIGH); // Watering.
delay(5000); // for 5 seconds
digitalWrite(SolenoidWaterBox1, LOW); // End of watering.
Box1WaterCooldownTime = time + 300000; // 5 min cooldown Box 1
}
}发布于 2022-04-28 09:30:52
真正确定它是否有效的唯一方法是将它上传到Arduino。
对于使用多个框的Arduino,懒惰的方法是复制/粘贴并一个接一个地检查这些框。
if (MoistValueBox1 < 50 && Box1WaterCooldownTime < time) {
digitalWrite(SolenoidWaterBox1, HIGH); // Watering.
delay(5000); // for 5 seconds
digitalWrite(SolenoidWaterBox1, LOW); // End of watering.
Box1WaterCooldownTime = time + 300000; // 5 min cooldown Box 1
}
time = millis();
if (MoistValueBox2 < 50 && Box2WaterCooldownTime < time) {
digitalWrite(SolenoidWaterBox2, HIGH); // Watering.
delay(5000); // for 5 seconds
digitalWrite(SolenoidWaterBox2, LOW); // End of watering.
Box2WaterCooldownTime = time + 300000;
} 等等..。
更好的做法是创建一个函数,以螺线管的引脚号、水分传感器和冷却时间作为其参数,并返回新的冷却时间。浇水时间为5分钟,其他时间则为零。
int waterBox(sensorPin, solenoidPin, cooldownTime) {
time = millis();
if (cooldownTime < time) {
int sensorValRaw = analogRead(sensorPin);
int sensorVal = map(sensorValRaw, 550, 10, 0, 100);
if (sensorVal < 50) {
digitalWrite(solenoidPin, HIGH); // Watering.
delay(5000); // for 5 seconds
digitalWrite(solenoidPin, LOW); // End of watering.
return time + 300000; // 5 min cooldown Box 2
}
}
return time;
}框1将像这样调用此函数
void loop() {
Box1WaterCooldownTime = waterBox(MoistSensorBox1, SolenoidWaterBox1, Box1WaterCooldownTime);
}进一步的清理可以包括为每个框创建一个类结构,或者将所有值存储在数组中,这样就可以轻松地扩展到更多的框,而无需复制粘贴大量代码。
https://stackoverflow.com/questions/71996989
复制相似问题