Try   HackMD

Beginner

1.3 Flight Movements: Roll and Pitch

Challenge: Flight Practice!

英文

For this challenge, find two pieces of paper and some scotch tape. If you don’t have scotch tapze that’s okay! Find a paper weight or use something heavier like a text book. For this lesson your two pieces of paper will mark  a take off zone or a landing zone. Once you determine where each zone is use your scotch tape to keep your landing zone in place. The farther apart these zones are the greater the challenge will be! With our new knowledge of Pitch and Roll we will write a program to get some practice with these new flight movements!

1. Write a program where your drone flies from the take off zone to the landing zone. For this exercise have your drone start by facing towards the landing zone

2. Write a program where your drone flies from the take off zone to the landing zone. For this exercise face your drone so that it is not facing directly towards or away from the landing zone. Make sure your mark on your paper where your drone is facing. This way it can start from the same position every time. (hint: You should have to use roll this time!)

3. Write a program where your drone flies from the takeoff zone to the landing zone. For this exercise place an obstacle directly in between your take off and landing zones. Your drone can start by facing any direction. (hint: You should use both Pitch and Roll to avoid crashing into the obstacle!)

中文

挑戰:找兩張紙和一些透明膠帶。如果你沒有透明膠帶也沒關係!找一個紙重或使用一些更重的東西,比如教科書。在這個課程中,你的兩張紙將標記一個起飛區或降落區。一旦確定每個區域的位置,使用透明膠帶將你的降落區固定在原地。這些區域之間距離越遠,挑戰就越大!憑藉我們對俯仰和橫滾的新知識,我們將編寫一個程序來練習這些新的飛行動作!

  1. 編寫一個程序,使你的無人機從起飛區飛到降落區。在這個練習中,讓你的無人機開始時面向降落區。

  2. 編寫一個程序,使你的無人機從起飛區飛到降落區。在這個練習中,讓你的無人機的方向不是直接面向或背向降落區。確保在紙上標記無人機的面向。這樣它每次都可以從同一位置開始。(提示:這次你應該使用橫滾!)

  3. 編寫一個程序,使你的無人機從起飛區飛到降落區。在這個練習中,在你的起飛和降落區之間直接放置一個障礙物。你的無人機可以開始時面向任何方向。(提示:你應該使用俯仰和橫滾來避免撞到障礙物!)

飛行示意圖

1_3_1
2.
1_3_2

3.
1_3_3

解題策略

1.起飛,往前飛,降落
2.起飛,旋轉90度,往右側飛,降落
3.起飛,升高,往前飛,降落

完整程式碼

from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機 drone.pair() # 配對無人機 drone.takeoff() # 無人機起飛 drone.set_pitch(30) # 設定無人機的俯仰角度為30度 drone.move(2) # 讓無人機向前移動2秒鐘 drone.land() # 無人機降落 drone.close() # 關閉無人機連接
from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機對象 drone.pair() # 配對無人機 drone.takeoff() # 無人機起飛 drone.set_yaw(45) # 設定無人機的偏航角度為45度 drone.move(2) # 讓無人機向前移動2秒鐘 drone.set_yaw(0) # 設定無人機的偏航角度為0度 drone.set_roll(30) # 設定無人機的滾轉角度為30度 drone.move(2) # 讓無人機向前移動2秒鐘 drone.set_roll(0) # 設定無人機的滾轉角度為0度 drone.land() # 無人機降落 drone.close() # 關閉無人機連接
from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機 drone.pair() # 配對無人機 drone.takeoff() # 無人機起飛 drone.set_throttle(25) # 設定無人機的油門為25% drone.move(2) # 讓無人機保持當前狀態並移動2秒鐘 drone.set_throttle(0) # 設定無人機的油門為0% drone.set_pitch(30) # 設定無人機的俯仰角度為30度 drone.move(3) # 讓無人機向前移動3秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.land() # 無人機降落 drone.close() # 關閉無人機連接

Challenge: Square Up!

英文

For this challenge, try to program your CoDrone EDU to fly in the shape of a square using your new knowledge of Pitch and Roll. As an additional rule, make sure that the CoDrone EDU is facing the same direction for all parts of the square!

中文

在這個挑戰中,嘗試使用你對俯仰和橫滾的新知識,編寫程序讓你的 CoDrone EDU 飛出一個正方形的形狀。作為一個額外的規則,確保 CoDrone EDU 在正方形的每個部分都面向相同的方向!

飛行示意圖

1_3_4

解題策略

起飛,往前飛,向右傾斜,向右飛,向後傾斜,向後飛,向左傾斜,向左飛

完整程式碼

from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機對象 drone.pair() # 配對無人機 drone.takeoff() # 無人機起飛 drone.set_pitch(20) # 設定無人機的俯仰角度為20度 drone.move(2) # 讓無人機向前移動2秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.set_yaw(-40) # 設定無人機的偏航角度為-40度 drone.move(2) # 讓無人機向右移動2秒鐘 drone.set_yaw(0) # 設定無人機的偏航角度為0度 drone.set_pitch(20) # 設定無人機的俯仰角度為20度 drone.move(2) # 讓無人機向後移動2秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.set_yaw(-40) # 設定無人機的偏航角度為-40度 drone.move(2) # 讓無人機向左移動2秒鐘 drone.set_yaw(0) # 設定無人機的偏航角度為0度 drone.set_pitch(20) # 設定無人機的俯仰角度為20度 drone.move(2) # 讓無人機向前移動2秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.set_yaw(-40) # 設定無人機的偏航角度為-40度 drone.move(2) # 讓無人機向左移動2秒鐘 drone.set_yaw(0) # 設定無人機的偏航角度為0度 drone.set_pitch(20) # 設定無人機的俯仰角度為20度 drone.move(2) # 讓無人機向前移動2秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.land() # 無人機降落 drone.close() # 關閉無人機連接

1.4 Flight Movements: Throttle and Yaw

Challenge: 1. Fly in a circle

英文

Below are a series of challenges to test your flight movement skills! These tasks may require combining movements together simultaneously.

中文

以下是一系列挑戰,用來測試你的飛行動作技能!這些任務可能需要你同時結合多種動作。

飛行示意圖

image

解題策略

邊自轉邊往前飛就是畫圓圈

完整程式碼

from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機對象 drone.pair() # 配對無人機,確保無人機與控制器或程式連接 drone.takeoff() # 無人機起飛 drone.set_yaw(-35) # 設定無人機的偏航角度為-35度 drone.set_pitch(35) # 設定無人機的俯仰角度為35度 drone.move(8) # 讓無人機向前移動8秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.set_yaw(0) # 設定無人機的偏航角度為0度 drone.land() # 無人機降落 drone.close() # 關閉無人機連接

Challenge: 2. Fly in the shape of a sine wave

英文

Below are a series of challenges to test your flight movement skills! These tasks may require combining movements together simultaneously.
Fly in the shape of a sine wave

中文

以下是一系列挑戰,用來測試你的飛行動作技能!這些任務可能需要你同時結合多種動作。
以正弦波的形狀飛行。

飛行示意圖

image

完整程式碼

from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機對象 drone.pair() # 配對無人機,確保無人機與控制器或程式連接 drone.takeoff() # 無人機起飛 i = 0 # 初始化變量 i 為 0 for i in range(3): # 進行3次循環 drone.set_pitch(30) # 設定無人機的俯仰角度為30度 drone.set_throttle(30) # 設定無人機的油門為30% drone.move(1) # 讓無人機移動1秒鐘 drone.set_throttle(0) # 設定無人機的油門為0% drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.set_pitch(30) # 設定無人機的俯仰角度為30度 drone.set_throttle(-30) # 設定無人機的油門為-30% drone.move(1) # 讓無人機移動1秒鐘 drone.set_throttle(0) # 設定無人機的油門為0 drone.set_pitch(0) # 設定無人機的俯仰角度為0度 drone.land() # 無人機降落 drone.close() # 關閉無人機連接

1.5: Variables Part 1: Data Types

Challenge: The Drone Slide

英文

Now that you know how to create variables, let’s use them in a program with CoDrone EDU! For this challenge, you need to have your drone fly a zig-zag pattern like the one shown below:

