This is sim.c in view mode; [Download] [Up]
/* * Simulate the difference equations which describe an * 4th-order delta-sigma modulator. */ #include <stdio.h> #include <math.h> #define ORDER 4 main(){ double beta[] = { -0.000944282, -0.0228947, -0.184512, -0.764231 }, gamma[] = { 0.000278509, 0.00178657 }, /* alpha0 must be slightly different from beta[0] ensure a dc gain of 1 */ alpha0 = 0.000996165, c[] = { 1, 1, 1, 1 }, scaling[] = { 0.02, 0.2, 1, 1.5 }; /* You may need to change the initial value of y to match simulations of your circuit. */ double u, x[ORDER], xx, y=0, zm1y=0, max[ORDER]; int i; /* initial state = 0 */ for( i=0; i<ORDER; ++i ){ x[i]=0; max[i]=0; } #ifdef SCALED /* Apply the scaling factors. */ alpha0 /= scaling[0]; for( i=0; i<ORDER; ++i ){ beta[i] /= scaling[i]; if( i<ORDER-1 ) c[i] = scaling[i]/scaling[i+1]; else c[i] = scaling[i]; } for( i=0; i<ORDER/2; ++i ) gamma[i] *= scaling[2*i+1]/scaling[2*i]; #endif #ifdef PRINTSCALEDVALUES printf("The scaling factors are: "); for( i=0; i<ORDER; ++i ) printf("%g ", scaling[i]); printf("\n"); printf("The a0 coefficient is: %g\n", alpha0); printf("The b coefficients are: "); for( i=0; i<ORDER; ++i ) printf("%g ", beta[i]); printf("\n"); printf("The g coefficients are: "); for( i=0; i<ORDER/2; ++i ) printf("%g ", gamma[i] ); printf("\n"); printf("The c coefficients are: "); for( i=0; i<ORDER; ++i ){ printf("%g ", c[i]); } printf("\n"); #else while( scanf("%lf",&u) > 0){ /* At the top of the loop, we have x[0,2](n), x[1,3](n-1) and y(n-1) */ x[1] += beta[1]*y + c[0]*x[0]; x[3] += beta[3]*y + c[2]*x[2]; x[0] += alpha0*u + beta[0]*y - gamma[0]*x[1]; x[2] += c[1]*x[1] + beta[2]*y - gamma[1]*x[3]; xx = c[3]*x[3]; y = (xx>=0)?1:-1; /* At the bottom of the loop, we have x[0,2](n+1), x[1,3](n) and y(n) */ #ifdef COMPARATORINPUT printf("%g\n", xx); #else #ifndef MAXIMA printf("%g\n", y); #endif #endif #ifdef MAXIMA /* check for maxima */ for(i=0; i<ORDER; ++i){ double tmp=fabs(x[i]); if( tmp > max[i] ) max[i]=tmp; } #endif } #ifdef MAXIMA for(i=0; i<ORDER; ++i) printf("%g\t", max[i]); printf("\n"); #endif #endif }
These are the contents of the former NiCE NeXT User Group NeXTSTEP/OpenStep software archive, currently hosted by Netfuture.ch.