« とりあえず現物 | 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

コンパイル時のポイントとしては、

といったところです(これで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が干渉しているようですが、当面ソケットは用いないため放置します(識者の方、アドバイスをいただければ幸いです)。

Topics: Cygwin, FT232R |

2 Responses to “Bit Bang用DLLの作製”

  1. Twitted by zetamatta Says:
    5 月 11th, 2009 at 2:40 AM

    [...] This post was Twitted by zetamatta - Real-url.org [...]


  2. Twitter Trackbacks for Bit Bang用DLLの作製 | PIC+R workbench [atword.jp] on Topsy.com Says:
    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 はんだ付け オシロスコープ オシロスコープもどき マイクロアレイ 工 [...]


Comments

*
画像に書かれた文字を入力してください

スパム対策用画像
ログインすると画像認証なしで投稿できます

ホットワード padding margin 統計 処理 PICマイコン
割引クーポンまとめ情報 - クー割