简体   繁体   中英

Wire.onReceive() function on Arduino

I am trying to take what is in this example given by the Arduino Wire library, and apply it to a program I am writing.

This is my code. The Comm.NDP[] statements are other class instances not saved in this file, so I believe you can ignore them.

**
* I2C.cpp handles sending of event messages
*    between the LORA and MEGA via I2C protocol.
*/

#include "I2C.h"
#include "DATA.h"
#include "Globals.h"
#include <Wire.h>
#include <Arduino.h>

/**
 * Constructor used to reference all other variables & functions.
 */
I2C::I2C() {
}

/**
 * Assigns the proper address to the current micro controller.
 */
void I2C::initialize() {
  //Sets the address for the current micro controller.
  //   Mega - 0
  //   LoRa - 1
  Wire.begin(0);
  Wire.setClock(8000000);
  //Registers recieveEvent as a interrupt.
  Wire.onReceive(receiveEvent); // register event
}

/**
 * Receives byte over I2C Connection.
 */
static void receiveEvent(int howmany) {
  //Iterator used below.
  int i = 0;
  for(i=0;i<120;i++) {
    Comm.NDP[i] = ' ';
  }
  //Resets iterator.
  i = 0;
  //Checks to see if serial port is empty.
  while (1 < Wire.available()) {
    //Reads in single character from serial port.
    char character = Wire.read();
    NDP[i] = character;
    i++;
  }
  Serial.println(Comm.NDP);
}

The example code from Arduino's Wire.h library

#include <Wire.h>

void setup() {
  Wire.begin(8); // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600); // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c); // print the character
  }
  int x = Wire.read(); // receive byte as an integer
  Serial.println(x); // print the integer
}

I am getting this error from the Arduino IDE.

error: invalid use of non-static member function

Wire.onReceive(receiveEvent); // register event

                          ^

exit status 1 invalid use of non-static member function

You're missing declaration of receiveEvent before first use. Either move it's definition before begin or add there:

void receiveEvent(int howMany);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM