Skip to content

Fix buffer sync issue in camera raw bytes example #143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Feb 23, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Decrease CPU load by avoiding unnecessary redraws
  • Loading branch information
sebromero committed Feb 23, 2021
commit 3512da443e2237d8077672c99173266bb119ce2d
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ final int bytesPerFrame = cameraPixelCount * cameraBytesPerPixel;
PImage myImage;
byte[] frameBuffer = new byte[bytesPerFrame];
int lastUpdate = 0;
boolean shouldRedraw = false;

void setup() {
size(640, 480);
Expand All @@ -44,14 +45,18 @@ void setup() {
}

void draw() {
PImage img = myImage.copy();
img.resize(640, 480);
image(img, 0, 0);
// Time out after 1.5 seconds and ask for new data
if(millis() - lastUpdate > 1500) {
println("Connection timed out.");
myPort.write(1);
}

if(shouldRedraw){
PImage img = myImage.copy();
img.resize(640, 480);
image(img, 0, 0);
shouldRedraw = false;
}
}

void serialEvent(Serial myPort) {
Expand All @@ -60,21 +65,26 @@ void serialEvent(Serial myPort) {
// read the received bytes
myPort.readBytes(frameBuffer);

// access raw bytes via byte buffer
// Access raw bytes via byte buffer and ensure
// proper endianness of the data for > 8 bit values.
ByteBuffer bb = ByteBuffer.wrap(frameBuffer);
bb.order(ByteOrder.BIG_ENDIAN);

int i = 0;

while (bb.hasRemaining()) {
// read 16-bit pixel
// read 8-bit pixel
byte pixelValue = bb.get();

// set pixel color
myImage.pixels[i++] = color(Byte.toUnsignedInt(pixelValue));
}

myImage.updatePixels();

// Ensures that the new image data is drawn in the next draw loop
shouldRedraw = true;

// Let the Arduino sketch know we received all pixels
// and are ready for the next frame
myPort.write(1);
Expand Down