MT7681 Io T WIFI Firmware Programming Guide V1.0
User Manual:
Open the PDF directly: View PDF .
Page Count: 32
- 1 INTRODUCTION
- 2 SW STRUCTURE
- 3 FILE STRUCTURE
- 4 FIRMWARE BOOT UP FLOW
- 5 WIFI CONNECTION STATE MACHINE FLOW
- 6 CUSTOMER HOOK FUNCTION
- 7 CUSTOMER UART-TO-WIFI FUNCTION
- 8 FLASH SETTINGS LOAD/STORAGE
- 9 AT COMMAND
- 10 DATA COMMAND
- 11 WIFI MAC APIS
- 12 SECURITY APIS
- 13 TIMER APIS
- 14 INTERFAE APIS
- 15 FLASH PARTITIONS
- 16 COMPILER SETUP
- 17 AT COMMAND USAGE

Version:1.0
Releasedate:2014‐8‐8
©2014MediaTekInc.
ThisdocumentcontainsinformationthatisproprietarytoMediaTekInc.
Unauthorizedreproductionordisclosureofthisinformationinwholeorinpartisstrictlyprohibited.
Specificationsaresubjecttochangewithoutnotice.
MT7681IoTWi‐FiFirmware
ProgrammingGuide
Mediatek Confidential

RevisionHistory
DateRevisionAuthorDescription
01.03.2014Firstv0.01JinchuanInitialdraftforMT7681IoTFirmwareProgrammingGuide.
01.16.2014v0.02JiayiUpdateFlashLayoutandFlashAPI
UpdateFolderStructure
01.24.2014v0.03JinchuanUpdateFlashLayoutandFlashAPI:spi_flash_write()
AddSection:ATCommandUsage
03.22.2014v0.04Jinchuan
Jerry
AddFIRMWAREbootUPflow
AddCustomerHookFunction
AddFlashsettingsLoad/Storage
AddTimerAPIs
ModifyInterfaeAPIs
ModifyFlashPartitions
04.15.2014v0.05Jinchuan
Jerry
ModifyFileStructure
ModifyGPIOInterfaceDescriptionandGPIO/PinModeSet
ModifyFlashPartitions
AddNewPWMAPI
AddCustomerUART‐TO‐WIFIFunction
AddCustomerHookFunctionforSmartConnection
05.16.2014v0.07JinchuanAddIoT_gpio_read()
AddIoT_Cust_Set_GPIINT_MODE();
IoT_Cust_Get_GPIINT_MODE();
IoT_Cust_GPIINT_Hdlr()
AddGetMsTimer()
AddSecurityAPI
UpdateFirmwareBootUpFlow
UpdateCustomerHootkFunctioin
UpdateFileStructure
UpdateIoT_led_pwm():led_numrangeinsoftpwmmode
DeleteATCmdaboutTCP/UDP
05.30.2014v0.08JinchuanAddAPIsforRxfiltercontrol
AddSetchannelAPI
AddRxPacketAPI:STARxDoneInterruptHandle
AddTxPacketAPI:mt76xx_dev_send
AddAPIsforMD5:RT_MD5()…
07.09.2014v0.09JinchuanAddWifiStateMachineFlowchart
UpdateRxfilterAPI’sNotes
UpdateIoT_Cmd_Set_ChannelAPI’schannelrange
UpdateATCmdChannelSwitch:AT#Channel‐b0‐c6
AddATcmdforSmartConnectionentry:AT#Smnt
Addspi_flash_write_func()description
Updatespi_flash_write()descriptionandAdddesignflow
AddHWTimer1InterruptFunction
8.8.2014V1.0JinchuanUpdateRxFilterDescription
CorrectAPInameas:RT_AES_Decrypt,RT_AES_Encrypt
Mediatek Confidential

AddSamplecodedescriptforAESECB/CBCDecrypt/Encrypt
AddIoT_send_udp_directly()APItosendudppacket
AddAsicSetChannel()API
AddSPICmdtableinthesectionof“FlashDriver”
Contents
1Introduction...................................................................................................................................................................5
1.1FlowChartSymbols..........................................................................................................................................5
1.2Keywords..........................................................................................................................................................5
2SWStructure.................................................................................................................................................................6
2.1Flowchart.........................................................................................................................................................6
3FileStructure.................................................................................................................................................................6
4FIRMWAREbootUPflow..............................................................................................................................................7
5WifiConnectionStateMachineFlow............................................................................................................................7
6CustomerHookFunction...............................................................................................................................................8
7CustomerUART‐TO‐WIFIFunction................................................................................................................................9
8FlashsettingsLoad/Storage........................................................................................................................................10
9ATCommand...............................................................................................................................................................13
9.1Flowchart:......................................................................................................................................................13
9.2FunctionDescription.......................................................................................................................................13
9.3HowtoaddanewATcommand.....................................................................................................................14
10DataCommand............................................................................................................................................................14
10.1Flowchart:......................................................................................................................................................14
10.2FunctionDescription.......................................................................................................................................15
10.3HowtoaddanewDatacommand.................................................................................................................15
11WIFIMACAPIS.............................................................................................................................................................16
11.1RxFilterControl..............................................................................................................................................16
11.2MACControl...................................................................................................................................................16
Mediatek Confidential
12SecurityAPIS................................................................................................................................................................18
13TimerAPIs....................................................................................................................................................................20
13.1SWTimerAPIs.................................................................................................................................................20
13.2HWtimer1interruptfunction.........................................................................................................................21
14InterfaeAPIs................................................................................................................................................................21
14.1FlashDriver.....................................................................................................................................................21
14.2UART...............................................................................................................................................................23
14.3LED/PWM......................................................................................................................................................24
14.4GPIO................................................................................................................................................................25
14.5GPIO/PinModeSet.........................................................................................................................................27
15FlashPartitions............................................................................................................................................................28
16CompilerSetup............................................................................................................................................................30
17ATCommandUsage....................................................................................................................................................31
17.1Displayversion................................................................................................................................................31
17.2Rebootthesystem..........................................................................................................................................31
17.3SetDefault......................................................................................................................................................31
17.4Switchchannel................................................................................................................................................31
17.5ConfigureUARTinterface...............................................................................................................................31
17.6UpdateFirmwarefromUart...........................................................................................................................31
17.7EnterintoSmartConnectionState.................................................................................................................31
17.8EnterintoDeepsleepmode...........................................................................................................................32
Mediatek Confidential

