我目前正在开展一个项目,通过I2C连接2个Arduino。 Arduino mega 2560是主人,UNO是奴隶。 IR接收器连接到UNO,其从遥控器捕获IR信号并将接收到的信号发送到MEGA进行一些处理。然而,即使没有传输IR信号,IR接收器仍然记录值为0的IR信号。这个问题是由于硬件问题还是我在代码中遗漏了什么?需要注意的是,Arduino每隔3秒就要求来自UNO的IR信号。 MEGA的工作是验证收到的信号是否应由Arduino UNO发送。此功能用于模拟控制房间中的IR设备。下面是奴隶UNO的代码:
IRrecv My_receiver(2);
IRdecode My_decoder;
String wireDecoderSignal = "";
String valueFromMaster;
long wireDecoderSignalValue;
void setup() {
Wire.begin(5);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
My_receiver.enableIRIn();
}
void loop() {
if (My_receiver.GetResults(&My_decoder))
{ //if (My_receiver.GetResults(&My_decoder)) starts
My_decoder.decode();
if (My_decoder.value != 4294967295 )
{ // if (My_decoder.value != 4294967295) starts
wireDecoderSignal = String(My_decoder.value, HEX);
wireDecoderSignalValue = My_decoder.value;
Serial.println(wireDecoderSignal);
} // if (My_decoder.value != 4294967295) ends
My_receiver.resume();
}//if (My_receiver.GetResults(&My_decoder)) ends
}
void requestEvent()
{
if (wireDecoderSignal.length() == 8)
{
Serial.println("sending" + wireDecoderSignal);
Wire.write(wireDecoderSignal.c_str());
wireDecoderSignal = "";
}
else
{
Serial.println("SENDING 11111111");
Wire.write("11111111");
}
}
void receiveEvent(int howManyBytes)
{
while (Wire.available())
{
valueFromMaster += (char)Wire.read();
}
if (valueFromMaster == "T" || valueFromMaster == "F")
{
Serial.println("VALUE FROM MASTER IS:" + valueFromMaster);
valueFromMaster = "";
wireDecoderSignalValue = 0;
}
else if (valueFromMaster.length() == 8)
{
// code to transmitting IR signal....signal received from mobile phone to MEGA to here
// unsigned long value=strtoul(valueFromMaster.c_str(), 0, 32);
// Serial.println(value);
long decValue = 0;
int nextInt;
for (int i = 0; i < valueFromMaster.length(); i++) {
nextInt = int(valueFromMaster.charAt(i));
if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
nextInt = constrain(nextInt, 0, 15);
decValue = (decValue * 16) + nextInt;
}
valueFromMaster = "";
}
else if (valueFromMaster.indexOf("on") >= 0 || valueFromMaster.indexOf("off") >= 0)
{
// code to turn light on or off based signal received from MEGA which in turn receives signal from mobile
if (valueFromMaster.indexOf("on") >= 0)
{
digitalWrite(relayPin, HIGH);
}
else
{
digitalWrite(relayPin, LOW);
}
valueFromMaster = "";
}
}