@@ -22,6 +22,7 @@ final int bytesPerFrame = cameraPixelCount * cameraBytesPerPixel;
22
22
PImage myImage;
23
23
byte [] frameBuffer = new byte [bytesPerFrame];
24
24
int lastUpdate = 0 ;
25
+ boolean shouldRedraw = false ;
25
26
26
27
void setup () {
27
28
size (640 , 480 );
@@ -44,14 +45,18 @@ void setup() {
44
45
}
45
46
46
47
void draw () {
47
- PImage img = myImage. copy();
48
- img. resize(640 , 480 );
49
- image (img, 0 , 0 );
50
48
// Time out after 1.5 seconds and ask for new data
51
49
if (millis () - lastUpdate > 1500 ) {
52
50
println (" Connection timed out." );
53
51
myPort. write(1 );
54
52
}
53
+
54
+ if (shouldRedraw){
55
+ PImage img = myImage. copy();
56
+ img. resize(640 , 480 );
57
+ image (img, 0 , 0 );
58
+ shouldRedraw = false ;
59
+ }
55
60
}
56
61
57
62
void serialEvent (Serial myPort ) {
@@ -60,21 +65,26 @@ void serialEvent(Serial myPort) {
60
65
// read the received bytes
61
66
myPort. readBytes(frameBuffer);
62
67
63
- // access raw bytes via byte buffer
68
+ // Access raw bytes via byte buffer and ensure
69
+ // proper endianness of the data.
64
70
ByteBuffer bb = ByteBuffer . wrap(frameBuffer);
65
71
bb. order(ByteOrder . BIG_ENDIAN );
66
72
67
73
int i = 0 ;
68
74
69
75
while (bb. hasRemaining()) {
70
- // read 16 -bit pixel
76
+ // read 8 -bit pixel
71
77
byte pixelValue = bb. get();
72
78
73
79
// set pixel color
74
80
myImage. pixels [i++ ] = color (Byte . toUnsignedInt(pixelValue));
75
81
}
76
82
77
83
myImage. updatePixels();
84
+
85
+ // Ensures that the new image data is drawn in the next draw loop
86
+ shouldRedraw = true ;
87
+
78
88
// Let the Arduino sketch know we received all pixels
79
89
// and are ready for the next frame
80
90
myPort. write(1 );
0 commit comments