1 INTRODUCTION
The7681IoTWi‐Fistructurecouldbedividedintotwolayers(HWlayer,FirmwareLayer);
Thisdocumentaimstohelptheprogrammersunderstandthe7681Wi‐FiFirmwarearchitectureandhowtodothe
customization,suchasATcommandorDatacommand
1.1 FlowChartSymbols
1.2 Keywords
BBP: BaseBandProcessor
SEC: SecurityEngine
PBF: PacketBuffer
PDMA: ProgrammableDirectMemoryAccess
FCE: FrameControlEngine
Mediatek Confidential

2 SWSTRUCTURE
2.1 Flowchart
HWinit:initializetheHWregisterstoenableHWinterfacesandWi‐Fifunction
Wi‐FiStatemachine:asinglelooptocontrolWi‐FiTx,Rx,andprocesstheDatacommand,ATcommand
DataCommandhandler:handletheDatacommandwhichreceivedfromWi‐Fi
ATCommandhandler:handletheATcommandwhichreceivedfromUART
3 FILESTRUCTURE
\cust\main_pub.c,Mainentry
\cust\wifi_task_pub.c,WifiTaskFunction
\cust\rtmp_data_pub.c,RxHandler
\cust\iot_customer.c,TheInitialHookandsettingload/storage
\cust\iot_at_cmd.c,handletheATcommandwhichreceivedfromUART
\cust\iot_at_cmd_utility.c,thecommonapiforATcommandusage
\cust\iot_parse.c,handletheDatacommandwhichreceivedfromWi‐Fi
\cust\tcpip\*.c,thesourcecodeandsamplecodeforTCPUDP
\mak\MT7681\,storetheconfigurationforcompilerorlinker
\mak\MT7681\flags_sta.mk,storethemacrosforallstationmodesourcecode
\mak\MT7681\flags_ap.mk,storethemacrosforallAPmodesourcecode
\out\,storethefileswhichcreatedbycompiler
\out\build.log,thecompilinglog
\out\MT7681.bin,thetargetbinaryfile
\src\include,theheaderfiles
libandessta.a,libraryforMT7681StationMode
libandesap.a,libraryforMT7681APMode
MT7681_all.bin,TheImageforFWupgradebyFlashwriter
(includeLoader.bin,EEPROM.bin,RecoveryFW.bin,
StationFW.bin,APFW.bin)
Mediatek Confidential

4 FIRMWAREBOOTUPFLOW
TheBootupflowis:LoaderÆRecoveryModeÆLoaderÆSTA/APFW
5 WIFICONNECTIONSTATEMACHINEFLOW
STAModev1.40:
*WhenScan,Auth,Assoc,4Way,DHCPfail,notbacktosmartconnectionstate
*SmartConnectionstateisonlytriggeredbyfollowingmethods:
1:ThereisnovalidcontentinFlashStaConfigregion
2:7681receiveATCmd:AT#Smnt
Customermaybechangethisprocess,tomakesmntstatecanbeenteredwithothermethod
bycontrolATSetSmntflag
Mediatek Confidential

6 CUSTOMERHOOKFUNCTION
Iot_customer.c
IoT_Cust_Ops()isusedtoregistercallbackfunction,whichcouldbecalledbyWifimainfunction
Whenandwherethiscallbackfunctionwillbeused,pleaseseenextpictureforthedetails
Mediatek Confidential

7 CUSTOMERUART‐TO‐WIFIFUNCTION
Iot_customer_uart2wifi.c
Mediatek Confidential

IoT_Cust_uart2wifi_data_handler():
Itisthekeyfunctionforuart‐to‐wifitransmission.
ItisthebridgebetweenuartmoduleandTCP/IPmoduleofWiFi.
Inthesamplecode,uip_send()iscalledtosenddatafromuarttowifi.
IoT_Cust_uart2wifi_init():
Youcanuseittoconfigureuart‐to‐wifitimerintervalanduarttriggercount.
Inthesamplecode,every300ms,orwhentheuartrxcontentislargerthan10,
auart‐to‐wifitransmissionjudgmentwillbetriggered.
IoT_Cust_uart2wifi_detect_gpio_input_change():
Youcanuseittodefineyourowninputstatuschange.
Inthesamplecode,whentheinputofgpio2ishigh,uartrxisswitchedtopuredatamode;
otherwise,itisswitchedtoATcmdmode.
Note:
Uart‐to‐wififunctioncollideswithdataparseruartrxfunction,
soyoumustsetDATAPARSING_UARTRX_SUPPORTto0first.
Whenandwherethesefunctionswillbeused,pleaseseenextpictureforthedetails
8 FLASHSETTINGSLOAD/STORAGE
Iot_customer.c
ThedefaultsettingsonUser/Commonconfigblockoftheflash,ifthereisnocontentorthecontentisinvalid,
systemshallusedthesedefaultsettings,thedetailimplementationisontheiot_customer.c
Mediatek Confidential