Rules:

Name the file 3_1_challenge
You must use at least 2 integer or float variables
The forward motions in the zig-zag must be the same length
The side to side motions in the zig-zag must be the same length

中文

現在你知道如何創建變數了,讓我們在 CoDrone EDU 程式中使用它們吧!在這個挑戰中,你需要讓你的無人機飛行成像下面所示的鋸齒形態式的模式:

規則:

將檔案命名為 3_1_challenge
你必須使用至少 2 個整數或浮點數變數
鋸齒形態式的前進動作必須是相同的長度
鋸齒形態式的左右移動必須是相同的長度

飛行示意圖

image

解題策略

根據題目在往前飛時向左或向右橫移

完整程式碼

from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機對象 drone.pair() # 配對無人機,確保無人機與控制器或程式連接 drone.takeoff() # 無人機起飛 left = 1 # 定義變量 left 為 1 秒 f = 2 # 定義變量 f 為 2 秒 drone.set_pitch(30) # 設定無人機的俯仰角度為 30 度 drone.move(f) # 讓無人機向前移動 2 秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為 0 度 drone.set_roll(40) # 設定無人機的滾轉角度為 40 度 drone.move(left) # 讓無人機向右移動 1 秒鐘 drone.set_roll(0) # 設定無人機的滾轉角度為 0 度 drone.set_pitch(30) # 設定無人機的俯仰角度為 30 度 drone.move(f) # 讓無人機向前移動 2 秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為 0 度 drone.set_roll(-40) # 設定無人機的滾轉角度為 -40 度 drone.move(left) # 讓無人機向左移動 1 秒鐘 drone.set_roll(0) # 設定無人機的滾轉角度為 0 度 drone.set_pitch(30) # 設定無人機的俯仰角度為 30 度 drone.move(f) # 讓無人機向前移動 2 秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為 0 度 drone.set_roll(40) # 設定無人機的滾轉角度為 40 度 drone.move(left) # 讓無人機向右移動 1 秒鐘 drone.set_roll(0) # 設定無人機的滾轉角度為 0 度 drone.set_pitch(30) # 設定無人機的俯仰角度為 30 度 drone.move(f) # 讓無人機向前移動 2 秒鐘 drone.set_pitch(0) # 設定無人機的俯仰角度為 0 度 drone.land() # 無人機降落 drone.close() # 關閉無人機連接

1.6: Variables Part 2: Variables Take Flight!

Challenge 1: A Not-So-Simple Rectangle

英文

We have flown in a square, where all sides are the same length, but what about a rectangle? Remember that a rectangle has two sets of sides that are the same length (A square is a special type of rectangle). For this challenge, you will make the drone fly in a rectangle. This may seem easy, but there are some rules that will make it a little more challenging!

Rules:

You must have two variables: power and duration.
The long sides of the rectangle should be twice as long as the shorter sides.
You can only use math operators on variables to get different values (you are not allowed to reassign variable values once they are initialized).

中文

我們已經飛過正方形,其中所有邊長都相同,但長方形呢?請記住,一個長方形有兩組邊長相同(正方形是一種特殊類型的長方形)。在這個挑戰中,你將讓無人機飛行成一個長方形。這可能看起來很容易,但有一些規則會讓它變得更具挑戰性!

規則:

你必須有兩個變量:power(動力)和duration(持續時間)。
長方形的長邊應該是短邊的兩倍長。
你只能使用數學運算符對變量進行操作以獲得不同的值(一旦它們被初始化,就不允許重新分配變量值)。

飛行示意圖

image

解題策略

初始化無人機,讓其起飛,然後設置動力和持續時間。接著,依次控制無人機向前、向右、向後、向左傾斜並移動,每次移動後將傾斜角度恢復為零。最後,讓無人機降落並關閉連接。

完整程式碼

from codrone_edu.drone import * # 初始化無人機並連接 drone = Drone() drone.pair() # 起飛 drone.takeoff() # 設置動力和飛行持續時間 power = 30 duration = 2 # 向前傾斜並移動 drone.set_pitch(power) drone.move(duration) drone.set_pitch(0) # 向右傾斜並移動 drone.set_roll(power) drone.move(duration*2) drone.set_roll(0) # 向後傾斜並移動 drone.set_pitch(-power) drone.move(duration) drone.set_pitch(0) # 向左傾斜並移動 drone.set_roll(-power) drone.move(duration*2) drone.set_roll(0) # 降落 drone.land() drone.close()

Challenge 2: Spiraling Out of Control

英文

For this challenge, try making your CoDrone EDU fly in the shape of a square, but instead of having each side be the same length, use variables to make the sides decrease in size to create a spiral shape!

Rules:

You cannot use hard-coded values. You must use math operations on a variable to decrease the length of each side.
You must complete 4 sides minimum. For an extra challenge, see how small you can go!

中文

在這個挑戰中,試著讓你的 CoDrone EDU 飛行成一個正方形,但不是讓每個邊長相同,而是使用變量使邊長逐漸減小,以創建螺旋形狀!

規則:

不能使用硬編碼的值。必須對變量進行數學運算以減少每個邊的長度。
必須完成至少 4 條邊。為了增加挑戰性,試著讓邊長盡可能小!

飛行示意圖

image

解題策略

設置初始的傾斜角度,並進入一個迴圈,迴圈內的每一次迭代代表著一個完整的移動序列。在迴圈內部,我們依次控制無人機向前、向右、向後、向左進行傾斜和移動,並在每個動作完成後將傾斜角度減少3度。完成所有移動後,我們讓無人機降落並關閉連接。

完整程式碼

from codrone_edu.drone import * # 初始化無人機 drone = Drone() drone.pair() drone.takeoff() # 設置初始傾斜角度 angle = 40 # 開始迴圈控制無人機移動 for i in range(2): # 向前傾斜並移動 drone.set_pitch(angle) drone.move(2) drone.set_pitch(0) angle -= 3 # 向右傾斜並移動 drone.set_roll(angle) drone.move(2) drone.set_roll(0) angle -= 3 # 向後傾斜並移動 drone.set_pitch(-angle) drone.move(2) drone.set_pitch(0) angle -= 3 # 向左傾斜並移動 drone.set_roll(-angle) drone.move(2) drone.set_roll(0) angle -= 3 # 降落和關閉 drone.land() drone.close()

1.7: For Loops

Challenge 1: Fly a Polygon

英文

For this challenge, we want your drone to fly in a polygon shape of your choosing. You can choose:

Pentagon
Hexagon
Octagon
To fly these properly, you will need to calculate how much you will have to turn to create the appropriate angles for each shape. The chart below demonstrates how to calculate the angles. You will need to be able to choose your polygon, then make the turns so that they turn the correct amount to make the shape (approximately). For example, a square has 360 total interior degrees.

360/4 = 90 degrees per corner

This means that at each turn, the drone would need to make a 90 degree turn. You would then need to determine how much yaw for how long will equate to a 90 degree turn. For the polygon you choose, you will need to do the same.

(Hint: figure out 90 and then use it as a ratio for your turn, for example 60 degrees is 2/3 of 90 degrees so take 2/3 of the time from the Yaw movement that got you a 90 degree turn and you will have a 60 degree turn. )

中文

在這個挑戰中,我們希望你的無人機以你選擇的多邊形形狀飛行。你可以選擇:

五邊形
六邊形
八邊形
為了正確飛行,你需要計算需要轉動多少角度來創建每個形狀的適當角度。下面的表格演示了如何計算這些角度。你需要能夠選擇你的多邊形,然後使轉向角度正確以形成該形狀(大致上)。例如,一個正方形有 360 個總內角度。

360/4=90度每個角

這意味著在每次轉彎時,無人機需要轉動 90 度。然後,你需要確定多少偏航角度和持續時間等於一個 90 度轉彎。對於你選擇的多邊形,你需要做同樣的事情。

(提示:找出 90 度,然後將其用作你轉向的比例,例如 60 度是 90 度的 2/3,因此從使你轉了 90 度的偏航運動中取 2/3 的時間,你將得到一個 60 度的轉彎。)

飛行示意圖

image

解題策略

