Video webcam motion detection troubles

Here it is.
You have to give the CAMARA permission to run.
You can test it downloading the app APDE on play store. I’ll take just two minutes.

// Thanks to
// Daniel Shiffman
// http://www.learningprocessing.com
// Code for Android / Ketai by noel

import ketai.camera.*;
KetaiCamera cam;

PImage prevFrame;
float threshold = 50;

void setup() {
  size(320, 240);
  cam = new KetaiCamera(this, 320, 240, 31);
  //  cam.setCameraID(1); // If you want the front camara
  cam.start();
  prevFrame = createImage(cam.width, cam.height, RGB);
}


void onCameraPreviewEvent() {
  prevFrame.copy(cam, 0, 0, cam.width, cam.height, 0, 0, cam.width, cam.height);
  prevFrame.updatePixels();
  cam.read();
}


void draw() {
  background(255);

  // You don't need to display it to analyze it!
  image(cam, 0, 0);

  cam.loadPixels();
  prevFrame.loadPixels();

  // Start with a total of 0
  // These are the variables we'll need to find the average X and Y
  float sumX = 0;
  float sumY = 0;
  int motionCount = 0; 

  // Begin loop to walk through every pixel
  for (int x = 0; x < cam.width; x++ ) {
    for (int y = 0; y < cam.height; y++ ) {
      // What is the current color
      color current = cam.pixels[x+y*cam.width];

      // What is the previous color
      color previous = prevFrame.pixels[x+y*cam.width];

      // Step 4, compare colors (previous vs. current)
      float r1 = red(current); 
      float g1 = green(current);
      float b1 = blue(current);
      float r2 = red(previous); 
      float g2 = green(previous);
      float b2 = blue(previous);

      // Motion for an individual pixel is the difference between the previous color and current color.
      float diff = dist(r1, g1, b1, r2, g2, b2);

      // If it's a motion pixel add up the x's and the y's
      if (diff > threshold) {
        sumX += x;
        sumY += y;
        motionCount++;
      }
    }
  }

  // average location is total location divided by the number of motion pixels.
  float avgX = sumX / motionCount; 
  float avgY = sumY / motionCount; 

  // Draw a circle based on average motion
  smooth();
  noStroke();
  fill(255);
  ellipse(avgX, avgY, 16, 16);
  
}