製作Arduino to Scratch2自定積木
原理其實相當簡單,以下是訊息處理的三個步驟:
  1. GaussSense_S2A.ino 將資料透過字串傳給Serial port。
  1. 由GaussSense_helper.py將Serial port的資料接起後,對資料去分段,並轉換成Http格式後,由新開的port(50100)傳出資料。
  1. 最後,Scratch2依照GaussSense_s2e定義好的資料格式,對從新開的Http port(50100)擷取到的資料分析,並將分析的結果輸入到Scratch積木當中。
以下用簡化的程式碼解釋具體做法:

透過字串傳給Serial port:在GaussSense_S2A Firmware當中會看到這樣的資料結構
Serial.print("NX:");
Serial.print((int)basicNorth.getX());
Serial.print(", NY:");
Serial.print((int)basicNorth.getY());
Serial.print(", NI:");
Serial.print((int)(basicNorth.getIntensity() * 200 / 127));
Serial.print('\n');
實際在Serial Monitor當中會看到的結果為(以NX = 250, NY = 130, NI = 30為例)
NX:250, NY:130, NI:30’\n’

GaussSense_helper.py 透過以下資料將Serial port的資料接起後,對資料進行分段
# skip over the / in the command
cmd = self.path[1:]
# create a list containing the command and all of its parameters
cmd_list = cmd.split('/')

result = ''
if  cmd.startswith("poll"):
    try:
        Data.connection.reset_input_buffer()
        string = Data.connection.readline().decode() 
        temp_list = string.strip().split(',')

        value = []
        for i in temp_list:
            value.append(i.split(':')[1])

        result = 'NX ' + value[0] + '\r\n'
        result = result + 'NY ' + value[1] + '\r\n'
        result = result + 'NI ' + value[2] + '\r\n''
        
    except:
        pass

分段完成後,轉換成Http格式(加上標頭),並由新開的port(50100)傳出資料。
http_response = "HTTP/1.1 200 OK" + '\r\n'
http_response += "Content-Type: text/html; charset=utf-8" + '\r\n'
http_response += "Content-Length" + str(len(result)) + '\r\n'
http_response += "Access-Control-Allow-Origin: *" + '\r\n'
http_response += '\r\n'

if result != '':