« とりあえず現物 | Home | RからラッパーDLLを叩く »
Bit Bang用DLLの作製
By kmgs | 10 月 28, 2008
Bit Bangモードを使用するためには、ftd2xx.dllを叩く必要があります。ftd2xx.dllのAPIドキュメントは、FTDI Chipのウェブサイトにあります。
しかし、RからDLLを呼ぶ場合、引数はポインタのみしか使えないという制約があるため、使い方にはちょっとした工夫が必要となります。今回はCygwinを用い、RでBit Bangモードを使用するためのラッパーDLLを作成します(エラーハンドリングは最低限のみしか行っていませんので注意)。
#include <stdio.h> #include <w32api/windows.h> #include "ftd2xx.h" #define CHUNK_SIZE 4096 static FT_HANDLE hFt; /* デバイス初期化 */ void bb_init(int *baud, unsigned char *mask, unsigned char *mode, int *ret) { if (FT_Open(0, &hFt) != FT_OK) { *ret = 1; return; } if (FT_SetBaudRate(hFt, *baud) != FT_OK) { *ret = 2; return; } if (FT_SetBitMode(hFt, *mask, *mode) != FT_OK) { *ret = 3; return; } } /* Bit BangのI/O */ void bb_send_recv(unsigned char *out, unsigned char *in, int *len, int *ret) { unsigned long num_read; unsigned long tmp; unsigned long written; int count = 0; while (*len - count >= CHUNK_SIZE) { if (FT_Write(hFt, out + count, CHUNK_SIZE, &written) != FT_OK) { *ret = 1; return; } num_read = 0; while (num_read <written) { if (FT_Read(hFt, in + count + num_read, written - num_read, &tmp) != FT_OK) { *ret = 2; return; } num_read += tmp; } count += written; } while (*len - count > 0) { if (FT_Write(hFt, out + count, *len - count, &written) != FT_OK) { *ret = 1; return; } num_read = 0; while (num_read <written) { if (FT_Read(hFt, in + count + num_read, written - num_read, &tmp) != FT_OK) { *ret = 2; return; } num_read += tmp; } count += written; } } /* デバイスを閉じる */ void bb_close(int *ret) { if (FT_Close(hFt) != FT_OK) { *ret = 1; } }
これを適当なファイル(例えばtest.c)とし、gccでコンパイルします。
$ gcc test.c ftd2xx.lib -mno-cygwin -I/usr/include -shared -Wl,--exclude-libs,ALL -o test.dll
コンパイル時のポイントとしては、
- test.cと同じディレクトリにftd2xx.h、ftd2xx.libおよびftd2xx.dllを置いておく (やや手抜き)
- -I/usr/includeはWin32APIのヘッダファイルを読みに行くために必要
- -mno-cygwinは、Windows環境で単独動作するために必要
- -sharedはDLLを作製するためのオプション
- -Wl,--exclude-libs,ALLはftd2xx.libのシンボルを再エクスポートしないために必要、これがないと"Cannot export FTD2XX_NULL_THUNK_DATA: symbol not found"などというエラーに悩まされる
といったところです(これで2日くらいハマった)。また、
In file included from /usr/include/w32api/windows.h:98,
from test.c:2:
/usr/lib/gcc/i686-pc-mingw32/3.4.4/../../../../include/w32api/winsock2.h:103:2: warning: #warning "fd_set and associated macros have been defined in sys/types. This may cause runtime problems with W32 sockets"
といった警告が出るため、Mingw環境のw32api周りと通常のw32apiが干渉しているようですが、当面ソケットは用いないため放置します(識者の方、アドバイスをいただければ幸いです)。

5 月 11th, 2009 at 2:40 AM
[...] This post was Twitted by zetamatta - Real-url.org [...]
9 月 2nd, 2009 at 7:44 PM
[...] Bit Bang用DLLの作製 | PIC+R workbench www3.atword.jp/kmgs/2008/10/28/bit-bang%E7%94%A8dll%E3%81%AE%E4%BD%9C%E8%A3%BD – view page – cached はんだ付け オシロスコープ オシロスコープもどき マイクロアレイ 工 [...]