Compare commits

...

110 Commits

Author SHA1 Message Date
Ayke van Laethem 7a3a92ffdb Implement enough wrappers to start the WiFi task 2021-09-29 02:24:28 +02:00
Dmitriy Zakharkin 9ae6050feb added more stubs 2021-09-29 01:32:54 +02:00
Ayke van Laethem 5a956deb4b Implement _task_get_current_task 2021-09-28 00:53:24 +02:00
Ayke van Laethem b74b250db5 Stub out spinlocks 2021-09-27 16:57:13 +02:00
Ayke van Laethem ab4d01654b Implement memory allocation 2021-09-27 16:39:04 +02:00
Ayke van Laethem 1a32b5be12 Implement locking using FreeRTOS compatibility layer from TinyGo 2021-09-27 16:23:52 +02:00
Ayke van Laethem 0f0fdf894c Use tabs instead of spaces. 2021-09-27 14:24:00 +02:00
Dmitriy 348b7724a3 comment and print mutex value 2021-09-26 22:51:19 -04:00
Dmitriy d5ade3299f added all function for g_wifi_osi_funcs 2021-09-26 22:46:35 -04:00
Ayke van Laethem 5d914b5e34 WIP add more stub functions to figure out which functions are called 2021-09-27 02:51:43 +02:00
Ayke van Laethem f8dd441827 espnet: WIP support for on-chip WiFi on an ESP32C3
Work in progress. Does not work yet.

Some notes:

  - This requires some changes to TinyGo, look at the espnet branch.
  - The  next step is probably defining all the functions in
    g_wifi_osi_funcs (see espnet.c). Right now it hangs in
    esp_wifi_init_internal, probably a NULL pointer dereference.
  - This is only for the ESP32-C3. This will require some work to work
    on other chips from Espressif.
