void enx(real_t x, int n1, int n2, real_t a[]) { if (x <= 1.5) { real_t ei(real_t); int i; real_t w,e; w = -ei(-x); if (n1 == 1) a[1]=w; if (n2 > 1) e=exp(-x); for (i=2; i<=n2; i++) { w=(e-x*w)/(i-1); if (i >= n1) a[i]=w; } } else { int i,n; real_t w,e,an; n=ceil(x); if (n <= 10) { real_t f,w1,t,h,p[20]; p[2] =0.37534261820491e-1; p[11]=0.135335283236613; p[3] =0.89306465560228e-2; p[12]=0.497870683678639e-1; p[4] =0.24233983686581e-2; p[13]=0.183156388887342e-1; p[5] =0.70576069342458e-3; p[14]=0.673794699908547e-2; p[6] =0.21480277819013e-3; p[15]=0.247875217666636e-2; p[7] =0.67375807781018e-4; p[16]=0.911881965554516e-3; p[8] =0.21600730159975e-4; p[17]=0.335462627902512e-3; p[9] =0.70411579854292e-5; p[18]=0.123409804086680e-3; p[10]=0.23253026570282e-5; p[19]=0.453999297624848e-4; f=w=p[n]; e=p[n+9]; w1=t=1.0; h=x-n; i=n-1; do { f=(e-i*f)/n; t = -h*t/(n-i); w1=t*f; w += w1; i--; } while (fabs(w1) > 1.0e-15*w); } else { real_t *allocate_real_vector(int, int); void free_real_vector(real_t *, int); void nonexpenx(real_t, int, int, real_t []); real_t *b; b=allocate_real_vector(n,n); nonexpenx(x,n,n,b); w=b[n]*exp(-x); free_real_vector(b,n); } if (n1 == n2 && n1 == n) a[n]=w; else { e=exp(-x); an=w; if (n <= n2 && n >= n1) a[n]=w; for (i=n-1; i>=n1; i--) { w=(e-i*w)/x; if (i <= n2) a[i]=w; } w=an; for (i=n+1; i<=n2; i++) { w=(e-x*w)/(i-1); if (i >= n1) a[i]=w; } } } }
void StructuralFE2MaterialStatus :: copyStateVariables(const MaterialStatus &iStatus) { //static int num = 0; //printf("Entering StructuralFE2MaterialStatus :: copyStateVariables.\n"); this->oldTangent = true; // if ( !this->createRVE(this->giveNumber(), gp, mInputFile) ) { // OOFEM_ERROR("Couldn't create RVE"); // } StructuralMaterialStatus :: copyStateVariables(iStatus); ////////////////////////////// MaterialStatus &tmpStat = const_cast< MaterialStatus & >(iStatus); StructuralFE2MaterialStatus *fe2ms = dynamic_cast<StructuralFE2MaterialStatus*>(&tmpStat); if ( !fe2ms ) { OOFEM_ERROR("Failed to cast StructuralFE2MaterialStatus.") } this->mNewlyInitialized = fe2ms->mNewlyInitialized; // The proper way to do this would be to clone the RVE from iStatus. // However, this is a mess due to all pointers that need to be tracked. // Therefore, we consider a simplified version: copy only the enrichment items. Domain *ext_domain = fe2ms->giveRVE()->giveDomain(1); if ( ext_domain->hasXfemManager() ) { Domain *rve_domain = rve->giveDomain(1); XfemManager *ext_xMan = ext_domain->giveXfemManager(); XfemManager *this_xMan = rve->giveDomain(1)->giveXfemManager(); DynamicDataReader dataReader("fe2"); if ( ext_xMan != NULL ) { IRResultType result; // Required by IR_GIVE_FIELD macro std::vector<std::unique_ptr<EnrichmentItem>> eiList; //DynamicInputRecord *xmanRec = new DynamicInputRecord(); //ext_xMan->giveInputRecord(* xmanRec); //dataReader.insertInputRecord(DataReader :: IR_xfemManRec, xmanRec); // Enrichment items int nEI = ext_xMan->giveNumberOfEnrichmentItems(); for ( int i = 1; i <= nEI; i++ ) { EnrichmentItem *ext_ei = ext_xMan->giveEnrichmentItem(i); ext_ei->appendInputRecords(dataReader); InputRecord *mir = dataReader.giveInputRecord(DataReader :: IR_enrichItemRec, i); std :: string name; result = mir->giveRecordKeywordField(name); if ( result != IRRT_OK ) { mir->report_error(this->giveClassName(), __func__, "", result, __FILE__, __LINE__); } std :: unique_ptr< EnrichmentItem >ei( classFactory.createEnrichmentItem( name.c_str(), i, this_xMan, rve_domain ) ); if ( ei.get() == NULL ) { OOFEM_ERROR( "unknown enrichment item (%s)", name.c_str() ); } ei->initializeFrom(mir); ei->instanciateYourself(dataReader); eiList.push_back( std :: move(ei) ); } this_xMan->clearEnrichmentItems(); this_xMan->appendEnrichmentItems(eiList); rve_domain->postInitialize(); rve->forceEquationNumbering(); } } //printf("done.\n"); #if 0 Domain *newDomain = fe2ms->giveRVE()->giveDomain(1)->Clone(); newDomain->SetEngngModel(rve.get()); bool deallocateOld = true; rve->setDomain(1, newDomain, deallocateOld); //rve->giveDomain(1)->postInitialize(); rve->giveNumericalMethod(NULL)->setDomain(newDomain); rve->postInitialize(); //rve->forceEquationNumbering(); rve->initMetaStepAttributes( rve->giveMetaStep(1) ); rve->giveNextStep(); // Makes sure there is a timestep (which we will modify before solving a step) rve->init(); // std :: ostringstream name; // name << this->rve->giveOutputBaseFileName() << "-gp" << n; // this->rve->letOutputBaseFileNameBe( name.str() ); // n++; double crackLength = 0.0; XfemStructureManager *xMan = dynamic_cast<XfemStructureManager*>( rve->giveDomain(1)->giveXfemManager() ); if ( xMan ) { crackLength = xMan->computeTotalCrackLength(); } std :: ostringstream name; name << this->rve->giveOutputBaseFileName() << "-gp" << num << "crackLength" << crackLength; if ( this->domain->giveEngngModel()->isParallel() && this->domain->giveEngngModel()->giveNumberOfProcesses() > 1 ) { name << "." << this->domain->giveEngngModel()->giveRank(); } num++; this->rve->letOutputBaseFileNameBe( name.str() ); // Update BC this->bc = dynamic_cast< PrescribedGradientHomogenization * >( this->rve->giveDomain(1)->giveBc(1) ); #if 1 XfemSolverInterface *xfemSolInt = dynamic_cast<XfemSolverInterface*>(rve.get()); StaticStructural *statStruct = dynamic_cast<StaticStructural*>(rve.get()); if ( xfemSolInt && statStruct ) { //printf("Successfully casted to XfemSolverInterface.\n"); TimeStep *tStep = rve->giveCurrentStep(); EModelDefaultEquationNumbering num; int numDofsNew = rve->giveNumberOfDomainEquations( 1, num ); FloatArray u; u.resize(numDofsNew); u.zero(); xfemSolInt->xfemUpdatePrimaryField(*statStruct, tStep, u); // Set domain pointer to various components ... rve->giveNumericalMethod(NULL)->setDomain(newDomain); //ioEngngModel.nMethod->setDomain(domain); } // TimeStep *tStep = rve->giveNextStep(); // setTimeStep(tStep); // rve->solveYourselfAt(tStep); int numExpModules = rve->giveExportModuleManager()->giveNumberOfModules(); for ( int i = 1; i <= numExpModules; i++ ) { // ... by diving deep into the hierarchies ... :-/ VTKXMLExportModule *vtkxmlMod = dynamic_cast< VTKXMLExportModule * >( rve->giveExportModuleManager()->giveModule(i) ); if ( vtkxmlMod != NULL ) { vtkxmlMod->giveSmoother()->setDomain(newDomain); vtkxmlMod->givePrimVarSmoother()->setDomain(newDomain); } } #endif #endif }
bool convertFromPythonExisting(PyObject *lst, TExample &example) { PDomain dom=example.domain; if (PyOrExample_Check(lst)) { const TExample &orex = PyExample_AS_ExampleReference(lst); if (orex.domain != dom) dom->convert(example, orex); else example = orex; return true; } if (!PyList_Check(lst)) { PyErr_Format(PyExc_TypeError, "invalid argument type (expected list, got '%s)", lst ? lst->ob_type->tp_name : "None"); return false; } int const nvars = dom->variables->size() + dom->classVars->size(); if (Py_ssize_t(nvars) != PyList_Size(lst)) { PyErr_Format(PyExc_IndexError, "invalid list size (got %i, expected %i items)", PyList_Size(lst), nvars); return false; } Py_ssize_t pos = 0; TExample::iterator ei(example.begin()); TVarList::iterator vi(dom->variables->begin()); TVarList::const_iterator const ve(dom->variables->end()); TVarList::const_iterator const ce(dom->classVars->end()); while(vi != ce && vi != ve) { PyObject *li=PyList_GetItem(lst, pos++); if (!li) PYERROR(PyExc_SystemError, "can't read the list", false); if (PyOrValue_Check(li)) if (PyValue_AS_Variable(li) ? (PyValue_AS_Variable(li) != *vi) : (PyValue_AS_Value(li).varType=!(*vi)->varType) ) { PyErr_Format(PyExc_TypeError, "wrong value type for attribute no. %i (%s)", pos, (*vi)->get_name().c_str()); return false; } else *(ei++)=PyValue_AS_Value(li); else { if (li == Py_None) { *(ei++) = (*vi)->DK(); } else if (PyString_Check(li)) (*vi)->str2val(string(PyString_AsString(li)), *(ei++)); else if ((*vi)->varType==TValue::INTVAR) { if (PyInt_Check(li)) *(ei++)=TValue(int(PyInt_AsLong(li))); else { PyErr_Format(PyExc_TypeError, "attribute no. %i (%s) is ordinal, string value expected", pos, (*vi)->get_name().c_str()); return false; } } else if ((*vi)->varType==TValue::FLOATVAR) { float f; if (PyNumber_ToFloat(li, f)) *(ei++) = TValue(f); else { PyErr_Format(PyExc_TypeError, "attribute no. %i (%s) is continuous, float value expected", pos, (*vi)->get_name().c_str()); return false; } } else ei++; } if (++vi == ve) { vi = dom->classVars->begin(); } } return true; }
//=============================================== //=============================================== //=============================================== //=============================================== void main(void) { t0_init(); ei(); PEIE=1; di(); ei(); TRISB=0x00; PORTB=0x00; PORTC|=(1<<led_ERR); sci_init(); while (1) { if(bRXIN) { bRXIN=0; UART_IN(); } if(bit_100Hz) { bit_100Hz=0; in_read(); step_contr(); mdvr_drv(); but_drv(); but_an(); } if(bit_10Hz) { bit_10Hz=0; // out_out(); led_out(); err_drv(); prog_drv(); if(prog==p1) OUT(3,CMND,eeprom_read(DELAY1),eeprom_read(DELAY2),0,0,0); else if(prog==p1) OUT(3,CMND,eeprom_read(DELAY3),eeprom_read(DELAY4),0,0,0); } if(bit_1Hz) { bit_1Hz=0; } } }
int main() { assert(!checkPhiInRange(-0.9f,1.f,-1.f)); assert(!checkPhiInRange(0.9f,1.f,-1.f)); assert(checkPhiInRange(-1.1f,1.f,-1.f)); assert(checkPhiInRange(1.1f,1.f,-1.f)); assert(checkPhiInRange(-0.9f,-1.f,1.f)); assert(checkPhiInRange(0.9f,-1.f,1.f)); assert(!checkPhiInRange(-1.1f,-1.f,1.f)); assert(!checkPhiInRange(1.1f,-1.f,1.f)); assert(checkPhiInRange(-2.9f,-3.f,3.f)); assert(checkPhiInRange(2.9f,-3.f,3.f)); assert(!checkPhiInRange(-3.1f,-3.f,3.f)); assert(!checkPhiInRange(3.1f,-3.f,3.f)); assert(!checkPhiInRange(-2.9f,3.f,-3.f)); assert(!checkPhiInRange(2.9f,3.f,-3.f)); assert(checkPhiInRange(-3.1f,3.f,-3.f)); assert(checkPhiInRange(3.1f,3.f,-3.f)); for (float x=-10;x<10;x+=1.) for (float y=-10;y<10;y+=1.) for (float z=-10;z<10;z+=1.) { if (x==0 && y==0) continue; GlobalPoint p(x,y,z); // eta for (float eta=-4;eta<3.5; eta+=0.2) for (float deta=0.1;deta<2.; deta+=0.2) { EtaInterval ei(eta,eta+deta); auto in = ei.inside(p.basicVector()); auto e = etaFromXYZ(x,y,z); auto in2 = (e>eta) & (e<eta+deta); assert(in==in2); } //phi for (float phi=-6.001;phi<6.5; phi+=0.2) for (float dphi=-3.1;dphi<3.15; dphi+=0.2) { PhiInterval pi(phi,phi+dphi); auto in = pi.inside(p.basicVector()); auto ph = p.barePhi(); auto in2 = checkPhiInRange(ph,phi,phi+dphi); assert(in==in2); } { PhiInterval pi(3.f,-3.f); auto in = pi.inside(p.basicVector()); auto ph = p.barePhi(); auto it = ph>3.f || ph<-3.f; assert(in==it); auto in2 = checkPhiInRange(ph,3.f,-3.f); assert(in2==it); } { PhiInterval pi(3.f,4.f); auto in = pi.inside(p.basicVector()); auto ph = p.barePhi(); auto it = ph>3.f || ph< 4-2*M_PI; ; assert(in==it); auto in2 = checkPhiInRange(ph,3.f,4.f); assert(in2==it); } { PhiInterval pi(-1.f,1.f); auto in = pi.inside(p.basicVector()); auto ph = p.barePhi(); auto it = std::abs(ph)<1; assert(in==it); auto in2 = checkPhiInRange(ph,-1.f,1.f); assert(in2==it); } } return 0; }
void fuzix_main(void) { /* setup state */ inint = false; udata.u_insys = true; ramtop = PROGTOP; tty_init(); if (d_open(TTYDEV, O_NOCTTY) != 0) panic(PANIC_NOTTY); /* Sign on messages */ kprintf( "FUZIX version %s\n" "Copyright (c) 1988-2002 by H.F.Bower, D.Braun, S.Nitschke, H.Peraza\n" "Copyright (c) 1997-2001 by Arcady Schekochikhin, Adriano C. R. da Cunha\n" "Copyright (c) 2013-2015 Will Sowerbutts <*****@*****.**>\n" "Copyright (c) 2014-2015 Alan Cox <*****@*****.**>\nDevboot\n", uname_str); #ifndef SWAPDEV #ifdef PROC_SIZE maxproc = procmem / PROC_SIZE; /* Check we don't exceed the process table size limit */ if (maxproc > PTABSIZE) { kprintf("WARNING: Increase PTABSIZE to %d to use available RAM\n", maxproc); maxproc = PTABSIZE; } #else maxproc = PTABSIZE; #endif #else maxproc = PTABSIZE; #endif /* Used as a stop marker to make compares fast on process scheduling and the like */ ptab_end = &ptab[maxproc]; /* Parameters message */ kprintf("%dkB total RAM, %dkB available to processes (%d processes max)\n", ramsize, procmem, maxproc); bufinit(); fstabinit(); pagemap_init(); create_init(); /* runtime configurable, defaults to build time setting */ ticks_per_dsecond = TICKSPERSEC / 10; kputs("Enabling interrupts ... "); ei(); kputs("ok.\n"); /* get the root device */ root_dev = get_root_dev(); /* finish building argv */ complete_init(); /* initialise hardware devices */ device_init(); /* Mount the root device */ kprintf("Mounting root fs (root_dev=%d, r%c): ", root_dev, ro ? 'o' : 'w'); if (fmount(root_dev, NULLINODE, ro)) panic(PANIC_NOFILESYS); root = i_open(root_dev, ROOTINODE); if (!root) panic(PANIC_NOROOT); kputs("OK\n"); udata.u_cwd = i_ref(root); udata.u_root = i_ref(root); rdtime32(&udata.u_time); exec_or_die(); }
__inline int foo() { return ei(); }
void interrupt isr(void) { //var static bit isr_sel, bit_read; static char n; static signed char parity; //this ISR detects the falling edge created by the IR sensor (RC5 Start Bit). isr_sel = INTE && INTF; // test if interrupt is activated and requestet by INT Pin isr_sel = isr_sel && ! rc5_ready; // only start receiving a new frame if last one is processed if (isr_sel == 1) { LED_RECEIVE = 1; // set receiving LED //set up parameters to start reading of the command frame sent by the remote. //timer0 delays until we are somewhere in the middle of the next rc5 half data bit TMR0 = 0x00; TMR0IF = 0; TMR0IE = 1; parity = 0; // clear the parity bit rc5_data = 0; // clear last rc5_datad frame n = 0; // set index to 0 read bits INTE = 0; // disable edge detection (must be activated again once receiving of the command is completed) } //this ISR reads values from RB0, stores them and creates the parity. It doesn't interpret the manchester code, it just stores a bit every 0,9ms isr_sel = TMR0IE && TMR0IF; if (isr_sel == 1) { //one RC5 frame in manchester coding is 26 bit long (start is not stored), therefore we rotate 26 bits (0...25) into rc5_data register if (n < 26) { /* start new wait period. Delay time should be ~0,9 ms. todo: tweak here if remote doesn't work properly. */ TMR0 = 0x28; bit_read = IR_IN; // store the read bit in memory to be independend from changes on the actual port pin //create parity. As manchester code is DC free, after one complete frame result must be 0. Otherwise frame invalid if (bit_read == 1) { parity ++; } else { parity --; } rc5_data = rc5_data << 1; // rotate bit in c doesn't work as in assembler... first rotate left by one (in first run it's a 0) rc5_data = rc5_data + bit_read; // then "add" the value of bit_read n++; // increment cycle counter by one } //when we have our 26 bits, finish reading, check parity and set parameters for edge detection again else { TMR0IE = 0; // disable timer interrupt INTF = 0; // enable edge detection INTE = 1; // only if parity is ok, enable access in main program if (parity == 0) { rc5_ready = 1; } LED_RECEIVE = 0; //clear receiving LED } } //reset interrupt requests TMR0IF = 0; INTF = 0; ei(); }
void configTimers (void) { unsigned char inicializacaoT1; // 31 khz //OSCCONbits.IRCF0 = 1; //OSCCONbits.IRCF1 = 1; //OSCCONbits.IRCF2 = 1; //OSCCONbits.OSTS = 1; // Oscillator Start-up Timer //OSCCONbits.IOFS = 1; // internal oscillator block has stabilized and is // providing the device clock in RC Clock modes //INTCONbits.GIE=0; // Desabilita Todas Interrupcoes durante o processo de configuracao /* * The OSTS, IOFS and T1RUN bits indicate which clock source is currently providing the device clock. The OSTS bit indicates that the Oscillator Start-up Timer (OST) has timed out and the primary clock is providing the device clock in primary clock modes. The IOFS bit indicates when the internal oscillator block has stabilized and is providing the device clock in RC Clock modes. The T1RUN bit (T1CON<6>) indicates when the Timer1 oscil- lator is providing the device clock in secondary clock modes. In power-managed modes, only one of these three bits will be set at any time. If none of these bits are set, the INTRC is providing the clock or the internal oscillator block has just started and is not yet stable. */ T1RUN=1; // bit 8 do T1CON /* T1RUN: Timer1 System Clock Status bit 1 = Device clock is derived from Timer1 oscillator 0 = Device clock is derived from another source */ //***** TIMER0 //PSA =0; // PSA: Timer0 Prescaler Assignment bit // 1 = TImer0 prescaler is NOT assigned. Timer0 clock input bypasses prescaler. // 0 = Timer0 prescaler is assigned. Timer0 clock input comes from prescaler output. //T0SE=0; // T0SE: Timer0 Source Edge Select bit // 1 = Increment on high-to-low transition on T0CKI pin // 0 = Increment on low-to-high transition on T0CKI pin //T0CS=0; // T0CS: Timer0 Clock Source Select bit // 1 = Transition on T0CKI pin // 0 = Internal instruction cycle clock (CLKO) //RCONbits.IPEN = 1; //Enable priority levels on interrupts //RCONbits.SBOREN = 0; //Disable BOR //T1CON (bit8)RD16 T1RUN(bit7) (bit6e5) T1CKPS1/T1CKPS0 (bit4)T1OSCEN (bit3)T1SYNC (bit2)TMR1CS (bit1)TMR1ON // obs: ? parece que existe uma ERRATA de troca entre os bits 7 e 8 ? // bit 2 bit 5e6 bit 4 bit 7 bit 3 bit 8 inicializacaoT1 = T1_SOURCE_EXT & T1_PS_1_8 & T1_OSC1EN_ON & T1_16BIT_RW & T1_SYNC_EXT_OFF; //& TIMER_INT_ON ; // TMR1CS T1CKPS T1OSCEN RD16 T1SYNC OpenTimer1(inicializacaoT1); //T1CONbits.RD16=1; // bit 7 do T1CON = T1_16BIT_RW ou T1_8BIT_RW /* * RD16: 16-Bit Read/Write Mode Enable bit * 1 = Enables register read/write of Timer1 in one 16-bit operation * 0 = Enables register read/write of Timer1 in two 8-bit operations */ // T1CKPS1:T1CKPS0 = T1_PS_x_y (bits 5 e 6) //T1OSCEN = 1; // bit 4 do T1CON = T1_OSC1EN ON ou OFF /* * An on-chip crystal oscillator circuit is incorporated * between pins T1OSI (input) and T1OSO (amplifier * output). It is enabled by setting the Timer1 Oscillator * Enable bit, T1OSCEN (T1CON<3>). The oscillator is a * low-power circuit rated for 32 kHz crystals. It will * continue to run during all power-managed modes. The * circuit for a typical LP oscillator is shown in Figure 12-3. * Table 12-1 shows the capacitor selection for the Timer1 * oscillator. */ //T1SYNC=0; // bit 3 do T1CON = T1_SYNC_EXT ON ou OFF /* T1SYNC: Timer1 External Clock Input Synchronization Select bit When TMR1CS = 1: 1 = Do not synchronize external clock input 0 = Synchronize external clock input */ //TMR1CS=0; // bit 2 do T1CON = T1_SOURCE EXT ou INT /* * TMR1CS: Timer1 Clock Source Select bit * 1 = External clock from RC0/T1OSO/T13CKI pin (on the rising edge) * 0 = Internal clock (F OSC /4) * Internal instruction cycle clock (CLKO) acts as source of clock * In select modes, OSC2 pin outputs CLKO which has 1/4 the * frequency of OSC1 and denotes the instruction cycle rate. * * The operating mode is determined by the clock select * bit, TMR1CS (T1CON<1>). When TMR1CS is cleared * (= 0), Timer1 increments on every internal instruction * cycle (F OSC /4). When the bit is set, Timer1 increments * on every rising edge of the Timer1 external clock input * or the Timer1 oscillator, if enabled. */ //SCS0=0; // bit 0 do OSCCON //SCS1=0; // bit 1 do OSCCON /* SCS1:SCS0: System Clock Select bits * 1x = Internal oscillator * 01 = Timer1 oscillator * 00 = Primary oscillator * * Primary ? all oscillator modes (00). * This is the normal full-power execution mode. */ // LOAD_TIMER = (estouro do timer) - ( tempo desejado * ( (Clock CPU/4) * prescaler ) ) ) // Preescaler de 1:8, clock interno (48MHz) e tempo 180. Utilizamos aqui uma variavel para // aumentar o prescaler, pois neste caso (Timer1) o maximo eh 8. // #define INICIO_TMR1 0 // 1 seg = 1.000 ms (10^-3) = 1.000.000 us (10^-6) = 1.000.000.000 ns (10^-9) // 1 ps (picosegundo) = 1 * e^-12 // 1 ns (nansegundo) = 1 * e^-9 // 1 us (microsegundo) = 1 * e^-6 // 1 ms (milisegundo) = 1 * e^-3 // 500 us = 500 * 10-6 = 0,0005 segs // 20 ms = 20 * 10-3 = 0.02 segs // 500 ms = 500 * 10-3 = 0.5 segs // quero um delay de 1/2 segundo ou 500 ms = 0,5 seg // Utilizando o Cristal default de 4 mhz // (65536) - [ 0,5 * (4.000.000/4) * (1/8) ] // 65536 - 0,5 * 1.000.000 * 0.125 // 65536 - 0,5 * 125.000 // 65536 - 62500 // igual a 3045 decimal ou 0xBE5 // Utilizando um Cristal de 32.768 mhz (para 0,5 seg) // 65536 - [ 0,5 * (32.768 / 4) * (1/8) ] // 65536 - [ 0,5 * 8192 * 0.125 ] // 65536 - [ 0,5 * 1024 ] // 65536 - [ 512 ] // igual a 65024 ou 0xFE00 // para 1 seg // 65536 - [ 1 * 1024 ] // igual a 64512 ou 0xFC00 WriteTimer1( 0xFC00 ); // equivalente a 1/2 segundo TMR1IF = 0; // interrupt flag do Timer1, bit 0 do PIR1 //PIR1bits.TMR1IF=0; // seria a mesma coisa ??? ei(); // Enable Interrupt (!!!????!!!!) ei() = (INTCONbits.GIE = 1) // Interrupts of Hi/Lo Priority or Peripheral interrupts GIE=1; // Faz o mesmo comando que o ei() acima; di() desabilita //INTCONbits.GIE=1; // o mesmo de cima //TMR0IE=0; // ** DESABILITA TIMER0 ** TMR1IE=1; // Timer1 Interrupt Enable bit bit 0 do PIE1 //PIE1bits.TMR1IE=1; // seria a mesma coisa ??? TMR1ON=1; // bit0 do T1CON1 LED2=1; }
void interrupt isr_high(){ di(); TMR0_interrupt(); ei(); }
int main(void) { TRIS_KEY1 = 1; TRIS_KEY2 = 1; TRIS_LED1 = 0; TRIS_LED2 = 0; LAT_LED1 = 0; LAT_LED2 = 0; /* External Interrupts Configuration */ INTCONbits.INT0E = 1; /* Enable Interrupt 0 (RB0 as interrupt) */ INTCON2bits.INTEDG0 = 1; /* Cause Interrupt 0 at rising edge */ INTCONbits.INT0F = 0; /* Clear Interrupt 0 flag */ INTCON3bits.INT1E = 1; /* Enable Interrupt 1 (RB1 as interrupt) */ INTCON2bits.INTEDG1 = 1; /* Cause Interrupt 1 at rising edge */ INTCON3bits.INT1F = 0; /* Clear Interrupt 0 flag */ ei(); /* Global Interrupt Enable */ /* Initialize LCD 16 cols x 2 rows */ HD44780_Init(16, 2); HD44780_Puts(3, 0, "PIC18F4520"); HD44780_Puts(0, 1, "16x2 HD44780 LCD"); Delayms(2000); SSEG_Init(); KEYPAD_Init(); OpenADC(ADC_FOSC_4 & ADC_RIGHT_JUST & ADC_0_TAD, ADC_CH0 & ADC_REF_VDD_VSS & ADC_INT_OFF, ADC_1ANA); Delay(50); /* Loop forever */ while(1) { if (state == STATE_LCD) { counter = 0; lcd_flag = 0; while(lcd_flag == 0) { HD44780_Clear(); Delayms(250); HD44780_Clear(); HD44780_Puts(0, 0, "1.LCD TEST"); HD44780_Puts(0, 1, "<<ADC LED>>"); Delayms(250); counter++; if(counter > 3) {counter = 0; break;} } HD44780_Clear(); HD44780_Puts(0, 0, "1.LCD TEST"); HD44780_Puts(0, 1, "<<ADC LED>>"); while(lcd_flag == 0){ HD44780_Clear(); HD44780_Puts(0, 0, "PRESS KEY1 FOR"); HD44780_Puts(0, 1, "LEFT"); Delayms(500); HD44780_Clear(); HD44780_Puts(0, 0, "PRESS KEY2 FOR"); HD44780_Puts(0, 1, "RIGHT"); Delayms(500); counter++; if(counter > 3) {counter = 0; break;} } } else if (state == STATE_LED) { counter = 0; led_flag = 0; while(led_flag == 0) { HD44780_Clear(); Delayms(250); HD44780_Clear(); HD44780_Puts(0, 0, "2.LED TEST"); HD44780_Puts(0, 1, "<<LCD SSEG>>"); Delayms(250); counter++; if(counter > 3) {counter = 0; break;} } HD44780_Clear(); HD44780_Puts(0, 0, "2.LED TEST"); HD44780_Puts(0, 1, "<<LCD SSEG>>"); while(led_flag == 0) { LAT_LED1 = 1; LAT_LED2 = 0; Delayms(50); LAT_LED1 = 0; LAT_LED2 = 1; Delayms(50); } LAT_LED2 = 0; } else if (state == STATE_SSEG) { counter = 0; sseg_flag = 0; while(sseg_flag == 0) { HD44780_Clear(); Delayms(250); HD44780_Clear(); HD44780_Puts(0, 0, "3.SSEG TEST"); HD44780_Puts(0, 1, "<<LED KEYPAD>>"); Delayms(250); counter++; if(counter > 3) {counter = 0; break;} } HD44780_Clear(); HD44780_Puts(0, 0, "3.SSEG TEST"); HD44780_Puts(0, 1, "<<LED KEYPAD>>"); while(sseg_flag == 0) { SSEG_Print(1,sseg_counter%10); Delayms(10); SSEG_Print(2,sseg_counter/10); Delayms(10); sseg_counter++; if(sseg_counter > 99) sseg_counter = 0; } LATCbits.LATC0 = 0; LATCbits.LATC5 = 0; } else if (state == STATE_KEYPAD) { counter = 0; keypad_flag = 0; while(keypad_flag == 0) { HD44780_Clear(); Delayms(250); HD44780_Clear(); HD44780_Puts(0, 0, "4.KEYPAD TEST"); HD44780_Puts(0, 1, "<<SSEG ADC>>"); Delayms(250); counter++; if(counter > 3) {counter = 0; break;} } HD44780_Clear(); HD44780_Puts(0, 0, "4.KEYPAD TEST"); HD44780_Puts(0, 1, "<<SSEG ADC>>"); while(keypad_flag == 0) { int_key = KEYPAD_Read(); char_key = (char)KEYPAD_KeytoASCII(int_key); HD44780_CursorSet(0,0); if(int_key != 0xFF) printf("4.KEYPAD TEST: %c", char_key); Delayms(50); } } else if (state == STATE_ADC) { counter = 0; adc_flag = 0; while(adc_flag == 0) { HD44780_Clear(); Delayms(250); HD44780_Clear(); HD44780_Puts(0, 0, "5.ADC TEST"); HD44780_Puts(0, 1, "<<KEYPAD LCD>>"); Delayms(250); counter++; if(counter > 3) {counter = 0; break;} } HD44780_Clear(); HD44780_Puts(0, 0, "5.ADC TEST"); HD44780_Puts(0, 1, "<<KEYPAD LCD>>"); while(adc_flag == 0){ ConvertADC(); while( BusyADC() ); adcin = 1023 - ReadADC(); dcf_old = dcf; dcf = (1-lamda)*dcf + lamda*adcin; if(dcf != dcf_old) { HD44780_CursorSet(0,0); printf("5.ADC TEST: %4d", (int)dcf); } } } else state = STATE_LCD; } }
unsigned char dht22_read(struct dht22 *s) { unsigned char i, p; unsigned char *ptr = &(s->rhi); di(); // Sending start condition //PORTBbits.RB5 = 0; //TRISBbits.TRISB5 = 0; DHT22_PORT = 0; DHT22_TRIS = 0; __delay_ms(2); //PORTBbits.RB5 = 1; //TRISBbits.TRISB5 = 0; DHT22_PORT = 1; DHT22_TRIS = 0; //PORTBbits.RB5 = 0; //TRISBbits.TRISB5 = 1; DHT22_PORT = 0; DHT22_TRIS = 1; __delay_us(40); // Wait for sensor response //while(PORTBbits.RB5); while(DHT22_PORT); // Discard 1st bit //while(! PORTBbits.RB5); while(! DHT22_PORT); //while(PORTBbits.RB5); while(DHT22_PORT); //__delay_us(75); // Reading data for(i=0;i<5;i++){ for(p=0;p<8;p++){ //p = i / 8; ptr[ i ] <<= 1; //while(! PORTBbits.RB5); while(! DHT22_PORT); TMR0 = 0; //while(PORTBbits.RB5); while(DHT22_PORT); if(TMR0 > 40){ ptr[ i ] |= 1; } } } ei(); // Verify data if( (unsigned char)(s->rhd + s->rhi + s->td + s->ti) != s->csum ){ //printf("Invalid data\r\n"); } int temp = (s->ti << 8) + s->td; int humidity = (s->rhi << 8) + s->rhd; //printf("Temp. = %dC\r\n", temp); //printf("Humid = %d%%\r\n", humidity); //printf("csum = %d\r\n", s->csum); //printf("act = %d\r\n", (unsigned char)(s->rhd + s->rhi + s->td + s->ti)); //printf("val = %d\r\n", i / 8); return 0; }
void fuzix_main(void) { /* setup state */ inint = false; udata.u_insys = true; ramtop = PROGTOP; tty_init(); if (d_open(TTYDEV, 0) != 0) panic("no tty"); /* Sign on messages (stashed in a buffer so we can bin them */ kprintf((char *)bufpool[0].bf_data, uname_str); #ifndef SWAPDEV #ifdef PROC_SIZE maxproc = procmem / PROC_SIZE; /* Check we don't exceed the process table size limit */ if (maxproc > PTABSIZE) { kprintf((char *)bufpool[1].bf_data, maxproc); maxproc = PTABSIZE; } #else maxproc = PTABSIZE; #endif #else maxproc = PTABSIZE; #endif /* Parameters message */ kprintf((char *)bufpool[2].bf_data, ramsize, procmem, maxproc); /* Now blow away the strings */ bufinit(); pagemap_init(); create_init(); kprintf("%x:%x\n", udata.u_page, udata.u_page2); kprintf("%x:%x\n", udata.u_ptab->p_page, udata.u_ptab->p_page2); kputs("Enabling interrupts ... "); ei(); kputs("ok.\n"); /* initialise hardware devices */ device_init(); root_dev = DEFAULT_ROOT; if (cmdline && *cmdline) { while (*cmdline == ' ') ++cmdline; root_dev = *cmdline - '0'; } else { kputs("bootdev: "); udata.u_base = bootline; udata.u_sysio = 1; udata.u_count = 2; udata.u_euid = 0; /* Always begin as superuser */ cdread(TTYDEV, O_RDONLY); /* read root filesystem name from tty */ if (*bootline >= '0') root_dev = *bootline - '0'; } /* Mount the root device */ kprintf("Mounting root fs (root_dev=%d): ", root_dev); if (fmount(root_dev, NULLINODE, 0)) panic("no filesys"); root = i_open(root_dev, ROOTINODE); if (!root) panic("no root"); kputs("OK\n"); i_ref(udata.u_cwd = root); i_ref(udata.u_root = root); rdtime32(&udata.u_time); exec_or_die(); }
PDistribution TLogRegClassifier::classDistribution(const TExample &origexam) { checkProperty(domain); TExample cexample(domain, origexam); TExample *example2; if (imputer) example2 = imputer->call(cexample); else { if (dataDescription) for(TExample::const_iterator ei(cexample.begin()), ee(cexample.end()-1); ei!=ee; ei++) if ((*ei).isSpecial()) return TClassifier::classDistribution(cexample, dataDescription); example2 = &cexample; } TExample *example = continuizedDomain ? mlnew TExample(continuizedDomain, *example2) : example2; float prob1; try { // multiply example with beta TAttributedFloatList::const_iterator b(beta->begin()), be(beta->end()); // get beta 0 prob1 = *b; b++; // multiply beta with example TVarList::const_iterator vi(example->domain->attributes->begin()); TExample::const_iterator ei(example->begin()), ee(example->end()); for (; (b!=be) && (ei!=ee); ei++, b++, vi++) { if ((*ei).isSpecial()) raiseError("unknown value in attribute '%s'", (*vi)->get_name().c_str()); prob1 += (*ei).floatV * (*b); } prob1 = exp(prob1)/(1+exp(prob1)); } catch (...) { if (imputer) mldelete example2; if (continuizedDomain) mldelete example; throw; } if (imputer) mldelete example2; if (continuizedDomain) mldelete example; if (classVar->varType == TValue::INTVAR) { TDiscDistribution *dist = mlnew TDiscDistribution(classVar); PDistribution res = dist; dist->addint(0, 1-prob1); dist->addint(1, prob1); return res; } else { TContDistribution *dist = mlnew TContDistribution(classVar); PDistribution res = dist; dist->addfloat(prob1, 1.0); return res; } }
Spectrum ConnectBDPT( const Scene &scene, Vertex *lightVertices, Vertex *cameraVertices, int s, int t, const Distribution1D &lightDistr, const std::unordered_map<const Light *, size_t> &lightToIndex, const Camera &camera, Sampler &sampler, Point2f *pRaster, Float *misWeightPtr) { Spectrum L(0.f); // Ignore invalid connections related to infinite area lights if (t > 1 && s != 0 && cameraVertices[t - 1].type == VertexType::Light) return Spectrum(0.f); // Perform connection and write contribution to _L_ Vertex sampled; if (s == 0) { // Interpret the camera subpath as a complete path const Vertex &pt = cameraVertices[t - 1]; if (pt.IsLight()) L = pt.Le(scene, cameraVertices[t - 2]) * pt.beta; DCHECK(!L.HasNaNs()); } else if (t == 1) { // Sample a point on the camera and connect it to the light subpath const Vertex &qs = lightVertices[s - 1]; if (qs.IsConnectible()) { VisibilityTester vis; Vector3f wi; Float pdf; Spectrum Wi = camera.Sample_Wi(qs.GetInteraction(), sampler.Get2D(), &wi, &pdf, pRaster, &vis); if (pdf > 0 && !Wi.IsBlack()) { // Initialize dynamically sampled vertex and _L_ for $t=1$ case sampled = Vertex::CreateCamera(&camera, vis.P1(), Wi / pdf); L = qs.beta * qs.f(sampled, TransportMode::Importance) * sampled.beta; if (qs.IsOnSurface()) L *= AbsDot(wi, qs.ns()); DCHECK(!L.HasNaNs()); // Only check visibility after we know that the path would // make a non-zero contribution. if (!L.IsBlack()) L *= vis.Tr(scene, sampler); } } } else if (s == 1) { // Sample a point on a light and connect it to the camera subpath const Vertex &pt = cameraVertices[t - 1]; if (pt.IsConnectible()) { Float lightPdf; VisibilityTester vis; Vector3f wi; Float pdf; int lightNum = lightDistr.SampleDiscrete(sampler.Get1D(), &lightPdf); const std::shared_ptr<Light> &light = scene.lights[lightNum]; Spectrum lightWeight = light->Sample_Li( pt.GetInteraction(), sampler.Get2D(), &wi, &pdf, &vis); if (pdf > 0 && !lightWeight.IsBlack()) { EndpointInteraction ei(vis.P1(), light.get()); sampled = Vertex::CreateLight(ei, lightWeight / (pdf * lightPdf), 0); sampled.pdfFwd = sampled.PdfLightOrigin(scene, pt, lightDistr, lightToIndex); L = pt.beta * pt.f(sampled, TransportMode::Radiance) * sampled.beta; if (pt.IsOnSurface()) L *= AbsDot(wi, pt.ns()); // Only check visibility if the path would carry radiance. if (!L.IsBlack()) L *= vis.Tr(scene, sampler); } } } else { // Handle all other bidirectional connection cases const Vertex &qs = lightVertices[s - 1], &pt = cameraVertices[t - 1]; if (qs.IsConnectible() && pt.IsConnectible()) { L = qs.beta * qs.f(pt, TransportMode::Importance) * pt.f(qs, TransportMode::Radiance) * pt.beta; VLOG(2) << "General connect s: " << s << ", t: " << t << " qs: " << qs << ", pt: " << pt << ", qs.f(pt): " << qs.f(pt, TransportMode::Importance) << ", pt.f(qs): " << pt.f(qs, TransportMode::Radiance) << ", G: " << G(scene, sampler, qs, pt) << ", dist^2: " << DistanceSquared(qs.p(), pt.p()); if (!L.IsBlack()) L *= G(scene, sampler, qs, pt); } } ++totalPaths; if (L.IsBlack()) ++zeroRadiancePaths; ReportValue(pathLength, s + t - 2); // Compute MIS weight for connection strategy Float misWeight = L.IsBlack() ? 0.f : MISWeight(scene, lightVertices, cameraVertices, sampled, s, t, lightDistr, lightToIndex); VLOG(2) << "MIS weight for (s,t) = (" << s << ", " << t << ") connection: " << misWeight; DCHECK(!std::isnan(misWeight)); L *= misWeight; if (misWeightPtr) *misWeightPtr = misWeight; return L; }
int Client::chunk_write(chunk_h chunkh, const std::string & varname, int32_t iteration, const void* data) { /* check that the variable is know in the configuration */ Variable* variable = metadataManager->getVariable(varname); if(variable == NULL) { ERROR("Variable \""<< varname << "\" not defined in configuration"); return -1; } ChunkHandle* chunkHandle = (ChunkHandle*)chunkh; /* check if the chunk matches the layout boundaries */ Layout* layout = variable->getLayout(); if(not chunkHandle->within(layout)) { ERROR("Chunk boundaries do not match variable's layout"); return -3; } ShmChunk* chunk = NULL; try { Types::basic_type_e t = layout->getType(); unsigned int d = chunkHandle->getDimensions(); std::vector<int> si(d); std::vector<int> ei(d); for(unsigned int i=0;i<d; i++) { si[i] = chunkHandle->getStartIndex(i); ei[i] = chunkHandle->getEndIndex(i); } chunk = new ShmChunk(segment,t,d,si,ei); chunk->setSource(env->getID()); chunk->setIteration(iteration); } catch (...) { ERROR("While writing \"" << varname << "\", allocation failed"); return -2; } // copy data size_t size = chunk->getDataMemoryLength(); memcpy(chunk->data(),data,size); // create message Message message; message.source = env->getID(); message.iteration = iteration; message.object = variable->getID(); message.type = MSG_VAR; message.handle = chunk->getHandle(); // send message msgQueue->send(&message,sizeof(Message),0); DBG("Variable \"" << varname << "\" has been written"); // free message delete chunk; return size; }
int main (void) { IRMP_DATA irmp_data; char c; InitApp(); PWMoff(); RS232init(); __delay_ms(200); printf("IRMP PIC 12F1840 1.8 ws\r\n"); irmp_init(); // initialize irmp timer1_init(); // initialize timer1 ei(); // enable interrupts TMR1ON=1; // start timer for (;;) { if (kbhit()) { c=getch(); if (c>32 && c<127) putch(c); putch(' '); if (c=='.') { printf("MX115OFF "); RC5(0x15,0x0c,2); // Philips MC115 AUX OFF } else if (c=='n') { printf("NEC "); NEC(0x55,0xaa); } else { putch('?'); continue; } while (irsnd_is_busy ()) ; printf("PR2 %d\r\n",PR2); continue; } if (irmp_get_data (&irmp_data)) { printf("P "); printf("%d a=0x%04x c=0x%04x f=0x%02x (",irmp_data.protocol, irmp_data.address,irmp_data.command,irmp_data.flags); #if IRMP_PROTOCOL_NAMES printf(irmp_protocol_names[irmp_data.protocol]); #else switch(irmp_data.protocol) { case 1: printf("Sony"); break; case 2: printf("NEC"); break; case 7: printf("RC5"); break; case 0x21: printf("Ortek"); break; } #endif printf(")\r\n"); } } }
vector<double> EGO::brute_search_local_loop(vector<double> particle, int npts, double radius, int lambda, bool has_to_run) { double best = 1000000; int size = dimension * lambda; vector<double> best_point(size, 0); int loop[lambda]; double steps[dimension]; bool has_result = false; bool more_viable = true; for(int i = 0; i < lambda; i++) loop[i] = i; for(int i = 0; i < dimension; i++) { if(is_discrete) { steps[i] = (int) floor(2 * radius / npts); if(steps[i] == 0) steps[i] = 1; } else { steps[i] = 2 * radius / npts; } } if(lambda == 1) { while(more_viable) { vector<double> x(size, 0.0); bool can_run = true; for(int i = 0; i < lambda; i++) { for(int j = 0; j < dimension; j++) { x[i * dimension + j] = particle[j] + (floor((loop[i] % (int) pow(npts + 1, dimension - j)) / pow(npts + 1, dimension - j - 1)) - npts/2) * steps[j]; if(x[j] > upper[j % dimension] || x[j] < lower[j % dimension]) can_run = false; } } int i = lambda - 1; for(; i >= 0; i--) { if(++loop[i] == (pow(npts + 1, dimension) + i - (lambda - 1))) { if(i == 0) more_viable = false; } else { break; } } for(int j = max(i + 1, 1); j < lambda; j++) { loop[j] = loop[j-1] + 1; if(loop[i] >= pow(npts + 1, dimension)) more_viable = false; } if(can_run && (!has_to_run || (not_run(&x[0]) && not_running(&x[0])))) { double mean = sg->mean(&x[0]); double var = sg->var(&x[0]); double result = -ei(mean, var, best_fitness); if(result < best) { best_point = x; best = result; has_result = true; } } } } else { //lambda >= 2 while(more_viable) { vector<double> x(size, 0.0); bool can_run = true; for(int i = 0; i < lambda; i++) { for(int j = 0; j < dimension; j++) { x[i * dimension + j] = particle[j] + (floor((loop[i] % (int) pow(npts + 1, dimension - j)) / pow(npts + 1, dimension - j - 1)) - npts/2) * steps[j]; if(x[i*dimension +j] > upper[j] || x[i*dimension+j] < lower[j]) can_run = false; } if(!can_run) break; } int i = lambda - 1; for(; i >= 0; i--) { if(++loop[i] == (pow(npts + 1, dimension) + i - (lambda - 1))) { if(i == 0) more_viable = false; } else { break; } } for(int j = max(i + 1, 1); j < lambda; j++) { loop[j] = loop[j-1] + 1; if(loop[j] >= pow(npts + 1, dimension) + j - (lambda - 1)) more_viable = false; } if(can_run && (!has_to_run || (not_run(&x[0]) && not_running(&x[0])))) { double result = fitness(x); if(result < best) { best_point = x; best = result; has_result = true; } } } } if(has_result) { return best_point; } else if(has_to_run) { return brute_search_local_loop(particle, 2*(radius + 1), radius + 1, lambda, has_to_run); } else { return brute_search_local_loop(particle, npts, radius + 1, lambda, has_to_run); } }
void InitApp(void) { /* Setup analog functionality and port direction */ //LEDs LED1_DIR = OUT; LED2_DIR = OUT; LED3_DIR = OUT; //Control panel CTRLPOT_DIR = IN; CTRLBUTTON1_DIR = IN; CTRLSWITCH1_DIR = IN; CTRLLED1_DIR = OUT; CTRLLED2_DIR = OUT; CTRLLED3_DIR = OUT; //UART RX_DIR = IN; TX_DIR = IN; //Module will dynamically change as needed /* Initialize peripherals */ //ADC OpenADC( ADC_FOSC_RC & ADC_RIGHT_JUST & ADC_4_TAD, ADC_CH3 & ADC_REF_VDD_VSS & ADC_INT_OFF, ADC_4ANA); //Timer OpenTimer0(TIMER_INT_ON & T0_16BIT & T0_SOURCE_INT & T0_PS_1_2); WriteTimer0(0x0000); OpenTimer1(TIMER_INT_ON & T1_SOURCE_INT & T1_16BIT_RW & T1_PS_1_1 & T1_OSC1EN_OFF & T1_SYNC_EXT_OFF); WriteTimer1(SERVO_MIN); //UART //BusPirate: m 3 6 ENTER ENTER ENTER 1 e 3 W (2)) P OpenUSART( USART_TX_INT_OFF & USART_RX_INT_OFF & USART_BRGH_HIGH & USART_NINE_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, UART_BAUDRATE); baudUSART(BAUD_IDLE_CLK_LOW & BAUD_16_BIT_RATE & BAUD_WAKEUP_OFF & BAUD_AUTO_OFF); /* Configure the IPEN bit (1=on) in RCON to turn on/off int priorities */ INTCONbits.TMR0IF = 1; //reset Interrupt Flag PIR1bits.TMR1IF = 1; RCONbits.IPEN = 1; RCSTAbits.SPEN=1; /* Enable interrupts */ ei(); }
vector<double> EGO::brute_search(int npts=10, int lambda=1) { double best = 1000000; int size = dimension * lambda; vector<double> best_point(size, 0); double points[size][npts + 1]; int num_steps = npts + 1; bool has_result = false; if(lambda == 1) { //Build our steps of possible values in each dimension for(int i = 0; i < dimension; i++) { if(is_discrete) { int step = floor((upper[i] - lower[i]) / npts); if(step == 0) step = 1; int j = 0; for(; j <= npts && (lower[i] + j * step) <= upper[i]; j++) { points[i][j] = floor(lower[i] + j * step); } num_steps = min(num_steps, j); } else { double step = (upper[i] - lower[i]) / npts; int j = 0; for(; j <= npts; j++) { points[i][j] = lower[i] + j * step; } num_steps = min(num_steps, j); } } //Loop through each possible combination of values for(int i = 0; i < pow(num_steps, dimension); i++) { double x[dimension]; for(int j = 0; j < dimension; j++) { x[j] = points[j][((int)(i / pow(num_steps, j))) % num_steps]; } if(not_running(x)) { double result = -ei(sg->mean(x), sg->var(x), best_fitness); if(result < best) { best = result; best_point.assign(x, x + dimension); has_result = true; } } } } else { //Build our steps of possible values in each dimension for(int i = 0; i < size; i++) { if(is_discrete) { int step = floor((upper[i % dimension] - lower[i % dimension]) / npts); if(step == 0) step = 1; int j = 0; for(; j <= npts && (lower[i % dimension] + j * step) <= upper[i % dimension]; j++) { points[i][j] = floor(lower[i % dimension] + j * step); } num_steps = min(num_steps, j); } else { double step = (upper[i % dimension] - lower[i % dimension]) / npts; int j = 0; for(; j <= npts; j++) { points[i][j] = lower[i % dimension] + j * step; } num_steps = min(num_steps, j); } } //Loop through each possible combination of values for(int i = 0; i < pow(num_steps, size); i++) { vector<double> x(size, 0.0); for(int j = 0; j < size; j++) { x[j] = points[j][((int) floor(i / pow(num_steps, j))) % num_steps]; } double result = fitness(x); if(result < best) { best = result; best_point = x; has_result = true; } } } if(has_result) { return best_point; } else { if(num_steps > npts || !is_discrete) { return brute_search(npts * 2, lambda); } cout << "Broken, can't brute search" << endl; exit(1); } }
void SaveSettings() { unsigned int addr = 0; di(); EEprom_write(&addr, (unsigned char *) &Config, sizeof (Config)); ei(); }
vector<double>* EGO::brute_search_loop(int npts, int lambda, double min_ei) { double best = 1000000; int size = dimension * lambda; vector<double> *best_point = new vector<double>(size, 0); int loop[lambda]; double steps[dimension]; bool has_result = false; bool more_viable = true; for(int i = 0; i < lambda; i++) loop[i] = i; for(int i = 0; i < dimension; i++) { if(is_discrete) { steps[i] = (int) floor((upper[i] - lower[i]) / npts); if(steps[i] == 0) steps[i] = 1; } else { steps[i] = (upper[i] - lower[i]) / npts; } } if(lambda == 1) { while(more_viable) { vector<double> x(size, 0.0); bool can_run = true; for(int i = 0; i < lambda; i++) { for(int j = 0; j < dimension; j++) { x[i * dimension + j] = lower[j] + floor((loop[i] % (int) pow(npts + 1, dimension - j)) / pow(npts + 1, dimension - j - 1)) * steps[j]; if(x[i*dimension +j] > upper[j] || x[i*dimension+j] < lower[j]) can_run = false; } } int i = lambda - 1; for(; i >= 0; i--) { if(++loop[i] == (pow(npts + 1, dimension) + i - (lambda - 1))) { if(i == 0) more_viable = false; } else { break; } } for(int j = max(i + 1, 1); j < lambda; j++) { loop[j] = loop[j-1] + 1; if(loop[i] >= pow(npts + 1, dimension)) more_viable = false; } if(can_run) { double mean = sg->mean(&x[0]); double var = sg->var(&x[0]); double result = -ei(mean, var, best_fitness); if(result < min(best, -min_ei)) { best_point->assign(x.begin(), x.end()); best = result; has_result = true; } } } } else { //lambda >= 2 int num_loops = pow(npts + 1, dimension); while(more_viable) { vector<double> x(size, 0.0); bool can_run = true; for(int i = 0; i < lambda; i++) { for(int j = 0; j < dimension; j++) { x[i * dimension + j] = lower[j] + floor((loop[i] % (int) pow(npts + 1, dimension - j)) / pow(npts + 1, dimension - j - 1)) * steps[j]; if(x[j] > upper[j % dimension] || x[j] < lower[j % dimension]) can_run = false; } } int i = lambda - 1; for(; i >= 0; i--) { if(++loop[i] == (num_loops + i - (lambda - 1))) { if(i == 0) more_viable = false; } else { break; } } for(int j = max(i + 1, 1); j < lambda; j++) { loop[j] = loop[j-1] + 1; if(loop[j] >= num_loops) more_viable = false; } if(can_run) { double result = fitness(x); if(result < min(best, -min_ei)) { best_point->assign(x.begin(), x.end()); best = result; has_result = true; } } } } if(has_result) { if(!suppress) { cout << "["; for(int i = 0; i < lambda; i++) { for(int j = 0; j < dimension; j++) { cout << (*best_point)[i*dimension + j] << " "; } cout << "\b; "; } cout << "\b\b] = best = " << best << endl; } return best_point; } else { delete best_point; return NULL; } }
void radio_tx_finish() { radio_tx_data(radio_tx_crc); radio_off(); ei(); }
int main() { SDL_Init(SDL_INIT_VIDEO); SDL_Surface *screen = SDL_SetVideoMode(1024, 768, 32, SDL_HWSURFACE); SDL_Surface *trace = SDL_CreateRGBSurface(SDL_HWSURFACE, 1024, 768, 32, 0, 0, 0, 0); SDL_WM_SetCaption("Solar system demo", NULL); Uint32 white = SDL_MapRGB(screen->format, 255, 255, 255); Uint32 black = SDL_MapRGB(screen->format, 0, 0, 0); Uint32 red = SDL_MapRGB(screen->format, 255, 0, 0); Uint32 green = SDL_MapRGB(screen->format, 0, 255, 0); Uint32 blue = SDL_MapRGB(screen->format, 0, 0, 255); // Universe U; // Sun *sun = new Sun(1e+10); // U.addBody(sun); // U.addBody(new SpaceBody(0, sun, 0.7, 150)); // U.addBody(new SpaceBody(0, sun, 0.5, 150, 0, 0, M_PI/4)); Universe U; double sunmass = 1e+10; StaticIntegrator si; U.addBody(new Body(sunmass, si)); KeplerIntegrator ki1(Orbit(sunmass, 0, 0.7, 150)); U.addBody(new Body(0, ki1)); // KeplerIntegrator ki2(Orbit(sunmass, 0, 0, 150, M_PI/2)); // U.addBody(new Body(0, ki2)); EulerIntegrator ei(Vector3D(150, 0, 0), Vector3D(0, -sqrt((sunmass * G)/150), 0)); Body *eulerbody = new Body(0, ei); U.addBody(eulerbody); LeapfrogIntegrator lfi(Vector3D(150, 0, 0), Vector3D(0, -sqrt((sunmass * G)/150), 0)); Body *leapfrogbody = new Body(0, lfi); U.addBody(leapfrogbody); SDL_Rect pos1, pos2; pos2.x = pos2.y = 0; Vector3D v; SDL_Surface *rect = SDL_CreateRGBSurface(SDL_HWSURFACE, 10, 10, 32, 0, 0, 0, 0); SDL_FillRect(rect, NULL, white); SDL_Surface *littlerect = SDL_CreateRGBSurface(SDL_HWSURFACE, 1, 1, 32, 0, 0, 0, 0); bool ok = true; SDL_Event evt; Uint32 color; Uint32 startTime = SDL_GetTicks(); while (ok) { SDL_PollEvent(&evt); switch (evt.type) { case SDL_QUIT: ok = false; break; } SDL_FillRect(screen, NULL, black); SDL_BlitSurface(trace, NULL, screen, &pos2); // for(int i=0;i<2000;i++) U.evolve(200); for (std::shared_ptr<Body> &it : U.getBodies()) { color=it.get() == eulerbody ? green : (it.get() == leapfrogbody ? red : blue); v = Vector3D(512, 384, 0) + it->getPosition(); if(it.get() == leapfrogbody) v+=Vector3D(2,0,0); pos1.x = v.getX(); pos1.y = v.getY(); SDL_FillRect(littlerect, NULL, color); SDL_BlitSurface(littlerect, NULL, trace, &pos1); pos1.x -= 5; pos1.y -= 5; SDL_FillRect(rect, NULL, color); SDL_BlitSurface(rect, NULL, screen, &pos1); } SDL_Flip(screen); } SDL_Quit(); return EXIT_SUCCESS; }
//=============================================== //=============================================== //=============================================== //=============================================== void main(void) { t0_init(); ei(); PEIE=1; di(); ei(); TRISB=0x00; PORTB=0x00; PORTC|=(1<<led_ERR); sci_init(); while (1) { if(bRXIN) { bRXIN=0; UART_IN(); } if(bit_100Hz) { bit_100Hz=0; in_read(); step_contr(); mdvr_drv(); but_drv(); but_an(); } if(bit_10Hz) { bit_10Hz=0; // out_out(); led_out(); err_drv(); prog_drv(); // if(prog==p1) OUT(3,CMND,eeprom_read(DELAY1),eeprom_read(DELAY2)/*3,3*/,0,0,0); // else if(prog==p2) OUT(3,CMND,eeprom_read(DELAY3),eeprom_read(DELAY4),0,0,0); if(prog==p3) { if(!sub_ind)adress=DELAY1; else adress=DELAY2; } else if(prog==p4) { if(!sub_ind)adress=DELAY3; else adress=DELAY4; } else if(prog==p1) { if(!sub_ind)adress=DELAY5; else adress=DELAY6; } else if(prog==p2) { if(!sub_ind)adress=DELAY7; else adress=DELAY8; } OUT(3,CMND,/*prog*/eeprom_read(adress),sub_ind+1,0,0,0); } if(bit_1Hz) { bit_1Hz=0; } } }
void main(void) { uint16_t v; uint8_t i; int16_t pad; uint32_t padsNow=0; uint32_t padsLast=0; int8_t lastKey; uint8_t cnt=0; uint16_t lastEncValue; uint8_t encStep; int16_t senseDelta; uint8_t easteregg; SetupBoard(); SetupCTMU(); encStep=1; encValue=0; lastEncValue=0; octave=3; encMin=0; encMax=14; senseDelta=99; OpenTimer4(TIMER_INT_ON & T4_PS_1_1 & T4_POST_1_1); // Timer4 - Rotary Encoder polling WriteTimer4(0xFF); TMR4IF=0; OpenTimer2(TIMER_INT_ON & T2_PS_1_4 & T2_POST_1_8); // Timer2 = Display Refresh WriteTimer2(0xFF); TMR2IF=0; GIE=1; PEIE=1; ei(); disp[0]=0x00; disp[1]=0x00; disp[2]=0x00; keys=0; easteregg=0; leds=0x7fff; __delay_ms(25); leds=0x0000; CalibratePads(); leds=0x7fff; __delay_ms(25); leds=0x0000; // // encMin=1; // encMax=24; // encValue=1; // for (;;) { // pad=ReadPad(encValue); // DispValue(pad); // leds=0; // if ((encValue>=1) && (encValue<=9)) {setbit(leds,encValue-1); setbit(leds,10);} // if ((encValue>=10) && (encValue<=19)) {setbit(leds,encValue-10);setbit(leds,11);} // if ((encValue>=20) && (encValue<=29)) {setbit(leds,encValue-20);setbit(leds,12);} // __delay_ms(25); // } for (;;) { // Check for tones H+A+D if (padsLast==0b000000000000101000000100) EasterEgg(1); if (padsLast==0b101000000100000000000000) EasterEgg(2); padsNow=0; for (i=0; i<PADS; i++) { pad=ReadPad(i); if (GetPadBaseValue(i)-pad>senseDelta) { setbit(padsNow,i); } } for (i=0; i<PADS; i++) { if (testbit(padsNow,i) != testbit(padsLast,i)) { if (testbit(padsNow,i)) { SendNoteOn(octave*12+i); } else { SendNoteOff(octave*12+i); } } } padsLast=padsNow; for (i=0; i<KEYS; i++) { if (testbit(keys,i)) { disp[0]=charmap[butSettings[i].txt[0]-32]; disp[1]=charmap[butSettings[i].txt[1]-32]; disp[2]=charmap[butSettings[i].txt[2]-32]; lastKey=i; encMin=butSettings[i].min; encMax=butSettings[i].max; encValue=butSettings[i].value; encStep=butSettings[i].stepSize; lastEncValue=encValue; break; } } if ((encValue!=lastEncValue) && (lastKey!=-1)) { lastEncValue=encValue; if (butSettings[lastKey].cc==127) { // OCTAVE DispValue(encValue*encStep); octave=encValue; butSettings[lastKey].value=encValue; DispValue(encValue*encStep); } else if (butSettings[lastKey].cc==126) { // SENSE DELTA senseDelta=encValue; butSettings[lastKey].value=senseDelta; DispValue(senseDelta); if (senseDelta&1) setbit(leds,0); else clrbit(leds,0); } else { SendCC(butSettings[lastKey].cc, encValue*encStep); DispValue(encValue*encStep); } } __delay_ms(10); } }
//=============================================== //=============================================== //=============================================== //=============================================== void main(void) { t0_init(); ei(); PEIE=1; di(); ei(); TRISB=0x00; PORTB=0x00; PORTC|=(1<<led_ERR); prog_drv(); led_cnt=prog*8; // while (1) { if(bit_100Hz) { bit_100Hz=0; // PORTC^=0x0f; // PORTB^=0b01100000; in_read(); step_contr(); mdvr_drv(); but_drv(); but_an(); } if(bit_10Hz) { bit_10Hz=0; //out_out(); led_out(); err_drv(); prog_drv(); // TRISC=0; // if(bVR) PORTB^=(1<<NET); // PORTC^=0xff; } if(bit_1Hz) { bit_1Hz=0; di(); // PORTB^=0xff; /* if(prog==p1) PORTB^=(1<<PP1); else if(prog==p2) PORTB^=(1<<PP2); else if(prog==p3) PORTB^=(1<<PP3); */ ei(); } } }
void main(void) { unsigned char backup_ultimo_caracter; //Var auxiliar para la rec serie unsigned int backup_tiempo_rampa; //Var auxiliar para la cuenta char paquete[4]; //arreglo para el envio serie unsigned char broadcast_flag=0; //flag auxiliar de broadcast backup_tiempo_rampa = ReadADC(); pic_ini13(); //inicializa las ent/salidas del shield 1.3 timer_ini13(); //inicializa el timer en 1ms para habilitar //el multiplexado de displays y la cuenta timer1_ini13(); //inicializa el timer 1 para generar 38.2KHz usart_ini13(); //inicializa el puerto serie a 9600 /* Si no se utiliza el MAX232 se debe de ejecutar lo siguiente: */ BAUDCONbits.RXCKP = 1; BAUDCONbits.TXCKP = 1; /* En caso contrario comentar las lineas */ ei(); //habilitación global de interrupciones assign_id('a'); //en caso de tratarse de un esclavo, asigna //el número enviado a slave_id rampa_ini13(); //inicialización while(1){ if(caracter_recibido != backup_ultimo_caracter){ backup_ultimo_caracter=caracter_recibido; /*decodifico el comando la secuencia correcta es: * * <address> <comando><EOM> * * * address: es el estado que verifica si es solicitado el dispositivo especico * la misma corresponde a un único byte codificado en ASCII * comando: se pueden enviar todos los bytes ASCII que uno desee pero * unicamente se utilizará el primero de todos * EOM: Sin este dato al final del paquete no se ejecuta el comando enviado * Si la secuencia es correcta se devuelve el comando************************** */ //****Que hago con el comando************************************************// switch(decode(caracter_recibido)){ case ninguno:; break; case per2per:{ broadcast_flag=OFF; }break; case broadcast:{ broadcast_flag=ON; }break; case start:{ rampa_status=ON; INTCONbits.INT0IF=0; INTCONbits.INT0IE=1; SOLENOIDE_ON; demora_solenoide = demora_solenoide_set; }break; case stop:{ rampa_status=OFF; INTCONbits.INT0IE=0; INTCONbits.INT0IF=0; }break; case lectura:{ if(!broadcast_flag) informar(paquete,4); //envia la lectura }break; case reset:{ tiempo_rampa=0; }break; } } /*para no hacer la siguiente conversión a menos que sea necesario se realiza una *comprobación */ if(tiempo_rampa !=backup_tiempo_rampa){ //separa la cuenta en BCD paquete[0]=tiempo_rampa/1000; //obtiene los segundos paquete[1]=(tiempo_rampa%1000)/100; //obtiene las decimas paquete[2]=(tiempo_rampa%100)/10; //obtiene la centesimas paquete[3]=tiempo_rampa%10; //obtiene las milesimas backup_tiempo_rampa=tiempo_rampa; } Send_4Disp(paquete[0],paquete[1],paquete[2],paquete[3]); //se actualiza la info del disp } }
void SetupHardware() { //Interal Oscillator @ 16Mhz OSCCON = 0b01110000; //Enable the 4X PLL PLLEN = 1; TMR0ON = 0; //Turn it off for now T08BIT = 0; //16 bit mode T0CS = 0; //Internal Clock (Fosc/4 = 16 mHz) PSA = 1; //Bypass the prescaler //Setup for 800 Cycles = 20kHz TMR0H = 0xFC; TMR0L = 0xF2; TMR0IF = 0; //Clear the Timer Interrupt Flag TMR0IE = 1; //Enable the timer interrupt TMR0IP = 1; //Timer 0 is High level Interrupt TMR0ON = 1; //ON! //Setup Timer 1 //Setup for 32000 Cycles = 500Hz TMR1H = 0x83; TMR1L = 0x50; TMR1IF = 0; //Clear the Timer Interrupt Flag TMR1IE = 1; //Enable the timer interrupt TMR1IP = 0; //Timer 1 is Low Level interrupt TMR1ON = 1; //Setup PWM TMR2 = 0; //Setup for 15.56kHz Operation PR2 = 0xFF; //Set TMR2 Prescaler to 4:1 T2CONbits.T2CKPS0 = 1; T2CONbits.T2CKPS1 = 0; //Ensure 0% output MOTOR_PWM_H = 0; //Make the PWM pin and output MOTOR_PWM_TRIS = 0; //Activate Timer2 TMR2ON = 1; //Turn on CCP1 CCP1CON = 0b00001100; //Setup Serial UART //Setup Pins TRISCbits.TRISC7 = 1; TRISCbits.TRISC = 0; //Setup USART TXSTA1bits.BRGH = 1; //High Bit Rate Mode BAUDCON1bits.BRG16 = 1; //16-bit Baud Rate Generator Only BAUDCON1bits.RXDTP = 0; //RX signal is NOT inverted (Active-high) BAUDCON1bits.TXCKP = 0; //TX Signal is NOT inverted (Active-high) BAUDCON1bits.WUE = 0; //Wake Up is NOT enabled BAUDCON1bits.ABDEN = 0; //Auto baud rate is NOT enabled //Fosc=64Mhz //Baud=115200bps //BRGH=1, 16-Bit //Baud=Fosc/[4/(BRG+1)] //BRG=137 (115,942bps @ 0.64% Error) SPBRGH1 = 0; SPBRG1 = 137; TXSTA1bits.SYNC = 0; //Async Mode RCSTA1bits.SPEN = 1; //Serial Port Enabled TX1IE = 0; //Disable Interrupts TXSTA1bits.TX9 = 0; //8-bit Mode TXSTA1bits.TXEN = 1; //TX Enabled RC1IE = 0; //Disable Interrupts RCSTA1bits.RC9 = 0; //8-bit Mode RCSTA1bits.CREN = 1; //Async Mode Enable Reciever IPEN = 1; //Enable Interrupt Priority PEIE = 1; //Peripheral Interrupts Enabled. GIEL = 1; //Low Level Interrupts Enabled. ei(); //Enable Interrupts }
void main() { di(); OSCCON = 0x78; microlan_init(); usart_init(); buttons_init(); ei(); usart_pkt_send('I', 1); while (1) { usart_check(); if (microlan_task != 0) { char fail = 0; char c; switch (microlan_task) { case MICROLAN_CMD_READROM: if (!microlan_reset(microlan_line)) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_PRESENCE); } else { microlan_send(microlan_line, 0x33); microlan_crc = 0; for (c = 0; c < 8; c++) { if (!microlan_recv(microlan_line, µlan_buf[c])) { fail = 1; break; } } if (fail) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_RECV); } else if (microlan_crc != 0) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_CRC); } else { usart_pkt_send('M', 10); usart_pkt_put(0); for (c = 0; c < 8; c++) usart_pkt_put(microlan_buf[c]); } } break; case MICROLAN_CMD_CONVERTT: if (!microlan_reset(microlan_line)) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_PRESENCE); } else { microlan_send(microlan_line, 0xcc); microlan_send(microlan_line, 0x44); usart_pkt_send('M', 2); usart_pkt_put(0); } break; case MICROLAN_CMD_READTEMP: if (!microlan_reset(microlan_line)) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_PRESENCE); } else { microlan_send(microlan_line, 0x55); for (c = 0; c < 8; c++) microlan_send(microlan_line, microlan_buf[c]); microlan_send(microlan_line, 0xbe); microlan_crc = 0; for (c = 0; c < 8; c++) { if (!microlan_recv(microlan_line, µlan_buf[c])) { fail = 1; break; } } if (fail || !microlan_recv(microlan_line, &c)) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_RECV); } else if (microlan_crc != 0) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_CRC); } else { usart_pkt_send('M', 4); usart_pkt_put(0); usart_pkt_put(microlan_buf[0]); usart_pkt_put(microlan_buf[1]); } } break; case MICROLAN_CMD_SEARCHROM: if (!microlan_reset(microlan_line)) { usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_PRESENCE); } else { microlan_send(microlan_line, 0xf0); for (c = 0; c < 64; c++) { unsigned char *buf = µlan_buf[c / 8]; unsigned char mask = (1 << (c & 7)); char selectBit = (*buf & mask) ? 1 : 0; char dataBit = microlan_search_bit(microlan_line, selectBit); if (dataBit == 0xff) { // Devices hold 0 too long fail = 1; usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_RECV); break; } else if (dataBit == 3) { // No devices replied fail = 1; usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_NODEVICES); break; } else if (c < microlan_prefix_len) { // Known bit if (dataBit != 2 && dataBit != selectBit) { fail = 1; usart_pkt_send('M', 2); usart_pkt_put(MICROLAN_ERROR_SEARCH); break; } } else if (dataBit == 2) { // Bit read conflict fail = 2; microlan_prefix_len = c; break; } else { *buf = (*buf & ~mask) | (dataBit ? mask : 0); } } if (fail == 1) { // Error already sent } else { usart_pkt_send('M', 11); usart_pkt_put(0); if (fail == 2) usart_pkt_put(microlan_prefix_len); else usart_pkt_put(64); for (c = 0; c < 8; c++) usart_pkt_put(microlan_buf[c]); } } break; } microlan_task = 0; } } }