Build Your Own Talking AI Robot!
A super fun Raspberry Pi project for curious kids and makers — your robot will talk, listen, and answer questions just like ChatGPT!
📋 What's Inside This Guide?
What You Will Build!
Imagine having your very own robot buddy that can answer any question you ask, just like asking ChatGPT — but it talks back to you and shows a cool face on a tiny screen! That's exactly what we're building today! 🎉
Parts & Components You Need
Always get a parent or teacher to help you buy parts online and handle soldering if needed. Safety first!
Use a breadboard and jumper wires to connect everything. Double-check each wire before powering on!
📍 Quick Pin Reference Table
| Component | Component Pin | Raspberry Pi Pin | Notes |
|---|---|---|---|
| OLED SSD1306 | VCC | 3.3V (Pin 1) | Power supply |
| OLED SSD1306 | GND | GND (Pin 6) | Ground |
| OLED SSD1306 | SDA | GPIO2 (Pin 3) | I2C Data |
| OLED SSD1306 | SCL | GPIO3 (Pin 5) | I2C Clock |
| DHT22 | VCC | 3.3V (Pin 1) | Power supply |
| DHT22 | GND | GND (Pin 6) | Ground |
| DHT22 | DATA | GPIO4 (Pin 7) | Sensor data |
| PIR Sensor | VCC | 5V (Pin 2) | Needs 5V! |
| PIR Sensor | GND | GND (Pin 6) | Ground |
| PIR Sensor | OUT | GPIO17 (Pin 11) | Motion signal |
| Green LED | Anode (+) | GPIO18 (Pin 12) | Via 220Ω resistor |
| Red LED | Anode (+) | GPIO23 (Pin 16) | Via 220Ω resistor |
| Push Button | One leg | GPIO24 (Pin 18) | Via 10kΩ pull-down |
Setting Up Raspberry Pi
Download Raspberry Pi Imager from raspberrypi.com and flash Raspberry Pi OS (64-bit) onto your MicroSD card.
- Boot up your Raspberry Pi and connect to your WiFi network from the desktop.
- Open a Terminal window (it looks like a black screen where you type commands).
- Enable I2C for the OLED display: go to Preferences → Raspberry Pi Configuration → Interfaces and turn I2C ON.
- Update your Pi by running the commands below — this makes sure everything is fresh!
# Step 1: Update your Raspberry Pi sudo apt update && sudo apt upgrade -y # Step 2: Install Python pip and audio tools sudo apt install -y python3-pip python3-dev portaudio19-dev espeak ffmpeg # Step 3: Install Python libraries pip3 install openai adafruit-circuitpython-ssd1306 \ pillow RPi.GPIO Adafruit_DHT \ SpeechRecognition pyaudio pyttsx3 gTTS playsound # Step 4: Check if OLED is detected (should show address 0x3c) sudo i2cdetect -y 1 # Step 5: Check microphone is working arecord -l
Go to platform.openai.com, create a free account, and grab your API key. You'll need it for the robot's brain! Ask a parent to help set up billing (it's very cheap for small use).
OLED Display Code — The Robot's Face!
This code draws a fun animated robot face on the tiny OLED screen. The eyes blink and change expression!
# oled_face.py — Controls the robot's OLED face display import board import busio import adafruit_ssd1306 from PIL import Image, ImageDraw import time # ── Setup OLED (128x64 pixels) ────────────────────────────────── i2c = busio.I2C(board.SCL, board.SDA) oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c) def draw_robot_face(mood="happy"): """Draw a robot face on the OLED screen. mood can be: 'happy', 'thinking', 'listening', 'speaking' """ image = Image.new("1", (oled.width, oled.height)) draw = ImageDraw.Draw(image) # Clear screen (black background) draw.rectangle((0, 0, oled.width, oled.height), fill=0) # ── Draw robot head outline ────────────────────────────────── draw.rounded_rectangle((10, 5, 118, 58), radius=8, outline=255) # ── Draw eyes based on mood ────────────────────────────────── if mood == "happy": # Normal round eyes draw.ellipse((28, 18, 50, 38), fill=255) # Left eye draw.ellipse((78, 18, 100, 38), fill=255) # Right eye # Happy smile draw.arc((35, 40, 93, 58), start=0, end=180, fill=255, width=2) elif mood == "thinking": # Squinting eyes (thinking hard!) draw.rectangle((28, 26, 50, 30), fill=255) # Left eye squint draw.rectangle((78, 26, 100, 30), fill=255) # Right eye squint # Thinking dots ... for i in range(3): draw.ellipse((45+i*15, 46, 52+i*15, 53), fill=255) elif mood == "listening": # Wide open eyes (paying attention!) draw.ellipse((22, 14, 52, 42), fill=255) # Big left eye draw.ellipse((76, 14, 106, 42), fill=255) # Big right eye # Neutral mouth draw.line((45, 52, 83, 52), fill=255, width=2) elif mood == "speaking": # Normal eyes with open mouth (talking!) draw.ellipse((28, 18, 50, 38), fill=255) draw.ellipse((78, 18, 100, 38), fill=255) # Open mouth draw.ellipse((42, 44, 86, 58), outline=255, fill=0) oled.image = image oled.show() def blink_animation(): """Make the robot blink its eyes — so cute! 👀""" draw_robot_face("happy") time.sleep(0.1) # Briefly close eyes image = Image.new("1", (oled.width, oled.height)) draw = ImageDraw.Draw(image) draw.rounded_rectangle((10, 5, 118, 58), radius=8, outline=255) draw.line((28, 28, 50, 28), fill=255, width=3) # Closed left eye draw.line((78, 28, 100, 28), fill=255, width=3) # Closed right eye oled.image = image oled.show() time.sleep(0.1) draw_robot_face("happy") # Test it! Run this file to see your robot face if __name__ == "__main__": moods = ["happy", "thinking", "listening", "speaking"] for mood in moods: print(f"Showing mood: {mood}") draw_robot_face(mood) time.sleep(2) blink_animation()
AI Brain Code — Connect to ChatGPT!
We send your question over the internet to OpenAI's servers. They think about it and send back an answer — just like magic! The robot then reads the answer out loud.
# ai_brain.py — The robot's AI brain powered by ChatGPT! from openai import OpenAI import os # ── IMPORTANT: Put your OpenAI API Key here ────────────────────── # Ask a parent to help get this from platform.openai.com API_KEY = "your-openai-api-key-here" # ← Replace this! client = OpenAI(api_key=API_KEY) # This is the robot's personality — you can change this! ROBOT_PERSONALITY = """You are Robo, a friendly and helpful robot assistant. You love talking to kids and explaining things in simple, fun ways. Keep your answers short (2-3 sentences max) and always be positive! If someone asks your name, say you are Robo, their robot buddy!""" # Remember the conversation so the robot doesn't forget! conversation_history = [ {"role": "system", "content": ROBOT_PERSONALITY} ] def ask_robot(question): """Send a question to ChatGPT and get a robot-friendly answer!""" global conversation_history print(f"\n🤔 You asked: {question}") print("🧠 Robot is thinking...") # Add your question to the conversation conversation_history.append({ "role": "user", "content": question }) try: # Ask ChatGPT! response = client.chat.completions.create( model="gpt-4o-mini", # Fast and cheap model messages=conversation_history, max_tokens=150, # Keep answers short temperature=0.7 # Makes answers creative ) # Get the answer answer = response.choices[0].message.content # Remember what the robot said conversation_history.append({ "role": "assistant", "content": answer }) # Keep memory from getting too long (last 10 messages) if len(conversation_history) > 12: conversation_history = [conversation_history[0]] + \ conversation_history[-10:] print(f"🤖 Robo says: {answer}") return answer except Exception as e: error_msg = f"Oops! I had a problem: {str(e)}" print(error_msg) return error_msg def reset_memory(): """Clear the robot's memory and start fresh!""" global conversation_history conversation_history = [ {"role": "system", "content": ROBOT_PERSONALITY} ] print("🔄 Memory cleared! Robot is fresh and ready.") # Test it! if __name__ == "__main__": answer = ask_robot("Hello! What is your name?") answer = ask_robot("What is 2 + 2?") answer = ask_robot("Why is the sky blue?")
Voice Code — Listen & Speak!
# voice.py — Gives the robot ears and a voice! import speech_recognition as sr import pyttsx3 from gtts import gTTS import os import time # ── Setup the robot's voice ────────────────────────────────────── engine = pyttsx3.init() engine.setProperty('rate', 160) # Speaking speed (words per minute) engine.setProperty('volume', 1.0) # Max volume # Try to set a robotic-sounding voice voices = engine.getProperty('voices') if voices: engine.setProperty('voice', voices[0].id) # Use first available voice # ── Setup the microphone ───────────────────────────────────────── recognizer = sr.Recognizer() recognizer.energy_threshold = 300 # Sensitivity (lower = more sensitive) recognizer.pause_threshold = 1.0 # Seconds of silence to stop listening def robot_speak(text): """Make the robot say something out loud!""" print(f"🔊 Speaking: {text}") try: # Use Google Text-to-Speech (needs internet, sounds better) tts = gTTS(text=text, lang='en', slow=False) tts.save("/tmp/robot_speech.mp3") os.system("mpg123 /tmp/robot_speech.mp3 2>/dev/null") except: # Fallback: use offline voice if no internet engine.say(text) engine.runAndWait() def robot_listen(timeout=10): """Listen through the microphone and return what was said. Returns the text string, or None if nothing was heard. """ with sr.Microphone() as source: print("👂 Listening... (speak now!)") # Adjust for background noise first recognizer.adjust_for_ambient_noise(source, duration=0.5) try: # Listen for up to 'timeout' seconds audio = recognizer.listen(source, timeout=timeout, phrase_time_limit=8) print("🎙️ Got audio! Processing...") # Convert speech to text using Google text = recognizer.recognize_google(audio) print(f"✅ You said: '{text}'") return text.lower() except sr.WaitTimeoutError: print("⏰ No speech detected (timeout)") return None except sr.UnknownValueError: print("❓ Could not understand the speech") return None except sr.RequestError as e: print(f"🌐 Network error: {e}") return None # Test it! if __name__ == "__main__": robot_speak("Hello! I am Robo, your robot buddy!") time.sleep(1) robot_speak("Say something and I will repeat it!") heard = robot_listen() if heard: robot_speak(f"You said: {heard}")
Main Robot Code — Put It All Together!
This is the big file that connects everything! It reads sensors, watches for motion, listens for questions, thinks with AI, and talks back.
#!/usr/bin/env python3 # robot_main.py — MAIN FILE: Run this to start your robot! # Talking AI Robot with Raspberry Pi # ───────────────────────────────────────────────────────────── import RPi.GPIO as GPIO import Adafruit_DHT import time import threading from oled_face import draw_robot_face, blink_animation from ai_brain import ask_robot, reset_memory from voice import robot_speak, robot_listen # ── GPIO Pin Numbers ────────────────────────────────────────────── PIR_PIN = 17 # Motion sensor GREEN_LED = 18 # Listening indicator RED_LED = 23 # Thinking indicator BUTTON_PIN = 24 # Manual question button DHT_PIN = 4 # Temperature/humidity DHT_TYPE = Adafruit_DHT.DHT22 # ── GPIO Setup ─────────────────────────────────────────────────── GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(PIR_PIN, GPIO.IN) GPIO.setup(GREEN_LED, GPIO.OUT) GPIO.setup(RED_LED, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Start with all LEDs off GPIO.output(GREEN_LED, GPIO.LOW) GPIO.output(RED_LED, GPIO.LOW) # ── Helper Functions ────────────────────────────────────────────── def set_status(status): """Control LEDs and face based on robot state.""" if status == "listening": GPIO.output(GREEN_LED, GPIO.HIGH) GPIO.output(RED_LED, GPIO.LOW) draw_robot_face("listening") elif status == "thinking": GPIO.output(GREEN_LED, GPIO.LOW) GPIO.output(RED_LED, GPIO.HIGH) draw_robot_face("thinking") elif status == "speaking": GPIO.output(GREEN_LED, GPIO.LOW) GPIO.output(RED_LED, GPIO.LOW) draw_robot_face("speaking") elif status == "idle": GPIO.output(GREEN_LED, GPIO.LOW) GPIO.output(RED_LED, GPIO.LOW) draw_robot_face("happy") def get_sensor_data(): """Read temperature and humidity from DHT22 sensor.""" humidity, temperature = Adafruit_DHT.read_retry(DHT_TYPE, DHT_PIN) if humidity is not None: return f"{temperature:.1f}°C, {humidity:.1f}% humidity" return "sensor unavailable" def handle_question(): """Full cycle: listen → think → speak → show face.""" # Step 1: Show listening mode set_status("listening") robot_speak("I am listening! Ask me anything!") # Step 2: Listen for question question = robot_listen(timeout=8) if question is None: set_status("idle") robot_speak("I did not hear anything. Try again!") return # Step 3: Check for special commands if "temperature" in question or "weather" in question: sensor_data = get_sensor_data() set_status("speaking") robot_speak(f"Right now it is {sensor_data} around me!") set_status("idle") return if "reset" in question or "forget" in question: reset_memory() robot_speak("Memory cleared! I am fresh and ready to go!") set_status("idle") return # Step 4: Think with AI set_status("thinking") answer = ask_robot(question) # Step 5: Speak the answer set_status("speaking") robot_speak(answer) # Step 6: Back to happy idle set_status("idle") # ── AUTO BLINK THREAD ───────────────────────────────────────────── def auto_blink(): """Blink the robot eyes automatically every few seconds.""" while True: time.sleep(4) blink_animation() blink_thread = threading.Thread(target=auto_blink, daemon=True) blink_thread.start() # ── MAIN LOOP ──────────────────────────────────────────────────── print("🤖 ROBO is starting up!") set_status("idle") robot_speak("Hello! I am Robo, your AI robot buddy! Press my button or wave to start!") print("✅ Robot is ready! Waiting for motion or button press...") print(" Press CTRL+C to stop the robot.") try: last_motion_time = 0 cooldown = 8 # Seconds between activations while True: current_time = time.time() button_pressed = GPIO.input(BUTTON_PIN) == GPIO.HIGH motion_detected = GPIO.input(PIR_PIN) == GPIO.HIGH # Activate if button pressed OR motion detected (after cooldown) if button_pressed or (motion_detected and (current_time - last_motion_time) > cooldown): last_motion_time = current_time print("\n🚀 Activated!", "Button" if button_pressed else "Motion") handle_question() time.sleep(0.1) # Small pause to not waste power except KeyboardInterrupt: print("\n👋 Robot shutting down... Goodbye!") robot_speak("Goodbye! See you next time!") GPIO.cleanup() print("GPIO cleaned up. Bye! 🤖")
Testing Your Robot! 🚀
- Double-check all your wires match the circuit diagram. Make sure nothing is loose!
- Open a terminal and navigate to your project folder:
cd ~/robot - Test the OLED face first:
python3 oled_face.py— you should see faces appear! - Test the voice:
python3 voice.py— the robot should speak and then repeat what you say. - Test the AI brain:
python3 ai_brain.py— check it connects to ChatGPT. - Run the full robot:
python3 robot_main.py— press the button and talk!
"What is the capital of France?" • "Tell me a joke!" • "What is the temperature?" • "How do volcanoes work?" • "Who invented the telephone?"
🔧 Troubleshooting — Something Not Working?
| Problem | Fix It! |
|---|---|
| OLED shows nothing | Run sudo i2cdetect -y 1 — check 0x3C shows up. Re-check SDA/SCL wires. |
| No sound from speaker | Check speaker is plugged in. Run speaker-test -t wav in terminal. |
| Robot can't hear you | Run arecord -l to check mic. Try speaking louder or closer. |
| API error / No internet | Check WiFi. Make sure your API key is correct in ai_brain.py |
| PIR sensor always ON | Adjust the sensitivity dial on the PIR module with a small screwdriver. |
| Python module not found | Re-run the pip3 install commands from Step 3. |
Cool Upgrades & Ideas! 💡
Here are some amazing ideas to make your robot even more awesome. Each one teaches you new coding skills!
Check out raspberrypi.com/learn for more free projects, or search for "Raspberry Pi for kids" on YouTube. Learning to build robots is a superpower — keep going! 💪
⚡ Make Robot Start Automatically When Pi Powers On
Add this to your crontab so the robot wakes up every time you turn on the Raspberry Pi!
# Open crontab editor crontab -e # Add this line at the bottom (change path to your folder!): @reboot sleep 10 && python3 /home/pi/robot/robot_main.py > /home/pi/robot/robot.log 2>&1 & # Save and exit. Now the robot starts automatically every boot! # Check logs anytime with: cat /home/pi/robot/robot.log

Comments
Post a Comment