You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
906 B

7 years ago
  1. #include <Wire.h>
  2. #define SLAVE_ADDRESS 0x04
  3. int number = 0;
  4. int state = 0;
  5. void setup() {
  6. pinMode(13, OUTPUT);
  7. Serial.begin(9600); // start serial for output
  8. // initialize i2c as slave
  9. Wire.begin(SLAVE_ADDRESS);
  10. // define callbacks for i2c communication
  11. Wire.onReceive(receiveData);
  12. Wire.onRequest(sendData);
  13. Serial.println("Ready!");
  14. }
  15. void loop() {
  16. delay(100);
  17. }
  18. // callback for received data
  19. void receiveData(int byteCount) {
  20. while (Wire.available()) {
  21. number = Wire.read();
  22. Serial.println(number);
  23. if (number == 1) {
  24. if (state == 0) {
  25. Serial.println("LED ON");
  26. state = 1;
  27. }
  28. else {
  29. Serial.println("LED OFF");
  30. state = 0;
  31. }
  32. }
  33. }
  34. }
  35. // callback for sending data
  36. void sendData() {
  37. Wire.write(number);
  38. Serial.println("Sending...");
  39. Wire.begin(0x08);
  40. delay(100);
  41. }