2021-09-24 18:52:09 +02:00
Yurii Soldak 3fe3fc64e4 wifinina: fix warnings 2021-09-19 13:05:38 +02:00
Yurii Soldak 0565a15b17 net: fix raddr typo 2021-09-19 13:05:38 +02:00
deadprogram fad9d12e0b examples/ili9341: correct go format
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-09-18 15:06:56 +02:00
sago35 f2e5278965 image: add support for image/jpeg and image/png (#303)
* Copy from go1.17 image package
* Remove unnecessary files
* Reduce memory usage
* Add examples/ili9341/slideshow
* image: add ./image/README.md
* image: change convert2bin to . /cmd
* Makefile: add ./cmd to NOTEST
2021-09-18 12:18:02 +02:00
Ayke van Laethem 259593e608 ws2812: add support for 168MHz (e.g. Adafruit Feather STM32F405) 2021-09-17 10:19:21 +02:00
Ayke van Laethem 7a2b1b8c90 ws2812: improve timings to be compatible with the WS2811
The WS2811 has a slightly slower data rate, but it is close enough that
a single library can support both LEDs at the same time. In my testing,
this package was already compatible with WS2811 LEDs before this change
when running at 4-5V, but when the voltage dropped to 3V or so the LEDs
started misbehaving. With these improved timings, the LEDs remained of
the correct color even at very low voltages (although blue was starting
to fade due to lack of voltage - that's not a software/protocol issue).
2021-09-17 10:08:46 +02:00
Ayke van Laethem cad03a7d4e ws2812: fix generated build tags 2021-09-17 09:42:28 +02:00
deadprogram 98f5396625 examples/sdcard: correct invalid build tag noticed by @aykevl
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-09-16 18:31:33 +02:00
deadprogram 3b16972ed8 all: use build directives for both Go1.17 and earlier versions
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-09-16 18:31:33 +02:00
deadprogram b35496dd1b make: correct fmt-check to look in all subdirectories
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-09-16 18:31:33 +02:00
Yurii Soldak ad6be40966 lsm6dox: minimal correct implementation 2021-09-14 12:10:59 +02:00
Ayke van Laethem b3af3f594e ws2812: generate assembly instead of handwriting it
Previously, a new implementation had to be written for each processor
speed. This is tedious and error-prone, therefore I've rewritten all of
the assembly code using a tool that will calculate exactly how many NOP
instructions are required.

I've also switched from build tags to a switch statement over all
processor speeds.

All in all, this means that:
  - Chips with a supported CPU performance will automatically be
    supported (no build tags necessary).
  - Adding a new chip is as easy as adding the MHz count to the
    generator script and to the switch statement.

Right now this is only for the Cortex-M, but it's certainly feasible to
extend this to other architectures such as the AVR.
2021-09-07 18:00:55 +02:00
sago35 9a3bfd4826 wifinina: add comments 2021-09-06 11:06:59 +02:00
sago35 1ba9ba3143 wifinina: add examples/wifinina/http-get 2021-09-06 11:06:59 +02:00
Yurii Soldak feb1c63656 Instructions on how to flash nina-fw on nano rp2040 connect w/o Arduino IDE 2021-09-05 11:57:07 +02:00
Yurii Soldak 0691ed5205 wifinina: nina-fw update docs 2021-09-05 11:57:07 +02:00
deadprogram e70beede1c ws2812: update examples to use go:build tags required by go 1.17
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-09-03 11:11:40 +02:00
sago35 92673d996d dht: improve build tag in lowfreq.go 2021-09-02 11:28:22 +02:00
sago35 374e2dfe1d ili9341: change to use drivers.SPI interface 2021-09-01 19:41:27 +02:00
sago35 b35aab6d61 Add support for case-insensitive header names 2021-08-24 10:45:28 +02:00
sago35 358501fc47 Add support for req.URL.RawQuery 2021-08-24 10:45:28 +02:00
sago35 a0119ffc6f rtl8720dn: add examples/rtl8720dn/tcpclient 2021-08-09 21:11:47 +02:00
sago35 58106b5942 Add examples/rtl8720dn/udpstation 2021-08-05 22:18:24 +02:00
sago35 2537c69b0f rtl8720dn: add support for http.Get(), http.Post() and cookie 2021-08-05 08:10:52 +02:00
sago35 633f19c4ac rtl8720dn: add examples/rtl8720dn/mqtt* 2021-07-31 11:02:45 +02:00
sago35 6a4cd9d8e7 rtl8720dn: add examples/rtl8720dn/webserver 2021-07-24 09:44:17 +02:00
sago35 8a4a0ff017 rtl8720dn: add info when debug mode is enabled 2021-07-24 09:28:46 +02:00
deadprogram 1cbf1a6f3d release: v0.17.1
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-07-01 20:38:55 +02:00
deadprogram 001bdb43ba release: v0.17.0
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-07-01 20:20:03 +02:00
deadprogram f7ae6fac6d modules: switch to use tinygo-org version of tinyfs package
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-07-01 20:00:52 +02:00
sago35 a575b2a4ed Update comments 2021-06-27 16:33:32 +02:00
sago35 0bc3702dd0 rtl8720dn: add support for rtl8720dn 2021-06-27 16:33:32 +02:00
sago35 b53a8a17e7 ili9341: add standard SPI driver 2021-06-27 08:08:27 +02:00
sago35 5e117c162c ws2812: rename the pin to ws2812 2021-06-26 14:04:13 +02:00
sago35 24dfd8795a sdcard: add write functionality to examples/sdcard/tinyfs 2021-06-23 18:34:26 +02:00
sago35 a748451cab Merge pull request #275 from tinygo-org/ws2812-add-nrf52833
ws2812: add tag for nrf52833
2021-06-23 20:33:53 +09:00
deadprogram a811483fd4 ws2812: add tag for nrf52833
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-06-20 11:11:08 +02:00
Daniel Bridges 7b565e8cb0 Disable interrupts before sending ws2812 data 2021-06-17 09:24:49 +02:00
sago35 5645eb3f91 ws2812: add support for qtpy and atsame5x 2021-06-01 21:09:08 +02:00
sago35 6b914f7af7 sdcard: add support for fatfs 2021-05-31 17:26:21 +02:00
Ayke van Laethem 5a02fe068b apa102: use 4-byte buffer to improve speed
Instead of sending the APA102 data byte by byte, it's more efficient to
send multiple bytes at once (especially when the SPI peripheral uses
DMA). This requires the apa102.Device object to be a pointer receiver to
avoid excessive heap allocations.

This commit also just happens to work around a hardware bug on the
nrf52832:
https://infocenter.nordicsemi.com/index.jsp?topic=%2Ferrata_nRF52832_Rev2%2FERR%2FnRF52832%2FRev2%2Flatest%2Fanomaly_832_58.html&anchor=anomaly_832_58
2021-05-30 22:39:50 +02:00
Ayke van Laethem 5ecefde991 bmi160: avoid heap allocations
The nrf52 series chips use DMA for writing and reading SPI data, which
means that the transmit and receive buffer slices escape. This can
easily be solved by pre-allocating the buffer in the BMI160 driver and
reusing this buffer every time.
2021-05-30 22:11:27 +02:00
Yurii Soldak 9adbde99a2 wifinina: avoid fmt package 2021-05-28 18:09:29 +02:00
Yurii Soldak a09ec31e7a Fix RSSI command for WiFiNINA
+ Print current SSID
+ Wait for correct time before printing it out
+ Cleanup
2021-05-27 08:00:13 +02:00
sago35 d07ad40373 sdcard: add support for spi sdcard driver 2021-05-23 11:22:42 +02:00
sago35 aa17ffd1cb uart: use machine.Serial as the default output 2021-05-14 13:26:59 +02:00
deadprogram ce03bebc34 release: prepare for release v0.16.0
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-05-12 15:51:16 +02:00
deadprogram dfd652ca1f docs: up to 65 devices
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-05-12 15:30:41 +02:00
Ayke van Laethem c765ef3970 servo: add driver using PWM
This PR adds support for controlling servos. For example, on the Arduino
Uno it should be able to control up to 6 servos jitter-free when using
all available PWM pins.

I haven't added support for setting a position in degrees, mainly
because this varies by servo and it's probably necessary to configure
the bounds in some way. Therefore, I added just SetMicroseconds. This
makes the API possible to use and leaves the possibility of adding a
SetPosition in the future.
2021-05-12 15:29:18 +02:00
akif999 428db3cd12 mcp2515: add support for mcp2515 CAN device 2021-05-12 13:37:02 +02:00
deadprogram d7f619ca21 docs: update count of supported devices to 63
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-05-12 09:24:16 +02:00
Kenneth Bell d1ace44754 aht20: add device 2021-05-12 09:21:52 +02:00
Kenneth Bell 6b58fdc95a tester: add a mock for command-oriented i2c devices 2021-05-12 09:21:52 +02:00
Yurii Soldak bd2530abee Example of ssd1306 with 128x64 display over I2C 2021-05-12 09:14:51 +02:00
Yurii Soldak 3bcde1485c Enable reset screen for SSD1306 via I2C 2021-05-12 09:14:51 +02:00
deadprogram 351700e48d wifinina: add information about Adafruit boards with ESP32 wifi coprocessors, and modify examples to remove code that was both not being used, and also prevented many Adafruit boards from being able to be targeted by the examples
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-05-12 09:13:09 +02:00
deadprogram cbcb62af01 wifinina: update docs to simplify the nina-fw update process
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-05-12 09:13:09 +02:00
Yurii Soldak 19bb773e5b fix println + cleanup 2021-05-12 09:11:18 +02:00
Yurii Soldak 69cc0b22c4 Example that connects to AP and prints ip addresses, time and mac 2021-05-12 09:11:18 +02:00
Kenneth Bell 2a48b5c25d wifinina: fix getMACAddress and getTime
Tested against Adafruit AirLift (compatibile variant of wifinina)
2021-05-12 09:11:18 +02:00
deadprogram e6a822f68b docs: up to 62 devices for the README
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-05-11 18:27:00 +02:00
Kenneth Bell f65bce6d36 ina260: add new i2c device 2021-05-11 11:13:29 +02:00
Yurii Soldak 67b8a341a6 Make TLS work over WiFiNINA
Verified on Arduino Nano33 IoT and nina fw v1.4.5
2021-05-11 10:59:52 +02:00
Tobias Theel b869d27170 remove debug flag and remove unnecessary padding call
(cherry picked from commit 9d3e63232b)
2021-05-11 10:59:52 +02:00
Tobias Theel 107932a201 fix padding and implement missing functions
(cherry picked from commit 0aa0bde76e)
2021-05-11 10:59:52 +02:00
sago35 d2db0c28e2 doc: update README.md 2021-05-10 14:42:12 +02:00
sago35 761bcfc4db pcf8563: add support for pcf8563 real time clock 2021-05-10 14:35:01 +02:00
Kenneth Bell 91dadd5535 Add 16-bit register mock device 2021-05-10 12:15:52 +02:00
Alan Wang f7dc106fc8 tm1637: add support for tm1637 7-segment LED 2021-05-07 18:05:44 +02:00
Ayke van Laethem df343190c2 tone: add package for producing tones using the PWM interface 2021-05-05 14:49:23 +02:00
deadprogram 6bc466f79b pwm: update drivers with PWM to use new interface
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-05-05 14:44:24 +02:00
Daniel M. Lambea 23776bf906 flash/drivers: fix EraseBlocks method which is erasing sectors instead 2021-04-05 14:44:56 +02:00
Ayke van Laethem e77e9249cd all: use interfaces for UART objects
This makes it possible to replace UART objects with dummy
implementations, for example. Or allows changing the `machine.UART` type
to `*machine.UART` without breaking compatibility.
2021-04-02 17:31:28 +02:00
Quentin Smith 1345bc2161 p1am: documentation and example program 2021-04-02 17:23:38 +02:00
Quentin Smith ab795cc186 p1am: support the P1AM-100 hardware watchdog 2021-04-02 17:23:38 +02:00
Quentin Smith 36213a1cdc p1am: fetch base controller version number 2021-04-02 17:23:38 +02:00
Quentin Smith 963c903d71 p1am: support discrete inputs and outputs 2021-04-02 17:23:38 +02:00
Quentin Smith 2cec480fb8 p1am: initial driver for the base controller
All the driver can currently do is initialize the base controller and enumerate
the connected modules.
2021-04-02 17:23:38 +02:00
Quentin Smith 68da7f437b p1am: import constants from P1AM Arduino library 2021-04-02 17:23:38 +02:00
sago35 d0632fccfa add .vscode/ to .gitignore 2021-03-28 12:23:16 +02:00
sago35 2c0a74df4d delete .vscode/settings.json 2021-03-28 18:50:51 +09:00
sago35 c6228a0677 Merge remote-tracking branch 'origin/release' into dev 2021-03-28 18:44:35 +09:00
deadprogram 33ec7fc98f examples: correct go fmt error
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:28:41 +01:00
deadprogram 75c15d5d0b build: correct error in Makefile from invalid merge
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:28:12 +01:00
Nerzal e1deb45aac add 4x4 keypad driver (#226)
add 4x4 keypad driver
2021-03-26 18:19:40 +01:00
deadprogram d1cafbc2b2 docs: add missing new drivers added since last release
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:12:02 +01:00
Ayke van Laethem 0b6bfda8cf all: do not take the pointer of an I2C object
This is in preparation of PR
https://github.com/tinygo-org/tinygo/pull/1693, which makes machine.I2C0
and similar objects of pointer type, so they can be freely passed
around.
2021-03-26 18:10:39 +01:00
Nerzal 84408279de add 4x4 keypad driver (#226)
add 4x4 keypad driver
2021-03-26 18:10:39 +01:00
deadprogram de1e6a626a Prepare for drivers release 0.15.1 to get tag correct
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:10:39 +01:00
deadprogram 7531c9d334 Prepare for drivers release 0.15.0
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:10:39 +01:00
pleomaxx3002 ee44900c25 DHTXX driver (#235)
dhtXX: add new driver for dht thermometer
2021-03-26 18:09:48 +01:00
deadprogram b9a70aeb6f docs: add missing new drivers added since last release
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:05:00 +01:00
deadprogram cad0a320b7 docs: update year in license to 2021
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:03:15 +01:00
Nick Craig-Wood a53a39922b hd44780: add a mode to work with boards where the RW pin is grounded
On some HD44780 boards (eg the Keyestudio LCD1602 expansion shield),
the RW pin isn't brought out and is permanently grounded.

This means that the board can't be read from, and in particular the
busy status can't be read.

This patch adapts the package to work with boards like these.

To signal this to the package, set the RW pin to machine.NoPin.

The package will then disallow all reading and use adjustable timing
based writing. The timing can be adjusted the configuration.
2021-03-26 18:03:15 +01:00
deadprogram 41d6a4c3fa adc: update drivers with ADC to use new config struct
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:03:15 +01:00
deadprogram 60ba0e3b30 st7789: correct errors on various godoc comments
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:03:15 +01:00
deadprogram 2b5f43029c st7789: add scrolling functions to match st7735
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-26 18:03:15 +01:00
Tobias Theel a771641339 max7219: add driver support 2021-03-26 18:03:15 +01:00
deadprogram 5741ceb9d1 Prepare for drivers release 0.15.1 to get tag correct
Signed-off-by: deadprogram <ron@hybridgroup.com>
2021-03-06 13:51:27 +01:00
252 changed files with 48814 additions and 2102 deletions
+1
View File
@@ -1 +1,2 @@
build
.vscode/
+3
View File
@@ -0,0 +1,3 @@
[submodule "espnet/esp-idf"]
path = espnet/esp-idf
url = https://github.com/espressif/esp-idf.git
+68
View File
@@ -1,3 +1,71 @@
0.17.1
---
- To correct an error in the release process. Same as 0.17.0.
0.17.0
---
- **new devices**
- rtl8720dn: add support for rtl8720dn
- sdcard: add support for spi sdcard driver, along with fatfs
- **enhancements**
- apa102: use 4-byte buffer to improve speed
- bmi160: avoid heap allocations
- ili9341: add standard SPI driver
- wifinina
- avoid fmt package
- Fix RSSI command for WiFiNINA + Print current SSID + Wait for correct time before printing it out + Cleanup
- ws2812
- rename the pin to ws2812
- add tag for nrf52833
- Disable interrupts before sending ws2812 data
- add support for qtpy and atsame5x
- **core**
- modules: switch to use tinygo-org version of tinyfs package
- all: use machine.Serial as the default output
0.16.0
---
- **new devices**
- aht20: add device
- ina260: add new i2c device
- keypad: add 4x4 keypad driver (#226)
- max7219: add driver support
- mcp2515: add support for mcp2515 CAN device
- p1am: support the P1AM-100 hardware watchdog
- pcf8563: add support for pcf8563 real time clock
- servo: add driver using PWM
- tm1637: add support for tm1637 7-segment LED
- tone: add package for producing tones using the PWM interface
- **enhancements**
- pwm: update drivers with PWM to use new interface
- wifinina: Make TLS work over WiFiNINA Verified on Arduino Nano33 IoT and nina fw v1.4.5
- ssd1306: Enable reset screen for SSD1306 via I2C
- st7789: add scrolling functions to match st7735
- **bugfixes**
- wifinina:
- fix getMACAddress and getTime
- fix println + cleanup
- remove debug flag and remove unnecessary padding call
- fix padding and implement missing functions
- flash: fix EraseBlocks method which is erasing sectors instead
- **core**
- all: use interfaces for UART objects
- all: do not take the pointer of an I2C object
- adc: update drivers with ADC to use new config struct
- **testing**
- tester:
- add a mock for command-oriented i2c devices
- add 16-bit register mock device
- **docs**
- ssd1306: example of ssd1306 with 128x64 display over I2C
- wifinina:
- add information about Adafruit boards with ESP32 wifi coprocessors, and modify examples to remove code that was both not being used, and also prevented many Adafruit boards from being able to be targeted by the examples
- update docs to simplify the nina-fw update process
- example that connects to AP and prints ip addresses, time and mac
- p1am: documentation and example program
- add missing new drivers added since last release
0.15.0
---
- **new devices**
+41 -2
View File
@@ -2,7 +2,7 @@
clean:
@rm -rf build
FMT_PATHS = ./*.go ./examples/**/*.go
FMT_PATHS = ./
fmt-check:
@unformatted=$$(gofmt -l $(FMT_PATHS)); [ -z "$$unformatted" ] && exit 0; echo "Unformatted:"; for fn in $$unformatted; do echo " $$fn"; done; exit 1
@@ -75,6 +75,8 @@ smoke-test:
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=xiao ./examples/ili9341/scroll
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=pyportal ./examples/ili9341/slideshow
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=circuitplay-express ./examples/lis3dh/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/lsm303agr/main.go
@@ -89,16 +91,22 @@ smoke-test:
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=itsybitsy-m0 ./examples/mcp3008/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=itsybitsy-m0 ./examples/mcp2515/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/microbitmatrix/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=itsybitsy-m0 ./examples/mma8653/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=itsybitsy-m0 ./examples/mpu6050/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=p1am-100 ./examples/p1am/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/pcd8544/setbuffer/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/pcd8544/setpixel/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=arduino ./examples/servo
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=pybadge ./examples/shifter/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=microbit ./examples/sht3x/main.go
@@ -115,6 +123,10 @@ smoke-test:
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=circuitplay-express ./examples/thermistor/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=circuitplay-bluefruit ./examples/tone
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=arduino-nano33 ./examples/tm1637/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=pyportal ./examples/touch/resistive/fourwire/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=pyportal ./examples/touch/resistive/pyportal_touchpaint/main.go
@@ -165,13 +177,40 @@ endif
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=circuitplay-express ./examples/lis2mdl/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=arduino-nano33 ./examples/max72xx/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=feather-m0 ./examples/dht/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=arduino ./examples/keypad4x4/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=xiao ./examples/pcf8563/alarm/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=xiao ./examples/pcf8563/clkout/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=xiao ./examples/pcf8563/time/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=xiao ./examples/pcf8563/timer/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=feather-m0 ./examples/ina260/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=nucleo-l432kc ./examples/aht20/main.go
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=feather-m4 ./examples/sdcard/console/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=feather-m4 ./examples/sdcard/tinyfs/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=wioterminal ./examples/rtl8720dn/webclient/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=wioterminal ./examples/rtl8720dn/webserver/
@md5sum ./build/test.hex
tinygo build -size short -o ./build/test.hex -target=wioterminal ./examples/rtl8720dn/mqttsub/
@md5sum ./build/test.hex
DRIVERS = $(wildcard */)
NOTESTS = build examples flash semihosting pcd8544 shiftregister st7789 microphone mcp3008 gps microbitmatrix \
hcsr04 ssd1331 ws2812 thermistor apa102 easystepper ssd1351 ili9341 wifinina shifter hub75 \
hd44780 buzzer ssd1306 espat l9110x st7735 bmi160 l293x dht
hd44780 buzzer ssd1306 espat l9110x st7735 bmi160 l293x dht keypad4x4 max72xx p1am tone tm1637 \
pcf8563 mcp2515 servo sdcard rtl8720dn image cmd
TESTS = $(filter-out $(addsuffix /%,$(NOTESTS)),$(DRIVERS))
unit-test:
+12 -1
View File
@@ -52,12 +52,13 @@ func main() {
## Currently supported devices
The following 56 devices are supported.
The following 67 devices are supported.
| Device Name | Interface Type |
|----------|-------------|
| [ADT7410 I2C Temperature Sensor](https://www.analog.com/media/en/technical-documentation/data-sheets/ADT7410.pdf) | I2C |
| [ADXL345 accelerometer](http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf) | I2C |
| [AHT20 I2C Temperature and Humidity Sensor](http://www.aosong.com/userfiles/files/media/AHT20%20%E8%8B%B1%E6%96%87%E7%89%88%E8%AF%B4%E6%98%8E%E4%B9%A6%20A0%2020201222.pdf) | I2C |
| [AMG88xx 8x8 Thermal camera sensor](https://cdn-learn.adafruit.com/assets/assets/000/043/261/original/Grid-EYE_SPECIFICATIONS%28Reference%29.pdf) | I2C |
| [APA102 RGB LED](https://cdn-shop.adafruit.com/product-files/2343/APA102C.pdf) | SPI |
| [AT24CX 2-wire serial EEPROM](https://www.openimpulse.com/blog/wp-content/uploads/wpsc/downloadables/24C32-Datasheet.pdf) | I2C |
@@ -80,24 +81,33 @@ The following 56 devices are supported.
| [HD44780 LCD controller](https://www.sparkfun.com/datasheets/LCD/HD44780.pdf) | GPIO/I2C |
| [HUB75 RGB led matrix](https://cdn-learn.adafruit.com/downloads/pdf/32x16-32x32-rgb-led-matrix.pdf) | SPI |
| [ILI9341 TFT color display](https://cdn-shop.adafruit.com/datasheets/ILI9341.pdf) | SPI |
| [INA260 Volt/Amp/Power meter](https://www.ti.com/lit/ds/symlink/ina260.pdf) | I2C |
| [4x4 Membrane Keypad](https://cdn.sparkfun.com/assets/f/f/a/5/0/DS-16038.pdf) | GPIO |
| [L293x motor driver](https://www.ti.com/lit/ds/symlink/l293d.pdf) | GPIO/PWM |
| [L9110x motor driver](https://www.elecrow.com/download/datasheet-l9110.pdf) | GPIO/PWM |
| [LIS2MDL magnetometer](https://www.st.com/resource/en/datasheet/lis2mdl.pdf) | I2C |
| [LIS3DH accelerometer](https://www.st.com/resource/en/datasheet/lis3dh.pdf) | I2C |
| [LSM6DS3 accelerometer](https://www.st.com/resource/en/datasheet/lsm6ds3.pdf) | I2C |
| [MAG3110 magnetometer](https://www.nxp.com/docs/en/data-sheet/MAG3110.pdf) | I2C |
| [MAX7219 & MAX7221 display driver](https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf) | SPI |
| [MCP23017 port expander](https://ww1.microchip.com/downloads/en/DeviceDoc/20001952C.pdf) | I2C |
| [MCP3008 analog to digital converter (ADC)](http://ww1.microchip.com/downloads/en/DeviceDoc/21295d.pdf) | SPI |
| [MCP2515 Stand-Alone CAN Controller with SPI Interface](https://ww1.microchip.com/downloads/en/DeviceDoc/MCP2515-Family-Data-Sheet-DS20001801K.pdf) | SPI |
| [Microphone - PDM](https://cdn-learn.adafruit.com/assets/assets/000/049/977/original/MP34DT01-M.pdf) | I2S/PDM |
| [MMA8653 accelerometer](https://www.nxp.com/docs/en/data-sheet/MMA8653FC.pdf) | I2C |
| [MPU6050 accelerometer/gyroscope](https://store.invensense.com/datasheets/invensense/MPU-6050_DataSheet_V3%204.pdf) | I2C |
| [P1AM-100 Base Controller](https://facts-engineering.github.io/modules/P1AM-100/P1AM-100.html) | SPI |
| [PCD8544 display](http://eia.udg.edu/~forest/PCD8544_1.pdf) | SPI |
| [PCF8563 real time clock](https://www.nxp.com/docs/en/data-sheet/PCF8563.pdf) | I2C |
| [Resistive Touchscreen (4-wire)](http://ww1.microchip.com/downloads/en/Appnotes/doc8091.pdf) | GPIO |
| [RTL8720DN 2.4G/5G Dual Bands Wireless and BLE5.0](https://www.seeedstudio.com/Realtek8720DN-2-4G-5G-Dual-Bands-Wireless-and-BLE5-0-Combo-Module-p-4442.html) | UART |
| [Semihosting](https://wiki.segger.com/Semihosting) | Debug |
| [Servo](https://learn.sparkfun.com/tutorials/hobby-servo-tutorial/all) | PWM |
| [Shift register (PISO)](https://en.wikipedia.org/wiki/Shift_register#Parallel-in_serial-out_\(PISO\)) | GPIO |
| [Shift registers (SIPO)](https://en.wikipedia.org/wiki/Shift_register#Serial-in_parallel-out_(SIPO)) | GPIO |
| [SHT3x Digital Humidity Sensor](https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/0_Datasheets/Humidity/Sensirion_Humidity_Sensors_SHT3x_Datasheet_digital.pdf) | I2C |
| [SPI NOR Flash Memory](https://en.wikipedia.org/wiki/Flash_memory#NOR_flash) | SPI/QSPI |
| [SPI SDCARD/MMC](https://en.wikipedia.org/wiki/SD_card) | SPI |
| [SSD1306 OLED display](https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf) | I2C / SPI |
| [SSD1331 TFT color display](https://www.crystalfontz.com/controllers/SolomonSystech/SSD1331/381/) | SPI |
| [SSD1351 OLED display](https://download.mikroe.com/documents/datasheets/ssd1351-revision-1.3.pdf) | SPI |
@@ -105,6 +115,7 @@ The following 56 devices are supported.
| [ST7789 TFT color display](https://cdn-shop.adafruit.com/product-files/3787/3787_tft_QT154H2201__________20190228182902.pdf) | SPI |
| [Stepper motor "Easystepper" controller](https://en.wikipedia.org/wiki/Stepper_motor) | GPIO |
| [Thermistor](https://www.farnell.com/datasheets/33552.pdf) | ADC |
| [TM1637 7-segment LED display](https://www.mcielectronics.cl/website_MCI/static/documents/Datasheet_TM1637.pdf) | I2C |
| [TMP102 I2C Temperature Sensor](https://download.mikroe.com/documents/datasheets/tmp102-data-sheet.pdf) | I2C |
| [VEML6070 UV light sensor](https://www.vishay.com/docs/84277/veml6070.pdf) | I2C |
| [VL53L1X time-of-flight distance sensor](https://www.st.com/resource/en/datasheet/vl53l1x.pdf) | I2C |
+108
View File
@@ -0,0 +1,108 @@
package aht20
import (
"time"
"tinygo.org/x/drivers"
)
// Device wraps an I2C connection to an AHT20 device.
type Device struct {
bus drivers.I2C
Address uint16
humidity uint32
temp uint32
}
// New creates a new AHT20 connection. The I2C bus must already be
// configured.
//
// This function only creates the Device object, it does not touch the device.
func New(bus drivers.I2C) Device {
return Device{
bus: bus,
Address: Address,
}
}
// Configure the device
func (d *Device) Configure() {
// Check initialization state
status := d.Status()
if status&0x08 == 1 {
// Device is initialized
return
}
// Force initialization
d.bus.Tx(d.Address, []byte{CMD_INITIALIZE, 0x08, 0x00}, nil)
time.Sleep(10 * time.Millisecond)
}
// Reset the device
func (d *Device) Reset() {
d.bus.Tx(d.Address, []byte{CMD_SOFTRESET}, nil)
}
// Status of the device
func (d *Device) Status() byte {
data := []byte{0}
d.bus.Tx(d.Address, []byte{CMD_STATUS}, data)
return data[0]
}
// Read the temperature and humidity
//
// The actual temperature and humidity are stored
// and can be accessed using `Temp` and `Humidity`.
func (d *Device) Read() error {
d.bus.Tx(d.Address, []byte{CMD_TRIGGER, 0x33, 0x00}, nil)
data := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
for retry := 0; retry < 3; retry++ {
time.Sleep(80 * time.Millisecond)
err := d.bus.Tx(d.Address, nil, data)
if err != nil {
return err
}
// If measurement complete, store values
if data[0]&0x04 != 0 && data[0]&0x80 == 0 {
d.humidity = uint32(data[1])<<12 | uint32(data[2])<<4 | uint32(data[3])>>4
d.temp = (uint32(data[3])&0xF)<<16 | uint32(data[4])<<8 | uint32(data[5])
return nil
}
}
return ErrTimeout
}
func (d *Device) RawHumidity() uint32 {
return d.humidity
}
func (d *Device) RawTemp() uint32 {
return d.temp
}
func (d *Device) RelHumidity() float32 {
return (float32(d.humidity) * 100) / 0x100000
}
func (d *Device) DeciRelHumidity() int32 {
return (int32(d.humidity) * 1000) / 0x100000
}
// Temperature in degrees celsius
func (d *Device) Celsius() float32 {
return (float32(d.temp*200.0) / 0x100000) - 50
}
// Temperature in mutiples of one tenth of a degree celsius
//
// Using this method avoids floating point calculations.
func (d *Device) DeciCelsius() int32 {
return ((int32(d.temp) * 2000) / 0x100000) - 500
}
+74
View File
@@ -0,0 +1,74 @@
package aht20
import (
"testing"
qt "github.com/frankban/quicktest"
"tinygo.org/x/drivers/tester"
)
func TestDefaultI2CAddress(t *testing.T) {
c := qt.New(t)
bus := tester.NewI2CBus(c)
dev := New(bus)
c.Assert(uint8(dev.Address), qt.Equals, uint8(Address))
}
func TestInitialization(t *testing.T) {
c := qt.New(t)
bus := tester.NewI2CBus(c)
fdev := tester.NewI2CDeviceCmd(c, Address)
fdev.Commands = defaultCommands()
bus.AddDevice(fdev)
// Set status to uninitialized to force initialization
fdev.Commands[CMD_STATUS].Response[0] = 0x0C
dev := New(bus)
dev.Configure()
// Check initialization command invoked
c.Assert(fdev.Commands[CMD_INITIALIZE].Invocations > 0, qt.Equals, true)
}
func TestRead(t *testing.T) {
c := qt.New(t)
bus := tester.NewI2CBus(c)
fdev := tester.NewI2CDeviceCmd(c, Address)
fdev.Commands = defaultCommands()
bus.AddDevice(fdev)
dev := New(bus)
dev.Read()
// Should be 25deg (250 decidegrees)
c.Assert(dev.DeciCelsius(), qt.Equals, int32(250))
// Should be 36.3% (363 decipercent)
c.Assert(dev.DeciRelHumidity(), qt.Equals, int32(363))
}
func defaultCommands() map[uint8]*tester.Cmd {
return map[uint8]*tester.Cmd{
CMD_INITIALIZE: {
Command: []byte{0xBE},
Mask: []byte{0xFF},
Response: []byte{},
},
CMD_TRIGGER: {
Command: []byte{0xAC, 0x33, 0x00},
Mask: []byte{0xFF, 0xFF, 0xFF},
Response: []byte{0x1C, 0x5D, 0x10, 0x66, 0x01, 0xD2, 0x93},
},
CMD_SOFTRESET: {
Command: []byte{0xBA},
Mask: []byte{0xFF},
Response: []byte{},
},
CMD_STATUS: {
Command: []byte{0x71},
Mask: []byte{0xFF},
Response: []byte{0x1C},
},
}
}
+20
View File
@@ -0,0 +1,20 @@
package aht20
import "errors"
const (
Address = 0x38
CMD_INITIALIZE = 0xBE
CMD_STATUS = 0x71
CMD_TRIGGER = 0xAC
CMD_SOFTRESET = 0xBA
STATUS_BUSY = 0x80
STATUS_CALIBRATED = 0x08
)
var (
ErrBusy = errors.New("device busy")
ErrTimeout = errors.New("timeout")
)
+19 -17
View File
@@ -27,44 +27,46 @@ var startFrame = []byte{0x00, 0x00, 0x00, 0x00}
type Device struct {
bus drivers.SPI
Order int
buf [4]byte
}
// New returns a new APA102 driver. Pass in a fully configured SPI bus.
func New(b drivers.SPI) Device {
return Device{bus: b, Order: BGR}
func New(b drivers.SPI) *Device {
return &Device{bus: b, Order: BGR}
}
// NewSoftwareSPI returns a new APA102 driver that will use a software based
// implementation of the SPI protocol.
func NewSoftwareSPI(sckPin, sdoPin machine.Pin, delay uint32) Device {
func NewSoftwareSPI(sckPin, sdoPin machine.Pin, delay uint32) *Device {
return New(&bbSPI{SCK: sckPin, SDO: sdoPin, Delay: delay})
}
// WriteColors writes the given RGBA color slice out using the APA102 protocol.
// The A value (Alpha channel) is used for brightness, set to 0xff (255) for maximum.
func (d Device) WriteColors(cs []color.RGBA) (n int, err error) {
func (d *Device) WriteColors(cs []color.RGBA) (n int, err error) {
d.startFrame()
// write data
for _, c := range cs {
// brightness is scaled to 5 bit value
d.bus.Transfer(0xe0 | (c.A >> 3))
d.buf[0] = 0xe0 | (c.A >> 3)
// set the colors
switch d.Order {
case BRG:
d.bus.Transfer(c.B)
d.bus.Transfer(c.R)
d.bus.Transfer(c.G)
d.buf[1] = c.B
d.buf[2] = c.R
d.buf[3] = c.G
case GRB:
d.bus.Transfer(c.G)
d.bus.Transfer(c.R)
d.bus.Transfer(c.B)
d.buf[1] = c.G
d.buf[2] = c.R
d.buf[3] = c.B
case BGR:
d.bus.Transfer(c.B)
d.bus.Transfer(c.G)
d.bus.Transfer(c.R)
d.buf[1] = c.B
d.buf[2] = c.G
d.buf[3] = c.R
}
d.bus.Tx(d.buf[:], nil)
}
d.endFrame(len(cs))
@@ -73,7 +75,7 @@ func (d Device) WriteColors(cs []color.RGBA) (n int, err error) {
}
// Write the raw bytes using the APA102 protocol.
func (d Device) Write(buf []byte) (n int, err error) {
func (d *Device) Write(buf []byte) (n int, err error) {
d.startFrame()
d.bus.Tx(buf, nil)
d.endFrame(len(buf) / 4)
@@ -82,14 +84,14 @@ func (d Device) Write(buf []byte) (n int, err error) {
}
// startFrame sends the start bytes for a strand of LEDs.
func (d Device) startFrame() {
func (d *Device) startFrame() {
d.bus.Tx(startFrame, nil)
}
// endFrame sends the end frame marker with one extra bit per LED so
// long strands of LEDs receive the necessary termination for updates.
// See https://cpldcpu.wordpress.com/2014/11/30/understanding-the-apa102-superled/
func (d Device) endFrame(count int) {
func (d *Device) endFrame(count int) {
for i := 0; i < count/16; i++ {
d.bus.Transfer(0xff)
}
+24 -5
View File
@@ -13,6 +13,8 @@ type DeviceSPI struct {
// Chip select pin
CSB machine.Pin
buf [7]byte
// SPI bus (requires chip select to be usable).
Bus drivers.SPI
}
@@ -80,7 +82,10 @@ func (d *DeviceSPI) Reset() error {
// ReadTemperature returns the temperature in celsius milli degrees (°C/1000).
func (d *DeviceSPI) ReadTemperature() (temperature int32, err error) {
data := []byte{0x80 | reg_TEMPERATURE_0, 0, 0}
data := d.buf[:3]
data[0] = 0x80 | reg_TEMPERATURE_0
data[1] = 0
data[2] = 0
d.CSB.Low()
err = d.Bus.Tx(data, data)
d.CSB.High()
@@ -113,7 +118,11 @@ func (d *DeviceSPI) ReadTemperature() (temperature int32, err error) {
// and the sensor is not moving the returned value will be around 1000000 or
// -1000000.
func (d *DeviceSPI) ReadAcceleration() (x int32, y int32, z int32, err error) {
data := []byte{0x80 | reg_ACC_XL, 0, 0, 0, 0, 0, 0}
data := d.buf[:7]
data[0] = 0x80 | reg_ACC_XL
for i := 1; i < len(data); i++ {
data[i] = 0
}
d.CSB.Low()
err = d.Bus.Tx(data, data)
d.CSB.High()
@@ -139,7 +148,11 @@ func (d *DeviceSPI) ReadAcceleration() (x int32, y int32, z int32, err error) {
// rotation along one axis and while doing so integrate all values over time,
// you would get a value close to 360000000.
func (d *DeviceSPI) ReadRotation() (x int32, y int32, z int32, err error) {
data := []byte{0x80 | reg_GYR_XL, 0, 0, 0, 0, 0, 0}
data := d.buf[:7]
data[0] = 0x80 | reg_GYR_XL
for i := 1; i < len(data); i++ {
data[i] = 0
}
d.CSB.Low()
err = d.Bus.Tx(data, data)
d.CSB.High()
@@ -185,7 +198,9 @@ func (d *DeviceSPI) readRegister(address uint8) uint8 {
// I don't know why but it appears necessary to sleep for a bit here.
time.Sleep(time.Millisecond)
data := []byte{0x80 | address, 0}
data := d.buf[:2]
data[0] = 0x80 | address
data[1] = 0
d.CSB.Low()
d.Bus.Tx(data, data)
d.CSB.High()
@@ -198,7 +213,11 @@ func (d *DeviceSPI) writeRegister(address, data uint8) {
// I don't know why but it appears necessary to sleep for a bit here.
time.Sleep(time.Millisecond)
buf := d.buf[:2]
buf[0] = address
buf[1] = data
d.CSB.Low()
d.Bus.Tx([]byte{address, data}, []byte{0, 0})
d.Bus.Tx(buf, buf)
d.CSB.High()
}
+49
View File
@@ -0,0 +1,49 @@
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
)
// See ../../image/README.md for the usage.
func main() {
err := run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func run(args []string) error {
if len(args) < 2 {
return fmt.Errorf("usage: %s FILE")
}
b, err := ioutil.ReadFile(args[1])
if err != nil {
return err
}
fmt.Printf("const %s = \"\" +\n", strings.Replace(args[1], ".", "_", -1))
i := 0
max := 32
for i = 0; i < len(b); i++ {
bb := b[i]
if (i % max) == 0 {
fmt.Printf(" \"")
}
fmt.Printf("\\x%02X", bb)
if (i%max) == max-1 && i != len(b)-1 {
fmt.Printf("\" + \n")
}
}
if (i % max) < max-1 {
fmt.Printf("\"\n")
}
return nil
}
+2 -1
View File
@@ -1,4 +1,5 @@
// +build mimxrt1062 stm32f405 atsamd51 stm32f103xx k210 stm32f407
//go:build mimxrt1062 || stm32f405 || atsamd51 || stm32f103xx || k210 || stm32f407
// +build mimxrt1062 stm32f405 atsamd51 stm32f103xx k210 stm32f407
package dht // import "tinygo.org/x/drivers/dht"
+2 -1
View File
@@ -1,4 +1,5 @@
// +build arduino atmega1284p nrf52840 digispark nrf52 arduino_nano nrf51 atsamd21 fe310 arduino_nano33 circuitplay_express arduino_mega2560
//go:build !mimxrt1062 && !stm32f405 && !atsamd51 && !stm32f103xx && !k210 && !stm32f407
// +build !mimxrt1062,!stm32f405,!atsamd51,!stm32f103xx,!k210,!stm32f407
package dht // import "tinygo.org/x/drivers/dht"
+3 -3
View File
@@ -20,17 +20,17 @@ package espat // import "tinygo.org/x/drivers/espat"
import (
"errors"
"machine"
"strconv"
"strings"
"time"
"tinygo.org/x/drivers"
"tinygo.org/x/drivers/net"
)
// Device wraps UART connection to the ESP8266/ESP32.
type Device struct {
bus machine.UART
bus drivers.UART
// command responses that come back from the ESP8266/ESP32
response []byte
@@ -43,7 +43,7 @@ type Device struct {
var ActiveDevice *Device
// New returns a new espat driver. Pass in a fully configured UART bus.
func New(b machine.UART) *Device {
func New(b drivers.UART) *Device {
return &Device{bus: b, response: make([]byte, 512), socketdata: make([]byte, 0, 1024)}
}
+49
View File
@@ -0,0 +1,49 @@
package espnet
/*
#cgo CFLAGS: -DCONFIG_IDF_TARGET_ESP32C3
#cgo CFLAGS: -Iinclude
#cgo CFLAGS: -Iesp-idf/components/esp_common/include
#cgo CFLAGS: -Iesp-idf/components/esp_event/include
#cgo CFLAGS: -Iesp-idf/components/esp_netif/include
#cgo CFLAGS: -Iesp-idf/components/esp_wifi/include
#cgo LDFLAGS: -Lesp-idf/components/esp_wifi/lib/esp32c3 -lnet80211 -lpp -lphy -lmesh -lcore
#cgo LDFLAGS: -Tesp-idf/components/esp_rom/esp32c3/ld/esp32c3.rom.ld
#include "esp_private/wifi.h"
#include "esp_wifi_types.h"
#include "espnet.h"
*/
import "C"
import _ "compat/freertos"
type ESPWiFi struct {
}
var WiFi = &ESPWiFi{}
type Config struct {
}
var internalConfig = C.wifi_init_config_t{
osi_funcs: &C.g_wifi_osi_funcs,
wpa_crypto_funcs: C.g_wifi_default_wpa_crypto_funcs,
static_rx_buf_num: 10,
static_tx_buf_num: 10,
mgmt_sbuf_num: 6,
sta_disconnected_pm: true,
magic: C.WIFI_INIT_CONFIG_MAGIC,
}
func (wifi ESPWiFi) Configure(config Config) error {
C.esp_wifi_internal_set_log_level(5)
return makeError(C.esp_wifi_init_internal(&internalConfig))
}
func (wifi ESPWiFi) AccessPointMAC() ([6]byte, error) {
var mac [6]byte
errCode := C.esp_wifi_get_mac(C.ESP_IF_WIFI_AP, &mac[0])
return mac, makeError(errCode)
}
+103
View File
@@ -0,0 +1,103 @@
package espnet
// #include <esp_err.h>
// #include <esp_wifi.h>
import "C"
// Wrapper for C.esp_err_t. Don't convert a C.esp_err_t to an Error type,
// instead use makeError to handle ESP_OK.
type Error C.esp_err_t
// makeError converts a C.esp_err_t into an error or nil depending on whether
// errCode indicates an error or not.
func makeError(errCode C.esp_err_t) error {
if errCode == C.ESP_OK {
return nil
}
return Error(errCode)
}
func (e Error) Error() string {
switch {
case e < C.ESP_ERR_WIFI_BASE:
// esp-idf/components/esp_common/include/esp_err.h
switch e {
case C.ESP_OK:
return "OK" // not an error
case C.ESP_FAIL:
return "ESP FAIL"
case C.ESP_ERR_NO_MEM:
return "Out of memory"
case C.ESP_ERR_INVALID_ARG:
return "Invalid argument"
case C.ESP_ERR_INVALID_STATE:
return "Invalid state"
case C.ESP_ERR_INVALID_SIZE:
return "Invalid size"
case C.ESP_ERR_NOT_FOUND:
return "Requested resource not found"
case C.ESP_ERR_NOT_SUPPORTED:
return "Operation or feature not supported"
case C.ESP_ERR_TIMEOUT:
return "Operation timed out"
case C.ESP_ERR_INVALID_RESPONSE:
return "Received response was invalid"
case C.ESP_ERR_INVALID_CRC:
return "CRC or checksum was invalid"
case C.ESP_ERR_INVALID_VERSION:
return "Version was invalid"
case C.ESP_ERR_INVALID_MAC:
return "MAC address was invalid"
default:
return "Unknown error"
}
case e >= C.ESP_ERR_WIFI_BASE && e < C.ESP_ERR_MESH_BASE:
// esp-idf/components/esp_wifi/include/esp_wifi.h
switch e {
case C.ESP_ERR_WIFI_NOT_INIT:
return "WiFi driver was not installed by esp_wifi_init"
case C.ESP_ERR_WIFI_NOT_STARTED:
return "WiFi driver was not started by esp_wifi_start"
case C.ESP_ERR_WIFI_NOT_STOPPED:
return "WiFi driver was not stopped by esp_wifi_stop"
case C.ESP_ERR_WIFI_IF:
return "WiFi interface error"
case C.ESP_ERR_WIFI_MODE:
return "WiFi mode error"
case C.ESP_ERR_WIFI_STATE:
return "WiFi internal state error"
case C.ESP_ERR_WIFI_CONN:
return "WiFi internal control block of station or soft-AP error"
case C.ESP_ERR_WIFI_NVS:
return "WiFi internal NVS module error"
case C.ESP_ERR_WIFI_MAC:
return "MAC address is invalid"
case C.ESP_ERR_WIFI_SSID:
return " SSID is invalid"
case C.ESP_ERR_WIFI_PASSWORD:
return "Password is invalid"
case C.ESP_ERR_WIFI_TIMEOUT:
return "Timeout error"
case C.ESP_ERR_WIFI_WAKE_FAIL:
return "WiFi is in sleep state(RF closed) and wakeup fail"
case C.ESP_ERR_WIFI_WOULD_BLOCK:
return "The caller would block"
case C.ESP_ERR_WIFI_NOT_CONNECT:
return "Station still in disconnect status"
case C.ESP_ERR_WIFI_POST:
return "Failed to post the event to WiFi task"
case C.ESP_ERR_WIFI_INIT_STATE:
return "Invalid WiFi state when init/deinit is called"
case C.ESP_ERR_WIFI_STOP_STATE:
return "Returned when WiFi is stopping"
case C.ESP_ERR_WIFI_NOT_ASSOC:
return "The WiFi connection is not associated"
case C.ESP_ERR_WIFI_TX_DISALLOW:
return "The WiFi TX is disallowed"
default:
return "Other WiFi error"
}
default:
return "Other error"
}
}
+1
Submodule espnet/esp-idf added at c9646ff0be
+829
View File
@@ -0,0 +1,829 @@
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "espnet.h"
#include "esp_wifi.h"
#include "esp_private/wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
// Stub functions, to know which functions need to be implemented for OS
// functionality.
static bool _env_is_chip(void) {
printf("called: _env_is_chip\n");
return false;
}
static void _set_intr(int32_t cpu_no, uint32_t intr_source, uint32_t intr_num, int32_t intr_prio) {
printf("called: _set_intr\n");
}
static void _clear_intr(uint32_t intr_source, uint32_t intr_num) {
printf("called: _clear_intr\n");
}
static void _set_isr(int32_t n, void *f, void *arg) {
printf("called: _set_isr\n");
}
static void _ints_on(uint32_t mask) {
printf("called: _ints_on\n");
}
static void _ints_off(uint32_t mask) {
printf("called: _ints_off\n");
}
static bool _is_from_isr(void) {
printf("called: _is_from_isr\n");
return false;
}
// Having conflict between when include
// #include "freertos/portmacro.h"
typedef struct {
/* owner field values:
* 0 - Uninitialized (invalid)
* portMUX_FREE_VAL - Mux is free, can be locked by either CPU
* CORE_ID_REGVAL_PRO / CORE_ID_REGVAL_APP - Mux is locked to the particular core
*
*
* Any value other than portMUX_FREE_VAL, CORE_ID_REGVAL_PRO, CORE_ID_REGVAL_APP indicates corruption
*/
uint32_t owner;
/* count field:
* If mux is unlocked, count should be zero.
* If mux is locked, count is non-zero & represents the number of recursive locks on the mux.
*/
uint32_t count;
} portMUX_TYPE;
#define portMUX_FREE_VAL SPINLOCK_FREE
#define SPINLOCK_FREE 0xB33FFFFF
#define portMUX_INITIALIZER_UNLOCKED { \
.owner = portMUX_FREE_VAL, \
.count = 0, \
}
static void * _spin_lock_create(void) {
portMUX_TYPE tmp = portMUX_INITIALIZER_UNLOCKED;
void *mux = malloc(sizeof(portMUX_TYPE));
if (mux) {
memcpy(mux,&tmp,sizeof(portMUX_TYPE));
return mux;
}
return NULL;
}
static void _spin_lock_delete(void *lock) {
free(lock);
}
static uint32_t _wifi_int_disable(void *wifi_int_mux) {
printf("called: _wifi_int_disable\n");
return 0;
}
static void _wifi_int_restore(void *wifi_int_mux, uint32_t tmp) {
printf("called: _wifi_int_restore\n");
}
static void _task_yield_from_isr(void) {
printf("called: _task_yield_from_isr\n");
}
static void *_semphr_create(uint32_t max, uint32_t init) {
return (void *)xSemaphoreCreateCounting(max, init);
}
static void _semphr_delete(void *semphr) {
vSemaphoreDelete(semphr);
}
static int32_t _semphr_take(void *semphr, uint32_t block_time_tick) {
if (block_time_tick == OSI_FUNCS_TIME_BLOCKING) {
return (int32_t)xSemaphoreTake(semphr, portMAX_DELAY);
} else {
return (int32_t)xSemaphoreTake(semphr, block_time_tick);
}
}
static int32_t _semphr_give(void *semphr) {
return (int32_t)xSemaphoreGive(semphr);
}
static void *_wifi_thread_semphr_get(void) {
static SemaphoreHandle_t sem = NULL;
if (!sem) {
sem = xSemaphoreCreateCounting(1, 0);
}
return (void*)sem;
}
static void *_mutex_create(void) {
printf("called: _mutex_create\n");
return NULL;
}
static void *_recursive_mutex_create(void) {
return xSemaphoreCreateRecursiveMutex();
}
static void _mutex_delete(void *mutex) {
return vSemaphoreDelete(mutex);
}
static int32_t _mutex_lock(void *mutex) {
return (int32_t)xSemaphoreTakeRecursive(mutex, portMAX_DELAY);
}
static int32_t _mutex_unlock(void *mutex) {
return (int32_t)xSemaphoreGiveRecursive(mutex);
}
static void * _queue_create(uint32_t queue_len, uint32_t item_size) {
printf("called: _queue_create\n");
return NULL;
}
static void _queue_delete(void *queue) {
printf("called: _queue_delete\n");
}
static int32_t _queue_send(void *queue, void *item, uint32_t block_time_tick) {
if (block_time_tick == OSI_FUNCS_TIME_BLOCKING) {
return (int32_t)xQueueSend(queue, item, portMAX_DELAY);
} else {
return (int32_t)xQueueSend(queue, item, block_time_tick);
}
}
static int32_t _queue_send_from_isr(void *queue, void *item, void *hptw) {
printf("called: _queue_send_from_isr\n");
return 0;
}
static int32_t _queue_send_to_back(void *queue, void *item, uint32_t block_time_tick) {
printf("called: _queue_send_to_back\n");
return 0;
}
static int32_t _queue_send_to_front(void *queue, void *item, uint32_t block_time_tick) {
printf("called: _queue_send_to_front\n");
return 0;
}
static int32_t _queue_recv(void *queue, void *item, uint32_t block_time_tick) {
if (block_time_tick == OSI_FUNCS_TIME_BLOCKING) {
return (int32_t)xQueueReceive(queue, item, portMAX_DELAY);
} else {
return (int32_t)xQueueReceive(queue, item, block_time_tick);
}
}
static void * _event_group_create(void) {
printf("called: _event_group_create\n");
return NULL;
}
static void _event_group_delete(void *event) {
printf("called: _event_group_delete\n");
}
static uint32_t _event_group_set_bits(void *event, uint32_t bits) {
printf("called: _event_group_set_bits\n");
return 0;
}
static uint32_t _event_group_clear_bits(void *event, uint32_t bits) {
printf("called: _event_group_clear_bits\n");
return 0;
}
static uint32_t _event_group_wait_bits(void *event, uint32_t bits_to_wait_for, int clear_on_exit, int wait_for_all_bits, uint32_t block_time_tick) {
printf("called: _event_group_wait_bits\n");
return 0;
}
#define P(x) printf("called: "#x"\n");
static int32_t _task_create_pinned_to_core(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle, uint32_t core_id) {
// Note: using xTaskCreate instead of xTaskCreatePinnedToCore.
return (uint32_t)xTaskCreate(task_func, name, stack_depth, param, prio, task_handle);
}
static int32_t _task_create(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle) {
P(_task_create)
return 0;
}
static void _task_delete(void *task_handle) {
P(_task_delete)
}
static int32_t _task_ms_to_tick(uint32_t ms) {
return (int32_t)(ms / portTICK_PERIOD_MS);
}
static int32_t _task_get_max_priority() {
return configMAX_PRIORITIES;
}
static int32_t _event_post(const char* event_base, int32_t event_id, void* event_data, size_t event_data_size, uint32_t ticks_to_wait) {
P(_event_post)
return 0;
}
static uint32_t _get_free_heap_size(void) {
P(_get_free_heap_size)
return 0;
}
static uint32_t _rand(void) {
P(_rand)
return 0;
}
static void _dport_access_stall_other_cpu_start_wrap(void) {
P(_dport_access_stall_other_cpu_start_wrap)
}
static void _dport_access_stall_other_cpu_end_wrap(void) {
P(_dport_access_stall_other_cpu_end_wrap)
}
static void _wifi_apb80m_request(void) {
P(_wifi_apb80m_request)
}
static void _wifi_apb80m_release(void) {
P(_wifi_apb80m_release)
}
static void _phy_disable(void) {
P(_phy_disable)
}
static void _phy_enable(void) {
P(_phy_enable)
}
static int _phy_update_country_info(const char* country) {
P(_phy_update_country_info)
return 0;
}
static int _read_mac(uint8_t* mac, uint32_t type) {
P(_read_mac)
return 0;
}
static void _timer_arm(void *timer, uint32_t tmout, bool repeat) {
P(_timer_arm)
}
static void _timer_disarm(void *timer) {
P(_timer_disarm)
}
static void _timer_done(void *ptimer) {
P(_timer_done)
}
static void _timer_setfn(void *ptimer, void *pfunction, void *parg) {
P(_timer_setfn)
}
static void _timer_arm_us(void *ptimer, uint32_t us, bool repeat) {
P(_timer_arm_us)
}
static void _wifi_reset_mac(void) {
P(_wifi_reset_mac)
}
static void _wifi_clock_enable(void) {
P(_wifi_clock_enable)
}
static void _wifi_clock_disable(void) {
P(_wifi_clock_disable)
}
static void _wifi_rtc_enable_iso(void) {
P(_wifi_rtc_enable_iso)
}
static void _wifi_rtc_disable_iso(void) {
P(_wifi_rtc_disable_iso)
}
static int64_t _esp_timer_get_time(void) {
P(_esp_timer_get_time)
return 0;
}
static int _nvs_set_i8(uint32_t handle, const char* key, int8_t value) {
P(_nvs_set_i8)
return 0;
}
static int _nvs_get_i8(uint32_t handle, const char* key, int8_t* out_value) {
P(_nvs_get_i8)
return 0;
}
static int _nvs_set_u8(uint32_t handle, const char* key, uint8_t value) {
P(_nvs_set_u8)
return 0;
}
static int _nvs_get_u8(uint32_t handle, const char* key, uint8_t* out_value) {
P(_nvs_get_u8)
return 0;
}
static int _nvs_set_u16(uint32_t handle, const char* key, uint16_t value) {
P(_nvs_set_u16)
return 0;
}
static int _nvs_get_u16(uint32_t handle, const char* key, uint16_t* out_value) {
P(_nvs_get_u16)
return 0;
}
static int _nvs_open(const char* name, uint32_t open_mode, uint32_t *out_handle) {
P(_nvs_open)
return 0;
}
static void _nvs_close(uint32_t handle) {
P(_nvs_close)
}
static int _nvs_commit(uint32_t handle) {
P(_nvs_commit)
return 0;
}
static int _nvs_set_blob(uint32_t handle, const char* key, const void* value, size_t length) {
P(_nvs_set_blob)
return 0;
}
static int _nvs_get_blob(uint32_t handle, const char* key, void* out_value, size_t* length) {
P(_nvs_get_blob)
return 0;
}
static int _nvs_erase_key(uint32_t handle, const char* key) {
P(_nvs_erase_key)
return 0;
}
static int _get_random(uint8_t *buf, size_t len) {
P(_get_random)
return 0;
}
static int _get_time(void *t) {
P(_get_time)
return 0;
}
static unsigned long _random(void) {
P(_random)
return 0;
}
// #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3
// uint32_t (* _slowclk_cal_get(void)
// #endif
static void _log_write(uint32_t level, const char* tag, const char* format, ...) {
va_list argList;
printf("[%s] ", tag);
va_start(argList, format);
vprintf(format, argList);
va_end(argList);
printf("\n");
}
static void _log_writev(uint32_t level, const char* tag, const char* format, va_list args) {
printf("[%s] ", tag);
vprintf(format, args);
printf("\n");
}
static uint32_t _log_timestamp(void) {
P(_log_timestamp)
return 0;
}
static void* _malloc_internal(size_t size) {
printf("called: _malloc_internal(%d)\n", size);
return malloc(size);
}
static void* _realloc_internal(void *ptr, size_t size) {
printf("called: _realloc_internal(%p,%d)\n", ptr, size);
return NULL;
}
static void* _calloc_internal(size_t n, size_t size) {
printf("called: _calloc_internal(%d,%d)\n", n, size);
return malloc(n * size);
}
static void* _zalloc_internal(size_t size) {
printf("called: _zalloc_internal(%d)\n", size);
return NULL;
}
static void* _wifi_malloc(size_t size) {
return malloc(size);
}
static void* _wifi_realloc(void *ptr, size_t size) {
printf("called: _wifi_realloc(%d)\n", size);
return NULL;
}
static void* _wifi_calloc(size_t n, size_t size) {
return calloc(n, size);
}
static void* _wifi_zalloc(size_t size) {
return calloc(1, size);
}
static void* _wifi_create_queue(int queue_len, int item_size) {
wifi_static_queue_t *queue = (wifi_static_queue_t*)malloc(sizeof(wifi_static_queue_t));
queue->handle = xQueueCreate( queue_len, item_size);
return queue;
}
static void _wifi_delete_queue(void * queue) {
vQueueDelete(queue);
}
static int _coex_init(void) {
P(_coex_init)
return 0;
}
static void _coex_deinit(void) {
P(_coex_deinit)
}
static int _coex_enable(void) {
P(_coex_enable)
return 0;
}
static void _coex_disable(void) {
P(_coex_disable)
}
static uint32_t _coex_status_get(void) {
P(_coex_status_get)
return 0;
}
static void _coex_condition_set(uint32_t type, bool dissatisfy) {
P(_coex_condition_set)
}
static int _coex_wifi_request(uint32_t event, uint32_t latency, uint32_t duration) {
P(_coex_wifi_request)
return 0;
}
static int _coex_wifi_release(uint32_t event) {
P(_coex_wifi_release)
return 0;
}
static int _coex_wifi_channel_set(uint8_t primary, uint8_t secondary) {
P(_coex_wifi_channel_set)
return 0;
}
static int _coex_event_duration_get(uint32_t event, uint32_t *duration) {
P(_coex_event_duration_get)
return 0;
}
static int _coex_pti_get(uint32_t event, uint8_t *pti) {
P(_coex_pti_get)
return 0;
}
static void _coex_schm_status_bit_clear(uint32_t type, uint32_t status) {
P(_coex_schm_status_bit_clear)
}
static void _coex_schm_status_bit_set(uint32_t type, uint32_t status) {
P(_coex_schm_status_bit_set)
}
static int _coex_schm_interval_set(uint32_t interval) {
P(_coex_schm_interval_set)
return 0;
}
static uint32_t _coex_schm_interval_get(void) {
P(_coex_schm_interval_get)
return 0;
}
static uint8_t _coex_schm_curr_period_get(void) {
P(_coex_schm_curr_period_get)
return 0;
}
static void* _coex_schm_curr_phase_get(void) {
P(_coex_schm_curr_phase_get)
return NULL;
}
static int _coex_schm_curr_phase_idx_set(int idx) {
P(_coex_schm_curr_phase_idx_set)
return 0;
}
static int _coex_schm_curr_phase_idx_get(void) {
P(_coex_schm_curr_phase_idx_get)
return 0;
}
uint32_t _slowclk_cal_get(void) {
return 0;
}
// OS adapter functions.
// See: esp-idf/components/esp_wifi/include/esp_private/wifi_os_adapter.h
wifi_osi_funcs_t g_wifi_osi_funcs = {
._version = ESP_WIFI_OS_ADAPTER_VERSION,
._env_is_chip = _env_is_chip,
._set_intr = _set_intr,
._clear_intr = _clear_intr,
._set_isr = _set_isr,
._ints_on = _ints_on,
._ints_off = _ints_off,
._is_from_isr = _is_from_isr,
._spin_lock_create = _spin_lock_create,
._spin_lock_delete = _spin_lock_delete,
._wifi_int_disable = _wifi_int_disable,
._wifi_int_restore = _wifi_int_restore,
._task_yield_from_isr = _task_yield_from_isr,
._semphr_create = _semphr_create,
._semphr_delete = _semphr_delete,
._semphr_take = _semphr_take,
._semphr_give = _semphr_give,
._wifi_thread_semphr_get = _wifi_thread_semphr_get,
._mutex_create = _mutex_create,
._recursive_mutex_create = _recursive_mutex_create,
._mutex_delete = _mutex_delete,
._mutex_lock = _mutex_lock,
._mutex_unlock = _mutex_unlock,
._queue_create = _queue_create,
._queue_delete = _queue_delete,
._queue_send = _queue_send,
._queue_send_from_isr = _queue_send_from_isr,
._queue_send_to_back = _queue_send_to_back,
._queue_send_to_front = _queue_send_to_front,
._queue_recv = _queue_recv,
._queue_msg_waiting = (uint32_t(*)(void *))uxQueueMessagesWaiting,
._event_group_create = _event_group_create,
._event_group_delete = _event_group_delete,
._event_group_set_bits = _event_group_set_bits,
._event_group_clear_bits = _event_group_clear_bits,
._event_group_wait_bits = _event_group_wait_bits,
._task_create_pinned_to_core = _task_create_pinned_to_core,
._task_create = _task_create,
._task_delete = _task_delete,
._task_delay = vTaskDelay,
._task_ms_to_tick = _task_ms_to_tick,
._task_get_current_task = (void *(*)(void))xTaskGetCurrentTaskHandle,
._task_get_max_priority = _task_get_max_priority,
._malloc = malloc,
._free = free,
._event_post = _event_post,
._get_free_heap_size = _get_free_heap_size,
._rand = _rand,
._dport_access_stall_other_cpu_start_wrap = _dport_access_stall_other_cpu_start_wrap,
._dport_access_stall_other_cpu_end_wrap = _dport_access_stall_other_cpu_end_wrap,
._wifi_apb80m_request = _wifi_apb80m_request,
._wifi_apb80m_release = _wifi_apb80m_release,
._phy_disable = _phy_disable,
._phy_enable = _phy_enable,
._phy_update_country_info = _phy_update_country_info,
._read_mac = _read_mac,
._timer_arm = _timer_arm,
._timer_disarm = _timer_disarm,
._timer_done = _timer_done,
._timer_setfn = _timer_setfn,
._timer_arm_us = _timer_arm_us,
._wifi_reset_mac = _wifi_reset_mac,
._wifi_clock_enable = _wifi_clock_enable,
._wifi_clock_disable = _wifi_clock_disable,
._wifi_rtc_enable_iso = _wifi_rtc_enable_iso,
._wifi_rtc_disable_iso = _wifi_rtc_disable_iso,
._esp_timer_get_time = _esp_timer_get_time,
._nvs_set_i8 = _nvs_set_i8,
._nvs_get_i8 = _nvs_get_i8,
._nvs_set_u8 = _nvs_set_u8,
._nvs_get_u8 = _nvs_get_u8,
._nvs_set_u16 = _nvs_set_u16,
._nvs_get_u16 = _nvs_get_u16,
._nvs_open = _nvs_open,
._nvs_close = _nvs_close,
._nvs_commit = _nvs_commit,
._nvs_set_blob = _nvs_set_blob,
._nvs_get_blob = _nvs_get_blob,
._nvs_erase_key = _nvs_erase_key,
._get_random = _get_random,
._get_time = _get_time,
._random = _random,
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3
._slowclk_cal_get = _slowclk_cal_get,
#endif
._log_write = _log_write,
._log_writev = _log_writev,
._log_timestamp = _log_timestamp,
._malloc_internal = _malloc_internal,
._realloc_internal = _realloc_internal,
._calloc_internal = _calloc_internal,
._zalloc_internal = _zalloc_internal,
._wifi_malloc = _wifi_malloc,
._wifi_realloc = _wifi_realloc,
._wifi_calloc = _wifi_calloc,
._wifi_zalloc = _wifi_zalloc,
._wifi_create_queue = _wifi_create_queue,
._wifi_delete_queue = _wifi_delete_queue,
._coex_init = _coex_init,
._coex_deinit = _coex_deinit,
._coex_enable = _coex_enable,
._coex_disable = _coex_disable,
._coex_status_get = _coex_status_get,
._coex_condition_set = _coex_condition_set,
._coex_wifi_request = _coex_wifi_request,
._coex_wifi_release = _coex_wifi_release,
._coex_wifi_channel_set = _coex_wifi_channel_set,
._coex_event_duration_get = _coex_event_duration_get,
._coex_pti_get = _coex_pti_get,
._coex_schm_status_bit_clear = _coex_schm_status_bit_clear,
._coex_schm_status_bit_set = _coex_schm_status_bit_set,
._coex_schm_interval_set = _coex_schm_interval_set,
._coex_schm_interval_get = _coex_schm_interval_get,
._coex_schm_curr_period_get = _coex_schm_curr_period_get,
._coex_schm_curr_phase_get = _coex_schm_curr_phase_get,
._coex_schm_curr_phase_idx_set = _coex_schm_curr_phase_idx_set,
._coex_schm_curr_phase_idx_get = _coex_schm_curr_phase_idx_get,
._magic = ESP_WIFI_OS_ADAPTER_MAGIC,
};
static int esp_aes_wrap(const unsigned char *kek, int n, const unsigned char *plain, unsigned char *cipher) {
P(aes_wrap)
return -1;
}
static int esp_aes_unwrap(const unsigned char *kek, int n, const unsigned char *cipher, unsigned char *plain) {
P(aes_unwrap)
return -1;
}
static int hmac_sha256_vector(const unsigned char *key, int key_len, int num_elem,
const unsigned char *addr[], const int *len, unsigned char *mac) {
return -1;
}
static int sha256_prf(const unsigned char *key, int key_len, const char *label,
const unsigned char *data, int data_len, unsigned char *buf, int buf_len) {
P(sha256_prf)
return -1;
}
static int hmac_md5(const unsigned char *key, unsigned int key_len, const unsigned char *data,
unsigned int data_len, unsigned char *mac) {
P(hmac_md5)
return -1;
}
static int hamc_md5_vector(const unsigned char *key, unsigned int key_len, unsigned int num_elem,
const unsigned char *addr[], const unsigned int *len, unsigned char *mac) {
P(hamc_md5_vector)
return -1;
}
static int hmac_sha1(const unsigned char *key, unsigned int key_len, const unsigned char *data,
unsigned int data_len, unsigned char *mac) {
P(hmac_sha1)
return -1;
}
static int hmac_sha1_vector(const unsigned char *key, unsigned int key_len, unsigned int num_elem,
const unsigned char *addr[], const unsigned int *len, unsigned char *mac) {
P(hmac_sha1_vector)
return -1;
}
static int sha1_prf(const unsigned char *key, unsigned int key_len, const char *label,
const unsigned char *data, unsigned int data_len, unsigned char *buf, unsigned int buf_len) {
P(sha1_prf)
return -1;
}
static int sha1_vector(unsigned int num_elem, const unsigned char *addr[], const unsigned int *len,
unsigned char *mac) {
P(sha1_vector)
return -1;
}
static int pbkdf2_sha1(const char *passphrase, const char *ssid, unsigned int ssid_len,
int iterations, unsigned char *buf, unsigned int buflen) {
P(pbkdf2_sha1)
return -1;
}
static int rc4_skip(const unsigned char *key, unsigned int keylen, unsigned int skip,
unsigned char *data, unsigned int data_len) {
P(rc4_skip)
return -1;
}
static int md5_vector(unsigned int num_elem, const unsigned char *addr[], const unsigned int *len,
unsigned char *mac) {
P(md5_vector)
return -1;
}
static void aes_encrypt(void *ctx, const unsigned char *plain, unsigned char *crypt) {
P(aes_encrypt)
}
static void * aes_encrypt_init(const unsigned char *key, unsigned int len) {
P(aes_encrypt_init)
return NULL;
}
static void aes_encrypt_deinit(void *ctx) {
P(aes_encrypt_deinit)
}
static void aes_decrypt(void *ctx, const unsigned char *crypt, unsigned char *plain) {
P(aes_decrypt)
}
static void * aes_decrypt_init(const unsigned char *key, unsigned int len) {
P(aes_decrypt_init)
return NULL;
}
static void aes_decrypt_deinit(void *ctx) {
P(aes_decrypt_deinit)
}
static int aes_128_decrypt(const unsigned char *key, const unsigned char *iv, unsigned char *data, int data_len) {
P(aes_128_decrypt)
return -1;
}
static int omac1_aes_128(const uint8_t *key, const uint8_t *data, size_t data_len,
uint8_t *mic) {
P(omac1_aes_128)
return -1;
}
static uint8_t * ccmp_decrypt(const uint8_t *tk, const uint8_t *ieee80211_hdr,
const uint8_t *data, size_t data_len,
size_t *decrypted_len, bool espnow_pkt) {
P(ccmp_decrypt)
return NULL;
}
static uint8_t * ccmp_encrypt(const uint8_t *tk, uint8_t *frame, size_t len, size_t hdrlen,
uint8_t *pn, int keyid, size_t *encrypted_len) {
P(ccmp_encrypt)
return NULL;
}
static int hmac_md5_vector(const unsigned char *key, unsigned int key_len, unsigned int num_elem,
const unsigned char *addr[], const unsigned int *len, unsigned char *mac) {
P(hmac_md5_vector)
return -1;
}
static void esp_aes_encrypt(void *ctx, const unsigned char *plain, unsigned char *crypt) {
P(esp_aes_encrypt)
}
static void esp_aes_decrypt(void *ctx, const unsigned char *crypt, unsigned char *plain) {
P(esp_aes_decrypt)
}
static int aes_128_cbc_encrypt(const unsigned char *key, const unsigned char *iv, unsigned char *data, int data_len) {
P(aes_128_cbc_encrypt)
return -1;
}
static int aes_128_cbc_decrypt(const unsigned char *key, const unsigned char *iv, unsigned char *data, int data_len) {
P(aes_128_cbc_decrypt)
return -1;
}
const wpa_crypto_funcs_t g_wifi_default_wpa_crypto_funcs = {
.size = sizeof(wpa_crypto_funcs_t),
.version = ESP_WIFI_CRYPTO_VERSION,
.aes_wrap = (esp_aes_wrap_t)esp_aes_wrap,
.aes_unwrap = (esp_aes_unwrap_t)esp_aes_unwrap,
.hmac_sha256_vector = (esp_hmac_sha256_vector_t)hmac_sha256_vector,
.sha256_prf = (esp_sha256_prf_t)sha256_prf,
.hmac_md5 = (esp_hmac_md5_t)hmac_md5,
.hamc_md5_vector = (esp_hmac_md5_vector_t)hmac_md5_vector,
.hmac_sha1 = (esp_hmac_sha1_t)hmac_sha1,
.hmac_sha1_vector = (esp_hmac_sha1_vector_t)hmac_sha1_vector,
.sha1_prf = (esp_sha1_prf_t)sha1_prf,
.sha1_vector = (esp_sha1_vector_t)sha1_vector,
.pbkdf2_sha1 = (esp_pbkdf2_sha1_t)pbkdf2_sha1,
.rc4_skip = (esp_rc4_skip_t)rc4_skip,
.md5_vector = (esp_md5_vector_t)md5_vector,
.aes_encrypt = (esp_aes_encrypt_t)esp_aes_encrypt,
.aes_encrypt_init = (esp_aes_encrypt_init_t)aes_encrypt_init,
.aes_encrypt_deinit = (esp_aes_encrypt_deinit_t)aes_encrypt_deinit,
.aes_decrypt = (esp_aes_decrypt_t)esp_aes_decrypt,
.aes_decrypt_init = (esp_aes_decrypt_init_t)aes_decrypt_init,
.aes_decrypt_deinit = (esp_aes_decrypt_deinit_t)aes_decrypt_deinit,
.aes_128_encrypt = (esp_aes_128_encrypt_t)aes_128_cbc_encrypt,
.aes_128_decrypt = (esp_aes_128_decrypt_t)aes_128_cbc_decrypt,
.omac1_aes_128 = (esp_omac1_aes_128_t)omac1_aes_128,
.ccmp_decrypt = (esp_ccmp_decrypt_t)ccmp_decrypt,
.ccmp_encrypt = (esp_ccmp_encrypt_t)ccmp_encrypt
};
// This is a string constant that is used all over ESP-IDF and is also used by
// libnet80211.a. The main purpose is to be a fixed pointer that can be compared
// against etc.
const char *WIFI_EVENT = "WIFI_EVENT";
// Required by libphy.a
int phy_printf(const char *format, ...) {
va_list args;
va_start(args, format);
printf("phy: ");
int res = vprintf(format, args);
va_end(args);
return res;
}
// Required by libpp.a
int pp_printf(const char *format, ...) {
va_list args;
va_start(args, format);
printf("pp: ");
int res = vprintf(format, args);
va_end(args);
return res;
}
// Required by libnet80211.a
int net80211_printf(const char *format, ...) {
va_list args;
va_start(args, format);
printf("net80211: ");
int res = vprintf(format, args);
va_end(args);
return res;
}
// Source: esp-idf/components/wpa_supplicant/src/utils/common.c
static int hex2num(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
// Source: esp-idf/components/wpa_supplicant/src/utils/common.c
int hex2byte(const char *hex)
{
int a, b;
a = hex2num(*hex++);
if (a < 0)
return -1;
b = hex2num(*hex++);
if (b < 0)
return -1;
return (a << 4) | b;
}
// Source: esp-idf/components/wpa_supplicant/src/utils/common.c
/**
* hexstr2bin - Convert ASCII hex string into binary data
* @hex: ASCII hex string (e.g., "01ab")
* @buf: Buffer for the binary data
* @len: Length of the text to convert in bytes (of buf); hex will be double
* this size
* Returns: 0 on success, -1 on failure (invalid hex string)
*/
int hexstr2bin(const char *hex, uint8_t *buf, size_t len)
{
size_t i;
int a;
const char *ipos = hex;
uint8_t *opos = buf;
for (i = 0; i < len; i++) {
a = hex2byte(ipos);
if (a < 0)
return -1;
*opos++ = a;
ipos += 2;
}
return 0;
}
+5
View File
@@ -0,0 +1,5 @@
#include <stdbool.h>
#include "esp_private/wifi_os_adapter.h"
extern wifi_osi_funcs_t g_wifi_osi_funcs;
View File
+1 -1
View File
@@ -9,7 +9,7 @@ import (
)
var (
i2c = &machine.I2C0
i2c = machine.I2C0
sensor = adt7410.New(i2c)
)
+55
View File
@@ -0,0 +1,55 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/aht20"
)
func main() {
machine.I2C0.Configure(machine.I2CConfig{})
dev := aht20.New(machine.I2C0)
dev.Configure()
dev.Reset()
for {
time.Sleep(500 * time.Millisecond)
err := dev.Read()
if err != nil {
println("Error", err)
continue
}
println("temp ", fmtD(dev.DeciCelsius(), 3, 1), "C")
println("humidity", fmtD(dev.DeciRelHumidity(), 3, 1), "%")
}
}
func fmtD(val int32, i int, f int) string {
result := make([]byte, i+f+1)
neg := false
if val < 0 {
val = -val
neg = true
}
for p := len(result) - 1; p >= 0; p-- {
result[p] = byte(int32('0') + (val % 10))
val = val / 10
if p == i+1 && p > 0 {
p--
result[p] = '.'
}
}
if neg {
result[0] = '-'
}
return string(result)
}
+15 -8
View File
@@ -13,9 +13,9 @@ import (
)
var (
apa apa102.Device
apa *apa102.Device
led = machine.PWM{machine.LED}
pwm = machine.TCC0
leds = make([]color.RGBA, 1)
wheel = &Wheel{Brightness: 0x10}
)
@@ -27,12 +27,19 @@ func init() {
apa = apa102.NewSoftwareSPI(machine.PA00, machine.PA01, 1)
// Configure the regular on-board LED for PWM fading
machine.InitPWM()
led.Configure()
err := pwm.Configure(machine.PWMConfig{})
if err != nil {
println("failed to configure PWM")
return
}
}
func main() {
channelLED, err := pwm.Channel(machine.LED)
if err != nil {
println("failed to configure LED PWM channel")
return
}
// We'll fade the on-board LED in a goroutine to show/ensure that the APA102
// works fine with the scheduler enabled. Comment this out to test this code
@@ -43,11 +50,11 @@ func main() {
brightening = !brightening
continue
}
var brightness uint16 = uint16(i) << 8
var brightness uint32 = uint32(i)
if !brightening {
brightness = 0xFFFF - brightness
brightness = 256 - brightness
}
led.Set(brightness)
pwm.Set(channelLED, pwm.Top()*brightness/256)
time.Sleep(5 * time.Millisecond)
}
}()
+1 -1
View File
@@ -30,7 +30,7 @@ var (
tx = machine.PA22
rx = machine.PA23
console = machine.UART0
console = machine.Serial
adaptor *espat.Device
)
+1 -1
View File
@@ -36,7 +36,7 @@ var (
tx = machine.PA22
rx = machine.PA23
console = machine.UART0
console = machine.Serial
adaptor *espat.Device
topic = "tinygo"
+1 -1
View File
@@ -37,7 +37,7 @@ var (
tx = machine.PA22
rx = machine.PA23
console = machine.UART0
console = machine.Serial
adaptor *espat.Device
cl mqtt.Client
+20
View File
@@ -0,0 +1,20 @@
package main
import "tinygo.org/x/drivers/espnet"
func main() {
err := espnet.WiFi.Configure(espnet.Config{})
if err != nil {
println("failed to configure:", err.Error())
}
mac, err := espnet.WiFi.AccessPointMAC()
if err != nil {
println("failed to read MAC address:", err.Error())
return
}
print("MAC address:")
for _, b := range mac {
print(" ", b)
}
println()
}
+1 -1
View File
@@ -20,7 +20,7 @@ var (
input [consoleBufLen]byte
store [storageBufLen]byte
console = machine.UART0
console = machine.Serial
dev *flash.Device
+1 -1
View File
@@ -10,7 +10,7 @@ import (
func main() {
println("GPS I2C Example")
machine.I2C0.Configure(machine.I2CConfig{})
ublox := gps.NewI2C(&machine.I2C0)
ublox := gps.NewI2C(machine.I2C0)
parser := gps.NewParser()
var fix gps.Fix
for {
+1 -1
View File
@@ -10,7 +10,7 @@ import (
func main() {
println("GPS UART Example")
machine.UART1.Configure(machine.UARTConfig{BaudRate: 9600})
ublox := gps.NewUART(&machine.UART1)
ublox := gps.NewUART(machine.UART1)
parser := gps.NewParser()
var fix gps.Fix
for {
+1
View File
@@ -1,3 +1,4 @@
//go:build atsamd21
// +build atsamd21
package main
+1
View File
@@ -1,3 +1,4 @@
//go:build pyportal
// +build pyportal
package main
+1
View File
@@ -1,3 +1,4 @@
//go:build wioterminal
// +build wioterminal
package main
File diff suppressed because it is too large Load Diff
+9 -6
View File
@@ -25,7 +25,7 @@ const (
)
var (
frameBuffer = [(graphics.BALLHEIGHT + 8) * (graphics.BALLWIDTH + 8)]uint16{}
frameBuffer = [(graphics.BALLHEIGHT + 8) * (graphics.BALLWIDTH + 8) * 2]uint8{}
startTime int64
frame int64
@@ -179,7 +179,8 @@ func main() {
c = BGCOLOR
}
}
frameBuffer[y*int(width)+x] = c
frameBuffer[(y*int(width)+x)*2] = byte(c >> 8)
frameBuffer[(y*int(width)+x)*2+1] = byte(c)
bx1++ // Increment bitmap position counters (X axis)
bgx1++
}
@@ -190,7 +191,7 @@ func main() {
bgy++
}
display.DrawRGBBitmap(minx, miny, frameBuffer[:width*height], width, height)
display.DrawRGBBitmap8(minx, miny, frameBuffer[:width*height*2], width, height)
// Show approximate frame rate
frame++
@@ -215,11 +216,13 @@ func DrawBackground() {
b = graphics.Background[j*byteWidth+k/8]
}
if b&0x80 == 0 {
frameBuffer[k] = BGCOLOR
frameBuffer[2*k] = byte(BGCOLOR >> 8)
frameBuffer[2*k+1] = byte(BGCOLOR & 0xFF)
} else {
frameBuffer[k] = GRIDCOLOR
frameBuffer[2*k] = byte(GRIDCOLOR >> 8)
frameBuffer[2*k+1] = byte(GRIDCOLOR & 0xFF)
}
}
display.DrawRGBBitmap(0, j, frameBuffer[0:w], w, 1)
display.DrawRGBBitmap8(0, j, frameBuffer[0:w*2], w, 1)
}
}
@@ -1,3 +1,4 @@
//go:build pyportal
// +build pyportal
package main
@@ -1,3 +1,4 @@
//go:build wioterminal
// +build wioterminal
package main
+1
View File
@@ -1,3 +1,4 @@
//go:build atsamd21
// +build atsamd21
package main
+1
View File
@@ -1,3 +1,4 @@
//go:build pyportal
// +build pyportal
package main
+1
View File
@@ -1,3 +1,4 @@
//go:build wioterminal
// +build wioterminal
package main
+18
View File
@@ -0,0 +1,18 @@
# examples/ili9341/slideshow
![](./slideshow.jpg)
This example uses the image package for TinyGo to display png and jpeg images.
## How to create an image
The following program will output an image binary like the one in [images.go](./images.go).
```
go run ./examples/ili9341/slideshow/convert2bin ./path/to/png_or_jpg.png
```
## Notes
Displaying a 320x240 png or jpeg often requires more than 50KB of memory.
The examples include samd21 settings, but if you run them as is, you will get a memory size error.
+30
View File
@@ -0,0 +1,30 @@
//go:build atsamd21
// +build atsamd21
package main
import (
"machine"
"tinygo.org/x/drivers/ili9341"
)
var (
display = ili9341.NewSPI(
machine.SPI0,
machine.D0,
machine.D1,
machine.D2,
)
backlight = machine.D3
)
func init() {
machine.SPI0.Configure(machine.SPIConfig{
SCK: machine.SPI0_SCK_PIN,
SDO: machine.SPI0_SDO_PIN,
SDI: machine.SPI0_SDI_PIN,
Frequency: 24000000,
})
}
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
package main
import (
"fmt"
"image/color"
"machine"
"strings"
"time"
"tinygo.org/x/drivers/ili9341"
"tinygo.org/x/drivers/image/jpeg"
"tinygo.org/x/drivers/image/png"
)
var (
black = color.RGBA{0, 0, 0, 255}
white = color.RGBA{255, 255, 255, 255}
red = color.RGBA{255, 0, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
green = color.RGBA{0, 255, 0, 255}
)
func main() {
err := run()
for err != nil {
errorMessage(err)
}
}
func run() error {
backlight.Configure(machine.PinConfig{machine.PinOutput})
display.Configure(ili9341.Config{})
width, height := display.Size()
if width < 320 || height < 240 {
display.SetRotation(ili9341.Rotation270)
}
display.FillScreen(black)
backlight.High()
for {
err := drawJpeg(display)
if err != nil {
return err
}
time.Sleep(time.Second)
err = drawPng(display)
if err != nil {
return err
}
time.Sleep(time.Second)
}
return nil
}
// Define the buffer required for the callback. In most cases, this setting
// should be sufficient. For jpeg, the callback will always be called every
// 3*8*8*4 pix. png will be called every line, i.e. every width pix.
var buffer [3 * 8 * 8 * 4]uint16
func drawPng(display *ili9341.Device) error {
p := strings.NewReader(pngImage)
png.SetCallback(buffer[:], func(data []uint16, x, y, w, h, width, height int16) {
err := display.DrawRGBBitmap(x, y, data[:w*h], w, h)
if err != nil {
errorMessage(fmt.Errorf("error drawPng: %s", err))
}
})
return png.Decode(p)
}
func drawJpeg(display *ili9341.Device) error {
p := strings.NewReader(jpegImage)
jpeg.SetCallback(buffer[:], func(data []uint16, x, y, w, h, width, height int16) {
err := display.DrawRGBBitmap(x, y, data[:w*h], w, h)
if err != nil {
errorMessage(fmt.Errorf("error drawJpeg: %s", err))
}
})
return jpeg.Decode(p)
}
func errorMessage(err error) {
for {
fmt.Printf("%s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
+23
View File
@@ -0,0 +1,23 @@
//go:build pyportal
// +build pyportal
package main
import (
"machine"
"tinygo.org/x/drivers/ili9341"
)
var (
display = ili9341.NewParallel(
machine.LCD_DATA0,
machine.TFT_WR,
machine.TFT_DC,
machine.TFT_CS,
machine.TFT_RESET,
machine.TFT_RD,
)
backlight = machine.TFT_BACKLIGHT
)
Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+30
View File
@@ -0,0 +1,30 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"machine"
"tinygo.org/x/drivers/ili9341"
)
var (
display = ili9341.NewSPI(
machine.SPI3,
machine.LCD_DC,
machine.LCD_SS_PIN,
machine.LCD_RESET,
)
backlight = machine.LCD_BACKLIGHT
)
func init() {
machine.SPI3.Configure(machine.SPIConfig{
SCK: machine.LCD_SCK_PIN,
SDO: machine.LCD_SDO_PIN,
SDI: machine.LCD_SDI_PIN,
Frequency: 40000000,
})
}
+63
View File
@@ -0,0 +1,63 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/ina260"
)
func main() {
machine.I2C0.Configure(machine.I2CConfig{})
dev := ina260.New(machine.I2C0)
dev.Configure(ina260.Config{
AverageMode: ina260.AVGMODE_16,
VoltConvTime: ina260.CONVTIME_140USEC,
CurrentConvTime: ina260.CONVTIME_140USEC,
Mode: ina260.MODE_CONTINUOUS | ina260.MODE_VOLTAGE | ina260.MODE_CURRENT,
})
if dev.Connected() {
println("INA260 detected")
} else {
println("INA260 NOT detected")
return
}
for {
microvolts := dev.Voltage()
microamps := dev.Current()
microwatts := dev.Power()
println(fmtD(microvolts, 4, 3), "mV,", fmtD(microamps, 4, 3), "mA,", fmtD(microwatts, 4, 3), "mW")
time.Sleep(10 * time.Millisecond)
}
}
func fmtD(val int32, i int, f int) string {
result := make([]byte, i+f+1)
neg := false
if val < 0 {
val = -val
neg = true
}
for p := len(result) - 1; p >= 0; p-- {
result[p] = byte(int32('0') + (val % 10))
val = val / 10
if p == i+1 && p > 0 {
p--
result[p] = '.'
}
}
if neg {
result[0] = '-'
}
return string(result)
}
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"machine"
"tinygo.org/x/drivers/keypad4x4"
)
func main() {
mapping := map[uint8]string{
1: "1",
2: "2",
3: "3",
4: "A",
5: "4",
6: "5",
7: "6",
8: "B",
9: "7",
10: "8",
11: "9",
12: "C",
13: "*",
14: "0",
15: "#",
16: "D",
}
keypadDevice := keypad4x4.NewDevice(machine.D2, machine.D3, machine.D4, machine.D5, machine.D6, machine.D7, machine.D8, machine.D9)
keypadDevice.Configure()
for {
key := keypadDevice.GetKey()
if key != keypad4x4.NoKeyPressed {
println("Button: ", mapping[key])
}
}
}
+18 -6
View File
@@ -8,19 +8,31 @@ import (
)
const (
maxSpeed = 30000
maxSpeed = 100
)
func main() {
machine.InitPWM()
err := machine.TCC0.Configure(machine.PWMConfig{
Period: 16384e3, // 16.384ms
})
if err != nil {
println(err.Error())
return
}
wheel := l293x.NewWithSpeed(machine.D10, machine.D11, machine.PWM{machine.D12})
spc, err := machine.TCC0.Channel(machine.D12)
if err != nil {
println(err.Error())
return
}
wheel := l293x.NewWithSpeed(machine.D10, machine.D11, spc, machine.TCC0)
wheel.Configure()
for i := 0; i <= 10; i++ {
println("Forward")
var i uint16
for i = 0; i < maxSpeed; i += 1000 {
var i uint32
for i = 0; i < maxSpeed; i += 10 {
wheel.Forward(i)
time.Sleep(time.Millisecond * 100)
}
@@ -30,7 +42,7 @@ func main() {
time.Sleep(time.Millisecond * 1000)
println("Backward")
for i = 0; i < maxSpeed; i += 1000 {
for i = 0; i < maxSpeed; i += 10 {
wheel.Backward(i)
time.Sleep(time.Millisecond * 100)
}
+25 -6
View File
@@ -8,19 +8,38 @@ import (
)
const (
maxSpeed = 30000
maxSpeed = 100
)
func main() {
machine.InitPWM()
machine.D11.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.D12.Configure(machine.PinConfig{Mode: machine.PinOutput})
wheel := l9110x.NewWithSpeed(machine.PWM{machine.D11}, machine.PWM{machine.D12})
err := machine.TCC0.Configure(machine.PWMConfig{})
if err != nil {
println(err.Error())
return
}
ca, err := machine.TCC0.Channel(machine.D11)
if err != nil {
println(err.Error())
return
}
cb, err := machine.TCC0.Channel(machine.D12)
if err != nil {
println(err.Error())
return
}
wheel := l9110x.NewWithSpeed(ca, cb, machine.TCC0)
wheel.Configure()
for i := 0; i <= 10; i++ {
println("Forward")
var i uint16
for i = 0; i < maxSpeed; i += 1000 {
var i uint32
for i = 0; i < maxSpeed; i += 10 {
wheel.Forward(i)
time.Sleep(time.Millisecond * 100)
}
@@ -30,7 +49,7 @@ func main() {
time.Sleep(time.Millisecond * 1000)
println("Backward")
for i = 0; i < maxSpeed; i += 1000 {
for i = 0; i < maxSpeed; i += 10 {
wheel.Backward(i)
time.Sleep(time.Millisecond * 100)
}
+108
View File
@@ -0,0 +1,108 @@
// Connects to an LSM6DSOX I2C a 6 axis Inertial Measurement Unit (IMU)
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/lsm6dsox"
)
const (
PLOTTER = true
SHOW_ACCELERATION = false
SHOW_ROTATION = true
SHOW_TEMPERATURE = false
// calibration is naive, good enough for a demo: do not shake a second after flashing
GYRO_CALIBRATION = true
)
var cal = [...]float32{0, 0, 0}
func main() {
machine.I2C0.Configure(machine.I2CConfig{})
device := lsm6dsox.New(machine.I2C0)
device.Configure(lsm6dsox.Configuration{
AccelRange: lsm6dsox.ACCEL_2G,
AccelSampleRate: lsm6dsox.ACCEL_SR_104,
GyroRange: lsm6dsox.GYRO_250DPS,
GyroSampleRate: lsm6dsox.GYRO_SR_104,
})
for {
if !device.Connected() {
println("LSM6DSOX not connected")
time.Sleep(time.Second)
continue
}
// heuristic: after successful calibration the value can't be 0
if GYRO_CALIBRATION && cal[0] == 0 {
calibrateGyro(device)
}
ax, ay, az := device.ReadAcceleration()
gx, gy, gz := device.ReadRotation()
t, _ := device.ReadTemperature()
if PLOTTER {
printPlotter(ax, ay, az, gx, gy, gz, t)
time.Sleep(time.Millisecond * 100)
} else {
printMonitor(ax, ay, az, gx, gy, gz, t)
time.Sleep(time.Millisecond * 1000)
}
}
}
func calibrateGyro(device *lsm6dsox.Device) {
for i := 0; i < 100; i++ {
gx, gy, gz := device.ReadRotation()
cal[0] += float32(gx) / 1000000
cal[1] += float32(gy) / 1000000
cal[2] += float32(gz) / 1000000
time.Sleep(time.Millisecond * 10)
}
cal[0] /= 100
cal[1] /= 100
cal[2] /= 100
}
// Arduino IDE's Serial Plotter
func printPlotter(ax, ay, az, gx, gy, gz, t int32) {
if SHOW_ACCELERATION {
fmt.Printf("AX:%f, AY:%f, AZ:%f,", axis(ax, 0), axis(ay, 0), axis(az, 0))
}
if SHOW_ROTATION {
fmt.Printf("GX:%f, GY:%f, GZ:%f,", axis(gx, cal[0]), axis(gy, cal[1]), axis(gz, cal[2]))
}
if SHOW_TEMPERATURE {
fmt.Printf("T:%f", float32(t)/1000)
}
println()
}
// Any Serial Monitor
func printMonitor(ax, ay, az, gx, gy, gz, t int32) {
if SHOW_ACCELERATION {
fmt.Printf("Acceleration: %f, %f, %f\r\n", axis(ax, 0), axis(ay, 0), axis(az, 0))
}
if SHOW_ROTATION {
fmt.Printf("Rotation: %f, %f, %f\r\n", axis(gx, cal[0]), axis(gy, cal[1]), axis(gz, cal[2]))
}
if SHOW_TEMPERATURE {
fmt.Printf("Temperature C: %f\r\n", float32(t)/1000)
}
println()
}
func axis(raw int32, cal float32) float32 {
return float32(raw)/1000000 - cal
}
+135
View File
@@ -0,0 +1,135 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/max72xx"
)
// example for a 4 digit 7 segment display
func main() {
// Pins for Arduino Nano 33 IOT
err := machine.SPI0.Configure(machine.SPIConfig{
SDO: machine.D11, // default SDO pin
SCK: machine.D13, // default sck pin
LSBFirst: false,
Frequency: 10000000,
})
if err != nil {
println(err.Error())
}
driver := max72xx.NewDevice(machine.SPI0, machine.D6)
driver.Configure()
digitNumber := 4
driver.StopDisplayTest()
driver.SetDecodeMode(4)
driver.SetScanLimit(4)
driver.StopShutdownMode()
for i := 1; i < int(digitNumber); i++ {
driver.WriteCommand(byte(i), byte(Blank))
}
for {
for _, character := range characters {
println("writing", "characterValue:", character.String())
driver.WriteCommand(byte(4), byte(character))
driver.WriteCommand(byte(3), byte(character))
driver.WriteCommand(byte(2), byte(character))
driver.WriteCommand(byte(1), byte(character))
time.Sleep(500 * time.Millisecond)
}
time.Sleep(time.Second)
}
}
var characters = []Character{
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Dash,
E,
H,
L,
P,
Blank,
Dot,
}
// Each bit translates to a pin, which is driven high or low
type Character byte
func (char Character) String() string {
switch char {
case Zero:
return "0"
case One:
return "1"
case Two:
return "2"
case Three:
return "3"
case Four:
return "4"
case Five:
return "5"
case Six:
return "6"
case Seven:
return "7"
case Eight:
return "8"
case Nine:
return "9"
case Dash:
return "-"
case E:
return "E"
case H:
return "H"
case L:
return "L"
case P:
return "P"
case Blank:
return ""
case Dot:
return "."
}
return ""
}
const (
Zero Character = 0 //126
One Character = 1 //48
Two Character = 2 // 109
Three Character = 3 // 121
Four Character = 4
Five Character = 5
Six Character = 6
Seven Character = 7
Eight Character = 8
Nine Character = 9
Dash Character = 10
E Character = 11
H Character = 12
L Character = 13
P Character = 14
Blank Character = 15
Dot Character = 128
)
+55
View File
@@ -0,0 +1,55 @@
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/mcp2515"
)
var (
spi = machine.SPI0
csPin = machine.D5
)
func main() {
spi.Configure(machine.SPIConfig{
Frequency: 115200,
SCK: machine.SPI0_SCK_PIN,
SDO: machine.SPI0_SDO_PIN,
SDI: machine.SPI0_SDI_PIN,
Mode: 0})
can := mcp2515.New(spi, csPin)
can.Configure()
err := can.Begin(mcp2515.CAN500kBps, mcp2515.Clock8MHz)
if err != nil {
failMessage(err.Error())
}
for {
err := can.Tx(0x111, 8, []byte{0x00, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA})
if err != nil {
failMessage(err.Error())
}
if can.Received() {
msg, err := can.Rx()
if err != nil {
failMessage(err.Error())
}
fmt.Printf("CAN-ID: %03X dlc: %d data: ", msg.ID, msg.Dlc)
for _, b := range msg.Data {
fmt.Printf("%02X ", b)
}
fmt.Print("\r\n")
}
time.Sleep(time.Millisecond * 500)
}
}
func failMessage(msg string) {
for {
println(msg)
time.Sleep(1 * time.Second)
}
}
+74
View File
@@ -0,0 +1,74 @@
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/p1am"
)
func main() {
for {
if err := loop(); err != nil {
fmt.Printf("loop failed, retrying: %v\n", err)
time.Sleep(500 * time.Millisecond)
}
}
}
func loop() error {
led := machine.LED
led.Configure(machine.PinConfig{Mode: machine.PinOutput})
sw := machine.SWITCH
sw.Configure(machine.PinConfig{Mode: machine.PinInput})
if err := p1am.Controller.Initialize(); err != nil {
return fmt.Errorf("initializing controller: %w", err)
}
version, err := p1am.Controller.Version()
if err != nil {
return fmt.Errorf("fetching base controller version: %w", err)
}
fmt.Printf("Base controller version: %d.%d.%d\n", version[0], version[1], version[2])
for i := 1; i <= p1am.Controller.Slots; i++ {
slot := p1am.Controller.Slot(i)
fmt.Printf("Slot %d: ID 0x%08x, Props %+v\n", i, slot.ID, slot.Props)
}
slot1 := p1am.Controller.Slot(1)
var lastInput uint32
state := sw.Get()
for {
if active, err := p1am.Controller.Active(); err != nil || !active {
return fmt.Errorf("controller active %v: %v", active, err)
}
if state != sw.Get() {
state = sw.Get()
fmt.Printf("New switch state: %v\n", state)
if slot1.Props.DO > 0 {
if err := slot1.Channel(1).WriteDiscrete(state); err != nil {
return err
}
}
}
if slot1.Props.DI > 0 {
sstate, err := slot1.ReadDiscrete()
if err != nil {
return fmt.Errorf("reading slot: %w", err)
}
if sstate != lastInput {
lastInput = sstate
fmt.Printf("new DI state: %#b\n", sstate)
}
}
if state {
led.High()
} else {
led.Low()
}
time.Sleep(time.Millisecond * 10)
}
return nil
}
+45
View File
@@ -0,0 +1,45 @@
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/pcf8563"
)
var (
i2c = machine.I2C0
rtc = pcf8563.New(i2c)
)
func main() {
i2c.Configure(machine.I2CConfig{Frequency: machine.TWI_FREQ_400KHZ})
rtc.Reset()
time.Sleep(3 * time.Second)
rtc.SetTime(time.Date(2006, 1, 2, 15, 4, 50, 0, time.UTC))
rtc.SetAlarm(time.Date(2006, 1, 2, 15, 5, 0, 0, time.UTC))
rtc.EnableAlarmInterrupt()
prev := -1
for {
for {
t, _ := rtc.ReadTime()
if prev != t.Second() {
fmt.Printf("%s\r\n", t.String())
prev = t.Second()
if rtc.AlarmTriggered() {
fmt.Printf("alarm triggered\r\n")
rtc.ClearAlarm()
}
break
}
time.Sleep(time.Millisecond * 100)
}
}
}
+31
View File
@@ -0,0 +1,31 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/pcf8563"
)
var (
i2c = machine.I2C0
rtc = pcf8563.New(i2c)
)
func main() {
i2c.Configure(machine.I2CConfig{Frequency: machine.TWI_FREQ_400KHZ})
rtc.Reset()
for {
rtc.SetOscillatorFrequency(pcf8563.RTC_COT_1HZ)
time.Sleep(3 * time.Second)
rtc.SetOscillatorFrequency(pcf8563.RTC_COT_32HZ)
time.Sleep(3 * time.Second)
rtc.SetOscillatorFrequency(pcf8563.RTC_COT_1KHZ)
time.Sleep(3 * time.Second)
rtc.SetOscillatorFrequency(pcf8563.RTC_COT_32KHZ)
time.Sleep(3 * time.Second)
rtc.SetOscillatorFrequency(pcf8563.RTC_COT_DISABLE)
time.Sleep(3 * time.Second)
}
}
+36
View File
@@ -0,0 +1,36 @@
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/pcf8563"
)
var (
i2c = machine.I2C0
rtc = pcf8563.New(i2c)
)
func main() {
i2c.Configure(machine.I2CConfig{Frequency: machine.TWI_FREQ_400KHZ})
rtc.Reset()
rtc.SetTime(time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC))
prev := -1
for {
for {
t, _ := rtc.ReadTime()
if prev != t.Second() {
fmt.Printf("%s\r\n", t.String())
prev = t.Second()
break
}
time.Sleep(time.Millisecond * 100)
}
}
}
+46
View File
@@ -0,0 +1,46 @@
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/pcf8563"
)
var (
i2c = machine.I2C0
rtc = pcf8563.New(i2c)
)
func main() {
i2c.Configure(machine.I2CConfig{Frequency: machine.TWI_FREQ_400KHZ})
rtc.Reset()
time.Sleep(3 * time.Second)
rtc.SetTime(time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC))
rtc.SetTimer(15 * time.Second)
rtc.EnableTimerInterrupt()
prev := -1
for {
for {
t, _ := rtc.ReadTime()
if prev != t.Second() {
fmt.Printf("%s\r\n", t.String())
prev = t.Second()
if rtc.TimerTriggered() {
fmt.Printf("timer triggered\r\n")
rtc.ClearTimer()
rtc.SetTimer(10 * time.Second)
}
break
}
time.Sleep(time.Millisecond * 100)
}
}
}
+131
View File
@@ -0,0 +1,131 @@
// This is a sensor station that uses a RTL8720DN running on the device UART2.
// It creates an MQTT connection that publishes a message every second
// to an MQTT broker.
//
// In other words:
// Your computer <--> USB-CDC <--> MCU <--> UART2 <--> RTL8720DN <--> Internet <--> MQTT broker.
//
// You must install the Paho MQTT package to build this program:
//
// go get -u github.com/eclipse/paho.mqtt.golang
//
// You can check that mqttpub is running successfully with the following command.
//
// mosquitto_sub -h test.mosquitto.org -t tinygo
//
package main
import (
"fmt"
"math/rand"
"time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/mqtt"
"tinygo.org/x/drivers/rtl8720dn"
)
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// debug = true
// server = "tinygo.org"
// }
var (
ssid string
password string
server string = "tcp://test.mosquitto.org:1883"
debug = false
)
var buf [0x400]byte
var lastRequestTime time.Time
var conn net.Conn
var adaptor *rtl8720dn.RTL8720DN
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
var (
topic = "tinygo"
)
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
rand.Seed(time.Now().UnixNano())
opts := mqtt.NewClientOptions()
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
println("Connectng to MQTT...")
cl := mqtt.NewClient(opts)
if token := cl.Connect(); token.Wait() && token.Error() != nil {
failMessage(token.Error().Error())
}
for i := 0; ; i++ {
println("Publishing MQTT message...")
data := []byte(fmt.Sprintf(`{"e":[{"n":"hello %d","v":101}]}`, i))
token := cl.Publish(topic, 0, false, data)
token.Wait()
if err := token.Error(); err != nil {
return err
}
time.Sleep(100 * time.Millisecond)
}
// Right now this code is never reached. Need a way to trigger it...
println("Disconnecting MQTT...")
cl.Disconnect(100)
println("Done.")
return nil
}
// Returns an int >= min, < max
func randomInt(min, max int) int {
return min + rand.Intn(max-min)
}
// Generate a random string of A-Z chars with len = l
func randomString(len int) string {
bytes := make([]byte, len)
for i := 0; i < len; i++ {
bytes[i] = byte(randomInt(65, 90))
}
return string(bytes)
}
func failMessage(msg string) {
for {
println(msg)
time.Sleep(1 * time.Second)
}
}
@@ -0,0 +1,74 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
if debug {
waitSerial()
}
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+154
View File
@@ -0,0 +1,154 @@
// This is a sensor station that uses a RTL8720DN running on the device UART2.
// It creates an MQTT connection that publishes a message every second
// to an MQTT broker.
//
// In other words:
// Your computer <--> USB-CDC <--> MCU <--> UART2 <--> RTL8720DN <--> Internet <--> MQTT broker.
//
// You must also install the Paho MQTT package to build this program:
//
// go get -u github.com/eclipse/paho.mqtt.golang
//
// You can check that mqttpub/mqttsub is running successfully with the following command.
//
// mosquitto_sub -h test.mosquitto.org -t tinygo/tx
// mosquitto_pub -h test.mosquitto.org -t tinygo/rx -m "hello world"
//
package main
import (
"fmt"
"math/rand"
"time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/mqtt"
"tinygo.org/x/drivers/rtl8720dn"
)
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// debug = true
// server = "tinygo.org"
// }
var (
ssid string
password string
server string = "tcp://test.mosquitto.org:1883"
debug = false
)
var buf [0x400]byte
var lastRequestTime time.Time
var conn net.Conn
var adaptor *rtl8720dn.RTL8720DN
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
// change these to connect to a different UART or pins for the ESP8266/ESP32
var (
cl mqtt.Client
topicTx = "tinygo/tx"
topicRx = "tinygo/rx"
)
func subHandler(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("[%s] ", msg.Topic())
fmt.Printf("%s\r\n", msg.Payload())
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
rand.Seed(time.Now().UnixNano())
opts := mqtt.NewClientOptions()
opts.AddBroker(server).SetClientID("tinygo-client-" + randomString(10))
println("Connecting to MQTT broker at", server)
cl = mqtt.NewClient(opts)
if token := cl.Connect(); token.Wait() && token.Error() != nil {
failMessage(token.Error().Error())
}
// subscribe
token := cl.Subscribe(topicRx, 0, subHandler)
token.Wait()
if token.Error() != nil {
failMessage(token.Error().Error())
}
go publishing()
select {}
// Right now this code is never reached. Need a way to trigger it...
println("Disconnecting MQTT...")
cl.Disconnect(100)
println("Done.")
return nil
}
func publishing() {
for i := 0; ; i++ {
println("Publishing MQTT message...")
data := []byte(fmt.Sprintf(`{"e":[{"n":"hello %d","v":101}]}`, i))
token := cl.Publish(topicTx, 0, false, data)
token.Wait()
if token.Error() != nil {
println(token.Error().Error())
}
time.Sleep(20 * 100 * time.Millisecond)
}
}
// Returns an int >= min, < max
func randomInt(min, max int) int {
return min + rand.Intn(max-min)
}
// Generate a random string of A-Z chars with len = l
func randomString(len int) string {
bytes := make([]byte, len)
for i := 0; i < len; i++ {
bytes[i] = byte(randomInt(65, 90))
}
return string(bytes)
}
func failMessage(msg string) {
for {
println(msg)
time.Sleep(1 * time.Second)
}
}
+74
View File
@@ -0,0 +1,74 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
if debug {
waitSerial()
}
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+144
View File
@@ -0,0 +1,144 @@
// This is an example of using the rtl8720dn driver to implement a NTP client.
// It creates a UDP connection to request the current time and parse the
// response from a NTP server.
package main
import (
"errors"
"fmt"
"runtime"
"time"
"tinygo.org/x/drivers/net"
)
// IP address of the server aka "hub". Replace with your own info.
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// ntpHost = "129.6.15.29"
// debug = true
// }
var (
ssid string
password string
ntpHost = "129.6.15.29"
debug = false
)
const NTP_PACKET_SIZE = 48
var b = make([]byte, NTP_PACKET_SIZE)
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
// now make UDP connection
hip := net.ParseIP(ntpHost)
raddr := &net.UDPAddr{IP: hip, Port: 123}
laddr := &net.UDPAddr{Port: 2390}
conn, err := net.DialUDP("udp", laddr, raddr)
if err != nil {
return err
}
for {
// send data
println("Requesting NTP time...")
t, err := getCurrentTime(conn)
if err != nil {
message("Error getting current time: %v", err)
} else {
message("NTP time: %v", t)
}
runtime.AdjustTimeOffset(-1 * int64(time.Since(t)))
for i := 0; i < 10; i++ {
message("Current time: %v", time.Now())
time.Sleep(1 * time.Second)
}
}
}
func getCurrentTime(conn *net.UDPSerialConn) (time.Time, error) {
if err := sendNTPpacket(conn); err != nil {
return time.Time{}, err
}
clearBuffer()
for now := time.Now(); time.Since(now) < time.Second; {
time.Sleep(5 * time.Millisecond)
if n, err := conn.Read(b); err != nil {
return time.Time{}, fmt.Errorf("error reading UDP packet: %w", err)
} else if n == 0 {
continue // no packet received yet
} else if n != NTP_PACKET_SIZE {
if n != NTP_PACKET_SIZE {
return time.Time{}, fmt.Errorf("expected NTP packet size of %d: %d", NTP_PACKET_SIZE, n)
}
}
return parseNTPpacket(), nil
}
return time.Time{}, errors.New("no packet received after 1 second")
}
func sendNTPpacket(conn *net.UDPSerialConn) error {
clearBuffer()
b[0] = 0b11100011 // LI, Version, Mode
b[1] = 0 // Stratum, or type of clock
b[2] = 6 // Polling Interval
b[3] = 0xEC // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
b[12] = 49
b[13] = 0x4E
b[14] = 49
b[15] = 52
if _, err := conn.Write(b); err != nil {
return err
}
return nil
}
func parseNTPpacket() time.Time {
// the timestamp starts at byte 40 of the received packet and is four bytes,
// this is NTP time (seconds since Jan 1 1900):
t := uint32(b[40])<<24 | uint32(b[41])<<16 | uint32(b[42])<<8 | uint32(b[43])
const seventyYears = 2208988800
return time.Unix(int64(t-seventyYears), 0)
}
func clearBuffer() {
for i := range b {
b[i] = 0
}
}
func message(format string, args ...interface{}) {
println(fmt.Sprintf(format, args...), "\r")
}
@@ -0,0 +1,72 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
waitSerial()
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+121
View File
@@ -0,0 +1,121 @@
// This example opens a TCP connection using a device with RTL8720DN firmware
// and sends some data, for the purpose of testing speed and connectivity.
//
// You can open a server to accept connections from this program using:
//
// nc -w 5 -lk 8080
//
package main
import (
"bytes"
"fmt"
"time"
"tinygo.org/x/drivers/net"
)
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "sghome-gw"
// password = "3af25537b4524"
// serverIP = "192.168.1.119"
// debug = true
// }
var (
ssid string
password string
serverIP = ""
debug = false
)
var buf = &bytes.Buffer{}
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
for {
sendBatch()
time.Sleep(500 * time.Millisecond)
}
println("Done.")
return nil
}
func sendBatch() {
// make TCP connection
ip := net.ParseIP(serverIP)
raddr := &net.TCPAddr{IP: ip, Port: 8080}
laddr := &net.TCPAddr{Port: 8080}
message("---------------\r\nDialing TCP connection")
conn, err := net.DialTCP("tcp", laddr, raddr)
for ; err != nil; conn, err = net.DialTCP("tcp", laddr, raddr) {
message(err.Error())
time.Sleep(5 * time.Second)
}
n := 0
w := 0
start := time.Now()
// send data
message("Sending data")
for i := 0; i < 1000; i++ {
buf.Reset()
fmt.Fprint(buf,
"\r---------------------------- i == ", i, " ----------------------------"+
"\r---------------------------- i == ", i, " ----------------------------")
if w, err = conn.Write(buf.Bytes()); err != nil {
println("error:", err.Error(), "\r")
continue
}
n += w
}
buf.Reset()
ms := time.Now().Sub(start).Milliseconds()
fmt.Fprint(buf, "\nWrote ", n, " bytes in ", ms, " ms\r\n")
message(buf.String())
if _, err := conn.Write(buf.Bytes()); err != nil {
println("error:", err.Error(), "\r")
}
// Right now this code is never reached. Need a way to trigger it...
println("Disconnecting TCP...")
conn.Close()
}
func message(msg string) {
println(msg, "\r")
}
@@ -0,0 +1,72 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
waitSerial()
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+137
View File
@@ -0,0 +1,137 @@
package main
import (
"bufio"
"fmt"
"strings"
"time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/http"
"tinygo.org/x/drivers/rtl8720dn"
)
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// debug = true
// url = "https://www.example.com"
// test_root_ca = "..."
// }
var (
ssid string
password string
url string = "https://www.example.com"
debug = false
)
// Set the test_root_ca created by the following command
// $ openssl s_client -showcerts -verify 5 -connect www.example.com:443 < /dev/null
var test_root_ca = `-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----
`
var buf [0x1000]byte
var lastRequestTime time.Time
var conn net.Conn
var adaptor *rtl8720dn.RTL8720DN
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
rtl.SetRootCA(&test_root_ca)
net.UseDriver(rtl)
http.SetBuf(buf[:])
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
// You can send and receive cookies in the following way
// import "tinygo.org/x/drivers/net/http/cookiejar"
// jar, err := cookiejar.New(nil)
// if err != nil {
// return err
// }
// client := &http.Client{Jar: jar}
// http.DefaultClient = client
cnt := 0
for {
// Various examples are as follows
//
// -- Get
// resp, err := http.Get(url)
//
// -- Post
// body := `cnt=12`
// resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(body))
//
// -- Post with JSON
// body := `{"msg": "hello"}`
// resp, err := http.Post(url, "application/json", strings.NewReader(body))
resp, err := http.Get(url)
if err != nil {
return err
}
fmt.Printf("%s %s\r\n", resp.Proto, resp.Status)
for k, v := range resp.Header {
fmt.Printf("%s: %s\r\n", k, strings.Join(v, " "))
}
fmt.Printf("\r\n")
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
fmt.Printf("%s\r\n", scanner.Text())
}
resp.Body.Close()
cnt++
fmt.Printf("-------- %d --------\r\n", cnt)
time.Sleep(10 * time.Second)
}
}
@@ -0,0 +1,72 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
waitSerial()
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+89
View File
@@ -0,0 +1,89 @@
package main
import (
"fmt"
"strconv"
"time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/http"
)
// IP address of the server aka "hub". Replace with your own info.
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// hubIP = "192.168.1.118"
// debug = true
// }
var (
ssid string
password string
hubIP = ""
debug = false
)
var buf [0x400]byte
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
http.SetBuf(buf[:])
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
// now make UDP connection
hip := net.ParseIP(hubIP)
raddr := &net.UDPAddr{IP: hip, Port: 2222}
laddr := &net.UDPAddr{Port: 2222}
println("Dialing UDP connection...")
conn, err := net.DialUDP("udp", laddr, raddr)
if err != nil {
return err
}
for {
// send data
println("Sending data...")
for i := 0; i < 25; i++ {
conn.Write([]byte("hello " + strconv.Itoa(i) + "\r\n"))
}
time.Sleep(1000 * time.Millisecond)
}
// Right now this code is never reached. Need a way to trigger it...
println("Disconnecting UDP...")
conn.Close()
println("Done.")
return nil
}
func message(msg string) {
println(msg, "\r")
}
@@ -0,0 +1,72 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
waitSerial()
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
@@ -0,0 +1,136 @@
package main
import (
"bufio"
"fmt"
"image/color"
"strings"
"time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/http"
"tinygo.org/x/tinyfont/proggy"
"tinygo.org/x/tinyterm"
)
// You can override the setting with the init() in another source code.
// If debug is enabled, a serial connection is required.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// debug = false // true
// server = "tinygo.org"
// }
var (
ssid string
password string
url = "http://tinygo.org/"
debug = false
)
var (
terminal = tinyterm.NewTerminal(display)
black = color.RGBA{0, 0, 0, 255}
white = color.RGBA{255, 255, 255, 255}
red = color.RGBA{255, 0, 0, 255}
blue = color.RGBA{0, 0, 255, 255}
green = color.RGBA{0, 255, 0, 255}
font = &proggy.TinySZ8pt7b
)
var buf [0x400]byte
func main() {
display.FillScreen(black)
backlight.High()
terminal.Configure(&tinyterm.Config{
Font: font,
FontHeight: 10,
FontOffset: 6,
})
err := run()
for err != nil {
fmt.Fprintf(terminal, "error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
fmt.Fprintf(terminal, "setupRTL8720DN()\r\n")
if debug {
fmt.Fprintf(terminal, "Running in debug mode.\r\n")
fmt.Fprintf(terminal, "A serial connection is required to continue execution.\r\n")
}
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
http.SetBuf(buf[:])
fmt.Fprintf(terminal, "ConnectToAP()\r\n")
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
fmt.Fprintf(terminal, "connected\r\n\r\n")
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Fprintf(terminal, "IP Address : %s\r\n", ip)
fmt.Fprintf(terminal, "Mask : %s\r\n", subnet)
fmt.Fprintf(terminal, "Gateway : %s\r\n", gateway)
// You can send and receive cookies in the following way
// import "tinygo.org/x/drivers/net/http/cookiejar"
// jar, err := cookiejar.New(nil)
// if err != nil {
// return err
// }
// client := &http.Client{Jar: jar}
// http.DefaultClient = client
cnt := 0
for {
// Various examples are as follows
//
// -- Get
// resp, err := http.Get(url)
//
// -- Post
// body := `cnt=12`
// resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(body))
//
// -- Post with JSON
// body := `{"msg": "hello"}`
// resp, err := http.Post(url, "application/json", strings.NewReader(body))
resp, err := http.Get(url)
if err != nil {
return err
}
fmt.Fprintf(terminal, "%s %s\r\n", resp.Proto, resp.Status)
for k, v := range resp.Header {
fmt.Fprintf(terminal, "%s: %s\r\n", k, strings.Join(v, " "))
}
fmt.Printf("\r\n")
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
fmt.Fprintf(terminal, "%s\r\n", scanner.Text())
}
resp.Body.Close()
cnt++
fmt.Fprintf(terminal, "-------- %d --------\r\n", cnt)
time.Sleep(10 * time.Second)
}
}
@@ -0,0 +1,98 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/ili9341"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
var (
display = ili9341.NewSPI(
machine.SPI3,
machine.LCD_DC,
machine.LCD_SS_PIN,
machine.LCD_RESET,
)
backlight = machine.LCD_BACKLIGHT
)
func init() {
machine.SPI3.Configure(machine.SPIConfig{
SCK: machine.LCD_SCK_PIN,
SDO: machine.LCD_SDO_PIN,
SDI: machine.LCD_SDI_PIN,
Frequency: 40000000,
})
display.Configure(ili9341.Config{})
backlight.Configure(machine.PinConfig{machine.PinOutput})
}
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
if debug {
waitSerial()
}
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+104
View File
@@ -0,0 +1,104 @@
package main
import (
"bufio"
"fmt"
"strings"
"time"
"tinygo.org/x/drivers/net"
"tinygo.org/x/drivers/net/http"
)
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// url = "http://tinygo.org/"
// debug = true
// }
var (
ssid string
password string
url = "http://tinygo.org/"
debug = false
)
var buf [0x400]byte
func main() {
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
net.UseDriver(rtl)
http.SetBuf(buf[:])
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
// You can send and receive cookies in the following way
// import "tinygo.org/x/drivers/net/http/cookiejar"
// jar, err := cookiejar.New(nil)
// if err != nil {
// return err
// }
// client := &http.Client{Jar: jar}
// http.DefaultClient = client
cnt := 0
for {
// Various examples are as follows
//
// -- Get
// resp, err := http.Get(url)
//
// -- Post
// body := `cnt=12`
// resp, err = http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(body))
//
// -- Post with JSON
// body := `{"msg": "hello"}`
// resp, err := http.Post(url, "application/json", strings.NewReader(body))
resp, err := http.Get(url)
if err != nil {
return err
}
fmt.Printf("%s %s\r\n", resp.Proto, resp.Status)
for k, v := range resp.Header {
fmt.Printf("%s: %s\r\n", k, strings.Join(v, " "))
}
fmt.Printf("\r\n")
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
fmt.Printf("%s\r\n", scanner.Text())
}
resp.Body.Close()
cnt++
fmt.Printf("-------- %d --------\r\n", cnt)
time.Sleep(10 * time.Second)
}
}
@@ -0,0 +1,72 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
waitSerial()
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+192
View File
@@ -0,0 +1,192 @@
package main
import (
"fmt"
"machine"
"strconv"
"time"
"tinygo.org/x/drivers/net/http"
)
// You can override the setting with the init() in another source code.
// func init() {
// ssid = "your-ssid"
// password = "your-password"
// debug = true
// }
var (
ssid string
password string
debug = false
)
var led = machine.LED
var backlight = machine.LCD_BACKLIGHT
func main() {
led.Configure(machine.PinConfig{Mode: machine.PinOutput})
backlight.Configure(machine.PinConfig{Mode: machine.PinOutput})
err := run()
for err != nil {
fmt.Printf("error: %s\r\n", err.Error())
time.Sleep(5 * time.Second)
}
}
func run() error {
rtl, err := setupRTL8720DN()
if err != nil {
return err
}
http.UseDriver(rtl)
err = rtl.ConnectToAP(ssid, password)
if err != nil {
return err
}
ip, subnet, gateway, err := rtl.GetIP()
if err != nil {
return err
}
fmt.Printf("IP Address : %s\r\n", ip)
fmt.Printf("Mask : %s\r\n", subnet)
fmt.Printf("Gateway : %s\r\n", gateway)
http.HandleFunc("/", root)
http.HandleFunc("/hello", hello)
http.HandleFunc("/cnt", cnt)
http.HandleFunc("/6", sixlines)
http.HandleFunc("/off", LED_OFF)
http.HandleFunc("/on", LED_ON)
if err := http.ListenAndServe(":80", nil); err != nil {
message(err.Error())
}
return nil
}
func root(w http.ResponseWriter, r *http.Request) {
access := 1
cookie, err := r.Cookie("access")
if err != nil {
if err == http.ErrNoCookie {
cookie = &http.Cookie{
Name: "access",
Value: "1",
}
} else {
http.Error(w, fmt.Sprintf("%s", err.Error()), http.StatusBadRequest)
return
}
} else {
v, err := strconv.ParseInt(cookie.Value, 10, 0)
if err != nil {
http.Error(w, fmt.Sprintf("invalid cookie.Value : %s", cookie.Value), http.StatusBadRequest)
return
}
cookie.Value = fmt.Sprintf("%d", v+1)
access = int(v) + 1
}
http.SetCookie(w, cookie)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
<html>
<head>
<title>TinyGo HTTP Server</title>
<script language="javascript" type="text/javascript">
var counter = 0
function ledOn() { fetch("/on").then(response => response.text()).then(text => { led.innerHTML = "<p>on</p>"; }); }
function ledOff() { fetch("/off").then(response => response.text()).then(text => { led.innerHTML = "<p>off</p>"; }); }
function fetchCnt() { fetch("/cnt").then(response => response.json()).then(json => { counter = json.cnt; cnt.innerHTML = counter; }); }
function incrCnt() { counter = counter + 1; fetch("/cnt?cnt=" + counter, { method: 'POST' }).then(response => response.json()).then(json => { counter = json.cnt; cnt.innerHTML = counter; }); }
function setCnt() { fetch("/cnt", {
method: "POST",
body: "cnt=" + document.getElementsByName("cnt")[0].value,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
}).then(response => response.json()).then(json => { counter = json.cnt; cnt.innerHTML = counter; }); return false; }
function onLoad() { fetchCnt(); }
</script>
</head>
<body onLoad="onLoad()">
<h5>TinyGo HTTP Server</h5>
<p>
access: %d
</p>
<a href="/hello">/hello</a><br>
<a href="/6">/6</a><br>
<p>
LED<br>
<a href="javascript:ledOn();">/on</a><br>
<a href="javascript:ledOff();">/off</a><br>
</p>
<p>
<a href="/cnt">/cnt</a><br>
cnt: <span id="cnt"></span><br>
<a href="javascript:incrCnt()">incrCnt()</a><br>
<form id="form1" style="display: inline" onSubmit="return setCnt()">
<input type="text" name="cnt">
<input type="button" value="set cnt", onClick="setCnt()">
</form>
</p>
</body>
</html>
`, access)
}
func sixlines(w http.ResponseWriter, r *http.Request) {
// https://fukuno.jig.jp/3267
fmt.Fprint(w, `<body onload='onkeydown=e=>K=parseInt(e.key[5]||6,28)/3-8;Z=X=[B=A=12];Y=_=>`+
`{for(C=[q=c=i=4];f=i--*K;c-=!Z[h+(K+6?p+K:C[i]=p*A-(p/9|0)*145)])p=B[i];for(c?0:K+6?h+=K:B=C;`+
`i=K=q--;f+=Z[A+p])X[p=h+B[q]]=1;h+=A;if(f|B)for(Z=X,X=[l=228],B=[[-7,-20,6,h=17,-9,3,3][t=++t%7]-4,0,1,t-6?-A:2];l--;)`+
`for(l%A?l-=l%A*!Z[l]:(P++,c=l+=A);--c>A;)Z[c]=Z[c-A];for(S="";i<240;S+=X[i]|(X[i]=Z[i]|=++i%A<2|i>228)?i%A?"■":"■<br>":" ");`+
`D.innerHTML=S+P;setTimeout(Y,i-P)};Y(h=K=t=P=0)'id=D>`)
}
func LED_ON(w http.ResponseWriter, r *http.Request) {
led.High()
backlight.High()
w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`)
fmt.Fprintf(w, "led.High()")
}
func LED_OFF(w http.ResponseWriter, r *http.Request) {
led.Low()
backlight.Low()
w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`)
fmt.Fprintf(w, "led.Low()")
}
func hello(w http.ResponseWriter, r *http.Request) {
w.Header().Set(`Content-Type`, `text/plain; charset=UTF-8`)
fmt.Fprintf(w, "hello")
}
var counter int
func cnt(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if r.Method == "POST" {
c := r.Form.Get("cnt")
if c != "" {
i64, _ := strconv.ParseInt(c, 0, 0)
counter = int(i64)
}
}
w.Header().Set(`Content-Type`, `application/json`)
fmt.Fprintf(w, `{"cnt": %d}`, counter)
}
func message(msg string) {
println(msg, "\r")
}
@@ -0,0 +1,74 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"device/sam"
"machine"
"runtime/interrupt"
"time"
"tinygo.org/x/drivers/rtl8720dn"
)
var (
uart UARTx
)
func handleInterrupt(interrupt.Interrupt) {
// should reset IRQ
uart.Receive(byte((uart.Bus.DATA.Get() & 0xFF)))
uart.Bus.INTFLAG.SetBits(sam.SERCOM_USART_INT_INTFLAG_RXC)
}
func setupRTL8720DN() (*rtl8720dn.RTL8720DN, error) {
machine.RTL8720D_CHIP_PU.Configure(machine.PinConfig{Mode: machine.PinOutput})
machine.RTL8720D_CHIP_PU.Low()
time.Sleep(100 * time.Millisecond)
machine.RTL8720D_CHIP_PU.High()
time.Sleep(1000 * time.Millisecond)
if debug {
waitSerial()
}
uart = UARTx{
UART: &machine.UART{
Buffer: machine.NewRingBuffer(),
Bus: sam.SERCOM0_USART_INT,
SERCOM: 0,
},
}
uart.Interrupt = interrupt.New(sam.IRQ_SERCOM0_2, handleInterrupt)
uart.Configure(machine.UARTConfig{TX: machine.PB24, RX: machine.PC24, BaudRate: 614400})
rtl := rtl8720dn.New(uart)
rtl.Debug(debug)
_, err := rtl.Rpc_tcpip_adapter_init()
if err != nil {
return nil, err
}
return rtl, nil
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
type UARTx struct {
*machine.UART
}
func (u UARTx) Read(p []byte) (n int, err error) {
if u.Buffered() == 0 {
time.Sleep(1 * time.Millisecond)
return 0, nil
}
return u.UART.Read(p)
}
+363
View File
@@ -0,0 +1,363 @@
package main
import (
"fmt"
"io"
"machine"
"os"
"strconv"
"strings"
"time"
"tinygo.org/x/drivers/sdcard"
)
const consoleBufLen = 64
const storageBufLen = 1024
var (
debug = false
input [consoleBufLen]byte
store [storageBufLen]byte
console = machine.Serial
dev *sdcard.Device
commands map[string]cmdfunc = map[string]cmdfunc{
"": cmdfunc(noop),
"help": cmdfunc(help),
"dbg": cmdfunc(dbg),
"erase": cmdfunc(erase),
"lsblk": cmdfunc(lsblk),
"write": cmdfunc(write),
"xxd": cmdfunc(xxd),
}
his history
)
type history struct {
buf [32]string
wp int
idx int
}
func (h *history) Add(cmd string) {
if len(cmd) == 0 {
h.idx = h.wp
return
}
if h.wp == len(h.buf)-1 {
for i := 1; i < len(h.buf); i++ {
h.buf[i-1] = h.buf[i]
}
h.wp--
}
h.buf[h.wp] = cmd
h.wp++
h.idx = h.wp
}
func (h *history) PeekPrev() string {
if h.idx > 0 {
h.idx--
}
return h.buf[h.idx]
}
func (h *history) PeekNext() string {
if h.idx < h.wp {
h.idx++
}
return h.buf[h.idx]
}
type cmdfunc func(argv []string)
const (
StateInput = iota
StateEscape
StateEscBrc
StateCSI
)
func RunFor(device *sdcard.Device) {
dev = device
prompt()
var state = StateInput
for i := 0; ; {
if console.Buffered() > 0 {
data, _ := console.ReadByte()
if debug {
fmt.Printf("\rdata: %x, his.idx: %d\r\n\r", data, his.idx)
prompt()
console.Write(input[:i])
}
switch state {
case StateInput:
switch data {
case 0x8:
fallthrough
case 0x7f: // this is probably wrong... works on my machine tho :)
// backspace
if i > 0 {
i -= 1
console.Write([]byte{0x8, 0x20, 0x8})
}
case 13:
// return key
console.Write([]byte("\r\n"))
runCommand(string(input[:i]))
his.Add(string(input[:i]))
prompt()
i = 0
continue
case 27:
// escape
state = StateEscape
default:
// anything else, just echo the character if it is printable
if strconv.IsPrint(rune(data)) {
if i < (consoleBufLen - 1) {
console.WriteByte(data)
input[i] = data
i++
}
}
}
case StateEscape:
switch data {
case 0x5b:
state = StateEscBrc
default:
state = StateInput
}
case StateEscBrc:
switch data {
case 0x41:
// up
println()
prompt()
cmd := his.PeekPrev()
i = len(cmd)
copy(input[:i], []byte(cmd))
console.Write(input[:i])
state = StateInput
case 0x42:
//down
println()
prompt()
cmd := his.PeekNext()
i = len(cmd)
copy(input[:i], []byte(cmd))
console.Write(input[:i])
state = StateInput
default:
// TODO: handle escape sequences
state = StateInput
}
default:
// TODO: handle escape sequences
state = StateInput
}
} else {
time.Sleep(1 * time.Millisecond)
}
}
}
func runCommand(line string) {
argv := strings.SplitN(strings.TrimSpace(line), " ", -1)
cmd := argv[0]
cmdfn, ok := commands[cmd]
if !ok {
println("unknown command: " + line)
return
}
cmdfn(argv)
}
func noop(argv []string) {}
func help(argv []string) {
fmt.Printf("help\r\n")
fmt.Printf("dbg\r\n")
fmt.Printf("erase\r\n")
fmt.Printf("lsblk\r\n")
fmt.Printf("write <hex offset> <bytes>\r\n")
fmt.Printf("xxd <start address> <length>\r\n")
}
func dbg(argv []string) {
if debug {
debug = false
println("Console debbuging off")
} else {
debug = true
println("Console debbuging on")
}
}
func lsblk(argv []string) {
csd := dev.CSD
sectors, err := csd.Sectors()
if err != nil {
fmt.Printf("%s\r\n", err.Error())
return
}
cid := dev.CID
fmt.Printf(
"\r\n-------------------------------------\r\n"+
" Device Information: \r\n"+
"-------------------------------------\r\n"+
" JEDEC ID: %v\r\n"+
" Serial: %v\r\n"+
" Status 1: %02x\r\n"+
" Status 2: %02x\r\n"+
" \r\n"+
" Max clock speed (MHz): %d\r\n"+
" Has Sector Protection: %t\r\n"+
" Supports Fast Reads: %t\r\n"+
" Supports QSPI Reads: %t\r\n"+
" Supports QSPI Write: %t\r\n"+
" Write Status Split: %t\r\n"+
" Single Status Byte: %t\r\n"+
"-Sectors: %d\r\n"+
"-Bytes (Sectors * 512) %d\r\n"+
"-ManufacturerID %02X\r\n"+
"-OEMApplicationID %04X\r\n"+
"-ProductName %s\r\n"+
"-ProductVersion %s\r\n"+
"-ProductSerialNumber %08X\r\n"+
"-ManufacturingYear %02X\r\n"+
"-ManufacturingMonth %02X\r\n"+
"-Always1 %d\r\n"+
"-CRC %02X\r\n"+
"-------------------------------------\r\n\r\n",
"attrs.JedecID", // attrs.JedecID,
cid.ProductSerialNumber, // serialNumber1,
0, // status1,
0, // status2,
csd.TRAN_SPEED, // attrs.MaxClockSpeedMHz,
false, // attrs.HasSectorProtection,
false, // attrs.SupportsFastRead,
false, // attrs.SupportsQSPI,
false, // attrs.SupportsQSPIWrites,
false, // attrs.WriteStatusSplit,
false, // attrs.SingleStatusByte,
sectors,
csd.Size(),
cid.ManufacturerID,
cid.OEMApplicationID,
cid.ProductName,
cid.ProductVersion,
cid.ProductSerialNumber,
cid.ManufacturingYear,
cid.ManufacturingMonth,
cid.Always1,
cid.CRC,
)
}
func erase(argv []string) {
fmt.Printf("erase - not impl\r\n")
}
var writeBuf [256]byte
func write(argv []string) {
if len(argv) < 3 {
println("usage: write <hex offset> <bytes>")
return
}
var err error
var addr uint64 = 0x0
if addr, err = strconv.ParseUint(argv[1], 16, 32); err != nil {
println("Invalid address: " + err.Error() + "\r\n")
return
}
buf := writeBuf[:0]
for i := 0; i < len(argv[2]); i += 2 {
var b uint64
if b, err = strconv.ParseUint(argv[2][i:i+2], 16, 8); err != nil {
println("Invalid bytes: " + err.Error() + "\r\n")
return
}
buf = append(buf, byte(b))
}
if _, err = dev.WriteAt(buf, int64(addr)); err != nil {
println("Write error: " + err.Error() + "\r\n")
}
}
func xxd(argv []string) {
var err error
var addr uint64 = 0x0
var size int = 64
switch len(argv) {
case 3:
if size, err = strconv.Atoi(argv[2]); err != nil {
println("Invalid size argument: " + err.Error() + "\r\n")
return
}
if size > storageBufLen || size < 1 {
fmt.Printf("Size of hexdump must be greater than 0 and less than %d\r\n", storageBufLen)
return
}
fallthrough
case 2:
if addr, err = strconv.ParseUint(argv[1], 16, 32); err != nil {
println("Invalid address: " + err.Error() + "\r\n")
return
}
fallthrough
case 1:
// no args supplied, so nothing to do here, just use the defaults
default:
println("usage: xxd <hex address, ex: 0xA0> <size of hexdump in bytes>\r\n")
return
}
buf := store[0:size]
_, err = dev.ReadAt(buf, int64(addr))
if err != nil {
fmt.Printf("xxd err : %s\r\n", err.Error())
}
xxdfprint(os.Stdout, uint32(addr), buf)
}
func xxdfprint(w io.Writer, offset uint32, b []byte) {
var l int
var buf16 = make([]byte, 16)
for i, c := 0, len(b); i < c; i += 16 {
l = i + 16
if l >= c {
l = c
}
fmt.Fprintf(w, "%08x: % x ", offset+uint32(i), b[i:l])
for j, n := 0, l-i; j < 16; j++ {
if j >= n || !strconv.IsPrint(rune(b[i+j])) || b[i+j] >= 0x80 {
buf16[j] = '.'
} else {
buf16[j] = b[i+j]
}
}
console.Write(buf16)
println()
}
}
func prompt() {
print("==> ")
}
+18
View File
@@ -0,0 +1,18 @@
//go:build feather_m4 || feather_m4_can || feather_nrf52840
// +build feather_m4 feather_m4_can feather_nrf52840
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D10
ledPin = machine.LED
}
@@ -0,0 +1,18 @@
//go:build grandcentral_m4
// +build grandcentral_m4
package main
import (
"machine"
)
func init() {
spi = machine.SPI1
sckPin = machine.SDCARD_SCK_PIN
sdoPin = machine.SDCARD_SDO_PIN
sdiPin = machine.SDCARD_SDI_PIN
csPin = machine.SDCARD_CS_PIN
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build atsamd21 && !p1am_100
// +build atsamd21,!p1am_100
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D2
ledPin = machine.LED
}
+51
View File
@@ -0,0 +1,51 @@
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/sdcard"
)
var (
spi machine.SPI
sckPin machine.Pin
sdoPin machine.Pin
sdiPin machine.Pin
csPin machine.Pin
ledPin machine.Pin
)
func main() {
waitSerial()
fmt.Printf("sdcard console\r\n")
led := ledPin
led.Configure(machine.PinConfig{Mode: machine.PinOutput})
sd := sdcard.New(spi, sckPin, sdoPin, sdiPin, csPin)
err := sd.Configure()
if err != nil {
fmt.Printf("%s\r\n", err.Error())
for {
time.Sleep(time.Hour)
}
}
go RunFor(&sd)
for {
led.High()
time.Sleep(200 * time.Millisecond)
led.Low()
time.Sleep(200 * time.Millisecond)
}
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
+18
View File
@@ -0,0 +1,18 @@
//go:build p1am_100
// +build p1am_100
package main
import (
"machine"
)
func init() {
spi = machine.SDCARD_SPI
sckPin = machine.SDCARD_SCK_PIN
sdoPin = machine.SDCARD_SDO_PIN
sdiPin = machine.SDCARD_SDI_PIN
csPin = machine.SDCARD_SS_PIN
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build pygamer
// +build pygamer
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D4
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build pyportal
// +build pyportal
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D32 // SD_CS
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"machine"
)
func init() {
spi = machine.SPI2
sckPin = machine.SCK2
sdoPin = machine.SDO2
sdiPin = machine.SDI2
csPin = machine.SS2
ledPin = machine.LED
}
+543
View File
@@ -0,0 +1,543 @@
//go:build tinygo
// +build tinygo
package console
import (
"fmt"
"io"
"machine"
"os"
"strconv"
"strings"
"time"
"tinygo.org/x/tinyfs"
)
const consoleBufLen = 64
const startBlock = 0
const blockCount = 0
var (
debug = false
input [consoleBufLen]byte
console = machine.Serial
readyLED = machine.LED
flashdev tinyfs.BlockDevice
fs tinyfs.Filesystem
currdir = "/"
commands = map[string]cmdfunc{
"": noop,
"dbg": dbg,
"help": help,
"lsblk": lsblk,
"mount": mount,
"umount": umount,
"format": format,
"xxd": xxd,
"ls": ls,
"samples": samples,
"mkdir": mkdir,
"cat": cat,
"create": create,
"write": write,
"rm": rm,
}
)
type cmdfunc func(argv []string)
const (
StateInput = iota
StateEscape
StateEscBrc
StateCSI
)
func RunFor(dev tinyfs.BlockDevice, filesys tinyfs.Filesystem) {
flashdev = dev
fs = filesys
readyLED.Configure(machine.PinConfig{Mode: machine.PinOutput})
readyLED.High()
readyLED.Low()
println("SPI Configured. Reading flash info")
/*
lfsConfig := flashlfs.NewConfig()
if blockCount == 0 {
lfsConfig.BlockCount = (flashdev.Attrs().TotalSize / lfsConfig.BlockSize) - startBlock
} else {
lfsConfig.BlockCount = blockCount
}
println("Start block:", startBlock)
println("Block count:", lfsConfig.BlockCount)
blockdev = flashlfs.NewBlockDevice(flashdev, startBlock, lfsConfig.BlockSize)
*/
prompt()
var state = StateInput
for i := 0; ; {
if console.Buffered() > 0 {
data, _ := console.ReadByte()
if debug {
fmt.Printf("\rdata: %x\r\n\r", data)
prompt()
console.Write(input[:i])
}
switch state {
case StateInput:
switch data {
case 0x8:
fallthrough
case 0x7f: // this is probably wrong... works on my machine tho :)
// backspace
if i > 0 {
i -= 1
console.Write([]byte{0x8, 0x20, 0x8})
}
case 13:
// return key
if console.Buffered() > 0 {
data, _ := console.ReadByte()
if data != 10 {
println("\r\nunexpected: \r", int(data))
}
}
console.Write([]byte("\r\n"))
runCommand(string(input[:i]))
prompt()
i = 0
continue
case 27:
// escape
state = StateEscape
default:
// anything else, just echo the character if it is printable
if strconv.IsPrint(rune(data)) {
if i < (consoleBufLen - 1) {
console.WriteByte(data)
input[i] = data
i++
}
}
}
case StateEscape:
switch data {
case 0x5b:
state = StateEscBrc
default:
state = StateInput
}
default:
// TODO: handle escape sequences
state = StateInput
}
}
}
}
func runCommand(line string) {
argv := strings.SplitN(strings.TrimSpace(line), " ", -1)
cmd := argv[0]
cmdfn, ok := commands[cmd]
if !ok {
println("unknown command: " + line)
return
}
cmdfn(argv)
}
func noop(argv []string) {}
func help(argv []string) {
fmt.Printf("help\r\n")
fmt.Printf(" show help\r\n")
fmt.Printf("dbg\r\n")
fmt.Printf(" toggle debug mode\r\n")
fmt.Printf("xxd <hex address, ex: 0xA0> <size of hexdump in bytes>\r\n")
fmt.Printf(" hexdump the specified address\r\n")
fmt.Printf("ls <target file>\r\n")
fmt.Printf(" list information\r\n")
fmt.Printf("samples\r\n")
fmt.Printf(" write some files in the root directory\r\n")
fmt.Printf("mkdir <target dir>\r\n")
fmt.Printf(" create directory\r\n")
fmt.Printf("cat <target file>\r\n")
fmt.Printf(" print the contents of file\r\n")
fmt.Printf("create <target file>\r\n")
fmt.Printf(" create file\r\n")
fmt.Printf("write <target file>\r\n")
fmt.Printf(" write to file (press CTRL-D to exit)\r\n")
fmt.Printf("rm\r\n")
}
func dbg(argv []string) {
if debug {
debug = false
println("Console debugging off")
} else {
debug = true
println("Console debugging on")
}
}
func lsblk(argv []string) {
fmt.Printf("lsblk : not implement\r\n")
}
func mount(argv []string) {
if err := fs.Mount(); err != nil {
println("Could not mount LittleFS filesystem: " + err.Error() + "\r\n")
} else {
println("Successfully mounted LittleFS filesystem.\r\n")
}
}
func format(argv []string) {
if err := fs.Format(); err != nil {
println("Could not format LittleFS filesystem: " + err.Error() + "\r\n")
} else {
println("Successfully formatted LittleFS filesystem.\r\n")
}
}
func umount(argv []string) {
if err := fs.Unmount(); err != nil {
println("Could not unmount LittleFS filesystem: " + err.Error() + "\r\n")
} else {
println("Successfully unmounted LittleFS filesystem.\r\n")
}
}
/*
var err error
if fatfs == nil {
fatfs, err = fat.New(fatdisk)
if err != nil {
fatfs = nil
println("could not load FAT filesystem: " + err.Error() + "\r\n")
}
fmt.Printf("loaded fs\r\n")
}
if rootdir == nil {
rootdir, err = fatfs.RootDir()
if err != nil {
rootdir = nil
println("could not load rootdir: " + err.Error() + "\r\n")
}
fmt.Printf("loaded rootdir\r\n")
}
if currdir == nil {
currdir = rootdir
}
*/
func ls(argv []string) {
path := "/"
if len(argv) > 1 {
path = strings.TrimSpace(argv[1])
}
dir, err := fs.Open(path)
if err != nil {
fmt.Printf("Could not open directory %s: %v\r\n", path, err)
return
}
defer dir.Close()
infos, err := dir.Readdir(0)
_ = infos
if err != nil {
fmt.Printf("Could not read directory %s: %v\r\n", path, err)
return
}
for _, info := range infos {
s := "-rwxrwxrwx"
if info.IsDir() {
s = "drwxrwxrwx"
}
fmt.Printf("%s %5d %s\r\n", s, info.Size(), info.Name())
}
}
func mkdir(argv []string) {
tgt := ""
if len(argv) == 2 {
tgt = strings.TrimSpace(argv[1])
}
if debug {
println("Trying mkdir to " + tgt)
}
if tgt == "" {
println("Usage: mkdir <target dir>")
return
}
err := fs.Mkdir(tgt, 0777)
if err != nil {
println("Could not mkdir " + tgt + ": " + err.Error())
}
}
func rm(argv []string) {
tgt := ""
if len(argv) == 2 {
tgt = strings.TrimSpace(argv[1])
}
if debug {
println("Trying rm to " + tgt)
}
if tgt == "" {
println("Usage: rm <target dir>")
return
}
err := fs.Remove(tgt)
if err != nil {
println("Could not rm " + tgt + ": " + err.Error())
}
}
func samples(argv []string) {
buf := make([]byte, 90)
for i := 0; i < 5; i++ {
name := fmt.Sprintf("file%d.txt", i)
if bytes, err := createSampleFile(name, buf); err != nil {
fmt.Printf("%s\r\n", err)
return
} else {
fmt.Printf("wrote %d bytes to %s\r\n", bytes, name)
}
}
}
func create(argv []string) {
tgt := ""
if len(argv) == 2 {
tgt = strings.TrimSpace(argv[1])
}
if debug {
println("Trying create to " + tgt)
}
buf := make([]byte, 90)
if bytes, err := createSampleFile(tgt, buf); err != nil {
fmt.Printf("%s\r\n", err)
return
} else {
fmt.Printf("wrote %d bytes to %s\r\n", bytes, tgt)
}
}
func write(argv []string) {
tgt := ""
if len(argv) == 2 {
tgt = strings.TrimSpace(argv[1])
}
if debug {
println("Trying receive to " + tgt)
}
buf := make([]byte, 1)
f, err := fs.OpenFile(tgt, os.O_CREATE|os.O_WRONLY|os.O_TRUNC)
if err != nil {
fmt.Printf("error opening %s: %s\r\n", tgt, err.Error())
return
}
defer f.Close()
var n int
for {
if console.Buffered() > 0 {
data, _ := console.ReadByte()
switch data {
case 0x04:
fmt.Printf("wrote %d bytes to %s\r\n", n, tgt)
return
default:
// anything else, just echo the character if it is printable
if strconv.IsPrint(rune(data)) {
console.WriteByte(data)
}
buf[0] = data
if _, err := f.Write(buf); err != nil {
fmt.Printf("\nerror writing: %s\r\n", err)
return
}
n++
}
}
}
}
func createSampleFile(name string, buf []byte) (int, error) {
for j := uint8(0); j < uint8(len(buf)); j++ {
buf[j] = 0x20 + j
}
f, err := fs.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC)
if err != nil {
return 0, fmt.Errorf("error opening %s: %s", name, err.Error())
}
defer f.Close()
bytes, err := f.Write(buf)
if err != nil {
return 0, fmt.Errorf("error writing %s: %s", name, err.Error())
}
return bytes, nil
}
/*
func cd(argv []string) {
if fatfs == nil || rootdir == nil {
mnt(nil)
}
if len(argv) == 1 {
currdir = rootdir
return
}
tgt := ""
if len(argv) == 2 {
tgt = strings.TrimSpace(argv[1])
}
if debug {
println("Trying to cd to " + tgt)
}
if tgt == "" {
println("Usage: cd <target dir>")
return
}
if debug {
println("Getting entry")
}
entry := currdir.Entry(tgt)
if entry == nil {
println("File not found: " + tgt)
return
}
if !entry.IsDir() {
println("Not a directory: " + tgt)
return
}
if debug {
println("Getting dir")
}
cd, err := entry.Dir()
if err != nil {
println("Could not cd to " + tgt + ": " + err.Error())
}
currdir = cd
}
*/
func cat(argv []string) {
tgt := ""
if len(argv) == 2 {
tgt = strings.TrimSpace(argv[1])
}
if debug {
println("Trying to cat to " + tgt)
}
if tgt == "" {
println("Usage: cat <target file>")
return
}
if debug {
println("Getting entry")
}
f, err := fs.Open(tgt)
if err != nil {
println("Could not open: " + err.Error())
return
}
defer f.Close()
if f.IsDir() {
println("Not a file: " + tgt)
return
}
off := 0x0
buf := make([]byte, 64)
for {
n, err := f.Read(buf)
if err != nil {
if err == io.EOF {
break
}
println("Error reading " + tgt + ": " + err.Error())
time.Sleep(1 * time.Second)
}
xxdfprint(os.Stdout, uint32(off), buf[:n])
off += n
}
}
func xxd(argv []string) {
var err error
var addr uint64 = 0x0
var size int = 64
switch len(argv) {
case 3:
if size, err = strconv.Atoi(argv[2]); err != nil {
println("Invalid size argument: " + err.Error() + "\r\n")
return
}
if size > 512 || size < 1 {
fmt.Printf("Size of hexdump must be greater than 0 and less than %d\r\n", 512)
return
}
fallthrough
case 2:
/*
if argv[1][:2] != "0x" {
println("Invalid hex address (should start with 0x)")
return
}
*/
if addr, err = strconv.ParseUint(argv[1], 16, 32); err != nil {
println("Invalid address: " + err.Error() + "\r\n")
return
}
fallthrough
case 1:
// no args supplied, so nothing to do here, just use the defaults
default:
println("usage: xxd <hex address, ex: 0xA0> <size of hexdump in bytes>\r\n")
return
}
buf := make([]byte, size)
//bsz := uint64(flash.SectorSize)
//blockdev.ReadBlock(uint32(addr/bsz), uint32(addr%bsz), buf)
flashdev.ReadAt(buf, int64(addr))
xxdfprint(os.Stdout, uint32(addr), buf)
}
func xxdfprint(w io.Writer, offset uint32, b []byte) {
var l int
var buf16 = make([]byte, 16)
for i, c := 0, len(b); i < c; i += 16 {
l = i + 16
if l >= c {
l = c
}
fmt.Fprintf(w, "%08x: % x ", offset+uint32(i), b[i:l])
for j, n := 0, l-i; j < 16; j++ {
if j >= n || !strconv.IsPrint(rune(b[i+j])) || b[i+j] >= 0x80 {
buf16[j] = '.'
} else {
buf16[j] = b[i+j]
}
}
console.Write(buf16)
println()
}
}
func prompt() {
print("==> ")
}
+18
View File
@@ -0,0 +1,18 @@
//go:build feather_m4 || feather_m4_can || feather_nrf52840
// +build feather_m4 feather_m4_can feather_nrf52840
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D10
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build grandcentral_m4
// +build grandcentral_m4
package main
import (
"machine"
)
func init() {
spi = machine.SPI1
sckPin = machine.SDCARD_SCK_PIN
sdoPin = machine.SDCARD_SDO_PIN
sdiPin = machine.SDCARD_SDI_PIN
csPin = machine.SDCARD_CS_PIN
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build atsamd21 && !p1am_100
// +build atsamd21,!p1am_100
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D2
ledPin = machine.LED
}
+49
View File
@@ -0,0 +1,49 @@
package main
import (
"fmt"
"machine"
"time"
"tinygo.org/x/drivers/examples/sdcard/tinyfs/console"
"tinygo.org/x/drivers/sdcard"
"tinygo.org/x/tinyfs/fatfs"
)
var (
spi machine.SPI
sckPin machine.Pin
sdoPin machine.Pin
sdiPin machine.Pin
csPin machine.Pin
ledPin machine.Pin
)
func main() {
waitSerial()
sd := sdcard.New(spi, sckPin, sdoPin, sdiPin, csPin)
err := sd.Configure()
if err != nil {
fmt.Printf("%s\r\n", err.Error())
for {
time.Sleep(time.Hour)
}
}
filesystem := fatfs.New(&sd)
// Configure FATFS with sector size (must match value in ff.h - use 512)
filesystem.Configure(&fatfs.Config{
SectorSize: 512,
})
console.RunFor(&sd, filesystem)
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
+18
View File
@@ -0,0 +1,18 @@
//go:build p1am_100
// +build p1am_100
package main
import (
"machine"
)
func init() {
spi = machine.SDCARD_SPI
sckPin = machine.SDCARD_SCK_PIN
sdoPin = machine.SDCARD_SDO_PIN
sdiPin = machine.SDCARD_SDI_PIN
csPin = machine.SDCARD_SS_PIN
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build pygamer
// +build pygamer
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D4
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build pyportal
// +build pyportal
package main
import (
"machine"
)
func init() {
spi = machine.SPI0
sckPin = machine.SPI0_SCK_PIN
sdoPin = machine.SPI0_SDO_PIN
sdiPin = machine.SPI0_SDI_PIN
csPin = machine.D32 // SD_CS
ledPin = machine.LED
}
+18
View File
@@ -0,0 +1,18 @@
//go:build wioterminal
// +build wioterminal
package main
import (
"machine"
)
func init() {
spi = machine.SPI2
sckPin = machine.SCK2
sdoPin = machine.SDO2
sdiPin = machine.SDI2
csPin = machine.SS2
ledPin = machine.LED
}
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/servo"
)
// Configuration for the Arduino Uno.
// Please change the PWM and pin if you want to try this example on a different
// board.
var (
pwm = machine.Timer1
pin = machine.D9
)
func main() {
s, err := servo.New(pwm, pin)
if err != nil {
for {
println("could not configure servo")
time.Sleep(time.Second)
}
return
}
println("setting to 0°")
s.SetMicroseconds(1000)
time.Sleep(3 * time.Second)
println("setting to 45°")
s.SetMicroseconds(1500)
time.Sleep(3 * time.Second)
println("setting to 90°")
s.SetMicroseconds(2000)
time.Sleep(3 * time.Second)
for {
time.Sleep(time.Second)
}
}
+60
View File
@@ -0,0 +1,60 @@
// This example shows how to use 128x64 display over I2C
// Tested on Seeeduino XIAO Expansion Board https://wiki.seeedstudio.com/Seeeduino-XIAO-Expansion-Board/
//
// According to manual, I2C address of the display is 0x78, but that's 8-bit address.
// TinyGo operates on 7-bit addresses and respective 7-bit address would be 0x3C, which we use below.
//
// To learn more about different types of I2C addresses, please see following page
// https://www.totalphase.com/support/articles/200349176-7-bit-8-bit-and-10-bit-I2C-Slave-Addressing
package main
import (
"machine"
"image/color"
"time"
"tinygo.org/x/drivers/ssd1306"
)
func main() {
machine.I2C0.Configure(machine.I2CConfig{
Frequency: machine.TWI_FREQ_400KHZ,
})
display := ssd1306.NewI2C(machine.I2C0)
display.Configure(ssd1306.Config{
Address: 0x3C,
Width: 128,
Height: 64,
})
display.ClearDisplay()
x := int16(0)
y := int16(0)
deltaX := int16(1)
deltaY := int16(1)
for {
pixel := display.GetPixel(x, y)
c := color.RGBA{255, 255, 255, 255}
if pixel {
c = color.RGBA{0, 0, 0, 255}
}
display.SetPixel(x, y, c)
display.Display()
x += deltaX
y += deltaY
if x == 0 || x == 127 {
deltaX = -deltaX
}
if y == 0 || y == 63 {
deltaY = -deltaY
}
time.Sleep(1 * time.Millisecond)
}
}
+40
View File
@@ -0,0 +1,40 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/tm1637"
)
func main() {
tm := tm1637.New(machine.D2, machine.D3, 7) // clk, dio, brightness
tm.Configure()
tm.ClearDisplay()
tm.DisplayText([]byte("Tiny"))
time.Sleep(time.Millisecond * 1000)
tm.ClearDisplay()
tm.DisplayChr(byte('G'), 1)
tm.DisplayDigit(0, 2) // looks like O
time.Sleep(time.Millisecond * 1000)
tm.DisplayClock(12, 59, true)
for i := uint8(0); i < 8; i++ {
tm.Brightness(i)
time.Sleep(time.Millisecond * 200)
}
i := int16(0)
for {
tm.DisplayNumber(i)
i++
time.Sleep(time.Millisecond * 50)
}
}
+33
View File
@@ -0,0 +1,33 @@
package main
import (
"machine"
"time"
"tinygo.org/x/drivers/tone"
)
var (
// Configuration for the Adafruit Circuit Playground Bluefruit.
pwm = machine.PWM0
pin = machine.D12
)
func main() {
speaker, err := tone.New(pwm, pin)
if err != nil {
println("failed to configure PWM")
return
}
// Two tone siren.
for {
println("nee")
speaker.SetNote(tone.B5)
time.Sleep(time.Second / 2)
println("naw")
speaker.SetNote(tone.A5)
time.Sleep(time.Second / 2)
}
}
+146
View File
@@ -0,0 +1,146 @@
// This example connects to Access Point and prints some info
package main
import (
"machine"
"strconv"
"time"
"tinygo.org/x/drivers/wifinina"
)
// access point info
const ssid = ""
const pass = ""
// these are the default pins for the Arduino Nano33 IoT.
// change these to connect to a different UART or pins for the ESP8266/ESP32
var (
// these are the default pins for the Arduino Nano33 IoT.
spi = machine.NINA_SPI
// this is the ESP chip that has the WIFININA firmware flashed on it
adaptor *wifinina.Device
)
func setup() {
// Configure SPI for 8Mhz, Mode 0, MSB First
spi.Configure(machine.SPIConfig{
Frequency: 8 * 1e6,
SDO: machine.NINA_SDO,
SDI: machine.NINA_SDI,
SCK: machine.NINA_SCK,
})
adaptor = wifinina.New(spi,
machine.NINA_CS,
machine.NINA_ACK,
machine.NINA_GPIO0,
machine.NINA_RESETN)
adaptor.Configure()
}
func main() {
setup()
waitSerial()
connectToAP()
for {
println("----------------------------------------")
printSSID()
printRSSI()
printMac()
printIPs()
printTime()
time.Sleep(10 * time.Second)
}
}
func printSSID() {
print("SSID: ")
ssid, err := adaptor.GetCurrentSSID()
if err != nil {
println("Unknown (error: ", err.Error(), ")")
return
}
println(ssid)
}
func printRSSI() {
print("RSSI: ")
rssi, err := adaptor.GetCurrentRSSI()
if err != nil {
println("Unknown (error: ", err.Error(), ")")
return
}
println(strconv.Itoa(int(rssi)))
}
func printIPs() {
ip, subnet, gateway, err := adaptor.GetIP()
if err != nil {
println("IP: Unknown (error: ", err.Error(), ")")
return
}
println("IP: ", ip.String())
println("Subnet: ", subnet.String())
println("Gateway: ", gateway.String())
}
func printTime() {
print("Time: ")
t, err := adaptor.GetTime()
for {
if err != nil {
println("Unknown (error: ", err.Error(), ")")
return
}
if t != 0 {
break
}
time.Sleep(time.Second)
t, err = adaptor.GetTime()
}
println(time.Unix(int64(t), 0).String())
}
func printMac() {
print("MAC: ")
mac, err := adaptor.GetMACAddress()
if err != nil {
println("Unknown (", err.Error(), ")")
}
println(mac.String())
}
// Wait for user to open serial console
func waitSerial() {
for !machine.Serial.DTR() {
time.Sleep(100 * time.Millisecond)
}
}
// connect to access point
func connectToAP() {
if len(ssid) == 0 || len(pass) == 0 {
for {
println("Connection failed: Either ssid or password not set")
time.Sleep(10 * time.Second)
}
}
time.Sleep(2 * time.Second)
println("Connecting to " + ssid)
adaptor.SetPassphrase(ssid, pass)
for st, _ := adaptor.GetConnectionStatus(); st != wifinina.StatusConnected; {
println("Connection status: " + st.String())
time.Sleep(1 * time.Second)
st, _ = adaptor.GetConnectionStatus()
}
println("Connected.")
}

Some files were not shown because too many files have changed in this diff Show More