tag:blogger.com,1999:blog-52981600273306964742024-03-16T11:52:32.107-07:00Arduino-er<i>Please visit my new address:</i> <b><a href="https://coxxect.blogspot.com/">https://coxxect.blogspot.com/</a></b>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.comBlogger526125tag:blogger.com,1999:blog-5298160027330696474.post-86073831473282511812022-07-24T01:39:00.007-07:002022-07-25T13:45:55.899-07:00Install Ubuntu MATE 22.04 LTS on VirtualBox, install Arduino IDE and set permission, setup and post install for Nano RP2040 Connect, and upgrade NINA firmware.<p>
It's posted in my another new blogspot,
<a href="https://coxxect.blogspot.com/" target="_blank">coXXect</a>, to
re-group all topic in one place.
</p>
<p>
-
<a href="https://coxxect.blogspot.com/2022/07/install-ubuntu-mate-2204-lts-on.html" target="_blank">Install Ubuntu MATE 22.04 LTS on VirtualBox 6.1</a>
</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/iUpS_AQeilU" title="YouTube video player" width="560"></iframe>
</center>
<br />- <a href="https://coxxect.blogspot.com/2022/07/install-arduino-ide-1819-on-ubuntu-mate.html" target="_blank">Install Arduino IDE 1.8.19 on Ubuntu MATE 22.04 LTS, and set permission</a><br /><br />
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/KVZ66ur7WOc" title="YouTube video player" width="560"></iframe>
</center>
<br />
If you target to develop for Arduino Nano RP2040 Connect, read <a href="https://coxxect.blogspot.com/2022/07/setup-and-post-install-arduino-ide-for.html" target="_blank">Setup and post install Arduino IDE for Nano RP2040 Connect, on Ubuntu MATE</a>.<br /><br />
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/FM9RxHG0u6g" title="YouTube video player" width="560"></iframe>
</center>
<br />Also <a href="https://coxxect.blogspot.com/2022/07/upgrade-nano-rp2040-connect-nina-w102.html" target="_blank">upgrade Nano RP2040 Connect NINA-W102 module's firmware,
using Arduino Cloud IoT and using Arduino IDE 1.8.19</a>.<br /><br />
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/xSEDtT0IMX4" title="YouTube video player" width="560"></iframe>
</center>
<br />
<br />
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/i_XSeOnAtIQ" title="YouTube video player" width="560"></iframe>
</center>
<br />Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-66392393786484742922022-03-16T18:31:00.003-07:002022-03-16T18:31:41.782-07:00Get user input from Serial Monitor<p> To get user input from Serial Monitor:<br /></p>
<pre style="border: 1px solid black;"><code><span style="color: black;">void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0){
String stringIn = Serial.readString();
stringIn.toUpperCase();
Serial.println(stringIn);
}
}</span></code></pre>
<br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEjGK6sr-MMqDnmfD6Vb8steHE6oHVRwhkdtWW_M123jJddv5EKKifKShwrNJ5lBsBsmpnzoOYd3A1ePBm8ESu6y--JvCQthFvgyYCJCcSRcfbXRtAXlJcx5CnYLH_mDlpgOIQ2DeFBrbkd-qocPQdmxbvUXtZBeaw7evIlK5zyJVU5lEx-mT3-F46Ov=s1800" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/a/AVvXsEjGK6sr-MMqDnmfD6Vb8steHE6oHVRwhkdtWW_M123jJddv5EKKifKShwrNJ5lBsBsmpnzoOYd3A1ePBm8ESu6y--JvCQthFvgyYCJCcSRcfbXRtAXlJcx5CnYLH_mDlpgOIQ2DeFBrbkd-qocPQdmxbvUXtZBeaw7evIlK5zyJVU5lEx-mT3-F46Ov=w640-h384" width="640" /></a></div><br />Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-87690850869407317462021-11-16T07:17:00.006-08:002021-11-16T09:34:19.657-08:00Arduino Nano RP2040 Connect generate QR Code and display on ST7735 TFT - software SPI<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/cb-QLyKI2q4" title="YouTube video player" width="560"></iframe>
</center>
<p>This post show how to generate QR Code with Nano RP2040 Connect (Arduino
Framework) using QRCode library by Richard Moore, also display on ST7735 SPI
TFT, and finally adapt to WiFiNINA > AP_SimpleWebServer example to
control onboard LED.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyAGOOV2UN9GH98ho9YkywcAddmSAjZpKV2arwV1iW4zBt7qavgtqZ5SkYltFvW0OcGhrcmRT8kkRR5Sl3qRPIPMk3D-uD0DYwJy7vMraEPNqQI7CVKduTsUni5K9M2dT84kT1jSnkV1I/s1000/nanoRP2040_QRCode_2.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="606" data-original-width="1000" height="388" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyAGOOV2UN9GH98ho9YkywcAddmSAjZpKV2arwV1iW4zBt7qavgtqZ5SkYltFvW0OcGhrcmRT8kkRR5Sl3qRPIPMk3D-uD0DYwJy7vMraEPNqQI7CVKduTsUni5K9M2dT84kT1jSnkV1I/w640-h388/nanoRP2040_QRCode_2.jpg" width="640" /></a>
</div>
<p>
<b><u>Library</u></b>
</p>
<p>
Install QRCode library by Richard Moore in Arduino IDE's Libraries
Manager.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi5ShC8hnSlXUolBHOpGKuWGO2avqeMYoJB1XqNAAeidbakwv0erlaIflH9pJzMxiiW_M-2yCQr3JAQeGvKvkSffPzOFHtql2LkNwW9piSNIKO2Tlff5fNvf6E6DDZZLHcO67ZTc5zmzis/s1800/QRCode+lib.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi5ShC8hnSlXUolBHOpGKuWGO2avqeMYoJB1XqNAAeidbakwv0erlaIflH9pJzMxiiW_M-2yCQr3JAQeGvKvkSffPzOFHtql2LkNwW9piSNIKO2Tlff5fNvf6E6DDZZLHcO67ZTc5zmzis/w640-h384/QRCode+lib.jpg" width="640" /></a>
</div>
<div><br /></div>
<div>
And, "Adafruit ST7735 and ST7789 Library" and "Adafruit GFX Library" are
needed to display with ST7735 SPI TFT.
</div>
<div><br /></div>
<div>
<b><u>Connection</u></b>
</div>
<div><br /></div>
<div>The hardware SPI of Arduino Nano RP2040 Connect are:</div>
<div>
<div>- (CIPO/MISO) - D12</div>
<div>- (COPI/MOSI) - D11</div>
<div>- (SCK) - D13</div>
<div>- (CS/SS) - Any GPIO (except for A6/A7)</div>
<div><br /></div>
<div>
(refer to
<a href="http://arduino-er.blogspot.com/2021/11/spi-pins-in-arduino-nano-rp2040-connect.html">SPI pins in Arduino Nano RP2040 Connect</a>)
</div>
</div>
<div><br /></div>
<div>
In this exercise, we have to control the onboard LED connected to D13. it's
conflict with SCK. So the exercise code here use software SPI.
</div>
<pre style="border: 1px solid black;"><code><span style="color: black;">/************************************************
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* VCC 3V3
* GND GND
* CS 10
* RESET 9
* A0(DC) 8
* SDA 11
* SCK 12
* LED 3V3
* **********************************************/
</span></code></pre>
<div>
<b><u>Exercise code</u></b>
</div>
<div><br /></div>
nanoRP2040_QRCode.ino
<pre style="border: 1px solid black;"><code><span style="color: black;">/**
* Arduino nano RP2040 Connect exercise to generate QR Code,
* with display on Serial Monitor and ST7735 SPI TFT.
* Modified from QRCode example.
*
* Library: QRCode by Richard Moore
* https://github.com/ricmoo/qrcode/
*
*/
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include "qrcode.h"
/************************************************
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* VCC 3V3
* GND GND
* CS 10
* RESET 9
* A0(DC) 8
* SDA 11
* SCK 12
* LED 3V3
* **********************************************/
// TFT display use software SPI interface.
#define TFT_MOSI 11 // Data out
#define TFT_SCLK 12 // Clock out
#define TFT_CS 10 // Chip select line for TFT display
#define TFT_DC 8 // Data/command line for TFT
#define TFT_RST 9 // Reset line for TFT (or connect to VCC)
Adafruit_ST7735 tft_ST7735 = Adafruit_ST7735(TFT_CS, TFT_DC,
TFT_MOSI, TFT_SCLK, TFT_RST);
void setup() {
delay(1000);
Serial.begin(115200);
delay(1000);
Serial.println("- setup() started -");
tft_ST7735.initR(INITR_BLACKTAB);
tft_ST7735.setRotation(2);
// tft display RGB to make sure it's work properly
tft_ST7735.fillScreen(ST7735_BLACK);
delay(300);
tft_ST7735.fillScreen(ST7735_RED);
delay(300);
tft_ST7735.fillScreen(ST7735_GREEN);
delay(300);
tft_ST7735.fillScreen(ST7735_BLUE);
delay(300);
tft_ST7735.fillScreen(ST7735_WHITE);
delay(300);
// Start time
uint32_t dt = millis();
// Create the QR code
QRCode qrcode;
const char *data = "http://arduino-er.blogspot.com/";
const uint8_t ecc = 0; //lowest level of error correction
const uint8_t version = 3;
uint8_t qrcodeData[qrcode_getBufferSize(version)];
qrcode_initText(&qrcode,
qrcodeData,
version, ecc,
data);
// Delta time
dt = millis() - dt;
Serial.print("QR Code Generation Time: ");
Serial.print(dt);
Serial.print("\n\n");
Serial.println(data);
Serial.print("qrcode.version: ");
Serial.println(qrcode.version);
Serial.print("qrcode.ecc: ");
Serial.println(qrcode.ecc);
Serial.print("qrcode.size: ");
Serial.println(qrcode.size);
Serial.print("qrcode.mode: ");
Serial.println(qrcode.mode);
Serial.print("qrcode.mask: ");
Serial.println(qrcode.mask);
Serial.println();
const int xy_scale = 3;
const int x_offset = (tft_ST7735.width() - xy_scale*qrcode.size)/2;
const int y_offset = (tft_ST7735.height() - xy_scale*qrcode.size)/2;
// Top quiet zone
Serial.print("\n\n\n\n");
for (uint8_t y = 0; y < qrcode.size; y++) {
// Left quiet zone
Serial.print(" ");
// Each horizontal module
for (uint8_t x = 0; x < qrcode.size; x++) {
// Print each module (UTF-8 \u2588 is a solid block)
bool mod = qrcode_getModule(&qrcode, x, y);
//Serial.print(mod ? "\u2588\u2588": " ");
if(mod){
Serial.print("██"); //same as "\u2588\u2588"
//direct paste "██" copied from Serial Monitor
int px = x_offset + (x * xy_scale);
int py = y_offset + (y * xy_scale);
tft_ST7735.fillRect(px, py, xy_scale, xy_scale, ST7735_BLACK);
}else{
Serial.print(" ");
}
}
Serial.print("\n");
}
// Bottom quiet zone
Serial.print("\n\n\n\n");
}
void loop() {
}
</span></code></pre>
<div><br /></div>
nanoRP2040_QRCode_web.ino
<pre style="border: 1px solid black;"><code><span style="color: black;">/**
* Arduino nano RP2040 Connect exercise to generate QR Code,
* WiFiWebServer with QRCode on ST7735 SPI TFT
*
* Library: QRCode by Richard Moore
* https://github.com/ricmoo/qrcode/
*
*/
#include <WiFiNINA.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include "qrcode.h"
/************************************************
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* VCC 3V3
* GND GND
* CS 10
* RESET 9
* A0(DC) 8
* SDA 11
* SCK 12
* LED 3V3
* **********************************************/
// TFT display use software SPI interface.
//
// Hardware SPI pins are specific to the Arduino board type and
// cannot be remapped to alternate pins.
//
// In this exercise, we are going to implement a web server to
// turn ON/OFF on board LED, which is connected to D13. It's
// conflict with hardware SPI SCK.
// So we cannot use hardware SPI to controll ST7735.
#define TFT_MOSI 11 // Data out
#define TFT_SCLK 12 // Clock out
#define TFT_CS 10 // Chip select line for TFT display
#define TFT_DC 8 // Data/command line for TFT
#define TFT_RST 9 // Reset line for TFT (or connect to VCC)
Adafruit_ST7735 tft_ST7735 = Adafruit_ST7735(TFT_CS, TFT_DC,
TFT_MOSI, TFT_SCLK, TFT_RST);
char ssid[] = "ssid"; // your network SSID (name)
char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
delay(1000);
Serial.begin(115200);
delay(1000);
Serial.println("- setup() started -");
Serial.print("LED_BUILTIN: ");
Serial.println(LED_BUILTIN);
pinMode(LED_BUILTIN, OUTPUT); // set the LED pin mode
tft_ST7735.initR(INITR_BLACKTAB);
tft_ST7735.setRotation(2);
tft_ST7735.setTextWrap(true);
tft_ST7735.setTextColor(ST77XX_BLACK);
// tft display RGB to make sure it's work properly
digitalWrite(LED_BUILTIN, HIGH);
tft_ST7735.fillScreen(ST7735_BLACK);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
tft_ST7735.fillScreen(ST7735_RED);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
tft_ST7735.fillScreen(ST7735_GREEN);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
tft_ST7735.fillScreen(ST7735_BLUE);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
tft_ST7735.fillScreen(ST7735_WHITE);
delay(300);
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
tft_ST7735.setCursor(0, 0);
tft_ST7735.print("Communication with WiFi module failed!");
// don't continue
while (true);
}
Serial.print("WiFi.firmwareVersion(): ");
Serial.println(WiFi.firmwareVersion());
// attempt to connect to WiFi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin();
// you're connected now, so print out the status:
printWifiStatus();
// Start time
uint32_t dt = millis();
// Create the QR code
QRCode qrcode;
char myIpQrData[30] ="http://";
prepareIpQrData(myIpQrData);
const uint8_t ecc = 0; //lowest level of error correction
const uint8_t version = 3;
uint8_t qrcodeData[qrcode_getBufferSize(version)];
qrcode_initText(&qrcode,
qrcodeData,
version, ecc,
myIpQrData);
// Delta time
dt = millis() - dt;
Serial.print("QR Code Generation Time: ");
Serial.print(dt);
Serial.print("\n\n");
Serial.println(myIpQrData);
Serial.print("qrcode.version: ");
Serial.println(qrcode.version);
Serial.print("qrcode.ecc: ");
Serial.println(qrcode.ecc);
Serial.print("qrcode.size: ");
Serial.println(qrcode.size);
Serial.print("qrcode.mode: ");
Serial.println(qrcode.mode);
Serial.print("qrcode.mask: ");
Serial.println(qrcode.mask);
Serial.println();
const int xy_scale = 3;
const int x_offset = (tft_ST7735.width() - xy_scale*qrcode.size)/2;
const int y_offset = (tft_ST7735.height() - xy_scale*qrcode.size)/2;
// Top quiet zone
Serial.print("\n\n\n\n");
for (uint8_t y = 0; y < qrcode.size; y++) {
// Left quiet zone
Serial.print(" ");
// Each horizontal module
for (uint8_t x = 0; x < qrcode.size; x++) {
// Print each module (UTF-8 \u2588 is a solid block)
bool mod = qrcode_getModule(&qrcode, x, y);
//Serial.print(mod ? "\u2588\u2588": " ");
if(mod){
Serial.print("██"); //same as "\u2588\u2588"
//direct paste "██" copied from Serial Monitor
int px = x_offset + (x * xy_scale);
int py = y_offset + (y * xy_scale);
tft_ST7735.fillRect(px, py, xy_scale, xy_scale, ST7735_BLACK);
}else{
Serial.print(" ");
}
}
Serial.print("\n");
}
// Bottom quiet zone
Serial.print("\n\n\n\n");
digitalWrite(LED_BUILTIN, LOW);
}
//prepare ip address in char *,
//to pass to qrcode_initText()
char * prepareIpQrData(char *dest){
Serial.println("***********************");
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip[0]);
Serial.println(ip[1]);
Serial.println(ip[2]);
Serial.println(ip[3]);
Serial.println("-------------");
char buffer0[3];
char buffer1[3];
char buffer2[3];
char buffer3[3];
itoa(ip[0], buffer0, 10);
itoa(ip[1], buffer1, 10);
itoa(ip[2], buffer2, 10);
itoa(ip[3], buffer3, 10);
char str[15] = "";
char dot[] = ".";
strcat(dest, buffer0);
strcat(dest, dot);
strcat(dest, buffer1);
strcat(dest, dot);
strcat(dest, buffer2);
strcat(dest, dot);
strcat(dest, buffer3);
Serial.println(dest);
Serial.println("***********************");
}
//The web page part is mainly modified
//from WiFiNINA example > AP_SimpleWebServer
//that lets you blink an LED via the web.
void loop() {
// compare the previous status to the current status
if (status != WiFi.status()) {
// it has changed update the variable
status = WiFi.status();
if (status == WL_AP_CONNECTED) {
// a device has connected to the AP
Serial.println("Device connected to AP");
} else {
// a device has disconnected from the AP, and we are back in listening mode
Serial.println("Device disconnected from AP");
}
}
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
delayMicroseconds(10); // This is required for the Arduino Nano RP2040 Connect
// - otherwise it will loop so fast that SPI will
// never be served.
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
// the content of the HTTP response follows the header:
client.print("Click <a href=\"/H\">here</a> turn the LED on<br>");
client.print("Click <a href=\"/L\">here</a> turn the LED off<br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else { // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
Serial.println("\n===> GET /H");
digitalWrite(LED_BUILTIN, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
Serial.println("\n===> GET /L");
digitalWrite(LED_BUILTIN, LOW); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
</span></code></pre>
<div>Related:</div>
<div>
~ <a href="http://arduino-er.blogspot.com/2021/11/arduino-nano-rp2040-connect-st7735-spi.html">Arduino Nano RP2040 Connect + ST7735 SPI TFT with SD Card, read and display
bitmap, using hardware SPI</a>.
</div>
<div><br /></div>
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-11389597451758062692021-11-09T23:09:00.005-08:002021-11-16T07:18:52.354-08:00Arduino Nano RP2040 Connect + ST7735 SPI TFT with SD Card, read and display bitmap, using hardware SPI.<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjDdshrGK6tNEBCiboBiyYfseJWUPw4cnKwE2e1jErFJIOxfjVSr-uFe4svwH2-lC3CZzpsR42zYjPw5fYTILpIWvOm6bVXnJehCiRSsIDZvy7KzVkBjZaIfIffYh8kNv4AVJL_XnYSa90/s1000/nanoRP2040_ST7735_SD_bmp.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="606" data-original-width="1000" height="388" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjDdshrGK6tNEBCiboBiyYfseJWUPw4cnKwE2e1jErFJIOxfjVSr-uFe4svwH2-lC3CZzpsR42zYjPw5fYTILpIWvOm6bVXnJehCiRSsIDZvy7KzVkBjZaIfIffYh8kNv4AVJL_XnYSa90/w640-h388/nanoRP2040_ST7735_SD_bmp.jpg" width="640" /></a>
</div>
<p>
Exercises run on <a href="http://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">Arduino Nano RP2040 Connect (in Arduino framework)</a> work with
1.8" 128x160 ST7735 SPI TFT/SD Card Module, to:<br />- simple display
something on ST7735 SPI TFT<br />- Display files in SD Card, and read txt file
from SD Card.<br />- Read bmp from SD Card and display on ST7735 SPI TFT<br />-
Try example of Adafruit_ImageReader<br />- Simplified version display bitmap
from SD and display on TFT using Adafruit_ImageReader.
</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/6pXUKjaVcd4" title="YouTube video player" width="560"></iframe>
</center>
<p>
In the following exercise Hardware SPI is used for ST7735 and SD Card SPI
interface. refer to last post, <a href="http://arduino-er.blogspot.com/2021/11/spi-pins-in-arduino-nano-rp2040-connect.html">SPI pins in Arduino Nano RP2040 Connec</a>t is:<br />- MISO<span> </span>- D12<br />- MOSI<span> </span>- D11<br />- SCK<span> </span><span> </span>-
D13
</p>
<b><u>Connection:</u></b><br />
<pre style="border: 1px solid black;"><code><span style="color: black;"> * Nano RP2040 Connect drive ST7735 SPI and SD using hardware SPI
*
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* VCC 3V3
* GND GND
* CS 10
* RESET 9
* A0(DC) 8
* SDA 11
* SCK 13
* LED 3V3
*
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* SD_CS 4
* SD_MOSI 11
* SD_MISO 12
* SD_SCK 13
****************************************************/
</span></code></pre>
<p><b><u>Exercise code:</u></b></p>
<p>
Please notice that "Adafruit ST7735 and ST7789 Library" and
"Adafruit GFX Library" are needed, make sure it's installed in Arduino IDE's
Libraries Manager.
</p>
<p><b>
nanoRP2040_ST7735.ino</b>, a simple exercise to display something on ST7735 SPI
TFT.
</p>
<pre style="border: 1px solid black;"><code><span style="color: black;">/***************************************************
* nano RP2040 Connect exercise
* + ST7745/SD
*
* On Arduino nanp RP2040 Connect:
* (CIPO/MISO) - D12
* (COPI/MOSI) - D11
* (SCK) - D13
* (CS/SS) - Any GPIO (except for A6/A7
*
* This example drive ST7735 SPI and SD using hardware SPI
*
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* VCC 3V3
* GND GND
* CS 10
* RESET 9
* A0(DC) 8
* SDA 11
* SCK 13
* LED 3V3
*
****************************************************/
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SD.h>
#include <SPI.h>
// TFT display using hardware SPI interface.
// Hardware SPI pins are specific to the Arduino board type and
// cannot be remapped to alternate pins.
#define TFT_CS 10 // Chip select line for TFT display
#define TFT_DC 8 // Data/command line for TFT
#define TFT_RST 9 // Reset line for TFT (or connect to +5V)
Adafruit_ST7735 tft_ST7735 = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
void setup(void) {
delay(1000);
Serial.begin(115200);
delay(1000);
Serial.println("=====================");
Serial.println("- setup() -");
tft_ST7735.initR(INITR_BLACKTAB);
Serial.println("tft: "
+ String(tft_ST7735.width()) + " : "
+ String(tft_ST7735.height()));
tft_ST7735.fillScreen(ST7735_BLACK);
tft_ST7735.setTextWrap(true);
tft_ST7735.setTextColor(ST77XX_WHITE);
tft_ST7735.setCursor(0, 0);
tft_ST7735.print("Arduino nano RP2040 Connect");
tft_ST7735.println("\n");
//----------------------------------------
delay(2000);
tft_ST7735.setRotation(3);
tft_ST7735.setCursor(0, 30);
tft_ST7735.print("rotation: " + String(tft_ST7735.getRotation()));
tft_ST7735.setCursor(0, 40);
tft_ST7735.print(String(tft_ST7735.width()) + " x " + String(tft_ST7735.height()));
delay(2000);
tft_ST7735.fillScreen(ST77XX_RED);
tft_ST7735.setCursor(50, 50);
tft_ST7735.print("RED");
delay(1000);
tft_ST7735.fillScreen(ST77XX_GREEN);
tft_ST7735.setCursor(50, 50);
tft_ST7735.print("GREEN");
delay(1000);
tft_ST7735.fillScreen(ST77XX_BLUE);
tft_ST7735.setCursor(50, 50);
tft_ST7735.print("BLUE");
delay(1000);
delay(1000);
//----------------------------------------
Serial.println("\n- End of setup() -\n");
}
void loop() {
tft_ST7735.fillScreen(ST77XX_BLUE);
for(int offset=0; offset<tft_ST7735.height()/2; offset++){
int col;
if(offset%5 == 0)
col = ST77XX_WHITE;
else
col = ST77XX_BLACK;
tft_ST7735.drawRect(offset, offset,
tft_ST7735.width()-2*offset, tft_ST7735.height()-2*offset,
col);
delay(100);
}
delay(2000);
tft_ST7735.fillScreen(ST77XX_BLACK);
int cx = tft_ST7735.width()/2;
int cy = tft_ST7735.height()/2;
for(int r=0; r<tft_ST7735.height()/2; r=r+10){
tft_ST7735.drawCircle(cx, cy,
r,
ST77XX_WHITE);
delay(200);
}
delay(2000);
delay(2000);
}
</span></code></pre>
<br /><b>
nanoRP2040_ST7735_SD.ino</b>, list files in SD card and read the text
file hello.txt.
<pre style="border: 1px solid black;"><code><span style="color: black;">/***************************************************
* nano RP2040 Connect exercise
* + ST7745/SD
*
* On Arduino nanp RP2040 Connect:
* (CIPO/MISO) - D12
* (COPI/MOSI) - D11
* (SCK) - D13
* (CS/SS) - Any GPIO (except for A6/A7
*
* This example drive ST7735 SPI and SD using hardware SPI
*
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* VCC 3V3
* GND GND
* CS 10
* RESET 9
* A0(DC) 8
* SDA 11
* SCK 13
* LED 3V3
*
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* SD_CS 4
* SD_MOSI 11
* SD_MISO 12
* SD_SCK 13
****************************************************/
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SD.h>
#include <SPI.h>
// TFT display and SD card will share the hardware SPI interface.
// Hardware SPI pins are specific to the Arduino board type
#define SD_CS 4 // Chip select line for SD card
#define TFT_CS 10 // Chip select line for TFT display
#define TFT_DC 8 // Data/command line for TFT
#define TFT_RST 9 // Reset line for TFT (or connect to +5V)
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
File root;
File myFile;
void setup(void) {
delay(1000);
Serial.begin(115200);
delay(1000);
Serial.println("=====================");
Serial.println("- setup() -");
tft.initR(INITR_BLACKTAB);
Serial.println("tft: "
+ String(tft.width()) + " : "
+ String(tft.height()));
tft.fillScreen(ST7735_BLACK);
tft.setTextWrap(true);
tft.setTextColor(ST77XX_WHITE);
tft.setCursor(0, 0);
tft.print("Arduino nano RP2040 Connect");
tft.println("\n");
//----------------------------------------
Serial.println("Initializing SD card...");
if (!SD.begin(SD_CS)){
Serial.println("SD.begin() failed!");
}
else{
Serial.println("SD.begin() Success.");
root = SD.open("/");
printDirectory(root, 0);
Serial.println("===============================");
// open the file for reading:
myFile = SD.open("hello.txt");
if (myFile) {
Serial.println("test.txt:");
Serial.println("-------------------------------");
// read from the file until there's nothing else in it:
while (myFile.available()) {
//Serial.write(myFile.read());
byte b = myFile.read();
Serial.write(b);
tft.print((char)b);
}
// close the file:
myFile.close();
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
Serial.println("\n===============================\n");
}
//----------------------------------------
Serial.println("\n- End of setup() -\n");
}
void loop() {
delay(100);
}
//
// printDirectory() copy from:
// Examples > SD > listfiles
//
void printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}
</span></code></pre>
<br /><b>
nanoRP2040_ST7735_SD_bmp.ino</b>, read bmp files in SD Card, test.bmp, test2.bmp and
test3.bmp, and display on ST7735 SPI TFT. It can be noted in bmpDraw(), copy from examples under "Adafruit ST7735 and ST7789 Library" > shieldtest, bmpDepth must be 24. To prepare bmp for this using GIMP, refer to the above video, ~ 6:38.<pre style="border: 1px solid black;"><code><span style="color: black;">/***************************************************
* nano RP2040 Connect exercise
* + ST7745/SD
*
* On Arduino nanp RP2040 Connect:
* (CIPO/MISO) - D12
* (COPI/MOSI) - D11
* (SCK) - D13
* (CS/SS) - Any GPIO (except for A6/A7
*
* This example drive ST7735 SPI and SD using hardware SPI
*
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* VCC 3V3
* GND GND
* CS 10
* RESET 9
* A0(DC) 8
* SDA 11
* SCK 13
* LED 3V3
*
* TFT_ST7735 nano RP2040 Connect
* ------------------------------
* SD_CS 4
* SD_MOSI 11
* SD_MISO 12
* SD_SCK 13
****************************************************/
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SD.h>
#include <SPI.h>
// TFT display and SD card will share the hardware SPI interface.
// Hardware SPI pins are specific to the Arduino board type.
#define SD_CS 4 // Chip select line for SD card
#define TFT_CS 10 // Chip select line for TFT display
#define TFT_DC 8 // Data/command line for TFT
#define TFT_RST 9 // Reset line for TFT (or connect to +5V)
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
File root;
File myFile;
void setup(void) {
delay(1000);
Serial.begin(115200);
delay(1000);
Serial.println("=====================");
Serial.println("- setup() -");
tft.initR(INITR_BLACKTAB);
Serial.println("tft: "
+ String(tft.width()) + " : "
+ String(tft.height()));
tft.fillScreen(ST7735_BLACK);
tft.setTextWrap(true);
tft.setTextColor(ST77XX_WHITE);
tft.setCursor(0, 0);
tft.print("Arduino nano RP2040 Connect");
//----------------------------------------
Serial.println("Initializing SD card...");
if (!SD.begin(SD_CS)){
Serial.println("SD.begin() failed!");
}
else{
Serial.println("SD.begin() Success.");
root = SD.open("/");
printDirectory(root, 0);
}
//----------------------------------------
Serial.println("\n- End of setup() -\n");
}
const int NO_OF_BMP = 3;
char* bmpFiles[NO_OF_BMP] = {"/test.bmp", "/test2.bmp", "/test3.bmp"};
void loop() {
for(int i=0; i<NO_OF_BMP; i++){
bmpDraw(bmpFiles[i], 0, 0);
delay(2000);
}
}
//
// printDirectory() copy from:
// Examples > SD > listfiles
//
void printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}
//
// bmpDraw() copy from:
// Examples under "Adafruit ST7735 and ST7789 Library" > shieldtest
//
// This function opens a Windows Bitmap (BMP) file and
// displays it at the given coordinates. It's sped up
// by reading many pixels worth of data at a time
// (rather than pixel by pixel). Increasing the buffer
// size takes more of the Arduino's precious RAM but
// makes loading a little faster. 20 pixels seems a
// good balance.
#define BUFFPIXEL 20
void bmpDraw(char *filename, uint8_t x, uint8_t y) {
File bmpFile;
int bmpWidth, bmpHeight; // W+H in pixels
uint8_t bmpDepth; // Bit depth (currently must be 24)
uint32_t bmpImageoffset; // Start of image data in file
uint32_t rowSize; // Not always = bmpWidth; may have padding
uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel)
uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer
boolean goodBmp = false; // Set to true on valid header parse
boolean flip = true; // BMP is stored bottom-to-top
int w, h, row, col;
uint8_t r, g, b;
uint32_t pos = 0, startTime = millis();
if((x >= tft.width()) || (y >= tft.height())) return;
Serial.println();
Serial.print("Loading image '");
Serial.print(filename);
Serial.println('\'');
// Open requested file on SD card
if ((bmpFile = SD.open(filename)) == NULL) {
Serial.print("File not found");
return;
}
// Parse BMP header
if(read16(bmpFile) == 0x4D42) { // BMP signature
Serial.print("File size: "); Serial.println(read32(bmpFile));
(void)read32(bmpFile); // Read & ignore creator bytes
bmpImageoffset = read32(bmpFile); // Start of image data
Serial.print("Image Offset: "); Serial.println(bmpImageoffset, DEC);
// Read DIB header
Serial.print("Header size: "); Serial.println(read32(bmpFile));
bmpWidth = read32(bmpFile);
bmpHeight = read32(bmpFile);
if(read16(bmpFile) == 1) { // # planes -- must be '1'
bmpDepth = read16(bmpFile); // bits per pixel
Serial.print("Bit Depth: "); Serial.println(bmpDepth);
if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed
goodBmp = true; // Supported BMP format -- proceed!
Serial.print("Image size: ");
Serial.print(bmpWidth);
Serial.print('x');
Serial.println(bmpHeight);
// BMP rows are padded (if needed) to 4-byte boundary
rowSize = (bmpWidth * 3 + 3) & ~3;
// If bmpHeight is negative, image is in top-down order.
// This is not canon but has been observed in the wild.
if(bmpHeight < 0) {
bmpHeight = -bmpHeight;
flip = false;
}
// Crop area to be loaded
w = bmpWidth;
h = bmpHeight;
if((x+w-1) >= tft.width()) w = tft.width() - x;
if((y+h-1) >= tft.height()) h = tft.height() - y;
// Set TFT address window to clipped image bounds
tft.startWrite();
tft.setAddrWindow(x, y, w, h);
for (row=0; row<h; row++) { // For each scanline...
// Seek to start of scan line. It might seem labor-
// intensive to be doing this on every line, but this
// method covers a lot of gritty details like cropping
// and scanline padding. Also, the seek only takes
// place if the file position actually needs to change
// (avoids a lot of cluster math in SD library).
if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
else // Bitmap is stored top-to-bottom
pos = bmpImageoffset + row * rowSize;
if(bmpFile.position() != pos) { // Need seek?
tft.endWrite();
bmpFile.seek(pos);
buffidx = sizeof(sdbuffer); // Force buffer reload
}
for (col=0; col<w; col++) { // For each pixel...
// Time to read more pixel data?
if (buffidx >= sizeof(sdbuffer)) { // Indeed
bmpFile.read(sdbuffer, sizeof(sdbuffer));
buffidx = 0; // Set index to beginning
tft.startWrite();
}
// Convert pixel from BMP to TFT format, push to display
b = sdbuffer[buffidx++];
g = sdbuffer[buffidx++];
r = sdbuffer[buffidx++];
tft.pushColor(tft.color565(r,g,b));
} // end pixel
} // end scanline
tft.endWrite();
Serial.print("Loaded in ");
Serial.print(millis() - startTime);
Serial.println(" ms");
} // end goodBmp
}
}
bmpFile.close();
if(!goodBmp) Serial.println("BMP format not recognized.");
}
// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.
uint16_t read16(File f) {
uint16_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read(); // MSB
return result;
}
uint32_t read32(File f) {
uint32_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read();
((uint8_t *)&result)[2] = f.read();
((uint8_t *)&result)[3] = f.read(); // MSB
return result;
}
</span></code></pre>
<br /><b>
nanoRP2040_ST7735_SD_ImageReader.ino</b>, a simplified version to display bitmaps
using Adafruit_ImageReader, make sure it's installed.
<pre style="border: 1px solid black;"><code><span style="color: black;">// Adafruit_ImageReader test for Adafruit ST7735 TFT Breakout for Arduino.
// Demonstrates loading images from SD card or flash memory to the screen,
// to RAM, and how to query image file dimensions.
// Requires three BMP files in root directory of SD card:
// test.bmp, test2.bmp and test3.bmp.
// As written, this uses the microcontroller's SPI interface for the screen
// (not 'bitbang') and must be wired to specific pins.
#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SdFat.h> // SD card & FAT filesystem library
#include <Adafruit_ImageReader.h> // Image-reading functions
// TFT display and SD card share the hardware SPI interface, using
// 'select' pins for each to identify the active device on the bus.
#define SD_CS 4 // SD card select pin
#define TFT_CS 10 // TFT select pin
#define TFT_DC 8 // TFT display/command pin
#define TFT_RST 9 // Or set to -1 and connect to Arduino RESET pin
SdFat SD; // SD card filesystem
Adafruit_ImageReader reader(SD); // Image-reader object, pass in SD filesys
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
Adafruit_Image img; // An image loaded into RAM
int32_t width = 0, // BMP image dimensions
height = 0;
void setup(void) {
ImageReturnCode stat; // Status from image-reading functions
Serial.begin(115200);
tft.initR(INITR_BLACKTAB); // Initialize screen
// The Adafruit_ImageReader constructor call (above, before setup())
// accepts an uninitialized SdFat or FatFileSystem object. This MUST
// BE INITIALIZED before using any of the image reader functions!
Serial.print(F("Initializing filesystem..."));
// SD card is pretty straightforward, a single call...
if(!SD.begin(SD_CS, SD_SCK_MHZ(10))) { // Breakouts require 10 MHz limit due ...
Serial.println(F("SD begin() failed"));
for(;;); // Fatal error, do not continue
}
Serial.println(F("OK!"));
// Fill screen blue. Not a required step, this just shows that we're
// successfully communicating with the screen.
tft.fillScreen(ST7735_BLUE);
// Load full-screen BMP file 'test.bmp' at position (0,0) (top left).
// Notice the 'reader' object performs this, with 'tft' as an argument.
Serial.print(F("Loading test.bmp to screen..."));
stat = reader.drawBMP("/test.bmp", tft, 0, 0);
reader.printStatus(stat); // How'd we do?
// Query the dimensions of image 'test2.bmp' WITHOUT loading to screen:
Serial.print(F("Querying test2.bmp image size..."));
stat = reader.bmpDimensions("/test2.bmp", &width, &height);
reader.printStatus(stat); // How'd we do?
if(stat == IMAGE_SUCCESS) { // If it worked, print image size...
Serial.print(F("Image dimensions: "));
Serial.print(width);
Serial.write('x');
Serial.println(height);
}
// Load small BMP 'test3.bmp' into a GFX canvas in RAM.
Serial.print(F("Loading test3.bmp to canvas..."));
stat = reader.loadBMP("/test3.bmp", img);
reader.printStatus(stat); // How'd we do?
delay(2000); // Pause 2 seconds before moving on to loop()
}
void loop() {
for(int r=0; r<4; r++) { // For each of 4 rotations...
tft.setRotation(r); // Set rotation
tft.fillScreen(0); // and clear screen
reader.drawBMP("/test2.bmp", tft, 0, 0);
delay(1000); // Pause 1 sec.
img.draw(tft, // Pass in tft object
0 , // Horiz pos.
0); // Vert pos
delay(2000); // Pause 2 sec.
}
}
</span></code></pre>
Related:<div>~ <a href="https://arduino-er.blogspot.com/2021/11/arduino-nano-rp2040-connect-generate-qr.html">Arduino Nano RP2040 Connect generate QR Code and display on ST7735 TFT - software SPI</a></div><div><br /></div><div><br /></div>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-32324391541685786782021-11-06T05:58:00.006-07:002021-11-16T09:31:51.024-08:00SPI pins in Arduino Nano RP2040 Connect<p>The pins used for SPI (Serial Peripheral Interface) on the Nano RP2040 Connect are the:</p><p></p><ul style="text-align: left;"><li>(CIPO/MISO) - D12</li><li>(COPI/MOSI) - D11</li><li>(SCK) - D13</li><li>(CS/SS) - Any GPIO (except for A6/A7)</li></ul><p></p><p>ref: <a href="https://docs.arduino.cc/tutorials/nano-rp2040-connect/rp2040-01-technical-reference" target="_blank">https://docs.arduino.cc/tutorials/nano-rp2040-connect/rp2040-01-technical-reference</a></p><p>Please note that SCK on D13 is conflict with the onboard LED.</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxv4AefbBMu3CoiIYYt6QfjJ_nNsH81k3JzBgn6wEPlzVF7Bbqtmfe272LnY8Q-PL2bqGHd1aqeYpfTuqE4t17DMHhSWsHKt9wWkmhcdqY0ercUOLuf6FtuhsxH1bK9UTI39ymZlDysgE/s2000/rp2040-01-technical-reference+SPI.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxv4AefbBMu3CoiIYYt6QfjJ_nNsH81k3JzBgn6wEPlzVF7Bbqtmfe272LnY8Q-PL2bqGHd1aqeYpfTuqE4t17DMHhSWsHKt9wWkmhcdqY0ercUOLuf6FtuhsxH1bK9UTI39ymZlDysgE/w640-h384/rp2040-01-technical-reference+SPI.jpg" width="640" /></a></div><br /><p>To get SPI pins programmatically: </p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhiW0OjonVubqCWV9aZTOqHUlql5O9ghnfFwi89PYnJc2lI8JcL0tpVa6q04Ml6HEgO2niKcDhOlJPSGqPEVksrp2YJh8ANBuVkJfNkDalvinfIeJLRFCEHrBlTbojaZZu7s5mDrpziOzk/s2000/rp2040Connect_SPIinfo+LED.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhiW0OjonVubqCWV9aZTOqHUlql5O9ghnfFwi89PYnJc2lI8JcL0tpVa6q04Ml6HEgO2niKcDhOlJPSGqPEVksrp2YJh8ANBuVkJfNkDalvinfIeJLRFCEHrBlTbojaZZu7s5mDrpziOzk/w640-h384/rp2040Connect_SPIinfo+LED.jpg" width="640" /></a></div><br /><div class="separator" style="clear: both; text-align: center;"><br /></div><div>ref: Nano RP2040 Connect pin out:</div><div><a href="https://docs.arduino.cc/static/8b9e4e17c1e1afa836057c5ba87c27c9/2f891/pinout.png" target="_blank">https://docs.arduino.cc/static/8b9e4e17c1e1afa836057c5ba87c27c9/2f891/pinout.png</a><br /><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="https://docs.arduino.cc/static/8b9e4e17c1e1afa836057c5ba87c27c9/2f891/pinout.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="800" data-original-width="800" height="640" src="https://docs.arduino.cc/static/8b9e4e17c1e1afa836057c5ba87c27c9/2f891/pinout.png" width="640" /></a></div><br /><div><br /><p><br /></p><p><br /></p></div></div>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-46905056206752760252021-10-29T08:52:00.007-07:002021-10-29T08:52:46.253-07:00Arduino IDE, open two independent Serial Monitor<p>
To open two Arduino IDEs, with independent board and Serial Monitor. Tested on
Arduino IDE 1.8 in Raspberry Pi OS, Windows 10 and Ubuntu 21.10.
</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/--d7E70IKRU" title="YouTube video player" width="560"></iframe>
</center>
<p>- Open new Arduino IDE from system, or<br />- from File Explorer.</p>
<p><br /></p>
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-5472084593726057942021-09-11T06:57:00.003-07:002021-09-11T07:07:38.981-07:00Arduino Nano RP2040 Connect (Arduino Framework) + ST7789 SPI LCD, using Adafruit ST7735 and ST7789 Library.<p>
This video show how to install "Adafruit ST7735 and ST7789 Library" on Arduino
IDE, tested with <a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">Arduino Nano RP2040 Connect</a> to display on 1.54 inch 240x240
and 2 inch 240x320 ST7789 SPI LCD, using hardware SPI and software SPI.
</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/aJuidRzPNUQ" title="YouTube video player" width="560"></iframe>
</center>
<p>
<b><u>Connection:</u></b>
</p>
<pre style="border: 1px solid black;"><code><span style="color: black;">Connection between ST7789 SPI to Arduino Nano RP2040 Connect,
using <b>HARDWARE SPI</b>.
ST7789 SPI Arduino Nano RP2040 Connect
GND GND
VCC 3V3
SCL 13
SDA 11
RES 9
DC 8
CS 10
BLK 3V3
</span></code></pre>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEio-18mj5ZoNRO59itjLLVal8te4wHT2IiznzjvgbfNtnagaaz2aq0NjIPQSlJB4Dt8PGONHCS-jh_q31dTC46F-BgS6pG5yRgxstqgeP6dWntFdVbi6p2fN1C9UG4wFOz8T77s23hZIYg/s2500/Nano_RP2040_ST7789_hardSPI_bbx.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2500" height="308" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEio-18mj5ZoNRO59itjLLVal8te4wHT2IiznzjvgbfNtnagaaz2aq0NjIPQSlJB4Dt8PGONHCS-jh_q31dTC46F-BgS6pG5yRgxstqgeP6dWntFdVbi6p2fN1C9UG4wFOz8T77s23hZIYg/w640-h308/Nano_RP2040_ST7789_hardSPI_bbx.png" width="640" /></a>
</div>
<br />
<pre style="border: 1px solid black;"><code><span style="color: black;">Connection between ST7789 SPI to Arduino Nano RP2040 Connect,
using <b>SOFTWARE SPI</b>.
ST7789 SPI Arduino Nano RP2040 Connect
GND GND
VCC 3V3
SCL 6
SDA 7
RES 9
DC 8
CS 10
BLK 3V3
</span></code></pre>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiU3U4matuQnxvzXVJ_VJqbdNECA6tFW0wF1X9a3k_8DIUGdIMeFYVZEVHo-kxVF_U-N7WmktNtJx7iDuIoP2-PcoP_U6aSBvO4RJfIHGVtm_pAYjDJSiodZxPgVoMQKhzWudq7hkzNmlA/s2500/Nano_RP2040_ST7789_softSPI_bbx.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2500" height="308" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiU3U4matuQnxvzXVJ_VJqbdNECA6tFW0wF1X9a3k_8DIUGdIMeFYVZEVHo-kxVF_U-N7WmktNtJx7iDuIoP2-PcoP_U6aSBvO4RJfIHGVtm_pAYjDJSiodZxPgVoMQKhzWudq7hkzNmlA/w640-h308/Nano_RP2040_ST7789_softSPI_bbx.png" width="640" /></a>
</div>
<br />
<div>graphicstest_NanoRP2040_ST7789_240x320_softSPI.ino, modified from graphicstest, to work on Arduino Nano RP2040 Connect, display on 240x320 ST7789 SPI LCD using software SPI.</div>
<pre style="border: 1px solid black;"><code><span>/**************************************************************************
This is a library for several Adafruit displays based on ST77* drivers.
Works with the Adafruit 1.8" TFT Breakout w/SD card
----> http://www.adafruit.com/products/358
The 1.8" TFT shield
----> https://www.adafruit.com/product/802
The 1.44" TFT breakout
----> https://www.adafruit.com/product/2088
The 1.14" TFT breakout
----> https://www.adafruit.com/product/4383
The 1.3" TFT breakout
----> https://www.adafruit.com/product/4313
The 1.54" TFT breakout
----> https://www.adafruit.com/product/3787
The 1.69" TFT breakout
----> https://www.adafruit.com/product/5206
The 2.0" TFT breakout
----> https://www.adafruit.com/product/4311
as well as Adafruit raw 1.8" TFT display
----> http://www.adafruit.com/products/618
Check out the links above for our tutorials and wiring diagrams.
These displays use SPI to communicate, 4 or 5 pins are required to
interface (RST is optional).
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution
**************************************************************************/
#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#if defined(ARDUINO_FEATHER_ESP32) // Feather Huzzah32
#define TFT_CS 14
#define TFT_RST 15
#define TFT_DC 32
#elif defined(ESP8266)
#define TFT_CS 4
#define TFT_RST 16
#define TFT_DC 5
#else
// For the breakout board, you can use any 2 or 3 pins.
// These pins will also work for the 1.8" TFT shield.
<b><span style="color: red;"> #define TFT_CS 10
#define TFT_RST 9 // Or set to -1 and connect to Arduino RESET pin
#define TFT_DC 8</span></b>
#endif
// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.
// For 1.44" and 1.8" TFT with ST7735 use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
// For 1.14", 1.3", 1.54", 1.69", and 2.0" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
<b><span style="color: red;">#define TFT_MOSI 7 // Data out
#define TFT_SCLK 6 // Clock out</span></b>
// For ST7735-based displays, we will use this call
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
// OR for the ST7789-based displays, we will use this call
<b><span style="color: red;">Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);</span></b>
float p = 3.1415926;
void setup(void) {
Serial.begin(9600);
Serial.print(F("Hello! ST77xx TFT Test"));
// Use this initializer if using a 1.8" TFT screen:
//tft.initR(INITR_BLACKTAB); // Init ST7735S chip, black tab
// OR use this initializer if using a 1.8" TFT screen with offset such as WaveShare:
// tft.initR(INITR_GREENTAB); // Init ST7735S chip, green tab
// OR use this initializer (uncomment) if using a 1.44" TFT:
//tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab
// OR use this initializer (uncomment) if using a 0.96" 160x80 TFT:
//tft.initR(INITR_MINI160x80); // Init ST7735S mini display
// OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
//tft.init(240, 240); // Init ST7789 240x240
// OR use this initializer (uncomment) if using a 1.69" 280x240 TFT:
//tft.init(240, 280); // Init ST7789 280x240
// OR use this initializer (uncomment) if using a 2.0" 320x240 TFT:
<b><span style="color: red;">tft.init(240, 320); // Init ST7789 320x240</span></b>
// OR use this initializer (uncomment) if using a 1.14" 240x135 TFT:
//tft.init(135, 240); // Init ST7789 240x135
// SPI speed defaults to SPI_DEFAULT_FREQ defined in the library, you can override it here
// Note that speed allowable depends on chip and quality of wiring, if you go too fast, you
// may end up with a black screen some times, or all the time.
//tft.setSPISpeed(40000000);
Serial.println(F("Initialized"));
uint16_t time = millis();
tft.fillScreen(ST77XX_BLACK);
time = millis() - time;
Serial.println(time, DEC);
delay(500);
// large block of text
tft.fillScreen(ST77XX_BLACK);
testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
delay(1000);
// tft print function!
tftPrintTest();
delay(4000);
// a single pixel
tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN);
delay(500);
// line draw test
testlines(ST77XX_YELLOW);
delay(500);
// optimized lines
testfastlines(ST77XX_RED, ST77XX_BLUE);
delay(500);
testdrawrects(ST77XX_GREEN);
delay(500);
testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
delay(500);
tft.fillScreen(ST77XX_BLACK);
testfillcircles(10, ST77XX_BLUE);
testdrawcircles(10, ST77XX_WHITE);
delay(500);
testroundrects();
delay(500);
testtriangles();
delay(500);
mediabuttons();
delay(500);
Serial.println("done");
delay(1000);
}
void loop() {
tft.invertDisplay(true);
delay(500);
tft.invertDisplay(false);
delay(500);
}
void testlines(uint16_t color) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(0, 0, x, tft.height()-1, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(0, 0, tft.width()-1, y, color);
delay(0);
}
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(tft.width()-1, 0, 0, y, color);
delay(0);
}
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(0, tft.height()-1, x, 0, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
delay(0);
}
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
delay(0);
}
}
void testdrawtext(char *text, uint16_t color) {
tft.setCursor(0, 0);
tft.setTextColor(color);
tft.setTextWrap(true);
tft.print(text);
}
void testfastlines(uint16_t color1, uint16_t color2) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t y=0; y < tft.height(); y+=5) {
tft.drawFastHLine(0, y, tft.width(), color1);
}
for (int16_t x=0; x < tft.width(); x+=5) {
tft.drawFastVLine(x, 0, tft.height(), color2);
}
}
void testdrawrects(uint16_t color) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
}
}
void testfillrects(uint16_t color1, uint16_t color2) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=tft.width()-1; x > 6; x-=6) {
tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
}
}
void testfillcircles(uint8_t radius, uint16_t color) {
for (int16_t x=radius; x < tft.width(); x+=radius*2) {
for (int16_t y=radius; y < tft.height(); y+=radius*2) {
tft.fillCircle(x, y, radius, color);
}
}
}
void testdrawcircles(uint8_t radius, uint16_t color) {
for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
tft.drawCircle(x, y, radius, color);
}
}
}
void testtriangles() {
tft.fillScreen(ST77XX_BLACK);
uint16_t color = 0xF800;
int t;
int w = tft.width()/2;
int x = tft.height()-1;
int y = 0;
int z = tft.width();
for(t = 0 ; t <= 15; t++) {
tft.drawTriangle(w, y, y, x, z, x, color);
x-=4;
y+=4;
z-=4;
color+=100;
}
}
void testroundrects() {
tft.fillScreen(ST77XX_BLACK);
uint16_t color = 100;
int i;
int t;
for(t = 0 ; t <= 4; t+=1) {
int x = 0;
int y = 0;
int w = tft.width()-2;
int h = tft.height()-2;
for(i = 0 ; i <= 16; i+=1) {
tft.drawRoundRect(x, y, w, h, 5, color);
x+=2;
y+=3;
w-=4;
h-=6;
color+=1100;
}
color+=100;
}
}
void tftPrintTest() {
tft.setTextWrap(false);
tft.fillScreen(ST77XX_BLACK);
tft.setCursor(0, 30);
tft.setTextColor(ST77XX_RED);
tft.setTextSize(1);
tft.println("Hello World!");
tft.setTextColor(ST77XX_YELLOW);
tft.setTextSize(2);
tft.println("Hello World!");
tft.setTextColor(ST77XX_GREEN);
tft.setTextSize(3);
tft.println("Hello World!");
tft.setTextColor(ST77XX_BLUE);
tft.setTextSize(4);
tft.print(1234.567);
delay(1500);
tft.setCursor(0, 0);
tft.fillScreen(ST77XX_BLACK);
tft.setTextColor(ST77XX_WHITE);
tft.setTextSize(0);
tft.println("Hello World!");
tft.setTextSize(1);
tft.setTextColor(ST77XX_GREEN);
tft.print(p, 6);
tft.println(" Want pi?");
tft.println(" ");
tft.print(8675309, HEX); // print 8,675,309 out in HEX!
tft.println(" Print HEX!");
tft.println(" ");
tft.setTextColor(ST77XX_WHITE);
tft.println("Sketch has been");
tft.println("running for: ");
tft.setTextColor(ST77XX_MAGENTA);
tft.print(millis() / 1000);
tft.setTextColor(ST77XX_WHITE);
tft.print(" seconds.");
}
void mediabuttons() {
// play
tft.fillScreen(ST77XX_BLACK);
tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
delay(500);
// pause
tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
delay(500);
// play color
tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
delay(50);
// pause color
tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
// play color
tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}
</span></code></pre>
<br />
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-90765962835762279322021-07-08T08:18:00.003-07:002021-07-08T08:18:41.499-07:00Change Arduino IDE Tab size, by editing preferences.txt.<p>This video show how to locate Arduino IDE's preferences.txt, and edit it to change Arduino Editor Tab size.</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/-VXmnpQKXXU" title="YouTube video player" width="560"></iframe>
</center>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-61480901180847665752021-06-30T14:36:00.003-07:002021-06-30T15:54:42.587-07:00UDP communication between Raspberry Pi/Python and Arduino Nano RP2040 Connect.<p>
This exercise run on Raspberry Pi/Python and Arduino Nano RP2040 Connect,
communicate in UDP.
</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOvXcV8vjI_m6PgGAcx2N-0E2iYN8y4H_UZ23G5LnW9eUhqdhdZ4qTHdYje2KZ50CctJHxkPdWHrpwPt1acMajwskE-qd6VRZV5QcjqotTZnlGkvyDg9H2-yiuM9JBtIHnTsfBy8qnvSc/s2000/UDP+communication+between+Raspberry+Pi+Python+and+Arduino+Nano+RP2040+Connect.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgOvXcV8vjI_m6PgGAcx2N-0E2iYN8y4H_UZ23G5LnW9eUhqdhdZ4qTHdYje2KZ50CctJHxkPdWHrpwPt1acMajwskE-qd6VRZV5QcjqotTZnlGkvyDg9H2-yiuM9JBtIHnTsfBy8qnvSc/w640-h384/UDP+communication+between+Raspberry+Pi+Python+and+Arduino+Nano+RP2040+Connect.jpg" width="640" /></a></div><p>WiFiNINA is needed, install it in Arduino IDE's Library Manager. </p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/ky7INpxLwU8" title="YouTube video player" width="560"></iframe>
</center>
<p><b><u>Exercise 1: Simple UDP example.</u></b></p>
<p>
With WiFiNINA installed and board of Arduino Nano RP2040 Connect
selected, you can load WiFiNINA example WiFiUdpSendReceiveString.
Remember to update ssid and password in arduino_secrets.h to match your WiFi
network. Upload it to Nano RP2040, open Serial Monitor, it will connect to the
WiFi network. Check the ip show in Serial Monitor.
</p>
<p>
In Raspberry Pi side, run the Python code with matched UDP_IP; simple send
message to nano RP2040 via UDP.
</p>
pyUDP_client_20210630.py
<pre style="border: 1px solid black;"><code><span style="color: black;"># ref:
# https://wiki.python.org/moin/UdpCommunication
import socket
#UDP_IP = "127.0.0.1"
#UDP_PORT = 5005
UDP_IP = "192.168.197.39"
UDP_PORT = 2390
MESSAGE = b"Hello, World!"
print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
</span></code></pre>
<br /><b><u>
Exercise 2: With GUI using PyQt5
</u></b><div><br /></div>
<div>Keep WiFiUdpSendReceiveString run on Nano RP2040.</div>
<div><br /></div>
<div>In Raspberry Pi side, run following code with GUI.</div>
<div><br /></div>
pyQt5_UDP_client_20210630.py
<pre style="border: 1px solid black;"><code><span style="color: black;">import sys
from pkg_resources import require
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
QTextEdit, QPushButton,
QVBoxLayout, QMessageBox)
from PyQt5.QtGui import QFont
from PyQt5.QtNetwork import QUdpSocket, QHostAddress
UDP_IP = "192.168.197.39"
UDP_PORT = 2390
print("Python version")
print(sys.version)
print()
class AppWindow(QWidget):
def __init__(self):
super().__init__()
self.sock = QUdpSocket(self)
self.sock.bind(QHostAddress(UDP_PORT), UDP_PORT)
self.sock.readyRead.connect(self.sock_readyRead_slot)
lbAppTitle = QLabel('Python UDP Client to send msg')
lbAppTitle.setFont(QFont('Anton', 15, QFont.Bold))
lbSysInfo = QLabel('Python:\n' + sys.version)
vboxInfo = QVBoxLayout()
vboxInfo.addWidget(lbAppTitle)
vboxInfo.addWidget(lbSysInfo)
self.edMsg = QTextEdit()
btnSend = QPushButton("Send")
btnSend.clicked.connect(self.btnSend_Clicked)
vboxMsg = QVBoxLayout()
vboxMsg.addWidget(self.edMsg)
vboxMsg.addWidget(btnSend)
vboxMain = QVBoxLayout()
vboxMain.addLayout(vboxInfo)
vboxMain.addLayout(vboxMsg)
vboxMain.addStretch()
self.setLayout(vboxMain)
self.setGeometry(100, 100, 500,400)
self.show()
def sock_readyRead_slot(self):
while self.sock.hasPendingDatagrams():
datagram, host, port = self.sock.readDatagram(
self.sock.pendingDatagramSize()
)
print("rx:")
message = '{}\nHost: {}\nPort: {}\n\n'.format(datagram.decode(),
host.toString(),
port)
print(message)
print()
def btnSend_Clicked(self):
msgToSend = self.edMsg.toPlainText()
print("tx:")
print(msgToSend)
print()
datagram = msgToSend.encode()
self.sock.writeDatagram(datagram, QHostAddress(UDP_IP), UDP_PORT)
def closeEvent(self, event):
close = QMessageBox.question(
self,
"QUIT",
"Close Application?",
QMessageBox.Yes | QMessageBox.No)
if close == QMessageBox.Yes:
print("Close")
event.accept()
else:
event.ignore()
if __name__ == '__main__':
print('run __main__')
app = QApplication(sys.argv)
window = AppWindow()
sys.exit(app.exec_())
print("- bye -")
</span></code></pre>
<div><br /></div>
<div><b><u>
Exercise 3: Raspberry Pi/Python remote control Nano RP2040 onboard RGB LED via
UDP.
</u></b></div>
<div><br /></div>
<div>
In Nano RP2040, modify to control onboard RGB LED base on incoming command:
start with "#RGB", follow with three bytes for R, G and B.
</div>
WiFiUdp_RGB__20210630.ino
<pre style="border: 1px solid black;"><code><span>/*
WiFi UDP to control Nano RP2040 Connect onboard RGB
*/
#include <SPI.h>
#include <WiFiNINA.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key index number (needed only for WEP)
unsigned int localPort = 2390; // local port to listen on
char packetBuffer[256]; //buffer to hold incoming packet
char ReplyBuffer[] = "acknowledged"; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
pinMode(LEDR, OUTPUT);
pinMode(LEDG, OUTPUT);
pinMode(LEDB, OUTPUT);
analogWrite(LEDR, 0);
analogWrite(LEDG, 0);
analogWrite(LEDB, 0);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
analogWrite(LEDR, 255);
analogWrite(LEDG, 255);
analogWrite(LEDB, 255);
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to WiFi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to WiFi");
printWifiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
Udp.begin(localPort);
analogWrite(LEDR, 0);
analogWrite(LEDG, 0);
analogWrite(LEDB, 0);
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
<span style="color: red;">String cmd = String(packetBuffer);
if(cmd.startsWith("#RGB")){
Serial.println("CMD: #RGB");
int valR = (int)(packetBuffer[4]);
int valG = (int)(packetBuffer[5]);
int valB = (int)(packetBuffer[6]);
Serial.println("R: " + String(valR));
Serial.println("G: " + String(valG));
Serial.println("B: " + String(valB));
analogWrite(LEDR, 255-valR);
analogWrite(LEDG, 255-valG);
analogWrite(LEDB, 255-valB);
}else{
Serial.println("NOT MATCH");
}</span>
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
</span></code></pre>
<div>In Raspberry Pi side:</div><div><br /></div>
pyQt5_UDP_client_RGB_20210630.py
<pre style="border: 1px solid black;"><code><span style="color: black;">import sys
from pkg_resources import require
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
QSlider, QPushButton,
QVBoxLayout, QHBoxLayout, QMessageBox)
from PyQt5.QtGui import QFont
from PyQt5.QtNetwork import QUdpSocket, QHostAddress
UDP_IP = "192.168.197.39"
UDP_PORT = 2390
print("Python version")
print(sys.version)
print()
class AppWindow(QWidget):
def __init__(self):
super().__init__()
self.sock = QUdpSocket(self)
self.sock.bind(QHostAddress(UDP_PORT), UDP_PORT)
self.sock.readyRead.connect(self.sock_readyRead_slot)
lbAppTitle = QLabel('Python UDP Client to control RGB')
lbAppTitle.setFont(QFont('Anton', 15, QFont.Bold))
lbSysInfo = QLabel('Python:\n' + sys.version)
vboxInfo = QVBoxLayout()
vboxInfo.addWidget(lbAppTitle)
vboxInfo.addWidget(lbSysInfo)
lbR = QLabel(' R: ')
self.sliderR = QSlider(Qt.Horizontal, self)
self.sliderR.setRange(0, 255)
self.sliderR.valueChanged.connect(self.sliderRGB_valueChanged_slot)
boxR = QHBoxLayout()
boxR.addWidget(lbR)
boxR.addWidget(self.sliderR)
lbG = QLabel(' G: ')
self.sliderG = QSlider(Qt.Horizontal, self)
self.sliderG.setRange(0, 255)
self.sliderG.valueChanged.connect(self.sliderRGB_valueChanged_slot)
boxG = QHBoxLayout()
boxG.addWidget(lbG)
boxG.addWidget(self.sliderG)
lbB = QLabel(' B: ')
self.sliderB = QSlider(Qt.Horizontal, self)
self.sliderB.setRange(0, 255)
self.sliderB.valueChanged.connect(self.sliderRGB_valueChanged_slot)
boxB = QHBoxLayout()
boxB.addWidget(lbB)
boxB.addWidget(self.sliderB)
boxRGB = QVBoxLayout()
boxRGB.addLayout(boxR)
boxRGB.addLayout(boxG)
boxRGB.addLayout(boxB)
btnSend = QPushButton("Update")
btnSend.clicked.connect(self.btnSend_Clicked)
vboxMsg = QVBoxLayout()
vboxMsg.addLayout(boxRGB)
vboxMsg.addWidget(btnSend)
vboxMain = QVBoxLayout()
vboxMain.addLayout(vboxInfo)
vboxMain.addLayout(vboxMsg)
vboxMain.addStretch()
self.setLayout(vboxMain)
self.setGeometry(100, 100, 500,400)
self.show()
def sock_readyRead_slot(self):
while self.sock.hasPendingDatagrams():
datagram, host, port = self.sock.readDatagram(
self.sock.pendingDatagramSize()
)
print("rx:")
message = '{}\nHost: {}\nPort: {}\n\n'.format(datagram.decode(),
host.toString(),
port)
print(message)
print()
def btnSend_Clicked(self):
print("tx:")
valueR = self.sliderR.value()
valueG = self.sliderG.value()
valueB = self.sliderB.value()
CMD_RGB = "#RGB"
bCMD_RGB = str.encode(CMD_RGB) + bytes([valueR, valueG, valueB])
print(type(bCMD_RGB))
print("CMD: ", bCMD_RGB)
self.sock.writeDatagram(bCMD_RGB, QHostAddress(UDP_IP), UDP_PORT)
"""
msgToSend = self.edMsg.toPlainText()
print("tx:")
print(msgToSend)
print()
datagram = msgToSend.encode()
self.sock.writeDatagram(datagram, QHostAddress(UDP_IP), UDP_PORT)
"""
def sliderRGB_valueChanged_slot(self):
print("sliderRGB_valueChanged_slot")
valueR = self.sliderR.value()
valueG = self.sliderG.value()
valueB = self.sliderB.value()
print(" R: ", valueR, " G: ", valueG, " B: ", valueB)
CMD_RGB = "#RGB"
bCMD_RGB = str.encode(CMD_RGB) + bytes([valueR, valueG, valueB])
print(type(bCMD_RGB))
print(bCMD_RGB)
def closeEvent(self, event):
close = QMessageBox.question(
self,
"QUIT",
"Close Application?",
QMessageBox.Yes | QMessageBox.No)
if close == QMessageBox.Yes:
print("Close")
event.accept()
else:
event.ignore()
if __name__ == '__main__':
print('run __main__')
app = QApplication(sys.argv)
window = AppWindow()
sys.exit(app.exec_())
print("- bye -")
</span></code></pre>
<div><br /></div>
<hr />
~ <a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">More exercise of Arduino Nano RP2040 Connect</a>.
<div><br /></div>
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-51930606255994625372021-06-24T12:48:00.008-07:002021-06-24T13:49:10.451-07:00Arduino Nano RP2040 Connect + ILI9341 SPI TFT, using adafruit_ILI9341 library.<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2EbBEjtfM8-4t6FFokLolXRMGeHnz6TXY7THz-QjrrFnZdV2kQjSs_ZgK99pSjYdFyf5swEWQNVMaS2FQMN3MA0gX9eafarH_JULeP7QWHfrDF84nlBZwLxB9lnMuMBAaubXCp2f4cx0/s800/NanoRP2040_ILI9341_001.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="604" data-original-width="800" height="484" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2EbBEjtfM8-4t6FFokLolXRMGeHnz6TXY7THz-QjrrFnZdV2kQjSs_ZgK99pSjYdFyf5swEWQNVMaS2FQMN3MA0gX9eafarH_JULeP7QWHfrDF84nlBZwLxB9lnMuMBAaubXCp2f4cx0/w640-h484/NanoRP2040_ILI9341_001.jpg" width="640" /></a>
</div>
<p>
To drive ILI9341 SPI TFT on Arduino Nano RP2040 Connect (Arduino
framework),
<a href="https://github.com/adafruit/Adafruit_ILI9341" target="_blank">Adafruit_ILI9341 library</a>
can be used.
</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/UoOqeK_F1lM" title="YouTube video player" width="560"></iframe>
</center>
<p>
<b><u>Install Library:</u></b>
</p>
<p>
In Arduino IDE, open Library Manager, search and install Adafruit
ILI9341, Adafruit GFX library is needed also.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKiR5kLlkaji1-WTanI04O-SEv4z_EGcLaNCqhmL_-9x8-RRCpTBH7LmzmknEeHluTYBYePwOrtNfcg7S_8g71t-t8W8Omfs5rXJ1gf_c1tlWRcC-cOEbBzHoFG7Gj9oUUAfWBCIX_vo0/s2000/Adafruit+ILI9341+library.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKiR5kLlkaji1-WTanI04O-SEv4z_EGcLaNCqhmL_-9x8-RRCpTBH7LmzmknEeHluTYBYePwOrtNfcg7S_8g71t-t8W8Omfs5rXJ1gf_c1tlWRcC-cOEbBzHoFG7Gj9oUUAfWBCIX_vo0/w640-h384/Adafruit+ILI9341+library.jpg" width="640" /></a>
</div>
<div class="separator" style="clear: both; text-align: center;"><br /></div>
You will be asked to install extra libraries needed, click Install All.
<div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhh5mlMJfrEbAIzApB1nFJNoE634PFB6q-lhKfAtOPKTHp2eolz3WMnp9fU5-DS2VxDMcyREPHLSogwQ2N0rMUnt6cUcwpVIVLNSBHLK0Fj-VG1glL2-MD9R0RUJj3TRCcnnEaV0ditv3A/s2000/Adafruit+ILI9341+library_2.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhh5mlMJfrEbAIzApB1nFJNoE634PFB6q-lhKfAtOPKTHp2eolz3WMnp9fU5-DS2VxDMcyREPHLSogwQ2N0rMUnt6cUcwpVIVLNSBHLK0Fj-VG1glL2-MD9R0RUJj3TRCcnnEaV0ditv3A/w640-h384/Adafruit+ILI9341+library_2.jpg" width="640" /></a>
</div>
<p>
<b><u>Connection:</u></b>
</p>
</div>
<pre style="border: 1px solid black;"><code><span style="color: black;">Connection:
ILI9341 TFT Nano RP2040 Connect
-------------------------------
VCC 3V3
GND GND
CS D10
RESET RESET
DC D9
SDI(MOSI) D11 (SPI0 TX)
SCK D13 (SPI0 SCK)
LED 3V3
SDA(MISO) D12 (SPI0 RX)
</span></code></pre>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijtm5ojd6WoBgu_TwEsH4u98sCBVXsVQDA1yryAb4w-2yrFl4IlkdRCmHCKsTKbQ78vDxuCSLy_BgpfXoxlozmrKgT1466jhjCwjrDCheffECHjftbBzKj0XkpHf-zJ282zZ52Zkhv4UI/s2048/nanoRP2040+ILI9341_X_bbxx.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1205" data-original-width="2048" height="376" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijtm5ojd6WoBgu_TwEsH4u98sCBVXsVQDA1yryAb4w-2yrFl4IlkdRCmHCKsTKbQ78vDxuCSLy_BgpfXoxlozmrKgT1466jhjCwjrDCheffECHjftbBzKj0XkpHf-zJ282zZ52Zkhv4UI/w640-h376/nanoRP2040+ILI9341_X_bbxx.png" width="640" /></a>
</div>
<div>After then, you can try Adafruit_ILI9341 example graphicstest.</div>
<hr />
~
<a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">More exercise of Arduino Nano RP2040 Connect</a>.
<br />
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-5030260355607153462021-06-23T06:58:00.004-07:002021-06-23T08:05:14.715-07:00BLE Communication between Nano RP2040 Connect (Peripheral) and ESP32 (Central), in Arduino framework.<p>Exercise of BLE Communication between Nano RP2040 Connect (Peripheral) and ESP32 (Central), in Arduino framework.</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinM27YRrss6vaX3oQMrR5r3rH-79cA5QI3AMqYAGD6Fne_AfeCTw5qWFi6qGxqT11H3welMqTAP7iTUIDj7ZqJOdex0R8LfjBmz6rHtAX8LwOCipfhpyb0I8pdWiLNXjrTT-doSNXw8V0/s2016/BLE_nanoRP2040_ESP32.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1216" data-original-width="2016" height="386" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEinM27YRrss6vaX3oQMrR5r3rH-79cA5QI3AMqYAGD6Fne_AfeCTw5qWFi6qGxqT11H3welMqTAP7iTUIDj7ZqJOdex0R8LfjBmz6rHtAX8LwOCipfhpyb0I8pdWiLNXjrTT-doSNXw8V0/w640-h386/BLE_nanoRP2040_ESP32.jpg" width="640" /></a></div><p><b>nanoRP2040_BLE_Peripheral_20210623a.ino</b> run on Arduino Nano RP2040 Connect, act as BLE Peripheral (server), wait to be connected.</p><pre style="border: 1px solid black;"><code><span style="color: black;">/*
* Arduino nano RP2040 Connect exercise:
* as BLE Peripheral
*
* reference:
* ArduinoBLE library-
* https://www.arduino.cc/en/Reference/ArduinoBLE
*
* In my implementation:
* BLEByteCharacteristic written event checked by polling.
* BLEStringCharacteristic/BLEIntCharacteristic using event haandler.
*
*/
#include <ArduinoBLE.h>
/* Visit Online GUID / UUID Generator
* (https://www.guidgenerator.com/)
* to generate your uuid
*/
const char* serviceUUID = "20a07a95-8c12-484c-94fa-b828c4465a3c";
const char* byteCharUUID = "d34dda3b-7b4a-4ce3-9666-a8338db4e604";
const char* stringCharUUID = "41281b9c-8dc4-4649-8cbe-c39fa01513e2";
const char* intCharUUID = "c7d27dc6-f4d8-4523-b060-3e2e4c187808";
const char* myLocalName = "MyBLE";
BLEService myBLEService(serviceUUID);
BLEByteCharacteristic myBLEByteCharacteristic(byteCharUUID,
BLERead|BLEWrite);
BLEStringCharacteristic myBLEStringCharacteristic(stringCharUUID,
BLERead|BLEWrite|BLENotify, 24); //max length = 10
BLEIntCharacteristic myBLEIntCharacteristic(intCharUUID,
BLERead|BLEWrite);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Serial.begin(115200);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
//Started, connect Serial to begin
while(!Serial);
Serial.println("\n---Start ---");
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Initialize BLE...");
if(!BLE.begin()){
Serial.println("Starting BLE failed!");
while(1);
}
Serial.println("BLE initialized.");
Serial.print("MAC: ");
Serial.println(BLE.address());
Serial.println("Service UUIID: \t\t\t" + String(serviceUUID));
Serial.println("Byte Characteristic UUIID: \t" + String(byteCharUUID));
Serial.println("String Characteristic UUIID: \t" + String(stringCharUUID));
Serial.println("Int Characteristic UUIID: \t" + String(intCharUUID));
Serial.println();
BLE.setLocalName(myLocalName);
BLE.setAdvertisedService(myBLEService);
myBLEService.addCharacteristic(myBLEByteCharacteristic);
myBLEService.addCharacteristic(myBLEStringCharacteristic);
myBLEService.addCharacteristic(myBLEIntCharacteristic);
BLE.addService(myBLEService);
myBLEStringCharacteristic.setEventHandler(BLEWritten, myBLEString_Written_Hndl);
myBLEIntCharacteristic.setEventHandler(BLEWritten, myBLEInt_Written_Hndl);
BLE.advertise();
}
void loop() {
BLEDevice central = BLE.central();
if(central){
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Connected: ");
Serial.println(central.address());
while(central.connected()){
if(myBLEByteCharacteristic.written()){
byte valByte = myBLEByteCharacteristic.value();
Serial.print("myBLEByteCharacteristic received: ");
Serial.println(valByte, HEX);
}
}
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Disconnected.");
}
}
// Event Handler for myBLEStringCharacteristic Written
// Print received Sring, and write back in upper case.
void myBLEString_Written_Hndl(BLEDevice central, BLECharacteristic characteristic) {
Serial.print("BLEStringCharacteristic event, written: ");
Serial.println("myBLEStringCharacteristic received: len=" +
String(myBLEStringCharacteristic.valueLength()));
String valString = myBLEStringCharacteristic.value();
Serial.println(valString);
valString.toUpperCase();
Serial.println(valString);
myBLEStringCharacteristic.setValue(valString);
}
// Event Handler for myBLEIntCharacteristic Written
void myBLEInt_Written_Hndl(BLEDevice central, BLECharacteristic characteristic) {
Serial.print("BLEIntCharacteristic event, written: ");
int valInt = myBLEIntCharacteristic.value();
Serial.println(valInt);
}
</span></code></pre>
<br /><b>
ESP32_BLE_Central_20210623a.ino run</b> on ESP32 Dev. Board, act as Central (client), scan and connect to Peripheral, and send something.<pre style="border: 1px solid black;"><code><span style="color: black;">/*
* ESP32 BLE exercise, as Central (Client)
* connect to nanoRP2040 BLE Peripheral
*
*/
#include "BLEDevice.h"
const String targetName = "MyBLE";
// The remote service/characteristic we wish to connect to.
// UUID(s) have to match with Peripheral side.
const char* serviceUUID = "20a07a95-8c12-484c-94fa-b828c4465a3c";
const char* byteCharUUID = "d34dda3b-7b4a-4ce3-9666-a8338db4e604";
const char* stringCharUUID = "41281b9c-8dc4-4649-8cbe-c39fa01513e2";
const char* intCharUUID = "c7d27dc6-f4d8-4523-b060-3e2e4c187808";
static BLEUUID BLEUUID_service(serviceUUID);
static BLEUUID BLEUUID_byteChar(byteCharUUID);
static BLEUUID BLEUUID_stringChar(stringCharUUID);
static BLEUUID BLEUUID_intChar(intCharUUID);
static BLERemoteCharacteristic* pRemoteChar_byte;
static BLERemoteCharacteristic* pRemoteChar_string;
static BLERemoteCharacteristic* pRemoteChar_int;
static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLEAdvertisedDevice* myDevice;
int notifyDur;
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
Serial.println("pRemoteChar_string notify callback -");
Serial.println(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.println(length);
Serial.print("data: ");
Serial.println((char*)pData);
}
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
}
void onDisconnect(BLEClient* pclient) {
connected = false;
Serial.println("onDisconnect");
}
};
bool connectToServer() {
Serial.print("Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();
Serial.println(" - Created client");
pClient->setClientCallbacks(new MyClientCallback());
// Connect to the remove BLE Server.
pClient->connect(myDevice);
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(BLEUUID_service);
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(BLEUUID_service.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our service");
// Obtain a reference to the characteristic in the service of the remote BLE server.
pRemoteChar_byte = pRemoteService->getCharacteristic(BLEUUID_byteChar);
pRemoteChar_string = pRemoteService->getCharacteristic(BLEUUID_stringChar);
pRemoteChar_int = pRemoteService->getCharacteristic(BLEUUID_intChar);
//assume all characteristics found, skip checking
/*
if (pRemoteChar_string == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(BLEUUID_stringChar.toString().c_str());
pClient->disconnect();
return false;
}
*/
Serial.println(" - Found our characteristic");
// Read the value of the characteristic.
if(pRemoteChar_string->canRead()) {
std::string value = pRemoteChar_string->readValue();
Serial.print("The characteristic value was: ");
Serial.println(value.c_str());
}
if(pRemoteChar_string->canNotify()){
Serial.println("pRemoteChar_string CAN Notify");
pRemoteChar_string->registerForNotify(notifyCallback);
}else{
Serial.println("pRemoteChar_string CANNOT Notify");
}
connected = true;
return true;
}
/**
* Scan for BLE servers and find the first one matched advertises service
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
/**
* Called for each advertising BLE server.
*/
void onResult(BLEAdvertisedDevice advertisedDevice) {
//Serial.print("BLE Advertised Device found: ");
//Serial.println(advertisedDevice.toString().c_str());
String devName = advertisedDevice.getName().c_str();
//Serial.println(devName);
if(devName == targetName){
Serial.println("Target found-");
// We have found a device,
// let us now see if it contains the service we are looking for.
Serial.println(advertisedDevice.getServiceUUID().toString().c_str());
if (advertisedDevice.haveServiceUUID() &&
advertisedDevice.isAdvertisingService(BLEUUID_service)) {
Serial.println("BLEUUID_service match -");
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);
doConnect = true;
doScan = true;
} // Found our server
}
} // onResult
}; // MyAdvertisedDeviceCallbacks
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("\n--- ESP32 Start ---");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
pBLEScan->start(5, false);
}
// This is the Arduino main loop function.
void loop() {
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {
if (connectToServer()) {
Serial.println("We are now connected to the BLE Server.");
} else {
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
// If we are connected to a peer BLE Server, update the characteristic each time we are reached
// with the current time since boot.
if (connected) {
notifyDur = millis();
String newValue = "time since boot: " + String(notifyDur/1000);
// Set the characteristic's value to be the array of bytes that is actually a string.
pRemoteChar_string->writeValue(newValue.c_str(), newValue.length());
pRemoteChar_int->writeValue(notifyDur, true);
}else if(doScan){
BLEDevice::getScan()->start(0);
}
delay(1000); // Delay a second between loops.
} // End of loop
</span></code></pre>
<br />
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/lXLIFmSEyOo" title="YouTube video player" width="560"></iframe>
</center>
<br />
<hr />
~ <a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">More exercise of Arduino Nano RP2040 Connect</a>.<br />
<br />Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-10068855655598117722021-06-21T12:07:00.005-07:002021-06-21T12:36:12.664-07:00ArduinoBLE exercise on Nano RP2040 Connect: BLE PeripheralArduinoBLE exercise run on Nano RP2040 Connect, act as BLE Peripheral. Tested
with nRF Connect app on Android.<div><br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCETPrc-TEon9r_lpMODxPAWN-r0N27SsUzENhBt5I-KazzhQN-zfJDHVlTVfY94HxoTsec2QSRU7swdwtu_3ezJs2MUpTgQ18TeZszwt304FpCxdyzpFT7-pavv4WZ3mhyNQkmZKiCRw/s2000/nanoRP2040_BLE_Peripheral_20210622a.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCETPrc-TEon9r_lpMODxPAWN-r0N27SsUzENhBt5I-KazzhQN-zfJDHVlTVfY94HxoTsec2QSRU7swdwtu_3ezJs2MUpTgQ18TeZszwt304FpCxdyzpFT7-pavv4WZ3mhyNQkmZKiCRw/w640-h384/nanoRP2040_BLE_Peripheral_20210622a.jpg" width="640" /></a></div><br /><div>nanoRP2040_BLE_Peripheral_20210622a.ino</div><pre style="border: 1px solid black;"><code><span style="color: black;">/*
* Arduino nano RP2040 Connect exercise:
* as BLE Peripheral
*
* reference:
* ArduinoBLE library-
* https://www.arduino.cc/en/Reference/ArduinoBLE
*
* In my implementation:
* BLEByteCharacteristic written event checked by polling.
* BLEStringCharacteristic/BLEIntCharacteristic using event haandler.
*
*/
#include <ArduinoBLE.h>
/* Visit Online GUID / UUID Generator
* (https://www.guidgenerator.com/)
* to generate your uuid
*/
const char* serviceUUID = "20a07a95-8c12-484c-94fa-b828c4465a3c";
const char* byteCharUUID = "d34dda3b-7b4a-4ce3-9666-a8338db4e604";
const char* stringCharUUID = "41281b9c-8dc4-4649-8cbe-c39fa01513e2";
const char* intCharUUID = "c7d27dc6-f4d8-4523-b060-3e2e4c187808";
const char* myLocalName = "MyBLE";
BLEService myBLEService(serviceUUID);
BLEByteCharacteristic myBLEByteCharacteristic(byteCharUUID,
BLERead|BLEWrite);
BLEStringCharacteristic myBLEStringCharacteristic(stringCharUUID,
BLERead|BLEWrite, 10); //max length = 10
BLEIntCharacteristic myBLEIntCharacteristic(intCharUUID,
BLERead|BLEWrite);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Serial.begin(115200);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
//Started, connect Serial to begin
while(!Serial);
Serial.println("\n---Start ---");
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Initialize BLE...");
if(!BLE.begin()){
Serial.println("Starting BLE failed!");
while(1);
}
Serial.println("BLE initialized.");
Serial.print("MAC: ");
Serial.println(BLE.address());
Serial.println("Service UUIID: \t\t\t" + String(serviceUUID));
Serial.println("Byte Characteristic UUIID: \t" + String(byteCharUUID));
Serial.println("String Characteristic UUIID: \t" + String(stringCharUUID));
Serial.println("Int Characteristic UUIID: \t" + String(intCharUUID));
Serial.println();
BLE.setLocalName(myLocalName);
BLE.setAdvertisedService(myBLEService);
myBLEService.addCharacteristic(myBLEByteCharacteristic);
myBLEService.addCharacteristic(myBLEStringCharacteristic);
myBLEService.addCharacteristic(myBLEIntCharacteristic);
BLE.addService(myBLEService);
myBLEStringCharacteristic.setEventHandler(BLEWritten, myBLEString_Written_Hndl);
myBLEIntCharacteristic.setEventHandler(BLEWritten, myBLEInt_Written_Hndl);
BLE.advertise();
}
void loop() {
BLEDevice central = BLE.central();
if(central){
digitalWrite(LED_BUILTIN, HIGH);
Serial.print("Connected: ");
Serial.println(central.address());
while(central.connected()){
if(myBLEByteCharacteristic.written()){
byte valByte = myBLEByteCharacteristic.value();
Serial.print("myBLEByteCharacteristic received: ");
Serial.println(valByte, HEX);
}
}
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Disconnected.");
}
}
// Event Handler for myBLEStringCharacteristic Written
// Print received Sring, and write back in upper case.
void myBLEString_Written_Hndl(BLEDevice central, BLECharacteristic characteristic) {
Serial.print("BLEStringCharacteristic event, written: ");
Serial.println("myBLEStringCharacteristic received: len=" +
String(myBLEStringCharacteristic.valueLength()));
String valString = myBLEStringCharacteristic.value();
Serial.println(valString);
valString.toUpperCase();
Serial.println(valString);
myBLEStringCharacteristic.setValue(valString);
}
// Event Handler for myBLEIntCharacteristic Written
void myBLEInt_Written_Hndl(BLEDevice central, BLECharacteristic characteristic) {
Serial.print("BLEIntCharacteristic event, written: ");
int valInt = myBLEIntCharacteristic.value();
Serial.println(valInt);
}
</span></code></pre>
<div><br /></div>
</div>
<center>
<iframe width="560" height="315" src="https://www.youtube.com/embed/N2jgS2i42ck" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</center>
<hr />
~ <a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">More exercises for Arduino Nano RP2040 Connect</a><br />
<br />Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-835518297094326242021-06-13T11:32:00.005-07:002021-09-07T06:19:58.716-07:00Raspberry Pi/Python BLE Central + Arduino Nano RP2040 Connect BLE Peripheral<p>
This exercise implement Python 3 code run on Raspberry Pi act as BLE Central,
connect to Arduino Nano RP2040 Connect act as BLE Peripheral. And send data
(0x01/0x00) to turn the Nano RP2040 Connect's onboard LED ON/OFF.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghZ6Vku_mQr8JXYMpVre9tY4I5vnUKL4Ek-ijtDRw5c8gDu4pGWRe9kePQat_r53pLQ3N-VsQ9COJmnKgP0LWxJ9RBY-hMbBSgsy12mlN-LSnpSJXVMPto8o1SglJZoER8CxUEBGKh-Uo/s2012/BLE_Python_NanoRP2040.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1262" data-original-width="2012" height="402" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghZ6Vku_mQr8JXYMpVre9tY4I5vnUKL4Ek-ijtDRw5c8gDu4pGWRe9kePQat_r53pLQ3N-VsQ9COJmnKgP0LWxJ9RBY-hMbBSgsy12mlN-LSnpSJXVMPto8o1SglJZoER8CxUEBGKh-Uo/w640-h402/BLE_Python_NanoRP2040.jpg" width="640" /></a>
</div>
<br />
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/PNMfmOn3ths" title="YouTube video player" width="560"></iframe>
</center>
<p>
<b><u>Arduino Nano RP2040 Connect act as BLE Peripheral side:</u></b>
</p>
<p>- Make sure ArduinoBLE library is installed.</p>
<p>
- The Arduino code is modified from ArduinoBLE Examples > Peripheral >
CallbackLED. With MAC, Service UUID, Characteristic UUID, and BLE written data
displayed. Such that we can program Central side accordingly.
</p>
nanoRP2040_BLE_CallbackLED.ino
<pre style="border: 1px solid black;"><code><span style="color: black;">/*
Callback LED
This example creates a BLE peripheral with service that contains a
characteristic to control an LED. The callback features of the
library are used.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic BLE central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include <ArduinoBLE.h>
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // create service
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
const int ledPin = LED_BUILTIN; // pin to use for the LED
void setup() {
Serial.begin(9600);
while (!Serial);
delay(1000);
Serial.println("\n--- Start---");
pinMode(ledPin, OUTPUT); // use the LED pin as an output
// begin initialization
if (!BLE.begin()) {
Serial.println("starting BLE failed!");
while (1);
}
</span><span style="color: red;">Serial.print("My BLE MAC:\t\t ");
Serial.println(BLE.address());
Serial.print("Service UUID:\t\t ");
Serial.println(ledService.uuid());
Serial.print("Characteristic UUID:\t ");
Serial.println(switchCharacteristic.uuid());
Serial.println();</span><span style="color: black;">
// set the local name peripheral advertises
BLE.setLocalName("LEDCallback");
// set the UUID for the service this peripheral advertises
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
// add service
BLE.addService(ledService);
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
// assign event handlers for characteristic
switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
switchCharacteristic.setValue(0);
// start advertising
BLE.advertise();
Serial.println(("Bluetooth device active, waiting for connections..."));
}
void loop() {
// poll for BLE events
BLE.poll();
}
void blePeripheralConnectHandler(BLEDevice central) {
// central connected event handler
Serial.print("Connected event, central: ");
Serial.println(central.address());
}
void blePeripheralDisconnectHandler(BLEDevice central) {
// central disconnected event handler
Serial.print("Disconnected event, central: ");
Serial.println(central.address());
}
void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) {
// central wrote new value to characteristic, update LED
Serial.println("Characteristic event, written: ");
</span><span style="color: red;">byte charValue = switchCharacteristic.value();
Serial.println(charValue);</span><span style="color: black;">
if (charValue) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
</span></code></pre>
<p>
<b><u>Raspberry Pi/Python BLE Central Side:</u></b><br />- bluepy library is used to control Bluetooth BLE.</p><p>To install bluepy for Python3, enter the command:<br /><b>$ sudo pip3 install bluepy</b></p><p>- tkinter is
used for GUI.
</p>
<p>
<b>py_BLE_Central_LedControl.py</b> connect to Peripheral with matched
MAC, and search for service/characteristic with match UUID. Then send
0x01/0x00 to turn ON/OFF the Nano RP2040 Connect's onboard LED.
</p>
<pre style="border: 1px solid black;"><code><span style="color: black;">"""
Python/Raspberry Pi BluetoothLE exercise:
using bluepy library
Work with Arduino Nano RP2040 Connect example:
ArduinoBLE > Peripheral > CallbackLED
Connect to Peripheral with matched MAC.
Check for service uuid and characteristic uuid,
if matched found: send bytes 0x01 and 0x00 for three time
to turn Nano RP2040 Connect onboard LED ON/OFF.
"""
from bluepy import btle
import time
#Have to match with Peripheral
MAC = "84:cc:a8:2e:8d:76"
SERVICE_UUID = "19b10000-e8f2-537e-4f6c-d104768a1214"
CHARACTERISTIC_UUID = "19b10001-e8f2-537e-4f6c-d104768a1214"
nanoRP2040_Char = None
print("Hello")
print("Connect to:" + MAC)
dev = btle.Peripheral(MAC)
print("\n--- dev ----------------------------")
print(type(dev))
print(dev)
print("\n--- dev.services -------------------")
for svc in dev.services:
print(str(svc))
print("\n------------------------------------")
print("Get Serice By UUID: " + SERVICE_UUID)
service_uuid = btle.UUID(SERVICE_UUID)
service = dev.getServiceByUUID(service_uuid)
print(service)
print("\n--- service.getCharacteristics() ---")
print(type(service.getCharacteristics()))
print(service.getCharacteristics())
#----------------------------------------------
characteristics = dev.getCharacteristics()
print("\n--- dev.getCharacteristics() -------")
print(type(characteristics))
print(characteristics)
for char in characteristics:
print("----------")
print(type(char))
print(char)
print(char.uuid)
if(char.uuid == CHARACTERISTIC_UUID ):
print("=== !CHARACTERISTIC_UUID matched! ==")
nanoRP2040_Char = char
print(char)
print(dir(char))
#print(char.getDescriptors)
#print(char.propNames)
#print(char.properties)
#print(type(char.read()))
print(char.read())
bytes_ON = b'\x01'
bytes_OFF = b'\x00'
if nanoRP2040_Char != None:
print("\nnanoRP2040_Char found")
print(nanoRP2040_Char)
for i in range(3):
nanoRP2040_Char.write(bytes_ON, True)
print(nanoRP2040_Char.read())
time.sleep(1.0)
nanoRP2040_Char.write(bytes_OFF, True)
print(nanoRP2040_Char.read())
time.sleep(1.0)
else:
print("\nnanoRP2040_Char NOT found!")
#=============================================
dev.disconnect()
print("\n--- bye ---\n")<span style="font-family: Times New Roman;"><span style="white-space: normal;">
</span></span></span></code></pre>
<div>
pyTk_BLE_Central_LedControl.py implement GUI with tkinter, user click on
button to turn ON/OFF LED.
</div>
<pre style="border: 1px solid black;"><code><span style="color: black;">"""
Python/Raspberry Pi BluetoothLE exercise:
using bluepy library
Work with Arduino Nano RP2040 Connect example:
ArduinoBLE > Peripheral > CallbackLED
Connect to Peripheral with matched MAC.
Check for service uuid and characteristic uuid,
if matched found:
Start GUI to control Nano RP2040 Connect onboard LED
"""
from bluepy import btle
import time
import tkinter as tk
#Have to match with Peripheral
MAC = "84:cc:a8:2e:8d:76"
SERVICE_UUID = "19b10000-e8f2-537e-4f6c-d104768a1214"
CHARACTERISTIC_UUID = "19b10001-e8f2-537e-4f6c-d104768a1214"
nanoRP2040_Char = None
def toggle():
if toggle_btn.config('relief')[-1] == 'sunken':
toggle_btn.config(relief="raised")
nanoRP2040_Char.write(bytes_OFF, True)
toggle_btn['text'] = 'Turn LED ON'
else:
toggle_btn.config(relief="sunken")
nanoRP2040_Char.write(bytes_ON, True)
toggle_btn['text'] = 'Turn LED OFF'
print("Hello")
print("Connect to:" + MAC)
dev = btle.Peripheral(MAC)
print("\n--- dev ----------------------------")
print(type(dev))
print(dev)
print("\n--- dev.services -------------------")
for svc in dev.services:
print(str(svc))
print("\n------------------------------------")
print("Get Serice By UUID: " + SERVICE_UUID)
service_uuid = btle.UUID(SERVICE_UUID)
service = dev.getServiceByUUID(service_uuid)
print(service)
print("\n--- service.getCharacteristics() ---")
print(type(service.getCharacteristics()))
print(service.getCharacteristics())
#----------------------------------------------
characteristics = dev.getCharacteristics()
print("\n--- dev.getCharacteristics() -------")
print(type(characteristics))
print(characteristics)
for char in characteristics:
print("----------")
print(type(char))
print(char)
print(char.uuid)
if(char.uuid == CHARACTERISTIC_UUID ):
print("=== !CHARACTERISTIC_UUID matched! ==")
nanoRP2040_Char = char
print(char)
print(dir(char))
#print(char.getDescriptors)
#print(char.propNames)
#print(char.properties)
#print(type(char.read()))
print(char.read())
bytes_ON = b'\x01'
bytes_OFF = b'\x00'
if nanoRP2040_Char != None:
print("\nnanoRP2040_Char found")
print(nanoRP2040_Char)
root = tk.Tk()
label = tk.Label( root, text="Toggle button to Turn ON/OFF the nano RP040 Connect LED")
label.pack(pady=10)
toggle_btn = tk.Button(text="Turn LED ON", width=12, relief="raised", command=toggle)
toggle_btn.pack(pady=10)
root.geometry("500x200")
#Place tkinter window center
root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id()))
root.title("arduino-er.blogspot.com")
root.mainloop()
else:
print("\nnanoRP2040_Char NOT found!")
#=============================================
dev.disconnect()
print("\n--- bye ---\n")
</span></code></pre>
<div><br /></div>
<hr />
~
<a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">More exercises of Arduino Nano RP2040 Connect</a>.
<div>~ <a href="https://helloraspberrypi.blogspot.com/2021/08/bi-direction-ble-communication-between.html" target="_blank">Another exercise: Bi-direction BLE communication between Raspberry Pi/Python (with PyQt5 GUI) and ESP32/Arduino Nano RP2040 Connect</a></div><div><br /></div>
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-49843820381340093932021-06-11T13:58:00.002-07:002021-06-27T14:09:34.405-07:00Arduino Nano RP2040 Connect exercise: control onboard RGB LED<p>
The Nano RP2040 Connect onboard RGB LED is connected through the W-102 module,
so the WiFiNINA library needs to be installed and included in sketch.
</p>
<p>Exercise to control onboard RGB LED.</p>
<pre style="border: 1px solid black;"><code><span style="color: black;">#include <WiFiNINA.h>
void setup() {
delay(2000);
Serial.begin(9600);
Serial.println(LEDR);
Serial.println(LEDG);
Serial.println(LEDB);
pinMode(LEDR, OUTPUT);
pinMode(LEDG, OUTPUT);
pinMode(LEDB, OUTPUT);
digitalWrite(LEDR, HIGH); //RED
digitalWrite(LEDG, HIGH); //GREEN
digitalWrite(LEDB, HIGH); //BLUE
}
void loop() {
delay(1000);
digitalWrite(LEDR, LOW); //RED
digitalWrite(LEDG, LOW); //GREEN
digitalWrite(LEDB, LOW); //BLUE
delay(1000);
digitalWrite(LEDR, HIGH); //RED
digitalWrite(LEDG, LOW); //GREEN
digitalWrite(LEDB, LOW); //BLUE
delay(1000);
digitalWrite(LEDR, LOW); //RED
digitalWrite(LEDG, HIGH); //GREEN
digitalWrite(LEDB, LOW); //BLUE
delay(1000);
digitalWrite(LEDR, LOW); //RED
digitalWrite(LEDG, LOW); //GREEN
digitalWrite(LEDB, HIGH); //BLUE
}
</span></code></pre>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigfG7A9jPu2oiHmommRbGwccYgbpX1NLs1u2Pnstqi1KaVHu51BzKkSPlADk1vsK9iFIlNMi6EDjZfR_WALOymkEyfDFPMwfyru1nN95-qV9AcV7DXaM5DImZ1vE7o9tWOpFiI4At_0YBn/s2000/nanoRP2040_RGB.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEigfG7A9jPu2oiHmommRbGwccYgbpX1NLs1u2Pnstqi1KaVHu51BzKkSPlADk1vsK9iFIlNMi6EDjZfR_WALOymkEyfDFPMwfyru1nN95-qV9AcV7DXaM5DImZ1vE7o9tWOpFiI4At_0YBn/w640-h384/nanoRP2040_RGB.jpg" width="640" /></a>
</div>
<br />
<hr />
<p><b>update@20211-06-28:</b><br /></p><p>After WiFiNINA library updated, the code <b>Serial.println(LEDR)</b> (also LEDG and LEDB) throw error of :</p><p><i>error: call to 'NinaPin::operator int' declared with attribute error: Change me to a #define Serial.println(LEDR);</i></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIUztTe_WoaxCqwyGcjWs-4FlxyPcKc3pJcpyMbZ0aiR-14XaShU6NU6dugQi215VA2mPg8SNdKL6viSfXMFv2T9aSWajONFdpteby2EhCWXh9IeXBr2niDNQgMFM8HcRHx5qkvHxe85c/s1800/error_WiFiNINA_RGB.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIUztTe_WoaxCqwyGcjWs-4FlxyPcKc3pJcpyMbZ0aiR-14XaShU6NU6dugQi215VA2mPg8SNdKL6viSfXMFv2T9aSWajONFdpteby2EhCWXh9IeXBr2niDNQgMFM8HcRHx5qkvHxe85c/w640-h384/error_WiFiNINA_RGB.png" width="640" /></a></div><p>Just comment the codes to make it work.</p>
rpiihttp://www.blogger.com/profile/11029985001257500904noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-14356311489367366432021-06-10T09:10:00.001-07:002021-06-11T14:02:19.219-07:00Arduino Nano RP2040 Connect example: read onboard LSM6DSOX IMU module (accelerometer and gyroscope)Examples to read <b><a href="http://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect.html">Nano RP2040 Connect</a></b> onboard LSM6DSOX IMU module (accelerometer and gyroscope), in Arduino framework.<div><br /></div><div><b><u>Install LSM6DSOX library:</u></b></div><div><br /></div><div>- Open Library Manager in Arduino IDE:</div><div>Click on Menu Sketch > Include Library > Manager Libraries...</div><div><br /></div><div>- Search and install <b>Arduino_LSM6DSOX</b> library.</div><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhALXxCsJYa9GYKiAk_KHIYFbjHrA9ntYMFmJllnPAzZNMCkYJBGQUXNMSGMiOhDQKz9JlVEqY-jJFwLE_txvRMEJOHkpZQzR-kRxhiBx8MLcRVTfuqhPlUDrnzC6oucqWXvgdJMGwv5gz/s2000/Arduino_LSM6DSOX+library.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhALXxCsJYa9GYKiAk_KHIYFbjHrA9ntYMFmJllnPAzZNMCkYJBGQUXNMSGMiOhDQKz9JlVEqY-jJFwLE_txvRMEJOHkpZQzR-kRxhiBx8MLcRVTfuqhPlUDrnzC6oucqWXvgdJMGwv5gz/w640-h384/Arduino_LSM6DSOX+library.jpg" width="640" /></a></div><br /><div><b><u>LSM6DSOX examples:</u></b></div><div><br /></div><div>Now you can try LSM6DSOX examples to read accelerometer and gyroscope data from Nano RP2040 Connect onboard LSM6DSOX IMU module.</div><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLLGqcq81EXZwU-QLNTrCPlmq2U_mefhLK5zRFesQ4pu_rhla0aiJT4r11i5M7XCl7STHki6alp9urFviDOJsDE33z0tmZSLDNhRpwB8HXzti-TUUpsPrUC982vBmPHnSjWzogNRIadZIo/s2000/Arduino_LSM6DSOX+Examples.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhLLGqcq81EXZwU-QLNTrCPlmq2U_mefhLK5zRFesQ4pu_rhla0aiJT4r11i5M7XCl7STHki6alp9urFviDOJsDE33z0tmZSLDNhRpwB8HXzti-TUUpsPrUC982vBmPHnSjWzogNRIadZIo/w640-h384/Arduino_LSM6DSOX+Examples.jpg" width="640" /></a></div><br /><div>with graphical view using Menu > Tools > Serial Plotter.</div><div><br /></div><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto;"><tbody><tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsyWtJF_T0jQV_38gTQ4R9QLJPAlSQFmgBBIbM2cW4k4cx3sf4Y9glH4KK0WhXzPPP7COID6Sns-ZPL_lGtM9YC2RuaTyknjtrygn-T2ZZrfaTNV2ZZRbW1WvOob_g8Z7L-LTAHC3R20Rf/s2000/SimpleAccelerometer.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsyWtJF_T0jQV_38gTQ4R9QLJPAlSQFmgBBIbM2cW4k4cx3sf4Y9glH4KK0WhXzPPP7COID6Sns-ZPL_lGtM9YC2RuaTyknjtrygn-T2ZZrfaTNV2ZZRbW1WvOob_g8Z7L-LTAHC3R20Rf/w640-h384/SimpleAccelerometer.jpg" width="640" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">SimpleAccelerometer</td></tr></tbody></table><br /><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto;"><tbody><tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhO7BIN46_GpwwuVQuQjD1EgQmx6IjRU2WBmYUxJilk0i7N5NYu1TKTy7mnyI1yO8Yqj1SGBV3-pXGFqBplrsV0NxDWJ4mU0if6RmRq76Zr75bsNZ1SXoCoYSntO18GCtHvho0c4uqR0gtF/s2000/SimpleGyroscope.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhO7BIN46_GpwwuVQuQjD1EgQmx6IjRU2WBmYUxJilk0i7N5NYu1TKTy7mnyI1yO8Yqj1SGBV3-pXGFqBplrsV0NxDWJ4mU0if6RmRq76Zr75bsNZ1SXoCoYSntO18GCtHvho0c4uqR0gtF/w640-h384/SimpleGyroscope.jpg" width="640" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;">SimpleGyroscope</td></tr></tbody></table><br /><div><br /></div><div><br /></div><div><br /></div>rpiihttp://www.blogger.com/profile/11029985001257500904noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-7418471093102517582021-06-09T07:50:00.019-07:002022-03-15T13:28:52.707-07:00Arduino Nano RP2040 Connect<p>Just receive Arduino Nano RP2040 Connect:</p>
<div class="separator" style="clear: both; text-align: right;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8GVXO47Z15y5BIlaEzKXIX-7qqIaXhZNoUdE7oAnJunmsvfk859-Tg_8AE37ghZYU7KcEC2uMqu_jzQZdb6Omdef9aHiNV0sYu2-ndBZeH7dBBDbrvhcIK19KMvkSMZ133da6sC0IQjRg/s800/Arduino+Nano+RP2040+Connect_01.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="604" data-original-width="800" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8GVXO47Z15y5BIlaEzKXIX-7qqIaXhZNoUdE7oAnJunmsvfk859-Tg_8AE37ghZYU7KcEC2uMqu_jzQZdb6Omdef9aHiNV0sYu2-ndBZeH7dBBDbrvhcIK19KMvkSMZ133da6sC0IQjRg/s320/Arduino+Nano+RP2040+Connect_01.jpg" width="320" /></a>
</div>
<br />
<div class="separator" style="clear: both; text-align: right;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSjT1UHTu9JSX1Ro8VQNTKgERhpbG-IHQGSB-HnVIKp4dl0LIhXEHLfsICf5m3fTcSuN_eEOi-uXnJ5J7QI8Cr4xZs88q8FDd8upyECTrDpYMusvQeERlh2Z5xUUpGqXXs39Uxyr7m36gC/s800/Arduino+Nano+RP2040+Connect_02.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="604" data-original-width="800" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhSjT1UHTu9JSX1Ro8VQNTKgERhpbG-IHQGSB-HnVIKp4dl0LIhXEHLfsICf5m3fTcSuN_eEOi-uXnJ5J7QI8Cr4xZs88q8FDd8upyECTrDpYMusvQeERlh2Z5xUUpGqXXs39Uxyr7m36gC/s320/Arduino+Nano+RP2040+Connect_02.jpg" width="320" /></a>
</div>
<br />
<div class="separator" style="clear: both; text-align: right;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjC9Lv0cpUdBapFBHPQJUG26xlUHUdIW7G_9iQg5e2txJZoOaIXJ_6jD65e_T97DwD1OK3IrnnUhB0DOBIdh5u7YvXlmmhpNFxvKJsZaRPKd7ahCxZkUWBH5jvvb9VltBmENxqg5yungZX8/s800/Arduino+Nano+RP2040+Connect_03.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="604" data-original-width="800" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjC9Lv0cpUdBapFBHPQJUG26xlUHUdIW7G_9iQg5e2txJZoOaIXJ_6jD65e_T97DwD1OK3IrnnUhB0DOBIdh5u7YvXlmmhpNFxvKJsZaRPKd7ahCxZkUWBH5jvvb9VltBmENxqg5yungZX8/s320/Arduino+Nano+RP2040+Connect_03.jpg" width="320" /></a>
</div>
<p><br /></p>
<hr />
Install Nano RP2040 Connect to Arduino IDE and fix "An error occurred while
uploading the sketch":
<div>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/Q6j0TMrnD4E" title="YouTube video player" width="560"></iframe>
</center>
<br />
<b> Install Arduino Nano RP2040 Connect board to Arduino IDE.</b>
<div><br /></div>
<div>- Open Board Manager in Arduino IDE.</div>
<div>
<div>
- Search and install Arduino Mbed OS Nano Boards by Arduino. It's version
2.1.0 currently.
</div>
<div><br /></div>
<div class="separator" style="clear: both; text-align: right;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPBcebioM1qe6BTyLCa12WOcKoeGyXjQDjEsN4l3BcSeiO_yKh-9dAGfVjiWe2goLE5Ng0KIT-eJ37ef-WRphw6Sm5_b84fXI012MguDiXnjIat7pTcE947oUsazoME78lpGNyukxYI9CA/s2000/01_install+Arduino+Mbed+OS+Nano+Boards.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPBcebioM1qe6BTyLCa12WOcKoeGyXjQDjEsN4l3BcSeiO_yKh-9dAGfVjiWe2goLE5Ng0KIT-eJ37ef-WRphw6Sm5_b84fXI012MguDiXnjIat7pTcE947oUsazoME78lpGNyukxYI9CA/s320/01_install+Arduino+Mbed+OS+Nano+Boards.jpg" width="320" /></a>
</div>
<br />
<div>
- Once installed, Arduino Mbed OS Nano Boards > Arduino Nano RP2040
Connect will available in board selection list.
</div>
</div>
<div class="separator" style="clear: both; text-align: right;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-nBoqu9Q2oZvx9fwNf492dEFCoy8Ni05Xu2FujN7bFjMlA7Hf32vJxRsY1zR4zDW5gt_m7g3xUFxl-Fix9hPBfZZ29dFkFUONUBivnZS7l4SX3_wGkxTB4Dr5Vo-CD6GV-9sksxdyq7KB/s2000/02_Mbed+OS+Nano+Boards_Arduino+Nano+RP2040+Connect.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-nBoqu9Q2oZvx9fwNf492dEFCoy8Ni05Xu2FujN7bFjMlA7Hf32vJxRsY1zR4zDW5gt_m7g3xUFxl-Fix9hPBfZZ29dFkFUONUBivnZS7l4SX3_wGkxTB4Dr5Vo-CD6GV-9sksxdyq7KB/s320/02_Mbed+OS+Nano+Boards_Arduino+Nano+RP2040+Connect.jpg" width="320" /></a>
</div>
<br />If you have XIAO BLE Sense also, check <a href="https://embedded-things.blogspot.com/2022/03/remark-on-arduino-nano-rp2040-connect.html" target="_blank">Remark on "Arduino Nano RP2040 Connect" of "Arduino Mbed OS Boards" vs "Arduino Mbed OS Nano Boards"</a>.<br /><br />
<hr />
<div>Fix "<b>An error occurred while uploading the sketch</b>".</div>
<div><br /></div>
<div>
In my case on Raspberry Pi, sketch cannot be uploaded; with "An error
occurred while uploading the sketch".
</div>
<div><br /></div>
<div>To fix it:</div>
<div>- Switch to mbed_rp2040 installed folder:</div>
<pre style="border: 1px solid black;"><code><span style="color: black;">/home/pi/.arduino15/packages/arduino/hardware/mbed_rp2040/2.1.0
</span></code></pre>
<div>- Run post_install.sh:</div>
<pre style="border: 1px solid black;"><code><span style="color: black;">$ sudo ./post_install.sh
</span></code></pre>
<div class="separator" style="clear: both; text-align: right;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmELeMz9nd21Jd2lp3LP1-c2eEHg5-J9m87TQeDskyxoWXsKKziRjGe7NDHkrYQ185CqrwvSlXw-8j9oEAfoRBrDjpaNKzWUsQZJ-8b7Vr5Ys9gSIWBmsoU7Zi3H3t0aJQGfAX-5rMTfl4/s2000/03_post_install.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmELeMz9nd21Jd2lp3LP1-c2eEHg5-J9m87TQeDskyxoWXsKKziRjGe7NDHkrYQ185CqrwvSlXw-8j9oEAfoRBrDjpaNKzWUsQZJ-8b7Vr5Ys9gSIWBmsoU7Zi3H3t0aJQGfAX-5rMTfl4/s320/03_post_install.jpg" width="320" /></a>
</div>
<div><br /></div>
<div>- Then, you can upload the sketch again.</div>
<div><br /></div>
</div>
<hr />
More exercise:<br />~ <a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect-example.html">read onboard LSM6DSOX IMU module (accelerometer and gyroscope)</a><div>~ <a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect-exercise.html">control onboard RGB LED</a><br />~ <a href="https://arduino-er.blogspot.com/2021/06/raspberry-pipython-ble-central-arduino.html">Raspberry Pi/Python BLE Central + Arduino Nano RP2040 Connect BLE Peripheral</a><br />~ <a href="https://arduino-er.blogspot.com/2021/06/arduinoble-exercise-on-nano-rp2040.html">ArduinoBLE exercise, act as BLE Peripheral</a><br />~ <a href="https://arduino-er.blogspot.com/2021/06/ble-communication-between-nano-rp2040.html">BLE Communication between Nano RP2040 Connect (Peripheral) and ESP32 (Central), in Arduino framework</a><br />~ <a href="https://arduino-er.blogspot.com/2021/06/arduino-nano-rp2040-connect-ili9341-spi.html">Arduino Nano RP2040 Connect + ILI9341 SPI TFT, using adafruit_ILI9341 library</a><br />~ <a href="https://arduino-er.blogspot.com/2021/06/udp-communication-between-raspberry.html">UDP communication between Raspberry Pi/Python and Arduino Nano RP2040 Connect</a><br />~ <a href="https://arduino-er.blogspot.com/2021/09/arduino-nano-rp2040-connect-arduino.html">Arduino Nano RP2040 Connect (Arduino Framework) + ST7789 SPI LCD, using Adafruit ST7735 and ST7789 Library</a><br />~ <a href="https://arduino-er.blogspot.com/2021/11/spi-pins-in-arduino-nano-rp2040-connect.html">SPI pins in Arduino Nano RP2040 Connect</a><br />~ <a href="https://arduino-er.blogspot.com/2021/11/arduino-nano-rp2040-connect-st7735-spi.html">Arduino Nano RP2040 Connect + ST7735 SPI TFT with SD Card, read and display bitmap - hardware SPI</a><br />~ <a href="https://arduino-er.blogspot.com/2021/11/arduino-nano-rp2040-connect-generate-qr.html">Arduino Nano RP2040 Connect generate QR Code and display on ST7735 TFT - software SPI</a></div><div><br /></div>rpiihttp://www.blogger.com/profile/11029985001257500904noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-26574751998140107642021-05-19T11:25:00.003-07:002021-05-19T11:36:16.743-07:00ESP32/Arduino BLE UART Client connect to Raspberry Pi Pico/CircuitPython + ESP32/nina-fw<p>
It's a BLE UART Client exercise run on ESP2-DevKitC using arduino-esp32
framework. Connect to cpyPico_ESP32_BLE.py in <a href="https://helloraspberrypi.blogspot.com/2021/05/raspberry-pi-picocircuitpython_16.html" target="_blank">Raspberry Pi Pico/CircuitPython + ESP32/adafruit nina-fw (act as WiFi/BLE
Co-Processor)</a>.
</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicMHxYnFnCZSwbyRzrxPG1BxkGgxt9OE9OxS8p2khXRP4u1FkLWcRliaNtRthKgPLl6Z5HczpyVSTtqS45RiSC43mhsyt_InvmITO8aQHtQIVM6cnVgw5ke4RSFF4JtKSfUc2v226xc9k/s2000/ESP32_BLE_client.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicMHxYnFnCZSwbyRzrxPG1BxkGgxt9OE9OxS8p2khXRP4u1FkLWcRliaNtRthKgPLl6Z5HczpyVSTtqS45RiSC43mhsyt_InvmITO8aQHtQIVM6cnVgw5ke4RSFF4JtKSfUc2v226xc9k/w640-h384/ESP32_BLE_client.jpg" width="640" /></a></div><br /><p>It search BLE device with specified service UUID, and characteristics for TX
and RX. Then sending something every 5 seconds. In the Pico/CircuitPython
+ESP32/nina-fw server side, receive and echo back every bytes. This client
then print the received byte on Terminal.</p>
ESP32_BLE_client.ino
<pre style="border: 1px solid black;"><code><span style="color: black;">/*
Modify from Arduino Examples for ESP32 Dev Module:
> ESP32 BLE Arduino > BLE_client
*/
#include "BLEDevice.h"
//#include "BLEScan.h"
#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" // RX Characteristic
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" // TX Characteristic
static BLEUUID serviceUUID(SERVICE_UUID);
static BLEUUID charUUID_RX(CHARACTERISTIC_UUID_RX);
static BLEUUID charUUID_TX(CHARACTERISTIC_UUID_TX);
static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pTXCharacteristic;
static BLERemoteCharacteristic* pRXCharacteristic;
static BLEAdvertisedDevice* myDevice;
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
/*
Serial.print("Notify callback for characteristic ");
Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.println(length);
Serial.print("data: ");
Serial.println((char*)pData);
*/
Serial.print((char*)pData);
}
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
}
void onDisconnect(BLEClient* pclient) {
connected = false;
Serial.println("onDisconnect");
}
};
bool connectToServer() {
Serial.print("Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();
Serial.println(" - Created client");
pClient->setClientCallbacks(new MyClientCallback());
// Connect to the remove BLE Server.
pClient->connect(myDevice);
// if you pass BLEAdvertisedDevice instead of address,
// it will be recognized type of peer device address (public or private)
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our service");
// =================================================================================
// Obtain a reference to the characteristic in the service of the remote BLE server.
// charUUID_TX
pTXCharacteristic = pRemoteService->getCharacteristic(charUUID_TX);
if (pTXCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(charUUID_TX.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found charUUID_TX characteristic");
// Read the value of the characteristic.
if(pTXCharacteristic->canRead()) {
std::string value = pTXCharacteristic->readValue();
Serial.print("The characteristic value was: ");
Serial.println(value.c_str());
}
if(pTXCharacteristic->canNotify())
pTXCharacteristic->registerForNotify(notifyCallback);
// =================================================================================
// Obtain a reference to the characteristic in the service of the remote BLE server.
// charUUID_RX
pRXCharacteristic = pRemoteService->getCharacteristic(charUUID_RX);
if (pRXCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(charUUID_RX.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found charUUID_RX characteristic");
String helloValue = "Hello Remote Server";
pRXCharacteristic->writeValue(helloValue.c_str(), helloValue.length());
// =================================================================================
connected = true;
return true;
}
/**
* Scan for BLE servers and find the first one that
* advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
/**
* Called for each advertising BLE server.
*/
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.print("BLE Advertised Device found: ");
Serial.println(advertisedDevice.toString().c_str());
// We have found a device,
// let us now see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() &&
advertisedDevice.isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);
doConnect = true;
doScan = true;
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
void setup() {
Serial.begin(115200);
Serial.println("Starting Arduino BLE Client application...");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
pBLEScan->start(5, false);
} // End of setup.
// This is the Arduino main loop function.
void loop() {
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {
if (connectToServer()) {
Serial.println("We are now connected to the BLE Server.");
} else {
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
// If we are connected to a peer BLE Server,
// update the characteristic each time we are reached
// with the current time since boot.
if (connected) {
//String newValue = "Time since boot: " + String(millis()/1000 + "\n");
//Serial.println("Setting new characteristic value to \"" + newValue + "\"");
String newValue = " " + String(millis()/1000);
// Set the characteristic's value to be the array of bytes that is actually a string.
pRXCharacteristic->writeValue(newValue.c_str(), newValue.length());
}else if(doScan){
BLEDevice::getScan()->start(0);
// this is just example to start scan after disconnect,
// most likely there is better way to do it in arduino
}
delay(5000); // Delay a second between loops.
} // End of loop
</span></code></pre>
<br />
<br />
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-86240874398276400892021-04-29T07:52:00.002-07:002021-04-29T07:52:55.445-07:00ESP32-C3/Arduino (ESP32-C3-DevKitM-1) read Network Time from pool.ntp.org<p>It's a example from arduino-esp32, ESP32 >Time > SimpleTime, to read Network Time from pool.ntp.org.</p><p>Tested on ESP32-C3 (ESP32-C3-DevKitM-1).</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEin_H-SMtnDecnzahkl1J5PuBUpTc6ibY-VBA_v9x7tU_SkJZjfVJ9Z3WBlHzXkNRhQ26mxZWwoV9IlxzS4ubMcAvDn31SKBoISRKNMtXozk7jP4GFxsdOQVkJpDCtQ9uMJYtWXNKj5HSM/s2000/SimpleTime.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEin_H-SMtnDecnzahkl1J5PuBUpTc6ibY-VBA_v9x7tU_SkJZjfVJ9Z3WBlHzXkNRhQ26mxZWwoV9IlxzS4ubMcAvDn31SKBoISRKNMtXozk7jP4GFxsdOQVkJpDCtQ9uMJYtWXNKj5HSM/w640-h384/SimpleTime.jpg" width="640" /></a></div><br /><p>Currently, to program ESP32-C3 using Arduino, <a href="https://arduino-er.blogspot.com/2021/04/install-arduino-esp32-200-alpha1-on.html">Install arduino-esp32 2.0.0-alpha1 on Arduino IDE</a>.</p><p><br /></p>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-30549851579551060292021-04-28T13:07:00.009-07:002021-04-30T11:29:50.988-07:00ESP32-S2/Arduino (ESP32-S2-Saola-1) web server control onboard RGB LED (NeoPixel)<p></p>
<div class="separator" style="clear: both; text-align: center;">
<a
href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-rnkWIc-9Va1MeLQ-UblJAv23qsW7mPyNIxvMXBDzWXx7S6JTtzNySgShKMXcNk7438q5bqW44M19pnMEb0jPyp5J6eo8DKqnHYRXBI49n0CXFBdrPJ44PAqIjFurPALwU5EQ7nmBdOc/s1000/arduino-esp32-S2_NeoPixel_01.jpg"
style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"
><img
border="0"
data-original-height="754"
data-original-width="1000"
src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-rnkWIc-9Va1MeLQ-UblJAv23qsW7mPyNIxvMXBDzWXx7S6JTtzNySgShKMXcNk7438q5bqW44M19pnMEb0jPyp5J6eo8DKqnHYRXBI49n0CXFBdrPJ44PAqIjFurPALwU5EQ7nmBdOc/s320/arduino-esp32-S2_NeoPixel_01.jpg"
width="320"
/></a>
</div>
With <a
href="http://arduino-er.blogspot.com/2021/04/install-arduino-esp32-200-alpha1-on.html"
>arduino-esp32 2.0.0-alpha1 installed</a
>, we can program ESP32-S2 using Arduino IDE.
<p></p>
<p>
This exercise run on ESP32-S2-Saola-1 (ESP32-S2), act as access point, setup
web server, and turn ON/OFF onboard RGB LED (NeoPixel) according to user
click.
</p>
<p>
Scroll down to have another exercise changing onboard LED color with HTML
ColorPicker.
</p>
<p>The onboard RGB LED of ESP32-S2-Saola-1 is connected to GPIO18.</p>
<p>
Adafruit NeoPixel library is needed, can be install in Arduino IDE's Library
Manager.
</p>
<br />
<center>
<iframe
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen=""
frameborder="0"
height="315"
src="https://www.youtube.com/embed/ZZ2nC_37W6c"
title="YouTube video player"
width="560"
></iframe>
</center>
<br />
<p>ESP32_WebRGB.ino</p>
<pre style="border: 1px solid black;"><code><span style="color: black;">/*
A simple web server that lets you blink the onboard RGB LED via the web.
Run on ESP32-S2-Saola-1 (ESP32-S2),
ast as access point, setup web server,
and turn ON/OFF onboard RGB LED (NexPixel) accordingly.
The onboard RGB LED of ESP32-S2-Saola-1 is connected to GPIO18.
http://yourAddress/H turns the LED on
http://yourAddress/L turns it off
reference examples in Arduino:
Examples > WiFi > WiFiAccessPoint
Examples > WiFi > SimpleWiFiServer
Examples > Adafruit NeoPixel > simple
*/
#include <Adafruit_NeoPixel.h>
#include <WiFi.h>
#include <Esp.h>
//Onboard RGB LED (NeoPixel)
#define PIXELPIN 18
#define NUMPIXELS 1
const char* ssid = "esp32s2";
const char* password = "password";
const char* html="<html>"
"<head>"
"<meta charset=\"utf-8\">"
"<title>ESP32-S2 Web control NeoPixel</title>"
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">"
"</head>"
"<body>"
"Click <a href=\"/H\">here</a> to turn the RGB LED (NeoPixel) ON.<br>"
"Click <a href=\"/L\">here</a> to turn the RGB LED (NeoPixel) OFF.<br>"
"</body>"
"</html>";
Adafruit_NeoPixel pixel(NUMPIXELS, PIXELPIN, NEO_GRB + NEO_KHZ800);
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
pixel.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
pixel.clear(); // Set pixel colors to 'off'
pixel.show();
delay(1);
Serial.printf("\n\n---Start---\n");
Serial.print("Chip Model: ");
Serial.print(ESP.getChipModel());
Serial.print("\nChip Revision: ");
Serial.print(ESP.getChipRevision());
Serial.println();
Serial.println();
Serial.println("Configuring access point...");
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
}
int value = 0;
void loop(){
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("New Client."); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
client.print(html);
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
Serial.println("\n--- ON ---");
pixel.setPixelColor(0, pixel.Color(100, 100, 0));
}
if (currentLine.endsWith("GET /L")) {
Serial.println("\n--- OFF ---");
pixel.setPixelColor(0, pixel.Color(0, 0, 0));
}
pixel.show();
}
}
// close the connection:
client.stop();
Serial.println("Client Disconnected.");
}
}
</span></code></pre>
<br />
<br />
<hr />
<b>
ESP32-S2/Arduino (ESP32-S2-Saola-1) web control onboard NeoPixel, with HTML
ColorPicker</b
>
<div><br /></div>
<div>
This another exercise run on ESP32-S2-Saola-1 (ESP32-S2), act as station,
connect to mobile hotspot, setup web server. User can open the web page using
browsers on mobile, change LED color using HTML ColorPicker.
</div>
<div><br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a
href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTBIk-0awZPCDBgHRHkb78sTGI2VUy-0lu9Nn1haNRsQddi1yL7YbWHG1D8ycU9QOE5GIz7ZokNoVgN3gtOanVe8jtcsp79Ox8UjNVDsrRuT5iFM4DNeNBUCNtaysum5A619xMaC3Ekps/s1000/ESP32_WebRGB_ColorPicker_01.jpg"
style="margin-left: 1em; margin-right: 1em;"
><img
border="0"
data-original-height="754"
data-original-width="1000"
height="482"
src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiTBIk-0awZPCDBgHRHkb78sTGI2VUy-0lu9Nn1haNRsQddi1yL7YbWHG1D8ycU9QOE5GIz7ZokNoVgN3gtOanVe8jtcsp79Ox8UjNVDsrRuT5iFM4DNeNBUCNtaysum5A619xMaC3Ekps/w640-h482/ESP32_WebRGB_ColorPicker_01.jpg"
width="640"
/></a>
</div>
<div><br /></div>
<center>
<iframe width="560" height="315" src="https://www.youtube.com/embed/3uViG48xwoQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</center>
<br /><a href="https://github.com/me-no-dev/ESPAsyncWebServer" target="_blank"
>ESPAsyncWebServer</a
>
and the
<a href="https://github.com/me-no-dev/AsyncTCP" target="_blank">AsyncTCP</a>
libraries are need.<br />
<div><br /></div>
<div>
ESP32_WebRGB_ColorPicker.ino
<pre
style="border: 1px solid black;"
><code><span style="color: black;">#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Adafruit_NeoPixel.h>
//Onboard RGB LED (NeoPixel)
#define PIXELPIN 18
#define NUMPIXELS 1
Adafruit_NeoPixel pixel(NUMPIXELS, PIXELPIN, NEO_GRB + NEO_KHZ800);
AsyncWebServer server(80);
// ssid/password match your WiFi Network
const char* ssid = "ssid";
const char* password = "password";
const char* Param_COLOR ="color";
// HTML
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
<title>ESP32-S2 exercise</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>
<p>Select Color</p>
<form action="/get">
<input name="color" type="color">
<input type="submit" value="Update RGB">
</form><br>
</body></html>)rawliteral";
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
void setup() {
Serial.begin(115200);
Serial.println("---Start---");
Serial.println("Chip Model: ");
Serial.println(ESP.getChipModel());
Serial.println("\nChip Revision: ");
Serial.println(ESP.getChipRevision());
Serial.println();
pixel.begin(); // INITIALIZE NeoPixel
pixel.clear(); // Set pixel colors to 'off'
pixel.show();
//Act as STA, connect to WiFi network
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
return;
}
Serial.println();
Serial.print("Visit IP Address: ");
Serial.println(WiFi.localIP());
// Send HTML
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html);
});
// Send a GET request to <ESP_IP>/get?color=#rrggbb
server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
String color_value;
//check if parameter "color" found
if (request->hasParam(Param_COLOR)) {
Serial.println("param_COLOR received");
color_value = request->getParam(Param_COLOR)->value();
Serial.println(color_value);
//Convert intMessage in #rrggbb form to r,g,b
color_value.remove(0, 1);
int intColor = hstol(color_value);
int r = (intColor & 0xff0000)>>16;
int g = (intColor & 0x00ff00)>>8;
int b = (intColor & 0x0000ff);
Serial.println(r);
Serial.println(g);
Serial.println(b);
//set NeoPixel color
pixel.setPixelColor(0, pixel.Color(r, g, b));
pixel.show();
}
else {
Serial.println("No color found");
}
//re-send html
request->send_P(200, "text/html", index_html);
});
server.onNotFound(notFound);
server.begin();
}
//hex-string to long
long hstol(String recv){
char c[recv.length() + 1];
recv.toCharArray(c, recv.length() + 1);
return strtol(c, NULL, 16);
}
void loop() {
}
</span></code></pre>
<br />
</div>
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com1tag:blogger.com,1999:blog-5298160027330696474.post-75676414032849614712021-04-27T11:18:00.009-07:002021-04-29T07:55:51.860-07:00Install arduino-esp32 2.0.0-alpha1 on Arduino IDE, Alpha preview with support for ESP32-S2 and ESP32-C3.<p>
Currently (as on 2021-04-28), arduino-esp32 support ESP32-S2 and ESP32-C3 in
development release 2.0.0-alpha1.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhErgK8_HYzbZ5ps0B6mR0tjNRJQI6uo65muandUuuffeN9rAKZ3scXUoMZxb7KCCSjoVSvDJx-sydBklRPvaIDWDVSIv2h9XDlgmNrzA0cOga_89Bx7xLZdHDb9HzMfL254P2Z2qFMFOMG/s1000/arduino-esp32+2.0.0-alpha1.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="606" data-original-width="1000" height="388" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhErgK8_HYzbZ5ps0B6mR0tjNRJQI6uo65muandUuuffeN9rAKZ3scXUoMZxb7KCCSjoVSvDJx-sydBklRPvaIDWDVSIv2h9XDlgmNrzA0cOga_89Bx7xLZdHDb9HzMfL254P2Z2qFMFOMG/w640-h388/arduino-esp32+2.0.0-alpha1.jpg" width="640" /></a>
</div>
<br />
<p>
<b><u>To install development release to Arduino IDE board manager:</u></b>
</p>
<p>Click in Arduino IDE Menu > File > Preferences</p>
<p>
Enter development release link () in Additional Boards Manager URLs:<br /><a href="https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json" target="_blank">https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json</a>
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijTXDDKmZt-E5d8JbaRKCNnueaziXFm0cDMBG8NRU4c7qVIQ-I-0eYdhwQFaVmrT0CxoMjYQcug4voyScmlNdJmSHfgZ6YkE7RjA4ITOsALyQU9jsGAfKHB7mFlIiQBaYIQkzrrLXgELi9/s2000/arduino-esp32+2.0.0-alpha1_01.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijTXDDKmZt-E5d8JbaRKCNnueaziXFm0cDMBG8NRU4c7qVIQ-I-0eYdhwQFaVmrT0CxoMjYQcug4voyScmlNdJmSHfgZ6YkE7RjA4ITOsALyQU9jsGAfKHB7mFlIiQBaYIQkzrrLXgELi9/w640-h384/arduino-esp32+2.0.0-alpha1_01.jpg" width="640" /></a>
</div>
<p>Open board manager:</p>
<p>
Tools > Board > Boards Manager<br />Search and select esp32 by Esoressif
systems, install the latest version, currentlt 2.0.0-alpha1.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkH08kilbggISAITS3hSBkW_rACi1oOuHYQqCXfkf_MY70MlASvczXYfHvexMqBu_PEKrwRdszY32f1r1rVkalcCWr0PrqfoHGvdpKcIekzVTzsrrPbRQf9m3cH9XRPLQSB9iQULwRfGbv/s2000/arduino-esp32+2.0.0-alpha1_02.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjkH08kilbggISAITS3hSBkW_rACi1oOuHYQqCXfkf_MY70MlASvczXYfHvexMqBu_PEKrwRdszY32f1r1rVkalcCWr0PrqfoHGvdpKcIekzVTzsrrPbRQf9m3cH9XRPLQSB9iQULwRfGbv/w640-h384/arduino-esp32+2.0.0-alpha1_02.jpg" width="640" /></a>
</div>
<br />
<p>After then, ESP32C3/ESP32S2 Dev Modules are available in board list.</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgO54DcTCHKFm1mPLQynA7C8WFhHx0WewSoxVssEr1HFMB5BKPmB2HcXUJ9QO1r6cfHqI6srnRlW9PQUrzQAxRGoV3JYFAjRcMQTBF_tyYZK8rIfQpJlggf0DUacL1XtfBDlsiv9aT3s3d4/s2000/arduino-esp32+2.0.0-alpha1_03.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgO54DcTCHKFm1mPLQynA7C8WFhHx0WewSoxVssEr1HFMB5BKPmB2HcXUJ9QO1r6cfHqI6srnRlW9PQUrzQAxRGoV3JYFAjRcMQTBF_tyYZK8rIfQpJlggf0DUacL1XtfBDlsiv9aT3s3d4/w640-h384/arduino-esp32+2.0.0-alpha1_03.jpg" width="640" /></a>
</div>
<div><br /></div>
~
<a href="https://github.com/espressif/arduino-esp32/releases/tag/2.0.0-alpha1" target="_blank">release note of 2.0.0-alpha1</a><br /><br /><center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/KKVuDO2HBrU" title="YouTube video player" width="560"></iframe>
</center>
<br />
<hr /><b>
Exercise:</b><div>ESP32-S2:</div><div>~ <a href="https://arduino-er.blogspot.com/2021/04/esp32-s2arduino-esp32-s2-saola-1-web.html">web server control onboard RGB LED (NeoPixel)</a></div><div><br /><div>ESP32-C3:</div></div><div>~ <a href="https://arduino-er.blogspot.com/2021/04/esp32-c3arduino-esp32-c3-devkitm-1-read.html">read Network Time from pool.ntp.org</a></div><div><br /></div>rpiihttp://www.blogger.com/profile/11029985001257500904noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-44326395104630357252021-04-25T11:06:00.006-07:002021-04-25T11:14:43.521-07:00Arduino read Playstation 2 compatible Wireless Controller using Arduino-PS2X<p>
This exercise program Arduino Uno to read Playstation 2 compatible 2.4G
Wireless Controller using Arduino-PS2X.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgK95oPtzXOq9YYRS91e80E9Sin19xwR9DD2kAptBokMb-k4oo_mD1ZSZ_5IGrWqpUZAY-CKAbuTcjH3BDFvLHFgvqzYPeqF9p_YIaHtGLxQjkKu4b4oOTHpfHFPfqha_SaXThuGERoMDw/s1000/Arduino+PS2+Controller_01.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="754" data-original-width="1000" height="482" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgK95oPtzXOq9YYRS91e80E9Sin19xwR9DD2kAptBokMb-k4oo_mD1ZSZ_5IGrWqpUZAY-CKAbuTcjH3BDFvLHFgvqzYPeqF9p_YIaHtGLxQjkKu4b4oOTHpfHFPfqha_SaXThuGERoMDw/w640-h482/Arduino+PS2+Controller_01.jpg" width="640" /></a>
</div>
<div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi226rHKk5Sbq1pDo6ScSJpzhkPDDbe88jDuTc2oZewqiJ3MNGtlDBI-Zp-BBJKaq0tMIHj5TtY8fOpU3ggwUACP4gFQeyj9oD1-6MllFsUm8gpASyiWFvals3L18DUyZlEK1gXmrT5lmQ/s1000/Arduino+PS2+Controller_02.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="754" data-original-width="1000" height="482" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi226rHKk5Sbq1pDo6ScSJpzhkPDDbe88jDuTc2oZewqiJ3MNGtlDBI-Zp-BBJKaq0tMIHj5TtY8fOpU3ggwUACP4gFQeyj9oD1-6MllFsUm8gpASyiWFvals3L18DUyZlEK1gXmrT5lmQ/w640-h482/Arduino+PS2+Controller_02.jpg" width="640" /></a>
</div>
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjshOWc8XRLv-wkjPa2xF2RrvhmNwVuwi6QBr53UA1GzxwSO7GXGWtABnOqGCkJG60u6gD98uQorUFW1e2Y6RVMdgdzoJudqm_eriutWrjQR5ZqdjlTM2sNgii5ypdb7mpSCTShxvF_jhM/s1000/Arduino+PS2+Controller_03.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="754" data-original-width="1000" height="482" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjshOWc8XRLv-wkjPa2xF2RrvhmNwVuwi6QBr53UA1GzxwSO7GXGWtABnOqGCkJG60u6gD98uQorUFW1e2Y6RVMdgdzoJudqm_eriutWrjQR5ZqdjlTM2sNgii5ypdb7mpSCTShxvF_jhM/w640-h482/Arduino+PS2+Controller_03.jpg" width="640" /></a>
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUpSjtXcCfuEGiSwrBpKuQ4NV9DhN-FFm1DLXtfgRMJyMkC__0NHxEIZ_xvn5tuPPubtYvkgWlOobZEjAV9W3pyR4QyrV21prCyhYdDc0VL0FLFHk9DEaJXFBUcsguSYNU_sF1J_oJqEo/s1000/Arduino+PS2+Controller_04.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="754" data-original-width="1000" height="482" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUpSjtXcCfuEGiSwrBpKuQ4NV9DhN-FFm1DLXtfgRMJyMkC__0NHxEIZ_xvn5tuPPubtYvkgWlOobZEjAV9W3pyR4QyrV21prCyhYdDc0VL0FLFHk9DEaJXFBUcsguSYNU_sF1J_oJqEo/w640-h482/Arduino+PS2+Controller_04.jpg" width="640" /></a>
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBvmMe6TQjU8Bh9U0wXBldqUplmHsFesTR7zTqjEt7ObEq035wrKjdLA3pekrMs1DIJF0xjbdp6DOiy_jPSba0cRwTwM6OugXZ2RmOpoTmfnpSzf7cdL6SZ1f-SdBIB-BtMwcZ3daGNMo/s1000/Arduino+PS2+Controller_05.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="754" data-original-width="1000" height="482" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiBvmMe6TQjU8Bh9U0wXBldqUplmHsFesTR7zTqjEt7ObEq035wrKjdLA3pekrMs1DIJF0xjbdp6DOiy_jPSba0cRwTwM6OugXZ2RmOpoTmfnpSzf7cdL6SZ1f-SdBIB-BtMwcZ3daGNMo/w640-h482/Arduino+PS2+Controller_05.jpg" width="640" /></a>
</div>
<p>
<b><a href="https://github.com/madsci1016/Arduino-PS2X" target="_blank">madsci1016/Arduino-PS2X</a></b>
is a Arduino Library to read PS2 controller.
</p>
<p>
To install Arduino-PS2X to Arduino IDE, download and unzip the code's ZIP
file. and place 'PS2X_lib' folder into your Arduino's libraries.
</p>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMfEcOQoE3I080a0UjawLQHGEhOL6YFfofkSDELOYEnDbMYc-yEaosksQ-kCuGneImqyAnLF-JBEDq_w-kuUmrhU6Qbyrhp66DYdl-Wn-CV5jSvaLr6yMZ3QLBWyIIe8f21uL136qKvEU/s2000/install+ps2x.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1200" data-original-width="2000" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMfEcOQoE3I080a0UjawLQHGEhOL6YFfofkSDELOYEnDbMYc-yEaosksQ-kCuGneImqyAnLF-JBEDq_w-kuUmrhU6Qbyrhp66DYdl-Wn-CV5jSvaLr6yMZ3QLBWyIIe8f21uL136qKvEU/w640-h384/install+ps2x.jpg" width="640" /></a>
</div>
<p>Restart the Arduino IDE, and open up the example sketch. </p>
<p>Connect PS2 controller pins to Arduino following in the example:</p>
<pre style="border: 1px solid black;"><code><span style="color: black;">#define PS2_DAT 13 //14
#define PS2_CMD 11 //15
#define PS2_SEL 10 //16
#define PS2_CLK 12 //17
</span></code></pre>
<center><iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/xl-nFryegIE" title="YouTube video player" width="560"></iframe>
</center>
<br />
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-51784405697518831362021-03-03T10:35:00.003-08:002021-03-04T10:59:05.855-08:00Install Arduino IDE 2.0 beta on Linux Mint 20.1, include ESP32/ESP8266 support.<p>
Arduino IDE 2.0 (beta) is now available (refer to
<a href="https://blog.arduino.cc/2021/03/01/announcing-the-arduino-ide-2-0-beta/" target="_blank">announcement in Arduino blog</a>). It,s my first try to install Arduino IDE 2.0 beta (2.0.0-beta3) on Linux
Mint 20.1, tested with VirtualBox 6.1/Windows 10.
</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/Zi2tdKQ5YVE" width="560"></iframe>
</center>
<p>
<b><u>Download Arduino IDE 2.0 beta</u></b>
</p>
<p>
Visit
<a href="https://www.arduino.cc/en/software" target="_blank">https://www.arduino.cc/en/software</a>, scroll download to download Arduino IDE 2.0 beta for Linux 64 bits
(X86-64).
</p>
<p>
<b><u>Run arduino-ide</u></b>
</p>
<p>
Extract the downloaded file to a any folder you want. Run arduino-ide in
Terminal<br /><b>$ ./arduino-ide</b>
</p>
<p>
<b><u>Install board</u></b>
</p>
<p>
In a fresh new installed Arduino IDE 2.0, no board is installed, you will be
report with error:
</p>
<p><b>Compilation error: Error: 2 UNKNOWN: platform not installed</b></p>
<p>
Click Boards Manager on left, search to install Arduino AVR Boards by Arduino.
</p>
<p>
<b><u>Add permission to user, to access USB</u></b>
</p>
<p>
In a new Linux, you (as a regular user) have no permission to access USB port,
and report with error:
</p>
<p>
<b>avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied</b>
</p>
<p>
Open Terminal, enter the command to add permission:<br /><b>$ sudo usermod -a -G dialout <username><br />$ sudo chmod a+rw
<port>
</b>
</p>
<p>Done.</p>
<p><br /></p>
<hr />
<b> Install board support for ESP32/ESP8266</b>
<div><br /></div>
<center>
<iframe width="560" height="315" src="https://www.youtube.com/embed/FYiC5Q67dsg" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</center>
<div><br /></div>
<div>
<div>Menu > File> Preferences</div>
<div>Enter the url in the "Additional Board Manager URLs":</div>
<div>
<a href="https://dl.espressif.com/dl/package_esp32_index.json" target="_blank">https://dl.espressif.com/dl/package_esp32_index.json</a>
(for ESP32)
</div>
<div>
<a href="http://arduino.esp8266.com/stable/package_esp8266com_index.json" target="_blank">http://arduino.esp8266.com/stable/package_esp8266com_index.json</a>
(for ESP8266)
</div>
</div>
<div><br /></div>
<div>Then you can add board of ESP32/ESP8266 in Boards Manager.</div>
<div><br /></div>
<div><u>Setup Python</u></div>
<div><br /></div>
<div>
By default Linux Mint 20.1 pre-install Python3, but no Python2. Currently,
esptool for ESPs call python. You can create a symlinks /usr/bin/python to
python3 by installing python-is-python3.
</div>
<div><br /></div>
<div><b>$ sudo apt install python-is-python3</b></div>
<div><br /></div>
<div>
Optionally, you can prevent Python 2 from being installed as a dependency of
something in the future:
</div>
<div>
<div><br /></div>
<div>
<b>$ sudo apt-mark hold python2 python2-minimal python2.7 python2.7-minimal
libpython2-stdlib libpython2.7-minimal libpython2.7-stdlib</b>
</div>
</div>
<div><br /></div>
<div>And you have to install pyserial with pip:</div>
<div><br /></div>
<div><b>$ sudo apt install python3-pip</b></div>
<div><b>$ pip3 install pyserial</b></div>
<div><br /></div>
<div>
<b><u>Add permission to your user (if not do in above steps):</u></b>
</div>
<div><br /></div>
<div>
<div>Additionally, if you cannot download your code to board caused by:</div>
<div>
avrdude: ser_open(): can't open device "/dev/xxx": Permission denied
</div>
<div><br /></div>
<div><b>$ sudo usermod -a -G dialout <username></b></div>
<div><b>$ sudo chmod a+rw <port></b></div>
</div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
<div><br /></div>
Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-41406001456482110002021-01-25T08:49:00.000-08:002021-01-25T08:49:00.404-08:00ESP32 drive NeoPixel using Adafruit_NeoPixel library<p>ESP32 (ESP32-DevKitC V4) code in Arduino Framework to drive a 8X NeoPixel Ring using Adafruit_NeoPixel library simple example.</p><p>In Arduino IDE library manager, install Adafruit_NeoPixel library.</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKBoSC5Urw413zAH3DH_UsRXwwdYPMSMkaexRjC998BEX-VLOJBFiadCFrHknS4dpn5_9tsmWmHwUToFvezDtWteMSSLHUNyW45LK0-8Jo8IIKa0Q6e9jGncoIwi2obeai-di2azvKidk/s1800/library+Adafruit_NeoPixel.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKBoSC5Urw413zAH3DH_UsRXwwdYPMSMkaexRjC998BEX-VLOJBFiadCFrHknS4dpn5_9tsmWmHwUToFvezDtWteMSSLHUNyW45LK0-8Jo8IIKa0Q6e9jGncoIwi2obeai-di2azvKidk/w640-h384/library+Adafruit_NeoPixel.png" width="640" /></a></div><br /><p>Open Example > Adafruit_NeoPixel > simple</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcQfFp7GNYUu5D1nrXp-Q7OK_trO7bWe7EBTDUEaxNOyEpg6R8hzJb5YjdgIrzvzyJhh6sFbt8vBt576PArFxil6G495-7xnDfjvV5qkj3bUx3Mv_r1JCVTG5xEAyTaJaSVJVnwu2cwgg/s1800/library+Adafruit_NeoPixel+simple+example.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcQfFp7GNYUu5D1nrXp-Q7OK_trO7bWe7EBTDUEaxNOyEpg6R8hzJb5YjdgIrzvzyJhh6sFbt8vBt576PArFxil6G495-7xnDfjvV5qkj3bUx3Mv_r1JCVTG5xEAyTaJaSVJVnwu2cwgg/w640-h384/library+Adafruit_NeoPixel+simple+example.png" width="640" /></a></div><br /><p>Edit PIN on the Arduino is connected to the NeoPixels, and number of NeoPixels are attached.</p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhImBYR9GKs-MPH5V6dAQ_QLM6B8F2QwmVDo30ROEKdfbuDHu_wSpolEgXC1sde6r0WQ4MHx1IuKv81H9L2s_vtcCRw8Kzkz_OiCKRDaVhAsIZUUs_npX8kd0NytTXnUv2KOv5_v1NekyQ/s1800/library+Adafruit_NeoPixel+simple+example+edited.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhImBYR9GKs-MPH5V6dAQ_QLM6B8F2QwmVDo30ROEKdfbuDHu_wSpolEgXC1sde6r0WQ4MHx1IuKv81H9L2s_vtcCRw8Kzkz_OiCKRDaVhAsIZUUs_npX8kd0NytTXnUv2KOv5_v1NekyQ/w640-h384/library+Adafruit_NeoPixel+simple+example+edited.png" width="640" /></a></div><br /> Connect NexPixel to ESP32 accordingly, verify and upload your code to run:<p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjA3l0LXeMZcd8a8kCL9CU0JNuVb_vMbKdsBrVAY_XIDG9mE5OfXE7UC3f_Q1o35wQ2x_-bHpaTZcg2dsGeTDB4X7gbj9zb5l6eP_cb5yJTQYzC77CR8xh0Lo5F5ISiRn-U_vSZqfGCQNs/s1000/ESP32+NeoPixel.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="765" data-original-width="1000" height="490" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjA3l0LXeMZcd8a8kCL9CU0JNuVb_vMbKdsBrVAY_XIDG9mE5OfXE7UC3f_Q1o35wQ2x_-bHpaTZcg2dsGeTDB4X7gbj9zb5l6eP_cb5yJTQYzC77CR8xh0Lo5F5ISiRn-U_vSZqfGCQNs/w640-h490/ESP32+NeoPixel.jpg" width="640" /></a></div><p><br /></p>
<hr />
Note that if you assign PIN to a wrong pin, such as input only. Error message will be output to Serial:<div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpvAJLLRSvAt6siZjGsT3VBMmKlNjKroXNTPBiZPBzOWQf7ahx3JGSwmmhw6nK3bwKgDmBuhtvdcDsP6R6qn64YtKKdUoVv-UqoaSi5NDwS932ZRpIND_oGsADREtSOBr4fYMRD-Cr8tA/s1800/RMT+GPIO+ERROR.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpvAJLLRSvAt6siZjGsT3VBMmKlNjKroXNTPBiZPBzOWQf7ahx3JGSwmmhw6nK3bwKgDmBuhtvdcDsP6R6qn64YtKKdUoVv-UqoaSi5NDwS932ZRpIND_oGsADREtSOBr4fYMRD-Cr8tA/w640-h384/RMT+GPIO+ERROR.png" width="640" /></a></div><br /><div><br /></div>
<hr />
~ <a href="https://arduino-er.blogspot.com/2020/12/esp32-devkitc-v4-esp32-wrover-e-with.html">more examples of ESP32-DevKitC V4</a><div><br /></div>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-33006585184594335972021-01-24T11:38:00.003-08:002021-01-24T11:58:45.293-08:00BLE Notification example: ESP32 BLE server read analog input and notify connected device<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTkl-4BOSFf6LaG8UI_xVQ1wk5xsXtQ6oO9UOjGv-odONbgOjQ0STKry0aWa3P2YvxZeZaYBQU2VtdFZWAVxKuNJJ6U9zyeQDuf2MumnpIpRm6Q8QvNIIRfdDuVFAvv9_apLqzJykHmYry/s1024/BLE_AIN_02.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="772" data-original-width="1024" height="482" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTkl-4BOSFf6LaG8UI_xVQ1wk5xsXtQ6oO9UOjGv-odONbgOjQ0STKry0aWa3P2YvxZeZaYBQU2VtdFZWAVxKuNJJ6U9zyeQDuf2MumnpIpRm6Q8QvNIIRfdDuVFAvv9_apLqzJykHmYry/w640-h482/BLE_AIN_02.jpg" width="640" /></a></div><p>Code run on ESP32-DevKitC V4 (Arduino framework), to act as BLE server. Once connected, it read Analog Input and notify connected device.</p><p>It's modified from last post of <a href="https://arduino-er.blogspot.com/2021/01/esp32-blenotify-example-handle.html">ESP32 BLE_notify example</a>.</p><p>The client side is programmed using <a href="https://helloraspberrypi.blogspot.com/2021/01/ble-notification-example_24.html" target="_blank"><b>Python run on Raspberry Pi, handle the notification and plot the value graphically</b></a>.</p>
<center>
<iframe width="560" height="315" src="https://www.youtube.com/embed/zTilzSklEO4" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</center>
<div><br /></div>
BLE_notify_AIN.ino
<pre style="border: 1px solid black;"><code><span style="color: black;">#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
#define PinAnalogIn 36
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value = 0;
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
bool rqsNotify;
unsigned long prvMillis;
#define INTERVAL_READ 1000
int valNotify;
#define MAX_VALNOTIFY 255
int ain = 0;
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
rqsNotify = false;
prvMillis = millis();
Serial.println("Device connected");
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
rqsNotify = false;
Serial.println("Device disconnected");
}
};
void prcRead(){
if(deviceConnected){
unsigned long curMillis = millis();
if((curMillis-prvMillis) >= INTERVAL_READ){
int valAIO = analogRead(PinAnalogIn);
valNotify = map(valAIO, 0, 4096, 0, 255);
Serial.println(valNotify);
rqsNotify = true;
prvMillis = curMillis;
}
}
}
void setup() {
Serial.begin(115200);
// Create the BLE Device
BLEDevice::init("ESP32");
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
// Create a BLE Descriptor
pCharacteristic->addDescriptor(new BLE2902());
// Start the service
pService->start();
// Start advertising
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter
BLEDevice::startAdvertising();
Serial.println("Waiting a client connection to notify...");
}
void loop() {
// notify changed value
if (deviceConnected) {
if(rqsNotify){
rqsNotify = false;
//pCharacteristic->setValue((uint8_t*)valNotify, 1);
//pCharacteristic->notify();
value = valNotify;
pCharacteristic->setValue((uint8_t*)&value, 4);
pCharacteristic->notify();
//value++;
}
}
// disconnecting
if (!deviceConnected && oldDeviceConnected) {
delay(500); // give the bluetooth stack the chance to get things ready
pServer->startAdvertising(); // restart advertising
Serial.println("start advertising");
oldDeviceConnected = deviceConnected;
}
// connecting
if (deviceConnected && !oldDeviceConnected) {
// do stuff here on connecting
oldDeviceConnected = deviceConnected;
}
prcRead();
}
</span></code></pre>
<p><br /></p>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0tag:blogger.com,1999:blog-5298160027330696474.post-8024507852768051162021-01-20T05:59:00.003-08:002021-01-24T11:39:31.425-08:00ESP32 BLE_notify example, handle Notification with Python/Raspberry Pi.<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3p4ZqHm9_DRjFaFw_HYyPN-FX4mdNhZCbGaokpcGp75RdvrPwK3x5wL9a0G0DeQhMDo2lMCHaRYNBLR7n52NeN1715XRM2og8Jx3j7uIOzw9a0h2FX7L-_nAtTmjrPOLwdPxPGQQ-Ex8/s1800/BLE_notify.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1080" data-original-width="1800" height="384" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3p4ZqHm9_DRjFaFw_HYyPN-FX4mdNhZCbGaokpcGp75RdvrPwK3x5wL9a0G0DeQhMDo2lMCHaRYNBLR7n52NeN1715XRM2og8Jx3j7uIOzw9a0h2FX7L-_nAtTmjrPOLwdPxPGQQ-Ex8/w640-h384/BLE_notify.png" width="640" /></a></div><p>ESP32 BLE_notify example create a BLE server that, once we receive a connection, will send periodic notifications.</p>
<center>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/rpHeisnmQUo" width="560"></iframe>
</center>
<p>In ESP32 side, load <br />Examples > ESP32 BLE Arduino > BLE_notify</p><p>Tested on ESP32-DevKitC V4 in my case.</p><p>I implemented <a href="https://helloraspberrypi.blogspot.com/2021/01/pythonraspberry-pi-handle-notification.html" target="_blank"><b>a simple Python code run on Raspberry Pi</b></a>, connect to ESP32 and handle notification.</p>
BLE_notify.ino
<pre style="border: 1px solid black;"><code><span style="color: black;">/*
Video: https://www.youtube.com/watch?v=oCMOYS71NIU
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
Ported to Arduino ESP32 by Evandro Copercini
updated by chegewara
Create a BLE server that, once we receive a connection, will send periodic notifications.
The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b
And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8
The design of creating the BLE server is:
1. Create a BLE Server
2. Create a BLE Service
3. Create a BLE Characteristic on the Service
4. Create a BLE Descriptor on the characteristic
5. Start the service.
6. Start advertising.
A connect hander associated with the server starts a background task that performs notification
every couple of seconds.
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value = 0;
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
void setup() {
Serial.begin(115200);
// Create the BLE Device
BLEDevice::init("ESP32");
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
// Create a BLE Descriptor
pCharacteristic->addDescriptor(new BLE2902());
// Start the service
pService->start();
// Start advertising
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter
BLEDevice::startAdvertising();
Serial.println("Waiting a client connection to notify...");
}
void loop() {
// notify changed value
if (deviceConnected) {
pCharacteristic->setValue((uint8_t*)&value, 4);
pCharacteristic->notify();
value++;
delay(3); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms
}
// disconnecting
if (!deviceConnected && oldDeviceConnected) {
delay(500); // give the bluetooth stack the chance to get things ready
pServer->startAdvertising(); // restart advertising
Serial.println("start advertising");
oldDeviceConnected = deviceConnected;
}
// connecting
if (deviceConnected && !oldDeviceConnected) {
// do stuff here on connecting
oldDeviceConnected = deviceConnected;
}
}
</span></code></pre>
<br />
Next:<div>~ <a href="https://arduino-er.blogspot.com/2021/01/ble-notification-example-esp32-ble_24.html">BLE Notification example: ESP32 BLE server read analog input and notify connected device</a></div><div><br /></div>Erikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.com0