Cc2540 usb dongle прошивка
The CC2540 USB Evaluation Module Kit contains one CC2540 Bluetooth low energy USB Dongle. The dongle can be used to enable Bluetooth low energy on your PC. It can also be used as a packet sniffer for analyzing the BLE protocol and for software and system level debugging (use the free tool SmartRF Packet Sniffer). The dongle comes preprogrammed as a packet sniffer.
To program and debug software running on the dongle, you need the CC Debugger (not included in the kit).
Features
- 1 x CC2540 USB Dongle
- Quick Start Guide
Bluetooth products
CC2540 — Bluetooth® Low Energy wireless MCU with USB CC2540T — Extended industrial temperature Bluetooth® Low Energy (LE) wireless MCU
Order & start development
CC2540EMK-USB — CC2540 USB Dongle
SMARTRFTM-STUDIO — SmartRF Studio
Supported products & hardware
Products
Bluetooth products
MSP430 microcontrollers
CC430F6127 — 20 MHz MCU with 32KB Flash, 4KB SRAM, Sub-1 GHz radio, AES-128, I2C/SPI/UART, 96 seg LCD ; CC430F6135 — 20 MHz MCU with 16KB Flash, 2KB SRAM, Sub-1 GHz radio, AES-128, 12-bit ADC, I2C/SPI/UART, 96 seg LCD CC430F6147 — 20 MHz MCU with 32KB Flash, 4KB SRAM, Sub-1 GHz radio, AES-128, 10-bit ADC, I2C/SPI/UART, 96 seg LCD
Sub-1 GHz products
CC1020 — Single-chip FSK/OOK CMOS wireless transceiver for Narrowband apps in 402-470 and 804-940 MHz range CC1021 — Multichannel FSK/OOK CMOS wireless transceiver for Narrowband app w/Ch Spacings of 50 kHz or Higher CC1070 — Single-chip, Low-Power, Low-Cost CMOS FSK/GFSK/ASK/00K RF Transmitter for Narrowband & Multi-Ch apps CC1100 — Highly Integrated MultiCh RF transceiver Designed for Low-Power Wireless apps CC1100E — Low-power Sub-1GHz wireless transceiver for China and Japan frequency bands CC1101 — Low-power Sub-1 GHz wireless transceiver CC110L — Value line Sub-1 GHz wireless transceiver CC1110-CC1111 — Sub-1 GHz wireless MCU with up to 32 kB Flash memory CC1120 — High performance Sub-1 GHz wireless transceiver for narrowband systems CC1121 — High performance low power Sub-1 GHz wireless transceiver CC1125 — Ultra-high performance Sub-1 GHz wireless transceiver for narrowband systems CC113L — Value line Sub-1 GHz wireless receiver CC1150 — Highly integrated multichannel wireless transmitter designed for low-power wireless applications CC115L — Value line Sub-1 GHz wireless transmitter CC1175 — High performance wireless transmitter for narrowband systems CC1201 — Low power and high performance wireless transceiver CC1310 — SimpleLink™ 32-bit Arm Cortex-M3 Sub-1 GHz wireless MCU with 128kB Flash CC1311R3 — SimpleLink™ Arm® Cortex®-M4 Sub-1 GHz wireless MCU with 352-kB flash CC1312R7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol Sub-1 GHz wireless MCU with 704-kB Flash CC430F5123 — 16-bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 8kB Flash and 2kB RAM CC430F5125 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 16kB Flash and 2kB RAM CC430F5133 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 12-Bit ADC, 8kB Flash and 2kB RAM CC430F5137 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 12-Bit ADC, 32kB Flash and 4kB RAM CC430F5143 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 10-bit ADC, 8kB Flash and 2kB RAM CC430F5145 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 10-bit ADC, 16kB Flash and 2kB RAM CC430F5147 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 10-bit ADC, 32kB Flash and 4kB RAM
Wi-SUN products
CC1200 — Low power and high performance wireless transceiver CC1312R — SimpleLink™ 32-bit Arm Cortex-M4F Sub-1 GHz wireless MCU with 352kB Flash
Thread products
CC2538 — 32-bit Arm Cortex-M3 Zigbee, 6LoWPAN, and IEEE 802.15.4 wireless MCU with 512kB Flash and 32kB RAM
Zigbee products
CC2430 — System-on-Chip Solution for 2.4 GHz IEEE 802.15.4 / ZigBee™ CC2431 — System-on-Chip (SoC) Solution for ZigBee/IEEE 802.15.4 Wireless Sensor Network CC2520 — Second generation 2.4 GHz ZigBee/IEEE 802.15.4 wireless transceiver CC2530 — Zigbee and IEEE 802.15.4 wireless MCU with 256kB Flash and 8kB RAM CC2531 — Zigbee and IEEE 802.15.4 wireless MCU with up to 256kB Flash and 8kB RAM CC2533 — A True System-on-Chip Solution for 2.4-GHz IEEE 802.15.4 and ZigBee Applications CC2630 — SimpleLink™ 32-bit Arm Cortex-M3 Zigbee and 6LoWPAN wireless MCU with 128kB Flash
Multi-protocol products
CC1350 — SimpleLink™ 32-bit Arm Cortex-M3 multiprotocol Sub-1 GHz & 2.4 GHz wireless MCU with 128kB Flash CC1352P — SimpleLink™ Arm Cortex-M4F multiprotocol Sub-1 GHz & 2.4 GHz wireless MCU integrated power amplifier CC1352P7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol sub-1 GHz and 2.4-GHz wireless MCU integrated power amp CC1352R — SimpleLink™ 32-bit Arm Cortex-M4F multiprotocol Sub-1 GHz & 2.4 GHz wireless MCU with 352kB Flash CC2651R3 — SimpleLink™ 32-bit Arm® Cortex®-M4 single-protocol 2.4-GHz wireless MCU w CC2652P — SimpleLink™ Arm Cortex-M4F multiprotocol 2.4 GHz wireless MCU with integrated power amplifier CC2652P7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol 2.4-GHz wireless MCU, 704-kB Flash, integrated power amp CC2652R — SimpleLink™ 32-bit Arm Cortex-M4F multiprotocol 2.4 GHz wireless MCU with 352kB Flash CC2652R7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol 2.4-GHz wireless MCU with 704-kB Flash CC2652RSIP — SimpleLink™ multiprotocol 2.4-GHz wireless system-in-package module with 352-KB memory
Other wireless technologies
CC2420 — Single-Chip 2.4 GHz IEEE 802.15.4 Compliant and ZigBee™ Ready RF Transceiver CC2500 — Low Cost, Low-Power 2.4 GHz RF Transceiver Designed for Low-Power Wireless Apps in the 2.4 GHz ISM B CC2510 — 2.4 GHz Radio Transceiver, 8051 MCU, and 16KB or 32 KB Memory CC2510F8 — 2.4 GHz Radio Transceiver, 8051 MCU and 8 kB Flash memory CC2511 — 2.4 GHz Radio Transceiver, 8051 MCU, 16KB or 32KB Flash memory and full-speed USB interface CC2511F8 — 2.4 GHz Radio Transceiver, 8051 MCU, 8 kB Flash memory and full-speed USB interface CC2530-RF4CE — Zigbee, IEEE 802.15.4 and RF4CE wireless MCU with 256kB Flash and 8kB RAM CC2531-RF4CE — Zigbee, IEEE 802.15.4 and RF4CE wireless MCU with up to 256kB Flash and 8kB RAM CC2543 — 2.4 GHz RF Value Line SoC with 32kB flash, 16 GPIO, I2C, SPI and UART CC2544 — 2.4 GHz RF Value Line SoC with 32kB flash, USB, SPI and UART CC2545 — 2.4 GHz RF Value Line SoC with 32kB flash, 31 GPIO, I2C, SPI and UART CC2550 — Low Cost 2.4 GHz Transmitter Designed for Low-Power Wireless Applications in 2.4 GHz ISM Band CC2620 — SimpleLink™ 32-bit Arm Cortex-M3 Zigbee® RF4CE wireless MCU with 128kB Flash
Hardware development
SMARTRFTM-STUDIO — SmartRF Studio
Zip file with Windows Installer and SW Manifest
Products
Bluetooth products
MSP430 microcontrollers
CC430F6127 — 20 MHz MCU with 32KB Flash, 4KB SRAM, Sub-1 GHz radio, AES-128, I2C/SPI/UART, 96 seg LCD ; CC430F6135 — 20 MHz MCU with 16KB Flash, 2KB SRAM, Sub-1 GHz radio, AES-128, 12-bit ADC, I2C/SPI/UART, 96 seg LCD CC430F6147 — 20 MHz MCU with 32KB Flash, 4KB SRAM, Sub-1 GHz radio, AES-128, 10-bit ADC, I2C/SPI/UART, 96 seg LCD
Sub-1 GHz products
CC1020 — Single-chip FSK/OOK CMOS wireless transceiver for Narrowband apps in 402-470 and 804-940 MHz range CC1021 — Multichannel FSK/OOK CMOS wireless transceiver for Narrowband app w/Ch Spacings of 50 kHz or Higher CC1070 — Single-chip, Low-Power, Low-Cost CMOS FSK/GFSK/ASK/00K RF Transmitter for Narrowband & Multi-Ch apps CC1100 — Highly Integrated MultiCh RF transceiver Designed for Low-Power Wireless apps CC1100E — Low-power Sub-1GHz wireless transceiver for China and Japan frequency bands CC1101 — Low-power Sub-1 GHz wireless transceiver CC110L — Value line Sub-1 GHz wireless transceiver CC1110-CC1111 — Sub-1 GHz wireless MCU with up to 32 kB Flash memory CC1120 — High performance Sub-1 GHz wireless transceiver for narrowband systems CC1121 — High performance low power Sub-1 GHz wireless transceiver CC1125 — Ultra-high performance Sub-1 GHz wireless transceiver for narrowband systems CC113L — Value line Sub-1 GHz wireless receiver CC1150 — Highly integrated multichannel wireless transmitter designed for low-power wireless applications CC115L — Value line Sub-1 GHz wireless transmitter CC1175 — High performance wireless transmitter for narrowband systems CC1201 — Low power and high performance wireless transceiver CC1310 — SimpleLink™ 32-bit Arm Cortex-M3 Sub-1 GHz wireless MCU with 128kB Flash CC1311R3 — SimpleLink™ Arm® Cortex®-M4 Sub-1 GHz wireless MCU with 352-kB flash CC1312R7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol Sub-1 GHz wireless MCU with 704-kB Flash CC430F5123 — 16-bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 8kB Flash and 2kB RAM CC430F5125 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 16kB Flash and 2kB RAM CC430F5133 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 12-Bit ADC, 8kB Flash and 2kB RAM CC430F5137 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 12-Bit ADC, 32kB Flash and 4kB RAM CC430F5143 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 10-bit ADC, 8kB Flash and 2kB RAM CC430F5145 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 10-bit ADC, 16kB Flash and 2kB RAM CC430F5147 — 16-Bit ultra-low-power CC430 Sub 1 GHz wireless MCU with 10-bit ADC, 32kB Flash and 4kB RAM
Wi-SUN products
CC1200 — Low power and high performance wireless transceiver CC1312R — SimpleLink™ 32-bit Arm Cortex-M4F Sub-1 GHz wireless MCU with 352kB Flash
Thread products
CC2538 — 32-bit Arm Cortex-M3 Zigbee, 6LoWPAN, and IEEE 802.15.4 wireless MCU with 512kB Flash and 32kB RAM
Zigbee products
CC2430 — System-on-Chip Solution for 2.4 GHz IEEE 802.15.4 / ZigBee™ CC2431 — System-on-Chip (SoC) Solution for ZigBee/IEEE 802.15.4 Wireless Sensor Network CC2520 — Second generation 2.4 GHz ZigBee/IEEE 802.15.4 wireless transceiver CC2530 — Zigbee and IEEE 802.15.4 wireless MCU with 256kB Flash and 8kB RAM CC2531 — Zigbee and IEEE 802.15.4 wireless MCU with up to 256kB Flash and 8kB RAM CC2533 — A True System-on-Chip Solution for 2.4-GHz IEEE 802.15.4 and ZigBee Applications CC2630 — SimpleLink™ 32-bit Arm Cortex-M3 Zigbee and 6LoWPAN wireless MCU with 128kB Flash
Multi-protocol products
CC1350 — SimpleLink™ 32-bit Arm Cortex-M3 multiprotocol Sub-1 GHz & 2.4 GHz wireless MCU with 128kB Flash CC1352P — SimpleLink™ Arm Cortex-M4F multiprotocol Sub-1 GHz & 2.4 GHz wireless MCU integrated power amplifier CC1352P7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol sub-1 GHz and 2.4-GHz wireless MCU integrated power amp CC1352R — SimpleLink™ 32-bit Arm Cortex-M4F multiprotocol Sub-1 GHz & 2.4 GHz wireless MCU with 352kB Flash CC2651R3 — SimpleLink™ 32-bit Arm® Cortex®-M4 single-protocol 2.4-GHz wireless MCU w CC2652P — SimpleLink™ Arm Cortex-M4F multiprotocol 2.4 GHz wireless MCU with integrated power amplifier CC2652P7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol 2.4-GHz wireless MCU, 704-kB Flash, integrated power amp CC2652R — SimpleLink™ 32-bit Arm Cortex-M4F multiprotocol 2.4 GHz wireless MCU with 352kB Flash CC2652R7 — SimpleLink™ Arm® Cortex®-M4F multiprotocol 2.4-GHz wireless MCU with 704-kB Flash CC2652RSIP — SimpleLink™ multiprotocol 2.4-GHz wireless system-in-package module with 352-KB memory
Other wireless technologies
CC2420 — Single-Chip 2.4 GHz IEEE 802.15.4 Compliant and ZigBee™ Ready RF Transceiver CC2500 — Low Cost, Low-Power 2.4 GHz RF Transceiver Designed for Low-Power Wireless Apps in the 2.4 GHz ISM B CC2510 — 2.4 GHz Radio Transceiver, 8051 MCU, and 16KB or 32 KB Memory CC2510F8 — 2.4 GHz Radio Transceiver, 8051 MCU and 8 kB Flash memory CC2511 — 2.4 GHz Radio Transceiver, 8051 MCU, 16KB or 32KB Flash memory and full-speed USB interface CC2511F8 — 2.4 GHz Radio Transceiver, 8051 MCU, 8 kB Flash memory and full-speed USB interface CC2530-RF4CE — Zigbee, IEEE 802.15.4 and RF4CE wireless MCU with 256kB Flash and 8kB RAM CC2531-RF4CE — Zigbee, IEEE 802.15.4 and RF4CE wireless MCU with up to 256kB Flash and 8kB RAM CC2543 — 2.4 GHz RF Value Line SoC with 32kB flash, 16 GPIO, I2C, SPI and UART CC2544 — 2.4 GHz RF Value Line SoC with 32kB flash, USB, SPI and UART CC2545 — 2.4 GHz RF Value Line SoC with 32kB flash, 31 GPIO, I2C, SPI and UART CC2550 — Low Cost 2.4 GHz Transmitter Designed for Low-Power Wireless Applications in 2.4 GHz ISM Band CC2620 — SimpleLink™ 32-bit Arm Cortex-M3 Zigbee® RF4CE wireless MCU with 128kB Flash
Hardware development
- $2.65 CC2540 module (RF-BM-S02) from Aliexpress (11.2 x 15.1 x 1.74 mm, onboard USB support)
- $1.83 Arduino Nano from Aliexpress (to program the chip)
- $0.92 Panasonic CR1216 lithium 3v battery (12.5 × 1.6 mm), 34 mAh
- $0.00 Cherry MX Blue keychain (20 x 11 mm) from GeekKeys (actually $3.50 but I got it for free)
Build or download precompiled firmware from the repository (HIDEmuKbd.hex), use CCLoader and Arduino Nano to flash it.
Build and upload CCLoader sketch (CCLoader.ino) to Arduino Nano using Arduino IDE.
Hook up CC2540 to Arduino Nano digital pins D4-D6 as shown in the table (don't forget about 3.3V VCC and GND):
Signal | CC254x | CCLoader |
---|---|---|
DEBUG_CLOCK | P2_1 | D6 |
DEBUG_DATA | P2_2 | D5 |
RESET | RES | D4 |
Convert firmware.hex to firmware.bin using hex to bin converter.
Run CCLoader client on PC. E.g. for COM6 and Arduino Nano (Device 0) use:
CCLoader.exe 6 firmware.bin 0
That's it, the cc2540 module should accept the new firmware and start working right away (after bluetooth pairing).
The keyboard button is attached to P0_1 (P01) and GND pins. It sends WinKey keycode, you may modify the code to send any key or a key sequence of your choice. The battery (3V) is attached to VCC and GND pins.
This keyboard uses modified HIDEmuKbd sample from the CC2540 SDK.
Copy provided files to the corresponding BLE-CC254x-1.4.0 SDK folders.
Run IAR, open .eww, hit Make. You may also try precompiled firmware from the repository.
- Error[e16]: Segment ISTACK (size: 0xc0 align: 0) is too long for segment definition. At least 0xe more bytes needed. The problem occurred while processing the segment
You got to set number of virtual registers to 8 (in Project - Options - General Options).
Experimental USB mode
This section is pure experimental and it's not related to the keyboard above, you may skip it.
As you know, CC2540 supports USB (CC2541 doesn't), and can be used as USB-HID, USB Serial or USB Mass Storage Device.
- HIDAdvRemoteDongle sample for the USB HID device.
- HostTestApp sample for the BTool-compatible serial device.
- util/UBL sample for the USB Mass Storage device
To run USB firmware and to detect USB on this module, U+ needs to be pulled to +3.3v via 1.5k resistor.
Sadly, USB Mass Storage doesn't work (yet) on this RF-BM-S02 module. It sometimes shows removable drive and even shows DEFAULT.CFG file but never opens it. Not sure if it is software or hardware problem (looks like it opens slightly faster on a low speed USB 2.0). The module uses CC254XF256 so memory should be enough. Probably software problem, because USB HID works just fine.
Official SDK Hardware
You don't really need official CC2540 SDK hardware (Keyfob and USB Dongle) but you could need schematics and defines.
CC2540 buttons and LEDs for Keyfob and Dongle development kits (defined in hal_board_cfg.h):
- $2.65 CC2540 module (RF-BM-S02) from Aliexpress (11.2 x 15.1 x 1.74 mm, onboard USB support)
- $1.83 Arduino Nano from Aliexpress (to program the chip)
- $0.92 Panasonic CR1216 lithium 3v battery (12.5 × 1.6 mm), 34 mAh
- $0.00 Cherry MX Blue keychain (20 x 11 mm) from GeekKeys (actually $3.50 but I got it for free)
Build or download precompiled firmware from the repository (HIDEmuKbd.hex), use CCLoader and Arduino Nano to flash it.
Build and upload CCLoader sketch (CCLoader.ino) to Arduino Nano using Arduino IDE.
Hook up CC2540 to Arduino Nano digital pins D4-D6 as shown in the table (don't forget about 3.3V VCC and GND):
Signal | CC254x | CCLoader | RF-BM-S02 |
---|---|---|---|
DEBUG_CLOCK | P2_1 | D6 | P21 |
DEBUG_DATA | P2_2 | D5 | P22 |
RESET | RES | D4 | RES |
Convert firmware.hex to firmware.bin using hex to bin converter.
Run CCLoader client on PC. E.g. for COM6 and Arduino Nano (Device 0) use:
CCLoader.exe 6 firmware.bin 0
That's it, the cc2540 module should accept the new firmware and start working right away (after bluetooth pairing).
The keyboard button is attached to P0_1 (P01) and GND pins. It sends WinKey keycode, you may modify the code to send any key or a key sequence of your choice. The battery (3V) is attached to VCC and GND pins.
Arduino Nano as CCLoader
This keyboard uses modified HIDEmuKbd sample from the CC2540 SDK.
Copy provided files to the corresponding BLE-CC254x-1.4.0 SDK folders.
Run IAR, open .eww, hit Make. You may also try precompiled firmware from the repository.
- Error[e16]: Segment ISTACK (size: 0xc0 align: 0) is too long for segment definition. At least 0xe more bytes needed. The problem occurred while processing the segment
You got to set number of virtual registers to 8 (in Project - Options - General Options).
Expiremental USB mode
This section is pure expiremental and it's not related to the keyboard above, you may skip it.
As you know, CC2540 supports USB (CC2541 doesn't), and can be used as USB-HID, USB Serial or USB Mass Storage Device.
- HIDAdvRemoteDongle sample for the USB HID device.
- HostTestApp sample for the BTool-compatible serial device.
- util/UBL sample for the USB Mass Storage device
To run USB firmware and to detect USB on this module, U+ needs to be pulled to +3.3v via 1.5k resistor.
Sadly, USB Mass Storage doesn't work (yet) on this RF-BM-S02 module. It sometimes shows removable drive and even shows DEFAULT.CFG file but never opens it. Not sure if it is software or hardware problem (looks like it opens slightly faster on a low speed USB 2.0). The module uses CC254XF256 so memory should be enough. Probably software problem, because USB HID works just fine.
Breadboard rig with attached USB
Official SDK Hardware
You don't really need official CC2540 SDK hardware (Keyfob and USB Dongle) but you could need schematics and defines.
CC2540 buttons and LEDs for Keyfob and Dongle development kits (defined in hal_board_cfg.h):
Biscuit is an open source firmware for TI CC2540 SoC (designed for Bluetooh 4.0 Low Energy applications).
This source code is designed and tested on BLE Mini hardware platform but it can be run on other CC2540 platforms with some modifications.
Note: USB upgrade can be done on Windows PC only (XP and up to 8.0, but except 8.1), also not Mac OSX nor Linux.
- CC2540 hardware (e.g. BLE Mini).
- To compile the Biscuit source code, obtain a copy of IAR Embedded Workbench for 8051 version 8.10 or latest. Refer to TI CC254x development resources.
- TI CC254x SDK version 1.4.
- UBL version 1.3 - We make use of the new USB bootloader so UBL 1.3 code is required.
- Besides using the bootloader, if you want to program/debug the firmware with hardware (e.g. BLE Mini), you need a CC Debugger.
- Biscuit-UART, it relays TX/RX data to/from Central device via BLE and forwards data to UART, so that you can connect to external MCU for processing.
Make sure you know how to do before trying to compile and load the firmware because incorrect configuration can cause the pre-loaded bootloader fails to function.
For details, see current\readme.txt or wiki,
The charateristic, UUID: 0x713D0004-503E-4C75-BA94-3148F18D941E can be used for changing the baudrate. You can use LightBlue or BLExplr Apps available on iOS or B-BLE on Android to change it.
To change the baudrate, write a byte 0x00 (9600bps), 0x01 (19200bps), 0x02 (38400bps), 0x03 (57600bps) or 0x04 (115200bps) to the characteristic.
Upgrade Firmware via USB Bootloader - TI's reference design or BLE Mini have a button connected to P1_2 pin is for triggering the USB upgrade mode. Press and hold the button, connect to a Windows PC, it will show a Mass Storage Drive, you can delete the old firmware and drag the new firmware to it.
USB Boot Loader - USB boot loader which is different from typical implementation, please refer to TI's document "Universal Boot Loader for SOC-8051 by USB-MSD Developer's Guide.pdf" and their sample project "HostTestApp" in their latest BLE SDK v1.3
Copyright (c) 2013 RedBearLab
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
После написания предыдущего материала про BLE розетку я познакомился со многими
людьми, которыми интересна тема использования BLE в собственных разработках, но есть определенные
сложности в использовании С-программирования с BLE стеком для СС2541. Использование
внутреннего контроллера дает много преимуществ, в частности: прошивка по воздуху, экономия
на внешнем контроллере, сокращение числа точек пайки…
Я решил разбить материал на две части. Первая – это подготовка к работе, программирование и
отладка. Вторая – создание собственного BLE профиля.
1. Подготовка к работе.
Для разработки приложений для СС2541 маст-хэв-набор это:
— CC-debugger – внутрисхемный отладчик для 8051 чипов TI;
— CC2450 USB dongle — для того чтобы быстро и просто проверять характеристики BLE профилей на
экране компьютера;
— ну и собственно какая-нибудь плата с чипом СС2541.
Идеально эти вещи сочетаются в отладочном наборе от TI – CC2541 mini DK. Рекомендую к приобретению.
Из софта нам понадобится:
Без лишних описаний, пройдемся по папкам стека, которые так или иначе потребуются для
работы.
— accessorize – содержит отладочную утилиту BTool, драйверы USB донгла и откомпилированные
образы готовых устройств;
— components – библиотеки (ОС, периферия и BLE);
— documents – папка создает видимость документации на все компоненты и модули;
— projects – примеры проектов.
2. IAR IDE, отладка программ.
Откроем к примеру проект SimpleBLEPerepherial. Пробуем скомпилировать… И я даю 7 из 10, что
проект не соберется. Ошибка происходит из-за того, что линковщик не может уместить в памяти
заданное количество виртуальных регистров. Вариантов решения проблемы два:
Подключив отладочную плату к CC-debugger, запустим приложение на ней (Project- Download and
Debug, Debug — Go).
Теперь при нажатии на правую кнопку брелок переходит в режим Advertising, то есть к нему
можно подключиться. Воткнем в USB донгл на базе СС2540. У нас есть два монитора для работы
с этим донглом: удобный BLE device monitor и хардкорный BTool (установочник последнего – в
комплекте со стеком). Воспользуемся BLE Device monitor.
Кроме того, из этого скрина важно почерпнуть, что пользовательская переменная для чтения
или записи определяется тремя записями в таблице устройства (определение характеристики,
значение характеристики, описание характеристики – первое и второе поля обязательны, объявление третьего- правило хорошего тона), а
переменная, которая, изменяясь, уведомляет приложение, помимо этого должна иметь
дополнительную характеристику-конфигуратор, включающую или отключающую уведомление.
Для отладки крайне полезна также утилита Packet Sniffer. Не буду рассказывать подробно,
только скажу, что для работы со снифером пакетов потребуется перепрошить USB донгл прошивкой
sniffer_fw_cc2540_usb.hex, лежащей где-то в недрах папки установки снифера (кстати, я искренне надеюсь, что вам не придется отлаживать приложения на столь низком уровне).
Так выглядят посылки iBeacon в снифере эфира:
3. Механизм функционирования периферийного BLE устройства
Дальше важно обратить внимание на кэлбэк, вызываемый стеком, определяющий параметры
соединения, – peripheralStateNotificationCB. Функция всегда позволяет понимать, установлено ли
соединение с центральным устройством или же нет.
Любые действия (управление выводами, чтение показателей датчиков, и т.д.) настоятельно
рекомендую выполнять в периодической задаче. Для этого понадобится функция из библиотеки
OSAL — osal_start_timerEx(), которой помимо идентификатора пользовательской задачи нужно
передать время, через которое произойдет системное прерывание, и битовую маску события,
которое при возникновении обрабатывается в кэлбэке SimpleBLEPeripheral_ProcessEvent().
4. Поддержка OAD
Теперь рассмотрим функцию OAD – обновление прошивки по воздуху. Сразу отмечу, что
такая функция доступна только в чипах с памятью 256 кБ. Максимально подробно механизм
создания приложений для OAD описан в документе, однако пару моментов прояснить стоит. Во-первых, память на чипе
выделяется для двух образов программы: текущей (исполняемой) и области для программы,
принимаемой по воздуху. Во-вторых, на чип должен быть установлен бутлоадер – загрузчик,
который при старте устройства будет выбирать, какой из образов нужно запустить.
Попробуем создать приложение с возможностью обновления прошивки по воздуху. Первым
делом прошьем чип прошивкой бутлоадера. Для этого скомпилируем проект BIM, находящийся
в папке \Projects\ble\util\BIM, и загрузим в контроллер получившийся образ посредством
Smart RF Flash Programmer (действие Erase, Programm and Verify). Дальше соберем образ, с
которым наше устройство будет стартовать: соберем проект SimpleBLEPerepherial в конфигурации
СС2541-OAD-ImgA (кстати, файл разметки памяти, который мы поправили в самом начале,
в этой сборке изменен, так что придется внести аналогичные изменения еще и в файл
cc254x_f256_imgA.xcl). Дошьем этот образ через Smart RF Flash Programmer (действие Append and
Verify), на этом шаге самое важное – не стереть предпрошитый бутлоадер. Теперь, перезагрузив
чип и подключившись к нему через BLE device monitor, увидим поддержку OAD.
Теперь скомпилируем образ для загрузки по воздуху и загрузим его на чип. Для начала
скомпилируем конфигурацию СС2541-OAD-ImgB. Далее в BLE Device Monitor перейдем во
вкладку File-programm. Убедимся, что чип работает на образе «А», выберем .bin файл в папке
выходных файлов конфигурации «ImgB» и обновим прошивку.
Презагрузим чип, переподключимся и убедимся, что чип работает с образом «B».
Стало быть, прошивка была обновлена и запущена новая версия. Теперь можно выделить для одного из секторов больший объем памяти, но это уже совершенно другая история…
На этом про стек все. В следующей части создадим свой пользовательский BLE профиль. Надеюсь, что для старта работы с СС2541 статья будет полезна.
Читайте также: