ツタンラーメンの忘備録

プログラミングや精神疾患、ラーメンについて書いていきます。たぶん。

ArduinoとpythonのSerial通信

基本形。ほんとに単純化した者。
pythonのコードを記載しておく。Arduinoは方位センサを使っている。

pip install pyserial

して

import serial
import re

def main():
    with serial.Serial('COM3',9600,timeout=1) as ser:
        while True:
            c = ser.readline()
            de = c.decode('utf-8') #バイトから文字として認識できる形に。
            m = re.match("\-*\d+", str(de))
            if(m != None):
                print(m.group())
            else:
                pass
                #print(type(m))
        ser.close()

if __name__ == "__main__":
    main()

ちなみに方位センサのコードは

#include <Wire.h>
#include "skHMC5883L.h"
#define SENSOR_ADRS     0x1E
skHMC5883L  Compass(SENSOR_ADRS);

void setup() {
  int ans;
  Serial.begin(9600);
  Wire.begin();
  ans = Compass.Begin() ;
  if (ans == 0) Serial.println("Initialization normal") ;
  else {
    Serial.print("Initialization abnormal ans=") ;
    Serial.println(ans) ;
  }
}

void loop() {
  int ans;
  float deg;
  ans = Compass.SingleRead(&deg,6.6);
  if(ans == 0){
    Serial.println(RowX);
    Serial.println(RowY);
    Serial.println(RowZ);
  }else Serial.println("NG");
  delay(1000);
}

別にサンプルコードのままだから特に何も。