Microbit Python 課程介紹 --Network

2017-07-22 20:10

Microbit Python 課程介紹 --Network

Microbit Shop

可以將設備連接在一起以發送和接收消息。 這被稱為網絡。 互聯網絡的網絡被稱為互聯網。 互聯網是所有互聯網的互聯網。

網絡很難,這反映在下面描述的程序中。 然而,這個項目的美麗之處在於它包含了您需要了解的網絡編程的所有常見方面。 它也非常簡單和有趣。

但首先,讓我們設置場景... (But first, let’s set the scene...)

Connection

想像一下網絡作為一系列的層次。 最底層是溝通最基本的方面:需要一種信號從一個設備到另一個設備的方式。 有時這是通過無線電連接完成的,但在這個例子中,我們只需要使用兩根線。

在這個基礎上,我們可以在網絡堆棧(the network stack)中構建所有其他層。

如圖所示,藍色和紅色micro:bits通過鱷魚導線連接。 兩者均使用引腳1作為輸出,引腳2用於輸入。 一個設備的輸出連接到另一個設備的輸入。 這有點像知道拿著電話聽筒的方式 - 一端有麥克風(輸入),另一端有揚聲器(輸出)。 通過麥克風錄製您的聲音是從另一個人的揚聲器播放的。 如果你握住手機錯誤的方式,你會得到奇怪的結果!

在這種情況下完全一樣:您必須正確連接電線!

Signal

 

網絡堆棧(the network stack )中的下一層是信號。 這通常取決於連接的特性。 在我們的例子中,它是簡單的數字開啟和關閉信號通過IO引腳發送下來的電線。

如果你還記得,可以這樣使用IO引腳:

pin1.write_digital(1)  # switch the signal on

pin1.write_digital(0)  # switch the signal off

input = pin2.read_digital()  # read the value of the signal (either 1 or 0)

 

The next step involves describing how to use and handle a signal. For that we need a...

下一步涉及到如何使用和處理信號。 為了我們需要...

Protocol

如果你見過女王,那麼你應該如何表現呢? 例如,當她到達時,你可以鞠躬或cur sey,如果她禮貌地握著她的手,把她稱為“你的威嚴”,然後稱為“女士”等等。 這套規則稱為皇家協議。 一個協議解釋瞭如何表現出特定的情況(如遇見女王)。 一個協議是預先定義的,以確保每個人都明白在發生特定情況之前發生了什麼。

正是由於這個原因,我們定義和使用通過計算機網絡傳達消息的協議。 計算機需要手頭同意如何發送和接收消息。 也許最著名的協議是由萬維網使用的超文本傳輸協議(HTTP)。

發送消息(預先計算機)的另一個著名協議是莫爾斯電碼。 它定義瞭如何通過長或短持續時間的開/關信號發送基於字符的消息。 通常這樣的信號會被吹噓。 長時間稱為破折號(-),而短持續時間是點(.)。 通過組合虛線和點莫爾斯定義了發送字符的方式。 例如,這裡是如何定義標準莫爾斯字母表:

.-    A     ---   J     ...   S     .----  1      ----.  9

-...  B     -.-   K     -     T     ..---  2      -----  0

-.-.  C     .-..  L     ..-   U     ...--  3

-..   D     --    M     ...-  V     ....-  4

.     E     -.    N     .--   W     .....  5

..-.  F     ---   O     -..-  X     -....  6

--.   G     .--.  P     -.--  Y     --...  7

....  H     --.-  Q     --..  Z     ---..  8

..    I     .-.   R

Given the chart above, to send the character “H” the signal is switched on four times for a short duration, indicating four dots (....). For the letter “L” the signal is also switched on four times, but the second signal has a longer duration (.-..).

給出上面的圖表,要發送字符“H”,信號在短時間內四次打開,表示四個點four dots (....)。 對於字母“L”,信號也被接通四次,但第二個信號具有較長的持續時間(.-..)。

顯然,信號的時機很重要:我們需要從一個破折號上點一下。 這是一個協議的另一個要點,要約定這樣的事情,所以每個人的協議的實現將與每個人都可以一起工作。 在這種情況下,我們只會說

·        A signal with a duration less than 250 milliseconds is a dot.

·        A signal with a duration from 250 milliseconds to less than 500 milliseconds is a dash.

·        Any other duration of signal is ignored.

·        A pause / gap in the signal of greater than 500 milliseconds indicates the end of a character.

•持續時間小於250毫秒的信號是一個點。

•持續時間從250毫秒到小於500毫秒的信號是一個破折號。

•任何其他持續時間的信號都被忽略。

•大於500毫秒的信號中的暫停/間隙表示字符的結尾。

以這種方式,發送一個字母“H”被定義為四個“開”信號(four “on” signals),每個持續不超過250毫秒,之後是大於500毫秒的暫停(指示字符結束)。

Message

我們終於在一個可以建立信息的階段 - 這個消息實際上意味著我們人類的一些信息。 這是我們網絡堆棧中最頂層的層。

使用上面定義的協議,我可以將以下物理線序列發送到另一個micro:bit:

...//.-.. /...-/---/.--/---/ .. /...-/ - ..

你能說出這個說法嗎?

Application

這是非常好的網絡堆棧(a network stack),但您還需要一種與之交互的方式 - 某種形式的應用程序來發送和接收消息。 雖然HTTP是有趣的,但大多數人不了解它,並讓他們的網絡瀏覽器處理它 - 萬維網的底層網絡堆棧是隱藏的(應該是)。

