diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c1c5317 --- /dev/null +++ b/.gitignore @@ -0,0 +1,40 @@ +# Ignore compiled Python files +*.pyc +__pycache__/ +*.pyo + +# Ignore hex files (these are generated and should be created fresh) +*.hex + +# Ignore OS-specific files +.DS_Store +Thumbs.db +desktop.ini + +# Ignore editor-specific files +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# Ignore temporary files +tmp/ +temp/ +*.tmp + +# Ignore build artifacts +build/ +dist/ +*.egg-info/ + +# Ignore node modules if using web tools +node_modules/ + +# Ignore logs +*.log + +# Keep the examples directory structure +!projects/**/.gitkeep +!exercises/**/.gitkeep +!resources/**/.gitkeep diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..38b53ba --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,223 @@ +# Contributing to micro:bit Workshop + +Thank you for your interest in contributing! This repository is designed to help students learn programming with the BBC micro:bit. + +## How to Contribute + +### Types of Contributions + +We welcome: +- 🐛 Bug fixes in code examples +- 📝 Improvements to documentation +- 💡 New project ideas +- 🎓 Educational exercises +- 🌍 Translations +- 📚 Additional resources and references + +### Getting Started + +1. **Fork the Repository** + - Click the "Fork" button at the top right of this repository + - Clone your fork to your local machine + +2. **Create a Branch** + ```bash + git checkout -b feature/your-contribution-name + ``` + +3. **Make Your Changes** + - Follow the guidelines below + - Test your code on an actual micro:bit if possible + +4. **Submit a Pull Request** + - Push your changes to your fork + - Open a pull request against the main repository + - Describe your changes clearly + +## Contribution Guidelines + +### Code Examples + +All code examples should: +- ✅ Work on both micro:bit v1 and v2 (or clearly indicate version requirements) +- ✅ Include comments explaining key concepts +- ✅ Follow Python PEP 8 style guidelines where applicable +- ✅ Be tested on actual hardware +- ✅ Include both Python and MakeCode versions when possible +- ✅ Be appropriate for the target age/skill level + +### Documentation + +Documentation should: +- ✅ Be clear and concise +- ✅ Use proper grammar and spelling +- ✅ Include examples where helpful +- ✅ Be accessible to beginners +- ✅ Avoid jargon or explain technical terms +- ✅ Include visual aids (diagrams, screenshots) when helpful + +### New Projects + +When adding a new project, include: + +1. **Clear Title and Description** + - What the project does + - What students will learn + +2. **Difficulty Level** + - Beginner, Intermediate, or Advanced + - Estimated time to complete + +3. **Requirements** + - Hardware needed + - Any additional components + - Software/editor requirements + +4. **Step-by-Step Instructions** + - Clear, numbered steps + - Code examples + - Expected outcomes + +5. **Extensions/Challenges** + - Ways to expand the project + - Additional learning opportunities + +### Project Template + +```markdown +# Project Title + +Brief description of what the project does. + +## What You'll Learn +- Concept 1 +- Concept 2 +- Concept 3 + +## Hardware Required +- List all required components + +## Code + +### Python Version +\`\`\`python +from microbit import * +# Your code here +\`\`\` + +### MakeCode Version +Description of blocks needed + +## Instructions +1. Step one +2. Step two +3. Step three + +## Customization Ideas +Ways to modify the project + +## Challenges +Extensions and advanced features + +--- +**Difficulty:** ⭐⭐☆☆☆ +**Time:** XX minutes +**Age:** XX+ +``` + +### Exercises + +When creating exercises: +- State the learning objective clearly +- Provide hints, not complete solutions +- Include expected outcomes +- Offer extension challenges +- Indicate difficulty and time + +## Code Style + +### Python +- Use 4 spaces for indentation +- Follow PEP 8 naming conventions +- Add comments for complex logic +- Keep code simple and readable + +Example: +```python +from microbit import * + +# Initialize counter +count = 0 + +# Main loop +while True: + # Check button press + if button_a.was_pressed(): + count += 1 + display.scroll(str(count)) + + sleep(100) +``` + +### MakeCode +- Provide clear block descriptions +- Include screenshots when possible +- Explain each block's purpose + +## Testing + +Before submitting: +- [ ] Test code on actual micro:bit hardware +- [ ] Verify on both v1 and v2 if applicable +- [ ] Check for typos and grammar errors +- [ ] Ensure links work +- [ ] Verify code formatting +- [ ] Test on both Python and MakeCode if applicable + +## Review Process + +1. **Submission**: You submit a pull request +2. **Review**: Maintainers review your contribution +3. **Feedback**: You may receive suggestions for improvements +4. **Approval**: Once approved, your contribution is merged +5. **Recognition**: You'll be added to the contributors list + +## Reporting Issues + +Found a bug or have a suggestion? + +1. Check if the issue already exists +2. Create a new issue with: + - Clear title + - Detailed description + - Steps to reproduce (for bugs) + - Expected vs actual behavior + - Your micro:bit version + - Any error messages + +## Community Guidelines + +- Be respectful and constructive +- Focus on educational value +- Help beginners feel welcome +- Give credit where due +- Follow the Code of Conduct + +## Questions? + +If you have questions: +- Open an issue for discussion +- Check existing documentation +- Reach out to maintainers + +## License + +By contributing, you agree that your contributions will be licensed under the same license as this project (CC0 1.0 Universal). + +## Recognition + +Contributors will be acknowledged in: +- README.md contributors section +- Project documentation where applicable + +Thank you for helping make learning with micro:bit better for everyone! 🎉 diff --git a/README.md b/README.md index 05a9a4c..c291f6f 100644 --- a/README.md +++ b/README.md @@ -1 +1,100 @@ -# microbit \ No newline at end of file +# micro:bit Student Workshop + +Welcome to the micro:bit student workshop repository! This repository contains everything you need to get started with programming the BBC micro:bit, an educational device designed to teach coding and electronics. + +## 🎯 What is micro:bit? + +The BBC micro:bit is a pocket-sized computer with motion detection, a built-in compass, LED display, and Bluetooth connectivity. It's designed to make learning fun and easy for students of all ages. + +## 📚 Workshop Contents + +- **Getting Started** - Setup instructions and first steps +- **Sample Projects** - Ready-to-use example projects +- **Exercises** - Hands-on activities for learning +- **Resources** - Additional learning materials and references +- **Troubleshooting** - Common issues and solutions + +## 🚀 Quick Start + +### Requirements + +- A BBC micro:bit device (v1 or v2) +- USB cable +- Computer with internet access +- Web browser (Chrome, Firefox, or Edge recommended) + +### Your First Program + +1. Visit the [MakeCode Editor](https://makecode.microbit.org/) +2. Create a new project +3. Drag blocks to create your program +4. Click "Download" to save the .hex file +5. Connect your micro:bit via USB +6. Copy the .hex file to the MICROBIT drive + +## 📖 Workshop Structure + +### Beginner Level +- LED patterns and animations +- Button inputs +- Simple games +- Music and sounds + +### Intermediate Level +- Sensor readings (accelerometer, compass) +- Radio communication between micro:bits +- Data logging +- Advanced animations + +### Advanced Level +- Bluetooth connectivity +- Creating libraries +- Integration with other devices +- Complex projects + +## 🛠️ Programming Languages + +The micro:bit supports multiple programming languages: + +- **MakeCode (Blocks)** - Visual block-based programming (beginner-friendly) +- **MakeCode (JavaScript)** - Text-based programming +- **Python** - Using the MicroPython editor +- **C/C++** - For advanced users + +## 📁 Repository Structure + +``` +microbit/ +├── getting-started/ # Setup and introduction guides +├── projects/ # Sample projects with code +│ ├── beginner/ # Simple starter projects +│ ├── intermediate/ # More complex projects +│ └── advanced/ # Advanced projects +├── exercises/ # Workshop exercises +├── resources/ # Additional materials +└── docs/ # Documentation +``` + +## 🤝 Contributing + +Contributions are welcome! Feel free to submit pull requests with new projects, exercises, or improvements. + +## 📝 License + +This project is licensed under CC0 1.0 Universal - see the LICENSE file for details. + +## 🔗 Useful Links + +- [micro:bit Official Website](https://microbit.org/) +- [MakeCode Editor](https://makecode.microbit.org/) +- [Python Editor](https://python.microbit.org/) +- [micro:bit Documentation](https://microbit.org/get-started/) +- [Community Projects](https://microbit.org/projects/) + +## 💡 Getting Help + +- Check the troubleshooting guide in `docs/troubleshooting.md` +- Visit the [micro:bit Support](https://support.microbit.org/) +- Join the [micro:bit Community](https://community.microbit.org/) + +Happy coding! 🎉 \ No newline at end of file diff --git a/docs/hardware-setup.md b/docs/hardware-setup.md new file mode 100644 index 0000000..987d0b9 --- /dev/null +++ b/docs/hardware-setup.md @@ -0,0 +1,420 @@ +# Hardware Setup Guide + +Complete guide to setting up and understanding your micro:bit hardware. + +## micro:bit Overview + +The BBC micro:bit is a pocket-sized computer designed to teach programming and electronics. It includes: + +### Front Features +``` + [Button A] [Button B] + ┌───────────────┐ + │ ■ ■ ■ ■ ■ │ + │ ■ ■ ■ ■ ■ │ 5×5 LED Display + │ ■ ■ ■ ■ ■ │ + │ ■ ■ ■ ■ ■ │ + │ ■ ■ ■ ■ ■ │ + │ │ + │ [Logo] │ Touch-sensitive (v2 only) + │ │ + └───────────────┘ +``` + +### Back Features +- **USB Port:** For programming and power +- **Battery Connector:** JST connector for external battery +- **Reset Button:** Restart the micro:bit +- **Edge Connector:** 25 pins for external connections + +## micro:bit v1 vs v2 + +### micro:bit v2 (Latest - Recommended) +Released in 2020, includes: +- Touch-sensitive logo (acts as a third button) +- Built-in speaker and microphone +- More memory (512KB flash, 128KB RAM) +- Faster processor (64MHz Nordic nRF52833) +- Power LED indicator +- Notched edge connector + +### micro:bit v1 (Original) +Released in 2016, includes: +- 2 buttons only +- No built-in speaker/microphone +- Less memory (256KB flash, 16KB RAM) +- Slower processor (16MHz Nordic nRF51822) + +**Note:** All projects in this repository work on both versions unless specifically noted. + +## Initial Setup + +### What You Need +1. **micro:bit board** (v1 or v2) +2. **USB cable** (Micro-B to USB-A or USB-C depending on your computer) +3. **Computer** with internet access +4. **Battery pack** (optional, for portable projects) + +### First Time Setup + +#### Step 1: Unpack +- Remove micro:bit from packaging +- Keep the USB cable handy +- Note any included batteries or accessories + +#### Step 2: Connect to Computer +1. Plug the micro USB end into the micro:bit +2. Plug the other end into your computer's USB port +3. The micro:bit should light up with a pattern + +#### Step 3: Verify Connection +- Look for a drive named "MICROBIT" in your file explorer +- You should see a few files: + - `DETAILS.TXT` - Information about your micro:bit + - `MICROBIT.HTM` - Link to getting started guide + +#### Step 4: Check Version +1. Open `DETAILS.TXT` on the MICROBIT drive +2. Look for the version information: + ``` + # Interface Version: 0257 + # DAPLink: 0257 + # Git Commit: ... + # Board ID: 9904... + ``` +3. Interface version 0254+ indicates v2, earlier versions are v1 + +## Pin Connections + +### Edge Connector Pinout + +The edge connector has 25 pins arranged in two rows: + +``` +Large Pins (easy to access): +┌─────────────────────────────┐ +│ 0 1 2 3V GND │ +│ │ +│ [micro:bit body] │ +│ │ +│ 3V GND │ +└─────────────────────────────┘ + +Small Pins (require edge connector): +Additional GPIO, I2C, SPI, etc. +``` + +### Pin Functions + +| Pin | Primary Use | Alternative Functions | +|-----|-------------|----------------------| +| 0 | GPIO/ADC | Touch input, I2C SDA | +| 1 | GPIO/ADC | Touch input, I2C SCL | +| 2 | GPIO/ADC | Touch input | +| 3V | Power Out | 3.0V supply (~90mA max) | +| GND | Ground | 0V reference | +| 8 | GPIO | - | +| 12 | GPIO | - | +| 13 | GPIO/SPI | SPI SCK | +| 14 | GPIO/SPI | SPI MISO | +| 15 | GPIO/SPI | SPI MOSI | +| 16 | GPIO | - | +| 19 | GPIO/I2C | I2C SCL | +| 20 | GPIO/I2C | I2C SDA | + +### Using Pins + +#### Digital Output (LED) +```python +from microbit import * + +# Turn on LED connected to pin0 +pin0.write_digital(1) + +# Turn off LED +pin0.write_digital(0) + +# Blink LED +while True: + pin0.write_digital(1) + sleep(500) + pin0.write_digital(0) + sleep(500) +``` + +#### Analog Input (Sensor) +```python +from microbit import * + +# Read analog value (0-1023) +value = pin0.read_analog() +display.scroll(str(value)) + +# Read as percentage +percentage = value * 100 // 1023 +``` + +#### Touch Sensor (pins 0, 1, 2) +```python +from microbit import * + +while True: + if pin0.is_touched(): + display.show(Image.HAPPY) + else: + display.clear() +``` + +## Power Options + +### USB Power +- **Voltage:** 5V from USB +- **Current:** Unlimited (from computer) +- **Best for:** Programming, testing, continuous use +- **Limitations:** Requires cable connection + +### Battery Power +- **Battery Pack:** 2×AAA (3V) or 3V coin cell +- **Connector:** JST connector on back +- **Best for:** Portable projects, untethered use +- **Limitations:** Limited runtime, needs replacement + +### External Power (Advanced) +- Can power through 3V or GND pins +- **Warning:** Do not exceed 3.3V on 3V pin +- Be careful with polarity + +## Connecting External Components + +### Using Crocodile Clips +Easiest method for beginners: + +1. **LED Connection:** + - Clip positive (longer leg) to pin 0 + - Clip negative (shorter leg) to GND + - Add 100Ω resistor if available + +2. **Button/Switch:** + - One side to pin 0 + - Other side to 3V + - Use pull-down in code: `pin0.read_digital()` + +3. **Buzzer:** + - Positive to pin 0 + - Negative to GND + +### Using Edge Connector Breakout +For more permanent connections: + +1. **Get an edge connector breakout board** + - Provides easy access to all pins + - Allows breadboard connections + - Available from Kitronik, SparkFun, etc. + +2. **Connect micro:bit to breakout** + - Align carefully + - Press firmly into connector + +3. **Wire components on breadboard** + - Use jumper wires + - More stable than clips + +### Common Sensors + +#### Ultrasonic Distance Sensor (HC-SR04) +```python +from microbit import * + +trigger = pin1 +echo = pin2 + +def get_distance(): + # Send pulse + trigger.write_digital(1) + sleep(0.01) + trigger.write_digital(0) + + # Measure echo time + # Note: MicroPython on micro:bit doesn't have precise timing + # This is simplified - use dedicated library for accuracy + +get_distance() +``` + +#### Servo Motor +```python +from microbit import * + +# Connect servo signal to pin0 +# Connect servo power to 3V (if low power) or external supply +# Connect servo ground to GND + +def set_angle(angle): + # Angle 0-180 degrees + # Pulse width 1000-2000 microseconds + pulse = 1000 + (angle * 1000 // 180) + pin0.set_analog_period(20) + pin0.write_analog(pulse // 20) + +# Move to 90 degrees +set_angle(90) +``` + +#### Temperature Sensor (DS18B20) +Requires OneWire library (not built-in). + +#### PIR Motion Sensor +```python +from microbit import * + +# Connect PIR output to pin0 +# Connect VCC to 3V, GND to GND + +while True: + if pin0.read_digital() == 1: + display.show(Image.SURPRISED) + else: + display.clear() + sleep(100) +``` + +## I2C Devices + +The micro:bit has an I2C bus on pins 19 (SCL) and 20 (SDA). + +### Common I2C Devices +- OLED displays +- BME280 temperature/humidity/pressure sensor +- Accelerometers +- Real-time clocks + +### Basic I2C Communication +```python +from microbit import * + +# Scan for I2C devices +i2c.scan() # Returns list of addresses + +# Read from device +data = i2c.read(address, n) # n bytes + +# Write to device +i2c.write(address, data) +``` + +## Building a Robot + +### Basic Components +1. **micro:bit** - The brain +2. **Motor driver** - L298N or similar +3. **2× DC motors** - For wheels +4. **Chassis** - Platform with wheels +5. **Battery pack** - For motors (separate from micro:bit) +6. **Wheels** - Matched to motors + +### Wiring +``` +micro:bit pin0 → Motor Driver IN1 +micro:bit pin1 → Motor Driver IN2 +micro:bit pin8 → Motor Driver IN3 +micro:bit pin12 → Motor Driver IN4 + +Motor Driver OUT1 & OUT2 → Left Motor +Motor Driver OUT3 & OUT4 → Right Motor + +Motor Driver 12V → Battery Pack (+) +Motor Driver GND → Battery Pack (-) AND micro:bit GND +``` + +### Basic Motor Control +```python +from microbit import * + +def forward(): + pin0.write_digital(1) + pin1.write_digital(0) + pin8.write_digital(1) + pin12.write_digital(0) + +def backward(): + pin0.write_digital(0) + pin1.write_digital(1) + pin8.write_digital(0) + pin12.write_digital(1) + +def stop(): + pin0.write_digital(0) + pin1.write_digital(0) + pin8.write_digital(0) + pin12.write_digital(0) + +# Drive forward for 2 seconds +forward() +sleep(2000) +stop() +``` + +## Safety Guidelines + +### Electrical Safety +⚠️ **Important Safety Rules:** + +1. **Never exceed voltage limits** + - micro:bit operates at 3.3V logic + - USB provides 5V (safe) + - Don't connect higher voltages directly to pins + +2. **Current Limitations** + - Each pin: max 5mA (safe), 15mA (absolute max) + - Total for all pins: 90mA max + - Use transistors/MOSFETs for high-current devices + +3. **Polarity** + - Check + and - before connecting + - Reversed polarity can damage micro:bit + - Use a multimeter to verify + +4. **Heat** + - Don't short-circuit pins + - If micro:bit gets hot, disconnect immediately + - Check for wiring mistakes + +### Handling +- Hold by edges, avoid touching components +- Keep away from water and liquids +- Store in anti-static bag when not in use +- Don't flex or bend the board + +### Adult Supervision +Projects involving: +- AC power (mains electricity) +- LiPo batteries +- High-power motors +- Sharp tools + +Should only be done with adult supervision. + +## Care and Maintenance + +### Cleaning +- Use dry cloth only +- Compressed air for dust +- Don't use liquids or solvents + +### Storage +- Keep in dry place +- Room temperature +- Anti-static bag recommended +- Store away from magnets + +### Troubleshooting Hardware +See `troubleshooting.md` for common hardware issues. + +## Next Steps + +Now that your hardware is set up: +1. Try the [Getting Started Guide](../getting-started/README.md) +2. Build a [Beginner Project](../projects/beginner/README.md) +3. Complete some [Exercises](../exercises/README.md) + +Happy making! 🔧 diff --git a/docs/quick-reference.md b/docs/quick-reference.md new file mode 100644 index 0000000..cb7d5b5 --- /dev/null +++ b/docs/quick-reference.md @@ -0,0 +1,362 @@ +# micro:bit Quick Reference + +A handy cheatsheet for common micro:bit commands and patterns. + +## Display + +### Show Text +```python +# Scroll text +display.scroll("Hello") + +# Show single character +display.show("A") + +# Show number +display.show(42) +``` + +### Images +```python +# Built-in images +display.show(Image.HEART) +display.show(Image.HAPPY) +display.show(Image.SAD) +display.show(Image.ANGRY) +display.show(Image.SMILE) +display.show(Image.CONFUSED) +display.show(Image.ASLEEP) +display.show(Image.SURPRISED) +display.show(Image.SILLY) +display.show(Image.YES) +display.show(Image.NO) + +# Arrows +display.show(Image.ARROW_N) # North +display.show(Image.ARROW_NE) +display.show(Image.ARROW_E) +display.show(Image.ARROW_SE) +display.show(Image.ARROW_S) +display.show(Image.ARROW_SW) +display.show(Image.ARROW_W) +display.show(Image.ARROW_NW) +``` + +### Individual LEDs +```python +# Set pixel (x, y, brightness) +display.set_pixel(2, 2, 9) # Center LED, full brightness + +# Clear pixel +display.set_pixel(2, 2, 0) + +# Clear entire display +display.clear() +``` + +### Custom Images +```python +# Create custom 5x5 image (0-9 brightness) +boat = Image("05050:" + "05050:" + "05050:" + "99999:" + "09990") +display.show(boat) +``` + +## Buttons + +```python +# Check if button was pressed +if button_a.was_pressed(): + # Do something + +# Check if button is currently pressed +if button_a.is_pressed(): + # Do something + +# Count presses +presses = button_a.get_presses() + +# Both buttons +if button_a.is_pressed() and button_b.is_pressed(): + # Do something +``` + +## Sensors + +### Accelerometer +```python +# Get acceleration (milli-g) +x = accelerometer.get_x() # -1024 to 1024 +y = accelerometer.get_y() +z = accelerometer.get_z() + +# Check gestures +if accelerometer.was_gesture('shake'): + # Shaken! + +# Other gestures: 'up', 'down', 'left', 'right', 'face up', 'face down', 'freefall' +``` + +### Compass +```python +# Must calibrate first! +compass.calibrate() + +# Get heading (0-359 degrees, 0 = North) +heading = compass.heading() +``` + +### Temperature +```python +# Get temperature in Celsius +temp = temperature() +``` + +### Light Level +```python +# Get light level (0-255) +light = display.read_light_level() +``` + +## Pins + +### Digital +```python +# Read digital (0 or 1) +value = pin0.read_digital() + +# Write digital +pin0.write_digital(1) # On +pin0.write_digital(0) # Off +``` + +### Analog +```python +# Read analog (0-1023) +value = pin0.read_analog() + +# Write analog (PWM) +pin0.write_analog(512) # 50% brightness/speed +``` + +### Touch +```python +# Check if pin touched (pins 0, 1, 2) +if pin0.is_touched(): + # Touched! +``` + +## Timing + +```python +# Pause/sleep (milliseconds) +sleep(1000) # Wait 1 second + +# Get running time +time = running_time() # Milliseconds since start +``` + +## Radio + +```python +import radio + +# Turn on radio +radio.on() + +# Set channel (0-83) +radio.config(channel=7) + +# Set group (0-255) +radio.config(group=1) + +# Send message +radio.send("Hello") + +# Receive message +message = radio.receive() +if message: + display.scroll(message) +``` + +## Music + +```python +import music + +# Play built-in melody +music.play(music.NYAN) + +# Other melodies: DADADADUM, ENTERTAINER, PRELUDE, ODE, BIRTHDAY, FUNERAL, PUNCHLINE, PYTHON, BADDY, CHASE, BA_DING, WAWAWAWAA, JUMP_UP, JUMP_DOWN, POWER_UP, POWER_DOWN + +# Play note (frequency, duration) +music.pitch(440, 1000) # A note for 1 second + +# Play tone sequence +music.play(['C4:4', 'D4:4', 'E4:4']) + +# Stop music +music.stop() +``` + +## Random + +```python +import random + +# Random integer +num = random.randint(1, 6) # Dice roll + +# Random choice from list +choice = random.choice(['A', 'B', 'C']) +``` + +## Common Patterns + +### Infinite Loop +```python +from microbit import * + +while True: + # Your code here + sleep(100) +``` + +### Button Toggle +```python +from microbit import * + +state = False + +while True: + if button_a.was_pressed(): + state = not state # Toggle + if state: + display.show(Image.YES) + else: + display.show(Image.NO) + sleep(100) +``` + +### Counter +```python +from microbit import * + +count = 0 + +while True: + if button_a.was_pressed(): + count += 1 + display.scroll(str(count)) + if button_b.was_pressed(): + count = 0 + display.show(Image.YES) + sleep(100) +``` + +### Animation +```python +from microbit import * + +frames = [Image.HEART, Image.HEART_SMALL] +frame = 0 + +while True: + display.show(frames[frame]) + frame = (frame + 1) % len(frames) + sleep(500) +``` + +### Tilt Control +```python +from microbit import * + +while True: + x = accelerometer.get_x() + + if x > 300: + display.show(Image.ARROW_E) + elif x < -300: + display.show(Image.ARROW_W) + else: + display.show(Image.DIAMOND) + + sleep(100) +``` + +### Radio Communication +```python +from microbit import * +import radio + +radio.on() +radio.config(channel=7) + +while True: + # Send + if button_a.was_pressed(): + radio.send("Hi!") + + # Receive + msg = radio.receive() + if msg: + display.scroll(msg) + + sleep(100) +``` + +## Tips + +- Remember to `import` modules you need +- Use `sleep()` to control timing +- Store values in variables: `x = pin0.read_analog()` +- Convert numbers to strings for display: `str(42)` +- Comment your code: `# This is a comment` +- Test often - upload after small changes + +## Common Errors + +### ImportError +```python +# Wrong +from micro:bit import * + +# Right +from microbit import * +``` + +### Indentation +```python +# Wrong - no indentation +while True: +display.show(Image.HEART) + +# Right +while True: + display.show(Image.HEART) +``` + +### Missing Import +```python +# If using radio, must import +import radio +radio.on() + +# If using music, must import +import music +music.play(music.NYAN) +``` + +## Quick Links + +- **MakeCode Editor:** https://makecode.microbit.org/ +- **Python Editor:** https://python.microbit.org/ +- **Documentation:** https://microbit-micropython.readthedocs.io/ +- **Support:** https://support.microbit.org/ + +--- + +**Keep this handy while coding!** 📝 diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..d20ce4e --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,406 @@ +# Troubleshooting Guide + +Common issues and solutions when working with micro:bit. + +## Hardware Issues + +### micro:bit Not Recognized by Computer + +**Symptoms:** +- MICROBIT drive doesn't appear +- No response when connected via USB +- Computer doesn't detect device + +**Solutions:** +1. **Try a Different USB Cable** + - Some cables are power-only and don't transfer data + - Use a cable that supports data transfer + - Try the cable that came with your micro:bit + +2. **Check USB Port** + - Try a different USB port on your computer + - Front panel ports sometimes have issues; try rear ports + - Avoid USB hubs; connect directly to computer + +3. **Update Drivers (Windows)** + - Visit [micro:bit Windows driver page](https://support.microbit.org/support/solutions/articles/19000105428) + - Download and install the Windows driver + - Restart computer after installation + +4. **Check Connection** + - Ensure USB cable is firmly connected + - Look for LED indicator on micro:bit (should light up) + - Try disconnecting and reconnecting + +5. **Reset micro:bit** + - Press the reset button on the back + - Unplug and replug the USB cable + +--- + +### Program Not Running After Upload + +**Symptoms:** +- File copied successfully but nothing happens +- micro:bit shows error pattern +- Program worked before but not now + +**Solutions:** +1. **Check Error Pattern** + - If LEDs show a sad face or error code, check micro:bit error codes + - Error codes: https://support.microbit.org/support/solutions/articles/19000016969 + +2. **Verify .hex File** + - Make sure you downloaded the complete .hex file + - File size should be reasonable (typically 500KB-700KB) + - Don't rename the file after downloading + +3. **Complete Transfer** + - Wait for the LED on back to stop flashing + - Don't unplug during file transfer + - Let the micro:bit reset on its own + +4. **Check Battery** + - If using battery power, ensure batteries are fresh + - Check battery connection + - Try USB power to eliminate battery issues + +5. **Re-download Program** + - Sometimes files get corrupted + - Delete old .hex file and download fresh copy + - Try a simple test program first + +--- + +### LED Display Issues + +**Symptoms:** +- Some LEDs don't light up +- Display is dim +- Flickering display + +**Solutions:** +1. **Check Power** + - Insufficient power can cause dim LEDs + - Try USB power instead of batteries + - Replace batteries if using battery pack + +2. **Brightness Settings** + - LEDs have brightness levels 0-9 + - Check your code uses appropriate brightness + - `display.set_pixel(x, y, 9)` for maximum brightness + +3. **Physical Damage** + - Check for visible damage to LED matrix + - If LEDs are physically damaged, contact support + - Handle micro:bit carefully to avoid damage + +--- + +### Button Not Responding + +**Symptoms:** +- Button presses not detected +- Inconsistent button behavior +- Stuck button + +**Solutions:** +1. **Press Firmly** + - Buttons need firm press to activate + - Press directly on the button, not the label + - Hold for a moment if using `is_pressed()` + +2. **Use Correct Detection Method** + ```python + # For momentary detection + if button_a.was_pressed(): + + # For current state + if button_a.is_pressed(): + + # Get press count + presses = button_a.get_presses() + ``` + +3. **Debouncing** + - Add small delays to avoid double-presses + ```python + if button_a.was_pressed(): + # Do something + sleep(200) # 200ms delay + ``` + +4. **Physical Issue** + - Check if button is stuck or damaged + - Clean around button with dry cloth + - Contact support if button is broken + +--- + +## Software/Programming Issues + +### Code Doesn't Work as Expected + +**Symptoms:** +- Program runs but behaves incorrectly +- Unexpected output +- Logic errors + +**Solutions:** +1. **Debug with Display** + ```python + # Show variable values + display.scroll(str(my_variable)) + + # Show checkpoint + display.show(Image.HAPPY) # Reached this point + ``` + +2. **Check Indentation** + - Python is sensitive to indentation + - Use consistent spaces (usually 4) + - Make sure loops and if statements are properly indented + +3. **Verify Logic** + - Walk through code step by step + - Check if conditions are correct + - Test one feature at a time + +4. **Use REPL (with Mu Editor)** + - Connect with Mu Editor + - Click "REPL" button + - Test commands interactively + - See immediate results and error messages + +5. **Start Simple** + - Comment out complex parts + - Test basic functionality first + - Add features one at a time + +--- + +### Import Errors + +**Symptoms:** +- "ImportError" or "ModuleNotFoundError" +- `from microbit import *` fails + +**Solutions:** +1. **Check Editor** + - Make sure you're using micro:bit compatible editor + - MakeCode Python or Mu Editor recommended + - Online Python editor: https://python.microbit.org/ + +2. **Correct Import Statement** + ```python + # Correct + from microbit import * + + # Also correct + import microbit + import music + import radio + ``` + +3. **Editor-Specific Modules** + - Some modules only work in specific editors + - `radio` works in Python but not MakeCode blocks + - Check module compatibility + +--- + +### Out of Memory + +**Symptoms:** +- MemoryError +- Program stops unexpectedly +- Can't create more variables + +**Solutions:** +1. **Reduce Variable Usage** + - Delete variables when no longer needed + - Use shorter variable names + - Reuse variables where possible + +2. **Optimize Lists** + - Don't create huge lists + - Limit list size + ```python + # Limit list length + if len(my_list) > 100: + my_list.pop(0) # Remove oldest + ``` + +3. **Avoid String Concatenation in Loops** + ```python + # Bad (creates many strings) + text = "" + for i in range(100): + text += str(i) + + # Better + for i in range(100): + display.scroll(str(i)) + ``` + +4. **Use Generators** + - For large sequences, use generators instead of lists + - They use less memory + +--- + +### Radio Communication Problems + +**Symptoms:** +- Messages not received +- Intermittent communication +- Wrong messages received + +**Solutions:** +1. **Same Channel/Group** + ```python + # Both micro:bits must use same settings + radio.config(channel=7, group=1) + ``` + +2. **Turn On Radio** + ```python + # Must call this on both sender and receiver + radio.on() + ``` + +3. **Check Range** + - Maximum range ~70 meters in open space + - Walls and obstacles reduce range + - Keep micro:bits closer for testing + +4. **Check Receiving Code** + ```python + # Continuous checking + while True: + message = radio.receive() + if message: + display.scroll(message) + sleep(100) + ``` + +5. **Increase Power** + ```python + # Power level 0-7, 7 is maximum + radio.config(power=7) + ``` + +--- + +### Sensor Reading Issues + +**Symptoms:** +- Accelerometer gives wrong values +- Compass points wrong direction +- Temperature seems incorrect + +**Solutions:** +1. **Calibrate Compass** + ```python + # Must calibrate compass before first use + compass.calibrate() # Follow on-screen instructions + ``` + +2. **Understand Coordinate System** + - X-axis: left (-) to right (+) + - Y-axis: back (-) to front (+) + - Z-axis: down (-) to up (+) + - Values in milli-g (1g ≈ 1000) + +3. **Temperature Offset** + - micro:bit CPU generates heat + - Reading may be 2-4°C higher than ambient + - Account for this in calculations + +4. **Averaging Readings** + ```python + # Take multiple readings for accuracy + total = 0 + for i in range(10): + total += temperature() + sleep(100) + average = total // 10 + ``` + +--- + +## Common Error Codes + +### Error 020: Micro:bit ran out of memory +- See "Out of Memory" section above +- Reduce variable usage +- Optimize code + +### Error 040: Invalid .hex file +- Re-download the program +- Don't modify .hex file +- Try different browser + +### Error 050: Hardware configuration error +- Reset micro:bit +- Check for physical damage +- Try re-flashing firmware + +--- + +## Getting More Help + +If these solutions don't work: + +1. **Official Support** + - Visit: https://support.microbit.org/ + - Search knowledge base + - Submit support ticket + +2. **Community Forum** + - https://community.microbit.org/ + - Ask questions + - Search existing discussions + +3. **Stack Overflow** + - Tag: `micro-bit` + - Search existing answers + - Post new questions with code examples + +4. **Documentation** + - MicroPython: https://microbit-micropython.readthedocs.io/ + - MakeCode: https://makecode.microbit.org/reference + +--- + +## Prevention Tips + +1. **Save Work Regularly** + - Download .hex files with descriptive names + - Keep backup copies + - Use version control for larger projects + +2. **Test Incrementally** + - Don't write all code at once + - Test each feature as you add it + - Easier to identify what broke + +3. **Comment Your Code** + - Explain complex sections + - Note what works and what doesn't + - Help future you understand + +4. **Handle Errors Gracefully** + ```python + try: + # Code that might fail + result = something() + except: + display.show(Image.SAD) + ``` + +5. **Keep Firmware Updated** + - Check for firmware updates periodically + - Follow official update procedures + +Good luck, and happy debugging! 🔧 diff --git a/docs/workshop-guide.md b/docs/workshop-guide.md new file mode 100644 index 0000000..5f98537 --- /dev/null +++ b/docs/workshop-guide.md @@ -0,0 +1,381 @@ +# Workshop Instructor Guide + +A comprehensive guide for teachers and workshop leaders running micro:bit sessions. + +## Pre-Workshop Preparation + +### Equipment Checklist + +For each student (or pair): +- [ ] 1× BBC micro:bit +- [ ] 1× USB cable +- [ ] 1× Battery pack (optional but recommended) +- [ ] Access to computer with internet +- [ ] Printed reference materials (optional) + +### Classroom Setup + +1. **Computer Requirements** + - Modern web browser (Chrome, Firefox, Edge) + - Internet connection + - USB ports available + - Optional: Mu Editor installed for offline work + +2. **Room Layout** + - Students can see projector/screen + - Easy access to power outlets + - Space for physical computing activities + - Tables for hardware assembly + +3. **Technical Preparation** + - Test all micro:bits beforehand + - Verify internet connectivity + - Bookmark editor URLs + - Prepare demo code + - Test projector/screen sharing + +### Pre-Workshop Testing + +1 week before: +- [ ] Test all micro:bits +- [ ] Check all USB cables +- [ ] Verify battery packs work +- [ ] Test computers and browsers +- [ ] Prepare backup devices + +## Workshop Structure + +### Recommended Timeline (2-hour workshop) + +#### Introduction (15 minutes) +- Welcome and introductions +- What is micro:bit? +- Show demo projects +- Explain workshop goals +- Safety guidelines + +#### Getting Started (20 minutes) +- Connect micro:bit to computer +- Open online editor +- First program: "Hello World" +- Upload and test +- Troubleshoot issues + +#### Guided Projects (45 minutes) +- Demonstrate first project +- Students follow along +- Individual exploration +- Q&A and troubleshooting + +#### Break (10 minutes) + +#### Independent Work (25 minutes) +- Students choose project +- Work at own pace +- Pair programming encouraged +- Instructor circulates to help + +#### Share & Reflect (5 minutes) +- Students demonstrate projects +- Discuss what they learned +- Next steps + +## Teaching Strategies + +### Differentiation + +**For Advanced Students:** +- Provide extension challenges +- Encourage helping peers +- Introduce advanced concepts +- Suggest complex projects + +**For Struggling Students:** +- Pair with stronger peer +- Break tasks into smaller steps +- Provide more scaffolding +- Use visual aids +- Allow more time + +**For Various Ages:** +- 7-9 years: MakeCode blocks, simple projects +- 10-12 years: Mix of blocks and Python +- 13+ years: Focus on Python, advanced concepts + +### Pair Programming + +Benefits: +- Reduces equipment needs +- Encourages collaboration +- Peer learning +- Builds communication skills + +Roles: +- **Driver**: Controls keyboard/mouse, implements code +- **Navigator**: Guides, spots errors, suggests solutions +- Switch roles regularly (every 10-15 minutes) + +### Common Challenges + +#### "My micro:bit isn't working!" +1. Check USB cable connection +2. Try different USB port +3. Check MICROBIT drive appears +4. Reset micro:bit +5. Try different cable +6. Use backup micro:bit if needed + +#### "I don't understand the code!" +1. Break it down line by line +2. Use analogies and real-world examples +3. Have them explain it back to you +4. Use the simulator to visualize +5. Draw diagrams + +#### "It's too easy/hard!" +1. Adjust difficulty level +2. Provide appropriate challenges +3. Group similar-ability students +4. Have extension activities ready +5. Differentiate instruction + +## Classroom Management + +### Setting Expectations + +Clear rules: +- Handle micro:bits carefully +- Wait for instructions before uploading code +- Help neighbors when you're done +- Ask questions when stuck +- Share and be kind + +### Time Management + +- Use timer for activities +- Give 5-minute warnings +- Have backup activities if ahead +- Be flexible if students need more time +- Plan for technical difficulties + +### Safety + +Physical: +- No running with equipment +- Careful with USB ports +- Adult supervision for advanced projects +- First aid kit available + +Digital: +- Appropriate use of computers +- No accessing inappropriate content +- Protect personal information +- Follow school internet policy + +## Curriculum Integration + +### Mathematics +- Coordinates (LED positions) +- Random numbers (probability) +- Data collection and graphing +- Timing and measurement + +### Science +- Sensors (light, temperature, motion) +- Data logging +- Scientific method +- Experiments with variables + +### Art & Music +- LED animations +- Music composition +- Pattern design +- Creative expression + +### Language Arts +- Following instructions +- Technical writing +- Presenting work +- Storytelling with code + +## Assessment + +### Formative Assessment +- Observe during activities +- Ask questions about understanding +- Check progress on tasks +- Review code together +- Debugging sessions + +### Summative Assessment +- Completed projects +- Presentation of work +- Written reflections +- Code portfolio +- Challenge completion + +### Assessment Rubric Example + +| Criteria | Beginning | Developing | Proficient | Advanced | +|----------|-----------|------------|------------|----------| +| Understanding | Needs help | Some concepts | Most concepts | All concepts + extensions | +| Code Quality | Errors, doesn't run | Runs with help | Runs independently | Optimized, well-commented | +| Problem Solving | Gives up easily | Tries, needs guidance | Persists, seeks help | Independent, helps others | +| Creativity | Copies exactly | Minor changes | Personalization | Original ideas | + +## Troubleshooting Guide + +### Common Issues + +| Problem | Quick Fix | +|---------|-----------| +| Drive doesn't appear | Check cable, try different port | +| Program doesn't run | Re-download, check for errors | +| Display not working | Check code, verify LEDs working | +| Button unresponsive | Check code, test button physically | +| Slow upload | Large file, wait patiently | + +### Emergency Backup Plans + +1. **Internet Down** + - Use Mu Editor offline + - Pre-downloaded examples + - Paper-based activities + +2. **Equipment Failure** + - Backup micro:bits + - Share devices + - Pair programming + - Use simulator only + +3. **Time Running Out** + - Have quick 5-minute projects + - Focus on one key concept + - Save complex parts for next session + +## Resources for Teachers + +### Preparation Materials +- [Lesson Plans](https://microbit.org/teach/) +- [Project Examples](https://microbit.org/projects/) +- [Video Tutorials](https://youtube.com/microbit) + +### Professional Development +- Online courses (FutureLearn) +- Webinars and workshops +- Teacher communities +- Conference presentations + +### Support Networks +- [micro:bit Slack](https://tech.microbit.org/get-involved/where-to-find/) +- Teacher forums +- Local user groups +- Online communities + +## Workshop Variations + +### 1-Hour Workshop +- Focus on 1-2 simple projects +- Pre-setup computers +- Skip theory, focus on doing +- Provide take-home materials + +### Half-Day Workshop +- More project variety +- Deeper exploration +- Group projects +- Presentations + +### Week-Long Camp +- Progressive skill building +- Final showcase project +- Guest speakers +- Field trips (e.g., maker spaces) + +### After-School Club +- Weekly sessions +- Student-led projects +- Competitions +- Community service projects + +## Follow-Up Activities + +### Take-Home Resources +- Printable reference cards +- Project ideas list +- Online resources links +- Challenge cards + +### Continued Learning +- Code club meetings +- Online communities +- Competitions (micro:bit awards) +- Advanced workshops + +### Parent Involvement +- Family coding night +- Newsletter with projects +- Parent helper training +- Home project suggestions + +## Evaluation + +After the workshop: +- [ ] Student feedback survey +- [ ] Self-reflection on teaching +- [ ] Note what worked well +- [ ] Identify areas for improvement +- [ ] Update materials for next time + +### Feedback Questions + +For students: +- What did you enjoy most? +- What was challenging? +- What do you want to learn next? +- Would you recommend to friends? + +For yourself: +- Did students meet learning objectives? +- What timing worked/didn't work? +- What materials need updating? +- What questions came up frequently? + +## Quick Reference + +### Editor URLs +- MakeCode: https://makecode.microbit.org/ +- Python: https://python.microbit.org/ +- Mu Download: https://codewith.mu/ + +### Key Shortcuts +- **Download**: Ctrl/Cmd + S (in some editors) +- **Zoom**: Ctrl/Cmd + Plus/Minus +- **Undo**: Ctrl/Cmd + Z + +### Default Credentials +N/A - No login required for web editors + +## Contact & Support + +For technical issues: +- micro:bit Support: https://support.microbit.org/ +- Community Forum: https://community.microbit.org/ + +For this workshop content: +- GitHub Issues: [repository]/issues +- Email: [Add contact email] + +## Appendix + +### Sample Welcome Script + +"Welcome to micro:bit workshop! Today you'll learn to program this small computer [hold up micro:bit]. By the end, you'll create your own projects. Don't worry if you've never coded before - we'll learn together. Ready? Let's begin!" + +### Sample Closing Script + +"Fantastic work today! You've learned [concepts]. I'm impressed by [specific achievements]. Keep practicing at home, and share what you create. Remember, every programmer started as a beginner. You're all on your way to becoming great coders!" + +--- + +**Good luck with your workshop! You're inspiring the next generation of makers and coders! 🌟** diff --git a/exercises/README.md b/exercises/README.md new file mode 100644 index 0000000..43a376c --- /dev/null +++ b/exercises/README.md @@ -0,0 +1,412 @@ +# Workshop Exercises + +These hands-on exercises are designed for classroom workshops and group learning sessions. Each exercise builds skills progressively. + +## Exercise Set 1: First Steps (30 minutes) + +### Exercise 1.1: Hello LED +**Time:** 5 minutes +**Difficulty:** Beginner + +**Task:** Make a single LED light up in the center of the display. + +**Hints:** +- Use `display.set_pixel(x, y, brightness)` +- Center is at coordinates (2, 2) +- Brightness is 0-9 (0=off, 9=brightest) + +**Expected Outcome:** Middle LED glows bright. + +--- + +### Exercise 1.2: LED Pattern +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Create a cross pattern on the LED display. + +**Hints:** +- You'll need to light up 5 LEDs +- Think about which coordinates form a cross +- The cross should go through the center + +**Expected Outcome:** A cross shape appears on the display. + +--- + +### Exercise 1.3: Blinking LED +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Make the center LED blink on and off every second. + +**Hints:** +- Use `sleep()` to create delays +- Turn LED on, wait, turn LED off, wait, repeat +- Put this in a `while True:` loop + +**Expected Outcome:** Center LED blinks continuously. + +--- + +### Exercise 1.4: Animation +**Time:** 5 minutes +**Difficulty:** Beginner + +**Task:** Create an animation that shows a dot moving from left to right across the middle row. + +**Hints:** +- Use a loop to change the x coordinate +- y coordinate stays at 2 (middle row) +- Clear the display between each frame + +**Expected Outcome:** A dot moves smoothly across the screen. + +--- + +## Exercise Set 2: Interaction (45 minutes) + +### Exercise 2.1: Button Press Counter +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Count button A presses and show the count on the display. + +**Hints:** +- Create a variable to store the count +- Check if button was pressed +- Increment the count +- Display the number + +**Solution Template:** +```python +from microbit import * + +count = 0 + +while True: + if button_a.was_pressed(): + # Your code here + sleep(100) +``` + +--- + +### Exercise 2.2: Two-Button Control +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Button A increases a number, Button B decreases it. Display the current number. + +**Hints:** +- One variable for the number +- Two if statements for the buttons +- Display the number each time it changes + +**Expected Outcome:** Number goes up with A, down with B. + +--- + +### Exercise 2.3: Button Hold Detector +**Time:** 15 minutes +**Difficulty:** Intermediate + +**Task:** Detect if button A is held down for more than 2 seconds. Show different messages for short press vs long press. + +**Hints:** +- Use `button_a.is_pressed()` to check if currently pressed +- Use `running_time()` to track how long it's pressed +- Record the time when button is first pressed + +**Expected Outcome:** "Short" for quick press, "Long" for hold. + +--- + +### Exercise 2.4: Both Buttons +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Display different images for: A pressed, B pressed, both A+B pressed, neither pressed. + +**Hints:** +- Check both buttons in each iteration +- Use if/elif/else structure +- Test with `button_a.is_pressed() and button_b.is_pressed()` + +**Expected Outcome:** Four different displays based on button state. + +--- + +## Exercise Set 3: Sensors (60 minutes) + +### Exercise 3.1: Temperature Reader +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Display the current temperature when button A is pressed. + +**Hints:** +- Use `temperature()` function +- Convert to string for display +- Add "C" to show it's Celsius + +**Expected Outcome:** Shows temperature in degrees. + +--- + +### Exercise 3.2: Hot/Cold Indicator +**Time:** 15 minutes +**Difficulty:** Beginner + +**Task:** Continuously monitor temperature. Show a flame icon when hot (>25°C), snowflake when cold (<18°C), smiley face when comfortable. + +**Hints:** +- Use if/elif/else with temperature comparisons +- Built-in icons: `Image.SQUARE`, `Image.HEART`, `Image.HAPPY` +- Update display continuously + +**Expected Outcome:** Display changes with temperature. + +--- + +### Exercise 3.3: Tilt Detector +**Time:** 15 minutes +**Difficulty:** Intermediate + +**Task:** Show an arrow pointing in the direction the micro:bit is tilted. + +**Hints:** +- Read `accelerometer.get_x()` and `accelerometer.get_y()` +- Use thresholds (e.g., >300 or <-300) to detect tilt +- Use arrow images: `Image.ARROW_N`, `Image.ARROW_E`, etc. + +**Expected Outcome:** Arrow follows tilt direction. + +--- + +### Exercise 3.4: Light Meter +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Display a bar graph showing light level (0-255 as 0-5 bars). + +**Hints:** +- Use `display.read_light_level()` (0-255) +- Divide by 51 to get 0-5 range +- Display that many bars/pixels in a row + +**Expected Outcome:** Bar graph shows brightness. + +--- + +### Exercise 3.5: Shake Counter +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Count how many times the micro:bit is shaken. + +**Hints:** +- Use `accelerometer.was_gesture('shake')` +- Increment counter each shake +- Display count on button press + +**Expected Outcome:** Shake count displayed on demand. + +--- + +## Exercise Set 4: Games (90 minutes) + +### Exercise 4.1: Simple Dice +**Time:** 15 minutes +**Difficulty:** Beginner + +**Task:** Create a dice that shows a random number (1-6) when shaken. + +**Hints:** +- Import random module +- Use `random.randint(1, 6)` +- Detect shake gesture +- Display the number + +**Expected Outcome:** Random number appears on shake. + +--- + +### Exercise 4.2: Coin Flip +**Time:** 10 minutes +**Difficulty:** Beginner + +**Task:** Flip a coin (Heads/Tails) when button A is pressed. + +**Hints:** +- Random choice between 0 and 1 +- Display "H" for heads, "T" for tails +- Could also use images + +**Expected Outcome:** Random H or T on button press. + +--- + +### Exercise 4.3: Reaction Game +**Time:** 20 minutes +**Difficulty:** Intermediate + +**Task:** After a random delay, show an image. Time how fast the player presses button A. + +**Hints:** +- Random delay before signal +- Record start time with `running_time()` +- Wait for button press +- Calculate difference +- Display reaction time + +**Expected Outcome:** Shows reaction time in milliseconds. + +--- + +### Exercise 4.4: Catch the Dot +**Time:** 25 minutes +**Difficulty:** Intermediate + +**Task:** A dot moves randomly. Player tilts to move their dot. Score when they overlap. + +**Hints:** +- Two sets of coordinates (player and target) +- Read accelerometer to move player +- Check if coordinates match +- Keep score + +**Expected Outcome:** Tilt-controlled dot-catching game. + +--- + +### Exercise 4.5: Memory Game +**Time:** 20 minutes +**Difficulty:** Advanced + +**Task:** Show a sequence of LEDs. Player must repeat by pressing buttons in correct order. + +**Hints:** +- Store sequence in a list +- Display sequence one LED at a time +- Wait for button inputs +- Check if input matches sequence +- Increase difficulty each round + +**Expected Outcome:** Simon-says style memory game. + +--- + +## Exercise Set 5: Communication (60 minutes) + +### Exercise 5.1: Radio Hello +**Time:** 15 minutes +**Difficulty:** Beginner +**Required:** 2 micro:bits + +**Task:** Send "Hello" from one micro:bit to another when button A is pressed. + +**Hints:** +- Turn on radio with `radio.on()` +- Set same group/channel +- Use `radio.send()` and `radio.receive()` +- Display received messages + +**Expected Outcome:** Message appears on receiving micro:bit. + +--- + +### Exercise 5.2: Wireless Doorbell +**Time:** 15 minutes +**Difficulty:** Beginner +**Required:** 2 micro:bits + +**Task:** One micro:bit is the button, one is the bell. Press A on button to ring bell. + +**Hints:** +- Sender: button press triggers radio send +- Receiver: displays icon and plays sound on receive +- Use music.play() for sound + +**Expected Outcome:** Remote doorbell system. + +--- + +### Exercise 5.3: Chat System +**Time:** 20 minutes +**Difficulty:** Intermediate +**Required:** 2 micro:bits + +**Task:** Create a simple chat with predefined messages selectable by buttons. + +**Hints:** +- Array of messages +- Button A cycles through messages +- Button B sends current message +- Display received messages + +**Expected Outcome:** Two-way message system. + +--- + +### Exercise 5.4: Score Keeper +**Time:** 10 minutes +**Difficulty:** Intermediate +**Required:** 2 micro:bits + +**Task:** Keep track of scores for two players. Each player's micro:bit shows their score. + +**Hints:** +- Button A increments score +- Button B decrements score +- Broadcast score changes +- Display both scores + +**Expected Outcome:** Synchronized scoreboard. + +--- + +## Challenge Exercises + +### Challenge 1: Ultimate Reaction Timer +Combine multiple concepts: random delays, button timing, best score tracking, and radio to compete with a friend. + +### Challenge 2: Remote Control Car +Use one micro:bit as a controller (tilt-based) to send commands to another micro:bit connected to motors. + +### Challenge 3: Weather Dashboard +Collect temperature from multiple micro:bits and display average, min, and max. + +### Challenge 4: Treasure Hunt +Create a hot/cold indicator using radio signal strength to find a hidden micro:bit. + +## Workshop Tips for Teachers + +1. **Group Work**: Pair students for radio exercises +2. **Debugging**: Teach students to use `display.scroll()` to debug values +3. **Progression**: Ensure students complete basics before advanced exercises +4. **Time Management**: Adjust time allocations based on class pace +5. **Extensions**: Have bonus challenges for fast learners +6. **Sharing**: Have students demonstrate their solutions + +## Assessment Rubric + +### Beginner Level +- [ ] Can create basic display patterns +- [ ] Understands button inputs +- [ ] Can use loops and delays +- [ ] Creates simple animations + +### Intermediate Level +- [ ] Uses variables effectively +- [ ] Reads and responds to sensors +- [ ] Implements conditional logic +- [ ] Debugs own code + +### Advanced Level +- [ ] Combines multiple concepts +- [ ] Creates original projects +- [ ] Optimizes code +- [ ] Helps others learn + +Good luck with your workshop! 🎓 diff --git a/getting-started/README.md b/getting-started/README.md new file mode 100644 index 0000000..9329cda --- /dev/null +++ b/getting-started/README.md @@ -0,0 +1,148 @@ +# Getting Started with micro:bit + +## What You'll Need + +### Hardware +- BBC micro:bit board (v1 or v2) +- Micro USB cable +- Battery pack (optional, for portable projects) +- Computer (Windows, Mac, or Linux) + +### Software +- Web browser (Chrome, Firefox, Edge, or Safari) +- Internet connection (for online editors) + +## Setting Up Your micro:bit + +### Step 1: Unpack Your micro:bit +Your micro:bit comes with: +- The micro:bit board +- USB cable +- Battery holder (sometimes included) + +### Step 2: Connect to Computer +1. Connect the micro USB end of the cable to your micro:bit +2. Connect the other end to your computer's USB port +3. The micro:bit will power on and show a scrolling pattern + +### Step 3: Choose Your Editor + +#### Option 1: MakeCode (Recommended for Beginners) +- Visit: https://makecode.microbit.org/ +- Block-based or JavaScript programming +- No installation required +- Works in your web browser + +#### Option 2: Python Editor +- Visit: https://python.microbit.org/ +- Text-based Python programming +- Great for learning Python +- Works in your web browser + +#### Option 3: Mu Editor (Offline Python) +- Download from: https://codewith.mu/ +- Install on your computer +- Works offline +- Includes REPL for interactive coding + +## Your First Program: Hello World + +### Using MakeCode + +1. Go to https://makecode.microbit.org/ +2. Click "New Project" +3. Name your project "Hello World" +4. You'll see two blocks already there: + - `on start` - runs once when the micro:bit starts + - `forever` - runs continuously + +5. From the "Basic" menu, drag a "show string" block into the `on start` block +6. Change the text to "Hello World" +7. Click the "Download" button +8. Save the .hex file to your computer +9. Copy the .hex file to the MICROBIT drive +10. Watch your micro:bit display "Hello World"! + +### Using Python + +1. Go to https://python.microbit.org/ +2. Replace the code with: + +```python +from microbit import * + +display.scroll("Hello World") +``` + +3. Click "Download" +4. Save the .hex file +5. Copy it to your MICROBIT drive +6. Your micro:bit will display "Hello World"! + +## Understanding the micro:bit Hardware + +### LED Display +- 5×5 grid of red LEDs +- Can show letters, numbers, and patterns +- Each LED can be controlled individually + +### Buttons +- Button A (left) +- Button B (right) +- Both buttons can be pressed together + +### Sensors +- **Accelerometer** - detects movement and tilt +- **Compass** - detects magnetic north +- **Light sensor** - uses LED display to detect light +- **Temperature sensor** - measures temperature + +### Radio +- Can communicate with other micro:bits +- Range of about 70 meters + +### GPIO Pins (Edge Connector) +- 25 pins for connecting external devices +- Can be used for inputs and outputs +- Allows expansion with accessories + +## Common First Projects + +### 1. Smiley Face +Display a happy face when button A is pressed, sad face when button B is pressed. + +### 2. Name Badge +Scroll your name across the LED display continuously. + +### 3. Dice +Shake the micro:bit to roll a dice and display a random number. + +### 4. Temperature Display +Show the current temperature when button A is pressed. + +## Tips for Success + +1. **Save your work often** - Download your .hex files regularly +2. **Experiment** - Don't be afraid to try new things +3. **Read error messages** - They help you find problems +4. **Start simple** - Build complexity gradually +5. **Test frequently** - Upload to your micro:bit often to see results + +## Next Steps + +Once you're comfortable with the basics: +1. Try the beginner projects in the `projects/beginner` folder +2. Complete the exercises in the `exercises` folder +3. Explore sensors and more advanced features +4. Share your projects with others! + +## Troubleshooting + +If your micro:bit doesn't work: +1. Check the USB connection +2. Try a different USB cable +3. Make sure the .hex file copied completely +4. Press the reset button on the back +5. Check the troubleshooting guide in `docs/troubleshooting.md` + +Happy coding! 🚀 diff --git a/projects/advanced/README.md b/projects/advanced/README.md new file mode 100644 index 0000000..2f9e4b0 --- /dev/null +++ b/projects/advanced/README.md @@ -0,0 +1,648 @@ +# Advanced Projects + +These projects are for experienced micro:bit programmers and involve complex programming concepts, external components, and sophisticated algorithms. + +## Project 1: Bluetooth Heart Rate Monitor + +**What you'll learn:** Bluetooth communication, external sensors + +### Description +Create a heart rate monitor that sends data to your phone via Bluetooth. + +### Python Code +```python +from microbit import * +import radio + +# Simulated heart rate sensor (replace with actual sensor reading) +def read_heart_rate(): + # In a real project, read from analog pin connected to sensor + # Example: sensor_value = pin0.read_analog() + # Process and convert to BPM + import random + return random.randint(60, 100) + +radio.on() +radio.config(channel=7) + +while True: + if button_a.was_pressed(): + # Take reading + display.show(Image.HEART) + sleep(500) + + bpm = read_heart_rate() + + # Display and transmit + display.scroll(str(bpm) + " BPM") + radio.send(str(bpm)) + + sleep(100) +``` + +### Required Components +- Pulse sensor or heart rate sensor module +- Connecting wires +- Optional: Phone with BLE app + +## Project 2: Line Following Robot + +**What you'll learn:** External sensors, PID control, motor control + +### Description +Build a robot that follows a black line on a white surface. + +### Python Code +```python +from microbit import * + +# Threshold for line detection (adjust based on your sensors) +THRESHOLD = 500 + +def read_left_sensor(): + return pin0.read_analog() + +def read_right_sensor(): + return pin1.read_analog() + +def set_motors(left_speed, right_speed): + # PWM control for motors + # Left motor on pin8 and pin12 + # Right motor on pin13 and pin14 + if left_speed > 0: + pin8.write_analog(min(1023, left_speed)) + pin12.write_digital(0) + else: + pin8.write_digital(0) + pin12.write_analog(min(1023, -left_speed)) + + if right_speed > 0: + pin13.write_analog(min(1023, right_speed)) + pin14.write_digital(0) + else: + pin13.write_digital(0) + pin14.write_analog(min(1023, -right_speed)) + +# Main loop +while True: + left = read_left_sensor() + right = read_right_sensor() + + left_on_line = left < THRESHOLD + right_on_line = right < THRESHOLD + + if left_on_line and right_on_line: + # Both on line - go straight + set_motors(512, 512) + display.show(Image.ARROW_N) + elif left_on_line: + # Turn left + set_motors(256, 768) + display.show(Image.ARROW_W) + elif right_on_line: + # Turn right + set_motors(768, 256) + display.show(Image.ARROW_E) + else: + # Lost line - search + set_motors(0, 0) + display.show(Image.CONFUSED) + + sleep(20) +``` + +### Required Components +- 2 x IR line sensors +- Motor driver (L298N or similar) +- 2 x DC motors +- Robot chassis +- Battery pack + +## Project 3: Weather Station + +**What you'll learn:** Multiple sensors, data aggregation, long-term logging + +### Description +Comprehensive weather station with temperature, humidity, and pressure sensors. + +### Python Code +```python +from microbit import * +import radio + +# Initialize radio for data transmission +radio.on() +radio.config(channel=7, power=7) + +# Simulate external sensors (replace with actual I2C sensors) +def read_humidity(): + # Read from DHT22 or similar + return 65 # Placeholder + +def read_pressure(): + # Read from BMP280 or similar + return 1013 # Placeholder in hPa + +# Data collection interval (milliseconds) +INTERVAL = 60000 # 1 minute +last_reading = 0 + +while True: + current_time = running_time() + + # Take readings at interval + if current_time - last_reading >= INTERVAL: + temp = temperature() + humidity = read_humidity() + pressure = read_pressure() + + # Format data + data = "T:{},H:{},P:{}".format(temp, humidity, pressure) + + # Transmit + radio.send(data) + + # Display briefly + display.scroll("T:" + str(temp)) + + last_reading = current_time + + # Manual reading on button press + if button_a.was_pressed(): + display.scroll("Temp: " + str(temperature()) + "C") + display.scroll("Humidity: " + str(read_humidity()) + "%") + display.scroll("Pressure: " + str(read_pressure()) + "hPa") + + sleep(100) +``` + +### Required Components +- BME280 or BMP280 sensor (temperature, humidity, pressure) +- Connecting wires +- Optional: Second micro:bit for data logging + +## Project 4: Smart Home Controller + +**What you'll learn:** Home automation, relay control, scheduling + +### Description +Control lights, fans, and appliances with your micro:bit. + +### Python Code +```python +from microbit import * + +# Device states +devices = { + 'light': False, + 'fan': False, + 'heater': False +} + +# Pin assignments +LIGHT_PIN = pin0 +FAN_PIN = pin1 +HEATER_PIN = pin2 + +current_device = 0 +device_names = ['light', 'fan', 'heater'] +device_pins = [LIGHT_PIN, FAN_PIN, HEATER_PIN] + +def update_display(): + device = device_names[current_device] + state = "ON" if devices[device] else "OFF" + display.scroll(device[0].upper() + ":" + state) + +# Initialize all devices to off +for pin in device_pins: + pin.write_digital(0) + +while True: + # Select device with button A + if button_a.was_pressed(): + current_device = (current_device + 1) % len(device_names) + update_display() + + # Toggle device with button B + if button_b.was_pressed(): + device = device_names[current_device] + devices[device] = not devices[device] + device_pins[current_device].write_digital(1 if devices[device] else 0) + update_display() + + # Emergency off - shake to turn everything off + if accelerometer.was_gesture('shake'): + for i, pin in enumerate(device_pins): + pin.write_digital(0) + devices[device_names[i]] = False + display.show(Image.NO) + sleep(500) + display.clear() + + sleep(100) +``` + +### Required Components +- Relay module (3 or 4 channel) +- AC appliances (CAUTION: Work with adult supervision) +- Power supply for relays +- Connecting wires + +### Safety Warning +⚠️ This project involves AC power. Only build this under adult supervision and follow all electrical safety guidelines. + +## Project 5: Maze Solving Robot + +**What you'll learn:** Pathfinding algorithms, autonomous navigation + +### Description +Robot that can navigate and solve mazes using wall-following algorithm. + +### Python Code +```python +from microbit import * + +# Ultrasonic sensor reading +def get_distance(trigger_pin, echo_pin): + # Send pulse + trigger_pin.write_digital(1) + sleep(0.01) + trigger_pin.write_digital(0) + + # Measure echo + # This is simplified - actual implementation needs precise timing + duration = echo_pin.read_digital() + distance = duration * 0.034 / 2 # Convert to cm + return distance + +# Motor control +def forward(): + pin0.write_digital(1) + pin1.write_digital(0) + pin2.write_digital(1) + pin3.write_digital(0) + +def turn_right(): + pin0.write_digital(1) + pin1.write_digital(0) + pin2.write_digital(0) + pin3.write_digital(1) + +def turn_left(): + pin0.write_digital(0) + pin1.write_digital(1) + pin2.write_digital(1) + pin3.write_digital(0) + +def stop(): + pin0.write_digital(0) + pin1.write_digital(0) + pin2.write_digital(0) + pin3.write_digital(0) + +# Right-hand wall following algorithm +while True: + # Simplified - would need actual distance sensors + front_clear = True # Check with sensor + right_clear = False # Check with sensor + + if right_clear: + # No wall on right, turn right + turn_right() + sleep(500) + forward() + elif front_clear: + # Wall on right, no wall ahead, go forward + forward() + else: + # Wall ahead, turn left + turn_left() + sleep(500) + + sleep(100) +``` + +### Required Components +- Ultrasonic sensors (3x recommended) +- Motor driver +- Robot chassis with motors +- Battery pack + +## Project 6: RFID Access Control + +**What you'll learn:** RFID reading, access control logic + +### Description +Create a security system that unlocks with the right RFID card. + +### Python Code +```python +from microbit import * + +# Authorized card IDs +AUTHORIZED_CARDS = [ + "1234567890", + "0987654321" +] + +def read_rfid(): + # This would interface with an RFID reader module + # Example using UART communication + uart.init(baudrate=9600) + if uart.any(): + card_id = str(uart.read(), 'utf-8').strip() + return card_id + return None + +def unlock(): + pin0.write_digital(1) # Servo or lock mechanism + display.show(Image.YES) + sleep(3000) + pin0.write_digital(0) + display.clear() + +def deny(): + display.show(Image.NO) + sleep(1000) + display.clear() + +display.scroll("Ready") + +while True: + card_id = read_rfid() + + if card_id: + display.scroll("Card: " + card_id[:4]) + + if card_id in AUTHORIZED_CARDS: + unlock() + else: + deny() + + sleep(100) +``` + +### Required Components +- RFID RC522 module +- RFID cards/tags +- Servo motor or electronic lock +- Connecting wires + +## Project 7: GPS Tracker + +**What you'll learn:** GPS module integration, coordinate systems + +### Description +Track location and display coordinates or distance traveled. + +### Python Code +```python +from microbit import * +import math + +def parse_gps(): + # Read from GPS module via UART + uart.init(baudrate=9600) + if uart.any(): + line = str(uart.read(), 'utf-8') + # Parse NMEA sentences (simplified) + # Real implementation would parse $GPGGA or $GPRMC + return {"lat": 0.0, "lon": 0.0} + return None + +def calculate_distance(lat1, lon1, lat2, lon2): + # Haversine formula + R = 6371 # Earth's radius in km + + dlat = math.radians(lat2 - lat1) + dlon = math.radians(lon2 - lon1) + + a = (math.sin(dlat/2) * math.sin(dlat/2) + + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * + math.sin(dlon/2) * math.sin(dlon/2)) + + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) + return R * c + +# Starting position +start_pos = None +total_distance = 0 + +while True: + pos = parse_gps() + + if pos and button_a.was_pressed(): + # Set starting position + start_pos = pos + display.show(Image.TARGET) + sleep(500) + display.clear() + + if pos and start_pos and button_b.was_pressed(): + # Calculate distance from start + dist = calculate_distance( + start_pos['lat'], start_pos['lon'], + pos['lat'], pos['lon'] + ) + display.scroll(str(int(dist * 1000)) + "m") + + sleep(1000) +``` + +### Required Components +- GPS module (NEO-6M or similar) +- Antenna +- Battery for portable use + +## Project 8: Air Quality Monitor + +**What you'll learn:** Environmental sensing, data interpretation + +### Python Code +```python +from microbit import * +import radio + +# Initialize +radio.on() +radio.config(channel=7) + +def read_air_quality(): + # Read from MQ-135 or similar sensor + value = pin0.read_analog() + # Convert to air quality index (simplified) + aqi = value // 4 # 0-255 range + return aqi + +def get_quality_level(aqi): + if aqi < 50: + return "Good", Image.HAPPY + elif aqi < 100: + return "Moderate", Image.MEH + elif aqi < 150: + return "Unhealthy", Image.SAD + else: + return "Hazardous", Image.SKULL + +while True: + aqi = read_air_quality() + level, icon = get_quality_level(aqi) + + # Display on button press + if button_a.was_pressed(): + display.show(icon) + sleep(1000) + display.scroll("AQI: " + str(aqi)) + display.scroll(level) + + # Continuous monitoring mode + if button_b.was_pressed(): + for i in range(10): + aqi = read_air_quality() + level, icon = get_quality_level(aqi) + display.show(icon) + + # Alert if dangerous + if aqi > 150: + import music + music.pitch(1000, 200) + + sleep(5000) + display.clear() + + sleep(100) +``` + +### Required Components +- MQ-135 Air Quality Sensor +- Connecting wires + +## Project 9: Gesture Recognition + +**What you'll learn:** Machine learning basics, pattern recognition + +### Python Code +```python +from microbit import * + +# Simple gesture templates +GESTURES = { + 'shake': [1000, 1200, 1000, 1200], # High variation pattern + 'tilt_left': [-800, -700, -800, -700], # Consistent left tilt + 'tilt_right': [800, 700, 800, 700], # Consistent right tilt +} + +def record_gesture(): + """Record a gesture pattern""" + pattern = [] + display.show(Image.ARROW_S) + + for i in range(20): + x = accelerometer.get_x() + pattern.append(x) + sleep(50) + + return pattern + +def match_gesture(pattern): + """Simple pattern matching""" + # Calculate average and variation + avg = sum(pattern) // len(pattern) + variation = sum(abs(x - avg) for x in pattern) // len(pattern) + + if variation > 500: + return 'shake' + elif avg < -500: + return 'tilt_left' + elif avg > 500: + return 'tilt_right' + else: + return 'still' + +# Main loop +while True: + if button_a.was_pressed(): + pattern = record_gesture() + gesture = match_gesture(pattern) + display.scroll(gesture) + + sleep(100) +``` + +## Project 10: Encryption Messenger + +**What you'll learn:** Cryptography basics, secure communication + +### Python Code +```python +from microbit import * +import radio + +# Simple Caesar cipher +KEY = 3 + +def encrypt(text): + result = "" + for char in text: + if char.isalpha(): + shift = 65 if char.isupper() else 97 + result += chr((ord(char) - shift + KEY) % 26 + shift) + else: + result += char + return result + +def decrypt(text): + result = "" + for char in text: + if char.isalpha(): + shift = 65 if char.isupper() else 97 + result += chr((ord(char) - shift - KEY) % 26 + shift) + else: + result += char + return result + +radio.on() +radio.config(channel=7) + +# Predefined messages +messages = ["HELLO", "SECRET", "MEETUP"] +current_msg = 0 + +while True: + # Select message + if button_a.was_pressed(): + current_msg = (current_msg + 1) % len(messages) + display.scroll(messages[current_msg]) + + # Send encrypted + if button_b.was_pressed(): + encrypted = encrypt(messages[current_msg]) + radio.send(encrypted) + display.show(Image.YES) + sleep(500) + display.clear() + + # Receive and decrypt + received = radio.receive() + if received: + decrypted = decrypt(received) + display.scroll("Got: " + decrypted) + + sleep(100) +``` + +## Challenges + +1. **Build a complete robot** - Combine multiple advanced features +2. **Create IoT device** - Connect to internet via external module +3. **Implement AI** - Add machine learning for advanced recognition +4. **Multi-sensor fusion** - Combine data from multiple sensors + +## Competition Ideas + +- Sumo robot competition +- Fastest maze solver +- Most accurate sensor readings +- Most creative use of radio communication + +These advanced projects will push your skills to the limit. Good luck! diff --git a/projects/beginner/README.md b/projects/beginner/README.md new file mode 100644 index 0000000..4cef1d8 --- /dev/null +++ b/projects/beginner/README.md @@ -0,0 +1,286 @@ +# Beginner Projects + +These projects are perfect for getting started with micro:bit programming. Each project introduces new concepts while building on what you've learned. + +## Project 1: LED Heart Animation + +**What you'll learn:** Basic LED display, animation + +### Description +Create a beating heart animation on the LED display. + +### MakeCode Blocks +1. Create a new project +2. In the `forever` block, add: + - `show icon` (heart) + - `pause` (500ms) + - `show icon` (small heart) + - `pause` (500ms) + +### Python Code +```python +from microbit import * + +while True: + display.show(Image.HEART) + sleep(500) + display.show(Image.HEART_SMALL) + sleep(500) +``` + +## Project 2: Button Counter + +**What you'll learn:** Button inputs, variables, displaying numbers + +### Description +Count how many times button A is pressed and display the count. + +### MakeCode Blocks +1. Create a variable called `count` +2. Set `count` to 0 on start +3. On button A pressed: + - Change `count` by 1 + - Show number `count` + +### Python Code +```python +from microbit import * + +count = 0 + +while True: + if button_a.was_pressed(): + count += 1 + display.scroll(str(count)) + sleep(100) +``` + +## Project 3: Digital Dice + +**What you'll learn:** Random numbers, shake detection + +### Description +Shake the micro:bit to roll a dice and display a random number from 1 to 6. + +### MakeCode Blocks +1. On shake: + - Set variable `roll` to `pick random 1 to 6` + - Show number `roll` + +### Python Code +```python +from microbit import * +import random + +while True: + if accelerometer.was_gesture('shake'): + number = random.randint(1, 6) + display.show(str(number)) + sleep(100) +``` + +## Project 4: Name Badge + +**What you'll learn:** Text scrolling, continuous loops + +### Description +Display your name scrolling across the LED screen. + +### MakeCode Blocks +1. In `forever`: + - `show string` "Your Name" + - `pause` (100ms) + +### Python Code +```python +from microbit import * + +while True: + display.scroll("Your Name") +``` + +## Project 5: Temperature Display + +**What you'll learn:** Sensors, conditional display + +### Description +Press button A to display the current temperature in Celsius. + +### MakeCode Blocks +1. On button A pressed: + - Set variable `temp` to `temperature` + - Show number `temp` + - Show string "°C" + +### Python Code +```python +from microbit import * + +while True: + if button_a.was_pressed(): + temp = temperature() + display.scroll(str(temp) + "C") + sleep(100) +``` + +## Project 6: Nightlight + +**What you'll learn:** Light sensor, conditional logic + +### Description +Turn on all LEDs when it's dark, turn them off when it's bright. + +### MakeCode Blocks +1. In `forever`: + - If `light level < 50`: + - Show all LEDs + - Else: + - Clear screen + +### Python Code +```python +from microbit import * + +while True: + light = display.read_light_level() + if light < 50: + display.show(Image.SQUARE) + else: + display.clear() + sleep(100) +``` + +## Project 7: Compass + +**What you'll learn:** Compass sensor, directions + +### Description +Show an arrow pointing North when button A is pressed. + +### MakeCode Blocks +1. On button A pressed: + - Set variable `heading` to `compass heading` + - Show arrow pointing in direction `heading` + +### Python Code +```python +from microbit import * + +compass.calibrate() + +while True: + if button_a.was_pressed(): + heading = compass.heading() + if heading < 45 or heading > 315: + display.show(Image.ARROW_N) + elif heading < 135: + display.show(Image.ARROW_E) + elif heading < 225: + display.show(Image.ARROW_S) + else: + display.show(Image.ARROW_W) + sleep(100) +``` + +## Project 8: Step Counter + +**What you'll learn:** Accelerometer, counting steps + +### Description +Count your steps as you walk (shake detection). + +### MakeCode Blocks +1. Create variable `steps` = 0 +2. On shake: + - Change `steps` by 1 +3. On button A pressed: + - Show number `steps` + +### Python Code +```python +from microbit import * + +steps = 0 + +while True: + if accelerometer.was_gesture('shake'): + steps += 1 + if button_a.was_pressed(): + display.scroll(str(steps)) + sleep(100) +``` + +## Project 9: Rock Paper Scissors + +**What you'll learn:** Random selection, images + +### Description +Shake to randomly select rock, paper, or scissors. + +### MakeCode Blocks +1. On shake: + - Set `choice` to random 0 to 2 + - If choice = 0: show icon rock + - If choice = 1: show icon scissors + - If choice = 2: show icon paper + +### Python Code +```python +from microbit import * +import random + +ROCK = Image("00000:09990:09990:09990:00000") +PAPER = Image("99999:90009:90009:90009:99999") +SCISSORS = Image("90009:09090:00900:09090:90009") + +choices = [ROCK, PAPER, SCISSORS] + +while True: + if accelerometer.was_gesture('shake'): + choice = random.choice(choices) + display.show(choice) + sleep(100) +``` + +## Project 10: Musical Buttons + +**What you'll learn:** Sound/music output + +### Description +Play different tones when buttons are pressed. + +### MakeCode Blocks +1. On button A pressed: + - Play tone `Middle C` for `1 beat` +2. On button B pressed: + - Play tone `Middle E` for `1 beat` + +### Python Code +```python +from microbit import * +import music + +while True: + if button_a.was_pressed(): + music.pitch(262, 500) # Middle C + if button_b.was_pressed(): + music.pitch(330, 500) # Middle E + sleep(100) +``` + +## Challenge Extensions + +Once you've completed these projects, try these challenges: + +1. **Combine projects** - Make a device that does different things based on button presses +2. **Add features** - Enhance existing projects with new functionality +3. **Create patterns** - Design custom LED patterns and animations +4. **Make it interactive** - Use multiple inputs for more complex behavior + +## Tips for Building Projects + +- Start with simple versions and add features gradually +- Test each new feature before adding the next one +- Save different versions as you go +- Comment your code to remember what each part does +- Share your creations with friends and family! diff --git a/projects/beginner/heart-beat.md b/projects/beginner/heart-beat.md new file mode 100644 index 0000000..cfab526 --- /dev/null +++ b/projects/beginner/heart-beat.md @@ -0,0 +1,239 @@ +# Heart Beat Animation + +A simple animated heart that beats on your micro:bit's LED display. + +## What You'll Learn +- Creating animations +- Using the LED display +- Working with delays +- Infinite loops + +## Hardware Required +- 1× BBC micro:bit +- 1× USB cable (for programming) +- Optional: Battery pack for portable use + +## How It Works + +This program creates a beating heart animation by alternating between two heart images: +1. A large heart (fully expanded) +2. A small heart (contracted) + +The animation loops forever, creating a heartbeat effect. + +## MakeCode Version + +### Blocks +1. Go to https://makecode.microbit.org/ +2. Create a new project named "Heart Beat" +3. Delete the default blocks +4. Add a `forever` block +5. Inside the forever block, add: + - `show icon` (select large heart) + - `pause` (500 ms) + - `show icon` (select small heart) + - `pause` (500 ms) + +### JavaScript Code +```javascript +basic.forever(function () { + basic.showIcon(IconNames.Heart) + basic.pause(500) + basic.showIcon(IconNames.SmallHeart) + basic.pause(500) +}) +``` + +## Python Version + +```python +from microbit import * + +while True: + display.show(Image.HEART) + sleep(500) + display.show(Image.HEART_SMALL) + sleep(500) +``` + +## Step-by-Step Instructions + +### Using MakeCode: +1. Open https://makecode.microbit.org/ in your browser +2. Click "New Project" +3. Name it "Heart Beat" +4. Drag the blocks as described above +5. Click "Download" to save the .hex file +6. Connect your micro:bit via USB +7. Copy the .hex file to the MICROBIT drive +8. Watch your micro:bit's heart beat! + +### Using Python: +1. Open https://python.microbit.org/ in your browser +2. Delete the existing code +3. Copy and paste the Python code above +4. Click "Download" to save the .hex file +5. Connect your micro:bit via USB +6. Copy the .hex file to the MICROBIT drive +7. Watch your micro:bit's heart beat! + +## Customization Ideas + +### Change the Speed +Modify the pause/sleep duration: +- Faster beat: Use 250 ms instead of 500 ms +- Slower beat: Use 1000 ms instead of 500 ms + +```python +# Faster heartbeat +from microbit import * + +while True: + display.show(Image.HEART) + sleep(250) + display.show(Image.HEART_SMALL) + sleep(250) +``` + +### Add More Frames +Create a smoother animation with custom images: + +```python +from microbit import * + +# Define custom heart frames +frame1 = Image("09090:99999:99999:09990:00900") +frame2 = Image("00000:09090:09990:00900:00000") + +while True: + display.show(Image.HEART) + sleep(300) + display.show(frame1) + sleep(200) + display.show(Image.HEART_SMALL) + sleep(200) + display.show(frame2) + sleep(300) +``` + +### Make It Interactive +Add button control: + +```python +from microbit import * + +# Control with button A +while True: + if button_a.is_pressed(): + display.show(Image.HEART) + sleep(500) + display.show(Image.HEART_SMALL) + sleep(500) + else: + display.clear() +``` + +### Add Different Speeds +Use buttons to change speed: + +```python +from microbit import * + +speed = 500 # Default speed + +while True: + # Button A = faster + if button_a.was_pressed(): + speed = max(100, speed - 100) + display.scroll(str(speed)) + + # Button B = slower + if button_b.was_pressed(): + speed = min(1000, speed + 100) + display.scroll(str(speed)) + + # Animate heart + display.show(Image.HEART) + sleep(speed) + display.show(Image.HEART_SMALL) + sleep(speed) +``` + +## Challenges + +1. **Triple Beat**: Make the heart beat three times, then pause +2. **Color Shift**: If using external RGB LEDs, change colors with each beat +3. **Sound**: Add a "thump" sound on each beat (micro:bit v2) +4. **Pulse Detection**: Connect a real pulse sensor and match the animation to your heartbeat + +## Troubleshooting + +**Problem:** Heart doesn't animate +- **Solution:** Check that both heart images are displaying +- Verify the pause/sleep times are present + +**Problem:** Animation is too fast/slow +- **Solution:** Adjust the pause/sleep duration values + +**Problem:** micro:bit shows error +- **Solution:** Check code for typos, re-download the .hex file + +## Extension: Real Heartbeat Monitor + +For advanced students, connect a pulse sensor: + +```python +from microbit import * + +def read_pulse(): + # Read from pulse sensor on pin0 + value = pin0.read_analog() + # Detect heartbeat (simplified) + return value > 512 + +last_beat = running_time() + +while True: + if read_pulse(): + # Beat detected + current = running_time() + if current - last_beat > 300: # Debounce + display.show(Image.HEART) + sleep(100) + display.show(Image.HEART_SMALL) + last_beat = current + sleep(10) +``` + +## Learning Objectives + +After completing this project, you should understand: +- ✅ How to use the LED display +- ✅ How to create simple animations +- ✅ How to use delays/timing +- ✅ How to create infinite loops +- ✅ How to use built-in images + +## Next Steps + +Try these related projects: +- [Name Badge](../name-badge.md) - Scroll text +- [Dice](../dice.md) - Random numbers +- [Button Counter](../button-counter.md) - User input + +## Share Your Creation! + +Take a video of your beating heart and share it: +- Twitter: #microbit +- Instagram: @microbit_edu +- School coding club + +## Credits + +This is a classic beginner project adapted for the micro:bit workshop. + +--- + +**Difficulty:** ⭐☆☆☆☆ (Beginner) +**Time:** 5-10 minutes +**Age:** 7+ diff --git a/projects/beginner/name-badge.md b/projects/beginner/name-badge.md new file mode 100644 index 0000000..11557c3 --- /dev/null +++ b/projects/beginner/name-badge.md @@ -0,0 +1,206 @@ +# Name Badge + +Create a scrolling name badge that displays your name on the LED screen. + +## What You'll Learn +- Text scrolling +- Infinite loops +- Basic display functions +- Customizing text speed + +## Hardware Required +- 1× BBC micro:bit +- 1× USB cable +- Optional: Battery pack for wearing as a badge + +## How It Works + +This program continuously scrolls your name (or any message) across the LED display, perfect for wearing as a digital name badge at events! + +## Python Code + +```python +from microbit import * + +# Change this to your name! +my_name = "Your Name" + +while True: + display.scroll(my_name) +``` + +## MakeCode Blocks + +1. Go to https://makecode.microbit.org/ +2. Create a new project named "Name Badge" +3. Inside the `forever` block, add: + - `show string` "Your Name" + +## Step-by-Step Instructions + +### Using Python: +1. Open https://python.microbit.org/ +2. Replace the code with the Python code above +3. Change `"Your Name"` to your actual name +4. Click "Download" +5. Copy the .hex file to your MICROBIT drive +6. Watch your name scroll! + +## Customization Ideas + +### Add Delay Between Scrolls +```python +from microbit import * + +my_name = "Alice" + +while True: + display.scroll(my_name) + sleep(1000) # 1 second pause before repeating +``` + +### Scroll Slower +```python +from microbit import * + +while True: + display.scroll("Slow Mo", delay=200) # Default is 150 +``` + +### Multiple Lines +```python +from microbit import * + +name = "Alice" +role = "Maker" + +while True: + display.scroll(name) + display.scroll(role) + sleep(500) +``` + +### Add Icons +```python +from microbit import * + +while True: + display.show(Image.HAPPY) + sleep(500) + display.scroll("Alice") + sleep(500) +``` + +### Interactive Badge +```python +from microbit import * + +name = "Alice" +fact = "I love coding!" + +while True: + display.scroll(name) + if button_a.was_pressed(): + display.scroll(fact) + sleep(100) +``` + +### Different Messages for Each Button +```python +from microbit import * + +name = "Alice" +hobby = "Robotics" +age = "12" + +while True: + display.scroll(name) + + if button_a.was_pressed(): + display.scroll("Age: " + age) + + if button_b.was_pressed(): + display.scroll("Hobby: " + hobby) + + sleep(100) +``` + +## Challenges + +1. **Temperature Badge**: Display your name, then show temperature when button pressed +2. **Countdown Badge**: Show name and a countdown timer +3. **Multi-Language**: Show name in different languages +4. **Secret Message**: Press both buttons for a secret message + +## Physical Badge Ideas + +### Make It Wearable +- Use battery pack for power +- Attach to lanyard or clip +- Put in clear plastic case +- Wear at coding club or science fair + +### Badge Holder +Materials needed: +- Cardboard or foam board +- Clear plastic sheet +- String or lanyard +- Tape or glue + +Steps: +1. Cut cardboard to size (larger than micro:bit) +2. Cut window for LED display +3. Secure micro:bit behind window +4. Attach string/lanyard +5. Add decorations! + +## Extensions + +### Workshop Ice Breaker +Perfect for: +- First day of class +- Coding club meetings +- Science fairs +- School events + +Everyone makes their own personalized badge! + +### Badge Contest +Categories: +- Most creative message +- Best use of icons +- Coolest animation +- Funniest badge + +## Troubleshooting + +**Problem:** Name scrolls too fast +- **Solution:** Add `delay` parameter: `display.scroll("Name", delay=200)` + +**Problem:** Want name to stay visible longer +- **Solution:** Add `sleep()` after scrolling: `sleep(1000)` + +**Problem:** Text is cut off +- **Solution:** Check spelling, make sure string is complete + +## Learning Objectives + +After completing this project: +- ✅ Understand text scrolling +- ✅ Know how to use variables for text +- ✅ Can customize scrolling speed +- ✅ Understand infinite loops +- ✅ Can add user interaction + +## Next Steps + +Try these related projects: +- [Heart Beat](heart-beat.md) - Add animation +- [Button Counter](../beginner/README.md#project-2-button-counter) - Add interaction +- [Temperature Display](../beginner/README.md#project-5-temperature-display) - Add sensors + +--- + +**Difficulty:** ⭐☆☆☆☆ (Beginner) +**Time:** 5 minutes +**Age:** 7+ diff --git a/projects/beginner/smiley-button.md b/projects/beginner/smiley-button.md new file mode 100644 index 0000000..cf51932 --- /dev/null +++ b/projects/beginner/smiley-button.md @@ -0,0 +1,300 @@ +# Smiley Button + +Display a smiley face when button A is pressed, sad face when button B is pressed. + +## What You'll Learn +- Button inputs +- Conditional statements (if/else) +- Displaying icons +- User interaction + +## Hardware Required +- 1× BBC micro:bit +- 1× USB cable + +## How It Works + +This program listens for button presses and displays different faces based on which button you press. It's a simple way to learn about input and output! + +## Python Code + +```python +from microbit import * + +while True: + if button_a.is_pressed(): + display.show(Image.HAPPY) + elif button_b.is_pressed(): + display.show(Image.SAD) + else: + display.clear() + + sleep(100) +``` + +## Alternative Version (Using was_pressed) + +```python +from microbit import * + +# Start with clear display +display.clear() + +while True: + if button_a.was_pressed(): + display.show(Image.HAPPY) + + if button_b.was_pressed(): + display.show(Image.SAD) + + sleep(100) +``` + +## MakeCode Blocks + +1. Go to https://makecode.microbit.org/ +2. Add block: `on button A pressed` + - Inside: `show icon` (happy face) +3. Add block: `on button B pressed` + - Inside: `show icon` (sad face) + +## Understanding the Code + +### is_pressed() vs was_pressed() + +**is_pressed()** - True while button is held down +```python +if button_a.is_pressed(): + # Runs continuously while holding button +``` + +**was_pressed()** - True once per press +```python +if button_a.was_pressed(): + # Runs once when button is clicked +``` + +Choose based on your needs: +- Use `is_pressed()` for continuous actions +- Use `was_pressed()` for toggle/count actions + +## Customization Ideas + +### More Faces +```python +from microbit import * + +while True: + if button_a.is_pressed(): + display.show(Image.HAPPY) + elif button_b.is_pressed(): + display.show(Image.SAD) + elif button_a.is_pressed() and button_b.is_pressed(): + display.show(Image.SURPRISED) # Both buttons! + else: + display.clear() + + sleep(100) +``` + +### Emoji Selector +```python +from microbit import * + +faces = [ + Image.HAPPY, + Image.SAD, + Image.SURPRISED, + Image.SILLY, + Image.ANGRY, + Image.ASLEEP, + Image.CONFUSED +] + +current = 0 + +while True: + # Change face + if button_a.was_pressed(): + current = (current + 1) % len(faces) + display.show(faces[current]) + + # Reset to happy + if button_b.was_pressed(): + current = 0 + display.show(faces[current]) + + sleep(100) +``` + +### Mood Tracker +```python +from microbit import * + +happy_count = 0 +sad_count = 0 + +while True: + if button_a.was_pressed(): + happy_count += 1 + display.show(Image.HAPPY) + sleep(1000) + display.scroll(str(happy_count)) + + if button_b.was_pressed(): + sad_count += 1 + display.show(Image.SAD) + sleep(1000) + display.scroll(str(sad_count)) + + sleep(100) +``` + +### Animated Faces +```python +from microbit import * + +def happy_animation(): + display.show(Image.SMILE) + sleep(200) + display.show(Image.HAPPY) + sleep(200) + +def sad_animation(): + display.show(Image.CONFUSED) + sleep(200) + display.show(Image.SAD) + sleep(200) + +while True: + if button_a.is_pressed(): + happy_animation() + elif button_b.is_pressed(): + sad_animation() + else: + display.clear() + + sleep(100) +``` + +### Random Emotion +```python +from microbit import * +import random + +emotions = [ + Image.HAPPY, + Image.SAD, + Image.ANGRY, + Image.SURPRISED, + Image.SILLY, + Image.CONFUSED +] + +while True: + if button_a.was_pressed(): + emotion = random.choice(emotions) + display.show(emotion) + + if button_b.was_pressed(): + display.clear() + + sleep(100) +``` + +## Challenges + +1. **Three Buttons**: Use button A, B, and logo touch (v2) for three different faces +2. **Face Timer**: Show happy face for 5 seconds, then automatically clear +3. **Opposite Day**: Button A shows sad, Button B shows happy +4. **Gradient**: Create custom faces with different brightness levels +5. **Shake to Clear**: Shake to clear the display + +## Game Ideas + +### Emotion Mirror +Two players: +- Player 1 presses a button +- Player 2 tries to match the emotion on their micro:bit +- Take turns and have fun! + +### Quick Draw +- Program shows random face +- First person to press matching button wins +- Keep score! + +## Educational Uses + +### Mood Check-In +In classroom: +- Start of day mood check +- Students press button matching their mood +- Teacher can see general class mood + +### Communication Tool +For non-verbal communication: +- Happy = Yes +- Sad = No +- Other faces for different needs + +## Code Explanation + +Let's break down the main code: + +```python +from microbit import * # Import micro:bit library + +while True: # Loop forever + if button_a.is_pressed(): # Check if button A pressed + display.show(Image.HAPPY) # Show happy face + elif button_b.is_pressed(): # Otherwise, check button B + display.show(Image.SAD) # Show sad face + else: # If no buttons pressed + display.clear() # Clear display + + sleep(100) # Wait 0.1 seconds before checking again +``` + +## Troubleshooting + +**Problem:** Faces appear even without pressing buttons +- **Solution:** Check wiring, buttons might be stuck or shorted + +**Problem:** Need to press hard for button to work +- **Solution:** This is normal! Press firmly on the button + +**Problem:** Display doesn't clear +- **Solution:** Make sure `else: display.clear()` is included + +**Problem:** Both buttons show same face +- **Solution:** Check your if/elif logic and button names + +## Learning Objectives + +After completing this project: +- ✅ Understand button inputs +- ✅ Use conditional statements (if/elif/else) +- ✅ Display built-in images +- ✅ Create interactive programs +- ✅ Understand program flow + +## Next Steps + +Try these related projects: +- [Button Counter](../beginner/README.md#project-2-button-counter) - Count button presses +- [Rock Paper Scissors](../beginner/README.md#project-9-rock-paper-scissors) - Game with buttons +- [Name Badge](name-badge.md) - Add text to your buttons + +## Fun Facts + +😊 The human face can make over 7,000 different expressions! + +🤖 Emojis were first created in Japan in 1999. + +💡 The micro:bit can display simple emotions, just like our faces do! + +--- + +**Difficulty:** ⭐☆☆☆☆ (Beginner) +**Time:** 5-10 minutes +**Age:** 7+ diff --git a/projects/intermediate/README.md b/projects/intermediate/README.md new file mode 100644 index 0000000..7eecc30 --- /dev/null +++ b/projects/intermediate/README.md @@ -0,0 +1,484 @@ +# Intermediate Projects + +These projects build on beginner concepts and introduce more advanced features like radio communication, complex sensors, and data handling. + +## Project 1: Radio Messenger + +**What you'll learn:** Radio communication between micro:bits + +### Description +Send and receive messages between two micro:bits using radio. + +### Setup +You'll need TWO micro:bits for this project. + +### Python Code +```python +from microbit import * +import radio + +radio.on() +radio.config(channel=7) # Use same channel on both micro:bits + +while True: + # Send message when button A is pressed + if button_a.was_pressed(): + radio.send("Hello!") + display.show(Image.YES) + sleep(500) + display.clear() + + # Receive and display messages + message = radio.receive() + if message: + display.scroll(message) + + sleep(100) +``` + +### MakeCode Blocks +1. On start: + - `radio set group 1` +2. On button A pressed: + - `radio send string "Hello"` + - Show checkmark icon +3. On radio received: + - `show string receivedString` + +## Project 2: Tilt-Based Game + +**What you'll learn:** Accelerometer for precise control + +### Description +Control a dot on the screen by tilting the micro:bit. Collect randomly placed targets. + +### Python Code +```python +from microbit import * +import random + +# Player position +x, y = 2, 2 +# Target position +tx, ty = random.randint(0, 4), random.randint(0, 4) +score = 0 + +while True: + # Read tilt + tilt_x = accelerometer.get_x() + tilt_y = accelerometer.get_y() + + # Update position based on tilt + if tilt_x < -200 and x > 0: + x -= 1 + elif tilt_x > 200 and x < 4: + x += 1 + + if tilt_y < -200 and y > 0: + y -= 1 + elif tilt_y > 200 and y < 4: + y += 1 + + # Check if target reached + if x == tx and y == ty: + score += 1 + tx, ty = random.randint(0, 4), random.randint(0, 4) + display.show(Image.HAPPY) + sleep(500) + + # Display + display.clear() + display.set_pixel(x, y, 9) + display.set_pixel(tx, ty, 5) + + # Show score on button press + if button_a.was_pressed(): + display.scroll(str(score)) + + sleep(100) +``` + +## Project 3: Data Logger + +**What you'll learn:** Collecting and storing sensor data + +### Description +Log temperature readings over time and display statistics. + +### Python Code +```python +from microbit import * + +readings = [] +max_readings = 50 + +while True: + # Take reading when button A is pressed + if button_a.was_pressed(): + temp = temperature() + readings.append(temp) + if len(readings) > max_readings: + readings.pop(0) # Remove oldest + display.show(Image.YES) + sleep(200) + display.clear() + + # Show statistics when button B is pressed + if button_b.was_pressed() and readings: + avg = sum(readings) // len(readings) + display.scroll("Avg: " + str(avg)) + display.scroll("Max: " + str(max(readings))) + display.scroll("Min: " + str(min(readings))) + display.scroll("Count: " + str(len(readings))) + + sleep(100) +``` + +## Project 4: Reaction Time Tester + +**What you'll learn:** Timing, random delays, precision measurement + +### Description +Test your reaction time by pressing button A when the LED lights up. + +### Python Code +```python +from microbit import * +import random + +while True: + display.scroll("Press A when lit") + sleep(1000) + + # Random delay + delay = random.randint(1000, 5000) + sleep(delay) + + # Show signal + display.show(Image.SQUARE) + start = running_time() + + # Wait for button press (timeout after 3 seconds) + while running_time() - start < 3000: + if button_a.was_pressed(): + reaction_time = running_time() - start + display.clear() + display.scroll(str(reaction_time) + "ms") + break + sleep(10) + else: + display.scroll("Too slow!") + + display.clear() + sleep(2000) +``` + +## Project 5: Motion Alarm + +**What you'll learn:** Complex sensor logic, state management + +### Description +Create an alarm that detects motion and alerts you. + +### Python Code +```python +from microbit import * +import music + +armed = False +alarm_triggered = False + +while True: + # Arm/disarm with button A + if button_a.was_pressed(): + armed = not armed + alarm_triggered = False + if armed: + display.show(Image.SWORD) + sleep(5000) # 5 second delay to set up + display.show(Image.SKULL) + else: + display.show(Image.HAPPY) + music.stop() + + # Check for motion when armed + if armed and not alarm_triggered: + x = accelerometer.get_x() + y = accelerometer.get_y() + z = accelerometer.get_z() + + # Detect significant movement + total = abs(x) + abs(y) + abs(z) + if total > 2000: + alarm_triggered = True + + # Sound alarm + if alarm_triggered: + display.show(Image.ANGRY) + music.pitch(1000, 200) + sleep(200) + + sleep(100) +``` + +## Project 6: Radio-Controlled Robot + +**What you'll learn:** Remote control, radio communication patterns + +### Description +Use one micro:bit as a remote control for another (connected to motors/servos). + +### Controller Code +```python +from microbit import * +import radio + +radio.on() +radio.config(channel=7) + +while True: + # Read tilt + x = accelerometer.get_x() + y = accelerometer.get_y() + + # Determine command + if y < -300: + command = "FORWARD" + elif y > 300: + command = "BACKWARD" + elif x < -300: + command = "LEFT" + elif x > 300: + command = "RIGHT" + else: + command = "STOP" + + # Send command + radio.send(command) + display.show(command[0]) # Show first letter + sleep(100) +``` + +### Robot Code +```python +from microbit import * +import radio + +radio.on() +radio.config(channel=7) + +while True: + message = radio.receive() + if message: + display.scroll(message) + # Here you would control motors based on message + # For example, using pins to control motor driver + if message == "FORWARD": + pin0.write_digital(1) + pin1.write_digital(0) + elif message == "BACKWARD": + pin0.write_digital(0) + pin1.write_digital(1) + elif message == "STOP": + pin0.write_digital(0) + pin1.write_digital(0) + + sleep(100) +``` + +## Project 7: Stopwatch + +**What you'll learn:** Time tracking, display formatting + +### Description +A fully functional stopwatch with start, stop, and reset. + +### Python Code +```python +from microbit import * + +running = False +start_time = 0 +elapsed = 0 + +while True: + # Start/Stop with button A + if button_a.was_pressed(): + if running: + elapsed += running_time() - start_time + running = False + else: + start_time = running_time() + running = True + display.show(Image.YES) + sleep(200) + display.clear() + + # Reset with button B + if button_b.was_pressed(): + running = False + elapsed = 0 + display.show(Image.NO) + sleep(200) + display.clear() + + # Display current time + if running: + current = elapsed + (running_time() - start_time) + else: + current = elapsed + + seconds = current // 1000 + display.scroll(str(seconds) + "s", wait=False, loop=True) + + sleep(100) +``` + +## Project 8: Pedometer + +**What you'll learn:** Advanced accelerometer processing + +### Description +Track steps with improved accuracy using step detection algorithm. + +### Python Code +```python +from microbit import * + +steps = 0 +last_total = 0 +threshold = 1200 +cooldown = 0 + +while True: + # Read acceleration + x = accelerometer.get_x() + y = accelerometer.get_y() + z = accelerometer.get_z() + total = abs(x) + abs(y) + abs(z) + + # Detect step (spike in movement) + if cooldown == 0: + if total > threshold and last_total < threshold: + steps += 1 + cooldown = 5 # Prevent double-counting + display.show(Image.HAPPY) + sleep(100) + display.clear() + else: + cooldown -= 1 + + last_total = total + + # Show steps on button press + if button_a.was_pressed(): + display.scroll("Steps: " + str(steps)) + + # Reset on button B + if button_b.was_pressed(): + steps = 0 + display.show(Image.YES) + sleep(500) + display.clear() + + sleep(100) +``` + +## Project 9: Spirit Level + +**What you'll learn:** Precise tilt measurement, visual feedback + +### Description +Create a digital spirit level showing which way to tilt. + +### Python Code +```python +from microbit import * + +while True: + x = accelerometer.get_x() + y = accelerometer.get_y() + + # Create display pattern + image = Image("00000:00000:00000:00000:00000") + + # Calculate LED position (2,2 is center) + led_x = 2 + led_y = 2 + + if x > 200: + led_x = 3 + elif x > 400: + led_x = 4 + elif x < -200: + led_x = 1 + elif x < -400: + led_x = 0 + + if y > 200: + led_y = 3 + elif y > 400: + led_y = 4 + elif y < -200: + led_y = 1 + elif y < -400: + led_y = 0 + + # Clear and set pixel + display.clear() + display.set_pixel(led_x, led_y, 9) + + # Show level indicator when centered + if led_x == 2 and led_y == 2: + display.show(Image.DIAMOND) + + sleep(50) +``` + +## Project 10: Music Player + +**What you'll learn:** Music sequences, melody creation + +### Description +Create a music player with multiple songs selectable by buttons. + +### Python Code +```python +from microbit import * +import music + +songs = [ + ["C4:4", "D4:4", "E4:4", "F4:4", "G4:4"], # Scale + ["E4:2", "E4:2", "F4:2", "G4:2", "G4:2", "F4:2"], # Ode to Joy + ["C4:1", "D4:1", "E4:1", "C4:1", "C4:1", "D4:1", "E4:1", "C4:1"] # Frere Jacques +] + +current_song = 0 + +display.scroll("Music Player") + +while True: + # Select song + if button_a.was_pressed(): + current_song = (current_song + 1) % len(songs) + display.scroll(str(current_song + 1)) + + # Play song + if button_b.was_pressed(): + display.show(Image.MUSIC_QUAVER) + music.play(songs[current_song]) + display.clear() + + sleep(100) +``` + +## Challenges + +1. **Combine radio and sensors** - Create a weather station that transmits data +2. **Multi-player games** - Build games for 2+ micro:bits +3. **Complex state machines** - Create devices with multiple modes +4. **Data visualization** - Display sensor data graphically on the LEDs + +## Next Steps + +Ready for more? Check out the advanced projects folder for even more challenging builds! diff --git a/resources/README.md b/resources/README.md new file mode 100644 index 0000000..9946e3a --- /dev/null +++ b/resources/README.md @@ -0,0 +1,356 @@ +# Resources and References + +A curated collection of useful resources for learning and teaching with micro:bit. + +## Official Resources + +### Documentation +- [micro:bit Website](https://microbit.org/) - Official homepage +- [micro:bit Technical Documentation](https://tech.microbit.org/) - Hardware specifications +- [MicroPython Documentation](https://microbit-micropython.readthedocs.io/) - Python API reference +- [MakeCode Documentation](https://makecode.microbit.org/reference) - Block and JavaScript reference + +### Editors and Tools +- [MakeCode Editor](https://makecode.microbit.org/) - Block and JavaScript programming (online) +- [Python Editor](https://python.microbit.org/) - Browser-based Python editor +- [Mu Editor](https://codewith.mu/) - Desktop Python editor (offline) +- [micro:bit Educational Foundation](https://microbit.org/teach/) - Teaching resources + +### Support +- [Support Portal](https://support.microbit.org/) - Official help and troubleshooting +- [Community Forum](https://community.microbit.org/) - Discussion forum +- [YouTube Channel](https://www.youtube.com/microbit) - Video tutorials + +--- + +## Learning Platforms + +### Interactive Tutorials +- [micro:bit Classroom](https://classroom.microbit.org/) - Curriculum-aligned lessons +- [Code Club micro:bit Projects](https://projects.raspberrypi.org/en/codeclub/microbit) - Structured projects +- [CS First micro:bit](https://csfirst.withgoogle.com/) - Google's computer science curriculum + +### Online Courses +- [FutureLearn micro:bit Courses](https://www.futurelearn.com/courses/microbit) - Free online courses +- [micro:bit on Khan Academy](https://www.khanacademy.org/) - Programming fundamentals +- [Code.org micro:bit Activities](https://code.org/) - Hour of Code activities + +### Video Tutorials +- [The Coding Train - micro:bit](https://thecodingtrain.com/) - Creative coding tutorials +- [Adafruit micro:bit Tutorials](https://learn.adafruit.com/category/micro-bit) - Hardware integration +- [SparkFun micro:bit Guides](https://learn.sparkfun.com/tutorials/tags/microbit) - Project tutorials + +--- + +## Books and Publications + +### Beginner Books +- "Getting Started with micro:bit" by Wolfram Donat +- "Learn to Program with micro:bit" by The Micro:bit Foundation +- "micro:bit in Wonderland" by The Micro:bit Foundation + +### Advanced Books +- "Programming the BBC micro:bit" by Simon Monk +- "micro:bit IoT in C" by Parmeet Singh +- "Artificial Intelligence with micro:bit" by Radhika Ghosal + +### Free E-books +- [micro:bit MicroPython Guide](https://microbit-micropython.readthedocs.io/) - Official guide +- [micro:bit User Guide](https://microbit.org/get-started/user-guide/) - Getting started + +--- + +## Project Ideas + +### Project Galleries +- [micro:bit Projects](https://microbit.org/projects/) - Official project gallery +- [Hackster.io micro:bit](https://www.hackster.io/microbit) - Community projects +- [Instructables micro:bit](https://www.instructables.com/circuits/microbit/) - DIY projects with instructions + +### Inspiration +- [micro:bit Awards](https://microbit.org/do-your-bit/) - Award-winning projects +- [micro:bit Blog](https://microbit.org/news/) - Latest projects and news +- [Twitter #microbit](https://twitter.com/hashtag/microbit) - Community sharing + +--- + +## Hardware and Accessories + +### Official Accessories +- [micro:bit Go Bundle](https://microbit.org/buy/) - Starter kit +- [micro:bit Club Pack](https://microbit.org/buy/) - Classroom set +- Battery holders and USB cables + +### Third-Party Add-ons +- **Kitronik** - Wide range of accessories and kits +- **SparkFun** - Electronics and breakout boards +- **Adafruit** - Sensors and components +- **Elecfreaks** - Robot kits and expansion boards +- **MonkMakes** - Educational electronics kits + +### Recommended Accessories +- **Sensors:** + - Ultrasonic distance sensor + - PIR motion sensor + - Soil moisture sensor + - Sound sensor + - Gas/air quality sensor + +- **Outputs:** + - Servo motors + - DC motors with driver + - RGB LED strips (NeoPixels) + - OLED displays + - Buzzers and speakers + +- **Power:** + - Battery packs (2xAAA or 3.7V LiPo) + - USB power banks + - Solar panels + +- **Robotics:** + - Robot chassis + - Wheels and motors + - Motor drivers (L298N) + - Ultrasonic sensors + +--- + +## Programming References + +### Python (MicroPython) + +#### Essential Modules +```python +from microbit import * # Core functionality +import radio # Radio communication +import music # Sound and music +import speech # Text-to-speech +import random # Random numbers +import math # Mathematical functions +``` + +#### Quick Reference +```python +# Display +display.show("A") +display.scroll("Hello") +display.set_pixel(x, y, brightness) +display.clear() + +# Buttons +button_a.was_pressed() +button_a.is_pressed() +button_a.get_presses() + +# Sensors +temperature() +accelerometer.get_x() +accelerometer.get_y() +accelerometer.get_z() +compass.heading() + +# Pins +pin0.read_analog() # 0-1023 +pin0.write_analog(512) +pin0.read_digital() # 0 or 1 +pin0.write_digital(1) + +# Radio +radio.on() +radio.send("message") +radio.receive() + +# Music +music.play(music.NYAN) +music.pitch(440, 1000) +``` + +### JavaScript (MakeCode) + +#### Common Blocks +- **Basic:** show string, show number, show icon +- **Input:** on button pressed, on shake +- **Loops:** forever, repeat, while +- **Logic:** if/then/else, and/or +- **Variables:** set, change +- **Math:** arithmetic, random +- **Radio:** send, receive + +--- + +## Classroom Resources + +### Lesson Plans +- [micro:bit Curriculum](https://microbit.org/teach/) - Complete curriculum +- [CS Unplugged](https://csunplugged.org/) - Computer science without computers +- [Barefoot Computing](https://www.barefootcomputing.org/) - Primary computing + +### Assessment Tools +- [Computing at School Resources](https://www.computingatschool.org.uk/) +- [Digital Schoolhouse Worksheets](https://www.digitalschoolhouse.org.uk/) +- micro:bit Skills Builder Framework + +### Workshop Materials +- [micro:bit Workshop Cards](https://microbit.org/teach/classroom-resources/) +- Printable reference sheets +- Student workbooks + +--- + +## Community and Events + +### Competitions +- [micro:bit Awards](https://microbit.org/do-your-bit/) - Annual competition +- [First Lego League](https://www.firstlegoleague.org/) - Robotics competition +- Local hackathons and coding clubs + +### User Groups +- [micro:bit Educational Foundation](https://microbit.org/get-involved/) +- Local Code Clubs and CoderDojos +- School coding clubs + +### Social Media +- Twitter: [@microbit_edu](https://twitter.com/microbit_edu) +- Facebook: micro:bit Educational Foundation +- Instagram: @microbit_edu +- YouTube: micro:bit + +--- + +## Development Tools + +### Advanced Programming +- [C/C++ with CODAL](https://tech.microbit.org/software/runtime/) - Low-level programming +- [Rust for micro:bit](https://github.com/nrf-rs/microbit) - Systems programming +- [Ada for micro:bit](https://github.com/AdaCore/Ada_Drivers_Library) - Safety-critical applications + +### Simulators +- [MakeCode Simulator](https://makecode.microbit.org/) - Built-in simulator +- [Python Simulator](https://python.microbit.org/) - Test code in browser + +### Version Control +- GitHub repositories for sharing code +- Git for tracking project changes + +--- + +## Accessibility + +### Inclusive Resources +- [micro:bit Accessibility](https://microbit.org/teach/send/) - SEND resources +- Text-to-speech functionality +- Large print resources +- Audio descriptions for projects + +### Assistive Technologies +- Screen reader compatible editors +- Voice control options +- Alternative input methods + +--- + +## Research and Academic Papers + +### Educational Research +- "The Effect of micro:bit on Student Learning" - Various studies +- "Physical Computing in Primary Education" - Research papers +- "Gender Differences in STEM with micro:bit" - Academic research + +### Conference Papers +- SIGCSE - Computer Science Education +- EDUCON - Engineering Education +- ICER - International Computing Education Research + +--- + +## Additional Languages and Localizations + +### Translations +- MakeCode available in 40+ languages +- Python editor supports multiple languages +- Community translations of resources + +### Regional Resources +- UK: Computing At School +- USA: Code.org, CS Teachers Association +- Europe: SciFest, CodeWeek +- Asia: Tech Kids, Coding Lab +- Australia: CSER Digital Technologies + +--- + +## Safety and Ethics + +### Online Safety +- [Internet Safety Guidelines](https://www.saferinternet.org.uk/) +- Digital citizenship resources +- Privacy considerations with IoT + +### Responsible Computing +- Environmental impact of electronics +- E-waste and recycling +- Ethical AI and data collection + +--- + +## Troubleshooting Resources + +### Common Issues +- See `troubleshooting.md` in this repository +- [Official Support Articles](https://support.microbit.org/) +- Community-contributed solutions + +### Firmware Updates +- [Updating micro:bit Firmware](https://microbit.org/get-started/user-guide/firmware/) +- [Latest Firmware Versions](https://tech.microbit.org/software/daplink-interface/) + +--- + +## Contributing to micro:bit + +### Open Source +- [MicroPython GitHub](https://github.com/bbcmicrobit/micropython) +- [MakeCode GitHub](https://github.com/microsoft/pxt-microbit) +- [DAL Runtime GitHub](https://github.com/lancaster-university/microbit-dal) + +### Getting Involved +- Report bugs and issues +- Contribute code improvements +- Create and share projects +- Help in community forums +- Translate resources + +--- + +## Stay Updated + +### Newsletters +- micro:bit Educational Foundation newsletter +- MakeCode newsletter +- Community updates + +### Blogs +- [micro:bit News](https://microbit.org/news/) +- [Microsoft MakeCode Blog](https://makecode.com/blog) +- Community member blogs + +--- + +## Quick Links Summary + +| Resource | URL | +|----------|-----| +| Main Website | https://microbit.org/ | +| MakeCode Editor | https://makecode.microbit.org/ | +| Python Editor | https://python.microbit.org/ | +| Support | https://support.microbit.org/ | +| Community | https://community.microbit.org/ | +| Teaching Resources | https://microbit.org/teach/ | +| Projects | https://microbit.org/projects/ | + +--- + +**Last Updated:** November 2025 + +For the most current resources, always check the official micro:bit website and community forums.