要讓無人機飛行成多邊形形狀,需要計算每個外角的度數。多邊形的外角為 360/n度,其中n是邊數。確定多邊形的邊數後,設定無人機向前移動和旋轉90度所需的時間。根據這個時間計算旋轉特定角度所需的時間。接下來,使用循環控制無人機向前移動並旋轉計算出的角度,重複這一過程直到完成多邊形的飛行路徑。

完整程式碼

from codrone_edu.drone import * def fly_polygon(sides, forward, yaw_90): # 初始化並連接無人機 drone = Drone() drone.pair() # 起飛 drone.takeoff() # 計算每個外角 angle = 360 / sides # 計算對應於外角的旋轉時間 yaw = yaw_90 * (angle / 90) for _ in range(sides): # 向前移動 drone.set_pitch(50) # 設置俯仰角,使無人機向前移動 drone.move(forward) # 移動指定的時間 drone.set_pitch(0) # 停止向前移動 # 順時針旋轉外角 drone.set_yaw(50) # 設置偏航角,使無人機旋轉 drone.move(yaw) # 旋轉指定的時間 drone.set_yaw(0) # 停止旋轉 # 降落 drone.land() # 關閉連接 drone.close() # 示例使用:飛行成五邊形、六邊形或八邊形 # 假設90度旋轉需要2秒,向前移動需要2秒 fly_polygon(5, 2, 2) # 五邊形 # fly_polygon(6, 2, 2) # 六邊形 # fly_polygon(8, 2, 2) # 八邊形

1.8: While Loops

Challenge 1: Tower of Terror

英文

Challenge: Tower of Terror

The Tower of Terror at a few of the Disney parks is a drop tower ride. These rides typically take riders up very high and very slowly, and then drop down very quickly. With a lot of drop tower rides, the riders go down, pause, go up a little bit but not that high, pause, go down, pause…you get it.

Your challenge is to use loops to program your CoDrone EDU to fly in the same pattern as the Tower of Terror!

Rules:

You must use either a for or while loop.
Your drone, after going up, must go down, pause, go up, and then pause at least three times.
You must use the randomint(a,b) function at least 2 times to vary the speed and timing of the drops.

中文

挑戰:驚悚之塔

在一些迪士尼樂園的驚悚之塔是一種下降塔遊樂設施。這些遊樂設施通常會慢慢地將乘客帶到很高很高的地方,然後迅速下降。在許多下降塔遊樂設施中,乘客會下降,暫停,稍微上升但不那麼高,暫停,再下降,暫停⋯你明白的。

你的挑戰是使用迴圈來編程你的 CoDrone EDU 飛行,以與驚悚之塔相同的模式!

規則:

你必須使用 for 或 while 迴圈。
你的無人機在上升後,必須下降,暫停,再上升,然後至少三次暫停。
你必須使用 randomint(a, b) 函數至少 2 次以改變下降的速度和時間。

解題策略

使用了迴圈來模擬 Tower of Terror 的動作模式。每次下降都包括慢速上升、在頂部暫停、快速下降和在底部暫停。速度和時間間隔通過randint函數產生隨機整數以實現變化。

完整程式碼

from codrone_edu.drone import * import time from random import randint drone = Drone() drone.pair() drone.takeoff() num_drops = 3 # 定義下降次數 for drop in range(num_drops): drone.set_throttle(50) # 慢速上升 drone.move(1) time.sleep(randint(1, 3)) # 在頂部暫停 drone.set_throttle(-100) # 快速下降 drone.move(1) time.sleep(randint(1, 3)) # 在底部暫停 drone.land()

Challenge 2: Boomerang

英文

For this challenge you will create a program where your drone will fly in 3 random directions and then return back to its starting position. For this challenge, you need to meet the following requirements:

Your drone must move in 3 random directions
Your drone must store the values of its movements
Your drone must use the stored values to return to its original starting point
You may use the go function or individual movement functions (pitch, yaw, roll, throttle) to make the drone move.

中文

在這個挑戰中,你需要創建一個程序,讓你的無人機向3個隨機方向飛行,然後返回到其起始位置。為了完成這個挑戰,你需要滿足以下要求:

你的無人機必須向3個隨機方向移動
你的無人機必須記錄其移動的數值
你的無人機必須使用記錄的數值返回到其原始起始點
你可以使用go函數或各個移動函數(pitch、yaw、roll、throttle)來讓無人機移動。

解題策略

隨機移動無人機,暫停後返回起始位置,再次暫停,最後降落,接著設計程式結構。初始化無人機并進行配對,生成隨機方向并儲存。根據隨機方向移動無人機,每次移動後暫停。然後反向移動無人機以返回起始位置,每次移動後暫停,最後降落無人機

from codrone_edu.drone import * import time from random import randint # 初始化無人機 drone = Drone() drone.pair() # 將無人機與控制器配對 drone.takeoff() # 起飛 # 定義隨機方向的數量 num_directions = 3 # 儲存移動方向的列表 movements = [] # 產生並儲存隨機方向 for _ in range(num_directions): pitch = randint(-100, 100) # 隨機的俯仰值 yaw = randint(-100, 100) # 隨機的偏航值 roll = randint(-100, 100) # 隨機的橫滾值 movements.append((pitch, yaw, roll)) # 移動無人機至隨機方向 for movement in movements: drone.go(*movement) # 使用隨機方向移動無人機 time.sleep(3) # 在每次移動之間暫停3秒 # 將無人機返回原始起飛位置 for movement in reversed(movements): # 反轉移動方向以返回原始位置 inverted_movement = tuple(-val for val in movement) drone.go(*inverted_movement) # 使用反轉的移動方向返回原始位置 time.sleep(3) # 在每次移動之間暫停3秒 # 降落無人機 drone.land()

1.10

Challenge: Custom Polygon

英文

For this challenge, you will need to create a program that does the following:

Takes in a value between 2 and 6 (2 is a circle)
Prints out a menu with each value option
Uses that value to make the appropriate sided polygon (for example, 4 would make the drone fly in a square)
Takeoff before requesting user input
Land once the polygon is completed.
Use at least one Sequence in the program.
It is strongly recommended that you go back to the for loops lesson and use your polygon program that you have already written and modify it to fit these new requirements. (We call this code reuse, and it is a popular concept in the professional world of programming)

中文

為了這個挑戰,你需要創建一個程式來完成以下任務:

接受一個介於2到6之間的數值(2代表圓形)。
列出一個包含每個數值選項的選單。
使用該數值來繪製相應邊數的多邊形(例如,輸入4會讓無人機飛行成一個正方形)。
在要求使用者輸入前起飛。
當多邊形完成後降落。
在程式中至少使用一個Sequence。
強烈建議你回顧for迴圈課程,並使用你已經寫好的多邊形程式來修改以符合這些新要求(這叫做程式碼重用,在專業的程式設計領域中是一個流行的概念)。

飛行示意圖

解題策略

定義飛行多邊形的函式,計算轉彎角度和持續時間,並使用無人機移動指令實現飛行。主函式顯示菜單供用戶選擇飛行的多邊形形狀,根據用戶輸入呼叫相應的函式,或退出程式。通過菜單提示和輸入驗證確保程式的正確運行。

完整程式碼

from codrone_edu.drone import * # 初始化無人機 drone = Drone() drone.pair() # 定義飛行多邊形的函式 def fly_polygon(drone, sides): angle = 360 / sides # 計算每個轉彎的角度 yaw_duration = 90 / angle # 計算每個轉彎的持續時間 drone.takeoff() # 在請求使用者輸入之前起飛 for _ in range(sides): drone.set_pitch(40) # 前進 drone.move(3.5) drone.set_pitch(0) drone.set_yaw(angle) # 以計算出的角度轉彎 drone.move(1.5) drone.set_yaw(0) #drone.hover(yaw_duration) # 懸停,持續時間為計算出的時間以完成轉彎 drone.land() # 完成多邊形後降落 # 主函式 def main(): while True: print("菜單:") print("2. 飛行圓形") print("3. 飛行三角形") print("4. 飛行正方形") print("5. 飛行五邊形") print("6. 飛行六邊形") print("7. 退出") option = input("選擇一個選項 (2-6): ") if option in ["2", "3", "4", "5", "6"]: sides = int(option) fly_polygon(drone, sides) elif option == "7": print("您已退出菜單。") break else: print("無效輸入。請輸入2到6之間的數字。") if __name__ == "__main__": main()

