Sunday, July 14, 2024

ESP NOW - Intro (1)

 ESP NOW is a simple peer-to-peer

    wireless communication method.

It can be set up for one-to-one,

   one-to-many, and many-to-many comm.

Some people use it as a remote control solution.


How to use?

Summary of steps:

    1) init esp now

    2) add peer(s), statistically!

    2) register callbacks

    3) do send message

        // payload is 250 bytes max, C struct


Read more »

Labels: , , , , ,

Tuesday, June 25, 2024

Sense Hat Cheatsheet (for Raspberry Pi)

from sense_hat import SenseHat

sense = SenseHat()

# -------------robotera.blogspot.com---------------------------

# 8x8 LED matrix

sense.clear()

sense.clear(r, g, b)

sense.show_letter("J")

sense.show_letter("L", red)

sense.show_message("Hello world")   # default scroll_speed = 0.1 sec

sense.show_message("Hello world", 0.3)   # 2nd argument scroll_speed; also set rotation to 270 degree

sense.show_message("Keep the arrow pointing up", scroll_speed=0.05, text_colour=[100,100,100])

sense.show_message(message, scroll_speed=0.05)

sense.show_message(message)    # optional to set scroll_speed=0.05, text_colour=[r,g,b], back_colour=[r,g,b]

sense.set_pixel(x,y, (r,g,b))       # index 0-7

sense.set_pixels(array_8x8_colours)

sense.set_rotation({angle:0|90|180|270})    # for LED matrix

sense.flip_h()      # horizontal mirroring

sense.flip_v()      # vertical mirroring

# ambient

sense.get_humidity()                # percentage, eg.  41.35004..

sense.get_pressure()                # millibars, eg. 1013.40380859

sense.get_temperature()             # celcius, eg. 33.5409..

sense.get_temperature_from_humidity()   # same as get_temperature()

sense.get_temperature_from_pressure()

# detect gravity

sense.get_accelerometer_raw() # return dictionary of x, y, z  # unit G

# gyroscope

sense.get_orientation()      # return dictionary of pitch, roll, yaw

# joystick opt 1) get events

event = sense.stick.get_events()

    event.direction     # string: {up | down | left | right | middle}

    event.action        # string: {pressed | released}

# joystick opt 2) register stick callbacks

    sense.stick.direction_up = fcn_up

    sense.stick.direction_down = fcn_dn

    sense.stick.direction_left = fcn_l

    sense.stick.direction_right = fcn_r

    sense.stick.direction_middle = fcn_m

# colour sensor (version 2 only)

    sense.color.gain = 60

    sense.color.integration_cycles = 64

    c = sense.colour.colour        # return tuple of (r,g,b,clear)

    sense.colour.integration_time

# -------------robotera.blogspot.com---------------------------

from time import sleep

sleep(0.5)      # half second

from random import randint

num = randint(0,10)     # inclusive [0,10]

from random import choice

card = choice(['A', 'K', 'Q', 'J'])

from random import uniform

fnum = uniform(0,10)    # exclusive [0.0, 10.0)

# built-in

f = round(f, 1)

s = str(5)

n = int('8')


Labels: ,

Sunday, April 09, 2023

raspberry pi write image (.xz) to SD through the pipe; without pre uncompress, everything on the fly

 

unxz raspberrypi-someversion.img.xz -c | dd of=/dev/sdc  bs=2M  && sync

# -c     stdout

# osx example, if /dev/disk2       bs=2m

Labels: , , ,

Sunday, October 09, 2022

STM32 HAL API functions (1) - basic

HAL stands for  Hardware Abstraction Layer.  It's generic API by ST Microtronics to program their MCUs.


/* delay */

HAL_Delay(1000);


/* GPIO */

HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);

HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);    // set HI

HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET);     // set LO


/* UART */

HAL_UART_Transmit(&huart2, (uint8_t*)msg, strlen(msg), HAL_MAX_DELAY);