Therearetwostructures:IOT_COM_CFG,IOT_USR_CFG
IOT_COM_CFG:Pleasedonotmodifythisstructure,becausetheWi‐Fimaintask/TCPIPwillusethisstructurefor
moduleinitializationoroperation
IOT_USR_CFG:Canbecustomized,becauseonlyiot_parser.c,iot_custom.cwillusethisstructure
Notice:BothofabovetwostructuresaremappingwithFlashLayout,andthesettingsload/resetisoptimizedforcode
sizeslimbymacro“FLASH_STRUCT_MAPPING1”withthiscondition.
IfthestructureisnotmappingwithFlashLayout,“FLASH_STRUCT_MAPPING”shouldbesetas0
Mediatek Confidential

ExampleA:ModifyIOTServerIPto{172.133.125.12}
Method1:Change#defineDEFAULT_IOT_SERVER_IP{182.148.129.91}to{172.133.125.12}
Method2:notmodifyDEFAULT_IOT_SERVER_IP,butuseFLASHAPItowritethenewvaluetorelated
positionoftheFLASH,thus,whileMT7681rebootorpoweronagain,thenewsettingsonflashwillbeload
ExampleB:AddaUart2WifiLengthparametertoUserConfigBlock
Step1:addnewmacroinflash_mapping.htoindicateUart2Wifipositionontheflash,
Step2:AddnewmemberonIOT_USR_CFGstructure
Step3:Addadefaultvaluemacro,justlike:#defineDEFAULT_IOT_SERVER_IP{182.148.129.91}
Step4:Addload/resetimplementationforUart2Wifionload_usr_cfg(),rest_usr_cfg()
Mediatek Confidential

9 ATCOMMAND
9.1 Flowchart:
9.2 FunctionDescription
z INT32IoT_parse_ATcommand(PUCHARcmd_buf,INT32at_cmd_len);
Description:ThisfunctionparsesATcommandfromtheUartport.Itclassifiesthecommandsandcallrespective
functionstoparsethecommands.
Paramters:
[IN]:cmd_buf ‐‐‐‐PointertoATcommandbuffer
[IN]:at_cmd_len ‐‐‐‐LengthoftheATcommand.
ReturnValues:Returnnegativeiferroroccurs.Returnzero,otherwise.
Remarks:Thecommandheader“AT#”isremovedbeforeenteringthisfunction.
z INT32IoT_exec_ATcommand_uart(PUCHARcmd_buf,INT32at_cmd_len)
Description:ThisfunctionparsesuartATcommand.
Paramters:
[IN]:cmd_buf‐‐‐‐PointertouartATcommandbuffer
[IN]:at_cmd_len‐‐‐‐LengthoftheuartATcommand.
ReturnValue:Returnnegativeiferroroccurs.Returnzero,otherwise.
Remark:None.
z INT32IoT_exec_ATcommand_netmode(PUCHARcmd_buf,INT32at_cmd_len)
Description:ThisfunctionparsesnetmodeATcommand.
Paramters:
[IN]:cmd_buf‐‐‐‐PointertonetmodeATcommandbuffer
[IN]:at_cmd_len‐‐‐‐LengthofthenetmodeATcommand.
ReturnValue:Returnnegativeiferroroccurs.Returnzero,otherwise.
Remark: None.
Mediatek Confidential

9.3 HowtoaddanewATcommand
1) Addanewelse/ifbranchforthenewATcommandtypeinthefunctionIoT_parse_ATcommand.
2)Addanewparsingfunctionforthenewtype.IoT_exec_ATcommand_netmodecanbeatemplate.
10 DATACOMMAND
10.1 Flowchart:
Mediatek Confidential

10.2 FunctionDescription
z INT32IoT_proc_app_packet(UCHARsock_num,PUCHARpacket,UINT16rawpacketlength);
Description:Thisfunctionparsescontrolprotocolpacketintheapplicationlayer.
Itremovesprotocolheaderandcallrespectivefunctionstoparsethedataheaderanddatacontent.
Parameters
[OUT]:sock_num‐‐‐‐socketnumberofthecurrentTCP/UDPtransmission
[OUT]:packet‐‐‐‐Pointertoprotocolheader
[OUT]:rawpacketlength ‐‐‐‐Lengthofthepacket
ReturnValue:Returnzero.
Remark:sock_numisusedtodistinguishdifferentTCP/UDPtransmission
z INT32IoT_proc_app_func_pkt(DataHeader*DataHeader,UINT16FuncType,
IoTPacketInfo*PacketInfo);
Description:Thisfunctionparsescontrolprotocolpacketofthefunctiontype.
Parameters
[OUT]:DataHeader‐‐‐‐Pointertodataheader
[OUT]:FuncType‐‐‐‐thefunctioncommandtype
[OUT]:PacketInfo‐‐‐‐packetinformationthatisusedwhensendingtheresponse.
ReturnValue:Returnzero.
Remark:None.
z INT32IoT_proc_app_mgt_pkt(DataHeader*Dataheader,UINT16MgtType,
IoTPacketInfo*PacketInfo);
Description:Thisfunctionparsescontrolprotocolpacketofthemanagementtype.
Parameters
[OUT]:Dataheader ‐‐‐‐Pointertodataheader
[OUT]:MgtType ‐‐‐‐themanagementcommandtype
[OUT]:PacketInfo ‐‐‐‐packetinformationthatisusedwhensendingtheresponse.
ReturnValue:Returnzero.
Remark:None.
10.3 HowtoaddanewDatacommand
1. functionrelatedcommand
1)Addnewcommandinthestructuret_FunctionCommand.
2)Addanewselect/casebranchinthefunctionIoT_proc_app_func_pkt
2. managementrelatedcommand
1)Addnewcommandinthestructuret_ManagementCommand.
2)Addanewselect/casebranchinthefunctionIoT_proc_app_mgt_pkt
3. commandofotherclass
1)Addnewtypeinthestructuret_CommandType.
2)Addnewparsingfunctionforthenewtype.IoT_proc_app_func_pktcanbeatemplate.
Mediatek Confidential

