C/C++

How to initialize struct sockaddr_in using initializer lists

This way of initializing a struct sockaddr_in uses modern C and avoids all the raw of days that should long be forgotten, at least for most applications. I use this approach successfully e.g. for ESP32 microcontrollers.

struct sockaddr_in server_addr = {
    .sin_family = AF_INET,
    .sin_port = htons(46118),
    .sin_addr = {.s_addr = htonl(INADDR_ANY)}
};

 

Posted by Uli Köhler in C/C++, ESP8266/ESP32, PlatformIO

ESP32 Filesystem initialization code example (LittleFS)

This example code takes care of mounting the filesystem, or creating a filesystem if none is present.

#pragma once
#include <stddef.h>

// InitFilesystem() sets this to true if the filesystem is available.
extern volatile bool filesystemOK;

void InitFilesystem();
#include "FS.h"
#include "LittleFS.h"

volatile bool filesystemOK = false;

void InitFilesystem() {
  // Initialize LittleFS
  if (!LittleFS.begin(false /* false: Do not format if mount failed */)) {
    Serial.println("Failed to mount LittleFS");
    if (!LittleFS.begin(true /* true: format */)) {
      Serial.println("Failed to format LittleFS");
    } else {
      Serial.println("LittleFS formatted successfully");
      filesystemOK = true;
    }
  } else { // Initial mount success
    filesystemOK = true;
  }
}

 

Posted by Uli Köhler in C/C++, ESP8266/ESP32

How to reverse std::string using std::reverse (C++)

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char** argv) {
    std::string s = "My string";
    // This reverses s in-place.
    std::reverse(std::begin(s), std::end(s));
    // Prints "gnirts yM"
    cout << s << endl;
}

 

Posted by Uli Köhler in C/C++

re2 C++ replace (GlobalReplace) minimal example

This minimal example shows how to replace strings using the re2 GlobalReplace() function:

#include <re2/re2.h>
#include <iostream>
#include <string>

using namespace re2;
using namespace std;

// Pre-compiled regex
RE2 myRegex("\\$[^\\$]+\\$");

int main(int argc, char** argv) {
    string myString = "This string $abc123$ contains two formulas $123 != 456$.";
    // NOTE: This will modify myString!
    RE2::GlobalReplace(&myString, myRegex, "FORMULA");
    // Prints "This string FORMULA contains two formulas FORMULA."
    cout << myString << endl;
}

 

Posted by Uli Köhler in C/C++

re2 C++ regular expressions library: How to #include?

#include <re2/re2.h>

using namespace re2;

 

Posted by Uli Köhler in C/C++

cpp-httplib: How to get query parameters

This example shows how to get a query parameter in cpp-httplib. See the cpp-httplib hello example for the full source code:

svr.Get("/hi", [](const httplib::Request& req, httplib::Response& res) {
    std::string id = req.get_param_value("id");
    res.set_content("id=" + id, "text/plain");
});

Access it at http://localhost:8080/hi?id=myid

and it will show you

id=myid

id will be empty (== "") if no such parameter is given.

Posted by Uli Köhler in C/C++