那麼我們應該為the BBC micro:bit寫什麼樣的應用程序? 從用戶的角度來看,應該如何工作

顯然,要發送消息,您應該可以輸入點和破折號(我們可以使用按鈕A)。 如果我們想看到我們發送或剛剛收到的消息,我們應該可以觸發它在顯示器上滾動(我們可以使用按鈕B)。 最後,這是莫爾斯電碼,如果附上一個揚聲器,我們應該能夠在用戶輸入消息時發出嘟嘟聲作為一種聽覺反饋。

The End Result

這是程序,在所有的榮耀和註釋與大量的意見,所以你可以看到發生了什麼:

from microbit import *

import music

 

 

# A lookup table of morse codes and associated characters.

MORSE_CODE_LOOKUP = {

    ".-": "A",

    "-...": "B",

    "-.-.": "C",

    "-..": "D",

    ".": "E",

    "..-.": "F",

    "--.": "G",

    "....": "H",

    "..": "I",

    ".---": "J",

    "-.-": "K",

    ".-..": "L",

    "--": "M",

    "-.": "N",

    "---": "O",

    ".--.": "P",

    "--.-": "Q",

    ".-.": "R",

    "...": "S",

    "-": "T",

    "..-": "U",

    "...-": "V",

    ".--": "W",

    "-..-": "X",

    "-.--": "Y",

    "--..": "Z",

    ".----": "1",

    "..---": "2",

    "...--": "3",

    "....-": "4",

    ".....": "5",

    "-....": "6",

    "--...": "7",

    "---..": "8",

    "----.": "9",

    "-----": "0"

}

 

 

def decode(buffer):

    # Attempts to get the buffer of Morse code data from the lookup table. If

    # it's not there, just return a full stop.

    return MORSE_CODE_LOOKUP.get(buffer, '.')

 

 

# How to display a single dot.

DOT = Image("00000:"

            "00000:"

            "00900:"

            "00000:"

            "00000:")

 

 

# How to display a single dash.

DASH = Image("00000:"

             "00000:"

             "09990:"

             "00000:"

             "00000:")

 

 

# To create a DOT you need to hold the button for less than 250ms.

DOT_THRESHOLD = 250

# To create a DASH you need to hold the button for less than 500ms.

DASH_THRESHOLD = 500

 

 

# Holds the incoming Morse signals.

buffer = ''

# Holds the translated Morse as characters.

message = ''

# The time from which the device has been waiting for the next keypress.

started_to_wait = running_time()

 

 

# Put the device in a loop to wait for and react to key presses.

while True:

    # Work out how long the device has been waiting for a keypress.

    waiting = running_time() - started_to_wait

    # Reset the timestamp for the key_down_time.

    key_down_time = None

    # If button_a is held down, then...

    while button_a.is_pressed():

        # Play a beep - this is Morse code y'know ;-)

        music.pitch(880, 10)

        # Set pin1 (output) to "on"

        pin1.write_digital(1)

        # ...and if there's not a key_down_time then set it to now!

        if not key_down_time:

            key_down_time = running_time()

    # Alternatively, if pin2 (input) is getting a signal, pretend it's a

    # button_a key press...

    while pin2.read_digital():

        if not key_down_time:

            key_down_time = running_time()

    # Get the current time and call it key_up_time.

    key_up_time = running_time()

    # Set pin1 (output) to "off"

    pin1.write_digital(0)

    # If there's a key_down_time (created when button_a was first pressed

    # down).

    if key_down_time:

        # ... then work out for how long it was pressed.

        duration = key_up_time - key_down_time

        # If the duration is less than the max length for a "dot" press...

        if duration < DOT_THRESHOLD:

            # ... then add a dot to the buffer containing incoming Morse codes

            # and display a dot on the display.

            buffer += '.'

            display.show(DOT)

        # Else, if the duration is less than the max length for a "dash"

        # press... (but longer than that for a DOT ~ handled above)

        elif duration < DASH_THRESHOLD:

            # ... then add a dash to the buffer and display a dash.

            buffer += '-'

            display.show(DASH)

        # Otherwise, any other sort of keypress duration is ignored (this isn't

        # needed, but added for "understandability").

        else:

            pass

        # The button press has been handled, so reset the time from which the

        # device is starting to wait for a  button press.

        started_to_wait = running_time()

    # Otherwise, there hasn't been a button_a press during this cycle of the

    # loop, so check there's not been a pause to indicate an end of the

    # incoming Morse code character. The pause must be longer than a DASH

    # code's duration.

    elif len(buffer) > 0 and waiting > DASH_THRESHOLD:

        # There is a buffer and it's reached the end of a code so...

        # Decode the incoming buffer.

        character = decode(buffer)

        # Reset the buffer to empty.

        buffer = ''

        # Show the decoded character.

        display.show(character)

        # Add the character to the message.

        message += character

    # Finally, if button_b was pressed while all the above was going on...

    if button_b.was_pressed():

        # ... display the message,

        display.scroll(message)

        # then reset it to empty (ready for a new message).

        message = ''

 

你會如何改善它? 你可以改變一個點和一個破折號的定義,這樣快的莫爾斯密碼用戶可以使用它嗎?(Can you change the definition of a dot and a dash so speedy Morse code users can use it?) 如果兩台設備同時發送,會發生什麼? 你可以做些什麼來處理這種情況?

Microbit 台灣 商店購買

Microbit 中文 課程 : Python , Javascript物聯網

              中國


 

—————

返回