1.11

Challenge: Super Program

英文

So you have a program that uses numbers to have your CoDrone EDU do different maneuvers, and you have another program that uses letters to have your CoDrone EDU fly in different directions. What if you combined them both in the same program?

Rules:

  • Must include an option to quit
  • Must include a print command that lets the user know when they input an option that’s not available

中文

所以你有一個程式,使用數字來讓你的 CoDrone EDU 做出不同的動作,還有另一個程式,使用字母來讓你的 CoDrone EDU 向不同方向飛行。如果你把這兩個程式合併到同一個程式會怎麼樣呢?

規則:

必須包含退出選項 必須包含一個打印指令,讓使用者知道他們輸入了一個不可用的選項

飛行示意圖

解題策略

通過鍵盤輸入控制無人機飛行:打印指令選項,起飛無人機,進入控制迴圈,根據輸入控制無人機移動,當輸入"q"時降落並退出。

完整程式碼

from codrone_edu.drone import *
import time

# 初始化無人機
drone = Drone()
drone.pair()

# 打印指令選項
print("Command Options: ")
print("w: throttle up \n"
    "s: throttle down \n"
    "a: yaw left \n"
    "d: yaw right \n"
    "i: pitch forward \n"
    "k: pitch backward \n"
    "j: roll left \n"
    "l: roll right \n"
    "q: quit")

# 起飛
drone.takeoff()
power = 40

while True:
    # 將無人機的動作設置為零
    drone.set_throttle(0)
    drone.set_roll(0)
    drone.set_yaw(0)
    drone.set_pitch(0)

    # 等待用戶輸入指令
    direction = input("Input a command: ")

    # 根據用戶輸入控制無人機運動
    if direction == "w":
        drone.set_pitch(power)  # 向前
    elif direction == "s":
        drone.set_pitch(-power)  # 向後
    elif direction == "a":
        drone.set_roll(-power)  # 向左
    elif direction == "d":
        drone.set_roll(power)  # 向右
    elif direction == "q":
        drone.land()  # 降落
        break  # 退出迴圈
    else:
        print("Not a command")

    # 移動無人機
    drone.move(1)  # 移動一秒

print("Done")  # 程式執行完成

Intermediate

2.1

Challenge 1: Color Bar

英文

Now that we know the basics of using the LED, let’s add it to a flight program! For this challenge, you will create a program that has the drone fly to 3 different altitudes. At each Altitude, have the drone change its light to a color of your choosing. Make sure that, for this challenge, you complete the following requirements:

  1. Have the drone takeoff then fly to 3 different altitudes
  2. Use 3 different colors (one at each altitude)
  3. Pause for at least 3 seconds between each altitude level to give your lights time to play
  4. Land  the drone once completed

One other important note:

If you decide to use an LED function before takeoff, make sure you sleep for at least 1 second before the takeoff command, otherwise, the program may miss LED command and it may not get displayed. See the code below for an example:

drone.set\_drone\_LED(255, 0, 0, 100) 

time.sleep(1)   \# Add a time.sleep(1) before takeoff 

drone.takeoff()

中文

現在我們已經了解如何使用 LED,讓我們將它添加到飛行程式中!在這個挑戰中,你將創建一個程式,讓無人機飛到三個不同的高度。在每個高度,讓無人機改變燈光顏色,顏色由你選擇。請確保在這個挑戰中完成以下要求:

  1. 讓無人機起飛,然後飛到三個不同的高度
  2. 使用三種不同的顏色(每個高度一種顏色)
  3. 在每個高度之間暫停至少3秒鐘,給燈光顯示時間
  4. 完成後讓無人機降落

另一個重要注意事項:

如果你決定在起飛前使用 LED 功能,請確保在起飛指令前暫停至少1秒鐘,否則程式可能會錯過 LED 指令,導致燈光無法顯示。請參考以下程式碼示例:

drone.set\_drone\_LED(255, 0, 0, 100) 

time.sleep(1)   \# Add a time.sleep(1) before takeoff 

drone.takeoff()

飛行示意圖

解題策略

讓 CoDrone 飛行成多邊形,並在飛行過程中改變 LED 燈的顏色。解決這個問題的策略是首先初始化 CoDrone,然後讓它起飛。接著,分別控制 CoDrone 向前飛行一定時間,並在每個飛行段落中改變 LED 燈的顏色,以示不同。在每個段落之間,程式會暫停一段時間,以確保 CoDrone 能夠穩定飛行。最後,所有飛行完成後,將 CoDrone 降落。

完整程式碼

from codrone_edu.drone import * import time # 初始化無人機並連接 drone = Drone() drone.pair() # 起飛 drone.takeoff() # 第一段飛行:向前移動,紅色LED燈 drone.set_throttle(20) # 設置油門 drone.move(1) # 向前移動1秒 drone.set_throttle(0) # 停止移動 drone.set_drone_LED(255, 0, 0, 100) # 設置無人機LED燈為紅色 drone.set_controller_LED(255, 0, 0, 100) # 設置遙控器LED燈為紅色 # 等待1秒 time.sleep(1) # 第二段飛行:向前移動,綠色LED燈 drone.set_throttle(25) drone.move(1) drone.set_throttle(0) drone.set_drone_LED(0, 255, 0, 100) # 設置無人機LED燈為綠色 drone.set_controller_LED(0, 255, 0, 100) # 設置遙控器LED燈為綠色 # 等待1秒 time.sleep(1) # 第三段飛行:向前移動,藍色LED燈 drone.set_throttle(30) drone.move(1) drone.set_throttle(0) drone.set_drone_LED(0, 0, 255, 100) # 設置無人機LED燈為藍色 drone.set_controller_LED(0, 0, 255, 100) # 設置遙控器LED燈為藍色 # 等待1秒 time.sleep(1) # 降落 drone.land()

Challenge 2: Red Light, Green Light Game!

英文

For your second challenge, we will make our own Red Light, Green Light game with our drone! This game will require you to manually fly your drone with your controller while your LEDs will change color at random intervals. Choose a take off zone and a finish line. Try to fly your drone across the finish line but you are only allowed to move when your LEDs are green. If you move when the LEDs are red start from the beginning! Your program should have the following

  1. Use the randint function to randomly choose a color and time. If you need a refresher look back at the while loop lesson!
  2. The only flight command in your program should be a take off
  3. Once your drone is in the air, press the power button once to switch from the link state to manual flying state
  4. Your drone and controller will continue to change color while in manual flying state.
  5. Play the Red Light, Green Light game!

Here is one example of how this could be programmed. Have fun!

from codrone_edu.drone import *
import time
from random import randint
drone = Drone()
drone.pair()
drone.takeoff()
while True:
    random_color = randint(1, 2)
    random_delay = randint(1, 4)
    if random_color == 1:
        drone.set_drone_LED(255, 0, 0, 100)
        drone.set_controller_LED(255, 0, 0, 100)
    else:
        drone.set_drone_LED(0, 255, 0, 100)
        drone.set_controller_LED(0, 255, 0, 100)
    time.sleep(random_delay)

中文

對於你的第二個挑戰,我們將用我們的無人機製作自己的紅綠燈遊戲!這個遊戲需要你用遙控器手動操控無人機,而燈光會在隨機時間改變顏色。選擇一個起飛區和一個終點線。試著讓你的無人機飛越終點線,但只有在燈光變綠時才允許移動。如果在燈光變紅時移動,就得從頭開始!你的程式應該具備以下功能:

  1. 使用 randint 函數隨機選擇顏色和時間。如果需要複習,請回顧 while 迴圈的課程!
  2. 程式中唯一的飛行指令應該是起飛。
  3. 一旦你的無人機在空中,按一次電源按鈕以從連結狀態切換到手動飛行狀態。
  4. 在手動飛行狀態下,你的無人機和遙控器將繼續改變顏色。
  5. 遊玩紅綠燈遊戲!

以下是如何編寫這個程式的一個例子。玩得開心!