3)AddanewtypeanditsparsingfunctioninthefunctionIoT_proc_app_pkt
11 WIFIMACAPIS
11.1 RxFilterControl
z UINT16IoT_Get_RxFilter(VOID)
Description:GetRxfilteraboutframereceive
ParametersNone
Returnvalue:Rxfiltervalue,thedefinitionofthesettingasblowtable
z UINT16IoT_Set_RxFilter(UINT16Value)
Description:SetRxfilteraboutframereceive
Parameters
[IN]:Value ‐‐‐‐TheRxFiltervalue,thesettingsreferstoabovetable
Returnvalue:thevalueactuallywritetoRxFilter,itshouldsameasInputParameter
Notes:whenbit5=1,bothBC/MCpacketshallbedropped,evenifbit6=0.
Notes:RxFiltershallberesetto0x7f97whenWifiStateChangebyfunctionwifi_state_chg()
11.2 MACControl
z IoT_Cmd_Set_Channel(UINT8Channel)
Description:switchCurrentChannel
Parameters
[IN]:Channel‐‐‐‐Thenewchannelshallbeswitchedto,ChannelRange[1~14]
Returnvalue:None
z INTAsicSetChannel(UCHARch,UCHARbw,UCHARext_ch)
Description:switchCurrentChannel,bandwidthandchannelsetting
Parameters
[IN]:ch,Channelnumber, ‐‐‐‐ [1~14]if'bw'isBW_40,'ch'isCenterchannel
[IN]:bw,Bandwidth‐‐‐‐ [BW_20,BW40]
Mediatek Confidential

[IN]:ext_ch,11nbandwidthsetting ‐‐‐‐ [EXTCHA_NONE,EXTCHA_ABOVE,EXTCHA_BELOW]
Returnvalue:0
Remark:
if'bw'=BW_20,'ext_ch'shouldbeEXTCHA_NONEorEXTCHA_ABOVE,thesetwooptionshavethesameeffect
forBW_20.
if'bw'=BW_20,'ext_ch'shouldnotbeEXTCHA_BELOW
Example:
AsicSetChannel(8,BW_40,EXTCHA_ABOVE)
Itmeans:7681willchangetoCenterchannel8,andbandwidth40with40MHzabovemode
Inthiscase,primarychannelis6
Ifyourwanttoscanallprimarychannels[1~13]in802.11nmode,itispossibletostartscanwiththebelowinputs
AsicSetChannel(n,BW_40,EXTCHA_ABOVE) ‐‐‐‐n=[3~11]
AsicSetChannel(m,BW_40,EXTCHA_BELOW) ‐‐‐‐m=[8‐11]
z INTrtmp_bbp_set_bw(UINT8bw)
Description:switchCurrentBandwidth
Parameters
[IN]:bw‐‐‐‐Thenewbandwidthshallbeswitchedto,bandwidthRange[0:BW20,1:BW40]
Returnvalue:AlwaysTRUE
Mediatek Confidential