/* I2C */     // example: TMP102

HAL_StatusTypeDef   ret;       // expect HAL_OK if operation is successful

// set request argument in buf[0], then:

ret = HAL_I2C_Master_Transit(&h12c1, TMP102_ADR, buf, 1, HAL_MAX_DELAY);

ret = HAL_I2C_Master_Receive(&h12c1, TMP102_ADR, buf, 2, HAL_MAX_DELAY);


/* ADC */

HAL_ADC_Start(&hadc1);

HAL_ADC_PollForConversion(&hadc1, HAL_MAX_DELAY);

uint16_t     raw;

raw = HAL_ADC_GetValue(&hadc1);


Labels: ,

Saturday, October 08, 2022

FreeRTOS Cheatsheet

/* basic - why RTOS? want tasks for concurrency */
#include "FreeRTOS.h"
#include "task.h"
TaskHandle_t    myTask1Handle = NULL;
void myTask1 (void *p) {
    while (1) {
    }
}
// then in main.c
  // create task
  vTaskStartScheduler ();    // won't return
  while (1) {
  }

//-------------------------------------------------
/* Task */
xTaskCreate ( myTask1, "task1", 200 /*stacksize*/, (void*)0, 
                    tskIDLE_PRIORITY, &myTask1Handle);
vTaskSuspend ( myTask1Handle );
vTaskSuspendAll();
vTaskResume ( myTask1Handle );

curTaskHandle = xTaskGetCurrentTaskHandle();
vTaskDelete ( curTaskHandle );  // delete oneself

taskName = pcTaskGetName ( myTask2Handle );
taskHandle = xTaskGetHandle ( "dog" );  // find handle by name

eTaskState myState;
myState = eTaskGetState ( myTaskHandle );   // return enum, 1 is eReady

char myTaskList[300];
vTaskList ( myTaskList );

uxTaskGetNumberOfTasks()
xTaskGetTickCount()             // do NOT use in ISR
xTaskGetTickCountFromISR()      // ISR version

//-------------------------------------------------
/* prefix */
https://www.freertos.org/FreeRTOS-Coding-Standard-and-Style-Guide.html#NamingConventions
// fcns:
v   void
x   return code or handle   // ux  eg. UBaseType_t
// vars:
ul  uint32_t    u   uint16_t    uc  uint8_t
c   char        l   long        s   short
e   Enumerated variables
pc  char *

//-------------------------------------------------
/* delay */
vTaskDelay ( 1000 ); // only if at default Hz; still slightly > 1000 ms
vTaskDelay ( 1000 * configTICK_RATE_HZ / 1000 ); // independent from Hz
  // precise version:
TickType_t  myLastUnblock;
myLastUnblock = xTaskGetTickCount ();
vTaskDelayUntil ( &myLastUnblock, 1000 * configTICK_RATE_HZ / 1000 );

//-------------------------------------------------
/* interrupt */
void myIntTask(void *p) {
    while (1) {
        vTaskSuspend( NULL );  // suspend right away once started
        // do work
    }
}
// in default IRQ Handler
BaesType_t xYieldRequired;
xYieldRequired = xTaskResumeFromISR ( myIntTask ); // resume my int fcn
portYIELD_FROM_ISR( xYieldRequired );  // require context switch

//-------------------------------------------------
/* Queue */     LIFO - add to back(tail), get from front(head)
#include "queue.h"
QueueHandle_t   myQueue;
char buf[30];
myQueue = xQeuueCreate ( /*len*/5, sizeof(txBuf) );
// task 1
xQueueSend ( myQueue, (void*) txBuf, (TickType_t) 0);  // block time 0 (no block)
xQueueSendToFront (..)  // reverse order
xQueueOverwrite (..)    // default send not overwrite
// task 2
if( xQueueReceive ( myQueue, (void*) rxBuf, (TickType_t) 5 )) {
    // "Receive" blocked to read
    // xQueuePeek (..)
    // ..
}