from codrone_edu.drone import *
import time
from random import randint
drone = Drone()
drone.pair()
drone.takeoff()
while True:
    random_color = randint(1, 2)
    random_delay = randint(1, 4)
    if random_color == 1:
        drone.set_drone_LED(255, 0, 0, 100)
        drone.set_controller_LED(255, 0, 0, 100)
    else:
        drone.set_drone_LED(0, 255, 0, 100)
        drone.set_controller_LED(0, 255, 0, 100)
    time.sleep(random_delay)

飛行示意圖

image

解題策略

讓CoDrone在飛行過程中隨機改變LED燈的顏色。解決這個問題的策略是:首先初始化CoDrone,並讓它起飛。接著,進入無限循環,以持續控制CoDrone。在每次循環中,使用 randint函數隨機選擇LED燈的顏色,然後根據選擇的顏色設置CoDrone和遙控器的LED燈顏色。在設置完LED燈顏色後,讓CoDrone在新的LED燈顏色下飛行一段時間,以讓使用者觀察到顏色的變化。這樣的循環將持續進行,直到人為停止程式為止。

完整程式碼

from codrone_edu.drone import *
import time
from random import randint

# 初始化無人機並連接
drone = Drone()
drone.pair()

# 起飛
drone.takeoff()

# 進入無限循環
while True:
    # 隨機選擇 LED 燈顏色
    random_color = randint(1, 2)

    # 根據隨機選擇設置 LED 燈顏色
    if random_color == 1:
        drone.set_drone_LED(255, 0, 0, 100)# 設置無人機LED燈為紅色
        drone.set_controller_LED(255, 0, 0, 100)# 設置遙控器LED燈為紅色
    else:
        drone.set_drone_LED(0, 255, 0, 100)# 設置無人機LED燈為綠色
        drone.set_controller_LED(0, 255, 0, 100)# 設置遙控器LED燈為綠色

    # 暫停1秒
    time.sleep(1)


2.2

Challenge 1: Make a Ringtone

英文

Now that we can make progressions of notes, try to create your own ringtone! Make sure your program meets the following requirements:

  1. Ringtone must last at least 10 seconds
  2. Use at least 2 lists
  3. Use at least 5 different notes
  4. Use at least 2 durations for the notes

Advanced: See if you can use a for or while loop outside of your for loop where the notes play to make your ringtone repeat the whole sequence of notes multiple times.

中文

現在我們可以製作音符的進行了,試著創建你自己的鈴聲吧!確保你的程式滿足以下要求:

  1. 鈴聲必須至少持續10秒。
  2. 使用至少2個列表。
  3. 使用至少5個不同的音符。
  4. 使用至少2種音符的持續時間。
  5. 進階:看看你是否可以在音符播放的 for 迴圈之外使用 for 或 while 迴圈,讓你的鈴聲重複整個音符序列多次。

飛行示意圖

解題策略

這段程式有兩個部分:播放音樂和控制LED燈。首先初始化無人機並連接。然後逐個播放音符,使用 drone_buzzer方法控制音樂。同時,也逐個控制LED燈,使用
set_drone_LED和set_controller_LED方法設置燈光顏色。在每次設置完燈光後,使用time.sleep函數暫停一段時間,讓燈光保持亮起的狀態。

完整程式碼

from codrone_edu.drone import * import time # 初始化無人機並連接 drone = Drone() drone.pair() # 音符和持續時間列表 notes = [Note.C3, Note.D3, Note.E3, Note.F3, Note.G3, Note.A3, Note.B3, Note.C4, Note.D4, Note.F4] duration = [1000, 1000, 2500, 2500, 2500, 1000, 1000, 2000, 2000, 3000, 1500] # 播放音樂 for i in range(len(notes)): drone.drone_buzzer(notes[i], duration[i])

Challenge 2: Light Show

英文

For this challenge, we will use our knowledge of LEDs to make a light show with our drone. To complete this challenge your drone should do the following:

  1. Create a list of color names (strings)
  2. Loop through the list
  3. Change the drone LED to the appropriate color based on the list of colors.
  4. Have different durations for each step in the show
  5. Run for at least 10 seconds

中文

在這個挑戰中,我們將利用 LED 的知識來為我們的無人機製作一個燈光秀。完成這個挑戰,你的無人機應該執行以下操作:

  1. 建立一個顏色名稱的列表(字串)。
  2. 遍歷列表。
  3. 基於顏色列表將無人機 LED 更改為適當的顏色。
  4. 每個步驟的燈光秀具有不同的持續時間。
  5. 持續運行至少10秒。

飛行示意圖

解題策略

建立包含三種顏色的列表,然後建立與無人機的連接。接著,定義每種顏色的持續時間。在循環中,遍歷顏色列表,將無人機的LED燈光設置為當前顏色,並等待指定的持續時間,確保循環持續運行至少10秒。最後,關閉與無人機的連接。

完整程式碼

from codrone_edu.drone import * import time import random # 1. 建立一個顏色名稱的列表 colors = ["紅色", "綠色", "藍色"] # 2. 遍歷列表 drone = Drone() drone.pair() start_time = time.time() # 5. 持續運行至少10秒 while time.time() - start_time < 10: for color in colors: # 3. 基於顏色列表將無人機 LED 更改為適當的顏色 if color == "紅色": drone.led("red") time.sleep(random.uniform(0.5, 1.5)) # 4. 每個步驟的燈光秀具有不同的持續時間 elif color == "綠色": drone.led("green") time.sleep(random.uniform(0.5, 1.5)) elif color == "藍色": drone.led("blue") time.sleep(random.uniform(0.5, 1.5))) # 關閉連接 drone.close()

2.3: Void Functions

Challenge 1: Dizzy Drone Rewrite

英文

Remember how we made our drone spin in circles a set number of times? This time we are going to make that program a little more complex. We want to make our drone spin a number of times specified by the user. After each rotation, we want the drone to display a light sequence, rise a little higher, and complete another rotation. The drone will continue this procedure until it has done all of its rotations. To successfully complete this challenge, your program should:

Take in a user input for the number of spins
Define 3 functions:
A function for the light show
A function to spin
A function that calls the spin function, makes the drone increase altitude, and calls the light show
Use a loop to call the 3rd function (the one that calls the others) the number of times the user inputs

中文

還記得我們如何讓無人機繞圈旋轉一定次數嗎?這次我們將使程式變得更複雜一些。我們想讓無人機旋轉使用者指定的次數。每次旋轉後,我們希望無人機顯示一個燈光序列,升得更高一點,並完成另一次旋轉。無人機將繼續此過程,直到完成所有旋轉。為了成功完成這項挑戰,您的程序應該:

接受使用者輸入的旋轉次數
定義3個函數:
燈光秀功能
旋轉的函數
呼叫旋轉函數,使無人機增加高度,並調用燈光秀的函數
使用循環呼叫第三個函數(呼叫其他函數的函數)使用者輸入的次數

解題策略

定義一個專門顯示燈光的function,再定義一個專門旋轉的function,再定義一個同時引用兩個function,而且同時往飛上的function,最後呼叫第三個function

完整程式碼

from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機對象 drone.pair() # 配對無人機,確保無人機與控制器或程式連接 def light_show(): # 定義一個顯示燈光效果的函數 drone.set_drone_LED(255, 0, 0, 100) # 設定無人機的LED燈為紅色 drone.set_controller_LED(255, 0, 0, 100) # 設定控制器的LED燈為紅色 time.sleep(1) # 暫停1秒鐘 def spin(): # 定義一個旋轉無人機的函數 drone.set_yaw(60) # 設定無人機的偏航角度為60度(向右旋轉) drone.move(2) # 旋轉2秒鐘 drone.set_yaw(0) # 恢復偏航角度為0度(停止旋轉) def spin_and_light(): # 定義一個結合旋轉和燈光效果的函數 spin() # 旋轉無人機 light_show() # 顯示燈光效果 drone.set_throttle(30) # 設定無人機的油門為30%(提升高度) drone.move(1) # 向上移動1秒鐘 drone.set_throttle(0) # 設定無人機的油門為0%(停止提升) num_spins = int(input("輸入旋轉次數:")) # 提示使用者輸入旋轉次數,並將其轉換為整數 drone.takeoff() # 無人機起飛 for i in range(num_spins): # 進行 num_spins 次旋轉和燈光效果 spin_and_light() drone.land() # 無人機降落 drone.close() # 關閉無人機連接

