@@ -22,6 +22,7 @@ final int bytesPerFrame = cameraPixelCount * cameraBytesPerPixel;
2222PImage myImage;
2323byte [] frameBuffer = new byte [bytesPerFrame];
2424int lastUpdate = 0 ;
25+ boolean shouldRedraw = false ;
2526
2627void setup () {
2728 size (640 , 480 );
@@ -44,14 +45,18 @@ void setup() {
4445}
4546
4647void draw () {
47- PImage img = myImage. copy();
48- img. resize(640 , 480 );
49- image (img, 0 , 0 );
5048 // Time out after 1.5 seconds and ask for new data
5149 if (millis () - lastUpdate > 1500 ) {
5250 println (" Connection timed out." );
5351 myPort. write(1 );
5452 }
53+
54+ if (shouldRedraw){
55+ PImage img = myImage. copy();
56+ img. resize(640 , 480 );
57+ image (img, 0 , 0 );
58+ shouldRedraw = false ;
59+ }
5560}
5661
5762void serialEvent (Serial myPort ) {
@@ -60,21 +65,26 @@ void serialEvent(Serial myPort) {
6065 // read the received bytes
6166 myPort. readBytes(frameBuffer);
6267
63- // access raw bytes via byte buffer
68+ // Access raw bytes via byte buffer and ensure
69+ // proper endianness of the data for > 8 bit values.
6470 ByteBuffer bb = ByteBuffer . wrap(frameBuffer);
6571 bb. order(ByteOrder . BIG_ENDIAN );
6672
6773 int i = 0 ;
6874
6975 while (bb. hasRemaining()) {
70- // read 16 -bit pixel
76+ // read 8 -bit pixel
7177 byte pixelValue = bb. get();
7278
7379 // set pixel color
7480 myImage. pixels [i++ ] = color (Byte . toUnsignedInt(pixelValue));
7581 }
7682
7783 myImage. updatePixels();
84+
85+ // Ensures that the new image data is drawn in the next draw loop
86+ shouldRedraw = true ;
87+
7888 // Let the Arduino sketch know we received all pixels
7989 // and are ready for the next frame
8090 myPort. write(1 );
0 commit comments