z BOOLEANSTARxDoneInterruptHandle(pBD_tpBufDesc)
Description:WifiMACRxpackethandler
Parameters
[IN]:pBufDesc‐‐‐‐ThereceivedRxdescriptor,includeRxMACcontentandRxInfo
Returnvalue:FALSEiftheRxpacketisinvalid,TRUEiftheRxpacketisvalid
z VOIDmt76xx_dev_send(void)
Description:SenduipTxpacket
ParametersNone
Returnvalue:None
Notes:Thisfunctionwillcopydatafrom“uip_buf”toTxDescriptorandsendittowireless
z INT32IoT_send_udp_directly(uip_ipaddr_t*DstAddr,
PUCHARDstMAC,
UINT16SrcPort,
UINT16DstPort,
PUCHARpPayload
UINT16PayloadLen)
Description:ThisfunctionisusedtosendpacketwithUDPformatdirectly
Parameters
[IN]:DstAddr ‐‐‐‐ThepointerofdestinationIPaddress
[IN]:DstMAC ‐‐‐‐ThepointerofdestinationMACaddress
[IN]:SrcPort ‐‐‐‐Theudpportofsource
[IN]:DstPort ‐‐‐‐Theudpportofdestination
[IN]:pPayload ‐‐‐‐Thepointerofpayloadwhichshallbesendtodestination
[IN]:PayloadLen ‐‐‐‐Thelengthofpayloadwhichshallbesendtodestination
Returnvalue:0=successful,1=inputparameterisinvalid2=allocatefreequeuebufferfail
12 SECURITYAPIS
z VOIDRT_AES_Decrypt(UINT8CipherBlock[].UINTCipherBlockSize,UINT8Key[],
UINTKeyLen,UINT8PlainBlock[],UINT*PlainBlockSize);
Description:ThisfunctionisusedtodecryptdatawithAESalgorithm
Parameters
[IN]:CipherBlock[]‐‐‐‐Theblockofciphertext,16Bytes(128bit)eachblock
[IN]:CipherBlockSize ‐‐‐‐Thelengthofblockofciphertextinbytes
[IN]:Key[]‐‐‐‐Cipherkey,itmaybe16,24or32bytes
[IN]:KeyLen‐‐‐‐Thelengthcipherkeyinbytes
[IN]:PlanBlockSize ‐‐‐‐ Thelengthofallocatedplainblockinbytes
[OUT]:PlanBlock[] ‐‐‐‐ Plainblocktostoreplaintext
[OUT]:PlanBlockSize ‐‐‐‐ Thelengthofrealusedplainblockinbytes
Returnvalue:None
z VOIDRT_AES_Encrypt(UINT8PlainBlock[],UINT*PlainBlockSize,UINT8Key[],
Mediatek Confidential

UINTKeyLen,UINT8CipherBlock[].UINTCipherBlockSize);
Description:ThisfunctionisusedtoDecryptdatawithAESalgorithm
Parameters
[IN]:PlanBlock[]‐‐‐‐TheblockofPlaintext,16bytes(128bit)eachblock
[IN]:PlanBlockSize ‐‐‐‐ Thelengthofblockofplaintextinbytes
[IN]:Key[]‐‐‐‐Cipherkey,itmaybe16,24or32bytes
[IN]:KeyLen‐‐‐‐Thelengthcipherkeyinbytes
[IN]:CipherBlockSize ‐‐‐‐Thelengthofallocatedcipherblockinbytes
[OUT]:CipherBlock[]‐‐‐‐ciptertext
[OUT]:CipherBlockSize‐‐‐‐Thelengthofrealusedcipherblockinbytes
Returnvalue:None
RT_AES_Decrypt(),RT_AES_Encrypt()areonly16Bytesinput16BytesoutputforPlainBlockandCipherBlock
Therearesomesamplecodesiniot_aes_pub.c,theentryofAESECB,CBCsamplecodeisAES_Sample()
z INT32RtmpPasswordHash(PSTRINGpassword,PUCHARssid,INT32ssid_lenPUCHARoutput);
Description:ThisfunctionisusedtocalculatethePMK
Parameters
[IN]:password ‐‐‐‐ ASCLLstringupto63charactersinlength
[IN]:ssid ‐‐‐‐ octectstringupto32octects
[IN]:ssid_len ‐‐‐‐ lengthofssidinoctects
[OUT]:output‐‐‐‐ mustbe40octectsinlengthand0~32octects(256bits)isthekey
Returnvalue:None
z VOID__romtextRT_MD5(constUINT8Message[],UINTMessageLen,UINT8DigestMessage[])
Description:MD5algorithm
Parameters
[IN]:message ‐‐‐‐ Messagecontext
[IN]:messageLen‐‐‐‐ Thelengthofmessageinbytes
[OUT]:digestMessage‐‐‐‐Digestmessage
ReturnValue:None
z VOID__romtextRT_MD5_Init(MD5_CTX_STRUC*pMD5_CTX)
Description:InitialMd5_CTX_STRUC
Parameters
[IN]:pMD5_CTXPointertoMd5_CTX_STRUC
Mediatek Confidential

ReturnValue:None
z VOID__romtextRT_MD5_Append(MD5_CTX_STRUC*pMD5_CTX,
constUINT8Message[],
UINTMessageLen)
Description:Themessageisappendedtoblock.Ifblocksize>64bytes,theMD5_Hashwillbecalled.
Parameters:
pMD5_CTXPointertoMD5_CTX_STRUC
MessageMessagecontext
MessageLenThelengthofmessageinbytes
ReturnValue:None
z VOID__romtextRT_MD5_End(MD5_CTX_STRUC*pMD5_CTX,UINT8DigestMessage[])
Description:
1.Appendbit1toendofthemessage
2.Appendthelengthofmessageinrightmost64bits
3.TransformtheHashValuetodigestmessage
Parameters
[IN]pMD5_CTXPointertoMD5_CTX_STRUC
[OUT]digestMessageDigestmessage
ReturnValue:None
13 TIMERAPIS
13.1 SWTimerAPIs.
z VOIDcnmTimerInitTimer(INP_TIMER_TprTimer,
INPFN_MGMT_TIMEOUT_FUNCpfFunc,
INUINT_32u4Data
INUINT_32u4Data2)
Description:Thisfunctionisusedtoinitializeatimer
Parameters
[IN]:prTimer ‐‐‐‐Pointertoatimerstructure
[IN]:pfFunc ‐‐‐‐Pointertothecallbackfunction
[IN]:u4Data ‐‐‐‐parameterforcallbackfunction
[IN]:u4Data2 ‐‐‐‐parameterforcallbackfunction
Returnvalue:None
z VOIDcnmTimerStartTimer(INP_TIMER_TprTimer,INUINT_32u4TimeoutMs)
Description:Thisfunctionisusedtostartatimer
Parameters
[IN]:prTimer ‐‐‐‐Pointertoatimerstructure
[IN]:u4TimeoutMs ‐‐‐‐Timeouttoissuethetimerandcallbackfunction(unit:ms)
Returnvalue:None
z VOIDcnmTimerStopTimer(INP_TIMER_TprTimer)
Description:Thisfunctionisusedtostopatimer
Mediatek Confidential

