int ping_ultrasonic(int echo, int trig, int max_distance) //max_distance in cm {//ping HC-SR04 ultrasonic range finder, 10us trigger pulse, sends eight 40kHz pulses //int start_time; int max_time; //max_time in system cycles int flight_time; //char message[100]; //sprintf(message, "bump"); //NU32_WriteUART1(message); max_time = max_distance * 2320; //Distance(cm) = Time(us)/58, 40 core cycles per us, 58*40=2320 //start_time = ReadCoreTimer(); WriteCoreTimer(0); set_pin(trig, HIGH); while(ReadCoreTimer() < 1600){ //400 cycles at 40MHz, 10us trigger pulse } set_pin(trig, LOW); //NU32_WriteUART1(message); while(!get_pin(echo)){ } //NU32_WriteUART1(message); //start_time = ReadCoreTimer(); WriteCoreTimer(0); while(get_pin(echo) && (ReadCoreTimer() < max_time)){ } //flight_time = ReadCoreTimer() - start_time; flight_time = ReadCoreTimer(); //sprintf(message, "%d\n", flight_time); //NU32_WriteUART1(message); return flight_time / 2320; }
int main(void) { // BootloaderEntry(); Initialize(); sprintf(text,"\r\n\r\nHypnocube Boot Loader testing ver %s.\r\n",BootloaderVersion()); PrintSerialMain(text); sprintf(text,"Boot loader result %d.\r\n",(int)bootResult); PrintSerialMain(text); WriteCoreTimer(0); while (1) { if (ReadCoreTimer()>1000*TICKS_PER_MILLISECOND) { PrintSerialMain("."); WriteCoreTimer(0); PORTAbits.RA1^=1; // blink our LED } uint8_t byte; if (UARTReadByte(&byte) && byte != 0xFC) { sprintf(text,"Main code saw command %d = %c.\r\n",(int)byte,byte); PrintSerialMain(text); BootloaderEntry(); // call again to simplify testing } } return 0; }
//#============================================================================= //# Delays //#============================================================================= //#----------------------------------------------------------------------------- void Delayus(unsigned int t) { unsigned int CalT; WriteCoreTimer(0); CalT = t * 20; while ( (unsigned int)(ReadCoreTimer()) < CalT ) {}; } //Delayus
// initialize hardware void Initialize() { // All of these items will affect the performance of your code and cause it to run significantly slower than you would expect. SYSTEMConfigPerformance(SYS_CLOCK); WriteCoreTimer(0); // Core timer ticks once every two clocks (verified) // set default digital port A for IO DDPCONbits.JTAGEN = 0; // turn off JTAG DDPCONbits.TROEN = 0; // ensure no tracing on //mPORTASetPinsDigitalOut(BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); // todo - set this based on width of image. make rest inputs? mPORTBSetPinsDigitalOut(BIT_0|BIT_1|BIT_2|BIT_3|BIT_4|BIT_5|BIT_6|BIT_7|BIT_8|BIT_9|BIT_10|BIT_11|BIT_12|BIT_13|BIT_14|BIT_15); // Configure the device for maximum performance but do not change the PBDIV // Given the options, this function will change the flash wait states, RAM // wait state and enable prefetch cache but will not change the PBDIV. // The PBDIV value is already set via the pragma FPBDIV option above.. int pbClk = SYSTEMConfig( SYS_CLOCK, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE); InitializeUART(pbClk); mPORTASetPinsDigitalOut(BIT_1); // set internals // SetUARTClockDivider(flashOptions.baudDivisor); // prepare 32 bit timer 45 to trigger interrupts //OpenTimer45(T45_ON | T45_SOURCE_INT | T45_PS_1_1, interruptTime); // set up the timer interrupt and priority //ConfigIntTimer45(T4_INT_ON | T4_INT_PRIOR_7); // enable multivectored interrupts //INTEnableSystemMultiVectoredInt(); // start watchdog timer //tickle in interrupt, turn off during reset of device, causes a reset //The next statement enables the Watchdog Timer: // WDTCONbits.ON = 1; //sprintf(text,"Wait states %d\r\n.",BMXCONbits.BMXWSDRM); //PrintSerial(text); //BMXCONbits.BMXWSDRM = 0; // set RAM access to zero wait states //sprintf(text,"TODO _ REMOVE:override %d\r\n",pinOverride); //PrintSerial(text); //sprintf(text,"TODO _ REMOVE:actual %d\r\n",PORTAbits.RA1); //PrintSerial(text); }
/******************************************************************** * Function: delay_us() * * Precondition: * * Input: Micro second * * Output: None. * * Side Effects: Uses Core timer. This may affect other functions using core timers. For example, core timer interrupt may not work, or may loose precision. * * Overview: Provides Delay in microsecond. * * * Note: None. ********************************************************************/ void delay_us(UINT us) { UINT targetCount; UINT bakupCount; UINT8 loop = 0; // Assert "us" not zero. This must be caught during debug phase. //ASSERT(us!=0); // backup current count of the core timer. bakupCount = ReadCoreTimer(); // Core timer increments every 2 sys clock cycles. // Calculate the counts required to complete "us". targetCount = countPerMicroSec * us; // Restart core timer. WriteCoreTimer(0); // Wait till core timer completes the count. while(ReadCoreTimer() < targetCount); // Restore count back. WriteCoreTimer(bakupCount + targetCount); }
double current_time(int reset) { unsigned int ns; if (reset) { WriteCoreTimer(0); } /* get timer in ns */ ns = ReadCoreTimer(); /* return seconds as a double */ return ( ns / CLOCK * 2.0); }
double current_time(int reset) { /* NOTE: core timer tick rate = 40 Mhz, 1 tick = 25 ns */ unsigned int ns; /* should we reset our timer back to zero? Helps prevent timer rollover */ if (reset) { WriteCoreTimer(0); } /* get timer in ns */ ns = ReadCoreTimer() * 25; /* return seconds as a double */ return ( ns / 1000000000.0 ); }
unsigned int adc_grab(int sample_pin) { unsigned int elapsed=0,finishtime=0; unsigned int sample; AD1CON3bits.ADCS = 2; AD1CON1bits.ADON = 1; //ANALOG INPUTS ON AN0(RA0),AN1{RA1),AN4(RB2),AN5(RB3 WriteCoreTimer(0); if (sample_pin<=1){ // sample_pin is 1 or 2 AD1CHSbits.CH0SA = sample_pin-1; } else{ //sample_pin is 3 or 4 AD1CHSbits.CH0SA = sample_pin+1; } AD1CON1bits.SAMP = 1; //start sampling elapsed = ReadCoreTimer(); finishtime = elapsed + SAMPLE_TIME; while(ReadCoreTimer() < finishtime){//sample for more than 200ns ; } AD1CON1bits.SAMP = 0; //stop sampling and start converting while (!AD1CON1bits.DONE){ ; } sample=ADC1BUF0;//read the buffer with the result char msg[100]={}; sprintf(msg,"AN0: %4u (%5.3f volts)",sample,sample*(3.3/1024)); //to check ADC values, set a breakpoint at the line below, view the variables tab //and look at the value for message. it says what the adc is reading in volts return(sample); //elapsed=ReadCoreTimer(); }
void ADBCallback(ADB_CHANNEL_HANDLE handle, const void* data, UINT32 data_len) { // Ignore empty messages if (data_len < 1) { return; } //DEBUGLED = 0; // Get data without the first byte //BYTE raw_data[data_len - 1]; //memmove(raw_data, data + 1, data_len - 1); // First byte identifies the data BYTE* id = (BYTE*) data; if (data_len > 5) { switch (*id) { case COMMAND_TEXT: handleTexture(((BYTE*) data) + 1, data_len - 1); break; default: break; } return; } switch (*id) { case COMMAND_FREQ: incoming = intFromBytes(((BYTE*) data) + 1); PR2 = (SYS_FREQ / incoming) - 1; TMR2 = 0; // reset the Timer2 count break; case COMMAND_MAG: tpadMAG = (int)*(((BYTE*) data) + 1); PWM_Set_DC(tpadMAG / 255.0 * 50); //scale incoming magnitude to a duty cycle 0-50 pauseTimer3(); tBuff.On = 0x0; break; case COMMAND_ALIVE: WriteCoreTimer(0); break; default: break; } return; }
int main() { CFGCONbits.JTAGEN = 0; // turn off JTAG, get back those pins for IO use // set PIC32to max computing power DEBUGLED = 0; // enable multi-vector interrupts INTEnableSystemMultiVectoredInt(); INTEnableInterrupts(); PIC32MX250_setup_pins(); SYSTEMConfigPerformance(SYS_FREQ); setTimer2(OUTPUT_FREQ); // setupTimer3(BUFFER_FREQ); initPWM(); //Initializing PWM on OC3. // Initialize texture buffer and index to zero int i; tBuff.Index = 0; //init to zero tBuff.On = 0; //turn off tBuff.Length0 = 0; //start with zero length tBuff.Length1 = 0; //start with zero length tBuff.Front = 0; for (i = 0; i < MAX_BUFFER_LENGTH; i++) { tBuff.Buff0[i] = 0; //init entire buffer to zero tBuff.Buff1[i] = 0; //init entire buffer to zero } // Initialize the USB host ConnectionInit(); DEBUGLED = 1; //Main USB State Machine while (1) { // Keep the USB connection running; // Handle incoming data and manage outgoing data. ConnectionTasks(); // Main state machine switch (state) { case STATE_INIT: state = STATE_WAITING; h = INVALID_CHANNEL_HANDLE; break; case STATE_WAITING: DEBUGLED = 0; if (ADBAttached()) { state = STATE_CONNECTING; } break; case STATE_CONNECTING: if (ADBConnected()) { // Open a channel to the Android device // See "adb.h" in libadb for more details // (I don't think the name tcp:4545 matters) h = ADBOpen("tcp:4545", &ADBCallback); if (h != INVALID_CHANNEL_HANDLE) { state = STATE_CONNECTED; WriteCoreTimer(0); // Send plaintext and let the recipient do formatting ADBWrite(h & 0xFF, "Hello from TPAD!", 17); } } break; case STATE_CONNECTED: DEBUGLED = 1; if (!ADBAttached()) { state = STATE_INIT; } if (ADBChannelReady(h)) { // Execute tasks that rely on the Android-PIC32 connection // Here we will just wait for messages to come in and be handled below } // Timeout timer. If the coretimer is not reset by a keepalive command from the Android, the PIC will reset the USB communications if (ReadCoreTimer() > 200000000) { state = STATE_INIT; } break; } // end state machine } // end while loop return 0; }
/************************************************************************************************** Function: void DelayInit(const UINT systemClock) Author(s): mkobit Summary: Sets internal variables to be used with other delays Description: Calculates how many core timer clock ticks are in a microseconds and a millisecond to be used later with delays Preconditions: Core timer configured Parameters: const UINT systemClock - microcontroller system clock Returns: void Example: <code> DelayInit(80000000L) </code> Conditions at Exit: Core timer reset, internal static variables set **************************************************************************************************/ void DelayInit(const UINT systemClock) { _core_hz = systemClock / 2; // runs at half-speed of system clock _core_ticks_in_us = DELAY_US_TO_CT_TICKS(_core_hz); _core_ticks_in_ms = DELAY_MS_TO_CT_TICKS(_core_hz); WriteCoreTimer(0); }
int main(void) { Initialize(); sprintf(text,"\r\n\r\nHypnocube FLASH destroyer %d.%d\r\n",VERSION>>4, VERSION&15); PrintSerial(text); sprintf(text,"Testing %d frames of %d bytes each.\r\n",FRAMES,WORDS_PER_FRAME*4); PrintSerial(text); sprintf(text,"Flash starts at 0x%08x.\r\n",FlashData); PrintSerial(text); int frame = 0; int ramFrame = -1; int i; uint32_t errors = 0; WriteCoreTimer(0); while (1) { uint32_t startOffset = WORDS_PER_FRAME*frame; if (ramFrame != frame) { InitRamFrame(); ramFrame = frame; } ++passes[frame]; // message for start uint32_t time = ReadCoreTimer(); sprintf(text,"Pass %d, frame %d, offset %08x, time %08x, errors %d\r\n", passes[frame],frame,startOffset,time,errors ); PrintSerial(text); // erase frame if (!FlashErase(startOffset,WORDS_PER_FRAME)) PrintSerial("ERROR: flash erase failed.\r\n"); // check all entries are FLASH_ERASED_WORD_VALUE for (i = 0; i < WORDS_PER_FRAME; ++i) { uint32_t word = FlashRead(startOffset+i); if (ramBufferErased[i] != word) { // an error, output, and set buffer OutputError('E',startOffset+i,word,ramBufferErased[i]); ramBufferErased[i] = word; ++errors; } } // write all ~FLASH_ERASED_WORD_VALUE for (i = 0; i < WORDS_PER_FRAME; ++i) { if (!FlashWrite(startOffset+i,~(FLASH_ERASED_WORD_VALUE))) { snprintf(text,TEXT_SIZE,"ERROR: flash write failed ar offset %08X.\r\n",startOffset+i); PrintSerial(text); } } // check all entries are FLASH_ERASED_WORD_VALUE for (i = 0; i < WORDS_PER_FRAME; ++i) { uint32_t word = FlashRead(startOffset+i); if (ramBufferWritten[i] != word) { // an error, output, and set buffer OutputError('W',startOffset+i,word,ramBufferWritten[i]); ramBufferWritten[i] = word; ++errors; } } // check if frame changed uint8_t byte; if (UARTReadByte(&byte)) { snprintf(text,TEXT_SIZE,"Command received %c [%02x].\r\n",byte,byte); PrintSerial(text); if ('0' <= byte && byte <= FRAMES+'0'-1) { // change frame frame = byte-'0'; snprintf(text,TEXT_SIZE,"Switching to frame %d.\r\n",frame); PrintSerial(text); } if (byte == 'q') break; } } PrintSerial("Quitting...\r\n"); return 0; }