Challenge 2: Morse Code Messages

英文

You may have heard about Morse code, a language made up of combining dots and dashs to create letters and numbers. For this program, we want to create functions that will produce the dots and dashes that make up each letter using the CoDrone EDU’s buzzer. To complete this challenge, your program must do the following:

Have defined functions for making the dot and dash in Morse code.
Using those dot and dash functions, try creating the word ‘hello’.
For an advanced challenge, try creating functions for each individual letter and using them to spell out your name.

中文

您可能聽過莫爾斯電碼,這是一種由點和破折號組合而成的字母和數字的語言。對於此程序,我們希望建立函數,使用 CoDrone EDU 的蜂鳴器產生組成每個字母的點和破折號。要完成此挑戰,您的程式必須執行以下操作:

定義了用莫爾斯電碼製作點和劃的函數。
使用這些點和破折號函數,嘗試建立單字「hello」。
對於高級挑戰,請嘗試為每個字母建立函數並使用它們拼出您的名字。

解題策略

定義摩斯密碼中,點跟線的聲音音高長短,並在未來拼出字母時,重複呼叫這些點跟線

完整程式碼

from codrone_edu.drone import * # 從 codrone_edu.drone 模組導入所有類別和函數 drone = Drone() # 創建一個無人機對象 drone.pair() # 配對無人機,確保無人機與控制器或程式連接 def dot(): # 定義發出一個短音(點)的函數 drone.drone_buzzer(Note.C4, 500) # 無人機蜂鳴器發出C4音高,持續500毫秒 time.sleep(0.5) # 暫停0.5秒 def dash(): # 定義發出一個長音(劃)的函數 drone.drone_buzzer(Note.C4, 1500) # 無人機蜂鳴器發出C4音高,持續1500毫秒 time.sleep(0.5) # 暫停0.5秒 def morse_h(): # 定義摩斯電碼字母"H"(四個點)的函數 dot() dot() dot() dot() time.sleep(2) # 字母之間的間隔 def morse_e(): # 定義摩斯電碼字母"E"(一個點)的函數 dot() time.sleep(2) # 字母之間的間隔 def morse_l(): # 定義摩斯電碼字母"L"(點劃點點)的函數 dot() dash() dot() dot() time.sleep(2) # 字母之間的間隔 def morse_o(): # 定義摩斯電碼字母"O"(三個劃)的函數 for _ in range(3): dash() time.sleep(2) # 字母之間的間隔 morse_h() # 發送摩斯電碼字母"H" morse_e() # 發送摩斯電碼字母"E" morse_l() # 發送摩斯電碼字母"L" morse_l() # 再次發送摩斯電碼字母"L" morse_o() # 發送摩斯電碼字母"O" drone.close() # 關閉無人機連接

2.4: Return Functions

Challenge: Conversion Calculator

英文

Many countries and systems use different ways of measuring quantities such as distance, mass, force, etc… For this exercise, you will create a conversion calculator that takes in 4 different measurements and converts them to a different measurement. For example, we created a conversion function for inches to centimeters earlier in the lesson. You can choose any conversions you would like. To successfully complete this challenge, your program must:

Have a list that contains the abbreviations a user will choose from for the measurement to be converted
Prompt for 2 input values, the amount and measurement
Have a function that takes in the two input values and returns the calculated value and measurement as a string
Store the result as a variable
Print the result in a sentence that tells the user what they input and what the result was (For example: “You entered 5 inches which is 12.7 centimeters)
A few notes:

You can add strings together by using the + sign
print(“Hello” + “World”) will print “Hello World”
You can do the same for variables and strings:
name = John
print(“Hello” + name) will print “Hello John”
To print text and variable

中文

挑戰:轉換計算器 許多國家和系統使用不同的方式來測量距離、質量、力量等數量。在這個練習中,你將創建一個轉換計算器,它可以接收4種不同的測量值並將它們轉換為不同的測量值。例如,我們在課堂上之前創建了一個從英寸轉換為厘米的轉換函數。你可以選擇任何你想要的轉換。為了成功完成這個挑戰,你的程式必須:

  1. 擁有一個列表,包含用戶將選擇的測量值縮寫,以進行轉換
  2. 提示輸入2個值,即數量和測量單位
  3. 有一個函數,接受這兩個輸入值並返回計算結果和測量值作為字符串
  4. 將結果儲存為變量
  5. 以句子的形式打印結果,告訴用戶他們輸入了什麼以及結果是什麼(例如:“你輸入了5英寸,相當於12.7厘米”)

一些提示:
您可以使用 + 號將字串加在一起
print(“Hello”+“World”) 將會列印“Hello World”
您可以對變數和字串執行相同的操作:
姓名 = 約翰
print(“Hello” + name) 將會印出“Hello John”

飛行示意圖

此題不需要使用無人機飛行

解題策略

根據題目要求,定義一個 function 來處理單位轉換
並讓使用者輸入數量及要轉換的單位
並輸出函式回傳的結果
便可完成本題要求

完整程式碼

from codrone_edu.drone import * # 引入模組 drone = Drone() # 取得 drone 實體 drone.pair() # 與無人機配對 # 定義轉換函數 def convert_measurement(amount, measurement): if measurement == 'inch': # 如果測量單位是英寸 return f"{amount * 2.54} 公分" # 返回轉換結果 elif measurement == 'pound': # 如果測量單位是磅 return f"{amount * 0.453592} 公斤" # 返回轉換結果 elif measurement == 'mile': # 如果測量單位是英里 return f"{amount * 1.60934} 公里" # 返回轉換結果 elif measurement == 'gallon': # 如果測量單位是加侖 return f"{amount * 3.78541} 公升" # 返回轉換結果 # 測量單位 list measurements = ['inch', 'pound', 'mile', 'gallon'] amount = float(input("請輸入數量: ")) # 請使用者輸入數量 measurement = input(f"請選擇測量單位 ({', '.join(measurements)}): ") # 請使用者選擇測量單位 # 獲取轉換結果 result = convert_measurement(amount, measurement) # 輸出結果 print(f"你輸入了 {amount} {measurement},相當於 {result}") drone.close() # 斷開連接

2.5 Random

Challenge 2: Random Noises

英文

For this challenge, you will have your CoDrone EDU create random noises using the buzzer. To complete this challenge, do the following:

Choose the random notes that your drone will choose from and place them in a void function that has one parameter, iterations.
Inside the the function, the iterations parameter will be used to determine how many times the notes will repeat in a loop.
For each loop iteration, generate a random note and duration and have the CoDrone EDU produce that sound.
Once you have completed this program, your drone should produce random sounds that repeat several times depending on your input.

中文

為了這個挑戰,你需要讓你的CoDrone EDU使用蜂鳴器發出隨機的聲音。要完成這個挑戰,請執行以下步驟:

選擇無人機將隨機選擇的音符,並將這些音符放在一個具有一個參數iterations的void函數中。
在這個函數中,使用iterations參數來決定音符在循環中重複的次數。
對於每一次循環迭代,生成一個隨機的音符和持續時間,並讓CoDrone EDU發出這個聲音。
完成這個程式後,根據你的輸入,你的無人機應該會發出隨機的聲音,並重複多次。

飛行示意圖

本題的無人機不需要飛行

解題策略

本題首先準備了兩個 list,分別用來存放不同音高以及時間
接著定義了一個函式,每次呼叫時,便會使用 for 迴圈
隨機挑出一種音高跟持續時間
並依此使無人機播放對應的聲音

完整程式碼

import random # 引入random 模組 from codrone_edu.drone import * # 引入Drone類別 # 創建Drone對象 drone = Drone() # 初始化並連接 drone.pair() # 定義音符和持續時間範圍 notes = [Note.C1, Note.C2, Note.C3, Note.C4, Note.C5, Note.C6, Note.C7] # 共有7個音符 durations = [1000, 1500, 2000, 500, 200] # 持續時間 (豪秒) def play_random_notes(iterations): #定義函數,播放隨機音符 for _ in range(iterations): #遍歷iterations次 note = random.choice(notes) # 隨機選擇音符 duration = random.choice(durations) # 隨機選擇持續時間 drone.drone_buzzer(note, duration) # 播放 iterations = int(input()) # 請使用者輸入播放次數 # 播放隨機音符 play_random_notes(iterations) # 斷開連接 drone.close()

