1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

1. はじめに

dSPACEとarduinoとをシリアル通信するための方法をまとめました.
今回はPythonで実装しますが,プラットフォームの端子とSimulinkのシリアル通信用のブロックでも実装できるような気もしています.

2. メソッド

pyserialを使います.
シリアル通信を無限ループ内で実行する場合は抜けるためにkeyboardライブラリもいれましょう.

3. 記述例

4自由度のアームのエンコーダ角度情報を送信するプログラム

  • マイナスの場合は360度から引いて正の値で表現
  • 画面のフリーズを防ぐためにスレッド使用
  • 無限ループから抜けるためのキーボード検知
import sys
import keyboard
import serial
import time
from win32com.client import Dispatch, DispatchWithEvents
from dspace.com.threads import STAThread

MyPlatform = Application.ActiveExperiment.Platforms["Platform"]

def main():
    Angle = [0.0, 0.0, 0.0, 0.0]
    Angle[0] = MyPlatform.ActiveVariableDescription.Variables['Platform()://Model Root/EncoderSubsystem/angle [deg]1/In1']
    Angle[1] = MyPlatform.ActiveVariableDescription.Variables['Platform()://Model Root/EncoderSubsystem/angle [deg]2/In1']
    Angle[2] = MyPlatform.ActiveVariableDescription.Variables['Platform()://Model Root/EncoderSubsystem/angle [deg]3/In1']
    Angle[3] = MyPlatform.ActiveVariableDescription.Variables['Platform()://Model Root/EncoderSubsystem/angle [deg]4/In1']

    # Start thread.
    print("[python] Start serial communication.")
    serialSendThread = STAThread(Hoge, "Hoge", (Angle,Application))
    serialSendThread.start()

def Hoge(Angle, Application):
    while (True):
        angles = [(int)(Angle[0].ValueConverted), \
            (int)(Angle[1].ValueConverted),	\
            (int)(Angle[2].ValueConverted),	\
            (int)(Angle[3].ValueConverted)]

        for	i in range(0, len(angles)):
            if (angles[i] <	0):
                angles[i] =	360	- angles[i]
	
        # example: b/090180045000
        #print(str(angles[0]) + ", "	+ str(angles[1]) + ", "	+ str(angles[2]) + ", "	+ str(angles[3]))
        serialCommand =	str(angles[0]).zfill(3)	+ str(angles[1]).zfill(3) +	str(angles[2]).zfill(3)	+ str(angles[3]).zfill(3) +	"\r\n"
        writeSer = serial.Serial('COM4', 115200, timeout=3)
        writeSer.write(serialCommand.encode())
        writeSer.close()
        time.sleep(0.05)
        
        # Stop serial communication by escape key.
        if (keyboard.is_pressed('escape')):
            print("[python] Stop serial communication.")
            sys.exit()

if __name__ == "__main__":
    main()
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?