Parameters
[IN]:prTimer ‐‐‐‐Pointertoatimerstructure
Returnvalue:None
ThereisaexampleonIoT_customer.c
z UINT32GetMsTimer(VOID)
Description:Getthetimefromsystemstart(Unit:1ms)
Parameters
Returnvalue:thecountervalue
13.2 HWtimer1interruptfunction
TheFrequencyforhardwaretimer1interrupt,Range[1~10]
#defineTICK_HZ_HWTIMER110/*T=1/TICK_HZ_HWTIEMR1*/
Aboveexample:IoT_Cust_HW_Timer1_Hdlrwillbetriggeredevery100ms(ThatisT=1/10)
14 INTERFAEAPIS
14.1 FlashDriver
z voidspi_flash_erase_SE(uint32address)
Description:Thisfunctionisusedtoerasethesectorinwhichtheaddressspecifies.
Parameters
[IN]:addr‐‐‐‐theaddressinflashtobeerased
Returnvalue:None
z voidspi_flash_erase_BE(uint32address)
Description:Thisfunctionisusedtoerasetheblockinwhichtheaddressspecifies.
Parameters
[IN]:addr‐‐‐‐theaddressinflashtobeerased
Returnvalue:None
Note:
1.Duetothecharacteristicofflash,erasethesector/blockwheredataistobewrittenismandatorybeforewrite
anythingtoflash.
2.Thesizeofsector/blockofoneflashisdifferent.Pleasecheckthedatasheetofusingflash.
Mediatek Confidential

3.abovetwoAPIswilleraseasectororablock,pleaseconsideriftherearesomedatashouldnotbeerasedinone
sector/blockbeforeusingthosetwoAPIs
.
z int32spi_flash_read(uint32addr,uint8*data,uint16len)
Description:Thisfunctionisusedtoreadspecifieddatafromflash
Parameters
[IN]:addr‐‐‐‐Theoffsetwhichthereadingdatastoredontheflash
[IN]:len‐‐‐‐Thedatalengthneedtoread
[OUT]:data ‐‐‐‐Thepointerindicatethereadingdata
Returnvalue:0meanssuccessful,non‐zeromeansfail
z int32spi_flash_read_m2(uint32addr,uint8*data,uint16len)
Description:ThisfunctionisusedtoreadspecifieddatafromflashwithSPIcommandmethod
Thefunctionhasthesameeffectwithspi_flash_read()
z int32spi_flash_write_func(uint32addr,uint8*data,uint16len)
Description:Thisfunctionisusedtowritespecifieddatatoflash
Parameters
[IN]:addr‐‐‐‐Theoffsetwhichthedatawillbewriteontheflash
[IN]:len‐‐‐‐Thedatalengthneedtowrite
[IN]:data‐‐‐‐Thepointerindicatethewritingdata
Returnvalue:0meanssuccessful,non‐zeromeansfail
Notes:ThisAPIwillwritedatatoflashoffset“addr”directly,
Iftheflashsectorwhichthe“addr”belongstoisnotbeerasedfirst,ThisAPIwillwritedatatoflashunsuccessful
z int32spi_flash_write(uint32addr,uint8*data,uint16len)
Description:Thisfunctionisusedtowritespecifieddatatoflash
Parameters
[IN]:addr‐‐‐‐Theoffsetwhichthedatawillbewriteontheflash
[IN]:len‐‐‐‐Thedatalengthneedtowrite
[IN]:data‐‐‐‐Thepointerindicatethewritingdata
Returnvalue:0meanssuccessful,non‐zeromeansfail
Notes:AstheRAMlimitation,thelenmust<=FLASH_OFFESET_WRITE_BUF(4KB)
ThisAPIwilleraseSectorfirstthenÆstoreoriginaldataÆmergethemodifieddataÆwritebacktosector
Thus,1:ifyouwanttowritesomedatatoflash,pleasedonotcallspi_flash_erase_SE()orspi_flash_erase_BE()to
eraseflashagain,butjustcallspi_flash_write().
2:AsthisAPIwillerasesector,thus,needavoidcallingthisAPIwithHighFrequency
Mediatek Confidential

SPICommanddescription
14.2 UART
z INT32IoT_uart_input(UINT_8*msg,INT32count);
Description:Thisfunctionreadsagivenlengthofdatafromtheuartport.
Parameters
[IN]:msg ‐‐‐‐Pointertoauartrxbuffer
[OUT]:count‐‐‐‐ Lengthofdatatoread
ReturnValue:Returnzero.
Remark:None.
z INT32IoT_uart_output(UINT_8*msg,INT32count);
Description:Thisfunctionwritesagivenlengthofdatatotheuartport.
Parameters
[OUT]:msg ‐‐‐‐ Pointertoauarttxbuffer
[OUT]:count ‐‐‐‐ Lengthofdatatowrite
ReturnValue:Returnzero.
Mediatek Confidential

