void FLOPPY_OnInterrupt(void) { int i; for(i=0;i<FLOPPY_NOF_DRIVES;i++) { if (FLOPPY_Drives[i].currentPeriod>0) { /* not disabled */ FLOPPY_Drives[i].currentTick++; /* increment tick */ if (FLOPPY_Drives[i].currentTick>=FLOPPY_Drives[i].currentPeriod) { /* check if expired */ FLOPPY_Drives[i].StepSetVal(); /* toggle pin ==> High */ FLOPPY_Drives[i].currentTick = 0; /* reset tick counter */ /* change direction if end has been reached */ if (FLOPPY_Drives[i].pos==FLOPPY_MAX_STEPS) { FLOPPY_SetDirection(&FLOPPY_Drives[i], FALSE); /* go backward */ } else if (FLOPPY_Drives[i].pos==0) { FLOPPY_SetDirection(&FLOPPY_Drives[i], TRUE); /* go forward */ } if (FLOPPY_Drives[i].forward) { FLOPPY_Drives[i].pos++; } else { FLOPPY_Drives[i].pos--; } WAIT1_Waitus(1); FLOPPY_Drives[i].StepClearVal(); /* toggle pin ==> Low */ } } } }
uint16_t SOCK_Recv(uint8_t sock, uint8_t *buf, uint16_t buflen) { uint16_t offaddr, realaddr; if (buflen<=0 || sock!=0) { return 1; } /* If the request size > MAX_BUF,just truncate it */ if (buflen>W5100_MAX_BUF) { buflen = W5100_MAX_BUF-2; } /* Read the Rx Read Pointer */ W5100_MemReadWord(W5100_S0_RX_RD, &offaddr); #if _DEBUG_MODE printf("RX Buffer: %x\n",offaddr); #endif while (buflen) { buflen--; realaddr = W5100_RXBUFADDR+(offaddr&W5100_RX_BUF_MASK); W5100_MemWriteByte(realaddr, *buf); offaddr++; buf++; } *buf='\0'; /* String terminated character */ /* Increase the S0_RX_RD value, so it point to the next receive */ W5100_MemWriteWord(W5100_S0_RX_RD, offaddr); /* Now Send the RECV command */ W5100_MemWriteByte(W5100_S0_CR, W5100_CR_RECV); WAIT1_Waitus(5); // Wait for Receive Process return 1; }
uint8_t SOCK_Receive(uint8_t sock, uint8_t *buf, size_t bufSize, size_t readSize) { uint16_t offaddr, realaddr; uint16_t sockaddr; if (readSize<=0 || sock>=W5100_NUM_SOCKETS) { return ERR_VALUE; /* failure */ } if (readSize>bufSize) { /* If the requested size > MAX_BUF, just truncate it */ readSize = bufSize-2; } sockaddr = W5100_SKT_BASE(sock); /* Read the Rx Read Pointer */ W5100_MemReadWord(sockaddr+W5100_RX_RD_OFFSET, &offaddr); while (readSize) { readSize--; realaddr = (W5100_RXBUFADDR + (0x0800*sock))+(offaddr&W5100_RX_BUF_MASK); W5100_MemReadByte(realaddr, buf); offaddr++; buf++; } *buf='\0'; /* string terminated character */ /* Increase the S0_RX_RD value, so it point to the next receive */ W5100_MemWriteWord(sockaddr+W5100_RX_RD_OFFSET, offaddr); /* Now Send the RECV command */ W5100_MemWriteByte(sockaddr+W5100_CR_OFFSET, W5100_CR_RECV); WAIT1_Waitus(5); /* Wait for Receive Process */ return ERR_OK; }
uint8_t FLOPPY_Steps(FLOPPY_DriveHandle drive, int steps) { if (steps>=0) { FLOPPY_SetDirection(drive, TRUE); /* go forward */ } else if (steps<0) { FLOPPY_SetDirection(drive, FALSE); /* go backward */ } while(steps!=0) { if (drive->pos==FLOPPY_MAX_STEPS) { FLOPPY_SetDirection(drive, FALSE); /* go backward */ } else if (drive->pos==0) { FLOPPY_SetDirection(drive, TRUE); /* go forward */ } /* do a step */ drive->StepSetVal(); WAIT1_Waitus(5); drive->StepClearVal(); if (steps>0) { steps--; } else { steps++; } if (drive->forward) { drive->pos++; } else { drive->pos--; } vTaskDelay(pdMS_TO_TICKS(5)); } /* while */ return ERR_OK; }
static void REF_MeasureRaw(SensorTimeType raw[NOF_SENSORS]) { uint8_t cnt; /* number of sensor */ uint8_t i; TMOUT1_CounterHandle timeout; FRTOS1_xSemaphoreTake(mutexHandle, portMAX_DELAY); if (ledON) { LED_IR_On(); /* IR LED's on */ WAIT1_Waitus(200); } for(i=0;i<NOF_SENSORS;i++) { SensorFctArray[i].SetOutput(); /* turn I/O line as output */ SensorFctArray[i].SetVal(); /* put high */ raw[i] = MAX_SENSOR_VALUE; } WAIT1_Waitus(20); /* give at least 10 us to charge the capacitor */ timeout = TMOUT1_GetCounter(20/TMOUT1_TICK_PERIOD_MS); /* set up timeout counter */ FRTOS1_vTaskSuspendAll(); (void)TU1_ResetCounter(timerHandle); /* reset timer counter */ for(i=0;i<NOF_SENSORS;i++) { SensorFctArray[i].SetInput(); /* turn I/O line as input */ } do { cnt = 0; if (TMOUT1_CounterExpired(timeout)) { break; /* get out of wile loop */ } for(i=0;i<NOF_SENSORS;i++) { if (raw[i]==MAX_SENSOR_VALUE) { /* not measured yet? */ if (SensorFctArray[i].GetVal()==0) { raw[i] = TU1_GetCounterValue(timerHandle); } } else { /* have value */ cnt++; } } } while(cnt!=NOF_SENSORS); TMOUT1_LeaveCounter(timeout); FRTOS1_xTaskResumeAll(); if (ledON) { LED_IR_Off(); /* IR LED's off */ WAIT1_Waitus(200); } FRTOS1_xSemaphoreGive(mutexHandle); }
/*! * \brief Measures the time until the sensor discharges * \param raw Array to store the raw values. * \return ERR_OVERFLOW if there is a timeout, ERR_OK otherwise */ static void REF_MeasureRaw(SensorTimeType raw[REF_NOF_SENSORS]) { uint8_t cnt; /* number of sensor */ uint8_t i; RefCnt_TValueType timerVal; LED_IR_On(); /* IR LED's on */ WAIT1_Waitus(200); for(i=0;i<REF_NOF_SENSORS;i++) { SensorFctArray[i].SetOutput(); /* turn I/O line as output */ SensorFctArray[i].SetVal(); /* put high */ raw[i] = MAX_SENSOR_VALUE; } WAIT1_Waitus(50); /* give at least 10 us to discharge the capacitor */ for(i=0;i<REF_NOF_SENSORS;i++) { SensorFctArray[i].SetInput(); /* turn I/O line as input */ } FRTOS1_taskENTER_CRITICAL(); (void)RefCnt_ResetCounter(timerHandle); /* reset timer counter */ do { cnt = 0; timerVal = RefCnt_GetCounterValue(timerHandle); for(i=0;i<REF_NOF_SENSORS;i++) { if (raw[i]==MAX_SENSOR_VALUE) { /* not measured yet? */ if ((SensorFctArray[i].GetVal()==0)){// || (timerVal > 0x2000)) { raw[i] = timerVal; } } else { /* have value */ cnt++; } } if (timerVal > 0x3000){ //9375) {/*5ms*/ for(i=0;i<REF_NOF_SENSORS;i++) { if (raw[i]==MAX_SENSOR_VALUE) { /* not measured yet? */ raw[i] = timerVal; } } break; } } while(cnt!=REF_NOF_SENSORS); FRTOS1_taskEXIT_CRITICAL(); LED_IR_Off(); /* IR LED's off */ }
static void REF_MeasureRaw(SensorTimeType raw[REF_NOF_SENSORS]) { uint8_t cnt; /* number of sensor */ uint8_t i; LED_IR_On(); /* IR LED's on */ WAIT1_Waitus(200); /*! \todo adjust time as needed */ for(i=0;i<REF_NOF_SENSORS;i++) { SensorFctArray[i].SetOutput(); /* turn I/O line as output */ SensorFctArray[i].SetVal(); /* put high */ raw[i] = MAX_SENSOR_VALUE; } WAIT1_Waitus(50); /* give some time to charge the capacitor */ (void)RefCnt_ResetCounter(timerHandle); /* reset timer counter */ for(i=0;i<REF_NOF_SENSORS;i++) { SensorFctArray[i].SetInput(); /* turn I/O line as input */ } int cntTimeOUt = 0; do { cnt = 0; for(i=0;i<REF_NOF_SENSORS;i++) { if (raw[i]==MAX_SENSOR_VALUE) { /* not measured yet? */ if (SensorFctArray[i].GetVal()==0) { FRTOS1_taskENTER_CRITICAL(); raw[i] = RefCnt_GetCounterValue(timerHandle); FRTOS1_taskEXIT_CRITICAL(); } cntTimeOUt++; if(cntTimeOUt >= 50*REF_NOF_SENSORS){ return; } } else { /* have value */ cnt++; } } } while(cnt!=REF_NOF_SENSORS); LED_IR_Off(); }
byte read_dht11_dat() { byte j = 0; byte result = 0; for (j = 0; j < 8; j++) { while (!DHT_GetVal());//while (!(PINC & _BV(DHT11_PIN))); // wait for 50us WAIT1_Waitus(30);//delayMicroseconds(30); if (DHT_GetVal())//if (PINC & _BV(DHT11_PIN)) { result |= (1 << (7 - j)); while (DHT_GetVal());//while ((PINC & _BV(DHT11_PIN))); // wait '1' finish } } return result; }
void TFC_TAOS_READ(void) { int i=0; TFC_TSI_SetVal(); TFC_TCLK_SetVal(); WAIT1_Waitus(1); TFC_TSI_ClrVal(); TFC_TCLK_ClrVal(); for(i=0;i<127;i++){ TFC_TCLK_SetVal(); TFC_ADCI_MeasureChan(FALSE,TAOS_1); TFC_TCLK_ClrVal(); TFC_ADCI_GetChanValue16(TAOS_1,&TAOS_VAL[i]); } }
/* measure and return the microseconds */ uint16_t US_Measure_us(void) { /* send 10us pulse on TRIG line. */ TRIG_SetVal(usDevice.trigDevice); WAIT1_Waitus(10); usDevice.state = ECHO_TRIGGERED; TRIG_ClrVal(usDevice.trigDevice); while(usDevice.state!=ECHO_FINISHED) { /* measure echo pulse */ if (usDevice.state==ECHO_OVERFLOW) { /* measurement took too long? */ usDevice.state = ECHO_IDLE; /* go back to idle */ return 0; /* no echo, error case */ } } usDevice.lastValue_us = (usDevice.capture*1000UL)/(TU_US_CNT_INP_FREQ_U_0/1000); return usDevice.lastValue_us; }
/* ** =================================================================== ** Method : GI2C1_ProbeACK (component GenericI2C) ** Description : ** Accesses the bus to check if the device responds with an ACK ** (ACK polling). ** Parameters : ** NAME - DESCRIPTION ** * data - Data write buffer ** dataSize - ** flags - flags for the transaction ** WaitTimeUS - Waiting time in microseconds ** to wait for the ACK on the bus. ** Returns : ** --- - Error code ** =================================================================== */ byte GI2C1_ProbeACK(void* data, word dataSize, GI2C1_EnumSendFlags flags, word WaitTimeUS) { byte res = ERR_OK; GI2C1_deviceData.dataTransmittedFlg = FALSE; res = CI2C1_MasterSendBlock(GI2C1_deviceData.handle, data, dataSize, flags==GI2C1_SEND_STOP?LDD_I2C_SEND_STOP:LDD_I2C_NO_SEND_STOP); if (res!=ERR_OK) { return res; } /*lint -save -e522 Lacks side effect */ WAIT1_Waitus(WaitTimeUS); /*lint -restore */ if (!GI2C1_deviceData.dataTransmittedFlg) { return ERR_FAILED; /* no ACK received? */ } return res; }
int send_msg(byte * pBuffer,int length) { int k = 0; SS_PutVal(NULL,0); WAIT1_Waitus(8); for(k=0;k<length;k++){ SM3_SendChar(pBuffer[k]); } SS_PutVal(NULL,1); memset(pBuffer,0,length); reset_interrupt(); return MAIN_SUCCESS; }
// send 12-bit number in Manchester code. void manchester_send(uint16_t t) { int mask = 0x800; // int ones = 0; manchester_send_bit(0); /* bit de preambule */ WAIT1_Waitus(HALF_BIT); //delayMicroseconds(HALF_BIT); for (int i = 0; i < 12; ++i) { int bit = !! (t & mask); manchester_send_bit(bit); mask >>= 1; // if (bit == 1) { // ones ++; // } else { // ones = 0; // } // if (ones == 2) { // manchester_send_bit(0); // ones = 0; // } } // if (ones > 0) { // manchester_send_bit(0); // } }
/*lint -save -e970 Disable MISRA rule (6.3) checking. */ int main(void) /*lint -restore Enable MISRA rule (6.3) checking. */ { /* Write your local variable definition here */ uint16_t sensorsVector[NUMBER_OF_SENSORS]; /* variables needed for deciding which direction it should turn more */ uint16_t robotTurnsRightMotor; uint16_t robotTurnsLeftMotor; /* in case of a white detection - it may be that simply the robot got completely * out of the track - but it should get back to the truck in case it was * just loosing a bit the track */ uint16_t flagStopWhite; /* correction algorith will relay on counting how bad * the curve (error), figuring out how many times the * sensor is activated */ uint16_t correctionS1; uint16_t correctionS2; uint16_t i; // for serial debug only flagStopWhite=0; /* initialize the correction counters * they follow how often in a loop cycle the error appears */ correctionS1 = 0; correctionS2 = 0; /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/ PE_low_level_init(); /*** End of Processor Expert internal initialization. ***/ /* Write your code here */ initializePlatform(); /* Wait for a button press before doing anything*/ while(Button_GetVal()) {} while (1) { /* Read the input sensors */ readSensors(sensorsVector); robotTurnsLeftMotor = sensorsVector[0] + sensorsVector[1] + sensorsVector[2]; robotTurnsRightMotor = sensorsVector[3] + sensorsVector [4] + sensorsVector[5]; #if 1 for (i = 0; i < NUMBER_OF_SENSORS; i++) { Term2_SendNum(sensorsVector[i]); Term2_SendChar(' '); } Term2_SendChar('R'); Term2_SendChar('='); Term2_SendNum(robotTurnsRightMotor); Term2_SendChar(' '); Term2_SendChar('L'); Term2_SendChar('='); Term2_SendNum(robotTurnsLeftMotor); Term2_CRLF(); //setRightMotorSpeed(FULL_SPEED); //setLeftMotorSpeed(FULL_SPEED); /* motor right turns faster case robot turns left as issue is on the left side */ if (robotTurnsRightMotor > robotTurnsLeftMotor){ /* if last sensor is seeing the black line * is pretty bad so speed has to be pretty high * also if situation repeats correction must be more dramatic * */ if (sensorsVector[0]==0 && sensorsVector[1]!= 0){ if(correctionS1 < TOLERANCE_S1) correctionS1= correctionS1 + CORRECTION_STEP_S1; setRightMotorSpeed(FULL_SPEED); setRightMotorSpeed(SPEED_MOTOR_S1_HIGH_REFERENCE + correctionS1); setLeftMotorSpeed(SPEED_MOTOR_S1_LOW_REFERENCE - correctionS1); /* clean up correction flag for RS2*/ WAIT1_Waitus(WAIT_SENSORS_1); correctionS2 = 0; } /* the case in which second sensor sees black line * less critical but also with potential of becoming an * issue */ else if( sensorsVector[1]==0){ if(correctionS2 < TOLERANCE_S2) correctionS2 = correctionS2 + CORRECTION_STEP_S2; setRightMotorSpeed(SPEED_MOTOR_S2_HIGH_REFERENCE + correctionS2); setLeftMotorSpeed(SPEED_MOTOR_S2_LOW_REFERENCE - correctionS2); /* clean up the correction flag for RS1 */ correctionS1 = 0; WAIT1_Waitus(WAIT_SENSORS_2); } flagStopWhite=0; } /* motor left turns robot goes to right as issue is on the right side */ if ( robotTurnsLeftMotor > robotTurnsRightMotor){ /* if last sensor is seeing the black line * is pretty bad so speed has to be pretty high * also if situation repeats correction must be more dramatic */ if (sensorsVector[5]==0 && sensorsVector[4]!=0){ if(correctionS1 < TOLERANCE_S1) correctionS1= correctionS1 + CORRECTION_STEP_S1; setRightMotorSpeed(SPEED_MOTOR_S1_LOW_REFERENCE - correctionS1); setLeftMotorSpeed(SPEED_MOTOR_S1_HIGH_REFERENCE + correctionS1); /* clean up correction flag for S2*/ WAIT1_Waitus(WAIT_SENSORS_1); correctionS2 = 0; } /* the case in which second sensor sees black line * less critical but also with potential of becoming an * issue */ else if (sensorsVector[4]==0){ if(correctionS2 < TOLERANCE_S2) correctionS2 = correctionS2 + CORRECTION_STEP_S2; setRightMotorSpeed(SPEED_MOTOR_S2_LOW_REFERENCE - correctionS2); setLeftMotorSpeed(SPEED_MOTOR_S2_HIGH_REFERENCE + correctionS2); /* clean up the correction flag for RS1 */ correctionS1 = 0; WAIT1_Waitus(WAIT_SENSORS_2); } flagStopWhite=0; } //case line is correctly read and it should move full speed if(robotTurnsRightMotor!=0 && robotTurnsLeftMotor != 0 && sensorsVector[2]==0 && sensorsVector[3]==0){ if(robotTurnsRightMotor==robotTurnsLeftMotor && robotTurnsRightMotor== 2){ setRightMotorSpeed(FULL_SPEED); setLeftMotorSpeed (FULL_SPEED); WAIT1_Waitus(WAIT_NORMAL); correctionS1 = 0; correctionS2 = 0; flagStopWhite=0; } } //case when it is on the black it also stops if (robotTurnsRightMotor==0 && robotTurnsLeftMotor == 0 ){ setRightMotorSpeed(0); setLeftMotorSpeed (0); correctionS1 = 0; correctionS2 = 0; flagStopWhite=0; } // case when it is on white board not sensor read black it stops if (robotTurnsRightMotor==3 && robotTurnsLeftMotor == 3 ){ if(flagStopWhite==TIME_TO_STOP_ON_WHITE){ setRightMotorSpeed(0); setLeftMotorSpeed (0); } else{ flagStopWhite++; WAIT1_Waitus(WAIT_NORMAL); } } #endif } /*** Don't write any code pass this line, or it will be deleted during code generation. ***/ /*** RTOS startup code. Macro PEX_RTOS_START is defined by the RTOS component. DON'T MODIFY THIS CODE!!! ***/ #ifdef PEX_RTOS_START PEX_RTOS_START(); /* Startup of the selected RTOS. Macro is defined by the RTOS component. */ #endif /*** End of RTOS startup code. ***/ /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/ for(;;){} /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/ } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/
static uint8_t Transfer(uint32_t dataAddress, size_t nofBytes) { static const uint8_t OneValue = 0xFF; /* value to clear or set the port bits */ TMOUT1_CounterHandle handle; bool isTimeout; uint32_t done0, done1, done2; /* clear any pending done flags for DMA channels */ DMA_PDD_ClearDoneFlag(DMA_BASE_PTR, DMA_PDD_CHANNEL_0); DMA_PDD_ClearDoneFlag(DMA_BASE_PTR, DMA_PDD_CHANNEL_1); DMA_PDD_ClearDoneFlag(DMA_BASE_PTR, DMA_PDD_CHANNEL_2); /* set DMA source addresses */ DMA_PDD_SetSourceAddress(DMA_BASE_PTR, DMA_PDD_CHANNEL_0, (uint32_t)&OneValue); /* set source address */ DMA_PDD_SetSourceAddress(DMA_BASE_PTR, DMA_PDD_CHANNEL_1, dataAddress); /* set source address */ DMA_PDD_SetSourceAddress(DMA_BASE_PTR, DMA_PDD_CHANNEL_2, (uint32_t)&OneValue); /* set source address */ /* set byte count addresses */ DMA_PDD_SetByteCount(DMA_BASE_PTR, DMA_PDD_CHANNEL_0, nofBytes); /* set number of bytes to transfer */ DMA_PDD_SetByteCount(DMA_BASE_PTR, DMA_PDD_CHANNEL_1, nofBytes); /* set number of bytes to transfer */ DMA_PDD_SetByteCount(DMA_BASE_PTR, DMA_PDD_CHANNEL_2, nofBytes); /* set number of bytes to transfer */ /* reset TPM counter */ TPM_PDD_InitializeCounter(TPM0_DEVICE); /* reset timer counter */ TPM_PDD_ClearChannelFlags(TPM0_DEVICE, 0x00); TPM_PDD_ClearOverflowInterruptFlag(TPM0_DEVICE); /* re-enable DMA Muxing: it will disabled at the end of the transfer */ DMAMUX_PDD_EnableChannel(DMAMUX0_BASE_PTR, 0, PDD_ENABLE); DMAMUX_PDD_EnableChannel(DMAMUX0_BASE_PTR, 1, PDD_ENABLE); DMAMUX_PDD_EnableChannel(DMAMUX0_BASE_PTR, 2, PDD_ENABLE); /* enable DMA peripheral requests */ DMA_PDD_EnablePeripheralRequest(DMA_BASE_PTR, DMA_PDD_CHANNEL_2, PDD_ENABLE); /* enable request from peripheral */ DMA_PDD_EnablePeripheralRequest(DMA_BASE_PTR, DMA_PDD_CHANNEL_1, PDD_ENABLE); /* enable request from peripheral */ DMA_PDD_EnablePeripheralRequest(DMA_BASE_PTR, DMA_PDD_CHANNEL_0, PDD_ENABLE); /* enable request from peripheral */ /* clear timer flags and status so it starts from a clean starting point */ TPM_PDD_ClearChannelFlags(TPM0_DEVICE, 0x00); TPM_PDD_ClearOverflowInterruptFlag(TPM0_DEVICE); /* enable TPM DMA */ TPM_PDD_WriteStatusControlReg(TPM0_DEVICE,TPM_PDD_ReadStatusControlReg(TPM0_DEVICE)|TPM_SC_DMA_MASK); TPM_PDD_EnableChannelDma(TPM0_DEVICE, 1); TPM_PDD_EnableChannelDma(TPM0_DEVICE, 0); /* start the TPM timer */ StartTimer(); isTimeout = FALSE; handle = TMOUT1_GetCounter(100/TMOUT1_TICK_PERIOD_MS); for(;;) { /* wait until transfer is complete */ if (TMOUT1_CounterExpired(handle)) { isTimeout = TRUE; break; /* leave loop */ } done0 = DMA_PDD_GetDoneFlag(DMA_BASE_PTR, DMA_PDD_CHANNEL_0); done1 = DMA_PDD_GetDoneFlag(DMA_BASE_PTR, DMA_PDD_CHANNEL_1); done2 = DMA_PDD_GetDoneFlag(DMA_BASE_PTR, DMA_PDD_CHANNEL_2); if (done0 && done1 && done2) { break; /* done! */ } WAIT1_WaitOSms(1); /* give back some time */ } TMOUT1_LeaveCounter(handle); WAIT1_Waitus(50); /* latch, low for at least 50 us (40x1.25us) */ /* disable DMA-Muxing: necessary, otherwise DMA events on TPM0 channel 0 might be still latched. * Will enable muxing for next transfer */ DMAMUX_PDD_EnableChannel(DMAMUX0_BASE_PTR, 0, PDD_DISABLE); DMAMUX_PDD_EnableChannel(DMAMUX0_BASE_PTR, 1, PDD_DISABLE); DMAMUX_PDD_EnableChannel(DMAMUX0_BASE_PTR, 2, PDD_DISABLE); /* disable peripheral DMA */ TPM_PDD_WriteStatusControlReg(TPM0_DEVICE,TPM_PDD_ReadStatusControlReg(TPM0_DEVICE)&(~TPM_SC_DMA_MASK)); TPM_PDD_DisableChannelDma(TPM0_DEVICE, 1); TPM_PDD_DisableChannelDma(TPM0_DEVICE, 0); StopTimer(); /* stop TPM */ if (isTimeout) { return ERR_BUSY; } return ERR_OK; }
/* write a byte to the PS2 device */ void PS2_write(unsigned char data) { unsigned char i; unsigned char parity = 1; FRTOS1_taskENTER_CRITICAL(); BitClock_SetDir((bool)INPUT); BitData_SetDir((bool)INPUT); WAIT1_Waitus(100); // Poner el bus en el modo Request to Send (petición de envío), para ello primero debe //inhibir la comunicación llevando //la línea de PS2_PIN_clock a “0” por al menos 100 microsegundos //El protocolo dice por lo menos 100 ms //PS2_PIN_data = high, PS2_PIN_clock = low: Communication Inhibited. BitClock_SetDir((bool)OUTPUT); BitClock_ClrVal(); WAIT1_Waitus(100); //Se lleva al bus al estado de Request to Send poniendo la línea PS2_PIN_data en “bajo” //y liberando la línea PS2_PIN_clock (estado “alto”) //PS2_PIN_data = low, PS2_PIN_clock = high: Host Request-to-Send BitData_SetDir((bool)OUTPUT); BitData_ClrVal(); WAIT1_Waitus(10); //Se libera la linea PS2_PIN_clock BitClock_SetDir((bool)INPUT); //Se espera a que el mouse tome el control y nos de el tren de pulsos //El Mouse va a leer cuando el PS2_PIN_clock este en alto //Cuando el mouse detecte este estado comenzará a enviar pulsos de reloj while (BitClock_GetVal() == 1U); //El host cambia los datos cuando la línea PS2_PIN_clock esta en “bajo” //y el mouse los lee cuando PS2_PIN_clock está en “alto” for (i=0; i < 8; i++) { if (data & 0x01) { BitData_SetDir((bool)INPUT); //Si el bit es un 1 se pone un 1 en el bus de datos } else { BitData_SetDir((bool)OUTPUT); BitData_ClrVal(); //Si el bit es un 0 se pone un 0 en el bus de datos } //Hay que esperar que el clk se ponga en alto que es cuando //el reloj va a leer el dato while (BitClock_GetVal() == 0U); //Hay que esperar que esperar que el clk se vuelva a poner en bajo //para enviar while (BitClock_GetVal() == 1U); parity = parity ^ (data & 0x01); data = data >> 1; } //Luego de mandar los datos, se envia el bit de paridad if (parity) { BitData_SetDir((bool)INPUT); } else { BitData_SetDir((bool)OUTPUT); BitData_ClrVal(); } //Se espera a que el ckl lea el bit de paridad while (BitClock_GetVal() == 0U); //Se espera a que baje el pulso while (BitClock_GetVal() == 1U); //Se libera el bus de datos BitData_SetDir((bool)INPUT); WAIT1_Waitus(50); //Esperar a que se ponga en bajo el ckl while (BitClock_GetVal() == 1U); //Esperar a que se liberen el bus de datos y clk while ((BitClock_GetVal() == 0U) || (BitData_GetVal() == 0U)); //Poner en espera los datos entrantes BitClock_SetDir((bool)OUTPUT); BitClock_ClrVal(); FRTOS1_taskEXIT_CRITICAL(); }
void readSensors(uint16_t sensorsValue[NUMBER_OF_SENSORS]){ /*used for reading how long it take for the line to fall to 0 *and this way detecting the black or white level */ uint16_t counterReadValue; uint16_t i; /* start the infrared LED */ IR_LED_SetVal(); // WAIT1_Waitus(USEC_WAITING_INFRARED_LED_TO_START); /* init the vector to reflecting by default * it will be populated with values in case reflection is discovered * - just a convention 0 means black and 1 means white */ for (i=0;i<NUMBER_OF_SENSORS;i++){ sensorsValue[i]=0; } /* set sensors as output and put them into 1 */ LS1_SetDir(TRUE); LS1_SetVal(); A1_SetDir(TRUE); A1_SetVal(); LS2_SetDir(TRUE); LS2_SetVal(); LS3_SetDir(TRUE); LS3_SetVal(); RS3_SetDir(TRUE); RS3_SetVal(); RS2_SetDir(TRUE); RS2_SetVal(); RS1_SetDir(TRUE); RS1_SetVal(); /* wait until sensors capacitor is fully up */ WAIT1_Waitus(USEC_WAITING_FOR_CAPACITOR_TO_CHARGE); /* set all sensors as inputs to read them */ LS1_SetDir(FALSE); LS2_SetDir(FALSE); LS3_SetDir(FALSE); RS3_SetDir(FALSE); RS2_SetDir(FALSE); RS1_SetDir(FALSE); /* read the time needed for the value of the sensor line to reach 0 * the longer it takes the less light it is reflected */ /* reset of the counter (using periods of 6.1 usec) used to count time * sensor needs till it line is falling to 0 */ CountTimer_ResetCounter((LDD_TDeviceData *)NULL); /* effective reading of the value of the line + decision if it is black or white * the sensor is seeing */ counterReadValue = CountTimer_GetCounterValue((LDD_TDeviceData *)NULL); while (counterReadValue < BLACK_OR_WHITE_BOUNDRY){ /* do nothing wait till enough time has passed * after this time has passed the sensors should be * in correct shape */ counterReadValue = CountTimer_GetCounterValue((LDD_TDeviceData *)NULL); } /* basically if level did not reach 0 which means it is black * and that is recorded in the sensors vector with a value of 1 * a bit tricky and maybe confusing here are they are opposite */ if(LS1_GetVal()==0){ sensorsValue[0] = 1; } if(LS2_GetVal()==0){ sensorsValue[1] = 1; } if(LS3_GetVal()==0){ sensorsValue[2] = 1; } if(RS3_GetVal()==0){ sensorsValue[3] = 1; } if(RS2_GetVal()==0){ sensorsValue[4] = 1; } if(RS1_GetVal()==0){ sensorsValue[5] = 1; } /* shut down the LED emitting infrared - need to see if this step is needed * here decision taken not to shut down the sensor * */ // IR_LED_ClrVal(); }
int Read(uint8_t *temp, uint8_t *humi) { int cntr; int loopBits; uint8_t buffer[5]; int i; int data; /* init buffer */ for (i = 0; i < sizeof(buffer); i++) { buffer[i] = 0; } //set to input and check if the signal gets pulled up DHT_SetInput(); WAIT1_Waitus(50); if (DHT_GetVal() == 0) { return NO_PULLUP; } // send start signal DHT_SetOutput(); DHT_ClrVal(); WAIT1_Waitms(18); /* keep signal low for at least 18 ms */ DHT_SetInput(); WAIT1_Waitus(50); /* check for acknowledge signal */ if (DHT_GetVal() != 0) { /* signal must be pulled low by the sensor */ return NO_ACK_0; } /* wait max 90 us for the ack signal from the sensor */ cntr = 18; while (DHT_GetVal() == 0) { /* wait until signal goes up */ WAIT1_Waitus(5); if (--cntr == 0) { return NO_ACK_1; /* signal should be up for the ACK here */ } } /* wait until it goes down again, end of ack sequence */ cntr = 18; while (DHT_GetVal() != 0) { /* wait until signal goes down */ WAIT1_Waitus(5); if (--cntr == 0) { return NO_ACK_0; /* signal should be down to zero again here */ } } /* now read the 40 bit data */ i = 0; data = 0; loopBits = 40; do { cntr = 11; /* wait max 55 us */ while (DHT_GetVal() == 0) { WAIT1_Waitus(5); if (--cntr == 0) { return NO_DATA_0; } } cntr = 5; /* wait max 75 us */ while (DHT_GetVal() != 0) { WAIT1_Waitus(15); if (--cntr == 0) { return NO_DATA_1; } } data <<= 1; /* next data bit */ if (cntr < 3) { /* data signal high > 40 us ==> data bit 1 */ data |= 1; } if ((loopBits & 0x7) == 1) { /* next byte */ buffer[i] = data; i++; data = 0; } } while (--loopBits != 0); /* now we have the 40 bit (5 bytes) data: * byte 1: humidity integer data * byte 2: humidity decimal data (not used for DTH11, always zero) * byte 3: temperature integer data * byte 4: temperature fractional data (not used for DTH11, always zero) * byte 5: checksum, the sum of byte 1 + 2 + 3 + 4 */ /* test CRC */ if (buffer[0] + buffer[1] + buffer[2] + buffer[3] != buffer[4]) { return BAD_CRC; } /* store data values for caller */ *humi = ((int) buffer[0]); *temp = ((int) buffer[2]); return OK; }
void DHT11() { byte dht11_dat[5]; byte dht11_in; byte i; // output DHT_SetDir(1); // pull-down i/o pin for 18ms DHT_ClrVal(); WAIT1_Waitms(19); DHT_SetVal(); //pull-up i/o pin for 30ms WAIT1_Waitus(30); //input DHT_SetDir(0); WAIT1_Waitus(30); while(!dht11_in) { dht11_in = DHT_GetVal(); } // if (dht11_in) { // printf("dht11 start condition 1 not met\r\n"); // return; // } WAIT1_Waitus(80);//delayMicroseconds(80); // dht11_in = DHT_GetVal();//dht11_in = PINC & _BV(DHT11_PIN); // if (!dht11_in) { // printf("dht11 start condition 2 not met\r\n"); // return; // } // WAIT1_Waitus(80);//delayMicroseconds(80); // now ready for data reception for (i = 0; i < 5; i++) dht11_dat[i] = read_dht11_dat(); DHT_SetDir(1); DHT_SetVal(); byte dht11_check_sum = dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]; // check check_sum if (dht11_dat[4] != dht11_check_sum) { printf("DHT11 checksum error\r\n"); } printf("Current humdity = "); //printf("%d",dht11_dat[0]); UTIL1_Num8uToStr(strTmp1, sizeof(strTmp1),dht11_dat[0]); UTIL1_Num8uToStr(strTmp2, sizeof(strTmp2),dht11_dat[1]); UTIL1_strcat(strTmp1, sizeof(strTmp1),(byte *)"."); UTIL1_strcat(strTmp1, sizeof(strTmp1),strTmp2); UTIL1_strcat(strTmp1, sizeof(strTmp1),(byte *)"%%\r\n"); //printf((char *)strTmp1); //printf("."); //printf((char *)strTmp2); //printf("%d",dht11_dat[1]); //printf("%%\r\n"); printf((char *)strTmp1); printf("temperature = "); printf("%d",dht11_dat[2]); printf("."); printf("%d",dht11_dat[3]); printf("C \r\n"); // WAIT1_Waitms(2000);//delay(2000); }
void irSensors(struct sensor s[6]){ /*############################################################################################################################################################################# ** Functia irSensors este folosita la citirea valorilor "raw" ale senzorilor. **Argumentul functiei este un vector de tip structura de date sensor. **Pasii pe care ii urmeaza: ** --declara pini care sunt conectati la senzori ca pini de output ** --seteaza valorile senzorilor pe HIGH -> se incarca condensatorul ** --asteapta 50us pentru incarcarea completa a condensatorului ** --declara pini care sunt conectati la senzori ca pini de input ** --reseteaza timer-ul deoarece poate iesi din limitele tipului de date int dupa un anumit timp ** --citirea valorii timer-ului ** --atribuirea valorii timer-ului variabilelor unde vom retine valorile senzorilor ** --intrarea in bucla de citire a senzorilor(se va termina cand toti pinii de la senzori au valoarea 0): ** ++variabila timer este folosita pentru a iesi din bucla daca este depasita valoarea constantei prag(datele mai mari decat valoarea pragului nu sunt relevante + ** citire mai rapida) ** ++verificarea valorilor pinilor conectati la senzori ** ++valoarea unui senzor devine egala cu valoarea timer-ului daca pinul respectiv are valoarea 1 (in final valoarea unui senzor va fi egala cu ultima valoare a ** timer-ului inainte ca pinul respectiv sa ia valoarea 0) ** ++daca variabila timer este mai mare decat valoarea pragului atunci este intrerupta executia buclei **#############################################################################################################################################################################*/ int v[6]; int timer,i; const int prag=1000; IR_LED_SetOutput(); IR_LED_PutVal(1); /*** Declararea senzorilor ca output. ***/ A1_SetOutput(); A3_SetOutput(); D11_SetOutput(); A0_SetOutput(); A2_SetOutput(); D5_SetOutput(); /*** Setarea senzoriilor pe HIGH. ***/ A1_PutVal(1); A3_PutVal(1); D11_PutVal(1); A0_PutVal(1); A2_PutVal(1); D5_PutVal(1); /*** Asteapta 50us pentru incarcarea completa a condensatorului. ***/ WAIT1_Waitus(50); //Declararea senzorilor ca input. ***/ A1_SetInput(); A3_SetInput(); D11_SetInput(); A0_SetInput(); A2_SetInput(); D5_SetInput(); /*** Resetarea timer-ului. ***/ CountTimer_ResetCounter((LDD_TDeviceData *)NULL); /*** Citirea vaorii timer-ului. ***/ timer=CountTimer_GetCounterValue((LDD_TDeviceData *)NULL); s[0].value=timer; s[1].value=timer; s[2].value=timer; s[3].value=timer; s[4].value=timer; s[5].value=timer; /*** Bucla de citire -- executia buclei se va termina cand s-a terminat citirea tuturor senzorilor. ***/ while(v[0] || v[1] || v[2] || v[3] || v[4] || v[5]){ /*** Variabila timer este acum folosit ca un prag pentru a nu pierde prea mult timp cat senzorii sunt pe negru. ***/ timer=CountTimer_GetCounterValue((LDD_TDeviceData *)NULL); /*** Variabilelor s1-s6 le este atribuita valoarea intrarilor senzoriilor(0 sau 1). ***/ v[0]=A1_GetVal(); v[1]=A3_GetVal(); v[2]=D11_GetVal(); v[3]=A0_GetVal(); v[4]=A2_GetVal(); v[5]=D5_GetVal(); /*** Daca intrarea unui senzor este 1 ii este atribuita variabilei s[i].value ultima valoare a timer-ului. ***/ for(i=0; i<6; i++){ if(v[i]) s[i].value=CountTimer_GetCounterValue((LDD_TDeviceData *)NULL); } if(timer>prag) break; } }