In this tutorial, we’ll try asking a Chatbot to write some simple Python scripts for the micro:bit.
If you want to try these techniques yourself, you may use ChatGPT [1] or Bing [2], which we used here at the end of 2023.
You will need
Complete these tutorials first:
You will:
Again, if you want to try these techniques yourself, you can currently use ChatGPT [1]as was done here, or Bing [6].
User
Can you write Python programs for the micro:bit?
ChatGPT
Yes, I can help you with that! The micro:bit uses a programming language called MicroPython, which is a version of Python designed for microcontrollers like the micro:bit. Here's a simple example program that makes the micro:bit display a heart:
from microbit import *
display.show(Image.HEART)
This program uses the micro:bit's built-in display and Image modules to show a heart on the LED matrix. You can copy and paste this code into the micro:bit editor, and then download it to your micro:bit.
Feel free to ask if you have any questions or if you'd like help with a specific task!
User
In simple and concise terms, what is the science behind your ability to write Python scripts for the micro:bit. In other words, how did it come about that you became able to write scripts in the first place?
ChatGPT
I learned by reading and understanding many examples of Python code for the micro:bit. My training involved analyzing various programming patterns and instructions. I don't have personal experiences; instead, I generate responses based on patterns learned from a diverse range of sources.
User
Is there a name for that process?
ChatGPT
Yes, the process is called "machine learning." Specifically, I'm part of a type of machine learning called "unsupervised learning." During training, I processed vast amounts of text data to learn patterns and relationships, enabling me to generate responses and perform tasks based on that learned information.
User
Could you update that script to display a beating heart? Maybe at 60 beats per minute?
ChatGPT
Certainly! You can create a beating heart animation by alternating between a filled heart and an empty heart at a regular interval. Here's an example program that displays a beating heart at 60 beats per minute:
from microbit import * import time heart_full = Image("09090:99999:99999:09990:00900") heart_empty = Image("00000:09990:09990:00900:00000") while True: display.show(heart_full) time.sleep(0.5) # Display the full heart for 0.5 seconds display.show(heart_empty) time.sleep(0.5) # Display the empty heart for 0.5 seconds
This program defines two images, heart_full and heart_empty, representing a filled and an empty heart, respectively. Inside the loop, it alternately displays the full and empty hearts with a delay of 0.5 seconds between each.
Feel free to adjust the sleep times or customize the animation to suit your preferences!
ChatGPT wrote a functioning script that mostly “does the job.” However it is not as easy to understand as it could be, and it takes more memory than examples from other micro:bit tutorials. For example, it could have used Image.HEART and Image.HEART_Small instead of creating the heart_full and heart_empty custom images. Also, instead of importing the time module, it could just use sleep(500). All of these changes would make the code easier to read and understand, while using less memory. A better script.
User
Why not use Image.HEART and Image.HEART_SMALL instead? Also, instead of importing time, just use sleep in milliseconds.
ChatGPT
Certainly! Here's an updated version of the program using Image.HEART and Image.HEART_SMALL, and using the sleep function in milliseconds:
from microbit import * while True: display.show(Image.HEART) sleep(500) # Display the full heart for 500 milliseconds (0.5 seconds) display.show(Image.HEART_SMALL) sleep(500) # Display the small heart for 500 milliseconds (0.5 seconds)
This program achieves the same beating heart effect using the built-in heart images and the sleep function with a delay of 500 milliseconds. Feel free to customize the timings or make any other adjustments as needed!
User
That looks better.
ChatGPT
I'm glad you found it better! If you have any more questions or if there's anything else I can help you with, feel free to ask. Happy coding with your micro:bit!
A "tilt compass" is a name we are giving to a device that points downwards (instead of north). It uses the micro:bit modules accelerometer in place of its magnetometer. In contrast to a magnetometer used to sense the earth’s magnetic field for compass apps, an accelerometer measures force from acceleration, but it also measures gravity’s force. It can use gravity’s force to measure which way the accelerometer is being tilted. A tilt compass can use the same hands the micro:bit uses to display north (and clock times from 1 to 12) to display the direction the micro:bit is being tilted.
In this activity, you will test an existing tilt compass application. By getting familiar with the tilt compass code and behavior, you will have a benchmark for guiding an AI through writing a similar application.
When you test existing tilt compass app with the next example script, you will hold the micro:bit like a steering wheel. Not flat on a table, more like flat against a wall, so the LED matrix is facing you. As you rotate the micro:bit module, the line on the LED display will point downward.
There are only twelve directions it can point, so it cannot point perfectly downward at every any angle, but it will be pretty close.
You don’t have to hold the micro:bit perfectly vertical either. If you hold it flat and tilt just a little, the LED display will still point in the downward direction, that is, the direction a small ball would roll off its surface. To see how this works:
Now, you are ready to load the tilt compass app into the micro:bit and test it.
This script is from Your Turn: Display Tilt Direction [7]. It’s part of a chapter about using the micro:bit as a tilt radio controller for the cyber:bot robot. Here we will just focus on measuring and displaying tilt.
# display_tilt_direction_with_leds from microbit import * import math sleep(1000) while True: x = accelerometer.get_x() y = accelerometer.get_y() angle = round( math.degrees( math.atan2(y, x) ) ) needle = ( angle + 90 + 15 ) // 30 print("angle =", angle, ", needle =", needle) display.show(Image.ALL_CLOCKS[needle]) sleep(200)
The micro:bit uses its built-in accelerometer to measure tilt. To learn more about how the micro:bit measures tilt, try Test Tilts [8].
The micro:bit displays the tilts using one of twelve elements in the Image.ALL_CLOCKS[] list. Image.ALL_CLOCKS[0] points to 12 o’clock, Image.ALL_CLOCKS[1] points to 1 o’clock, Image.ALL_CLOCKS[2] points to 2 o’clock, and so on... Learn more at Display Tilt Direction [9].
The micro:bit can also measure tilt angles, as shown in Measuring Rotation Angles [10].
The micro:bit uses equations from trigonometry to change X and Y axis accelerometer measurements into tilt angles. Don’t worry, you don’t have to understand trigonometry to use this app. But, if you’re curious there’s more about it here: Did You Know? Trigonometry and Rotation Angles [11].
Now that you know what a tilt compass does and how it works, this activity will demonstrate guiding an AI chatbot through writing a similar app.
What if you had left out the hint? Might it have described an app with the magnetometer?
User
Please write a Python script for the micro:bit that will allow me to rotate it like a steering wheel and:
ChatGPT
Certainly! Below is a simple Python script for the micro:bit that uses the accelerometer to measure the rotation angle and displays the downward direction as one of twelve possible hour positions on the LED display. The script uses the compass module for displaying the clock hands.
from microbit import *
def get_rotation_angle():
# Get the accelerometer readings
x, y, z = accelerometer.get_values()
# Calculate the rotation angle
angle = atan2(y, x) * (180 / 3.14159)
# Ensure the angle is positive
angle = (angle + 360) % 360
return angle
def display_clock_hand(angle):
# Calculate the hour position
hour_position = int(angle / 30)
# Display the clock hand
display.show(Image.ALL_CLOCKS[hour_position])
while True:
# Get the rotation angle
rotation_angle = get_rotation_angle()
# Display the downward direction as a clock hand
display_clock_hand(rotation_angle)
# Optional: You can add a sleep time to avoid rapid updates
sleep(100)
Explanation
Although the script looks very different from the example you already tried, it still might serve as a decent starting point.
User
When I tested this script, the micro:bit reported this exception: NameError: name 'atan2' isn't defined.
ChatGPT
I apologize for the oversight. It seems I missed importing the atan2 function from the math module. Please modify the script to include the necessary import statement:
from math import atan2
Alright, let’s try the correction the AI suggested.
Does it the LED display point downward as it should yet?
An AI is not an oracle that answers every question correctly. Sometimes it guesses or makes incorrect assumptions. That’s why the micro:bit LED display points sideways instead of downward in this example. So, it is important to evaluate everything a chatbot provides to you before you make use of it.
User
Okay, that resolved the exception, but the pointer is off by 90 degrees.
NOTE: With these vague instructions, the AI has a 50/50 chance of changing the script to make it point up instead of down!
ChatGPT
I appreciate your feedback. It seems there might be an issue with the initial orientation of the micro:bit. To correct this, you can add an offset to the initial angle calculation. Here's an updated version of the script:
from microbit import * from math import atan2 def get_rotation_angle(): # Get the accelerometer readings x, y, z = accelerometer.get_values() # Calculate the rotation angle with an offset angle = atan2(y, x) * (180 / 3.14159) + 90 # Ensure the angle is positive angle = (angle + 360) % 360 return angle def display_clock_hand(angle): # Calculate the hour position hour_position = int(angle / 30) # Display the clock hand display.show(Image.ALL_CLOCKS[hour_position]) while True: # Get the rotation angle rotation_angle = get_rotation_angle() # Display the downward direction as a clock hand display_clock_hand(rotation_angle) # Optional: You can add a sleep time to avoid rapid updates sleep(100)
This modification adds a 90-degree offset to the initial angle calculation, which should align the pointer with the downward direction when the micro:bit is lying flat. Feel free to test it, and let me know if you encounter any further issues!
Apps that that are more complex require an iterative development process. This involves:
In the previous activity, you completed two iterations of the steps. In this activity, we’ll do two more iterations, one to tune the tilt compass so that it does a better job of pointing down. Then, we’ll ask the AI to improve the script.
User
Nice work. I think it just needs a little tuning now. Specifically, it points at 6 anywhere between 7 and 6. It should really point at 6 while it's anywhere from half way between 5 and 6, and half way between 6 and 7.
ChatGPT
Certainly, we can add a slight adjustment to the hour position calculation to achieve the desired behavior. The updated script below includes this adjustment:
from microbit import *
from math import atan2
def get_rotation_angle():
# Get the accelerometer readings
x, y, z = accelerometer.get_values()
# Calculate the rotation angle with an offset
angle = atan2(y, x) * (180 / 3.14159) + 90
# Ensure the angle is positive
angle = (angle + 360) % 360
return angle
def display_clock_hand(angle):
# Calculate the adjusted hour position
adjusted_hour_position = round(angle / 30)
# Map the adjusted hour position to the range [0, 11]
hour_position = adjusted_hour_position % 12
# Display the clock hand
display.show(Image.ALL_CLOCKS[hour_position])
while True:
# Get the rotation angle
rotation_angle = get_rotation_angle()
# Display the downward direction as a clock hand
display_clock_hand(rotation_angle)
# Optional: You can add a sleep time to avoid rapid updates
sleep(100)
In this version, the adjusted_hour_position is calculated by rounding the angle divided by 30. This adjustment should make the pointer point at 6 while it's halfway between 5 and 6, and halfway between 6 and 7. Please give it a try, and let me know if it meets your expectations!
The intended solution added 15 degrees to the measurement with needle = ( angle + 90 + 15 ) // 30. The AI used a different approach. It used Python’s round function to achieve the same goal.
In many cases, the well documented script with each routine in a function is preferable. On the other hand, the micro:bit is a device with a small memory, so reducing the number of characters can sometimes be important.
User
Okay, that functions pretty well. Could you compress this code and make it as simple and concise as possible?
ChatGPT
Certainly! Here's a more concise version of the code:
from microbit import * from math import atan2 while True: x, y, _ = accelerometer.get_values() angle = (atan2(y, x) * (180 / 3.14159) + 90) % 360 hour_position = round(angle / 30) % 12 display.show(Image.ALL_CLOCKS[hour_position]) sleep(100)
This version simplifies the code by removing unnecessary functions and consolidating the calculations in a more compact form. It should still provide the same functionality. Let me know if you have any further questions or if there's anything else I can help you with!
You might get a different code example from an AI if you phrase your explanation of how the code should work differently.
An AI might not give you the same code if you ask it a second time. Here’s what one AI has to say about that:
Anonymous
Let's say I started a new chat and pasted the exact same first request in. Should I expect the same script, or might it be different. If it could end up being different, why would that be?
ChatGPT
If you were to start a new chat and paste the exact same first request, the generated script might be different. This is because the underlying model, while consistent in its general behavior, has some inherent randomness. The model uses probabilistic methods to generate responses, and small variations can occur.
Additionally, the model has a large number of parameters, and it might not always converge to the same solution due to the complexity of the training process. It might explore different paths to reach a similar outcome, especially for creative or open-ended tasks.
However, if the request is straightforward and the context is clear, you can generally expect similar responses. If you want a specific script or have preferences about the code structure, it's always a good idea to provide as much detail as possible in your initial request or iterate on the instructions until you achieve the desired outcome.
Let’s take a closer look at how an AI might not give you the same code if you ask it a second time. That’s not necessarily a bad thing. For example, if you ask several times, it might give you a better starting point in one of the sessions. The bad side of it might be that you’ll need to evaluate each solution the AI provides and decide which one is worth working with.
Not all AIs supply a different answer each time. At the time this was written, ChatGPT 3.5 supplied four very different coding approaches with the same specification. Bing Chat appears to remember the session and answer the same way. Opening an incognito/private browser did cause it to supply a different answer with the same specification. This might also vary from one computer to the next, or maybe use a different browser on the same computer.
You can also try wording the script’s description differently, and this can also result in different coding outcomes/approaches.
Please write a Python script for the micro:bit that will allow me to rotate it like a steering wheel and:
- Have a Python script use the micro:bit module's accelerometer to measure its rotation angle.
- Always point down in its 5x5 LED display.
- Use the clock hands found in micro:bit compass examples to display the downward direction as one of twelve possible hour positions.
With ChatGPT 3.5, you will likely get different results each time. With Bing Chat, the same question might result in the same answer, but if you use a different browser or a different computer the answer might be different.
Write a Python script for the micro:bit that functions as a tilt compass. This is not the same as a compass. It should display tilt instead of north. To display tilt, it should display the direction a ball would roll off the surface of the micro:bit when titled. Use the micro:bit display API’s clock hand image display feature to point in one of twelve different directions.
Links
[1] https://chat.openai.com/
[2] https://www.bing.com/search?q=Bing+AI&showconv=1
[3] https://learn.parallax.com/tutorials/language/python/intro-ai-chatbots
[4] https://learn.parallax.com/tutorials/robot/cyberbot/get-started-microbit-and-python
[5] https://learn.parallax.com/tutorials/robot/cyberbot/writing-microbit-programs
[6] https://www.bing.com/chat
[7] https://learn.parallax.com/tutorials/robot/cyberbot/cybersecurity-radio-tilt-control/display-tilt-direction/your-turn-display
[8] https://learn.parallax.com/tutorials/robot/cyberbot/cybersecurity-radio-tilt-control/measure-accelerometer-tilt/test-tilts
[9] https://learn.parallax.com/tutorials/robot/cyberbot/cybersecurity-radio-tilt-control/display-tilt-direction
[10] https://learn.parallax.com/tutorials/robot/cyberbot/cybersecurity-radio-tilt-control/measure-rotation-angles/measuring-rotation
[11] https://learn.parallax.com/tutorials/robot/cyberbot/cybersecurity-radio-tilt-control/measure-tilt-angles/did-you-know