Remark:None.
14.3 LED/PWM
z INT32IoT_led_pwm(INT32led_num,INT32brightness);
Description:Thisfunctionconfiguresthebrightnessofaled.
Parameters
[OUT]:led_num ‐‐‐‐Inhardwarepwmmode,led_numisledcontrollernumber,range(1~3)..
[Ex:Led_num=1,usePin26asLed/PWM
Led_num=2,usepin31asLed/PWM
Led_num=3,usepin30asLed/PWM]
Insoftwarepwmmode,led_numisgpionumber,range(0~4).
[Ex:Led_num=0,usePin31asLed/PWM
Led_num=1,usepin30asLed/PWM
Led_num=2,usepin29asLed/PWM
Led_num=3,usepin28asLed/PWM
Led_num=4,usepin27asLed/PWM]
[OUT]:brightness ‐‐‐Brightnesslevelofled.
Inhardwarepwmmode,range(0~5)
Insoftwarepwmmode,range(0~20).
ReturnValue:Return‐1ifled_numisinvalid.Return0,otherwise.
Remark
1) Twopwmmodeissupported.
IfIOT_PWM_TYPE==1,hardwarepwmmodeisused.
IfIOT_PWM_TYPE==2(defaulttype),softwarepwmmodeisused.
2) Level0isoff.Level5isthebrightestinhardwarepwmmode.
Level0isoff.Level20isthebrightestinsoftwarepwmmode.
3) SoftwarepwmmodeconsumesmoreCPUresources.
However,ithashighfrequencyandmorebrightnesslevels.
4) InHardwarePWMmode,
ifyouwanttocancelPWMmodeforpin26,31,30andsetthemasGPIOmode
needcallIoT_gpio_output(5,0),IoT_gpio_output(0,0),IoT_gpio_output(1,0)
ThepinandGPIOrelationship,pleaserefertosection:“GPIO/PinModeSet”
z VOIDIoT_software_pwm_addset(INT32led_num,INT32brightness)
Description:Thisfunctionconfiguresagpiopintosoftwarepwmmodeandsetthebrightnesslevel.
ItabsolutesameasIoT_led_pwm()insoftPWMmode
Parameters
[OUT]:led_num ‐‐‐‐Specifythegpionumberwhichistobeconfiguredtosoftwarepwmmode.
Shouldberangedfrom0to4
[OUT]:brightness ‐‐‐Brightnesslevelofled.
AvailableonlyInsoftwarepwmmode,shouldberangedfrom0to20.
ReturnValue:Return‐1ifled_numisinvalid.Return0,otherwise.
Remark
1)ThisAPIisavailable.onlyifsoftwarepwmmodeisused
2)Level0isoff.Level20isthebrightestinsoftwarepwmmode.
Mediatek Confidential

z INT32IoT_software_pwm_del(INT32led_num)
Description:Thisfunctionchangesagpiopinfromsoftwarepwmmodebacktogpiomode
Parameters
[OUT]:led_num ‐‐‐‐Specifythegpionumberwhichistobechanged.Shouldberangedfrom0to4
ReturnValue:Return‐1ifled_numisinvalid.Return0,otherwise.
Remark
1)ThisAPIisavailable.onlyifsoftwarepwmmodeisused
14.4 GPIO
z INT32IoT_gpio_read(INT32gpio_num,UINT8*pVal,UINT8*pPolarity);
Description:ThisfunctionsettheGPIOasinputmode,andreadit’sinputvalue
Parameters
[IN]:gpio_num‐‐‐‐Specifythegpionumber.Shouldberangedfrom0to6.
[OUT]:pPolarity ‐‐‐‐readthegpiopolarity,0=OutputMode,1=InputMode
[OUT]:pVal ‐‐‐‐readthegpiostatus,0=low,1=High
ReturnValue:none
Remarks:
TheGPIO/PinModeSetpleaserefertosection:“GPIO/PinModeSet”
WecansetonespecificGPIO’smode/valueatonetimewithfollowingAPIs
z INT32IoT_gpio_input(INT32gpio_num,UINT32*input);
Description:ThisfunctionsettheGPIOasinputmode,andreadit’sinputvalue
Parameters
[IN]:gpio_num ‐‐‐‐Specifythegpionumber.Shouldberangedfrom0to6
[OUT]:input ‐‐‐‐theinputstatusofthegivengpionumber.0islow.1ishigh.
ReturnValue:Return‐1ifgpio_numisinvalid.
Return‐2ifinputisinvalid.
Returnzero,Otherwise.
Remarks:
TheGPIO/PinModeSetpleaserefertosection:“GPIO/PinModeSet”
z INT32IoT_gpio_output(INT32gpio_num,INT32output);
Description:Thisfunctionconfigurestheoutputstatusofagpio.
Parameters
[IN]:gpio_num ‐‐‐‐Specifythegpionumber.Shouldberangedfrom0to6
[OUT]:output ‐‐‐‐theoutputstatusofthegivengpionumber.0islow.1ishigh.
ReturnValues:Return‐1ifgpio_numisinvalid.Return‐2ifoutputisinvalid.Return0,otherwise.
Remarks:
TheGPIO/PinModeSetpleaserefertosection:“GPIO/PinModeSet”
WecansetseveralGPIOsmode/valueatonetimewithfollowingAPIs
z INT32IoT_gpio_batch_modify_mode(INT32output_bitmap);
Description:Thisfunctionconfiguresabatchofgpiopinstooutputmode
Parameters
Mediatek Confidential

[OUT]:output_bitmap ‐‐‐‐Specifythegpiooutputmodebitmap.
Bit(i)standsforgpio(i).Shouldberangedfrom00000Bto11111B
ReturnValues:Return0
Remarks:
1.TheGPIO/PinModeSetpleaserefertosection:“GPIO/PinModeSet”
2.Ifoutput_bitmapis10001B,gpio0andgpio4willbesettooutputmode
z INT32IoT_gpio_batch_modify_output_value(INT32output_bitmap,INT32value_bitmap);
Description:Thisfunctionconfiguresabatchofgpiopinstooutputhigh.
Parameters
[OUT]:output_bitmap‐‐‐‐Specifythegpiooutputmodebitmap.
Bit(i)standsforgpio(i).Shouldberangedfrom00000Bto11111B.
[OUT]:value_bitmap ‐‐‐‐Specifythegpiooutputstatusbitmap.
Bit(i)standsforgpio(i).Shouldberangedfrom00000Bto11111B.
ReturnValues:Return0
Remarks:
1.TheGPIO/PinModeSetpleaserefertosection:“GPIO/PinModeSet”
2.Thisfunctiondoesnotchangegpiopinstooutputmode.Itmodifiestheoutputvalueonly
3.Ifoutput_bitmapis10001B,andvalue_bitmapis10000B,
gpio0willbesettolow,andgpio4willbesettohigh
z UINT8IoT_Cust_Set_GPIINT_MODE(INUINT8GPIO_Num,INUINT8Val)
Description:SetGPIOinterruptmode
Parameters
[IN]:GPIO_Num‐‐‐‐[0~6].
[IN]:Val‐‐‐‐[0~4]
0:notrigger,1:fallingedgetrigger
2:risingedgetrigger3:bothfallingadnrisingedgetrigger
ReturnValues:0‐Success,1‐invalidinput
z UINT8IoT_Cust_Get_GPIINT_MODE(OUTUINT16*pGPI_INT_MODE)
Description:SetGPIOinterruptmode
Mediatek Confidential

