Esempio n. 1
0
void main(void) {
  unsigned long numSectors;

  /* init interrupts */
  initInterrupts();
  /* check disk ready */
  if (!checkDiskReady()) {
    error("disk not ready");
  }
  /* determine disk size */
  numSectors = getDiskSize();
  printf("Disk has %lu (0x%lX) sectors.\n",
         numSectors, numSectors);
  if (numSectors < 32) {
    error("disk is too small");
  }
  /* copy boot block to write buffer */
  copyBootBlock();
  /* write boot block to disk */
  printf("Writing boot block to disk...\n");
  if (!writeDisk(0, 32, wrBuf)) {
    error("cannot write boot block to disk");
  }
  /* done */
  printf("Halting...\n");
}
Esempio n. 2
0
int main(void) {
	
	unsigned char errorCode = NO_ERROR;

	//initialization
	errorCode = initIOPorts();
	errorCode = initSREGFlags();
	errorCode = initInterrupts();
		
    FOREVER {
		
		if(lightBarState != OFF) {
			
			lightBarState = pollJoystickSignals(lightBarState);
		
			switch(lightBarState) {
				
				case UP:	if(lightBar == 0x80) lightBar = 0x01;
							else lightBar <<= 1;
							break;
						
				case DOWN:	if(lightBar == 0x01) lightBar = 0x80;
							else lightBar >>= 1;
							break;
						
				default:	break;
			}
		
			_delay_ms(300);
        
		}
		
		PORTL = lightBar;
	}
Esempio n. 3
0
int main(void) {
  unsigned char c;
  int n;

  printf("Keyboard Test:\n");
  printf("initializing interrupts...\n");
  initInterrupts();
  printf("setting kbd ISR...\n");
  setISR(4, kbdISR);
  printf("enabling kbd interrupt mask bit...\n");
  setMask(getMask() | (1 << 4));
  printf("enabling interrupts in kbd controller...\n");
  kbdEnable();
  n = 0;
  while (1) {
    while (charAvail == 0) ;
    disable();
    c = charRead;
    charAvail = 0;
    enable();
    printf("%02X ", c);
    if (++n == 24) {
      n = 0;
      printf("\n");
    }
  }
  return 0;
}
int main()
{
    init_platform();
    initInterrupts();

	int source_word[16];
	int destination_word[16];
	setArray(source_word, 16, 0);
	setArray(destination_word, 16, 1);

    printf("Printing value before DMA transfer.\n\r");
    printArray(destination_word, 16);

    DMA_CONTROLLER_InitiateTransfer(XPAR_DMA_CONTROLLER_0_BASEADDR, (Xuint32) &source_word, (Xuint32) &destination_word, 4 * 10);

    printf("Printing value after DMA transfer.\n\r");
    printArray(destination_word, 16);

	setArray(source_word, 6, 1);
    DMA_CONTROLLER_InitiateTransfer(XPAR_DMA_CONTROLLER_0_BASEADDR, (Xuint32) &source_word, (Xuint32) &destination_word, 4 * 10);

    printf("Printing value after 2nd DMA transfer.\n\r");
    printArray(destination_word, 16);

    cleanup_platform();

    return 0;
}
Esempio n. 5
0
void measinit(void) {
	cycleData.intFlag = 0;
	cycleData.Cnt = 0;
	initWheelData();
	initPorts();
	initTimers();
	initInterrupts();
}
Esempio n. 6
0
// returns the timer handle (hTimer)
unsigned StartKernelTimer (unsigned nHzDelay, TKernelTimerHandler *pHandler, void *pParam, void *pContext) {
    if(interrupt->ENABLE_BASIC_IRQ != 1) {initInterrupts(); interruptBasicIRQ();}
    
    enableTimeout(40, RPI_ARMTIMER_CTRL_23BIT | RPI_ARMTIMER_CTRL_ENABLE | RPI_ARMTIMER_CTRL_INT_ENABLE | RPI_ARMTIMER_CTRL_PRESCALE_256);

    pHandler(1, pParam, pContext);
    return 1;
}
Esempio n. 7
0
int main() {
	DWORD t = 0;

	//Needed because a bug in picc-18?
	MIWRL=0;
	MIWRH=0;

	TRISA = 0;
	TRISB = 0;
	TRISC = 0;
	TRISD = 0;
	TRISE = 0;
	TRISF = 0;
	TRISG = 0;
	PORTA=0;
	PORTB=0;
	PORTC=0;
	PORTD=0;
	PORTE=0;
	PORTF=0;

	OSCTUNE = 0x40; //Speed up to 41.67 MHz

	//Turn off AD
	ADCON1 = 0x0F;

#if defined(DEBUG) && defined(_18F87J60)
	initUsart2();
#endif

	initTransmitter();
	initReceiver();
	initPwm();
	initInterrupts();
	initAppConfig();
	initWDT();
	TickInit();
	StackInit();
	//Set the LED on the connector
	SetLEDConfig(0x3742); //See MAC.h for the values

	printf("Telldus TellStick Net v%s\r\n", FIRMWARE_VERSION);

	while(1) {
		StackTask();
		StackApplications();
		if(TickGet() - t >= TICK_SECOND) {
			t = TickGet();
		}
#if defined(DEBUG)
		debugTask();
#endif
		rfReceiveTask();
		discoveryTask();
		ClrWdt();
	}
	return 42;
}
Esempio n. 8
0
/** @brief The main top level init
 *
 * The main init function to be called from main.c before entering the main
 * loop. This function is simply a delegator to the finer grained special
 * purpose init functions.
 *
 * @author Fred Cooke
 */
void init(){
	ATOMIC_START();			/* Disable ALL interrupts while we configure the board ready for use */
	initPLL();				/* Set up the PLL and use it */
	initIO();				/* TODO make this config dependent. Set up all the pins and modules to be in low power harmless states */
	initAllPagedRAM();			/* Copy table and config blocks of data from flash to the paged ram blocks for fast data lookup */
	initAllPagedAddresses();	/* Save the paged memory addresses to variables such that we can access them from another paged block with no warnings */
	initVariables();		/* Initialise the rest of the running variables etc */
	initFlash();			/* TODO, finalise this */
	initECTTimer();			/* TODO move this to inside config in an organised way. Set up the timer module and its various aspects */
	initPITTimer();			/* TODO ditto... */
	initSCIStuff();			/* Setup the sci module(s) that we will use. */
	initConfiguration();	/* TODO Set user/feature/config up here! */
	initInterrupts();		/* still last, reset timers, enable interrupts here TODO move this to inside config in an organised way. Set up the rest of the individual interrupts */
	ATOMIC_END(); /* Re-enable any configured interrupts */
}
Esempio n. 9
0
int main(int argc, char* argv[], char* envp[])
{
	printf("Started\n");
	initOSDataStructs();
	printf("Init structs\n");
	initInterrupts();
	printf("Init interrupts\n");
	initVGA();
	printf("Init vga\n");
	initCreateTasks();
	printf("Init tasks\n");
	vTaskStartScheduler();
	printf("Init scheduler\n");
	for (;;);
	return 0;
}
Esempio n. 10
0
int main(void) {
    cli();
    cycleData.intFlag = 0;
    cycleData.Cnt = 0;
    initWheelData();
    initPorts();
    initTimers();
    initUSART();
    initInterrupts();
    sei();
    for(;;) {
        if(cycleData.intFlag)
            prgm800Hz();
        if(cycleData.Cnt == 8)
            prgm100Hz();
    }
}
Esempio n. 11
0
Sensorik::Sensorik() {
	initInterrupts();

	// create channel for dispatcher
	sensorik_Chid = ChannelCreate(0);
	if (sensorik_Chid == -1) {
		perror("Dispatcher: ChannelCreate sensorik_Chid failed");
		exit(EXIT_FAILURE);
	}

	// attach to signal channel(stellt die verbindung zu dem channel des Prozesses PID)
	sensorik_Coid = ConnectAttach(0, 0, sensorik_Chid, _NTO_SIDE_CHANNEL, 0);
	if (sensorik_Coid == -1) {
		perror("SensorCtrl: ConnectAttach sensorik_Coid failed");
		exit(EXIT_FAILURE);
	}
}
Esempio n. 12
0
int main(void) {

	uint8_t oldStatus = 0;

	initSysVars();
	initPorts();

	// we use RS485 here, to go with RS232 just have a look at Modbus_uart.c/.h
	// and use the rs232 init function
	rs485_init(UART_BAUD_SELECT(9600,F_CPU));
	initInterrupts();
	sei();

//	actProfileData[IDX_DW_Debug02] = 2;
	actProfileData[IDX_DW_Debug01] = 101;
	actProfileData[IDX_DW_Debug02] = 102;
	actProfileData[IDX_DW_Debug03] = 103;

	actProfileData[IDX_DW_EncSteps] = 200;
	actProfileData[IDX_DW_EncHyst] = 4;
	setBitValForSysBit(IDX_AB_EncSync, ON);


	for (;;) {


		if (oldStatus != uart0_status.status) {
			oldStatus = uart0_status.status;

			if (uart0_status.status == RS_FrameComplete) {
				if (UART_RxHead) {
					modbus_processSlaveFrame((uint8_t*) UART_RxBuf, UART_RxHead);
				}
				uart_flush();
				uart0_status.status = RS_Wait;
			}
		}

		if (changedBit.cBit != 99) {
			performBitActions();
		}
	}

}
int main()
{
	initTimers();
	initVideo();
	sound_initAC97();
	mouse_init();
	initInterrupts();
	isNewGame = true;
	initGameScreen();

	PIT_startRecurringTimer(XPAR_PIT_0_BASEADDR, CLOCK_FREQ_HZ / INTERRUPTS_PER_SECOND);

	while(1) // Program never ends.
		if(low_priority_intc_status != 0)
			lowPriorityInterruptHandler();

	cleanup_platform();
	return 0;
}
Esempio n. 14
0
/** @brief The main top level init
 *
 * The main init function to be called from main.c before entering the main
 * loop. This function is simply a delegator to the finer grained special
 * purpose init functions.
 */
void init(){
	ATOMIC_START();         /* Disable ALL interrupts while we configure the board ready for use */
	initPLL();              /* Set up the PLL and use it */
	initGPIO();
	initPWM();
	initADC();
	initAllPagedRAM();      /* Copy table and config blocks of data from flash to the paged RAM blocks for fast data lookup */
	initVariables();        /* Initialise the rest of the running variables etc */
	initFlash();            /* TODO, finalise this */
	initECTTimer();         /* TODO move this to inside config in an organised way. Set up the timer module and its various aspects */
//	initPITTimer();         /* TODO ditto... */
	initSCIStuff();         /* Setup the sci module(s) that we will use. */
	initConfiguration();    /* TODO Set user/feature/config up here! */
#ifdef XGATE
	initXgate();            /* Fred is a legend, for good reason as of now */
#endif
	initInterrupts();       /* still last, reset timers, enable interrupts here TODO move this to inside config in an organised way. Set up the rest of the individual interrupts */
	ATOMIC_END();           /* Re-enable any configured interrupts */
}
Esempio n. 15
0
/**
  Add an interrupt handler for this signal.
  If you want to get notified when the signal on this pin changes,
  you can register an interrupt handler, instead of constantly reading the pin.
  To do this, define a function you want to be called when the pin changes, and
  then register it with the Io you want to monitor.  The function has to have a
  specific signature - it must be of the form:
  \code void myHandler(void* context) \endcode
  
  This function will be called any time the signal on the Io pin changes.  When you 
  register the handler, you can provide a pointer to some context that will be passed
  into your handler.  This can be an instance of a class, if you want to 
  
  \b Example
  \code
  void myHandler(void* context); // declare our handler
  
  void myTask(void* p)
  {
    Io io(IO_PB27, Io::GPIO, INPUT);   // Io on AnalogIn 0 - as digital input
    io.addInterruptHandler(myHandler); // register our handler
    
    while(true)
    {
      // do the rest of my task...
    }
  }
  
  int count = 0; // how many times has our interrupt triggered?
  // now this will get called every time the value on PB27 changes
  void myHandler(void* context)
  {
    count++;
    if(count > 100)
      count = 0;
  }
  \endcode
  
  @param h The function to be called when there's an interrupt
  @param context (optional) Context that will be passed into your handler, if desired.
  @return True if the handler was registered successfully, false if not.
*/
bool Io::addInterruptHandler(handler h, void* context)
{
  if(isrSourceCount >= MAX_INTERRUPT_SOURCES)
    return false;
  
  isrSources[isrSourceCount].port = basePort;
  isrSources[isrSourceCount].mask = mask;
  
  // if this is the first time for either channel, set it up
  if( (!isrAInit && basePort == AT91C_BASE_PIOA) || 
      (!isrBInit && basePort == AT91C_BASE_PIOB) )
  {
    initInterrupts(basePort, (AT91C_AIC_SRCTYPE_INT_HIGH_LEVEL | 3) );
  }
  
  basePort->PIO_ISR;                                   // clear the status register
  basePort->PIO_IER = isrSources[isrSourceCount].mask; // enable our channel

  isrSources[isrSourceCount].handler = h;
  isrSources[isrSourceCount++].context = context; // make sure to increment our handler count

  return true;
}
Esempio n. 16
0
int main(void) {

	int error = NO_ERROR;

	error = initIOPorts();
	error = initADC();
	error = initTimer();
	error = initInterrupts();


	FOREVER {

		ADCSRA |= 0x40;
		while(ADCSRA & 0x40) {}
		adResult = ADCH;

		// mindestens 32 als ergebnis festlegen
		// ergebnis wird als top wert fuer timer benutzt
		if(adResult < 32) adResult = 32;

	}

	return error;
}
Esempio n. 17
0
 int main(void) {

  uint8_t payload[ADVLEN];

  //Disable JTAG to allow for Standby
  AONWUCJtagPowerOff();

  //Force AUX on
  powerEnableAuxForceOn();
  powerEnableRFC();

  powerEnableXtalInterface();
  

  // Divide INF clk to save Idle mode power (increases interrupt latency)
  powerDivideInfClkDS(PRCM_INFRCLKDIVDS_RATIO_DIV32);

  initRTC();

  powerEnablePeriph();
  powerEnableGPIOClockRunMode();
  /* Wait for domains to power on */
  while((PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON));

  sensorsInit();
  ledInit();

  //Config IOID4 for external interrupt on rising edge and wake up
  //IOCPortConfigureSet(BOARD_IOID_KEY_RIGHT, IOC_PORT_GPIO, IOC_IOMODE_NORMAL | IOC_FALLING_EDGE | IOC_INT_ENABLE | IOC_IOPULL_UP | IOC_INPUT_ENABLE | IOC_WAKE_ON_LOW);

  // Config reedSwitch as input
  IOCPortConfigureSet(BOARD_IOID_DP0, IOC_PORT_GPIO, IOC_IOMODE_NORMAL | IOC_RISING_EDGE | IOC_INT_ENABLE | IOC_IOPULL_DOWN | IOC_INPUT_ENABLE | IOC_WAKE_ON_HIGH);
  //Set device to wake MCU from standby on PIN 4 (BUTTON1)
  HWREG(AON_EVENT_BASE + AON_EVENT_O_MCUWUSEL) = AON_EVENT_MCUWUSEL_WU0_EV_PAD;  //Does not work with AON_EVENT_MCUWUSEL_WU0_EV_PAD4 --> WHY??

  IntEnable(INT_EDGE_DETECT);

  powerDisablePeriph();
  //Disable clock for GPIO in CPU run mode
  HWREGBITW(PRCM_BASE + PRCM_O_GPIOCLKGR, PRCM_GPIOCLKGR_CLK_EN_BITN) = 0;
  // Load clock settings
  HWREGBITW(PRCM_BASE + PRCM_O_CLKLOADCTL, PRCM_CLKLOADCTL_LOAD_BITN) = 1;

  initInterrupts();
  initRadio();




  // baek: before while
      powerEnablePeriph();
      powerEnableGPIOClockRunMode();

       /* Wait for domains to power on */
     while((PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON)); // CRASH !!!!!!!!!!!!!!

       sensorsInit();
       ledInit();
  // end baek:


  // Turn off FLASH in idle mode
  powerDisableFlashInIdle();

  // Cache retention must be enabled in Idle if flash domain is turned off (to avoid cache corruption)
  powerEnableCacheRetention();

  //AUX - request to power down (takes no effect since force on is set)
  powerEnableAUXPdReq();
  powerDisableAuxRamRet();

  //Clear payload buffer
  memset(payload, 0, ADVLEN);

  while(1) {

  //if((g_count& 0x04)== 1){

    rfBootDone  = 0;
    rfSetupDone = 0;
    rfAdvertisingDone = 0;

	select_bmp_280();     				// activates I2C for bmp-sensor
	enable_bmp_280(1);					// works

    //Wait until RF Core PD is ready before accessing radio
    waitUntilRFCReady();
    initRadioInts();
    runRadio();

    //Wait until AUX is ready before configuring oscillators
    waitUntilAUXReady();

    //Enable 24MHz XTAL
    OSCHF_TurnOnXosc();

    //IDLE until BOOT_DONE interrupt from RFCore is triggered
    while( ! rfBootDone) {
      powerDisableCPU();
      PRCMDeepSleep();
    }

    //This code runs after BOOT_DONE interrupt has woken up the CPU again
    // ->
    //Request radio to keep on system bus
    radioCmdBusRequest(true);

    //Patch CM0 - no RFE patch needed for TX only
    radioPatch();

    //Start radio timer
    radioCmdStartRAT();

    //Enable Flash access while doing radio setup
    powerEnableFlashInIdle();

    //Switch to XTAL
    while( !OSCHF_AttemptToSwitchToXosc())
    {}
  
/* baek: before while
    powerEnablePeriph();
    powerEnableGPIOClockRunMode();

     /* Wait for domains to power on */
 /*    while((PRCMPowerDomainStatus(PRCM_DOMAIN_PERIPH) != PRCM_DOMAIN_POWER_ON)); // CRASH !!!!!!!!!!!!!!

     sensorsInit();
     ledInit();
*/
/*****************************************************************************************/
// Read sensor values


     uint32_t pressure = 0;  			// only 3 Bytes used
	//uint32_t temp = 0;
	select_bmp_280();     				// activates I2C for bmp-sensor
	enable_bmp_280(1);					// works

	do{
		pressure = value_bmp_280(BMP_280_SENSOR_TYPE_PRESS);  //  read and converts in pascal (96'000 Pa)
		//temp = value_bmp_280(BMP_280_SENSOR_TYPE_TEMP);
	}while(pressure == 0x80000000);
		if(pressure == 0x80000000){
			CPUdelay(100);

			pressure = value_bmp_280(BMP_280_SENSOR_TYPE_PRESS);  //  read and converts in pascal (96'000 Pa)

		}


    //Start Temp measurement
    uint16_t temperature;
    enable_tmp_007(1);

   //Wait for, read and calc temperature
    {
    int count = 0;
    do{
    	temperature = value_tmp_007(TMP_007_SENSOR_TYPE_AMBIENT);
    	//g_count++;
    }while( ((temperature == 0x80000000) || (temperature == 0)) && (count <=5) );
    count++;
	count--;
    }
    enable_tmp_007(0);
    char char_temp[2];



   //start hum measurement
        configure_hdc_1000();
        start_hdc_1000();
//    //Wait for, read and calc humidity
    while(!read_data_hdc_1000());
   int humidity = value_hdc_1000(HDC_1000_SENSOR_TYPE_HUMIDITY);
//    char char_hum[5];



//END read sensor values
/*****************************************************************************************/

    powerDisablePeriph();
	// Disable clock for GPIO in CPU run mode
	HWREGBITW(PRCM_BASE + PRCM_O_GPIOCLKGR, PRCM_GPIOCLKGR_CLK_EN_BITN) = 0;
	// Load clock settings
	HWREGBITW(PRCM_BASE + PRCM_O_CLKLOADCTL, PRCM_CLKLOADCTL_LOAD_BITN) = 1;

/*****************************************************************************************/
// Set payload and transmit
	uint8_t p;
    p = 0;

    /*jedes 5.te mal senden*/


		payload[p++] = ADVLEN-1;        /* len */
		payload[p++] = 0x03;
		payload[p++] = 0xde;
		payload[p++] = 0xba;
		payload[p++] =(sequenceNumber >> 8);				// laufnummer
		payload[p++] = sequenceNumber;

		// Speed
		payload[p++] = g_diff >> 24;						// higher seconds
		payload[p++] = g_diff >> 16;						// lower  seconds
		payload[p++] = g_diff >> 8;							// higher subseconds
		payload[p++] = g_diff;								// lower  subseconds

		//pressure
		payload[p++] = 0;
		payload[p++] = 0; //(pressure >> 16);
		payload[p++] = 0; //(pressure >> 8);
		payload[p++] = 0; //pressure;

		//temperature
		payload[p++] = 0;
		payload[p++] = 0; // char_temp[2];
		payload[p++] = 0;//temperature >> 8; // char_temp[1];
		payload[p++] = 0; //temperature; //char_temp[0];

		// huminity
		payload[p++] = 0;
		payload[p++] = 0;//char_hum[0];
		payload[p++] = 0;//char_hum[1];
		payload[p++] = 0;//char_hum[2];

		payload[p++] = 0;
		payload[p++] = 0;



		//Start radio setup and linked advertisment
		radioUpdateAdvData(ADVLEN, payload);

		//Start radio setup and linked advertisment
		radioSetupAndTransmit();
	//}


//END: Transmit
/*****************************************************************************************/


    //Wait in IDLE for CMD_DONE interrupt after radio setup. ISR will disable radio interrupts
    while( ! rfSetupDone) {
      powerDisableCPU();
      PRCMDeepSleep();
    }

    //Disable flash in IDLE after CMD_RADIO_SETUP is done (radio setup reads FCFG trim values)
    powerDisableFlashInIdle();

    //Wait in IDLE for LAST_CMD_DONE after 3 adv packets
    while( ! rfAdvertisingDone) {
      powerDisableCPU();
      PRCMDeepSleep();
    }

    //Request radio to not force on system bus any more
    radioCmdBusRequest(false);

 // } // end if
 // g_count++;

    //
    // Standby procedure
    //

    powerDisableXtal();

    // Turn off radio
    powerDisableRFC();

    // Switch to RCOSC_HF
    OSCHfSourceSwitch();

    // Allow AUX to turn off again. No longer need oscillator interface
    powerDisableAuxForceOn();

    // Goto Standby. MCU will now request to be powered down on DeepSleep
    powerEnableMcuPdReq();

    // Disable cache and retention
    powerDisableCache();
    powerDisableCacheRetention();

    //Calculate next recharge
    SysCtrlSetRechargeBeforePowerDown(XOSC_IN_HIGH_POWER_MODE);

    // Synchronize transactions to AON domain to ensure AUX has turned off
    SysCtrlAonSync();

    //
    // Enter Standby
    //

    powerDisableCPU();
    PRCMDeepSleep();

    SysCtrlAonUpdate();

    SysCtrlAdjustRechargeAfterPowerDown();

    SysCtrlAonSync();

    //
	// Wakeup from RTC, code starts execution from here
	//
   
    powerEnableRFC();

    powerEnableAuxForceOn();

    //Re-enable cache and retention
    powerEnableCache();
    powerEnableCacheRetention();

    //MCU will not request to be powered down on DeepSleep -> System goes only to IDLE
    powerDisableMcuPdReq();
  }
}
Esempio n. 18
0
/* Main Function */
int main( int argc, char *argv[] )
{
	//Color constants' initilizations
	BLACK = makeColour( 0, 0, 0 );
	WHITE = makeColour(63,63,63 );
	RED   = makeColour(63, 0, 0 );
	GREEN = makeColour( 0,63, 0 );
	BLUE  = makeColour( 0, 0,63 );

	//Initializations
	initInterrupts();
	initScreen();
	initChars();

	//Enable Interrupts
	enableBalloonIRQ(1000*ONE_MS, balloonISR );
	int keys_to_watch = 0x04 | 0x02 ;
	enableKeyIRQ( keys_to_watch, keyISR );


//	fillScreen(BLACK);
	int i = 0;
	welcomeMessage();

	mouse_status = resetPS2();

	int left, right;
	int lastTime;

	while(1)
	{
		//in case of losing (past 20 misses)
		if(missed >= MAX_MISS)
		{

			disableInterrupt(IRQ_COUNTER);

			fillScreen(RED);
			emptyScreen();

			printStr(10, 10, "Too many misses...");

			printStr(14, 13, "GAME OVER!");
			printStr(8, 16, "Press KEY2 to restart");
			for(i = 0; i < 30000000; i++);
//			while(missed >= 20);
//			printStr(8, 20, "HOOOOOORAY");
			enableInterrupt(IRQ_COUNTER);
			printStr(10, 10, "                  ");
	
			printStr(14, 13, "          ");
			printStr(8, 16, "                     ");
		}

		drawChar (1, 6, ' ');

		disableInterrupt(IRQ_COUNTER);
		if (*pSWITCH != 0)
		{
			if (*pSWITCH&1)
			{
				increment = 1;
				circleRad = 30;
			}
			else if (*pSWITCH&2)
			{
				increment = 2;
				circleRad = 20;

			}
			else if (*pSWITCH&4)
			{
				increment = 3;
				circleRad = 15;
			}
		}
		else
		{
			increment = 1;
			circleRad = 30;
		}		

		enableInterrupt(IRQ_COUNTER);

		/// MUSIC PLAYER ///
//		drawChar (1, 5, 16);
		if(musicCounter == 0)
		{
			left = 0;
			right = 1;
		}
		if(musicCounter < musicLength/4)
		{
			i = musicCounter;
			for(i; i<musicCounter+200; i++)
			{
				playMusic(music[left], music[right]);
				left+=2;
				right+=2;
			}
			musicCounter += 200;
		}
		else
		{
			musicCounter = 0;
			left = 0;
			right = 1;
		}
		/// MUSIC ///

		if ( mouse_status == PS2_MOUSE ) 
		{
//			drawChar (1, 5, 22);
			if( getMouseMotion( &dxMouse, &dyMouse, &mouse_button ) ) 
			{
				if( mouse_button & MOUSE_BUTTON1 )
				{
					if(getColor(xMouse+1, yMouse) == RED)
					{
						score += increment;
						drawCircle(xCircle, yCircle, 30, BLACK);
						/// SOUND EFFECT ///
						int sleft = 0;
						int sright = 1;
						int i;
						for(i=0; i<effectLength/4; i++)
						{
							playMusic(effect[sleft], effect[sright]);
							sleft+=2;
							sright+=2;
						}
						sleft = 0;
						sright = 1;
						/// SOUND EFFECT ///
					}
					else
					{
						if(time != lastTime)
						{
							missed++;
							time = lastTime;
						}
					}
				}

	/*			if( mouse_button & MOUSE_BUTTON2 )
					fillScreen( BLACK );
	
				if( mouse_button & MOUSE_BUTTON3 )
				{
					printStr(17, 13, "PAUSED!");
					disableInterrupts(IRQ_COUNTER);
					while( 1 )
					{
						if( mouse_button & MOUSE_BUTTON2 )
						{
							enableInterrupts(IRQ_COUNTER);
							printStr(17, 13, "       ");
							break;
						}
					}
				}
	*/


				if(getColor(xMouse+1, yMouse) == RED)
					dragColor = RED;
				else
					dragColor = BLACK;

				drawPixel( xMouse, yMouse, dragColor );

				xMouse += dxMouse;
				yMouse -= dyMouse;
				xMouse = max( 0, min( xMouse, MAX_X_PIXELS-1 ) );
				yMouse = max( 0, min( yMouse, MAX_Y_PIXELS-1 ) );

				drawPixel( xMouse, yMouse, WHITE );
				//drawCursor(xMouse, yMouse);
			}
		}
	}
	
	return 0;
}
int main(void)
{
	initUART(UBBR);
	printf("Simple RAM TEST \r\n");
	initExtMemIface();
	initTimer();
	initInterrupts();
	SRAM_test();
	joyInit();
	initOLED();
	initSPI();
	initCAN(NORMAL);
	
	struct joypos_t p;
	enum joydir_t d;
	struct canMessage m0,m1,m2s;

	 while(1){
		 
		/* slide1Point=getSlidePosition(1);
		 slide2Point=getSlidePosition(2);
		 printf("SLIDE1 -> %d",slide1Point.x);
		 printf("SLIDE2 -> %d",slide2Point.x);SLIDE READINGS*/
		if (readControl) {
			readControl = 0;
			
			d = getJoyDirection();
			p = getJoyPosition();
		    sendCANJoy(2,p,d);
			if (d == TOP || d == RIGHT_TOP || d == LEFT_TOP) menuOption = (menuOption-1)%NUM_MENU_OPTIONS;
			else if (d == BOTTOM || d == RIGHT_BOTTOM|| d == LEFT_BOTTOM) menuOption = (menuOption+1)%NUM_MENU_OPTIONS;
			printMenu(menuOption);
		}
		if (flagJoyButton) {
		
			m2s.id = JOY_BUTTON;
			m2s.size = 0;
			printf("Sending joy bu\r\n");
			fillTxBufferMCP(0,m2s);
			requestToSendMCP(0);
		
			struct canMessage m2s;
			flagJoyButton = 0;
			gotoCharOLED(7,0);
			putsOLED("                        "); //Cleans last selected option from screen
			switch(menuOption){
				case 0: //Play
					gotoCharOLED(7,0);
					putsOLED("PLAY");
					break;
					
			   case 1: //Options
					gotoCharOLED(7,0);
					putsOLED("OPTIONS");
					break;
					
			   case 2: //Help
					printHelp();
					break;
					
			  default:
					gotoCharOLED(7,0);
					putsOLED("Stick to the OPTIONS !!!");
					break;
				
			}
		}
		/*
		if(flagMCP) {
			flagMCP = 0;
			struct canMessage m0,m1;
			m0 = readRxBufferMCP(0);
			m1 = readRxBufferMCP(1);
			printf ("Buffer 0 ID: %d, Size: %d, Data: %s \r\n", m0.id, m0.size, m0.data);
			printf ("Buffer 1 ID: %d, Size: %d, Data: %s \r\n", m1.id, m1.size, m1.data);
		}*/
	}
}
Esempio n. 20
0
/*******************************************************************************
* main()
*
* Description:
*   Main application code
*
* See also:
*
* Arguments:
*   void
*
* Returns:
*   void
*
* Callers: C start-up code
*
* Notes :
*
*******************************************************************************/
int main(void)
{
    CBUFFNUM    testBufferNum;
    CBUFFNUM    uartOutBufferNum;
    volatile unsigned int x = 0;
    /* Initialise all used hardware and   */
    /* related interrupts                 */
    initLEDs();
    initUart2();
    initTimer2();
    initInterrupts();
    termInit();

    /* Create circular buffers            */
    cbuffInit();
    testBufferNum = cbuffCreate(testBuffer, TESTBUFFERSIZE,
                                &testBufferObj);
    uartOutBufferNum = cbuffCreate(uartOutBuffer, UARTOUTBUFFERSIZE,
                                   &uartOutBufferObj);

    /* Check buffers were created         */
    if (testBufferNum == 0 || uartOutBufferNum == 0)
    {
        error();
    }

    /* Get handles to buffers             */
    hTestBuffer = cbuffOpen(testBufferNum);
    hUartOutBuffer = cbuffOpen(uartOutBufferNum);
    /* Check buffers were opened          */
    if (hTestBuffer == (HCBUFF) 0 || hUartOutBuffer == (HCBUFF) 0)
    {
        error();
    }
    /* Start Timer based data generation  */
    startTimer2();
    /* Output statistics                  */
    while(1)
    {
        triggerUART2(hUartOutBuffer);

        updateStats(hTestBuffer);

        //termOutput(hUartOutBuffer);

        if(termIsAutomatic())
        {
            if(cbuffGetSpace(hTestBuffer) <= termGetEmptyTrigger())
            {
                termCheckBuffer(hTestBuffer);
                termFullScreenUpdate();
            }
        }
        else if(emptyBuffer == 1)
        {
            emptyBuffer = 0;
            termCheckBuffer(hTestBuffer);
            termFullScreenUpdate();
        }

        if (x >= 0x0FFF)
        {
            termOutput(hUartOutBuffer);
            x = 0;
        }
        else
        {
            x++;
        }
    }
}
Esempio n. 21
0
int main()
{
	long int savedfreq = 0;
	int s, c;
	unsigned char sw=0;

	// PORTB output for LCD
	DDRB = 0xff;
	PORTB = 0xff;

#ifdef BOARD2
	// PORTC PC0-4 output, PC5 input
	DDRC = 0x1f;
	PORTC = 0x00;
	sbi(PORTC, MUTE);
#endif
#ifdef BOARD1
	// PORTC PC0,2-5 output, PC1 input
	DDRC = 0x3d;
	PORTC = 0x00;
	sbi(PORTC, MUTE);
#endif

	// PORTD is input with pullup
	DDRD = 0x00;
	PORTD = 0xff;

	initLcd();
	initADC();

	// set reference freq
	fref = eeprom_read_word((unsigned int *)0x00);
	if (fref < 2000 || (fref % 100) != 0) {
		fref = 12000;
		eeprom_write_word((unsigned int *)0x00, fref);
	}

	// read squelch level from eeprom
	muteval = eeprom_read_word((unsigned int *)0x0c);
	if (muteval < 0 || muteval > 100) {
		muteval = 0;
		eeprom_write_word((unsigned int *)0x0c, muteval);
	}

	// read last frequency from eeprom
	freq = eeprom_read_dword((unsigned long int *)0x10);
	if (freq < 1240000UL || freq > 1300000UL) {
		freq = 1298375UL;
		eeprom_write_dword((unsigned long int *)0x10, freq);
	}

	// read shift from eeprom
	shift = eeprom_read_word((unsigned int *)0x18);
	if (shift < 60000UL || shift > 60000UL) {
		shift = -28000UL;
		eeprom_write_word((unsigned int *)0x18, shift);
	}

	// read tone (*10) from eeprom
	tone = eeprom_read_word((unsigned int *)0x1c);
	if (tone < 650 || tone > 1500) {
		tone = 650;
		eeprom_write_word((unsigned int *)0x1c, tone);
	}

	initInterrupts();
    initPLL(freq - IF);
	update();

	sprintf(str, "JPD 23cm v%s", version);
	lcdCmd(0x80);
	lcdStr(str);
	_delay_ms(500);

	for (;;) {

		lcdCmd(0x80);
		lcdStr("VFO             ");
		lcdCmd(0xc0);
		lcdStr("                ");
		update();

		for (;;) {
			// read switches on PORTD
			sw = PIND;

			// switch from tx to rx??
			if (tx && (sw & (1<<PTT) )) {
				cbi(PORTC, TXON);
				// switch TX off
				tx = FALSE;
//  				TCCR2A  &= ~(1<<COM2A1);
				update();
			}

			// switch from rx to tx?
			else if (!tx && !(sw & (1<<PTT) )) {
				tx = TRUE;
				displaySmeter(0);
				// switch TX on
				sbi(PORTC, TXON);
				sbi(PORTC, MUTE);
//				if (tone > 650) {
//	   				TCCR2A  |= (1<<COM2A1);
//				}
				update();
			}

			if (!tx) {
				s = readSmeter();
				displaySmeter(s);
				if (s > muteval)
					cbi(PORTC, MUTE);
				else
					sbi(PORTC, MUTE);
			}

			// switch shift off
			if ( (shiftSwitch == TRUE) && (sw & (1<<SHIFTKEY) )) {
				shiftSwitch = FALSE;
				update();
			}
			// switch shift on
			else if ( (shiftSwitch == FALSE) && !(sw & (1<<SHIFTKEY) )) {
				shiftSwitch = TRUE;
				update();
			}

			// save vfo frequency in eeprom after ~2 secs inactivity
			if (tick > 200) {
				if (freq != savedfreq) {
					eeprom_write_dword((unsigned long int *)0x10, freq);
					savedfreq = freq;
				}
			}
	
			// handle encoder pulses
			c = handleRotary();
			if (c!=0) {
				if (c>0) {
					freq += step;
				}
				else {
					freq -= step;
				}
				tick = 0;
				update();
			}

			if (rotaryPushed()) {
				doMenu();
				break;
			}
		}
	}
}
int main(void) {

  uint8_t numSensors = 0, i;
  // unsigned long nextflash = 0;

  // Configure all pins as inputs with pullups initially
  DDRA = 0x00;
  PORTA = 0xff;
  DDRB = 0x00;
  PORTB = 0xff;

  // Serial output line
  DDRB |= _BV(PINB0);
  PORTB |= _BV(PINB0);

  // LED
  // DDRA |= _BV(PINA0);

  // Radio power is PA1
  PORTA &= ~_BV(PINA1);
  DDRA |= _BV(PINA1);

  // Onewire power is PA2
  PORTA &= ~_BV(PINA2);
  DDRA |= _BV(PINA2);

  myPutStr("Hello world\r\n");

  // Various power-saving things

  // Disable BOD while sleeping. I hope.
  MCUCR |= (_BV(BODS) | _BV(BODSE));
  MCUCR &= ~_BV(BODSE);
  MCUCR |= (_BV(BODS));
 
  // Disable the ADC
  ADCSRA &= ~_BV(ADEN);

  // Disable the Analog Comparator
  ACSR |= _BV(ACD);

  // Disable clocking of timer1 and ADC
  PRR |= (_BV(PRTIM1)|_BV(PRADC));

  timerInit();
  wdtInit();
  initInterrupts();


  // Power up the Onewire bus
  PORTA |= _BV(PINA2);
  while(numSensors == 0) {
    myPutStr("Scanning for sensors\r\n");
    numSensors = search_sensors();
    myPutStr("Found ");
    myPutUint8(numSensors);
    myPutStr(" sensors\r\n");

    for (i=0;i<numSensors;i++) {
      uint8_t j;
      myPutStr("Sensor ");
      myPutUint8(i);
      myPutStr(" address ");
      for (j=0;j<OW_ROMCODE_SIZE;j++) {
	myPutUint8(gSensorIDs[i][j]);
      }
      if (gSensorIDs[i][0] == DS18S20_FAMILY_CODE ) {
	myPutStr(" DS18S20/DS1820");
      } else if ( gSensorIDs[i][0] == DS1822_FAMILY_CODE ) {
	myPutStr(" DS1822");
      } else {
	myPutStr(" DS18B20");
      }
      if ( DS18X20_get_power_status( &gSensorIDs[i][0] ) == DS18X20_POWER_PARASITE ) {
	myPutStr(" parasite\r\n");
      } else {
	myPutStr(" external\r\n");
      }

      // Enable 12 bit mode (won't do anything on DS18S20)
      DS18X20_write_scratchpad(&gSensorIDs[i][0], 0, 0, DS18B20_12_BIT);
      DS18X20_scratchpad_to_eeprom(DS18X20_get_power_status( &gSensorIDs[i][0] ),&gSensorIDs[i][0]);
	
    }
      

  }
  while(1) {
    unsigned long wakepoint;
    myRadioBuf_t radiobuf;
    //char debugbuf[10];

    // if ((signed long)now - (signed long)nextflash >= 0) {
    //   debugLedToggle(0);
    //   nextflash = now + 1000;
    // }

    // Power up the Onewire bus
    PORTA |= _BV(PINA2);
    // Let is stabilize for a few ms
    wakepoint = getMillis() + 15;
    numSensors = search_sensors();
    while (! ((signed long)getMillis() - (signed long)wakepoint >= 0)) {
      set_sleep_mode(SLEEP_MODE_IDLE);
      sleep_mode();
    }
    if ( DS18X20_start_meas( DS18X20_POWER_PARASITE, NULL ) == DS18X20_OK) {
      wakepoint = getMillis() + DS18B20_TCONV_12BIT;
      while (! ((signed long)getMillis() - (signed long)wakepoint >= 0)) {
	set_sleep_mode(SLEEP_MODE_IDLE);
	sleep_mode();
      }
      // Power the radio up
      PORTA |= _BV(PINA1);
      // Wakepoint set to now +100ms to allow radio to wake
      wakepoint = getMillis() + 100;

      for ( i = 0; i < numSensors; i++ ) {
        radiobuf.tenthousandths = -9999999L;
	if (DS18X20_read_maxres( &gSensorIDs[i][0], &(radiobuf.tenthousandths) ) != DS18X20_OK) {
	  radiobuf.tenthousandths = -9999999L;
	}

	//myPutStr("Sensor ");
	uint8_t j;
	for (j=0;j<OW_ROMCODE_SIZE;j++) {
            radiobuf.sensid[j] = gSensorIDs[i][j];
	    //myPutUint8(gSensorIDs[i][j]);
        }
	//myPutStr(" = ");
	//sprintf(debugbuf, "%d.%d\r\n", (int)(radiobuf.tenthousandths/10000), (int)(radiobuf.tenthousandths % 10000));
	//myPutStr(debugbuf);
        if (0 == i) {
	  // First time around, radio not initialized
	  while (! ((signed long)getMillis() - (signed long)wakepoint >= 0)) {
            set_sleep_mode(SLEEP_MODE_IDLE);
            sleep_mode();
          }
	  radioInit();
	  // No auto ack
	  radioSetAutoAck(0);
	  radioOpenWritingPipe(pipe);
        }
	radiobuf.tstamp = getMillis();
	//myPutStr("about to radioWrite, i=");
	//myPutUint8(i);
	//myPutStr("...");
	radioWrite(&radiobuf,sizeof(radiobuf));
	//myPutStr("Done\r\n");
      }
      // Power the radio down
      PORTA &= ~_BV(PINA1);
      // Plus the CE and CSN pins
      PORTA &= ~_BV(PINA7);
      PORTB &= ~_BV(PINB2);
      // And the onewire bus
      PORTA &= ~_BV(PINA2);
    } else {
      myPutStr("Error measuring sensors\n");
    }
    //tmp = getMillis();
    //radioWrite(&tmp , sizeof(unsigned long) );
    // Sleep hard until WDT fires
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_mode();
  }
}
Esempio n. 23
0
File: main.c Progetto: wazuba/AFC
void stateMachine(void)
{
	
	/******************************************************************************
	* INIT State
	* Executes at boot up or when the processor is reset.
	*
	******************************************************************************/
	if (state == STATE_INIT)
	{
		initPeripherals();
		initInterrupts();
		
		unsigned int checkRead;
	
		checkRead = M24LC64FReadWord(CHECK_ADDRESS, M24LC64F_ADDRESS_0);
		__delay32(EEPROM_DELAY*10);
		
		if (checkRead)
		{
			homePos = 0;	
			M24LC64FWriteWord(HOME_ADDRESS, homePos ,M24LC64F_ADDRESS_0);
			__delay32(EEPROM_DELAY*10);
			M24LC64FWriteWord(CHECK_ADDRESS, homePos ,M24LC64F_ADDRESS_0);
			__delay32(EEPROM_DELAY*10);
		}
		
		homePos = M24LC64FReadWord(HOME_ADDRESS, M24LC64F_ADDRESS_0);			/* Retrieve the stored delay value */
		//homePos = 0;
		__delay32(EEPROM_DELAY*10);
		motorPos = M24LC64FReadWord(MOTOR_POS_ADDRESS, M24LC64F_ADDRESS_0);			/* Retrieve the stored Motor Position value */
		//motorPos = 0;
		__delay32(EEPROM_DELAY*10);
		initPWM();
		initADC();
		initTMR();
		indexMotor(homePos, MAX_STEPS); //MAX_STEPS is 250, moveMotor() steps 4 motor steps at a time.
	}
	/* End of INIT State*/
	
	/******************************************************************************
	* WARM_UP State
	* As long as the warm up complete signal is not given the AFC will remain in
	* this state.
	******************************************************************************/
	
	/*if (state == STATE_WARM_UP)
	{
		triggerINT = disableINT0();
		//updateAnalogOut(homePos);
		bufferFull = 0;
		
	}*/

	/******************************************************************************
	* MAN State
	* Executes if the user selected MAN using the proper hardware control signals
	* This state enables the user to manually change configuration parameters and
	* the position of the motor.
	******************************************************************************/
	
	if (state == STATE_MAN)
	{
	
		if (triggerINT || IFS0bits.INT0IF) 			/* Disabling the external interrupt INT0, only needed in AFC state */
		{
			triggerINT = disableINT0();
		}
		
		if (!MAN_DELAY_CTRL == 1)					/* Check if we are setting Motor Position (= 1) or Delay (= 0) */
		{
			motorOrDelay = 0;
			homePos = motorPos;
			updateAnalogOut(homePos);
			M24LC64FWriteWord(HOME_ADDRESS, homePos ,M24LC64F_ADDRESS_0);
		}
		else
		{
			motorOrDelay = 1;
			updateAnalogOut(motorPos);
		}
	
		if (!MAN_DELAY_UP == 1)								
		{
			
			__delay32(EEPROM_DELAY*10); 			/* Debouncing (50ms Delay) can be made faster for practical application */
			if (motorOrDelay == 1)
			{
				unsigned int countTemp = 0;
				count =0;
				//do{	
				while(!MAN_DELAY_UP == 1)
				{
				//__delay32(EEPROM_DELAY*4);
				setDir = FORWARD;
				motorPos++;
				moveMotor(setDir, TIMER_PERIOD2);
				while(count==countTemp);
				countTemp++;
				updateAnalogOut(motorPos);
				}
				 
				//M24LC64FWriteWord(MOTOR_POS_ADDRESS, motorPos, M24LC64F_ADDRESS_0);
				
				//}while (count <500);
				setDir = STOP;
				moveMotor(setDir, TIMER_PERIOD2);
			}
			else
			{
				
				if (homePos >= MAX_STEPS)
					homePos = MAX_STEPS;
				else
					homePos ++; 						
			
				updateAnalogOut(homePos);
				M24LC64FWriteWord(HOME_ADDRESS, homePos ,M24LC64F_ADDRESS_0);
				
			}
		}
	
		if (!MAN_DELAY_DOWN == 1)
		{
			__delay32(EEPROM_DELAY*10);				/* Debouncing (50ms Delay) can be made faster for practical application */
			if (motorOrDelay == 1)
			{
				unsigned int countTemp = 0;
				count =0;
				//do{	
				while(!MAN_DELAY_DOWN == 1)
				{
				//__delay32(EEPROM_DELAY*4);
				setDir = REVERSE;
				motorPos--;
				moveMotor(setDir, TIMER_PERIOD2);
				while(count==countTemp);
				countTemp++;
				updateAnalogOut(motorPos);
				}
				 
				//M24LC64FWriteWord(MOTOR_POS_ADDRESS, motorPos, M24LC64F_ADDRESS_0);
				
				//}while (count <500);
				setDir = STOP;
				moveMotor(setDir, TIMER_PERIOD2);				
			}
			else
			{
				
			
				if (homePos <= MIN_DELAY)
					homePos = 0;
				else
					homePos --;							
				
				updateAnalogOut(homePos);
				M24LC64FWriteWord(HOME_ADDRESS, homePos ,M24LC64F_ADDRESS_0);
			}
		}
	
	}
	/* End of MAN State*/
	
		
	/******************************************************************************
	* AFC State
	* Executes if the user selected AFC using the proper hardware control signals
	* This state locks all manual control and the AFC controls the motor position
	******************************************************************************/
	
	if (state == STATE_AFC)
	{
		if (!MAN_DELAY_UP == 1)
		{
			indexMotor(motorPos, MAX_STEPS);
		}
		if (!MAN_DELAY_DOWN == 1)
		{
			indexMotor(homePos, MAX_STEPS);
		}
		
		heatPerPulse = 0;
		
		if (sampleTrigger)
		{
			sampleTrigger = 0;
			
			prevReflectedPower = 0;
			
			/* The ADC is triggered by a special comparison event of the PWM module */
			ADCPC2bits.SWTRG5 = 1; /*Trigger ADC to convert AN11 (Heat Per Pulse input from PLC) */
			while(!ADSTATbits.P5RDY);
		
			heatPerPulse = ADCBUF11;
			
			ADCPC0bits.SWTRG0 = 1; /*Trigger ADC to convert AN0 (Reflected port) */
			while(!ADSTATbits.P0RDY);
			
			prevReflectedPower = reflectedPower;
			
			reflectedPower = ADCBUF0;
			
			// delta = ADCBUF1;
			
			ADSTATbits.P0RDY = 0;           /* Clear the ADSTAT bits */
			//ADSTATbits.P1RDY = 0;
			ADSTATbits.P5RDY = 0;
			 
			/*__asm__ volatile ("clr B");
			__asm__ volatile ("lac %0,B":"+r"(heatPerPulse));
			__asm__ volatile ("sftac B,#16");
			__asm__ volatile ("add A");*/
			
			heatAccumulator += heatPerPulse;
						
			/*No buffer*/
			error = (int)(reflectedPower - prevReflectedPower);
			
			/* Filtering using a FIFO buffer*/
			
			/*errorArray[strPTR] = (int)(reflectedPower - prevReflectedPower);
			strPTR++;
			if (strPTR >= endPTR)
				{
					bufferFull = 1;
					strPTR = 0;
				}
			if (bufferFull == 1)
				{
					int i;
					for (i = 0; i < endPTR; i++)
					{
						error += errorArray[i];
					}
					error = error >> 5; //BUFFER_SIZE = 32 -> 2^5 = 32
				}*/
		/*	else
				{
					int j;
					for (j = 0; j < strPTR; j++)
					{
						error += errorArray[j];
					}
					error = error/strPTR;
				}*/
			triggerINT = enableINT0();
			//calcError();						/* Calculate Error based on A/D results for reflected power*/
			//moveMotor(setDir, motorStep);
			//while (T2CONbits.TON);
		}

			
			if (thermalCounter == 50000) //Using the PWM special event interrupt to increment every TMR1 period match (~20us) 5000*20uS ~= 100mS
			{
				
				/*Reduce the accumulator by the cool rate coef.*/
				heatAccumulator -= (heatAccumulator>>COOL_SHIFTS)*COOL_RATE;

				
			}		
				/* Outer loop, calculates Thermal Drift effects and moves motor proactivley (Feedforward)*/
				target = homePos + calcThermalError() + error;
				moveMotorThermal();
		
	}
Esempio n. 24
0
LeanSensorController::LeanSensorController(){
  sensorState = LOW;
  initInterrupts();
}
Esempio n. 25
0
File: main.c Progetto: pe1jpd/23cm
int main()
{
	// PORTB output for LCD
	DDRB = 0xff;
	PORTB = 0xff;

#ifdef BOARD2
	// PORTC PC0-4 output, PC5 input
	DDRC = 0x1f;
	PORTC = 0x00;
	sbi(PORTC, MUTE);
#endif
#ifdef BOARD1
	// PORTC PC0,2-5 output, PC1 input
	DDRC = 0x3d;
	PORTC = 0x00;
	sbi(PORTC, MUTE);
#endif

	// PORTD is input with pullup
	DDRD = 0x00;
	PORTD = 0xff;

	lcdInit();
	adcInit();

	readGlobalSettings();
	toneCount = 5*F_CPU/tone;

	initInterrupts();
    initPLL();

	sprintf(str, "PE1JPD 23cm v%s", version);
	lcdCursor(0,0);
	lcdStr(str);
	_delay_ms(500);

	for (;;) {
		switch(mode) {
			case VFO:
				mode = Vfo();
				writeGlobalSettings();
				break;
			case MEMORY:
				mode = Memory();
				writeGlobalSettings();
				break;
			case SPECTRUM:
				mode = Spectrum();
				break;
			case MENU:
				mode = Menu(mode);
				break;
			case MEMORY_MENU:
				mode = MemoryMenu(mode);
				break;
			default:
				mode = VFO;
				break;
		}
	}
}