uxQueueMessageWaiting ( myQueue ); // wait until ready
uxQueueSpaceAvailable ( myQueue );
xQueueReset ( myQueue );           // dump all unread message

//-------------------------------------------------
/* Notification */
/*task1*/ xTaskNotifyGive ( myTask2Handle ); // 'Give' to increment by 1 // default 0
/*task2*/ notifiedValue = ulTaskNotifyTake ( pdFALSE,
                                        (TickType_t) portMAX_DELAY );
    // decrement if false, reset to 0 if true

// task1
xTaskNotify ( myTask2Handle, 0, eNoAction );
    // eSetBits, eIncrement, eSetValueWithOverwrite, eSetValueWithoutOverwrite
    // eg. xTaskNotify ( myTask2Handle, (1<<2) | (1<<1), eSetBits );
xTaskNotifyAndQuery ( myTask2Handle,
                      (1<<2),
                      eSetValueWithOverwrite, 
                      &ulNotifiedValue ); // store last value before inc
xTaskNotifyStateClear ( myTask2Handle ); // cancel send, value remains
// task2
if ( xTaskNotifyWait(0, 0, &ulNotifiedValue, portMAX_DELAY ) == pdTRUE ) {
    // ..
}

//-------------------------------------------------
/* Semaphore */
#include "semphr.h"
// same handle for mutex & semaphore, up to create fcn
SemaphoreHandle_t   xMutex; 
xMutex = xSemaphoreCreateMutex(); // ... here determine what type
if ( xSemaphoreTake ( xMutex, (TickType_t) 0xFFFFFFFF ) == 1 ) { // LOCK
    // do work
    xSemaphoreGive ( xMutex );  // UNLOCK
}
Read more »

Labels:

Saturday, October 02, 2021

Raspberry Pi 樹莓派 在 Manjaro-ARM 安裝中文輸入法 倉頡

Pi 可以裝linux,Manjaro 出名輕量,少佔用系統資源,而且是rolling release,不用每幾年fresh install 新版本。

安裝中文輸入法,我本來先試scim ,貪其輕巧,但一來找不到倉頡,二來慣用ibus,所以,換ibus 再試,步驟如下。


1. 用GUI介面menu > install/remove software,選:

ibus

ibus-table

ibus-table-chinese


2. 重啓後,menu 搜session and startup

autostart applications 加 /usr/bin/ibus-daemon


3. 設定 keyboard hotkeys


完成!


x86/64 版 Manjaro 應該亦OK。

Labels: , , , ,

Tuesday, June 29, 2021

try Adafruit Feather Huzzah32 on Arduino IDE, mx-linux

A feather (optional with wing) is like an arduino (optional with shield) but toward a different direction - a feather is like an abstracted hardware layer, not big problem with the underneath physical chipsets, that codes can theoretically run fine even if in a project, swapping a feather with another one, for power or feature upgrade.

Choosing Huzzah32 for its supporting to MQTT server, Arduino IO.

The chipset ESP32 is the "big sister" of the popular ESP8266 with WIFI built-in, in addition, bluetooth too.

The official guide said ESP32 is better with Arduino IDE, although the installation configs is slightly different from likely due to the changes in the latest version of tools, as below:

0. if not yet, linux needs pyserial module for serial port communication.

    a. if not yet have pip, 

            $ sudo apt install python-pip

    b. get the serial module

            $ pip install pyserial

1. The guide recommends IDE 1.6.  Some other lines said recent version stock IDE releases support loading thiry-party board definitions.   I use 1.8.15 on site from arduino.cc.

2. to add Huzzah32 board definition, menu  File > Preference

        add Espressif URL, not from Adafruit

3. (after connecting usb to the board and select port ttyusb0)  

    select board - menu tools > board manager...

    select "contributed" category, search for "esp32" from Expressif, install.


    

Labels: , , , ,