How to fix Paho MQTT undefined reference to `SHA1_Init’

Problem:

When trying to build your C++ application using Paho MQTT, you see a bunch of undefined reference error messages:

MQTTAsync.c:(.text+0x3482): undefined reference to `OpenSSL_version'
/usr/bin/ld: MQTTAsync.c:(.text+0x34a1): undefined reference to `OpenSSL_version'
/usr/bin/ld: MQTTAsync.c:(.text+0x34c0): undefined reference to `OpenSSL_version'
/usr/bin/ld: MQTTAsync.c:(.text+0x34df): undefined reference to `OpenSSL_version'
/usr/bin/ld: MQTTAsync.c:(.text+0x34fe): undefined reference to `OpenSSL_version'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(MQTTAsyncUtils.c.o): in function `MQTTAsync_closeOnly':
MQTTAsyncUtils.c:(.text+0x9b6): undefined reference to `SSL_SESSION_free'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(MQTTAsyncUtils.c.o): in function `MQTTAsync_receiveThread':
MQTTAsyncUtils.c:(.text+0x463b): undefined reference to `SSL_set_session'
/usr/bin/ld: MQTTAsyncUtils.c:(.text+0x5255): undefined reference to `SSL_get1_session'
/usr/bin/ld: MQTTAsyncUtils.c:(.text+0x55bb): undefined reference to `SSL_get1_session'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `call_ssl_psk_cb':
SSLSocket.c:(.text+0x11b): undefined reference to `SSL_get_SSL_CTX'
/usr/bin/ld: SSLSocket.c:(.text+0x129): undefined reference to `SSL_CTX_get_ex_data'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_error':
SSLSocket.c:(.text+0x1fa): undefined reference to `SSL_get_error'
/usr/bin/ld: SSLSocket.c:(.text+0x22d): undefined reference to `ERR_print_errors_cb'
/usr/bin/ld: SSLSocket.c:(.text+0x2f1): undefined reference to `ERR_get_error'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSL_CTX_info_callback':
SSLSocket.c:(.text+0x376): undefined reference to `SSL_alert_desc_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x381): undefined reference to `SSL_alert_type_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x3bc): undefined reference to `SSL_get_verify_result'
/usr/bin/ld: SSLSocket.c:(.text+0x411): undefined reference to `SSL_state_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x461): undefined reference to `SSL_get_current_cipher'
/usr/bin/ld: SSLSocket.c:(.text+0x469): undefined reference to `SSL_CIPHER_get_name'
/usr/bin/ld: SSLSocket.c:(.text+0x474): undefined reference to `SSL_state_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x4d1): undefined reference to `SSL_alert_desc_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x4dc): undefined reference to `SSL_alert_type_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x4e7): undefined reference to `SSL_state_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x503): undefined reference to `SSL_alert_desc_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x50e): undefined reference to `SSL_alert_type_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x541): undefined reference to `SSL_alert_desc_string_long'
/usr/bin/ld: SSLSocket.c:(.text+0x54c): undefined reference to `SSL_alert_type_string_long'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_initialize':
SSLSocket.c:(.text+0x8ee): undefined reference to `OPENSSL_init_ssl'
/usr/bin/ld: SSLSocket.c:(.text+0x90a): undefined reference to `OPENSSL_init_crypto'
/usr/bin/ld: SSLSocket.c:(.text+0x916): undefined reference to `OPENSSL_init_ssl'
/usr/bin/ld: SSLSocket.c:(.text+0x922): undefined reference to `OPENSSL_init_crypto'
/usr/bin/ld: SSLSocket.c:(.text+0xa11): undefined reference to `CRYPTO_get_ex_new_index'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_createContext':
SSLSocket.c:(.text+0xbee): undefined reference to `SSL_CTX_use_certificate_chain_file'
/usr/bin/ld: SSLSocket.c:(.text+0xc48): undefined reference to `SSL_CTX_set_default_passwd_cb'
/usr/bin/ld: SSLSocket.c:(.text+0xc55): undefined reference to `SSL_CTX_set_default_passwd_cb_userdata'
/usr/bin/ld: SSLSocket.c:(.text+0xc67): undefined reference to `SSL_CTX_use_PrivateKey_file'
/usr/bin/ld: SSLSocket.c:(.text+0xc9a): undefined reference to `SSL_CTX_load_verify_locations'
/usr/bin/ld: SSLSocket.c:(.text+0xce5): undefined reference to `SSL_CTX_set_default_verify_paths'
/usr/bin/ld: SSLSocket.c:(.text+0xd2e): undefined reference to `SSL_CTX_set_cipher_list'
/usr/bin/ld: SSLSocket.c:(.text+0xd56): undefined reference to `SSL_CTX_set_ex_data'
/usr/bin/ld: SSLSocket.c:(.text+0xd66): undefined reference to `SSL_CTX_set_psk_client_callback'
/usr/bin/ld: SSLSocket.c:(.text+0xd8f): undefined reference to `SSL_CTX_ctrl'
/usr/bin/ld: SSLSocket.c:(.text+0xdc5): undefined reference to `SSL_CTX_free'
/usr/bin/ld: SSLSocket.c:(.text+0xe51): undefined reference to `SSL_CTX_set_alpn_protos'
/usr/bin/ld: SSLSocket.c:(.text+0xeb9): undefined reference to `TLS_client_method'
/usr/bin/ld: SSLSocket.c:(.text+0xec1): undefined reference to `SSL_CTX_new'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_setSocketForSSL':
SSLSocket.c:(.text+0x1046): undefined reference to `SSL_CTX_set_info_callback'
/usr/bin/ld: SSLSocket.c:(.text+0x1056): undefined reference to `SSL_CTX_set_msg_callback'
/usr/bin/ld: SSLSocket.c:(.text+0x1075): undefined reference to `SSL_new'
/usr/bin/ld: SSLSocket.c:(.text+0x10ab): undefined reference to `SSL_get_cipher_list'
/usr/bin/ld: SSLSocket.c:(.text+0x10be): undefined reference to `SSL_set_fd'
/usr/bin/ld: SSLSocket.c:(.text+0x113b): undefined reference to `SSL_ctrl'
/usr/bin/ld: SSLSocket.c:(.text+0x121c): undefined reference to `SSL_CTX_set_verify'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_connect':
SSLSocket.c:(.text+0x12b7): undefined reference to `ERR_clear_error'
/usr/bin/ld: SSLSocket.c:(.text+0x12bf): undefined reference to `SSL_connect'
/usr/bin/ld: SSLSocket.c:(.text+0x135d): undefined reference to `SSL_get_peer_certificate'
/usr/bin/ld: SSLSocket.c:(.text+0x138c): undefined reference to `X509_check_host'
/usr/bin/ld: SSLSocket.c:(.text+0x13d4): undefined reference to `CRYPTO_free'
/usr/bin/ld: SSLSocket.c:(.text+0x13f6): undefined reference to `X509_free'
/usr/bin/ld: SSLSocket.c:(.text+0x144d): undefined reference to `X509_check_ip_asc'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_getch':
SSLSocket.c:(.text+0x1569): undefined reference to `ERR_clear_error'
/usr/bin/ld: SSLSocket.c:(.text+0x1579): undefined reference to `SSL_read'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_destroyContext':
SSLSocket.c:(.text+0x1630): undefined reference to `SSL_CTX_free'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_close':
SSLSocket.c:(.text+0x16b8): undefined reference to `ERR_clear_error'
/usr/bin/ld: SSLSocket.c:(.text+0x16c1): undefined reference to `SSL_shutdown'
/usr/bin/ld: SSLSocket.c:(.text+0x16ce): undefined reference to `SSL_free'
/usr/bin/ld: SSLSocket.c:(.text+0x16fd): undefined reference to `SSL_CTX_free'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_putdatas':
SSLSocket.c:(.text+0x191f): undefined reference to `ERR_clear_error'
/usr/bin/ld: SSLSocket.c:(.text+0x1930): undefined reference to `SSL_write'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_getdata':
SSLSocket.c:(.text+0x1ca5): undefined reference to `ERR_clear_error'
/usr/bin/ld: SSLSocket.c:(.text+0x1cb8): undefined reference to `SSL_read'
/usr/bin/ld: SSLSocket.c:(.text+0x1d7f): undefined reference to `SSL_pending'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(SSLSocket.c.o): in function `SSLSocket_continueWrite':
SSLSocket.c:(.text+0x1e2f): undefined reference to `ERR_clear_error'
/usr/bin/ld: SSLSocket.c:(.text+0x1e3f): undefined reference to `SSL_write'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(Base64.c.o): in function `Base64_encodeDecode.part.0':
Base64.c:(.text+0x1f): undefined reference to `BIO_f_base64'
/usr/bin/ld: Base64.c:(.text+0x27): undefined reference to `BIO_new'
/usr/bin/ld: Base64.c:(.text+0x2f): undefined reference to `BIO_s_mem'
/usr/bin/ld: Base64.c:(.text+0x37): undefined reference to `BIO_new'
/usr/bin/ld: Base64.c:(.text+0x45): undefined reference to `BIO_push'
/usr/bin/ld: Base64.c:(.text+0x55): undefined reference to `BIO_set_flags'
/usr/bin/ld: Base64.c:(.text+0x78): undefined reference to `BIO_write'
/usr/bin/ld: Base64.c:(.text+0x8e): undefined reference to `BIO_ctrl'
/usr/bin/ld: Base64.c:(.text+0x9e): undefined reference to `BIO_free_all'
/usr/bin/ld: Base64.c:(.text+0xc1): undefined reference to `BIO_read'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(WebSocket.c.o): in function `WebSocket_buildFrame.constprop.0':
WebSocket.c:(.text+0x441): undefined reference to `RAND_bytes'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(WebSocket.c.o): in function `uuid_generate':
WebSocket.c:(.text+0x721): undefined reference to `RAND_bytes'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(WebSocket.c.o): in function `WebSocket_connect':
WebSocket.c:(.text+0x929): undefined reference to `RAND_bytes'
/usr/bin/ld: /home/uli/.conan/data/paho-mqtt-c/1.3.9/_/_/package/6fbd1993993594bd3f9451023a96c5ec2eef0e19/lib/libpaho-mqtt3as.a(WebSocket.c.o): in function `WebSocket_upgrade':
WebSocket.c:(.text+0x1dd9): undefined reference to `SHA1_Init'
/usr/bin/ld: WebSocket.c:(.text+0x1def): undefined reference to `SHA1_Update'
/usr/bin/ld: WebSocket.c:(.text+0x1dff): undefined reference to `SHA1_Final'
collect2: error: ld returned 1 exit status

Solution

In addition to linking the Paho MQTT libraries, you also need to link OpenSSL, i.e. the ssl and crypto libraries. You can link them, for example using

target_link_libraries(myexecutable ssl crypto)

in CMake or by adding these linker flags for GCC:

-lssl -lcrypto

 

Posted by Uli Köhler in C/C++

How to link Paho MQTT C++ binding using CMake

target_link_libraries(myexecutable paho-mqttpp3 paho-mqtt3as ssl crypto)

 

Posted by Uli Köhler in C/C++, MQTT

How to initialize new C++ executable project using conan 1.x

Important note: This post is for Conan 1.x and is not compatible with the current version conan 2.x! See How to initialize C++ project using conan 2.x for an updated version of this post!

In the directory where you want to create the project, run (obviously, replace mypackageby the name of everywhere in our code!)

conan new mypackage/1.0.0 -s

-s is important here. It tells conan that the source is available in the project directory and it should not be pulled using git etc.

This will initialize a shared library project, which we will now modify to build an executable.

First, open src/CMakeLists.txt and change add_library() to add_executable(), for example

add_library(mypackage mypackage.cpp)

to

add_executable(mypackage mypackage.cpp)

Now we shall modify conanfile.py to properly build & install the executable:

    def package(self):
        self.copy("*.h", dst="include", src="src")
        self.copy("*.lib", dst="lib", keep_path=False)
        self.copy("*.dll", dst="bin", keep_path=False)
        self.copy("*.dylib*", dst="lib", keep_path=False)
        self.copy("*.so", dst="lib", keep_path=False)
        self.copy("*.a", dst="lib", keep_path=False)
    def package_info(self):
        self.cpp_info.libs = ["NoxecoDB"]

with

    def package(self):
        self.copy("mypackage", src="bin", dst="bin", keep_path=False)

    def package_info(self):
        self.env_info.PATH = os.path.join(self.package_folder, "bin")

    def deploy(self):
        self.copy("mypackage", dst="bin", src="bin")

and add

import os.path

to the top of the file

Now let’s add a main() function to  src/mypackage.cpp. Replace the file’s content with

#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Hello World!" <<std::endl;
}

Now it’s time to install the dependencies & build the project using

conan install . && conan build .

The executable will be in

bin/mypackage

You can run it using

./bin/mypackage

which will print

Hello World!

I also recommend to add this .gitignore:

CMakeCache.txt
CMakeFiles/
Makefile
bin/
cmake_install.cmake
conan.lock
conanbuildinfo.cmake
conanbuildinfo.txt
conaninfo.txt
graph_info.json

 

Posted by Uli Köhler in C/C++, Conan

How to split strings in C++ using boost::algorithm::split() – a minimal example

#include <boost/algorithm/string/split.hpp> // boost::algorithm::split
#include <boost/algorithm/string/classification.hpp> // boost::is_any_of
#include <string>
#include <iostream>
#include <vector>

int main() {
    std::string mystr = "foo-bar-x";
    // Split by "-"
    std::vector<std::string> splitResult;
    boost::algorithm::split(splitResult, mystr, boost::is_any_of("-"));
    // Print results, one line at a time
    // Prints:
    // foo
    // bar
    // x
    for(const std::string& s : splitResult) {
        std::cout << s << std::endl;
    }
}

 

Posted by Uli Köhler in Boost, C/C++

How to link the boost string algorithms library – which linker flags to use?

You do not need to link the boost::algorithm library. It is a header only library, hence you only need to #include its header files.

For examples, see

Posted by Uli Köhler in Boost, C/C++

How to use boost string algorithm starts_with: A minimal example

#include <boost/algorithm/string/predicate.hpp>
#include <string>
#include <iostream>

int main() {
    std::string mystr = "foobar";
    // Prints "true, false"
    std::cout << std::boolalpha
        << boost::algorithm::starts_with(mystr, "foo") << ", "
        << boost::algorithm::starts_with(mystr, "bar") << std::endl;
}

Also see: How to use boost string algorithm ends_with: A minimal example

Posted by Uli Köhler in Boost, C/C++

How to use boost string algorithm ends_with: A minimal example

#include <boost/algorithm/string/predicate.hpp>
#include <string>
#include <iostream>

int main() {
    std::string mystr = "foobar";
    // Prints "false, true"
    std::cout << std::boolalpha
        << boost::algorithm::ends_with(mystr, "foo") << ", "
        << boost::algorithm::ends_with(mystr, "bar") << std::endl;
}

Also see: How to use boost string algorithm starts_with: A minimal example

Posted by Uli Köhler in Boost, C/C++

How to fix ModuleNotFoundError: No module named ‘conans’

Problem:

When running conanfile.py or other Python scripts, you see an error message like

Traceback (most recent call last):
  File "/home/myuser/myproject/conanfile.py", line 1, in <module>
    from conans import ConanFile, CMake
ModuleNotFoundError: No module named 'conans'

Solution:

Install conan using one of the recommended methods such as the recommended install via pip

sudo pip3 install conan
Posted by Uli Köhler in C/C++, Python

How to fix ArduinoJSON: error: ‘DynamicJSONDocument’ was not declared in this scope

Problem:

While trying to compile your project, you see an error message like

error: 'DynamicJSONDocument' was not declared in this scope

Solution:

The Json in DynamicJsonDocument must be spelled camel case: Json, not JSON! The correct spelling is DynamicJsonDocument.

If that does not help, ensure

#include <ArduinoJson.h>

is at the top of the file where the error occurs.

Posted by Uli Köhler in C/C++

FreeRTOS task queue minimal example

This is how you create and use a task queue in FreeRTOS:

Global declaration

Declare the structure of a task (I recommend to use a task type enum class in order to keep the flexibility of using multiple task types:

#include <freertos/queue.h>

enum class I2CTaskType : uint8_t {
    MyTaskType = 0
};

struct I2CTask {
    I2CTaskType type;
    // Parameters
    int16_t value;
};
static QueueHandle_t i2cTaskQueue;

Initialization code

Call this once, before using it:

// Create task queue
i2cTaskQueue = xQueueCreate(8 /* Number of queue slots */, sizeof(I2CTask));

In the thread processing the queue

if (xQueueReceive(i2cTaskQueue, (void *)&task, portMAX_DELAY /* Wait infinitely for new tasks */) == pdTRUE) {
    if(task.type == I2CTaskType::MyTaskType) {
        // TODO process task
        Serial.printf("My task type: %d\r\n", task.value);
    }
}

How to add a task to the queue

void AddTask(int16_t val) {
    I2CTask task;
    task.type = I2CTaskType::MyTaskType;
    task.value = val;
    xQueueSend(i2cTaskQueue, (void*)&task, 10 / portTICK_PERIOD_MS /* timeout */);
}

 

Posted by Uli Köhler in C/C++, Embedded, FreeRTOS, PlatformIO

How to fix Arduino error: ‘size_t’ has not been declared

Problem:

In Arduino, you see an error message like

src/main.cpp:7:48: error: 'size_t' has not been declared
void MyFunction(size_t size);

Solution:

Include stddef.h where size_t is declared:

#include <stddef.h>

Add this line to the top of the file where the error occured.

Posted by Uli Köhler in Arduino, C/C++, Embedded, PlatformIO

How to fix Arduino I2C Wire error: call of overloaded ‘begin(const int&, const int&, int)’ is ambiguous

Problem:

You are trying to call Wire.begin() for I2C using

Wire.begin(Pin_I2C_SDA, Pin_I2C_SCL, 400000);

but you see an error message like

src/MyI2C.cpp: In function 'void MyInitI2C()':
src/NyI2C.cpp:139:47: error: call of overloaded 'begin(const int&, const int&, int)' is ambiguous
     Wire.begin(Pin_I2C_SDA,Pin_I2C_SCL, 400000);
                                               ^
In file included from include/MyIO.hpp:2:0,
                 from src/MyI2C.cpp:2:
/home/uli/.platformio/packages/framework-arduinoespressif32/libraries/Wire/src/Wire.h:79:10: note: candidate: bool TwoWire::begin(int, int, uint32_t)
     bool begin(int sda=-1, int scl=-1, uint32_t frequency=0); // returns true, if successful init of i2c bus
          ^
/home/uli/.platformio/packages/framework-arduinoespressif32/libraries/Wire/src/Wire.h:80:10: note: candidate: bool TwoWire::begin(uint8_t, int, int, uint32_t)
     bool begin(uint8_t slaveAddr, int sda=-1, int scl=-1, uint32_t frequency=0);

Solution:

This happens with specific versions of the Arduino framework. For me it happened specifically when upgrading to arduino-esp32 version 2.0.1.

You need to explicitly cast the third argument (400000) to uint32_t in order to tell the compiler which of the two functions you want to call:

Wire.begin(Pin_I2C_SDA, Pin_I2C_SCL, 400000);
Posted by Uli Köhler in Arduino, C/C++, Embedded, PlatformIO

Example of how to do std::enable_if<...> with multiple conditions

Simply use && like this:

std::enable_if<CONDITION1::value && CONDITION2::value, T>

Full example:

template<class T, class I>
constexpr typename std::enable_if<std::is_enum<T>::value && std::is_integral<I>::value, I>::type operator|(T lhs, I rhs) 
{
    return static_cast<typename std::underlying_type<T>::type>(lhs) | rhs;
}
Posted by Uli Köhler in C/C++