0
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?

異なる型を返すメソッド

Last updated at Posted at 2024-11-21

自分用のメモ.
しばらくPythonやJavaScriptを触ってた時期に書き殴って放置してたC++のコード.
仲間から問い合わせがあって,リモートで会話しながら,「ああ,それならこれで動くはず.. あっ,あれ?あれぇ?」て感じでバグ発見.

readメソッドを呼ぶときにrawが省かれてたらマイクロボルト値を,trueに指定されてたら整数値を返すつもりだったけど(^^;
そりゃぁ動かんわwww

ていうか見るからに簡潔さに欠けるコードだし,自分のアホさ加減に呆れる.
違う型は返せないし,delay指定を行える関数を別に作ってしまってる.

class NAFE13388_Base : public SPI_for_AFE{
	virtual double read( int ch, float delay, bool raw = false );
	virtual double read( int ch, bool raw = false );
}
...
double NAFE13388_Base::read( int ch, float delay, bool raw )
{
	start( ch );
	wait( delay );
	
	return read( ch, raw );
};

double NAFE13388_Base::read( int ch, bool raw )
{
	if ( raw )
		return read_r24( 0x2040 + ch );
	else
		return read_r24( 0x2040 + ch ) * coeff_uV[ ch ];
}

ほんで書き直したのがコレ.
まぁまぁ簡潔.readメソッドを呼ぶ際には型を明示しなければならないのが面倒だけど.. たとえばread<int32_t>( 0, 0.01 )みたいに.
でもそれぞれ別の関数として定義しておくよりはずっと良いんではないかな.

template<> 
int32_t NAFE13388_Base::read( int ch, float delay )
{
	start_and_delay( ch, delay );
	return read_r24( 0x2040 + ch );
};

template<>
double NAFE13388_Base::read( int ch, float delay )
{
	return read<int32_t>( ch, delay ) * coeff_uV[ ch ];
};

void NAFE13388_Base::start_and_delay( int ch, float delay )
{
	if ( delay >= 0.0 )
	{
		start( ch );
		wait( delay );
	}
}

これを使うmain()の中身はこんな感じ.
実際のサンプルコードではrawmicrovoltのような型名を定義しといた.

#include	"r01lib.h"
#include	"NAFE13388_UIM.h"

SPI				spi( D11, D12, D13, D10 );	//	MOSI, MISO, SCLK, CS
NAFE13388_UIM	afe( spi );

int main( void )
{
	printf( "***** Hello, NAFE13388 UIM board! *****\r\n" );

	spi.frequency( 1000 * 1000 );
	spi.mode( 1 );

	afe.begin();

	afe.logical_ch_config( 0, 0x1070, 0x0084, 0x2900, 0x0000 );
	afe.logical_ch_config( 1, 0x2070, 0x0084, 0x2900, 0x0000 );

	while ( true )
	{		
		printf( "microvolt: %11.2f, %11.2f\r\n", afe.read<double>(   0, 0.01 ), afe.read<double>(  1, 0.01 ) );
		printf( "raw:       %ld, %ld\r\n",       afe.read<int32_t>(  0, 0.01 ), afe.read<int32_t>( 1, 0.01 ) );

		wait( 0.05 );
	}
}

コードの置き場所:
https://github.com/teddokano/UIM_NAFE13388_FRDM_MCX/

参考にした記事:
https://qiita.com/SaitoAtsushi/items/d8ae623663878feeb181

0
0
2

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
0
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?