Parameters
[OUT]:GPI_STS
[1:0]:GPIO1Interruptmode
[3:2]:GPIO0Interruptmode
[5:4]:GPIO2Interruptmode
[7:6]:GPIO3Interruptmode
[9:8]:GPIO4Interruptmode
[11:10]:GPIO5Interruptmode
[13:12]:GPIO6Interruptmode
ForeachGPIO'sinterruptmode
0:notrigger,1:fallingedgetrigger
2:risingedgetrigger3:bothfallingadnrisingedgetrigger
ReturnValues:None
z VOIDIoT_Cust_GPIINT_Hdlr(INUINT8GPI_STS);
Description:ThisHandlershallbecalledasanyGPIOInterrputbetriggered
Parameters
[IN]:GPIO_Num‐‐‐‐[0~6].GPIO0~6Interruptstatus
ReturnValues:0‐Success,1‐invalidinput
14.5 GPIO/PinModeSet
Current,WeuseIOT_PWM_TYPE=2,TheGPIOlistasbelow:
IOT_PWM_TYPE
CHIPPin01
(HWPWMMode)
2
(SWPWMMode)
Pin31GPIO0PWM2GPIO0/PWM1
Pin30GPIO1PWM3GPIO1/PWM2
Pin29GPIO2GPIO2GPIO2/PWM3
Pin28GPIO3GPIO3GPIO3/PWM4
Pin27 GPIO4GPIO4GPIO4/PWM5
Pin26 UartTxPWM1/UartTx UartTx
Pin25 UartRxUartRxUartRx
Remark PWM:20Hz,Level(0~5)
Level0=off
Level5=brightest
PWM:50Hz,Level(0~20)
Level0=off
Level20=brightest
Mediatek Confidential

15 FLASHPARTITIONS
Mediatek Confidential

Mediatek Confidential

Note:1.AsthelimitationofRAMsize,whiledoflashread/writeatatime,
only256BofdatacanbereadfromFLASHtoRAM,(useIoTpAd.flash_rw_buf[256])
Thenrewritethedatatocorrespondingplaceafterbeingmodified.
16 COMPILERSETUP
PleaserefertodescriptionontheAndesweb
http://forum.andestech.com/viewtopic.php?f=23&t=576&p=672
http://forum.andestech.com/viewtopic.php?f=23&t=587
Mediatek Confidential

17 ATCOMMANDUSAGE
17.1 Displayversion
Command:Ver
ArgumentDescriptions:None
Example:AT#Ver+enter
17.2 Rebootthesystem
Command:Reboot
ArgumentDescriptions:None
Example:AT#Reboot+enter
17.3 SetDefault
Command:Default
ArgumentDescriptions:‐s<channelnumber>
Example:AT#Default+enter
17.4 Switchchannel
Command:Channel
ArgumentDescriptions:‐b<Bandwidth>(0forBW_20,1forBW_40)
‐c<channelnumber>(1~14)
Example:AT#Channel‐b0‐c6+enter
Remarks:whenset1to‐b,the‐cmeanscentralchannelforBW40
17.5 ConfigureUARTinterface
Command:Uart
ArgumentDescriptions:
‐b<baudrate>(57600,115200,230400,…)
‐w<databits>(5,6,7,8)
‐p<parity>(0fornoparity,1forodd,2foreven)
‐s<stopbits>(1for1bit,2for2bits,3for1.5bits)
Example:AT#Uart‐b57600‐w7‐p1‐s1+enter
Remarks:dlr=round(systemclock/(16*baudrate),0)
actualbaudrate=systemclock/(16*dlr)
Youcanfindmoresupportedbaudrateforyoursystemaccordingtheformulaandexperiment
17.6 UpdateFirmwarefromUart
Command:UpdateFW
ArgumentDescriptions:‐t<flashareatype>
Example:AT#UpdateFW+enter
Remarks:shouldbeenabledonRecoverymode,X‐modemshallbestartupafterimplementthiscommand
17.7 EnterintoSmartConnectionState
Command:Smnt
ArgumentDescriptions:
Mediatek Confidential

Example:AT#Smnt+enter
Remarks:whenthiscmdbeinputto7681,7681needchangestatemachinetoSmntstate,andstarttolisten
packetintheairtodosmartconnection
17.8 EnterintoDeepsleepmode
Command:PowerSaving
ArgumentDescriptions:
‐l<PowerSavingLevel>(1~5)
‐t<PowerSleepTime>(0~0xFFFFFF(unit::us))
‐r<readPowerSavingLevel>
Example:AT#PowerSaving‐l1‐t0xFFFFFF+enter
AT#PowerSaving‐r<Space>+enter
Remarks:7681willgotosleepwhengetcmd”AT#PowerSaving‐l1‐t0xFFFFFF”,andawakeafter0xFFFFFF(us)
(ThePowerSavingmodeisalsoinimproving,soturnthisCmdoffbydefaulttemporary,ifcustomerwanttotest
powersavinginpresent,theycanturnthisCmdoninMT7681_sta.mk)
Mediatek Confidential