Hello everyone. I'm having a tough time figuring out the error in my code. I have a bluetooth module on a Nano, which will send data to a Mega using Wire. Here is the code for the Nano+BT module:
char data = 0;
#define led 3
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop()
{
if(Serial.available() > 0) // Send data only when you receive data:
{
data = Serial.read();
Serial.print(data);
Serial.print("\n");
digitalWrite(led, HIGH); // flash LED when BT command received
delay(150);
digitalWrite(led, LOW);
Wire.beginTransmission(A4); // SDA on Mega
Wire.write(data);
Wire.endTransmission();
int x = Wire.endTransmission();
Serial.println(x, DEC);
}
}
This module receives BT commands just fine, but Serial.println returns 2 for Wire.endTransmission.
Here is the code for the mega:
#include <Wire.h>
#define lights 4
int data;
void setup() {
Wire.begin(20); // SDA
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void receiveEvent(int bytes)
{
data = Wire.read();
Serial.print(data);
}
void loop()
{
if (data = 1) {
analogWrite(lights,255);
Serial.println(data);
}
}
With that code, the serial monitor for the Mega returns a constant stream of 1's. I could change it to "if (data = 2)", but then it just returns a constant stream of 2's (even though the BT module is not sending a 2). I can also remove the receiveEvent code, but it still returns 1's. However if I change it to "if (data == 1)", then nothing is returned at all.
What am I doing wrong? Thank you in advance.