void main (void) { initBoard(); memcpypgm2ram((void*)GetLcdBuffer(), "I am Alive",10); LCDUpdate(); while (1) { StateMachine(); sprintf(GetLcdBuffer(),"%d %d %d %d %d %d %d ",L_MOTOR_FB1,L_WHITE_LINE_SENSE,R_BACK_BUMPER,FRONT_BUMPER,L_BACK_BUMPER,R_WHITE_LINE_SENSE,R_MOTOR_FB1); LCDUpdate(); #if 0 if( !BUTTON0_IO ) { LED0_IO =1; CCPR3L += 1; CCPR4L += 1; sprintf(GetLcdBuffer(),"%d %d %d %d %d %d %d ",L_MOTOR_FB1,L_WHITE_LINE_SENSE,BUMPER1,BUMPER2,BUMPER3,R_WHITE_LINE_SENSE,R_MOTOR_FB1); sprintf(GetLcdBuffer()+16,"val: %d",CCPR3L); LCDUpdate(); MOTOR_CARD_RELAY = 1; //L_MOTOR_BREAK = 1; R_MOTOR_BREAK = 1; DelayMs(100); } else { LED0_IO = 0; sprintf(GetLcdBuffer(),"%d %d %d %d %d %d %d ",L_MOTOR_FB1,L_WHITE_LINE_SENSE,BUMPER1,BUMPER2,BUMPER3,R_WHITE_LINE_SENSE,R_MOTOR_FB1); LCDUpdate(); } if( !BUTTON1_IO ) { MOTOR_CARD_RELAY = 0; L_MOTOR_BREAK = 0; R_MOTOR_BREAK = 0; CCPR3L = 0; CCPR4L = 0; } #endif } }
void DisplayIPValue(IP_ADDR IPVal) #endif { BYTE IPDigit[4]; //enough for a number <256: 3 digits + \0 BYTE i; BYTE j; BYTE LCDPos=16; //write on second line of LCD #if defined(__SDCC__) unsigned int IP_field, radix=10; //type expected by sdcc's uitoa() #endif for(i = 0; i < sizeof(IP_ADDR); i++) //sizeof(IP_ADDR) is 4 { #if defined(__SDCC__) IP_field =(WORD)(IPdw>>(i*8))&0xff; //ML uitoa(IP_field, IPDigit, radix); //ML #else uitoa((WORD)IPVal.v[i], IPDigit); #endif for(j = 0; j < strlen((char*)IPDigit); j++) { LCDText[LCDPos++] = IPDigit[j]; } if(i == sizeof(IP_ADDR)-1) break; LCDText[LCDPos++] = '.'; } if(LCDPos < 32u) LCDText[LCDPos] = 0; LCDUpdate(); }
void LCDDisplayIPValue(IP_ADDR IPVal) { BYTE IPDigit[4]; BYTE i; BYTE j; BYTE LCDPos=16; for(i = 0; i < sizeof(IP_ADDR); i++) { uitoa((WORD)IPVal.v[i], IPDigit); for(j = 0; j < strlen((char*)IPDigit); j++) { LCDText[LCDPos++] = IPDigit[j]; } if(i == sizeof(IP_ADDR)-1) break; LCDText[LCDPos++] = '.'; } if(LCDPos < 32u) LCDText[LCDPos] = 0; LCDUpdate(); }
void LCDDisplayIPValue(IP_ADDR IPVal) { #ifdef USE_LCD uint8_t IPDigit[4]; uint8_t i; uint8_t j; uint8_t LCDPos=16; for (i = 0; i < sizeof(IP_ADDR); i++) { uitoa((uint16_t)IPVal.v[i], IPDigit); for (j = 0; j < strlen((char*)IPDigit); j++) { LCDText[LCDPos++] = IPDigit[j]; } if (i == sizeof(IP_ADDR) - 1) break; LCDText[LCDPos++] = '.'; } if (LCDPos < 32u) LCDText[LCDPos] = 0; LCDUpdate(); #endif }
/********************************************************************* * Function: void LCDDisplay(char *text, BYTE value, BOOL delay) * * PreCondition: LCD has been initialized * * Input: text - text message to be displayed on LCD * value - the text message allows up to one byte * of variable in the message * delay - whether need to display the message for * 2 second without change * * Output: None * * Side Effects: None * * Overview: This function display the text message on the LCD, * including up to one BYTE variable, if applicable. * * Note: This routine is only effective if Explorer16 or * PIC18 Explorer demo boards are used ********************************************************************/ void LCDDisplay(char *text, BYTE value, BOOL delay) { #if defined(EXPLORER16) || defined(PIC18_EXPLORER) || \ (defined(EIGHT_BIT_WIRELESS_BOARD) && defined(SENSOR_PORT_LCD)) LCDErase(); #if defined(PIC18_EXPLORER) || defined(EIGHT_BIT_WIRELESS_BOARD) sprintf((char *)LCDText, (far rom char *) text, value); #elif defined(EXPLORER16) sprintf((char *)LCDText, (const char *)text, value); #endif LCDUpdate(); // display the message for 2 seconds if(delay) { BYTE i; for(i = 0; i < 8; i++) { DelayMs(250); } } #endif }
void WF_AssertionFailed(UINT8 moduleNumber, UINT16 lineNumber) { #if defined(STACK_USE_UART) char buf[8]; putrsUART("WF ASSERTION: Module Number = "); sprintf(buf, "%d ", moduleNumber); putsUART(buf); putrsUART("Line Number = "); sprintf(buf, "%d", lineNumber); putsUART(buf); #endif #if defined(USE_LCD) { char buf[] = {WIFI_ASSERT_STRING}; memset(LCDText, ' ', sizeof(LCDText)); memcpy((void *)LCDText, (void *)buf, strlen(buf)); uitoa(moduleNumber, (BYTE*)buf); memcpy((void *)&LCDText[18], (void *)buf, strlen(buf)); LCDText[23] = 'L'; LCDText[24] = ':'; uitoa(lineNumber, &LCDText[25]); LCDUpdate(); } #endif while(1); }
void LCDInit(void) { // Initialize SPI Interface Initialize_SPI(); // set pin directions LCD_CS_MAKE_OUT(); LCD_CS_HIGH(); LCD_DC_MAKE_OUT(); LCD_RES_MAKE_OUT(); // Toggle reset pin LCD_RES_LOW(); Delay(1000); LCD_RES_HIGH(); Delay(1000); // Send sequence of command LCDSend(0x21, SEND_CMD); // LCD Extended Commands. LCDSend(0xC8, SEND_CMD); // Set LCD Vop (Contrast). 0xC8 LCDSend(0x04 | !!(LCD_START_LINE_ADDR & (1u << 6)), SEND_CMD); // Set Temp S6 for start line LCDSend(0x40 | (LCD_START_LINE_ADDR & ((1u << 6) - 1)), SEND_CMD); // Set Temp S[5:0] for start line //LCDSend( 0x13, SEND_CMD ); // LCD bias mode 1:48. LCDSend(0x12, SEND_CMD); // LCD bias mode 1:68. LCDSend(0x20, SEND_CMD); // LCD Standard Commands, Horizontal addressing mode. //LCDSend( 0x22, SEND_CMD ); // LCD Standard Commands, Vertical addressing mode. LCDSend(0x08, SEND_CMD); // LCD blank LCDSend(0x0C, SEND_CMD); // LCD in normal mode. // Clear and Update LCDClear(); LCDUpdate(); }
/************************************************* Function DisplayString: Writes an IP address to string to the LCD display starting at pos *************************************************/ void DisplayString(BYTE pos, char* text) { BYTE l= strlen(text)+1; BYTE max= 32-pos; strlcpy((char*)&LCDText[pos], text,(l<max)?l:max ); LCDUpdate(); }
/********************************************************************* * Function: void RebootTask(void) * * PreCondition: Stack is initialized() * * Input: None * * Output: None * * Side Effects: None * * Overview: Checks for incomming traffic on port 69. * Resets the PIC if a 'R' is received. * * Note: This module is primarily for use with the * Ethernet bootloader. By resetting, the Ethernet * bootloader can take control for a second and let * a firmware upgrade take place. ********************************************************************/ void RebootTask(void) { static UDP_SOCKET MySocket = INVALID_UDP_SOCKET; struct { BYTE vMACAddress[6]; DWORD dwIPAddress; WORD wChecksum; } BootloaderAddress; if(MySocket == INVALID_UDP_SOCKET) MySocket = UDPOpenEx(0,UDP_OPEN_SERVER,REBOOT_PORT,INVALID_UDP_PORT); // MySocket = UDPOpen(REBOOT_PORT, NULL, INVALID_UDP_PORT); if(MySocket == INVALID_UDP_SOCKET) return; // Do nothing if no data is waiting if(!UDPIsGetReady(MySocket)) return; #if defined(REBOOT_SAME_SUBNET_ONLY) // Respond only to name requests sent to us from nodes on the same subnet if((remoteNode.IPAddr.Val & AppConfig.MyMask.Val) != (AppConfig.MyIPAddr.Val & AppConfig.MyMask.Val)) { UDPDiscard(); return; } #endif // Get our MAC address, IP address, and compute a checksum of them memcpy((void*)&BootloaderAddress.vMACAddress[0], (void*)&AppConfig.MyMACAddr.v[0], sizeof(AppConfig.MyMACAddr)); BootloaderAddress.dwIPAddress = AppConfig.MyIPAddr.Val; BootloaderAddress.wChecksum = CalcIPChecksum((BYTE*)&BootloaderAddress, sizeof(BootloaderAddress) - sizeof(BootloaderAddress.wChecksum)); // To enter the bootloader, we need to clear the /POR bit in RCON. // Otherwise, the bootloader will immediately hand off execution // to us. #if defined(USE_LCD) strcpypgm2ram((char*)LCDText, "Bootloader Reset"); LCDUpdate(); #endif #if !defined(__STM32F10X__) RCONbits.POR = 0; #if defined(__18CXX) { WORD_VAL wvPROD; wvPROD.Val = ((WORD)&BootloaderAddress); PRODH = wvPROD.v[1]; PRODL = wvPROD.v[0]; } #endif #endif Reset(); }
void DisplaySSID(void) { IP_ADDR IPVal; BYTE IPDigit[4]; BYTE i; LCDErase(); LCDUpdate(); //Display SSID //REMOVE ME /* if (AppConfig.networkType == WF_ADHOC) sprintf((char *)MySSID, "MCHP_ADHOC_%02x%02x", AppConfig.MyMACAddr.v[4], AppConfig.MyMACAddr.v[5]); else if (AppConfig.networkType == WF_SOFT_AP) sprintf((char *) MySSID, "MCHP_SFTAP_%02x%02x", AppConfig.MyMACAddr.v[4], AppConfig.MyMACAddr.v[5]); else sprintf((char *) MySSID, "MCHP_%02x%02x", AppConfig.MyMACAddr.v[4], AppConfig.MyMACAddr.v[5]); */ sprintf((char *) LCDText, (char*) AppConfig.MySSID); //Display IP Address IPVal = AppConfig.MyIPAddr; BYTE j; BYTE LCDPos = 16; for (i = 0; i < sizeof (IP_ADDR); i++) { uitoa((WORD) IPVal.v[i], IPDigit); for (j = 0; j < strlen((char*) IPDigit); j++) { LCDText[LCDPos++] = IPDigit[j]; } if (i == sizeof (IP_ADDR) - 1) break; LCDText[LCDPos++] = '.'; } if (LCDPos < 32u) LCDText[LCDPos] = 0; LCDUpdate(); }
void LCDWriteLine(BYTE line, char *buffer) { BYTE i = 0; BYTE j = 0; do { LCDText[line-1][j++] = buffer[i++]; } while ((LCDText[line-1][j-1] != 0) && (j < 15)); LCDUpdate(); }
/********************************************************************* * Function: void LCDTRXCount(BYTE txCount, BYTE rxCount) * * PreCondition: LCD has been initialized * * Input: txCount - the total number of transmitted messages * rxCount - the total number of received messages * * Output: None * * Side Effects: None * * Overview: This function display the total numbers of TX and * RX messages on the LCD, if applicable. * * Note: This routine is only effective if Explorer16 or * PIC18 Explorer demo boards are used ********************************************************************/ void LCDTRXCount(BYTE txCount, BYTE rxCount) { #if defined(EXPLORER16) || defined(PIC18_EXPLORER) || (defined(EIGHT_BIT_WIRELESS_BOARD) && defined(SENSOR_PORT_LCD)) LCDErase(); #if defined(PIC18_EXPLORER) || defined(EIGHT_BIT_WIRELESS_BOARD) sprintf((char *)LCDText, (far rom char*)"TX Messages: %3d", txCount); sprintf((char *)&(LCDText[16]), (far rom char*)"RX Messages: %3d", rxCount); #else sprintf((char *)LCDText, (const char*)"TX Messages: %d", txCount); sprintf((char *)&(LCDText[16]), (const char*)"RX Messages: %d", rxCount); #endif LCDUpdate(); #endif }
tZGVoidReturn ZGErrorHandler(ROM char *p_errorString) { #if defined STACK_USE_UART ZG_PUTRSUART("ERROR: "); ZG_PUTRSUART(p_errorString); ZG_PUTRSUART("\r\n"); #endif #if defined(USE_LCD) strcpypgm2ram((char*)LCDText, p_errorString); LCDUpdate(); #endif while (1); }
// Writes an IP address to the LCD display and the UART as available void DisplayIPValue(IP_ADDR IPVal) { // printf("%u.%u.%u.%u", IPVal.v[0], IPVal.v[1], IPVal.v[2], IPVal.v[3]); #if defined (__dsPIC33E__) || defined (__PIC24E__) static BYTE IPDigit[4]; /* Needs to be declared as static to avoid the array getting optimized by C30 v3.30 compiler for dsPIC33E/PIC24E. Otherwise the LCD displays corrupted IP address on Explorer 16. To be fixed in the future compiler release*/ #else BYTE IPDigit[4]; #endif BYTE i; #ifdef USE_LCD BYTE j; BYTE LCDPos=16; #endif for(i = 0; i < sizeof(IP_ADDR); i++) { uitoa((WORD)IPVal.v[i], IPDigit); #if defined(STACK_USE_UART) putsUART((char *) IPDigit); #endif #ifdef USE_LCD for(j = 0; j < strlen((char*)IPDigit); j++) { LCDText[LCDPos++] = IPDigit[j]; } if(i == sizeof(IP_ADDR)-1) break; LCDText[LCDPos++] = '.'; #else if(i == sizeof(IP_ADDR)-1) break; #endif #if defined(STACK_USE_UART) while(BusyUART()); WriteUART('.'); #endif } #ifdef USE_LCD if(LCDPos < 32u) LCDText[LCDPos] = 0; LCDUpdate(); #endif }
void DisplayWORD(BYTE pos, WORD w) //WORD is a 16 bits unsigned { BYTE WDigit[6]; //enough for a number < 65636: 5 digits + \0 BYTE j; BYTE LCDPos=0; //write on first line of LCD unsigned radix=10; //type expected by sdcc's ultoa() LCDPos=pos; ultoa(w, WDigit, radix); for(j = 0; j < strlen((char*)WDigit); j++) { LCDText[LCDPos++] = WDigit[j]; } if(LCDPos < 32u) LCDText[LCDPos] = 0; LCDUpdate(); }
// Writes an IP address to the LCD display and the UART as available void DisplayIPValue(IP_ADDR IPVal) { // printf("%u.%u.%u.%u", IPVal.v[0], IPVal.v[1], IPVal.v[2], IPVal.v[3]); BYTE IPDigit[4]; BYTE i; #ifdef USE_LCD BYTE j; BYTE LCDPos=16; #endif for(i = 0; i < sizeof(IP_ADDR); i++) { uitoa((WORD)IPVal.v[i], IPDigit); #if defined(STACK_USE_UART) putsUART((char *) IPDigit); #endif #ifdef USE_LCD for(j = 0; j < strlen((char*)IPDigit); j++) { LCDText[LCDPos++] = IPDigit[j]; } if(i == sizeof(IP_ADDR)-1) break; LCDText[LCDPos++] = '.'; #else if(i == sizeof(IP_ADDR)-1) break; #endif #if defined(STACK_USE_UART) while(BusyUART()); WriteUART('.'); #endif } #ifdef USE_LCD if(LCDPos < 32u) LCDText[LCDPos] = 0; LCDUpdate(); #endif }
void Coordinates(void){ unsigned char numberl,numberh; int number; number = numberh = numberl = 0; ReadReg(&numberl, OUTX_L);//diavazei ta 8 ligotero shmantika pshfia ths x syntetagmenhs ReadReg(&numberh, OUTX_H);//diavazei ta 8 pio shmantika pshfia ths x syntetagmenhs number = (numberh<<8)|numberl;//olisthish 8 pshfiwn pros ta aristera gia ton arithmo me ta 8 pio shmantika pshfia kai me ena or pairnoume ton 16diko pou theloume sprintf(&bufferx[i], "X acceleration:0x%04x\0", number);//apothikeuetai sto stoixeio i tou pinaka h x syntetagmenh Data[a]=number; a++; number = numberh = numberl = 0; ReadReg(&numberl, OUTY_L); ReadReg(&numberh, OUTY_H); number = (numberh<<8)|numberl; sprintf(&buffery[i], "Y acceleration:0x%04x\0", number); Data[a]=number; a++; number = numberh = numberl = 0; ReadReg(&numberl, OUTZ_L); ReadReg(&numberh, OUTZ_H); number = (numberh<<8)|numberl; sprintf(&bufferz[i], "Z acceleration:0x%04x\0", number); Data[a]=number; a++; LCDClear();//katharizei thn LCD LCDStr(0,(unsigned char*)bufferx[i],0);//stelnei kapoio string sthn LCD(edw sth thesh (0,0) LCDStr(1,(unsigned char*)buffery[i],0);//stelnei kapoio string sthn LCD(edw sth thesh (1,0) LCDStr(2,(unsigned char*)bufferz[i],0);//stelnei kapoio string sthn LCD(edw sth thesh (2,0) LCDUpdate();//kanei update sth mnhmh ths lcd i++; if (a==Data_Size-1){ Check_SD();//synarthsh pou kanei elegxo gia thn SD a=0; } }
void WriteLCDMenu(void) {// Update the LCD screen // Blank the LCD display strcpypgm2ram((char*)LCDText, (ROM char*)" "); // Show the name strcpy((char*)LCDText, (char*)Products[curItem].name); LCDText[strlen((char*)Products[curItem].name)] = ' '; // Show the price, or sold out status if(Products[curItem].stock == 0u) { memcpypgm2ram(&LCDText[12], (ROM void*)"SOLD", 4); } else { LCDText[11] = '$'; WritePriceLCD(Products[curItem].price, 12); } // Show the current credit LCDText[16] = '$'; WritePriceLCD(curCredit, 17); // Show the vend button if available if(Products[curItem].stock != 0u && Products[curItem].price <= curCredit) memcpypgm2ram(&LCDText[22], (ROM void*)"Vend", 4); else memcpypgm2ram(&LCDText[23], (ROM void*)"--", 2); // Show the rest of the buttons if(curItem != 0u) memcpypgm2ram(&LCDText[27], (ROM void*)"<<", 2); if(curItem != MAX_PRODUCTS-1) memcpypgm2ram(&LCDText[30], (ROM void*)">>", 2); // Update to the screen LCDUpdate(); }
void LCDStr(unsigned char row, const unsigned char *dataPtr, unsigned char inv) { // variable for X coordinate unsigned char x = 0; // loop to the and of string while (*dataPtr) { if (inv) { LCDChrXYInverse(x, row, *dataPtr); } else { LCDChrXY(x, row, *dataPtr); } x++; dataPtr++; } LCDUpdate(); }
void ServiceIt (BYTE aCode, char* msg, int len_msg) { int l; l=(len_msg > LCD_SIZE) ? LCD_SIZE : len_msg; memset((void *)LCDText, ' ', LCD_SIZE); memcpy((void *)LCDText, (void *)msg, l); LCDText[l] = '\0'; LCD_decode(LCDText); LCDUpdate(); if(aCode & ACCESS_INDICATOR) event_send(MODULE_SRVMACHINE, EVT_SM_ENABLE_INDICATOR); if(!(aCode & ACCESS_CONTROL)) { event_send(MODULE_SRVMACHINE, EVT_SM_DISABLE_CONTROL); state = WAIT_UID; readers_reset_state(); LCD_set_tout(TICK_SECOND * 5); } else { event_send(MODULE_SRVMACHINE, EVT_SM_ENABLE_CONTROL); state = WAIT_SM; } }
void LCDWriteLine(WORD number, char *line) { BYTE i; BYTE j; j = 0; i = 0; if(number == 2) { while ((LCDText[j] != 0) && (j < 16)) { j++; } } do { LCDText[j++] = line[i++]; } while ((LCDText[j-1] != 0) && (j < 31)); LCDUpdate(); }
void HTTPExecCmd(BYTE** argv, BYTE argc) { BYTE command; BYTE var; #if defined(ENABLE_REMOTE_CONFIG) DWORD_VAL dwVal; BYTE CurrentArg; WORD_VAL TmpWord; #endif /* * Design your pages such that they contain command code * as a one character numerical value. * Being a one character numerical value greatly simplifies * the job. */ command = argv[0][0] - '0'; /* * Find out the cgi file name and interpret parameters * accordingly */ switch(command) { case CGI_CMD_DIGOUT: // ACTION=0 /* * Identify the parameters. * Compare it in upper case format. */ var = argv[1][0] - '0'; switch(var) { case CMD_LED1: // NAME=0 // Toggle LED. LED1_IO ^= 1; break; case CMD_LED2: // NAME=1 // Toggle LED. LED2_IO ^= 1; break; } memcpypgm2ram((void*)argv[0], (ROM void*)COMMANDS_OK_PAGE, COMMANDS_OK_PAGE_LEN); break; #if defined(USE_LCD) case CGI_CMD_LCDOUT: // ACTION=1 if(argc > 2u) // Text provided in argv[2] { // Convert %20 to spaces, and other URL transformations UnencodeURL(argv[2]); // Write 32 received characters or less to LCDText if(strlen((char*)argv[2]) < 32u) { memset(LCDText, ' ', 32); strcpy((char*)LCDText, (char*)argv[2]); } else { memcpy(LCDText, (void*)argv[2], 32); } // Write LCDText to the LCD LCDUpdate(); } else // No text provided { LCDErase(); } memcpypgm2ram((void*)argv[0], (ROM void*)COMMANDS_OK_PAGE, COMMANDS_OK_PAGE_LEN); break; #endif #if defined(ENABLE_REMOTE_CONFIG) // Possibly useful code for remotely reconfiguring the board through // HTTP case CGI_CMD_RECONFIG: // ACTION=2 // Loop through all variables that we've been given CurrentArg = 1; while(argc > CurrentArg) { // Get the variable identifier (HTML "name"), and // increment to the variable's value TmpWord.v[1] = argv[CurrentArg][0]; TmpWord.v[0] = argv[CurrentArg++][1]; var = hexatob(TmpWord); // Make sure the variable's value exists if(CurrentArg >= argc) break; // Take action with this variable/value switch(var) { case VAR_IP_ADDRESS: case VAR_SUBNET_MASK: case VAR_GATEWAY_ADDRESS: { // Convert the returned value to the 4 octect // binary representation if(!StringToIPAddress(argv[CurrentArg], (IP_ADDR*)&dwVal)) break; // Reconfigure the App to use the new values if(var == VAR_IP_ADDRESS) { // Cause the IP address to be rebroadcast // through Announce.c or the RS232 port since // we now have a new IP address if(dwVal.Val != *(DWORD*)&AppConfig.MyIPAddr) DHCPBindCount++; // Set the new address memcpy((void*)&AppConfig.MyIPAddr, (void*)&dwVal, sizeof(AppConfig.MyIPAddr)); } else if(var == VAR_SUBNET_MASK) memcpy((void*)&AppConfig.MyMask, (void*)&dwVal, sizeof(AppConfig.MyMask)); else if(var == VAR_GATEWAY_ADDRESS) memcpy((void*)&AppConfig.MyGateway, (void*)&dwVal, sizeof(AppConfig.MyGateway)); } break; case VAR_DHCP: if(AppConfig.Flags.bIsDHCPEnabled) { if(!(argv[CurrentArg][0]-'0')) { AppConfig.Flags.bIsDHCPEnabled = FALSE; } } else { if(argv[CurrentArg][0]-'0') { AppConfig.MyIPAddr.Val = 0x00000000ul; AppConfig.Flags.bIsDHCPEnabled = TRUE; AppConfig.Flags.bInConfigMode = TRUE; DHCPInit(0); } } break; } // Advance to the next variable (if present) CurrentArg++; } // Save any changes to non-volatile memory SaveAppConfig(&AppConfig); // Return the same CONFIG.CGI file as a result. memcpypgm2ram((void*)argv[0], (ROM void*)CONFIG_UPDATE_PAGE, CONFIG_UPDATE_PAGE_LEN); break; #endif // #if defined(ENABLE_REMOTE_CONFIG) default: memcpypgm2ram((void*)argv[0], (ROM void*)COMMANDS_OK_PAGE, COMMANDS_OK_PAGE_LEN); break; } }
int main(void) #endif { BYTE i; static DWORD t = 0; static DWORD dwLastIP = 0; static UINT8 updateDisplay = 0; #if defined (EZ_CONFIG_STORE) static DWORD ButtonPushStart = 0; #endif #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) UINT8 channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN; // WF_PRESCAN tWFScanResult bssDesc; #endif // Initialize application specific hardware InitializeBoard(); // Initiates board setup process if button is depressed // on startup if (BUTTON1_IO == 0u) { while (BUTTON1_IO == 0); SelfTestMode(); } //#if defined(USE_LCD) /*******************************************************************/ // Initialize the LCD /*******************************************************************/ ConfigureLCD_SPI(); LCDInit(); /*******************************************************************/ // Display Start-up Splash Screen /*******************************************************************/ LCDBacklightON(); LEDS_ON(); LCDErase(); sprintf((char *) LCDText, (char*) " MiWi - WiFi "); sprintf((char *) &(LCDText[16]), (char*) " Gateway Demo"); LCDUpdate(); /*******************************************************************/ // Initialize the MiWi Protocol Stack. The only input parameter indicates // if previous network configuration should be restored. /*******************************************************************/ MiApp_ProtocolInit(FALSE); /*******************************************************************/ // Set Device Communication Channel /*******************************************************************/ if (MiApp_SetChannel(myChannel) == FALSE) { LCDDisplay((char *) "ERROR: Unable to Set Channel..", 0, TRUE); while (1); } /*******************************************************************/ // Set the connection mode. The possible connection modes are: // ENABLE_ALL_CONN: Enable all kinds of connection // ENABLE_PREV_CONN: Only allow connection already exists in // connection table // ENABL_ACTIVE_SCAN_RSP: Allow response to Active scan // DISABLE_ALL_CONN: Disable all connections. /*******************************************************************/ MiApp_ConnectionMode(ENABLE_ALL_CONN); /*******************************************************************/ // Function MiApp_EstablishConnection try to establish a new // connection with peer device. // The first parameter is the index to the active scan result, // which is acquired by discovery process (active scan). If // the value of the index is 0xFF, try to establish a // connection with any peer. // The second parameter is the mode to establish connection, // either direct or indirect. Direct mode means connection // within the radio range; indirect mode means connection // may or may not in the radio range. /*******************************************************************/ i = MiApp_EstablishConnection(0xFF, CONN_MODE_DIRECT); /*******************************************************************/ // Display current opertion on LCD of demo board, if applicable /*******************************************************************/ if (i != 0xFF) { ; // Connected Peer on Channel } else { /*******************************************************************/ // If no network can be found and join, we need to start a new // network by calling function MiApp_StartConnection // // The first parameter is the mode of start connection. There are // two valid connection modes: // - START_CONN_DIRECT start the connection on current // channel // - START_CONN_ENERGY_SCN perform an energy scan first, // before starting the connection on // the channel with least noise // - START_CONN_CS_SCN perform a carrier sense scan // first, before starting the // connection on the channel with // least carrier sense noise. Not // supported for current radios // // The second parameter is the scan duration, which has the same // definition in Energy Scan. 10 is roughly 1 second. 9 is a // half second and 11 is 2 seconds. Maximum scan duration is // 14, or roughly 16 seconds. // // The third parameter is the channel map. Bit 0 of the // double word parameter represents channel 0. For the 2.4GHz // frequency band, all possible channels are channel 11 to // channel 26. As the result, the bit map is 0x07FFF800. Stack // will filter out all invalid channels, so the application // only needs to pay attention to the channels that are not // preferred. /*******************************************************************/ MiApp_StartConnection(START_CONN_DIRECT, 10, 0); } // Turn OFF LCD after setting up MiWi Connection LCDBacklightOFF(); // Initialize stack-related hardware components that may be // required by the UART configuration routines TickInit(); #if defined(STACK_USE_MPFS2) MPFSInit(); #endif // Initialize Stack and application related NV variables into AppConfig. InitAppConfig(); dwLastIP = AppConfig.MyIPAddr.Val; // Initialize core stack layers (MAC, ARP, TCP, UDP) and // application modules (HTTP, SNMP, etc.) StackInit(); #if defined ( EZ_CONFIG_SCAN ) WFInitScan(); #endif #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) // WF_PRESCAN: Pre-scan before starting up as SoftAP mode WF_CASetScanType(MY_DEFAULT_SCAN_TYPE); WF_CASetChannelList(channelList, sizeof (channelList)); if (WFStartScan() == WF_SUCCESS) { SCAN_SET_DISPLAY(SCANCXT.scanState); SCANCXT.displayIdx = 0; //putsUART("main: Prescan WFStartScan() success ................. \r\n"); } // Needed to trigger g_scan_done WFRetrieveScanResult(0, &bssDesc); #else #if defined(WF_CS_TRIS) WF_Connect(); #endif // defined(WF_CS_TRIS) #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) // Initialize any application-specific modules or functions/ // For this demo application, this only includes the // UART 2 TCP Bridge #if defined(STACK_USE_UART2TCP_BRIDGE) UART2TCPBridgeInit(); #endif #if defined(STACK_USE_ZEROCONF_LINK_LOCAL) ZeroconfLLInitialize(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSInitialize(MY_DEFAULT_HOST_NAME); mDNSServiceRegister( (const char *) AppConfig.NetBIOSName, // base name of the service "_http._tcp.local", // type of the service 80, // TCP or UDP port, at which this service is available ((const BYTE *) "path=/index.htm"), // TXT info 1, // auto rename the service when if needed NULL, // no callback function NULL // no application context ); mDNSMulticastFilterRegister(); #endif #if defined(WF_CONSOLE) WFConsoleInit(); #endif // Now that all items are initialized, begin the co-operative // multitasking loop. This infinite loop will continuously // execute all stack-related tasks, as well as your own // application's functions. Custom functions should be added // at the end of this loop. // Note that this is a "co-operative mult-tasking" mechanism // where every task performs its tasks (whether all in one shot // or part of it) and returns so that other tasks can do their // job. // If a task needs very long time to do its job, it must be broken // down into smaller pieces so that other tasks can have CPU time. LEDS_OFF(); while (1) { /*******************************************************************/ // Check Button Events /*******************************************************************/ if (BUTTON1_IO == 0u) { while (BUTTON1_IO == 0); LCDErase(); sprintf((char *) LCDText, (char*) "Erase Room Info?"); sprintf((char *) &(LCDText[16]), (char*) "SW0:Yes SW2:No"); LCDUpdate(); while (1) { if (BUTTON1_IO == 0u) { while (BUTTON1_IO == 0); LCDDisplay((char *) "STATUS: Erasing...", 0, TRUE); EraseRoomInfo(); DisplaySSID(); break; } else if (BUTTON2_IO == 0u) { while (BUTTON2_IO == 0); DisplaySSID(); break; } } } // Blink LED0 twice per sec when unconfigured, once per sec after config if ((TickGet() - t >= TICK_SECOND / (4ul - (CFGCXT.isWifiDoneConfigure * 2ul)))) { t = TickGet(); LED0_INV(); } if(CFGCXT.isWifiNeedToConfigure) updateDisplay = 1; #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) if (g_scan_done) { if (g_prescan_waiting) { SCANCXT.displayIdx = 0; while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) { WFDisplayScanMgr(); } #if defined(WF_CS_TRIS) WF_Connect(); #endif DisplaySSID(); g_scan_done = 0; g_prescan_waiting = 0; } } #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP) // This task performs normal stack task including checking // for incoming packet, type of packet and calling // appropriate stack entity to process it. StackTask(); WiFiTask(); // This tasks invokes each of the core stack application tasks StackApplications(); #if defined(STACK_USE_ZEROCONF_LINK_LOCAL) ZeroconfLLProcess(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSProcess(); // Use this function to exercise service update function // HTTPUpdateRecord(); #endif // Process application specific tasks here. // For this demo app, this will include the Generic TCP // client and servers, and the SNMP, Ping, and SNMP Trap // demos. Following that, we will process any IO from // the inputs on the board itself. // Any custom modules or processing you need to do should // go here. #if defined(WF_CONSOLE) //WFConsoleProcess(); // #if !defined(STACK_USE_EZ_CONFIG) // IperfAppCall(); // #endif //WFConsoleProcessEpilogue(); wait_console_input: #endif #if defined(STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE) GenericTCPClient(); #endif #if defined(STACK_USE_GENERIC_TCP_SERVER_EXAMPLE) GenericTCPServer(); #endif #if defined(STACK_USE_SMTP_CLIENT) SMTPDemo(); #endif #if defined(STACK_USE_ICMP_CLIENT) PingDemo(); //PingConsole(); #endif #if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED) //User should use one of the following SNMP demo // This routine demonstrates V1 or V2 trap formats with one variable binding. SNMPTrapDemo(); #if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3) //This routine provides V2 format notifications with multiple (3) variable bindings //User should modify this routine to send v2 trap format notifications with the required varbinds. //SNMPV2TrapDemo(); #endif if (gSendTrapFlag) SNMPSendTrap(); #endif #if defined ( WF_CONSOLE ) && defined ( EZ_CONFIG_SCAN ) WFDisplayScanMgr(); #endif #if defined(STACK_USE_BERKELEY_API) BerkeleyTCPClientDemo(); BerkeleyTCPServerDemo(); BerkeleyUDPClientDemo(); #endif if((updateDisplay && CFGCXT.isWifiDoneConfigure) || (dwLastIP != AppConfig.MyIPAddr.Val)) { if(dwLastIP != AppConfig.MyIPAddr.Val) dwLastIP = AppConfig.MyIPAddr.Val; if(updateDisplay && CFGCXT.isWifiDoneConfigure) updateDisplay = 0; #if defined(STACK_USE_ANNOUNCE) AnnounceIP(); #endif #if defined(STACK_USE_ZEROCONF_MDNS_SD) mDNSFillHostRecord(); #endif DisplaySSID(); } } }
//função principal void main(void) { static TICK t = 0; //inicializa todas as configuraçoes de hardware InitializeBoard(); #if defined(USE_LCD) //inicializa configs do LCD se acaso estiver habilitado LCDInit(); DelayMs(100); strcpypgm2ram((char*)LCDText, "APP TCPIP"); LCDUpdate(); #endif //inicializa um tick de tempo usado para TICK,SPI,UAT TickInit(); //inicializa MPSF para upload de paginas web se acaso estiver habilitado #if defined(STACK_USE_MPFS) || defined(STACK_USE_MPFS2) MPFSInit(); #endif //inicializa variaveis da aplicação AppConfig (IP, MASCARA, GATWAY, ETC) InitAppConfig(); //inicializa a layer da pilha TCPIP (MAC, ARP, TCP, UDP) //e tambem as aplicaçoes habilitadas (HTTP, SNMP, SOCKET, ETC) StackInit(); //inicializa UART 2 TCP Bridge #if defined(STACK_USE_UART2TCP_BRIDGE) UART2TCPBridgeInit(); #endif //laço principal (nunca use delays, apenas maquinas de estado) //todos os processos devem estar executando paralelamente while(1) { //pisca o led para informar a pilha rodando if(TickGet() - t >= TICK_SECOND/2ul) { t = TickGet(); LED0_IO ^= 1; } //processa coisas relacionadas ao hardware, leitura de pinos,etc. ProcessIO(); //chama tarefas da pilha TCPIP StackTask(); //chama tarefas das aplicaçoes habilitadas StackApplications(); //exemplo de aplicação Cliente Socket #if defined(STACK_USE_TCP_CLIENT) ClientSocketTCP(); #endif //exemplo de aplicação Servidor Socket #if defined(STACK_USE_TCP_SERVER) ServerSocketTCP(); #endif } }
void accessor_module(void) { bd_t ipacket, opacket; static uid_t uid; static WORD label_cache; if (mail_reciev(MYSELF, &ipacket)) { if (bcp_buffer(ipacket)->status == BD_TIMEOUT) process_tout_buffer(ipacket); else if (bcp_buffer(ipacket)->status == BD_OBTAINED) process_host_buffer(ipacket); } switch (state) { case WAIT_UID: if (readers_get_uid(&uid)) { memset((void *)LCDText, ' ', LCD_SIZE); LCDText[LCD_SIZE] = '\0'; LCDUpdate(); state = CHECK_SM; } break; case CHECK_SM: if(sm_is_ready()) { event_send(MODULE_SRVMACHINE, EVT_SM_PREPARE); } else { strcpy(LCD_STRING_0, AppConfig.acc_busy_msg); LCD_decode(LCD_ALL); LCDUpdate(); LCD_set_tout(TICK_SECOND * 5); state = WAIT_UID; break; } /* It's OK, send to host */ opacket = bcp_obtain_buffer(MYSELF); if (opacket < 0) { TRACE("\n\rACS: can't obtaine buffer (QAC_AR_REQUEST)"); break; } { bcp_header_t * hdr = (bcp_header_t *) bcp_buffer(opacket)->buf; ar_req *request = (ar_req *) &hdr->raw[RAW_DATA]; TRACE("\n\rACS: buffer obtained (QAC_AR_REQUEST)"); hdr->hdr_s.type = TYPE_NPDL; SET_FQ(hdr->hdr_s.type); hdr->hdr_s.packtype_u.npdl.qac = QAC_AR_REQUEST; hdr->hdr_s.packtype_u.npdl.len = (sizeof(ar_req) - MAX_UID_SIZE) + strlen(uid.uid) + CRC16_BYTES; request->retries = AppConfig.acc_retry_cnt; request->reader_n = uid.gate; request->req_label = label_cache = (WORD) TickGet(); strcpy(request->uid, uid.uid); bcp_send_buffer(opacket); state = WAIT_HOST_ANSWER; } break; case WAIT_HOST_ANSWER: break; case WAIT_SM: if(event_recieve(MYSELF, &event)) { opacket = bcp_obtain_buffer(MYSELF); if (opacket < 0) { break; } if(event & EVT_AC_DONE) { bcp_header_t * hdr = (bcp_header_t *) bcp_buffer(opacket)->buf; eos_req *request = (eos_req *) &hdr->raw[RAW_DATA]; TRACE("\n\rACS: buffer obtained (QAC_SERV_DONE)"); hdr->hdr_s.type = TYPE_NPDL; SET_FQ(hdr->hdr_s.type); hdr->hdr_s.packtype_u.npdl.qac = QAC_SERV_DONE; hdr->hdr_s.packtype_u.npdl.len = sizeof(eos_req) + CRC16_BYTES; request->retries = AppConfig.acc_retry_cnt; request->reader_n = uid.gate; request->req_label = label_cache; bcp_send_buffer(opacket); state = WAIT_UID; readers_reset_state(); } else if (event & EVT_AC_TOUT) { bcp_header_t * hdr = (bcp_header_t *) bcp_buffer(opacket)->buf; eos_req *request = (eos_req *) &hdr->raw[RAW_DATA]; TRACE("\n\rACS: buffer obtained (QAC_SERV_REJECT)"); hdr->hdr_s.type = TYPE_NPDL; SET_FQ(hdr->hdr_s.type); hdr->hdr_s.packtype_u.npdl.qac = QAC_SERV_REJECT; hdr->hdr_s.packtype_u.npdl.len = sizeof(eos_req) + CRC16_BYTES; request->retries = AppConfig.acc_retry_cnt; request->reader_n = uid.gate; request->req_label = label_cache; bcp_send_buffer(opacket); state = WAIT_UID; readers_reset_state(); } else { bcp_release_buffer(opacket); } } break; } }
// Only dynamic read-write variables needs to be handled. BOOL SNMPSetVar(SNMP_ID var, SNMP_INDEX index, BYTE ref, SNMP_VAL val) { switch(var) { case LED_D5: LED1_IO = val.byte; return TRUE; case LED_D6: LED2_IO = val.byte; return TRUE; case TRAP_RECEIVER_IP: // Make sure that index is within our range. if ( index < trapInfo.Size ) { // This is just an update to an existing entry. trapInfo.table[index].IPAddress.Val = val.dword; return TRUE; } else if ( index < TRAP_TABLE_SIZE ) { // This is an addition to table. trapInfo.table[index].IPAddress.Val = val.dword; trapInfo.table[index].communityLen = 0; trapInfo.Size++; return TRUE; } break; case TRAP_RECEIVER_ENABLED: // Make sure that index is within our range. if ( index < trapInfo.Size ) { // Value of '1' means Enabled". if ( val.byte == 1 ) trapInfo.table[index].Flags.bEnabled = 1; // Value of '0' means "Disabled. else if ( val.byte == 0 ) trapInfo.table[index].Flags.bEnabled = 0; else // This is unknown value. return FALSE; return TRUE; } // Given index is more than our current table size. // If it is within our range, treat it as an addition to table. else if ( index < TRAP_TABLE_SIZE ) { // Treat this as an addition to table. trapInfo.Size++; trapInfo.table[index].communityLen = 0; } break; case TRAP_COMMUNITY: // Since this is a ASCII_STRING data type, SNMP will call with // SNMP_END_OF_VAR to indicate no more bytes. // Use this information to determine if we just added new row // or updated an existing one. if ( ref == SNMP_END_OF_VAR ) { // Index equal to table size means that we have new row. if ( index == trapInfo.Size ) trapInfo.Size++; // Length of string is one more than index. trapInfo.table[index].communityLen++; return TRUE; } // Make sure that index is within our range. if ( index < trapInfo.Size ) { // Copy given value into local buffer. trapInfo.table[index].community[ref] = val.byte; // Keep track of length too. // This may not be NULL terminate string. trapInfo.table[index].communityLen = (BYTE)ref; return TRUE; } break; #if defined(USE_LCD) case LCD_DISPLAY: // Copy all bytes until all bytes are transferred if ( ref != SNMP_END_OF_VAR ) { LCDText[ref] = val.byte; LCDText[ref+1] = 0; } else { LCDUpdate(); } return TRUE; #endif } return FALSE; }
void PingPongStateMachine() { BYTE i; WORD j, k; BYTE packagerssi; switch(case_value) { case 0: //Send 0x01 frame to initiate ping - pong test MiApp_FlushTx(); MiApp_WriteData(0x01); for(i = 0; i < sizeof(PingPongPacket); i++) { MiApp_WriteData(PingPongPacket[i]); } /*******************************************************************/ // Function MiApp_BroadcastPacket is used to broadcast a message // The only parameter is the boolean to indicate if we need to // secure the frame /*******************************************************************/ MiApp_BroadcastPacket(FALSE); PingPong_Count = 0; previous_state = 0; case_value = 8; LCDDisplay((char *)"Transmitting...", 0, TRUE); //Printf("\r\nIn case 0"); break; case 1: //Send 0x04 frames - indicating data transmission MiApp_FlushTx(); MiApp_WriteData(0x04); for(i = 0; i < sizeof(PingPongPacket); i++) { MiApp_WriteData(PingPongPacket[i]); } if(PingPong_Count != PingPong_Package) { MiApp_BroadcastPacket(FALSE); case_value = 1; PingPong_Count++; LED_1 ^= 1; LCDErase(); sprintf((char *)LCDText, (far rom char *) "Transmitting..."); sprintf((char *) &(LCDText[16]), (far rom char *) "Count: %d", PingPong_Count); LCDUpdate(); } else { Printf("\r\nSent Packet Count: "); PrintDec(PingPong_Package); PingPong_Count = 0; case_value = 2; } previous_state = 1; //Printf("\r\nIn case 1"); break; case 2: //Send 0x02 frame to get status response MiApp_FlushTx(); MiApp_WriteData(0x02); for(i = 0; i < sizeof(PingPongPacket); i++) { MiApp_WriteData(PingPongPacket[i]); } MiApp_BroadcastPacket(FALSE); previous_state = 2; case_value = 8; //Printf("\r\n In case 2"); break; case 3: //Ping Pong Receive Mode if(MiApp_MessageAvailable()) { if(rxMessage.Payload[0] == 0x01) { BYTE rssi = rxMessage.PacketRSSI; #if defined(MRF24J40) rssi = RSSIlookupTable[rssi]; #endif MiApp_DiscardMessage(); MiApp_FlushTx(); MiApp_WriteData(0x03); for(i = 0; i < sizeof(PingPongPacket); i++) { MiApp_WriteData(PingPongPacket[i]); } MiApp_BroadcastPacket(FALSE); PingPong_RxCount = 0; //LCDDisplay((char *)"Ping Pong Test Rcvng.. RSSI:", rssi, TRUE); LCDErase(); sprintf((char *)LCDText, (far rom char *) "Receiving.. "); #if defined(MRF24J40) sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): --"); #else sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): --"); #endif LCDUpdate(); packagerssi = rssi; } else if(rxMessage.Payload[0] == 0x04) { BYTE rssi = rxMessage.PacketRSSI; #if defined(MRF24J40) rssi = RSSIlookupTable[rssi]; #endif MiApp_DiscardMessage(); PingPong_RxCount++; previous_state = 3; LED_2 ^= 1; LCDErase(); sprintf((char *)LCDText, (far rom char *) "Receiving.. %d", PingPong_RxCount); #if defined(MRF24J40) sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): -%d", packagerssi); #else sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): -%d", packagerssi); #endif LCDUpdate(); case_value++; } else if(rxMessage.Payload[0] == 0x02) { Printf("\r\nReceived Packet Count:"); PrintDec(PingPong_RxCount); MiApp_DiscardMessage(); case_value = case_value + 2; } else { //Printf("\r\nIllegal packet received with payload first byte set to - "); //PrintDec(rxMessage.Payload[0]); MiApp_DiscardMessage(); } } //Printf("\r\n In case 3"); break; case 4: if(MiApp_MessageAvailable()) { if(rxMessage.Payload[0] == 0x04) { BYTE rssi = rxMessage.PacketRSSI; MiApp_DiscardMessage(); PingPong_RxCount++; LED_2 ^= 1; LCDErase(); sprintf((char *)LCDText, (far rom char *) "Receiving.. %d", PingPong_RxCount); #if defined(MRF24J40) sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): -%d", packagerssi); #else sprintf((char *) &(LCDText[16]), (far rom char *) "RSSI (dB): %d", packagerssi); #endif LCDUpdate(); } else if(rxMessage.Payload[0] == 0x02) { Printf("\r\nReceived Packet Count:"); PrintDec(PingPong_RxCount); MiApp_DiscardMessage(); case_value++; } else { //Printf("\r\nIllegal packet received with payload first byte set to - "); //PrintDec(rxMessage.Payload[0]); //Printf("\r\n"); MiApp_DiscardMessage(); } } //Printf("\r\n In case 4"); break; case 5: MiApp_FlushTx(); MiApp_WriteData(0x03); for(i = 0; i < sizeof(PingPongPacket); i++) { MiApp_WriteData(PingPongPacket[i]); } MiApp_BroadcastPacket(FALSE); previous_state = 0; case_value = 8; //Printf("\r\n In case 5"); break; case 8: case_value = previous_state; DelayMs(20); if(MiApp_MessageAvailable()) { if(rxMessage.Payload[0] == 0x03) { case_value = (previous_state + 1); } if(rxMessage.Payload[0] == 0x01) { case_value = (previous_state + 1); } if(rxMessage.Payload[0] == 0x02) { case_value = 5; } MiApp_DiscardMessage(); } //Printf("\r\nIn case 8"); break; default: break; } //end of switch statement }
/********************************************************************* * Function: void RangeDemo(void) * * PreCondition: none * * Input: none * * Output: none * * Side Effects: none * * Overview: Following routine * * * Note: **********************************************************************/ void RangeDemo(void) { BOOL Run_Demo = TRUE; BOOL Tx_Packet = TRUE; BYTE rssi = 0; BYTE Pkt_Loss_Cnt = 0; MIWI_TICK tick1, tick2; BYTE switch_val; /*******************************************************************/ // Dispaly Range Demo Splach Screen /*******************************************************************/ LCDBacklightON(); LCDDisplay((char *)" Microchip Range Demo ", 0, TRUE); LCDBacklightOFF(); /*******************************************************************/ // Read Start tickcount /*******************************************************************/ tick1 = MiWi_TickGet(); while(Run_Demo) { /*******************************************************************/ // Read current tickcount /*******************************************************************/ tick2 = MiWi_TickGet(); // Send a Message if((MiWi_TickGetDiff(tick2,tick1) > (ONE_SECOND * TX_PKT_INTERVAL))) { LCDErase(); if(Tx_Packet) { LCDDisplay((char *)"Checking Signal Strength...", 0, TRUE); MiApp_FlushTx(); MiApp_WriteData(RANGE_PKT); MiApp_WriteData(0x4D); MiApp_WriteData(0x69); MiApp_WriteData(0x57); MiApp_WriteData(0x69); MiApp_WriteData(0x20); MiApp_WriteData(0x52); MiApp_WriteData(0x6F); MiApp_WriteData(0x63); MiApp_WriteData(0x6B); MiApp_WriteData(0x73); MiApp_WriteData(0x21); if( MiApp_UnicastConnection(0, FALSE) == FALSE ) Pkt_Loss_Cnt++; else Pkt_Loss_Cnt = 0; Tx_Packet = FALSE; } else { if(Pkt_Loss_Cnt < 1) { if(rssi > 120) { sprintf((char *)&LCDText, (far rom char*)"Strength: High "); LED0 = 1; LED1 = 0; LED2 = 0; } else if(rssi < 121 && rssi > 60) { sprintf((char *)&LCDText, (far rom char*)"Strength: Medium"); LED0 = 1; LED1 = 1; LED2 = 0; } else if(rssi < 61) { sprintf((char *)&LCDText, (far rom char*)"Strength: Low"); LED0 = 0; LED1 = 1; LED2 = 0; } // Convert to dB //rssi = RSSIlookupTable[rssi]; sprintf((char *)&(LCDText[16]), (far rom char*)"Rcv RSSI: %03d", rssi); } else { LCDDisplay((char *)"No Device Found or Out of Range ", 0, TRUE); LED0 = 0; LED1 = 0; LED2 = 1; } LCDUpdate(); Tx_Packet = TRUE; } /*******************************************************************/ // Read New Start tickcount /*******************************************************************/ tick1 = MiWi_TickGet(); } // Check if Message Available if(MiApp_MessageAvailable()) { if(rxMessage.Payload[0] == EXIT_PKT) { MiApp_DiscardMessage(); MiApp_FlushTx(); MiApp_WriteData(ACK_PKT); MiApp_UnicastConnection(0, FALSE); Run_Demo = FALSE; LCDBacklightON(); LCDDisplay((char *)" Exiting.... Range Demo ", 0, TRUE); LCDBacklightOFF(); } else if(rxMessage.Payload[0] == RANGE_PKT) { // Get RSSI value from Recieved Packet rssi = rxMessage.PacketRSSI; // Disguard the Packet so can recieve next MiApp_DiscardMessage(); } else MiApp_DiscardMessage(); } // Check if Switch Pressed switch_val = ButtonPressed(); if((switch_val == SW0) || (switch_val == SW1)) { /*******************************************************************/ // Send Exit Demo Request Packet and exit Range Demo /*******************************************************************/ MiApp_FlushTx(); MiApp_WriteData(EXIT_PKT); MiApp_UnicastConnection(0, FALSE); LCDBacklightON(); LCDDisplay((char *)" Exiting.... Range Demo ", 0, TRUE); LCDBacklightOFF(); tick1 = MiWi_TickGet(); // Wait for ACK Packet while(Run_Demo) { if(MiApp_MessageAvailable()) { if(rxMessage.Payload[0] == ACK_PKT) Run_Demo = FALSE; MiApp_DiscardMessage(); } if ((MiWi_TickGetDiff(tick2,tick1) > (ONE_SECOND * EXIT_DEMO_TIMEOUT))) Run_Demo = FALSE; tick2 = MiWi_TickGet(); } } } }
Zone_States CheckEOL (int ZoneID, WORD* ADval) { char AN0String[7]; char DebugTemp[7]; int PlexerDevice, BinaryValue; // Disable all analogue multiplexer PLEXERA_S_IO = 1; // High = disabled PLEXERB_S_IO = 1; PLEXERC_S_IO = 1; // Select the analogue multiplexer PlexerDevice = ZoneID / 8; BinaryValue = ZoneID - ((ZoneID / 8) * 8); // The value can now be expressed as a 3 bit value if (PlexerDevice == 0) { PLEXERA_S_IO = 0; //enable this device PLEXERA_2_IO = ((BinaryValue / 4 > 0)?TRUE:FALSE); BinaryValue -= (BinaryValue / 4) * 4; PLEXERA_1_IO = ((BinaryValue / 2 > 0)?TRUE:FALSE); BinaryValue -= (BinaryValue / 2) * 2; PLEXERA_0_IO = ((BinaryValue > 0)?TRUE:FALSE); } // PlexerDevice ==0 else if (PlexerDevice == 1) { PLEXERB_S_IO = 0; //enable this device PLEXERB_2_IO = BinaryValue / 4; BinaryValue -= (BinaryValue / 4) * 4; PLEXERB_1_IO = BinaryValue / 2; BinaryValue -= (BinaryValue / 2) * 2; PLEXERB_0_IO = BinaryValue; } // PlexerDevice == 1 else if (PlexerDevice == 2) { PLEXERC_S_IO = 0; //enable this device PLEXERC_2_IO = BinaryValue / 4; BinaryValue -= (BinaryValue / 4) * 4; PLEXERC_1_IO = BinaryValue / 2; BinaryValue -= (BinaryValue / 2) * 2; PLEXERC_0_IO = BinaryValue; } // PlexerDevice == 2 else { #if defined(DEBUG_UART) putrsUART((ROM char*)" !!! CheckEOL is out of range !!!!! "); #endif *ADval = 0; return StateNormal; } //60 ns delay is required for the Multiplexer to swith analogue channels //Nop();Nop();Nop();Nop();Nop(); // Select A/D channel AN4 ADCON0 = 0b00010000; // ADON = On(1), GO/DONE = Idle (0), AN4 selected (0100), not used (0), calibration off (0) ADCON0bits.ADON = 1; ADCON0bits.GO = 1; // Wait until A/D conversion is done while(ADCON0bits.GO); // Convert 10-bit value into ASCII string *ADval = (WORD)ADRES; uitoa(*ADval, AN0String); if (ZoneID == 1) { memset(LCDText, '\0', 32); if (strlen(AN0String) < (unsigned int)4 ) strcatpgm2ram(AN0String, (rom char *) " "); if (strlen(AN0String) < (unsigned int)4 ) strcatpgm2ram(AN0String, (rom char *) " "); if (strlen(AN0String) < (unsigned int)4 ) strcatpgm2ram(AN0String, (rom char *) " "); strcat(LCDText, AN0String); strcatpgm2ram(LCDText, (rom char *) "->"); } if ( (*ADval >= (WORD)(EOLNORMAL - EOLTOLERANCE)) && (*ADval <= (WORD)(EOLNORMAL + EOLTOLERANCE))) { if (ZoneID == 1) { strcatpgm2ram(LCDText, (rom char *) "Normal"); LCDUpdate(); } // Need to consider if the zone is Normaly Open or Normaly Closed if (ZoneConfig[ZoneID].IsNO == FALSE) return StateNormal; else return StateTrigger; } else if ( (*ADval >= (WORD)(EOLTRIGGER - EOLTOLERANCE)) && (*ADval <= (WORD)(EOLTRIGGER + EOLTOLERANCE))) { if (ZoneID == 1) { strcatpgm2ram(LCDText, (rom char *) "Trigger"); LCDUpdate(); } // Need to consider if the zone is Normaly Open or Normaly Closed if (ZoneConfig[ZoneID].IsNO == FALSE) return StateTrigger; else return StateNormal; } else { if (ZoneID == 1) { strcatpgm2ram(LCDText, (rom char *) "Tamper"); LCDUpdate(); } return StateTamper; } } // CheckEOL
/***************************************************************************** Function: void PingDemo(void) Summary: Demonstrates use of the ICMP (Ping) client. Description: This function implements a simple ICMP client. The function is called periodically by the stack, and it checks if BUTTON0 has been pressed. If the button is pressed, the function sends an ICMP Echo Request (Ping) to a Microchip web server. The round trip time is displayed on the UART when the response is received. This function can be used as a model for applications requiring Ping capabilities to check if a host is reachable. Precondition: TCP is initialized. Parameters: None Returns: None ***************************************************************************/ void PingDemo(void) { static enum { SM_HOME = 0, SM_GET_ICMP_RESPONSE } PingState = SM_HOME; static uint32_t Timer; int32_t ret; switch(PingState) { case SM_HOME: // Send a ping request out if the user pushes BUTTON0 (right-most one) if(BUTTON0_IO == 0u) { // Don't ping flood: wait at least 1 second between ping requests if(TickGet() - Timer > 1ul*TICK_SECOND) { // Obtain ownership of the ICMP module if(!ICMPBeginUsage()) break; // Update anti-ping flood timer Timer = TickGet(); // Send ICMP echo request #if defined(STACK_USE_DNS) ICMPSendPingToHostROM((ROM uint8_t*)HOST_TO_PING); #else ICMPSendPing(AppConfig.MyGateway.Val); #endif PingState = SM_GET_ICMP_RESPONSE; } } break; case SM_GET_ICMP_RESPONSE: // Get the status of the ICMP module ret = ICMPGetReply(); if(ret == -2) { // Do nothing: still waiting for echo break; } else if(ret == -1) { // Request timed out #if defined(USE_LCD) memcpypgm2ram((void*)&LCDText[16], (ROM void *)"Ping timed out", 15); LCDUpdate(); #endif PingState = SM_HOME; } else if(ret == -3) { // DNS address not resolvable #if defined(USE_LCD) memcpypgm2ram((void*)&LCDText[16], (ROM void *)"Can't resolve IP", 16); LCDUpdate(); #endif PingState = SM_HOME; } else { // Echo received. Time elapsed is stored in ret (Tick units). #if defined(USE_LCD) memcpypgm2ram((void*)&LCDText[16], (ROM void *)"Reply: ", 7); uitoa((uint16_t)TickConvertToMilliseconds((uint32_t)ret), &LCDText[16+7]); strcatpgm2ram((char*)&LCDText[16+7], "ms"); LCDUpdate(); #endif PingState = SM_HOME; } // Finished with the ICMP module, release it so other apps can begin using it ICMPEndUsage(); break; } }