This project demonstrates how to use an ESP32 with an ILI9341 TFT display to interact with Together AI's LLM API. The ESP32 connects to Wi-Fi, sends a prompt to Together AI, and displays the AI's response on the screen. This enables a simple embedded AI chatbot or information display.
ILI9341 + Together AI Setup 1
ILI9341 + Together AI Setup 2
import urequests
import json
import time
import network
from machine import Pin, SPI
import ili934xnew
import glcdfont
import tt14
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to Wi-Fi...")
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(0.5)
print("Connected to:", wlan.ifconfig())
def ask_together_ai(prompt):
display.print("Asking AI...")
API_KEY = "YOUR_API_KEY"
url = "https://api.together.xyz/v1/chat/completions"
headers = {
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json"
}
data = {
"model": "moonshotai/Kimi-K2-Instruct",
"messages": [{"role": "user", "content": "Write using only letters in exact 100 words" + prompt}],
"temperature": 0.7,
"max_tokens": 200
}
try:
response = urequests.post(url, headers=headers, data=json.dumps(data))
result = response.json()
response.close()
if "choices" in result:
return result["choices"][0]["message"]["content"]
else:
return "API error: " + str(result.get("error", "Unknown error"))
except Exception as e:
return "Request failed: " + str(e)
def main():
connect_wifi("Wokwi-GUEST", "") # Change to your Wi-Fi SSID/PW if needed
print("Asking AI...")
prompt = "What is ESP32?"
display.set_pos(0,0)
display.print(prompt+"\n")
answer = ask_together_ai(prompt)
display.set_pos(0,30)
display.print(answer)
# ==== SPI and ILI9341 Display Setup ====
spi = SPI(1, baudrate=20000000, sck=Pin(18), mosi=Pin(23))
cs = Pin(5, Pin.OUT)
dc = Pin(2, Pin.OUT)
rst = Pin(4, Pin.OUT)
display = ili934xnew.ILI9341(spi, cs, dc, rst, w=240, h=320, r=1)
display.erase()
display.set_font(tt14)
display.set_color(0xFFFF, 0x0000)
main()