int main() { char out_buffer[32]; CyGlobalIntEnable; /* Enable global interrupts. */ isr_wire_StartEx(wireHandler); isr_uart_StartEx(uartHandler); isr_stop_StartEx(stopHandler); isr_wstart_StartEx(wstartHandler); isr_ustart_StartEx(ustartHandler); UART_Start(); uint16_t counter1, counter2; for(;;) { counter1 = Timer_wire_ReadCounter(); sprintf(out_buffer,"Wired: %i:%i:%i:%i\n\r",wire.hour,wire.min,wire.sec, counter1); UART_PutString(out_buffer); counter2 = Timer_uart_ReadCounter(); sprintf(out_buffer,"Xbee: %i:%i:%i:%i\n\r",uart.hour,uart.min,uart.sec, counter2); UART_PutString(out_buffer); sprintf(out_buffer, "delta = %i\n\n\r", Timer_wire_ReadCounter()-Timer_uart_ReadCounter()); UART_PutString(out_buffer); CyDelay(500); } }
/******************************************************************************* * 获取温度 ********************************************************************************/ void getTempture() { uint16 voltageRawCount;//电平值得统计 ADC_DelSig_1_IsEndConversion(ADC_DelSig_1_WAIT_FOR_RESULT); /* 等待温度转换完成 */ voltageRawCount = ADC_DelSig_1_GetResult32(); /* 得到转换后的值 GetResult16 最大值是32767 */ tempture = 1.024*voltageRawCount/65536*1000; /* 根据公式进行转换 */ if (voltageRawCount <= 0) { errorDisplay();/* 处理错误数据或是零下的温度 */ UART_PutString("sl0e"); } else if(tempture > highTempture ) { char tem[6]; tem[0] = 's'; tem[1] = 'h'; tem[2] = '0'; tem[3] = 'e'; tem[4] = '\0'; UART_PutString(tem); LCD_Char_1_PrintNumber(highTempture); } else if(tempture < lowTempture)//防止温度值溢出 { char tem[6]; tem[0] = 's'; tem[1] = 'l'; tem[2] = '0'; tem[3] = 'e'; tem[4] = '\0'; UART_PutString(tem); LCD_Char_1_PrintNumber(lowTempture); } else { char tem[9]; tem[0] = 's'; tem[1] = 't'; tem[2] = '0'; tem[3] = tempture/100 + 48; tem[4] = (tempture%100)/10 + 48; tem[5] = tempture%10 + 48; tem[6] = 'e'; tem[7] = '\0'; UART_PutString(tem); } //LCD_Char_1_PrintString(" tempture "); //LCD_Char_1_PrintNumber(tempture/10); /* 打印小数点前面的数据 */ //LCD_Char_1_PrintNumber(tempture%10); /* 打印小数点后面的数据 */ //LCD_Char_1_PrintNumber(tempture); //updateDisplay(tempture); /* 打印数据到LCD */ }
void BT_Cmd(void) { int n,m; char cmd[50]; n = Check_Rx_Buffer(UART_BT); if (n >= 2) { // parser the command cmd[0] = UART_PopFIFO(UART_BT); cmd[1] = UART_PopFIFO(UART_BT); cmd[2] = 0; UART_PutString(UART_BT, cmd); m = atoi(cmd); switch (m) { case CMD_DEBUG_1: cmd_sw_debug = 1 - cmd_sw_debug; sprintf(cmd, "Debug=%d\r\n", cmd_sw_debug); break; case CMD_MOTOR: cmd_sw_motor = 1 - cmd_sw_motor; sprintf(cmd, "Motor=%d\r\n", cmd_sw_motor); break; case CMD_ACCEL_X_OFFSET_U: Accel_x_offset += 100; sprintf(cmd, "Accel_x_offset=%f\r\n", Accel_x_offset); break; case CMD_ACCEL_X_OFFSET_D: Accel_x_offset -= 100; sprintf(cmd, "Accel_x_offset=%f\r\n", Accel_x_offset); break; case CMD_GYRO_Y_OFFSET_U: Gyro_y_offset += 2; sprintf(cmd, "Gyro_y_offset=%f\r\n", Gyro_y_offset); break; case CMD_GYRO_Y_OFFSET_D: Gyro_y_offset -= 2; sprintf(cmd, "Gyro_y_offset=%f\r\n", Gyro_y_offset); break; default: sprintf(cmd, "No Cmd=%d\r\n", m); break; } UART_PutString(UART_BT, cmd); } }
int main() { /* Place your initialization/startup code here (e.g. MyInst_Start()) */ ADC_DelSig_Start(); AMux_Start(); UART_Start(); CyGlobalIntEnable; /* Uncomment this line to enable global interrupts. */ // LCD_Char_Start(); //status = LCD_SegStat_Start(); CyDelay(10000u); //10 second delay to allow for sensors to "warm up" //uint8 buffer[50]; //uint8 buffer2[50]; uint8 value[128]; for(;;) { /* Place your application code here. */ Radiation rad; rad = take_radiation_reading(); Vaisala vais; vais = take_Temp_RH_reading(); //LCD_Char_ClearDisplay(); //LCD_Char_Position(0u, 0u); //sprintf(buffer,"%d %d %d %d", (int)fake.SW_In, (int)fake.SW_Out, (int)fake.LW_In, (int)fake.LW_Out); //LCD_Char_PrintString(buffer); //LCD_Char_Position(1u, 0u); //sprintf(buffer2,"%d %d",(int)fake2.Temp, (int)fake2.RH); //LCD_Char_PrintString(buffer2); sprintf(value,"%d,%d,%d,%d,%d,%d,%d\r\n",(int)rad.SW_In, (int)rad.SW_Out, (int)rad.LW_In, (int)rad.LW_Out,(int)((rad.temp-273.15)*100), (int)(vais.Temp*100), (int)(vais.RH*100)); UART_PutString(value); uint8 x = 0; } }
/* * JGA25-371全金属电机(12V)、超耐磨65MM橡胶轮胎、3MM铝合金车身 * 2014.02.08 Regis */ void vTask_Balance_Car_1(void *pvParameters ) { (void)pvParameters; //prevent compiler worning/error char m[100]; portTickType xLastWakeTime; //portTickType xStartTime, xEndTime; Balance_Car_Init(); Motor_L298N_Init(); MPU6050_Init(); Motor_L298N_PWM_Init(1000); //1kHz xLastWakeTime = xTaskGetTickCount(); for( ;; ) { vTaskDelayUntil(&xLastWakeTime, task_dt); // set the timer as 10ms BT_Cmd(); //xStartTime = xTaskGetTickCount(); Angle_Calculate(); Position_Calculate(); PWM_Calculate(); speed_mr = speed_ml = 0; //xEndTime = xTaskGetTickCount(); //xEndTime -= xStartTime; if (cmd_sw_debug) { //sprintf(m, "%u %f %f S:%f %f P:%d %d\r\n", xEndTime, Angle, Gyro_y, speed, position, PWM_R, PWM_L); sprintf(m, "%f %f %f %d\r\n", Angle, Gyro_y, speed, PWM_L); UART_PutString(UART_BT, m); } } }
void oa_set_target(struct obstacle_avoidance * oa,int16_t x,int16_t y){ oa->target_xy.x = x; oa->target_xy.y = y; oa->state = OA_TARGET_SET; #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> New target! -> {%d,%d}\r\n", oa->target_xy.x,oa->target_xy.y); UART_PutString(&uart_out_buffer); #endif }
void main(){ CYGlobalIntDisable;//Disable interrupts to avoid triggering during setup. LCD_Start();// Start LCD. UART_Start();// Start UART. Rx_Int_Start();//Start the Interrupt. Rx_Int_SetVector(Rx_ISR);//Set the Vector to the ISR. LCD_PrintString("UART:RX ISR Demo");//Print to the LCD. UART_PutString("UART:RX ISR Demo");//Print to Serial Terminal. CyDelay(1000); LCD_ClearDisplay();//Clear the screen for RX Data. CYGlobalIntEnable;//Enable Interrupts,and let the Games begin! for(;;); }
int main() { CyGlobalIntEnable; /* Enable global interrupts. */ // Set up LCD screen LCD_Start(); LCD_ClearDisplay(); rx_isr_StartEx(rx_isr); // start RX interrupt (look for CY_ISR with RX_INT address) // for code that writes received bytes to LCD. UART_Start(); // initialize UART UART_ClearRxBuffer(); // Check status message UART_PutString("AT\r\n"); CyDelay(1000);\ LCD_ClearDisplay(); // Set name to VizDude UART_PutString("AT+NAME=VizDude\r\n"); CyDelay(1000);\ LCD_ClearDisplay(); // Set rate to 115200 Baud, 1 stop bit, no parity UART_PutString("AT+UART=115200,1,0\r\n"); CyDelay(1000);\ LCD_ClearDisplay(); /* Place your initialization/startup code here (e.g. MyInst_Start()) */ for(;;) { /* Place your application code here. */ } }
// This function get's a line of text. It writes data into buffer with a maximum size of bufferLen. The function returns number of bytes written // when enter is pressed. Values of buffer and strPos are continuously passed to the function. The function returns TRUE if a line was received // otherwise false if its still getting data char GetLine(char *buffer, char *strPos, char bufferLen) { char c; static char newCommand = TRUE; // Since this is static, only gets set to true once but is a global essentially if (newCommand) // If it is a new command, put a > character and set this to false { UART_PutChar('>'); newCommand = FALSE; } if ((c = UART_cReadChar())) { if (c == 0x08 || c == 0x7F) // Delete or backspace pressed { if (*strPos > 0) // Only delete if there are characters to delete { (*strPos)--; // Set the position back one UART_PutString(rubout); // Sends the rubout sequence to the serial. } } else if (c == 0x0D) // Newline enter is pressed { buffer[*strPos] = 0x00; // put the null character at the current strPos UART_PutCRLF(); // Go to another line *strPos = 0; newCommand = TRUE; // Next time GetLine is called, > will be outputted return TRUE; // This means that the program should handle the buffer } else if (c >= 0x20 && c < 0x7F) // only valid characters to the string. These are any alphabet, numeric, or symbols { if (*strPos < bufferLen) // If there is space in the buffer { buffer[(*strPos)++] = c; // Set the current character in buffer to c and then increment strPos UART_PutChar(c); // Send the character to the computer } else UART_PutChar(0x07); // Send BEL key because there is no more space left to add to the string } } return FALSE; // Data is not ready to be handled }
// This function gets a line of text. It writes data into buffer with a maximum size of bufferLen. The function returns number of bytes written // when enter is pressed void GetLine(char *buffer, char bufferLen) { char c; char strPos = 0; // Current position in the string UART_PutChar('>'); // Print line pointer while (1) { c = UART_cReadChar(); // Use UART module to read the character user enters if (c == 0x08 || c == 0x7F) // Delete or backspace pressed { if (strPos > 0) // Only delete if there are characters to delete { strPos--; // Set the position back one UART_PutString(rubout); // Sends the rubout sequence to the serial. } } else if (c == 0x0D) // Newline enter is pressed { buffer[strPos] = 0x00; // put the null character at the current strPos UART_PutCRLF(); // Go to another line break; } else if (c >= 0x20 && c < 0x7F) // only valid characters to the string. These are any alphabet, numeric, or symbols { if (strPos < bufferLen) // If there is space in the buffer { buffer[strPos++] = c; // Set the current character in buffer to c and then increment strPos UART_PutChar(c); // Send the character to the computer } else UART_PutChar(0x07); // Send BEL key because there is no more space left to add to the string } } return; }
/********************************************************************* * * Logging: OS dependent Note: Logging is used in higher debug levels only. The typical target build does not use logging and does therefore not require any of the logging routines below. For a release build without logging the routines below may be eliminated to save some space. (If the linker is not function aware and eliminates unreferenced functions automatically) */ void FS_X_Log(const char *s) { FS_USE_PARA(s); UART_PutString((uint8*)s); }
void oa_find_adj_areas_to_target(struct obstacle_avoidance * oa,play_area * my_area,play_area * target_area){ int8_t sens_x,sens_y; sens_x = target_area->x - my_area->x; sens_y = target_area->y - my_area->y; if(sens_x>0){ //we have to increase area x to get to target oa->adj_area_tab[0].x = my_area->x+1; sens_x=1; } else if(sens_x<0){ oa->adj_area_tab[0].x = my_area->x-1; sens_x = -1; } else //==0 oa->adj_area_tab[0].x = my_area->x; if(sens_y>0){ oa->adj_area_tab[0].y = my_area->y+1; sens_y = 1; } else if(sens_y<0){ oa->adj_area_tab[0].y = my_area->y-1; sens_y = -1; } else oa->adj_area_tab[0].y = my_area->y; /* Here we have to differenciate two cases: 1st: (x: target R: my robot, the . are the adj_areas to targed) the move is straight ------------------- | | x | | |-----|------|-----| | . | . | . | |-----|------|-----| | | R | | |-----|------|-----| 2nd: the move is diagonal ------------------- | R | . | | |-----|------|-----| | . | . | | |-----|------|-----| | | | x | |-----|------|-----| */ if(sens_x == 0 || sens_y == 0){ //we are in the 1st case here oa->adj_area_tab[1].x = oa->adj_area_tab[0].x - sens_y; oa->adj_area_tab[1].y = oa->adj_area_tab[0].y - sens_x; oa->adj_area_tab[2].x = oa->adj_area_tab[0].x + sens_y; oa->adj_area_tab[2].y = oa->adj_area_tab[0].y + sens_x; } else{ //none of them are 0, so we are in the 2nd case //we save the 2 other possible combinations oa->adj_area_tab[1].x = oa->adj_area_tab[0].x; oa->adj_area_tab[1].y = my_area->y; oa->adj_area_tab[2].x = my_area->x; oa->adj_area_tab[2].y = oa->adj_area_tab[0].y; } //sprintf(uart_out_buffer,"oa> my area {%d,%d} target {%d,%d}",my_area.x,my_area.y,target_area.x,target_area.y); //UART_PutString(&uart_out_buffer); sprintf(uart_out_buffer,"next areas: {%d,%d}{%d,%d}{%d,%d} \r\n",oa->adj_area_tab[0].x,oa->adj_area_tab[0].y,oa->adj_area_tab[1].x,oa->adj_area_tab[1].y,oa->adj_area_tab[2].x,oa->adj_area_tab[2].y); UART_PutString(&uart_out_buffer); }
/******************************************************************************* * Function Name: Bootloader_HostLink ******************************************************************************** * * Summary: * Causes the bootloader to attempt to read data being transmitted by the * host application. If data is sent from the host, this establishes the * communication interface to process all requests. * * Parameters: * timeOut: * The amount of time to listen for data before giving up. Timeout is * measured in 10s of ms. Use 0 for an infinite wait. * * Return: * None * *******************************************************************************/ static void Bootloader_HostLink(uint32 timeout) { uint16 CYDATA numberRead; cystatus CYDATA readStat; uint16 bytesToRead; uint16 bytesToWrite; uint32 counterVal; static const uint8 deviceID[7] = {'A','V','R','B', 'O', 'O', 'T'}; static const uint8 swID[2] = {'1', '0'}; static const uint8 hwID[2] = {'1', '0'}; uint32 currentAddress = 0; uint8 packetBuffer[Bootloader_SIZEOF_COMMAND_BUFFER]; /* Initialize communications channel. */ CyBtldrCommStart(); counterVal = 0; do { do { readStat = CyBtldrCommRead(packetBuffer, Bootloader_SIZEOF_COMMAND_BUFFER, &numberRead, 10); counterVal = Reset_Timer_ReadCounter() * -1; #ifdef USE_UART char dbstring[24]; sprintf(dbstring,"%ld\r", counterVal); UART_PutString(dbstring); CyDelay(50); #endif if (counterVal >= timeout) { Bootloader_SET_RUN_TYPE(Bootloader_SCHEDULE_BTLDB); CySoftwareReset(); } } while ( readStat != CYRET_SUCCESS ); Reset_Timer_Stop(); Reset_Timer_WriteCounter(0); Reset_Timer_Start(); switch(packetBuffer[0]) { /************************************************************************* * Set read/write address *************************************************************************/ case 'A': currentAddress = packetBuffer[1] << 9; currentAddress |= packetBuffer[2] << 1; packetBuffer[0] = '\r'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Set read/write address *************************************************************************/ case 'H': currentAddress = packetBuffer[1] << 17; currentAddress |= packetBuffer[2] << 9; currentAddress |= packetBuffer[3] << 1; packetBuffer[0] = '\r'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Erase chip (unimplemented) *************************************************************************/ case 'e': break; /************************************************************************* * Enter/Leave bootloader mode - UNUSED *************************************************************************/ case 'P': case 'L': packetBuffer[0] = '\r'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Exit bootloader *************************************************************************/ case 'E': /* Normally, the CyBootloader checks the validity of the app here. We will * assume that the app is valid b/c it was checked as it was being * uploaded. */ Bootloader_SET_RUN_TYPE(Bootloader_SCHEDULE_BTLDB); packetBuffer[0] = '\r'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); while (USBUART_CDCIsReady() == 0) { /* wait for USB to finish sending response to the exit command */ } CySoftwareReset(); /* Will never get here */ break; /************************************************************************* * Block read *************************************************************************/ case 'g': bytesToRead = packetBuffer[1] << 8; bytesToRead |= packetBuffer[2]; int16 idx; for(idx = 0u; idx < bytesToRead; idx++) { packetBuffer[idx] = Bootloader_GET_CODE_BYTE(currentAddress + idx); } CyBtldrCommWrite(packetBuffer, bytesToRead, NULL, 0); break; /************************************************************************* * Block load *************************************************************************/ case 'B': bytesToWrite = packetBuffer[1]<<8 | packetBuffer[2]; packetBuffer[0] = BlockLoad(packetBuffer[3], bytesToWrite, \ packetBuffer + 4, currentAddress); if ((packetBuffer[0] == '\r') && packetBuffer[3] == 'F') { currentAddress += bytesToWrite; } CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Report device ID *************************************************************************/ case 'S': CyBtldrCommWrite((uint8*)deviceID, 8, NULL, 0); break; /************************************************************************* * Report firmware revision *************************************************************************/ case 'V': CyBtldrCommWrite((uint8*)swID, 2, NULL, 0); break; /************************************************************************* * Report programmer type ('S' for "Serial") *************************************************************************/ case 'p': packetBuffer[0] = 'S'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Report autoincrement address support ('Y' for "Yes") *************************************************************************/ case 'a': packetBuffer[0] = 'Y'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Report block write support ('Y' for "Yes", then two bytes of block size * written MSB first. *************************************************************************/ case 'b': packetBuffer[0] = 'Y'; packetBuffer[1] = 0x01; packetBuffer[2] = 0x00; CyBtldrCommWrite(packetBuffer, 3, NULL, 0); break; /************************************************************************* * Report hardware device version *************************************************************************/ case 'v': CyBtldrCommWrite((uint8*)hwID, 2, NULL, 0); break; /************************************************************************* * Report (bogus) part ID, followed by list terminator 0x00. *************************************************************************/ case 't': packetBuffer[0] = 0x44; packetBuffer[1] = 0; CyBtldrCommWrite(packetBuffer, 2, NULL, 0); break; /************************************************************************* * Report device signature (this is that of the Atmega32u4) *************************************************************************/ case 's': packetBuffer[0] = 0x87; packetBuffer[1] = 0x95; packetBuffer[2] = 0x1e; CyBtldrCommWrite(packetBuffer, 3, NULL, 0); break; /************************************************************************* * Unimplemented fuse AVR fuse register read/write *************************************************************************/ case 'N': case 'Q': case 'F': case 'r': packetBuffer[0] = 0x00; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Unused but implemented in AVRDUDE, so some response needed. *************************************************************************/ case 'T': case 'x': case 'y': packetBuffer[0] = '\r'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; /************************************************************************* * Unsupported command *************************************************************************/ default: packetBuffer[0] = '?'; CyBtldrCommWrite(packetBuffer, 1, NULL, 0); break; } } while (1); }
void oa_sixt(struct obstacle_avoidance * oa){ /*we check different possible "next_area" that are in fact the adj_areas and try to find the shortest, and the most safe one*/ //we start by computing the possibles next areas int16_t my_pos_x,my_pos_y; play_area my_area,next_area,target_area,opp_area; uint8_t i,j; int16_t d_nxt_area_opp[3],d_nxt_area_target[3]; float tmp; uint8_t index0,index1,index2; xy_position my_pos_xy; next_area.x=0; next_area.y=0; my_pos_x=position_get_x_s16(oa->traj->position); my_pos_y=position_get_y_s16(oa->traj->position); my_pos_xy.x = my_pos_x; my_pos_xy.y = my_pos_y; my_area = oa_xy_to_area(my_pos_x,my_pos_y); target_area = oa_xy_to_area(oa->target_xy.x,oa->target_xy.y); opp_area = oa_xy_to_area(oa->opponent_xy.x,oa->opponent_xy.y); //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: char is_opp_adj=oa_is_in_v4(&my_area,&opp_area); //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> my area {%d,%d}\r\n",my_area.x,my_area.y); UART_PutString(&uart_out_buffer); sprintf(uart_out_buffer,"oa> target area {%d,%d}\r\n",target_area.x,target_area.y); UART_PutString(&uart_out_buffer); sprintf(uart_out_buffer,"oa> opp area {%d,%d}\r\n",opp_area.x,opp_area.y); UART_PutString(&uart_out_buffer); #endif /*let's calc adj areas now..*/ oa_find_adj_areas_to_target(oa,&my_area,&target_area); /*we check if one or more, of the computed adj areas isn't/aren't one of the forbidden areas or just out of the game_area*/ for(i=0;i<3;i++){ for(j=0;j<NB_FORBIDDEN_AREAS;j++){ xy_position pos1 = oa_area_to_xy(oa->adj_area_tab[i]); // xy_position pos2 = oa_area_to_xy(target_area); if( ( (oa->adj_area_tab[i].x == oa->forbidden_area[j].x) && (oa->adj_area_tab[i].y == oa->forbidden_area[j].y)) || oa_is_out_of_table(oa->adj_area_tab[i]) || !( oa_get_com_dt(pos1,oa->target_xy)) || !( oa_get_com_dt(my_pos_xy,pos1)) || ((oa->adj_area_tab[i].x ==opp_area.x)&&(oa->adj_area_tab[i].y==opp_area.y)) ){ /*if adj area is target, just forget about the forbidden areas...*/ if((oa->adj_area_tab[i].x == target_area.x) && (oa->adj_area_tab[i].y == target_area.y)){ //not forbidden areas when it's out target! d_nxt_area_opp[i] = 0; d_nxt_area_target[i] = 0; } else { //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if (is_opp_adj) { if (oa_is_in_v4(&oa->adj_area_tab[i],&opp_area)) { //on a une case en diagonale, on veut la remplacer if( oa->adj_area_tab[i].x==opp_area.x) //on remplace par une case du voisinage de my_area qui n'est pas l'adacent oa->adj_area_tab[i].x=my_area.x; else //oa->adj_area_tab[i].y==opp_area.y oa->adj_area_tab[i].y=my_area.y; } else { d_nxt_area_opp[i] = MARKED_FORBIDDEN; d_nxt_area_target[i] = MARKED_FORBIDDEN; } } else { d_nxt_area_opp[i] = MARKED_FORBIDDEN; d_nxt_area_target[i] = MARKED_FORBIDDEN; } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: } //if((oa->adj_area_tab[i].x != target_area.x) && (oa->adj_area_tab[i].y != target_area.y)){} #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> area %d is forb. or out of table!\r\n",i); UART_PutString(&uart_out_buffer); #endif //} } } } /*we calc the dist from opponent and from target for authorized next areas we'll choose the shortest one from the target AND the most far from the opponent -(NO YET)distance from target has a coeff of 1/2 -distance from opponent has a coeff 1 we'll choose the smallest result[] */ uint16_t dist_target_opp = ABS(target_area.x - opp_area.x)*ABS(target_area.x - opp_area.x) + ABS(target_area.y - opp_area.y)*ABS(target_area.y - opp_area.y); uint16_t dist_me_opp = ABS(opp_area.x - my_area.x)*ABS(opp_area.x - my_area.x) + ABS(opp_area.y - my_area.y)*ABS(opp_area.y - my_area.y); if((dist_me_opp > MIN_DIST_BEFORE_IGNORING_OPP) ){ //&& (dist_me_opp > MIN_DIST_BEFORE_IGNORING_OPP) /*if we, and the target are too far from the opponent, we ignore the opponent for the next_area choice*/ #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> opp too far! d:%d(^1/2) check. d aj<->targ.!\r\n",dist_target_opp); UART_PutString(&uart_out_buffer); #endif for(i=0;i<3;i++){ if( d_nxt_area_target[i] != MARKED_FORBIDDEN){ d_nxt_area_target[i] = (int16_t)((oa->adj_area_tab[i].x - target_area.x)*(oa->adj_area_tab[i].x - target_area.x) + (oa->adj_area_tab[i].y - target_area.y)*(oa->adj_area_tab[i].y - target_area.y)); } } /*sorting d_my_area_target ascending (0 shortest, 3 longest)*/ uint8_t sorted_d_nxt_area_target[3]; oa_sort_tab3(d_nxt_area_target,sorted_d_nxt_area_target); index0=sorted_d_nxt_area_target[0]; index1=sorted_d_nxt_area_target[1]; index2=sorted_d_nxt_area_target[2]; #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> sorted areas {%d,%d}{%d,%d}{%d,%d}\r\n", oa->adj_area_tab[index0].x,oa->adj_area_tab[index0].y, oa->adj_area_tab[index1].x,oa->adj_area_tab[index1].y, oa->adj_area_tab[index2].x,oa->adj_area_tab[index2].y); UART_PutString(&uart_out_buffer); #endif /*electing next area (we have to choose the shortest)*/ for(i=0;i<3;i++){ j = sorted_d_nxt_area_target[2-i]; //var reuse if(d_nxt_area_target[j]!=MARKED_FORBIDDEN){ next_area = oa->adj_area_tab[j]; } } } else{ if(dist_target_opp==0){ //really close if(oa->wait<TIMEOUT_WAIT_IN_PLACE){ #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> opp in same place than target! waiting %d \r\n",oa->wait); UART_PutString(&uart_out_buffer); #endif next_area.x = 0; next_area.y = 0; oa->wait++; } else{ /**/ #ifdef DEBUG_OA UART_CPutString("oa> waiting for soooo long... going back to prev quad\r\n"); #endif oa_goto_quad(oa,oa->prev_quad); } } else{ #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> opp too close d:%d(^1/2) checking dist op<->adj\r\n",dist_me_opp); UART_PutString(&uart_out_buffer); #endif for(i=0;i<3;i++){ if( d_nxt_area_opp[i] != MARKED_FORBIDDEN) d_nxt_area_opp[i] = (int16_t)((oa->adj_area_tab[i].x - opp_area.x)*(oa->adj_area_tab[i].x - opp_area.x) + (oa->adj_area_tab[i].y - opp_area.y)*(oa->adj_area_tab[i].y - opp_area.y)); } uint8_t sorted_d_nxt_area_opp[3]; oa_sort_tab3(d_nxt_area_opp,sorted_d_nxt_area_opp); index0= sorted_d_nxt_area_opp[0]; index1= sorted_d_nxt_area_opp[1]; index2= sorted_d_nxt_area_opp[2]; #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> sorted areas {%d,%d}{%d,%d}{%d,%d}\r\n", oa->adj_area_tab[index0].x,oa->adj_area_tab[index0].y, oa->adj_area_tab[index1].x,oa->adj_area_tab[index1].y, oa->adj_area_tab[index2].x,oa->adj_area_tab[index2].y); UART_PutString(&uart_out_buffer); #endif //electing next area (we have to choose the longest) for(i=0;i<3;i++){ j = sorted_d_nxt_area_opp[2-i]; if(d_nxt_area_opp[j]!=MARKED_FORBIDDEN){ next_area = oa->adj_area_tab[j]; } } } } /* We have to take the farest from the opp, and the shortest from target if opp is too far(), we have to ignore it */ //UART_CPutString("oa>election done..\r\n"); if((next_area.x == target_area.x) && (next_area.y == target_area.y)){ trajectory_goto_xy_abs(oa->traj,(double)oa->target_xy.x,(double)oa->target_xy.y); oa->state=OA_IN_TARGET; } else{ if(next_area.x==0 && next_area.y==0){ //no one has been elected, stay in place for the moment #ifdef DEBUG_OA UART_CPutString("oa> sixt: nowhere to go, going back \r\n"); #endif next_area.x= oa->prev_area.x; next_area.y= oa->prev_area.y; } else{ #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> sixt: going to area {%d,%d}\r\n",next_area.x,next_area.y); UART_PutString(&uart_out_buffer); #endif } xy_position pos; pos = oa_area_to_xy(next_area); /*we save our previous area, is next time we have nowhere to go..*/ trajectory_goto_xy_abs(oa->traj,(double)pos.x,(double)pos.y); } oa->prev_area.x = next_area.x; oa->prev_area.y = next_area.y; }
void oa_manage(struct obstacle_avoidance *oa){ xy_position my_pos_xy; my_pos_xy.x = position_get_x_s16(oa->traj->position); my_pos_xy.y = position_get_y_s16(oa->traj->position); uint8_t my_quad = oa_get_quad(my_pos_xy); if(oa->state==OA_TARGET_SET && oa->traj->state==READY){ //new target where to go ! uint8_t opp_quad = oa_get_quad(oa->opponent_xy); uint8_t target_quad = oa_get_quad(oa->target_xy); //oa->state==OA_PROCESSING; uint8_t tmpquad; #ifdef DEBUG_OA UART_CPutString("oa> processing new target\r\n"); #endif if(oa_get_com_dt(my_pos_xy,oa->target_xy)!=0){ //!=0 #ifdef DEBUG_OA UART_CPutString("oa> same dt than target\r\n"); #endif if(oa_get_com_dt(my_pos_xy,oa->opponent_xy)!=0){ #ifdef DEBUG_OA UART_CPutString("oa> same dt than opp-> sixt\r\n"); #endif oa_sixt(oa); } else{ #ifdef DEBUG_OA UART_CPutString("oa> not same dt than opp ->xy!\r\n"); #endif trajectory_goto_xy_abs(oa->traj,oa->target_xy.x,oa->target_xy.y); oa->state=OA_IN_TARGET; } } else{ //==0 #ifdef DEBUG_OA UART_CPutString("oa> not in same dt than target\r\n"); #endif #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> quads: me %d opp %d targ %d\r\n",my_quad,opp_quad,target_quad); UART_PutString(&uart_out_buffer); #endif if(oa_is_adj(my_quad,opp_quad)){ //me & opp are adj #ifdef DEBUG_OA UART_CPutString("oa> I'm adj to opponent\r\n"); #endif if(my_quad==target_quad){ //my_quad==target_quad #ifdef DEBUG_OA UART_CPutString("oa> my_qd=tg_qd->my_qd center\r\n"); #endif oa_goto_quad(oa,my_quad); } else{ //my_quad!=target_quad #ifdef DEBUG_OA UART_CPutString("oa> my_qd!=tg_qd\r\n"); #endif if(target_quad==opp_quad){ //target_quad==opp_quad #ifdef DEBUG_OA UART_CPutString("oa> tg_qd=op_qd->!opp half\r\n"); #endif tmpquad = oa_get_no_half_quad(oa->opponent_xy,target_quad,my_quad); oa_goto_quad(oa,tmpquad); #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> !opp half is qd %d\r\n",tmpquad); UART_PutString(&uart_out_buffer); #endif } else{//target_quad!=opp_quad #ifdef DEBUG_OA UART_CPutString("oa> tg_qd!=op_qd->sym opp quad (but first, my quad)\r\n"); #endif // /*last modified stuff: before: oa_goto_quad(oa,oa_get_sym_quad(opp_quad)); only..*/ if(!(oa->flags & OA_FLAG_GOSYMQD_PART1_DONE)){ setBit(oa->flags,OA_FLAG_GOSYMQD_PART1_DONE); #ifdef DEBUG_OA UART_CPutString("oa> my quad...\r\n"); #endif oa_goto_quad(oa,my_quad); } else { clearBit(oa->flags,OA_FLAG_GOSYMQD_PART1_DONE); #ifdef DEBUG_OA UART_CPutString("oa> opp sym quad...\r\n"); #endif oa_goto_quad(oa,oa_get_sym_quad(opp_quad)); } } } } else{ //me & opp aren't adj #ifdef DEBUG_OA UART_CPutString("oa> I'm not adj to opponent\r\n"); #endif if(my_quad==opp_quad){ //my_quad==opp_quad #ifdef DEBUG_OA UART_CPutString("oa> my_qd=opp_qd->sixt\r\n"); #endif oa_sixt(oa); //apply the celebre "Sixt()" algorithm.. } else{ // !my_quad==opp_quad #ifdef DEBUG_OA UART_CPutString("oa> my_qd!=opp_qd\r\n"); #endif if(target_quad==opp_quad){ //target_quad==opp_quad #ifdef DEBUG_OA UART_CPutString("oa> tg_qd=opp_qd->!opp half\r\n"); #endif //tmpquad = (my_quad-1+oa_get_no_half_quad(oa->opponent_xy,target_quad))%4+1; tmpquad = oa_get_no_half_quad(oa->opponent_xy,target_quad,my_quad); //oa_goto_quad(oa,tmpquad); if(!(oa->flags & OA_FLAG_GOOPPQD_PART1_DONE)){ setBit(oa->flags,OA_FLAG_GOOPPQD_PART1_DONE); #ifdef DEBUG_OA UART_CPutString("oa> my quad...\r\n"); #endif oa_goto_quad(oa,my_quad); } else { clearBit(oa->flags,OA_FLAG_GOOPPQD_PART1_DONE); #ifdef DEBUG_OA UART_CPutString("oa> !opp quad...\r\n"); #endif oa_goto_quad(oa,tmpquad); } //-1 because we don't want to go to the same half quad than the opponent #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> !opp half is qd %d\r\n",tmpquad); UART_PutString(&uart_out_buffer); #endif } else{ // !target_quad==opp_quad #ifdef DEBUG_OA UART_CPutString("oa> tg_qd!=opp_qd->tg qd\r\n"); #endif oa_goto_quad(oa,target_quad); //0 middle, +1 upper half, -1 lower half } } } } } /* //we calc the dist between me and the opp. oa->curr_dist_me_opp =(int16_t)(abs(my_pos_xy.x - oa->opponent_xy.x)*abs(my_pos_xy.x - oa->opponent_xy.x)+abs(my_pos_xy.y - oa->opponent_xy.y)*abs(my_pos_xy.y - oa->opponent_xy.y)); //if we are getting closer, and we are tooo close, we just stop, wait, if((oa->curr_dist_me_opp < oa->prev_dist_me_opp) && (oa->curr_dist_me_opp < MIN_COLLISION_DIST)){ #ifdef DEBUG_OA sprintf(uart_out_buffer,"oa> opp @ %d(^1/2) cm !!!! \r\n",oa->curr_dist_me_opp); UART_PutString(&uart_out_buffer); #endif trajectory_hardstop(oa->traj); oa->state=OA_COLLISION_AVOIDED; oa->timeout=gettime(); } if(oa->state==OA_COLLISION_AVOIDED && (gettime()-oa->timeout)>COLLISION_AVOIDED_TIMEOUT ){ //hope nothing's broken... #ifdef DEBUG_OA UART_CPutString("oa> collision avoided ?\r\n"); #endif oa->state=OA_TARGET_SET; oa->traj->state=READY; oa->timeout = 0; } */ oa->prev_dist_me_opp = oa->curr_dist_me_opp; oa->prev_quad = my_quad; }
int main() { uint8 loop; /* *** Start SPI bus. *** */ SPI_Start(); SPI_SS_Write(1); /* *** Turn off leds at startup. *** */ Led_Red_Write(1); Led_Green_Write(1); Led_Blue_Write(1); /* *** Start serial port. *** */ UART_Start(); UART_PutString("\nPSoC RFM69 Test... PSoC 5LP...\n"); /* *** Blink Red Led two times before starting RFM69 module. * ***/ Led_Red_Write(0); CyDelay(250); Led_Red_Write(1); CyDelay(250); Led_Red_Write(0); CyDelay(250); Led_Red_Write(1); CyDelay(250); /* *** Start RFM69 module. Configure it. If the module is not found, program gets locked. And red led gets turned on. If can find RFM module, then turn on green led. *** */ UART_PutString("Looking for RFM69 module... "); if (RFM69_Start() != 1) { UART_PutString("FAILED\n\n"); Led_Red_Write(0); while (1) {}; } else { UART_PutString("OK\n\n"); Led_Green_Write(1); } /* If testing with interrupts. But disabled until entering RX mode. */ #ifdef TEST_USING_INTERRUPTS RFM_isr_StartEx(RFM69_IsrHandler); #endif /* Start SysTick. When compiled for "MASTER" this is used to control timeout while in reception state. */ CySysTickStart(); // interrupt every 1ms. /* Find unused callback slot. */ for (loop = 0; loop < CY_SYS_SYST_NUM_OF_CALLBACKS; ++loop) { if (CySysTickGetCallback(loop) == NULL) { /* Set callback */ CySysTickSetCallback(loop, SysTickIsrHandler); break; } } /* ----------------------------------------- */ /* Configuration depending on node type. */ #ifdef COMPILE_FOR_MASTER Config_ForMaster(); #endif #if defined COMPILE_FOR_SLAVE_1 || defined COMPILE_FOR_SLAVE_2 Config_ForSlave(); #endif /* ----------------------------------------- */ /* Uncomment next line and adjust params if you want to change bitrate at runtime. */ RFM69_SetBitrateCls(BITRATE_MSB_9600, BITRATE_LSB_9600); /* If testing using encryption, change encryption mode and key at runtime. */ #ifdef TEST_WITH_ENCRYPTION RFM69_Encryption(1, encryptionkey); #endif CyGlobalIntEnable; /* Enable global interrupts. */ for(;;) { /* ----------------------------------------- */ /* Call main loop depending on node type. */ #ifdef COMPILE_FOR_MASTER Loop_Master(); #endif #if defined COMPILE_FOR_SLAVE_1 || defined COMPILE_FOR_SLAVE_2 Loop_Slave(); #endif /* ----------------------------------------- */ } }
int main() { init(); while(1) { //LCD_Char_1_PrintNumber(RxSize); if(RxSize>4)//来自PC的数据,应该进行解析 { int i = 0; //LCD_Char_1_PrintNumber(RxSize); if(RxBuffer[RxSize-1] == 'e' && RxBuffer[0] == 's') { uint8 config = 0; switch(RxBuffer[3])//获取针对节点的信息 { case 'a' : { config += 3; break; } case '0' : { config += 0; break; } case '1' : { config += 1; break; } case '2' : { config += 2; break; } default : { config = 20; break; } } switch(RxBuffer[1]) { case 'c' : //设置节点 { if(RxBuffer[2] == 'o')//打开 { ; } else if(RxBuffer[2] == 'c')//关闭 { config += 10; } configNode(config); break; } case 's' : { if(RxBuffer[2] == 'h')//打开 { ; } else if(RxBuffer[2] == 'l')//关闭 { config += 10; } setNode(config); break; } case 'p' : { setPeriod(config); break; } default : { break; } } for(i = 0; i < RxSize; ++i)//处理完 清指令队列 { RxBuffer[RxSize] = '\0'; } RxSize = 0; } else if(RxBuffer[RxSize-1] == 'e' && RxBuffer[0] != 's')//指令出错 { LCD_Char_1_PrintString("e0"); for(i = 0; i < RxSize; ++i)//错误指令 清指令队列 { RxBuffer[RxSize] = '\0'; } RxSize = 0; } else if(RxSize > 10) { LCD_Char_1_PrintString("c0"); for(i = 0; i < RxSize; ++i)//错误指令 清指令队列 { RxBuffer[i] = '\0'; } RxSize = 0; } } if(Rx_1_Size > 2)//来自结点1的数据,应该转发给电脑 { uint8 i = 0; if(Rx_1_Buffer[Rx_1_Size-1] == 'e' && Rx_1_Buffer[0] == 's') { LCD_Char_1_PrintString(Rx_1_Buffer); if(Rx_1_Buffer[1] == 't') //转发温度,加上节点号 { char tem[9]; tem[0] = 's'; tem[1] = 't'; tem[2] = '1';//节点号 tem[3] = Rx_1_Buffer[2]; tem[4] = Rx_1_Buffer[3]; tem[5] = Rx_1_Buffer[4]; tem[6] = 'e'; tem[7] = '\0'; UART_PutString(tem); } else if(Rx_1_Buffer[1] == 'h') //转发温度过高 { LCD_Char_1_PutChar('l'); UART_PutString("sh1he"); } else if(Rx_1_Buffer[1] == 'l') //转发温度过低 { UART_PutString("sh1le"); } for(i = 0; i < Rx_1_Size; ++i)//处理完 清指令队列 { Rx_1_Buffer[i] = '\0'; } Rx_1_Size = 0; } else if(Rx_1_Buffer[Rx_1_Size-1] == 'e' && Rx_1_Buffer[0] != 's')//指令出错 { LCD_Char_1_PrintString("e"); for(i = 0; i < Rx_1_Size; ++i)//错误指令 清指令队列 { Rx_1_Buffer[i] = '\0'; } Rx_1_Size = 0; } else if(Rx_1_Size > 10) { LCD_Char_1_PrintString("c"); for(i = 0; i < Rx_1_Size; ++i)//错误指令 清指令队列 { Rx_1_Buffer[i] = '\0'; } Rx_1_Size = 0; } } if(Rx_2_Size > 4)//来自结点2的数据,应该转发给电脑 { uint8 i = 0; if(Rx_2_Buffer[Rx_2_Size-1] == 'e' && Rx_2_Buffer[0] == 's') { if(Rx_2_Buffer[1] == 't') //转发温度,加上节点号 { char tem[9]; tem[0] = 's'; tem[1] = 't'; tem[2] = '2';//节点号 tem[3] = Rx_2_Buffer[2]; tem[4] = Rx_2_Buffer[3]; tem[5] = Rx_2_Buffer[4]; tem[6] = 'e'; tem[7] = '\0'; UART_PutString(tem); } else if(Rx_2_Buffer[1] == 'h') //转发温度过高 { UART_PutString("sh2he"); } else if(Rx_2_Buffer[1] == 'l') //转发温度过低 { UART_PutString("sh2le"); } for(i = 0; i < Rx_2_Size; ++i)//处理完 清指令队列 { Rx_2_Buffer[i] = '\0'; } Rx_2_Size = 0; } else if(Rx_2_Buffer[Rx_2_Size-1] == 'e' && Rx_2_Buffer[0] != 's')//指令出错 { LCD_Char_1_PrintString("e"); for(i = 0; i < Rx_2_Size; ++i)//错误指令 清指令队列 { Rx_2_Buffer[i] = '\0'; } Rx_2_Size = 0; } else if(Rx_2_Size > 10) { LCD_Char_1_PrintString("c"); for(i = 0; i < Rx_2_Size; ++i)//错误指令 清指令队列 { Rx_2_Buffer[i] = '\0'; } Rx_2_Size = 0; } } } }
void serial_print(unsigned char *str) { UART_PutString(str); UART_CPutString("\r\n"); }
void FS_X_ErrorOut(const char *s) { FS_USE_PARA(s); UART_PutString((uint8*)"FS error: "); UART_PutString((uint8*)s); UART_PutString((uint8*)"\n"); }
int main(){ CyGlobalIntEnable; SPI_Start(); UART_Start(); isrIRQ_Start(); isrBTN_Start(); ADC_Start(); CyDelay(100); UART_PutString("Test TX and Rx Payload\r\n"); NRF_INIT_t tx; tx.channel = CHANNEL; tx.isTX = true; tx.RF_SETUP_DR = NRF_RF_SETUP_RF_DR_1000; tx.RF_SETUP_PWR = 0; tx.SETUP_RETR_ARC = NRF_SETUP_RETR_ARC_15; tx.SETUP_RETR_ARD = NRF_SETUP_RETR_ARD_1500; // Test Rx Payload NRF_WriteSingleRegister(NRF_DYNPD, 0x01u); NRF_WriteSingleRegister(NRF_FEATURE, 0x06u); NRF_SetRxPayloadSize(NRF_RX_PW_P0, PAYLOAD_SIZE); // NRF_SetRxAddress(ADDR, sizeof(ADDR)); NRF_SetTxAddress(ADDR, sizeof(ADDR)); NRF_Init(&tx); NRF_TxTransmit(data, sizeof(data)); CyDelay(4000); NRF_GetRetransmissionsCount(&test); UART_PutHexByte(test); UART_PutCRLF(); for(;;){ /* if(pressCount){ if(3 == pressCount) pressCount = 0; ADCoutput = ADC_Read32(); data[1] = (ADCoutput & 0xFF00) >> 8; data[2] = ADCoutput & 0xFF; data[6] = pressCount; NRF_TxTransmit(data, sizeof(data)); } */ count++; if(12 == count){ if(250 == pressCount){ pressCount = 0; } if(250 == test){ test = 0; } count = 0; test++; data[9] = test; data[0] = pressCount; ADCoutput = ADC_Read32(); data[1] = (ADCoutput & 0xFF00) >> 8; data[2] = ADCoutput & 0xFF; NRF_TxTransmit(data, sizeof(data)); } CyDelay(20); NRF_GetLostPackets(&test); if(0x0F == test){ NRF_ResetStatusIRQ(NRF_STATUS_MAX_RT); } UART_PutHexByte(test); UART_PutCRLF(); if(isrFlag){ isrFlag = false; if(NRF_GetStatus() & 0x40u){ /* RX_DR: Data Received */ do{ NRF_RxPayload(RXdata, sizeof(RXdata)); NRF_ResetStatusIRQ(NRF_STATUS_RX_DR); NRF_ReadSingleRegister(NRF_FIFO_STATUS, &status); }while(!(status & 0x01)); printFlag = true; }else if(NRF_GetStatus() & 0x60u){ /* TX_DS: Data Sent */ LED_Write(~LED_Read()); NRF_ResetStatusIRQ(NRF_STATUS_TX_DS); }else if(NRF_GetStatus() & 0x10u){ /* MAX_RT: Retry Timeout */ MAX_Write(~MAX_Read()); NRF_ResetStatusIRQ(NRF_STATUS_MAX_RT); } } if(printFlag){ UART_PutHexByte(RXdata[0]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[1]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[2]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[3]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[4]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[5]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[6]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[7]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[8]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[9]); UART_PutString("\r\n"); printFlag = false; } } }
void main(void) { M8C_EnableGInt ; // Uncomment this line to enable Global Interrupts // Start the UART(with no parity), and Counter16 UART_Start(UART_PARITY_NONE); // clock for moving serial Counter16_Start(); // Start I2CHW I2CHW_Start(); I2CHW_EnableMstr(); I2CHW_EnableInt(); // This is the command usage string UART_CPutString("########################## I2C External SRAM ########################\r\n\ # W # XX T [Data]\r\n\ # W - Write command\r\n\ # # - Group Address (0 - 7)\r\n\ # XX - Memory Location in hex (00 - FF)\r\n\ # T - Data Type, either A for ASCII or H for Hexadecimal\r\n\ # Data - Either ASCII string or Hexadecimal separates by spaces\r\n\ #\t\t\tA - Mary had a little lamb\r\n\ #\t\t\tH - 01 FF A0 0F D8 C3\r\n\ #\r\n\ # R # XX T NN\r\n\ # R - Read command\r\n\ # # - Group Address (0 - 7)\r\n\ # XX - Memory Location in hex (00 - FF)\r\n\ # T - Data Type, either A for ASCII or H for Hexadecimal\r\n\ # NN - Number of bytes to read in hexadecimal\r\n\ #####################################################################\r\n"); while (1) { char *cmd; char *params; char slaveAddress = 0x50; // 010100000 R/W shifted to front GetLine(buf, 79); // Retrieves a line with a maximum length of 70 characters and put it in buf. memset(data, 0x00, 256); // Initialize all the set {data} to NULL bytes cmd = Lowercase(cstrtok(buf, " ")); // Get the first word from the entered string and lowercase it. if (strlen(cmd) == 1 && cmd[0] == 'w') // If the command is one letter and it is w, then write command { int groupAddress; // only 1 and 2 actually go to SRAM int memLoc; char dataType; int len; params = cstrtok(0x00, " "); // 0x00 indicates it will continue from last cstrtok command and get next word. This gets the next parameter // csscanf if used to parse the string into values such as hexadecimal or integers // It returns the number of parameters it parsed which should be one // If the length of the params is not right or it does not parse the right amount, it returns an error // %d gets an integer, this is the groupAddress if (strlen(params) != 1 || csscanf(params, "%d", &groupAddress) != 1) goto error; // %x gets a hexadecimal value, this can read capital or lowercase letters, this is the memory location params = cstrtok(0x00, " "); if (strlen(params) != 2 || csscanf(params, "%x", &memLoc) != 1) goto error; // %c gets a character, the data type character params = cstrtok(0x00, " "); if (strlen(params) != 1 || csscanf(params, "%c", &dataType) != 1) goto error; // This reads the rest of the string and stores it in params. // If the length is zero or if cstrtok returns 0, this means that there was no valid string/hex entered params = cstrtok(0x00, "\0"); if (strlen(params) == 0 || params == 0x00) goto error; // They did all the params but didn't write anything dataType = tolower(dataType); // Lowercase the data type if (groupAddress < 0 || groupAddress > 7) goto error; // groupAddress was not in range data[0] = memLoc; // First byte needs to be the memory location according to PCF8570 datasheet slaveAddress |= groupAddress; // ORs the group 2 address to the group 1 address to get slaveAddress if (dataType == 'a') // If the data type is ASCII { strcpy((data + 1), params); // Copy the string from params and put it right after the data[0] byte len = strlen((data + 1)) + 1; // len is the number of bytes to write, it is the length of the string and then +1 because of the memLoc byte // Cant just do strlen(data) because data[0] could be 0x00 and it would return 0 as the string length } else if (dataType == 'h') // If the data type is hex { // Take ASCII encoded hex data params and put it after data[0], returns number of bytes converted if ((len = HexConversion(params, (data + 1))) == -1) goto error; len++; // Add one to the length because of the memLoc byte at data[0] } else goto error; I2CHW_bWriteBytes(slaveAddress, data, len, I2CHW_CompleteXfer); // Write len bytes from data while (!(I2CHW_bReadI2CStatus() & I2CHW_WR_COMPLETE)); // Wait while it is writing I2CHW_ClrWrStatus(); // Clear the write bit csprintf(data, "%x bytes were written", len); // csprintf takes the string and substitutes %x for len, puts into data str UART_PutString(data); // Print the string to UART UART_PutCRLF(); } else if (strlen(cmd) == 1 && cmd[0] == 'r') // If the command is one letter and it is r, then read command { int groupAddress; int memLoc; char dataType; int numBytes; char hexStr[4]; int i; // csscanf if used to parse the string into values such as hexadecimal or integers // It returns the number of parameters it parsed which should be one // If the length of the params is not right or it does not parse the right amount, it returns an error // %d gets an integer, this is the groupAddress params = cstrtok(0x00, " "); if (strlen(params) != 1 || csscanf(params, "%d", &groupAddress) != 1) goto error; // %x gets a hexadecimal value, this can read capital or lowercase letters, this is the memory location params = cstrtok(0x00, " "); if (strlen(params) != 2 || csscanf(params, "%x", &memLoc) != 1) goto error; // %c gets a character, the data type character params = cstrtok(0x00, " "); if (strlen(params) != 1 || csscanf(params, "%c", &dataType) != 1) goto error; // %x gets a hexadecimal value, number of bytes to read params = cstrtok(0x00, " "); if (strlen(params) != 2 || csscanf(params, "%x", &numBytes) != 1) goto error; // If there is any data after the number of bytes, then the format is invalid and it should return an error if (cstrtok(0x00, " ") != 0x00) goto error; dataType = tolower(dataType); // Lowercase the data type if (groupAddress < 0 || groupAddress > 7) goto error; // groupAddress was not in range data[0] = memLoc; // First byte needs to be the memory location according to PCF8570 datasheet slaveAddress |= groupAddress; // ORs the group 2 address to the group 1 address to get slaveAddress I2CHW_bWriteBytes(slaveAddress, data, 1, I2CHW_NoStop); // Write one byte to the RAM, the slaveAddress so it knows who were talking to while (!(I2CHW_bReadI2CStatus() & I2CHW_WR_COMPLETE)); // Wait while it is writing I2CHW_ClrWrStatus(); // Clear the write bit I2CHW_fReadBytes(slaveAddress, data, numBytes, I2CHW_CompleteXfer); // Read numBytes from the RAM, put it in data while(!(I2CHW_bReadI2CStatus() & I2CHW_RD_COMPLETE)); // Wait while it is reading I2CHW_ClrRdStatus(); // Clear the read bit if (dataType == 'a') // If the data type is ASCII { for (i = 0; i < numBytes; ++i) // Loop through each byte UART_PutChar(data[i]); // Put the character in PuTTy UART_PutCRLF(); } else if (dataType == 'h') // If the data type is Hex { for (i = 0; i < numBytes; ++i) // Loop through each byte { csprintf(hexStr, "%X ", data[i]); // csprintf prints into hexStr a hexadecimal with a space UART_PutString(hexStr); // Print hexStr } UART_PutCRLF(); } else goto error; } else goto error; continue; // This is so that the error is skipped when everything goes right error: // This outputs an invalid format message and continues on to read another line UART_CPutString("Invalid format entered. Valid formats are:\r\n\tW [GroupAddress] [MemoryLocation] [h|a] Hex/ASCII\r\n\tR [GroupAddress] [MemoryLocation] [h|a] [NumBytes]\r\n"); } }
/******************************************************************************* * Function Name: main ******************************************************************************** * * Summary: * * Parameters: * None. * * Return: * None. * *******************************************************************************/ int main() { int16 res = 0; int32 temperature; char uartLine[250]; int16 ADCCountsCorrected; /* Initialize the UART */ UART_Start(); UART_PutCRLF(); UART_PutCRLF(); UART_PutString("Starting temperature measurement..."); UART_PutCRLF(); PWM_Start(); PWM_TriggerCommand(PWM_MASK, PWM_CMD_START); /* Init and start sequencing SAR ADC */ ADC_SAR_SEQ_Start(); ADC_SAR_SEQ_StartConvert(); /* Enable interrupt and set interrupt handler to local routine */ ADC_SAR_SEQ_IRQ_StartEx(ADC_SAR_SEQ_ISR_LOC); /* Init interrupt from timer to measure the temperature rarely */ ISR_TIMER_StartEx(ISR_TIMER_LOC); CyGlobalIntEnable; for(;;) { /* When conversion of sequencing channels has completed */ if((dataReady & ADC_SAR_SEQ_EOS_MASK) != 0u) { /* Get voltage, measured by ADC */ dataReady &= ~ADC_SAR_SEQ_EOS_MASK; res = ADC_SAR_SEQ_CountsTo_mVolts(CH0_N, result[CH0_N]); } /* When conversion of the injection channel has completed */ if((dataReady & ADC_SAR_SEQ_INJ_EOC_MASK) != 0u) { dataReady &= ~ADC_SAR_SEQ_INJ_EOC_MASK; /****************************************************************************** * Adjust data from ADC with respect to Vref value. * This adjustment is to be done if Vref is set to any other than * internal 1.024V. * For more detailed description see Functional Description section * of DieTemp P4 datasheet. *******************************************************************************/ ADCCountsCorrected = result[TEMP_CH]*((int16)((float)ADC_VREF_VALUE_V/1.024)); temperature = DieTemp_CountsTo_Celsius(ADCCountsCorrected); /* Print temperature value to UART */ sprintf( uartLine, "Temperature value: %dC", (int16) temperature ); UART_PutString(uartLine); UART_PutCRLF(); /* Print voltage value to UART */ sprintf( uartLine, "ADC measured voltage: %dmV", (uint16) res ); UART_PutString(uartLine); UART_PutCRLF(); } } }
void FS_X_Warn(const char *s) { FS_USE_PARA(s); UART_PutString((uint8*)"FS warning: "); UART_PutString((uint8*)s); UART_PutString((uint8*)"\n"); }
int main(){ CyGlobalIntEnable; isrSW_Start(); isr_Timer_Start(); UART_Start(); ADC_Start(); ADC_StartConvert(); CyDelay(50); UART_PutString("nRF Tx\r\n"); NRF_INIT_t tx; tx.channel = NRF_CHANNEL; tx.isTX = true; tx.RF_SETUP_DR = NRF_RF_SETUP_RF_DR_1000; tx.RF_SETUP_PWR = NRF_RF_SETUP_RF_PWR_18; tx.SETUP_RETR_ARC = NRF_SETUP_RETR_ARC_15; tx.SETUP_RETR_ARD = NRF_SETUP_RETR_ARD_1500; /* Start the component before anything else */ nRF_Tx_Start(&tx); /* Test Dynamic Payload */ nRF_Tx_EnableDynamicPayload(NRF_DYNPD_DPL_P0); nRF_Tx_SetRxPayloadSize(NRF_RX_PW_P0, PAYLOAD_SIZE); nRF_Tx_SetRxAddress(ADDR, sizeof(ADDR)); nRF_Tx_SetTxAddress(ADDR, sizeof(ADDR)); Timer_Start(); for(;;){ if(true == isrTimerFlag){ // Stop the Timer just for fun Timer_Stop(); test++; data[0] = pressCount; data[9] = test; ADCoutput = ADC_Read32(); UART_PutString("Resultado de la conversion del ADC: "); UART_PutHexInt((uint16_t)ADCoutput); UART_PutCRLF(); data[1] = (ADCoutput & 0xFF00) >> 8; data[2] = ADCoutput & 0xFF; nRF_Tx_TxTransmit(data, sizeof(data)); isrTimerFlag = false; // Start the Timer again Timer_Start(); } if(isrFlag){ if(nRF_Tx_GetStatus() & NRF_STATUS_RX_DR_MASK){ UART_PutString("Status: "); UART_PutHexByte(nRF_Tx_GetStatus()); UART_PutCRLF(); UART_PutString("RX\r\n"); do{ nRF_Tx_RxPayload(RXdata, sizeof(RXdata)); nRF_Tx_ResetStatusIRQ(NRF_STATUS_RX_DR); nRF_Tx_ReadSingleRegister(NRF_FIFO_STATUS, &status); }while(!(status & NRF_STATUS_TX_FIFO_FULL)); printFlag = true; }else if(nRF_Tx_GetStatus() & NRF_STATUS_TX_DS_MASK){ UART_PutString("Status: "); UART_PutHexByte(nRF_Tx_GetStatus()); UART_PutCRLF(); UART_PutString("TX\r\n"); LED_Write(~LED_Read()); nRF_Tx_ResetStatusIRQ(NRF_STATUS_TX_DS); }else if(nRF_Tx_GetStatus() & NRF_STATUS_MAX_RT_MASK){ UART_PutString("Status: "); UART_PutHexByte(nRF_Tx_GetStatus()); UART_PutCRLF(); UART_PutString("Max RT\r\n"); MAX_Write(~MAX_Read()); nRF_Tx_ResetStatusIRQ(NRF_STATUS_MAX_RT); } isrFlag = false; } if(printFlag){ UART_PutHexByte(RXdata[0]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[1]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[2]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[3]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[4]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[5]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[6]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[7]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[8]); UART_PutString("\r\n"); UART_PutHexByte(RXdata[9]); UART_PutString("\r\n"); printFlag = false; } }