2.6 Timers

Challenge 1: One Minute Code

英文

Fit as much flight movement as you can into one minute exactly (according to the
elapsed_time
variable in your program)!

Rules:

You must include at least one pitch, one throttle, one yaw, and one roll.
Any flight movement, including hovering or delaying, can only last for 3 seconds.
The same movement cannot be used in consecutive order, whether that is one after the other or in a loop (so don’t loop pitching forward for 3 seconds 20 times).
Takeoff and landing are included in the one minute.

中文

將儘可能多的飛行動作在恰好一分鐘內完成(根據程序中的 elapsed_time 變數計算)!

規則:

你必須至少包含一次俯仰、一次油門、一次偏航和一次滾轉。
任何飛行動作,包括懸停或延遲,都只能持續3秒鐘。
同樣的動作不能連續使用,無論是一次接一次還是在迴圈中(所以不能迴圈前俯仰3秒鐘重複20次)。
起飛和降落都包括在這一分鐘內。

飛行示意圖

由於動作太多,故採用流程圖之形式展現

image

解題策略

完整程式碼

from codrone_edu.drone import * # 匯入Drone類別 # 創建Drone對象 drone = Drone() # 初始化並連接 drone.pair() # 起飛 drone.takeoff() # 計時器起始 start_time = time.time() # 計算已經過的時間 elapsed_time = 0 # 飛行動作列表,確保不連續重複 actions = [ drone.set_pitch(30), # 俯仰 drone.set_throttle(30), # 油門 drone.set_yaw(30), # 偏航 drone.set_roll(30), # 滾轉 drone.set_pitch(-30), # 反向俯仰 drone.set_throttle(-30), # 反向油門 drone.set_yaw(-30), # 反向偏航 drone.set_roll(-30), # 反向滾轉 ] # 循環執行動作,3*18=54秒,加上起飛和降落,總共60秒 actions_id=0 # 動作 id for i in range(18): actions[actions_id] # 執行動作 move(3) # 移動 3 秒 actions_id+=1 # 動作 id 加 1 if actions_id>=len(actions): # 如果動作 id 超過動作列表長度 actions_id=0 # 重置動作 id # 降落 drone.land() # 斷開連接 drone.close()

Challenge 2: Alarm Clock

英文

For this challenge, create a program that takes a user input and sets a timer to wait for an amount of time equal to that input. After the timer has finished, have your drone take off and act as an alarm clock, changing LED colors and playing sounds. In order to complete this challenge, your program must have the following:

A user input prompt asking for the amount of time for the timer in seconds
The input must be converted into an integer to be used for the timer
You must have at least two different LED colors and three different sounds after the timer has finished

中文

挑戰說明:創建一個程式,該程式接受使用者輸入並設置一個計時器,等待等同於該輸入時間的時間量。計時器結束後,讓您的無人機起飛並作為鬧鐘,改變LED顏色並播放聲音。為了完成此挑戰,您的程式必須包含以下內容:

  1. 提示使用者輸入計時器時間(以秒為單位)
  2. 將輸入轉換為整數以用於計時器
  3. 計時器結束後,您必須至少有兩種不同的LED顏色和三種不同的聲音

飛行示意圖

image

解題策略

首先,讓使用者輸入起飛前的等待時間,並讓無人機等待
接著使無人機起飛,並改變其 LED 顏色,以及播放聲音 (共三組)

完整程式碼

import time # 匯入時間模組
from codrone_edu.drone import Drone # 匯入Drone類別

drone = Drone() # 建立無人機物件
timer_seconds = input("請輸入計時器時間(秒):") # 提示使用者輸入計時器時間
timer_seconds = int(timer_seconds) # 將輸入轉換為整數

print(f"計時 {timer_seconds} 秒...") # 顯示計時器時間
time.sleep(timer_seconds) # 等待

drone.pair() # 連接無人機

drone.takeoff() # 無人機起飛

# 改變LED顏色和播放聲音
drone.led("red") # 改變LED為紅色
drone.drone_buzzer(Note.C1, 1000) # 播放C1音符,持續1秒
time.sleep(1) # 等待1秒
drone.led("blue") # 改變LED為藍色
drone.drone_buzzer(Note.C2, 1000) # 播放C2音符,持續1秒
time.sleep(1) # 等待1秒
drone.led("green") # 改變LED為綠色
drone.drone_buzzer(Note.C3, 1000) # 播放C3音符,持續1秒

print("鬧鐘響了!無人機已起飛並改變LED顏色和播放聲音。") # 顯示訊息

time.sleep(5)  # 保持5秒鐘的飛行時間
drone.land() # 降落無人機

# 斷開連接
drone.close()

Advanced

3.2 Battery

Challenge 1: Battery Calculator

英文

For this challenge, we want to predict whether or not our drone will be able to fly the flight path we have programmed for it. To do this, repeat the step where we checked the difference in battery power after a takeoff, wait, and land. Figure out how much battery is lost per 5 seconds of flight time:

  1. Takeoff, hover 5 seconds, land -> take before and after battery measurements
  2. Takeoff, hover 10 seconds, land -> take before and after battery measurements
  3. Take the difference of the battery usage between steps 1 and 2. This is your battery drain per 5 seconds of stationary flight.

Now, write a flight plan that has at least 5 movements and at least 30 seconds of flight time. Store the beginning and ending battery percentage. Also store the beginning and ending flight time. Print both of these values at the end of the flight, after landing.

When you run the program, time it and make a prediction as to how much battery life you will lose. Check your drone’s output versus your prediction. How close was your prediction? What could be causing any differences?

中文

為了完成此挑戰,我們需要預測無人機是否能夠按照我們編程的飛行路徑飛行。為了做到這一點,重複檢查起飛、等待和降落後的電池電量差異。計算每5秒飛行時間消耗的電量如下:

  1. 起飛,懸停5秒,降落 -> 記錄起飛前和降落後的電池電量
  2. 起飛,懸停10秒,降落 -> 記錄起飛前和降落後的電池電量
  3. 計算步驟1和步驟2之間的電池使用差異。這就是每5秒靜止飛行的電池消耗量。

接下來,撰寫一個包含至少5個動作且至少30秒飛行時間的飛行計劃。記錄起始和結束時的電池百分比,以及起始和結束時的飛行時間。飛行結束後,打印這些數據。

當你運行程序時,計時並預測你會消耗多少電池電量。檢查無人機的輸出與你的預測相比,看看差距有多大。分析可能導致差異的原因。

飛行示意圖

image

解題策略

首先,紀錄每5秒靜止飛行的電池消耗量
接下來,撰寫一個包含至少5個動作且至少30秒飛行時間的飛行計劃,這個可以參考先前範例,並在結束後比較前後電池的消耗量即可完成挑戰

完整程式碼

from codrone_edu.drone import Drone
import time

drone = Drone()
drone.pair()

# 計算電池損耗
def get_battery_loss(hover_time): 
    drone.takeoff()
    time.sleep(hover_time)
    drone.land()
    return drone.get_battery()

# 測量懸停 5 秒的電池損耗
battery_before_5s = drone.get_battery()
battery_after_5s = get_battery_loss(5)
battery_loss_5s = battery_before_5s - battery_after_5s

# 測量懸停 10 秒的電池損耗
battery_before_10s = drone.get_battery()
battery_after_10s = get_battery_loss(10)
battery_loss_10s = battery_before_10s - battery_after_10s

# 計算每 5 秒的電池損耗
battery_loss_per_5s = (battery_loss_10s - battery_loss_5s)
print(f"每 5 秒的電池損耗: {battery_loss_per_5s}%")

drone.close()


drone = Drone() # 創建 Drone 物件
drone.pair() # 連接無人機

