バージョン情報
Arduino Uno , Arduino IDE 1.0.5 , windows 8.1 , python 3.4 , pyserial 2.7
今回は久しぶりにPCとArduinoの通信。pythonに挑戦してみた。
pythonから文字列を送信し、Arduinoに接続したTFT液晶に表示してみた。
回路
前回作ったものを流用。
ソースコード
Arduino側
受信バッファに受信した文字数をカウントし、char配列に格納しTFT液晶に表示するプログラムをつくってみた。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include <TFT.h> // Arduino LCD library #include <SPI.h> // pin definition for the Uno #define cs_TFT 5 #define dc 9 #define rst 8 TFT TFTscreen = TFT(cs_TFT, dc, rst); int cnt_buf; void setup() { Serial.begin( 9600 ); // Put this line at the beginning of every sketch that uses the GLCD: TFTscreen.begin(); TFTscreen.background( 0 , 0 , 0 ); // write the static text to the screen TFTscreen.stroke( 255 , 255 , 255 ); TFTscreen.setTextSize( 2 ); TFTscreen.text( "start" , 0 , 0 ); } void loop() { //受信したら if (Serial.available() > 0 ){ delay( 100 ); cnt_buf = Serial.available(); //受信文字数 char charA_out[cnt_buf+ 1 ]; for ( int iii = 0 ; iii < cnt_buf; iii++){ charA_out[iii] = Serial.read(); } charA_out[cnt_buf] = '\0' ; //終端文字 Serial.print(charA_out); //そのまま返答 TFTscreen.background( 0 , 0 , 0 ); TFTscreen.text(charA_out, 0 , 20 ); } } |
PC側
pythonで文字列をcomポートから出力するプログラム。
“hello”の前にbがないとエラーになったので要注意。
1 2 3 4 5 6 7 8 9 10 | # -*- coding: utf-8 -*- import time from serial import Serial com = Serial(port = "com3" ,baudrate = 9600 ) time.sleep( 2 ); com.write(b "hello" ) com.close() |
動作確認
無事にTFT液晶にhelloと表示された。
pythonのコードの短さはすごいな。もっと使い込もう。
「Arduinoシリアル通信 その3:python」への1件のフィードバック