Send Image to gemma4:e2b

Application : Android Edge-Gallery App (Model = gemma4:e2b , AI Chat with Text/Image API)

Example: Ollama_sendImage.ino

Question: the following code’s waitTime is fix at 10000 ms, how to modify it to keep waiting till all text are received from LLM ?

    Serial.println("Receive");
    uint32_t waitTime = 10000;
    uint32_t startTime = millis();
    boolean state = false;
    boolean markState = false;

    while ((startTime + waitTime) > millis()) {
        Serial.print(".");
        delay(1000);
    }

    while (client.available()) {
        char c = client.read();
        if (String(c) == "{") {
            markState = true;
        }
        if (state == true && markState == true) {
            Feedback += String(c);
        }
        if (c == '\n') {
            if (getResponse.length() == 0) {
                state = true;
            }
            getResponse = "";
        } else if (c != '\r') {
            getResponse += String(c);
        }
    }

:waving_hand: Thanks for posting!

For documentation, SDK resources, FAQs, and community guidelines, please visit: here

For commercial users, if you would like to have dedicated technical support or to connect with us, please fill in the Private User Form

Happy building with Ameba!


:waving_hand: 感謝您的分享!

如需查閱技術文件、SDK 資源、常見問題及社群指南,請參考: 這裡

若您是商業用戶,希望獲得專屬技術支援或與我們聯繫,請填寫 Private User Form (商業用戶表單)

祝您使用 Ameba 開發順利!

i made the example copy and pasting a few things together, i never did figure that part out. im sure if you stick the code into one of the AI’s it will fix it.

gemini gave me this

void send_Ollama()
{
Serial.println("Connect to " + String(myDomain));
if (!client.connect(myDomain, 11434)) {
Serial.println(“Connection failed”);
return;
}

Serial.println(“Connection successful”);
Camera.getImage(0, &img_addr, &img_len);
Serial.println(“Image Captured: " + String(img_len) + " bytes”);

// 1. Prepare JSON structure
String jsonStart = “{\“model\”: \”" + model + “\”, \“messages\”: [{\“role\”: \“user\”,\“content\”: [{ \“type\”: \“text\”, \“text\”: \“” + prompt + “\”},{\“type\”: \“image_url\”, \“image_url\”: {\“url\”: \“data:image/jpeg;base64,”};
String jsonEnd = “\”}}]}]}";

// 2. Calculate Content-Length without building the string in memory
// Base64 expands 3 bytes to 4 characters. We calculate exact padded length.
uint32_t b64Len = 4 * ((img_len + 2) / 3);
uint32_t contentLength = jsonStart.length() + b64Len + jsonEnd.length();

// 3. Send HTTP Headers
Serial.println(“Sending Request…”);
client.println(“POST /v1/chat/completions HTTP/1.1”);
client.println("Host: " + String(myDomain));
client.println("Authorization: Bearer " + ollama_key);
client.println(“Content-Type: application/json; charset=utf-8”);
client.println("Content-Length: " + String(contentLength));
client.println(“Connection: close”);
client.println();

// 4. Stream JSON start
client.print(jsonStart);

// 5. Stream Base64 directly to the client
uint8_t *input = (uint8_t *)img_addr;
uint32_t bytesLeft = img_len;
char b64Chunk[5]; // 4 bytes + null terminator

while (bytesLeft > 0) {
uint8_t chunkLen = (bytesLeft < 3) ? bytesLeft : 3;
base64_encode(b64Chunk, (char*)input, chunkLen);
client.print(b64Chunk);
input += chunkLen;
bytesLeft -= chunkLen;
}

// 6. Stream JSON end
client.print(jsonEnd);

// 7. Wait for response with a timeout (e.g., 60 seconds for LLM processing)
Serial.println(“\nWaiting for server response…”);
uint32_t startTime = millis();
while (client.connected() && !client.available()) {
if (millis() - startTime > 60000) {
Serial.println(“Timeout waiting for response.”);
client.stop();
return;
}
delay(10);
}

// 8. Read the response robustly
String responseBody = “”;
bool isBody = false;

while (client.connected() || client.available()) {
if (client.available()) {
String line = client.readStringUntil(‘\n’);
line.trim(); // Remove \r

    if (line.length() == 0 && !isBody) {
        isBody = true; // Empty line separates HTTP headers from the body
    } else if (isBody) {
        responseBody += line;
    }
}

}

// 9. Parse JSON
if (responseBody.length() > 0) {
DeserializationError error = deserializeJson(doc, responseBody);
if (!error) {
String content = doc[“choices”][0][“message”][“content”];
Serial.println(“\n— Ollama Response —”);
Serial.println(content);
} else {
Serial.print("JSON Parse Failed: ");
Serial.println(error.c_str());
Serial.println(responseBody); // Print raw text to debug
}
}

client.stop();
Serial.println(“Connection closed.”);