# 設定飛行計劃
def flight_plan():
    battery_start = drone.get_battery() # 記錄起始電池
    start_time = time.time() # 記錄起始時間
    
    drone.takeoff()
    time.sleep(5)  # 懸停 5 秒
    
    drone.set_pitch(50)  # 向前飛行
    time.sleep(5)
    drone.set_pitch(0)
    
    time.sleep(5)  # 懸停 5 秒
    
    drone.set_pitch(-50)  # 向後飛行
    time.sleep(5)
    drone.set_pitch(0)
    
    time.sleep(5)  # 懸停 5 秒
    
    drone.land()
    
    end_time = time.time() # 記錄結束時間
    battery_end = drone.get_battery() # 記錄結束電池
    
    return battery_start, battery_end, start_time, end_time # 回傳電池、時間資訊

battery_start, battery_end, start_time, end_time = flight_plan() # 開始飛行計劃

# 計算預測的電池損耗
flight_time_seconds = end_time - start_time # 計算飛行時間
predicted_battery_loss = (flight_time_seconds / 5) * battery_loss_per_5s # 預測電池損耗
actual_battery_loss = battery_start - battery_end # 實際電池損耗

print(f"起始電池: {battery_start}%")
print(f"結束電池: {battery_end}%")
print(f"實際電池損耗: {actual_battery_loss}%")
print(f"預測電池損耗: {predicted_battery_loss}%")

drone.close() # 關閉連接

Challenge 2: Battery Charge Reporter

英文

For this challenge, we want to find out what the most battery intensive actions are so that we don’t tax our drone too much when flying. To complete this challenge, complete the following steps:

  1. Create a list that contains the names of the maneuvers your drone will perform. (For example, flip, circle, square, hover).
  2. Create an empty list for battery levels.
  3. Call the functions in the list you created in step 1. At the end of each step, append to the list the current battery level and time.
  4. At the end of the program, print the list of maneuvers with their battery levels. You must use a loop to do this.

**BONUS Challenge: **If you dare, try to figure out the maneuver that uses the most battery and print this as well.

中文

對於這個挑戰,我們想找出哪些動作最耗電,以便在飛行時不會讓我們的無人機過度耗電。要完成這個挑戰,請完成以下步驟:

  1. 建立一個包含無人機將要執行的動作名稱的清單。(例如,翻轉、繞圈、方形、懸停)。
  2. 建立一個空的清單來記錄電池電量。
  3. 呼叫你在步驟1中建立的清單中的函數。在每個步驟結束時,將當前的電池電量和時間附加到清單中。
  4. 在程式結束時,列印動作及其對應的電池電量。你必須使用循環來完成這個步驟。 附加挑戰:如果你敢,試著找出最耗電的動作並列印出來。

飛行示意圖

image

解題策略

根據題目列點的敘述逐步實作,動作名稱的清單可以參考之前做過的部分
關於挑戰的部分,我們可以把所有動作所消耗的 battery 記錄下來,並在最後取出極值

完整程式碼

# 引入必要的庫
from codrone_edu.drone import * # 引入Drone類別
import time # 引入time模組

# 初始化無人機
drone = Drone()

# 設置無人機並起飛
drone.pair()
drone.takeoff()

# 建立一個包含無人機將要執行的動作名稱的清單
maneuvers = ["flip", "circle", "square", "hover"] # 翻轉、繞圈、畫正方形、懸停

# 建立一個空的清單來記錄電池電量
battery_levels = []

# 定義各個動作的函數
def flip(): # 翻轉
    drone.set_flip(0) # 0代表向前翻轉
    time.sleep(2)

def circle(): # 繞圈
    drone.set_roll(50) # 設定橫滾速度
    drone.set_yaw(30) # 設定偏航速度
    time.sleep(5)
    drone.set_roll(0)
    drone.set_yaw(0)

def square():   # 畫正方形
    for _ in range(4):
        drone.set_pitch(50) # 設定俯仰速度
        time.sleep(1)
        drone.set_pitch(0)
        drone.set_yaw(90) # 旋轉90度
        time.sleep(1)
        drone.set_yaw(0)

def hover():   # 懸停
    time.sleep(5)

# 建立一個字典將動作名稱與函數對應起來
maneuver_functions = {
    "flip": flip,
    "circle": circle,
    "square": square,
    "hover": hover
}

# 執行動作並記錄電池電量
for maneuver in maneuvers: # 依序執行清單中的動作
    start_time = time.time() # 記錄開始時間
    maneuver_functions[maneuver]()  # 執行動作
    end_time = time.time() # 記錄結束時間
    battery_levels.append((maneuver, drone.get_battery(), end_time - start_time)) # 記錄電池電量

# 列印動作及其對應的電池電量
for maneuver, battery, duration in battery_levels: # 依序列印清單中的動作、電池電量、持續時間
    print(f"動作: {maneuver}, 電池電量: {battery}%, 持續時間: {duration:.2f}秒") # 列印動作、電池電量、持續時間

# 找出最耗電的動作
most_battery_intensive = min(battery_levels, key=lambda x: x[1]) # 找出電池電量最低的動作
print(f"最耗電的動作: {most_battery_intensive[0]}, 電池電量: {most_battery_intensive[1]}%") # 列印最耗電的動作及其電池電量

# 降落無人機並結束
drone.land()

3.3

Challenge 1: Height Calculator Part 1

英文

For this challenge, we will first take, store and print barometer measurements. We will then attempt to correlate those to the height of the drone.

Define a function that takes readings and appends them to a list of pressures every second. You must use a loop to accomplish this. The function should take in a duration or number of readings as a parameter. Have the drone take off, call the function for a time of your choosing. Have the drone throttle up at a throttle level of your choosing for the duration that you chose (it is recommended to use a small number for both). Finally,  use a loop to print the values stored in the pressures. When you run your program, use something to measure the height of the drone at takeoff and the approximate height at each 1 second interval (you could use the number of blocks on the wall from the floor or a measuring stick or even your body).

中文

為了完成這個挑戰,我們將首先記錄並儲存氣壓計的測量值,然後嘗試將這些測量值與無人機的高度進行關聯。

定義一個函數來每秒鐘記錄一次讀數並將其附加到氣壓值列表中。你必須使用迴圈來完成這項工作。這個函數應該接收一個持續時間或讀數次數作為參數。讓無人機起飛,並呼叫這個函數來記錄你選擇的時間長度。在選擇的持續時間內,以你選擇的節流水平讓無人機向上加速(建議兩者都使用較小的數值)。最後,使用迴圈來列印儲存在氣壓值中的數據。當你運行你的程式時,使用某些工具來測量無人機起飛時的高度以及每1秒鐘間隔的大約高度(你可以使用牆上從地板開始的方塊數,或者測量棒,甚至是你的身體)。

飛行示意圖

image

解題策略

首先,需要寫一個函數,用來記錄呼叫時的氣壓值,並將該值加入至 list 中
接著,使得無人機向上飛行,並間歇性的紀錄當前氣壓值
最後,使用迴圈印出結果即可

完整程式碼

import time # 導入時間模組
from codrone import CoDrone # 導入CoDrone類別

# 初始化無人機
drone = CoDrone()

def record(duration): # 定義一個函數,用於記錄氣壓值
    pressures = [] # 創建一個空列表,用於存儲氣壓值
    start_time = time.time() # 記錄開始時間
    while time.time() - start_time < duration: # 當當前時間減去開始時間小於持續時間時
        pressure = drone.get_pressure() # 獲取當前氣壓值
        pressures.append(pressure) # 將氣壓值添加到列表中
        time.sleep(1)  # 每秒鐘記錄一次
    return pressures # 返回氣壓值列表

# 設定持續時間和節流水平
ac_time = 10  # 例如,10秒
temp = 30  # 根據需要調整這個值

# 讓無人機起飛
drone.takeoff()

# 記錄氣壓值
presure_list = record(ac_time)

# 在選定的持續時間內以指定的節流水平向上加速
drone.set_throttle(temp)
time.sleep(ac_time)

# 停止無人機並降落
drone.land()

# 列印氣壓值
for i, pressure in enumerate(presure_list):
    print(f"第{i+1}秒: 氣壓值 = {pressure}")

# 使用某些工具來測量無人機的高度,並將這些數值與記錄的氣壓值進行比較