Tuesday, August 14, 2018

Pointers of String

It is always tricky dealing with string in C/C++, but if we know the rule of evaluation of expression in C++, it's not that hard to understand it.

A string declaration is always evaluated from right to left.  For example, "char *str" is evaluated as "a variable with name 'str' is a pointer (*) of type char".

Another example:

"const char *str" is evaluated as variable str as a pointer of type char that is const (the content is immutable").  (Please remember, "const char .." expression is identical to expression "char const ...")

"char * const str" is evaluated as a variable with name 'str' is a constant pointer to type char, meaning once the pointer is initialized to point to a string, it cannot be changed to point to another string.

"char const * const str" is evaluated as "a variable with name 'str' is a constant pointer to constant char content.  It is a combination to all above.

#include <iostream>


char* str: 
const char* str OR char const *str
char* const str: 
const char* const str: 


#define L(v)       #v << " = " << v

using namespace std;

static char cstr[] = "String ini statis!";

int main()
    char*   ps1;  // just a regular pointer to a string
    ps1 = cstr;
    cout << L(ps1) << endl;

#if 0
    char const * p_constr = cstr;
    // the following causes compile error, as it tries to change value of the static string
    *p_constr = '1';
    cout << L(p_constr) << endl;

    // a dialect of the above (char const *)
    const char* p_constr2 = cstr;
    *p_constr2 = '1';
    cout << L(p_constr2) << endl;

#if 0
    const char* const const_ptr = cstr;  // the pointer cannot be set to different one

    // the following will cause compile error
    const_ptr = cstr2;
    cout << L(const_ptr) << std::endl;

Saturday, June 30, 2018

WeMos D1 WiFi uno based ESP8266 for arduino Compatible

www.aliexpress.com: $7.60, 5 Jan 2016

Docs: http://www.wemos.cc/d1/

  • based on the ESP-8266EX.
  •     Arduino Compatible, you can use it on Arduino IDE.
  •     11 Digital I/O pins
  •     1 Analog Input pin
  •     OTA   -- Wireless Upload(Program)
  •     Onboard switching power supply -- Max 24V input, 5V 1A output 
  •     All GPIOs are 3.3 volts only

cd ~/build
git clone https://github.com/esp8266/Arduino.git esp8266
#cd ~/sketchbook
cd /opt/Arduino/hardware
ln -s ~/build/esp8266 ./esp8266
cd ./esp8266/tools
sudo ./get.py


Board: WeMos D1
CPU Freq: 80 MHz
Upload using: Serial
Upload speed: 115200
Programmer: USBasp

Compile AVR code (ARDUINO NANO)

$(TOOLCHAIN_DIR)/avr-g++ -c -g -Os -std=gnu++11 -fno-exceptions \
    -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p \
    "-I/opt/Arduino/hardware/arduino/avr/cores/arduino" \
    <C/C++ source> -o <.o file>

TOOLCHAIN_DIR = /opt/Arduino/hardware/tools/avr/bin


with avrdude:

/usr/bin/avrdude -q -V -p atmega328p -C /etc/avrdude.conf -D -c arduino -b 57600 -P /dev/ttyUSB0 \
-U flash:w:build-nano-atmega328/Blink.hex:i

make show_boards

Thursday, June 28, 2018

ESP32 from Espressif Systems

This beast is really awesome.  For about $6 (on eBay), we can get a full functional IoT system using ESP32 application SoC made by a Chinese company called Espressif.  The CPU core is based on XTensa architecture.  XTensa is a CPU/MCU architecture designed by a Silicon Valley-based company named Cadence Tensilica.  Cadence Tensilica, according to Wikipedia, was founded by the former co-founder of the MIPS Technologies (one of the first player in RISC CPU architecture), Chris Rowen.

Espressif bought the IP rights to use in their own SoC products such as in ESP32 series. ESP32 itself is an evolutional product of its predecessor, ESP8266.  A lot of features in this tiny SoC, such as WiFi & Bluetooth,  cryptographic co-processor, Hall sensor, generous amount of ADC inputs (but multiplexed with other GPIOs), 2 DAC outputs, SPI, I2S, I2C,  ultra-low power coprocessor, Ethernet MAC MII interface (but we need to add PHY interface to connect to a medium), temperature sensor, touch sensors, CAN, 4 MB flash, etc.

Another interesting and cool thing is there a bunch of toolkits, SDK etc., including FreeRTOS support.  Configuring the device can be as easy with menu-driven a-la Linux Kernel.

Below is an example to blink the onboard LED (GPIO2) with FreeRTOS:

/* Blink Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"

/* Can run 'make menuconfig' to choose the GPIO to blink,
   or you can edit the following line and set a number here.

void blink_task(void *pvParameter)
    /* Configure the IOMUX register for pad BLINK_GPIO (some pads are
       muxed to GPIO on reset already, but some default to other
       functions and need to be switched to GPIO. Consult the
       Technical Reference for a list of pads and their default
    /* Set the GPIO as a push/pull output */
    gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
    while(1) {
        /* Blink off (output low) */
        gpio_set_level(BLINK_GPIO, 0);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
        /* Blink on (output high) */
        gpio_set_level(BLINK_GPIO, 1);
        vTaskDelay(1000 / portTICK_PERIOD_MS);

void app_main()
    xTaskCreate(&blink_task, "blink_task", configMINIMAL_STACK_SIZE, NULL, 5, NULL);

The Extensa ISA is actually a hybrid of RISC and CISC ISA.  As detailed in the documents at Github, about it has about 80 RISC instructions with length 24 or 16-bit (unlike common RISC instructions which uniformly 32 bits).  The architecture let the SoC designers customize it to add several extended CISC instructions to speed up and save memory space.  The CPU endianness is also changeable between Little and Big endian.

The extended instructions, among others, are to support MAC (Multiply-Accumulate) which is common in DSP applications and other media processing operations.  Another thing is the support for coprocessors.

Sunday, June 10, 2018

Regular Expression in C++



#include <iostream>
#include <string>
#include <regex>

class RegexDemo
        /** Default constructor */
        RegexDemo(char const *str) : m_str(str), m_matches() {};
        RegexDemo(std::string const & str);
        /** Default destructor */
        virtual ~RegexDemo();

        bool match(std::string const & pattern)
            return match(pattern.c_str());
        bool match(char const * pattern);

        std::cmatch& get_cmatch() { return m_matches; }

        friend std::ostream& operator<<(std::ostream& ios, std::cmatch const & cm);

        std::string     m_str;
        std::cmatch     m_matches;
        std::regex_constants::match_flag_type flag = std::regex_constants::match_any;

std::ostream& operator<<(std::ostream& ios, std::cmatch const & cm);

#endif // REGEXDEMO_H


#include "RegexDemo.h"

RegexDemo::RegexDemo(std::string const & str) :
    m_str(str), m_matches()


#if 0
bool RegexDemo::match(std::string const & pattern)
    std::regex exp(pattern);
    return std::regex_match(m_str, exp);

bool RegexDemo::match(char const * pattern/*, std::cmatch &cm*/)
    std::regex exp(pattern);
    return std::regex_match(m_str.c_str(), m_matches, exp, flag);

std::ostream& operator<<(std::ostream& ios, std::cmatch const & cm)
    for(unsigned i=0; i< cm.size(); ++i)
        ios << "[" << cm[i] << "] ";

    return ios;


#include <iostream>
#include "RegexDemo.h"

using namespace std;

int main()
    RegexDemo reg("Hello, World Ahsan,123Bae!");

    std::cout << "Match1: " << reg.match(".*123!") << std::endl;

    std::cmatch matches;
    if (reg.match("(.*),([0-9]+)(.*)"))
        std::cout << "The matches were: " << reg.get_cmatch() << std::endl;
        std::cout << "The number is " << reg.get_cmatch()[2] << std::endl;
    return 0;

The Output

$ ./myregex 
Match1: 0
The matches were: [Hello, World Ahsan,123Bae!] [Hello, World Ahsan] [123] [Bae!] 
The number is 123

Saturday, May 19, 2018

How to build wxWidgets for Windows

For sure we need Visual Studio installed (get the community edition for free).  After we install the source code package (e.g, in B:\WxWidgets-3.0.4)

Steps to build:

  1. Open "x64 Native Tools Command Prompt for VS ..." Command shell (just type in the Cortana search)
  2. Change to the wxWidgets directory
  3. type: 
cd wxWidgets-3.0.4\build\msw

nmake /f makefile.vc

After it finishes, just set WXWIN environment variable to poin to that directory (e.g, B:\WxWidgets-3.0.4)

Thursday, May 10, 2018

How to print ClassName

#ifndef __CNAME_H__
#define __CNAME_H__

#include <string>

inline std::string className(const std::string& prettyFunction)
    size_t colons = prettyFunction.find("::");
    if (colons == std::string::npos)
        return "::";

    size_t begin = prettyFunction.find_last_of("::") + 1;
    return prettyFunction.substr(begin);

#ifdef __GNUC__
#define __CLASS_NAME__ className(__PRETTY_FUNCTION__)
#define __CLASS_NAME__ className(__FUNCTION__)
#define __FUNCNAME__ __FUNCTION__