EmbeddedRelated.com
Code Snippets
The 2024 Embedded Online Conference

Additive White Gaussian Noise Generator

Dr Cagri Tanriover March 3, 20131 comment Coded in C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define PI 3.1415926536

double AWGN_generator()
{/* Generates additive white Gaussian Noise samples with zero mean and a standard deviation of 1. */
 
  double temp1;
  double temp2;
  double result;
  int p;

  p = 1;

  while( p > 0 )
  {
	temp2 = ( rand() / ( (double)RAND_MAX ) ); /*  rand() function generates an
                                                       integer between 0 and  RAND_MAX,
                                                       which is defined in stdlib.h.
                                                   */

    if ( temp2 == 0 )
    {// temp2 is >= (RAND_MAX / 2)
      p = 1;
    }// end if
    else
    {// temp2 is < (RAND_MAX / 2)
       p = -1;
    }// end else

  }// end while()

  temp1 = cos( ( 2.0 * (double)PI ) * rand() / ( (double)RAND_MAX ) );
  result = sqrt( -2.0 * log( temp2 ) ) * temp1;

  return result;	// return the generated random sample to the caller

}// end AWGN_generator()

Little Endian Converter Functions

Dr Cagri Tanriover February 18, 20131 comment Coded in C
unsigned short u16ToLittleEndian( unsigned short u16input )
{/* Use this function to convert a 16-bit number into little endian. */

  return( (u16input >> 8) ^ (u16input << 8) );

}// end u16ToLittleEndian()

unsigned long u32ToLittleEndian( unsigned long u32input )
{/* Use this function to convert a 32-bit number into little endian. */

  return( (u32input >> 24)
           ^ ( (u32input >> 8) & 0x000FF00 )
           ^ ( (u32input << 8) & 0x00FF0000 )
           ^ ( (u32input << 24) & 0xFF000000 )
         );

}// end u32ToLittleEndian()

Binary Coded Decimal (BCD) - ASCII Converter

Dr Cagri Tanriover February 12, 2013 Coded in C
char bcdToAscii( unsigned char bcdNibble )
{
  char result;
	
  if( bcdNibble < 10 )
  {// valid BCD input. ( [0,9] is the valid range for BCD input. )
    result = (char)( bcdNibble + 48 );	// +48 is applicable to [0,9] input range.
  }// end if
  else
  {// invalid input
    result = '0';
  }// end else

  return( result );
	
}// end bcdToAscii()

unsigned char asciiToBcd( char asciiByte )
{/* Converts an input ASCII character (expected within the [ '0' - '9' ] range) into its BCD counterpart. */
	
  unsigned char result;

  if( 
      asciiByte >= '0'
      && asciiByte <= '9'
  )
  {// range check passed.
    result = (unsigned char)(asciiByte - 48);	// -48 offset gives the decimal value of the ASCII character.
  }
  else
  {// range check failed.
    result = 0;
  }// end else

  return( result );
	
}// end asciiToBcd()

The 2024 Embedded Online Conference