I’ve been trying to receive image data from an Arduino, but I keep creating a corrupted file. I based it off the code from one of the Electric Imp example on Github.
This is the code I’m using to receive the data. The CHUNK_SIZE is 32 and the Arduino sends the same chunk size continouously. However, I’m still not correctly receiving the image. I added the imp.sleep since I thought the UART buffer was getting full.
`
function read_bytes(n) {
local rx_buffer = blob(n);
local data = arduino.read();
while ((data >= 0) && (rx_buffer.tell() < n)) {
rx_buffer.writen(data,'b');
data = arduino.read();
while (data == -1){
data = arduino.read();
}
}
return rx_buffer;
}
function send_pic(num_chunks){
for(local i = 0; i < num_chunks; i++) {
imp.sleep(0.01);
local startingAddress = i*CHUNK_SIZE;
local buf = read_bytes(CHUNK_SIZE);
agent.send(“jpeg_chunk”, [startingAddress, buf]);
}
}`
As far as I can see, your nested while loop will never be executed. Is it there to clear any remaining data after your rx_buffer is full? If so, the while loop should come AFTER the first loop, not inside it.
The while loop is because the rx_buffer was being filled with null bytes from invalid reads, so I waited until the read created a valid read. It does get executed if the read in the line before gets -1.
uart.read() returns -1 (0xFF*) if there’s nothing in the buffer, so your section:
while (data == -1) { data = arduino.read(); }
will sit there forever once the Arduino stops transmitting.
I think I’d replace this with
if (data == -1) break;
to get you out of the loop and return rx_buffer.
I might be inclined to try something like this:
`function read_bytes(n)
{
local rx_buffer = blob(n);
do
{
data = arduino.read()
if (data != -1) rx_buffer.writen(data,'b');
}
while (rx_buffer.tell() < n)
return rx_buffer;
}`
Keeps reading until you have a full rx_buffer.
PS. The UART read buffer size is 80 bytes.
*Actually, it is 0xFFFFFFFF, @philmy reminds me. Squirrel’s integers are 32 bits long, not 8. Old habits die hard…