2024年11月19日 星期二

VirtualBox 空間減肥

@windows vm
sdelete64 -z c:

@macos
VBoxManage  modifymedium  disk  "/Users/fellow/VirtualBox VMs/Win10/Win10.vdi"  --compact

*.vdi 路徑可以在 VirtualBox 儲存空間中找到

2023年7月25日 星期二

更高效處理 micro second 的方式

更高效處理 micro second 的方式… 

以 STM32 為例…

__IO unsigned long sys_tick = 0;

void SysTick_Handler(void)
{
    HAL_IncTick();
    sys_tick += (SysTick->LOAD + 1);
}

unsigned long  micros_ticks(void)
{
    unsigned long save_sys_tick;
    unsigned long st;

    do
    {
        save_sys_tick = sys_tick;
        st = SysTick->VAL;
    } while (save_sys_tick != sys_tick);
    return (save_sys_tick-st);
}

Get micro second...
micros = micros_ticks()/(SysTick->LOAD + 1) 
or just get ticks for saving cpu calculate time...
microsxconstant = micros_ticks()

*在只需計時的場合直接使用 micros_ticks,可以節省 CPU 運算除法的時間

2023年3月8日 星期三

ArchLinux 安裝筆記

ArchLinux 安裝筆記 

使用 vm 練習 archlinux 安裝…

/// 磁碟分割
fdisk /dev/sda
// gpt 分割表
g
// 建立第一磁區 for /mnt/boot
n
1
ENTER
+512M
yes
// type 改為 EFI
t
uefi
// 建立第二磁區 for /mnt
n
2
ENTER
ENTER
yes
/// 寫入磁碟
w

/// 格式化磁碟
mkfs.fat -F32 /dev/sda1
mkfs.btrfs /dev/sda2

/// mount 磁區到 /mnt
mount /dev/sda2 /mnt

/// mount 磁區到 /mnt/boot
/// 注意!! /mnt/boot 資料夾在這邊就好建好 mount 好,系統才會安裝在正確的位置
mkdir /mnt/boot
mount /dev/sda1 /mnt/boot

/// 安裝基本系統
pacstrap /mnt base linux linux-firmware

/// 設定開機硬碟掛載規則
genfstab -U /mnt >> /mnt/etc/fstab

/// 進到新系統
arch-chroot /mnt

/// 安裝必要的軟體 networkmanager 才能連網
pacman -S sudo nano networkmanager

/// 啟用網路
systemctl enable NetworkManager.service
systemctl start NetworkManager.service

/// 變更 root 密碼
passwd
xxxxxxxx
xxxxxxxx

/// 安裝 grub 開機選單
pacman -S grub efibootmgr

/// 安裝 grub 至 EFI 分區
grub-install --target=x86_64-efi --bootloader-id=GRUB --efi-directory=/boot
grub-mkconfig -o /boot/grub/grub.cfg

/// 收尾
exit
umount /mnt/boot
umount /mnt
shutdown now


2021年10月14日 星期四

One Source, Multi-MCUs

The global chip shortage has turned me into a multi-platform firmware developer.

Zero code modifications.

STM / MM32 / Nuvotone



解決 Google Drive 中文名稱的問題

問題 :

    Google Drive 雲端硬碟檔案串流 在中文環境下預設是「G:\我的雲端硬碟」,磁碟代號可改,但「我的雲端硬碟」卻無法修改,導致有些「非多國語應用程式」無法正確指到檔案路徑。

解決 :

    使用 Windows 內建虛擬磁碟指令將 指定目錄變成一顆磁碟機…

        subst x: G:\我的雲端硬碟

2021年9月13日 星期一

一個奇怪的問題、一種簡單的解法

兩個未知規格的熱敏電阻(10K、20K或50K…未知),熱敏電阻A、熱敏電阻B

如何驗證二顆不同的熱敏電阻規格是一致的?

原來是一個簡單的分壓問題…

測試一、正電-->熱敏電阻A--求分壓a-->熱敏電阻B--負電

測試二、正電-->熱敏電阻B--求分壓b-->熱敏電阻A--負電

測試環境從 100°C~0°C,分壓a 需恆等於分壓b

即可初步判定二顆熱敏電阻規格是一致的

2021年9月9日 星期四

RDM DISCOVERY_COMMAND use Recursive Method

void DiscoveryAll( void ) {     /// unmute all devices : RDM_UnMute()     /// implement DISCOVERY_COMMAND:DISC_UNMUTE    RDM_UnMute( 0xFFFFFFFFFFFF ); 

    /// discovery full range      Discovery( 0, 0xFFFFFFFFFFFE );           }

void Discovery( long long low, long long high ) {     unsigned char res;

    while(1)     {         /// try to discover devices : RDM_Discovery()         /// implement DISCOVERY_COMMAND:DISC_UNIQUE_BRANCH        res = RDM_Discovery( low, high ); 

        if( res == TARGET_IDENTIFIED )    /// target identified                {             /// mute identified target : RDM_Mute()             /// implement DISCOVERY_COMMAND:DISC_MUTE            RDM_Mute(target);                continue;    /// repeat         } else if( res == DETECT_COLLISIONS )    /// detect collisions        {            Discovery( low, (low+high)/2 );    /// discovery low bound            Discovery( (low+high)/2+1, high );    /// discovery high bound        }

        return;    /// finish     } }

2020年3月10日 星期二

Raspberry Pi 3 Static IP, WIFI and Ethernet


sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
network={
ssid="XXX"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP TKIP
psk="XXXXX"
}

sudo nano /etc/network/interfaces
iface eth0 inet manual 
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

sudo nano /etc/dhcpcd.conf
interface eth0
static ip_address=192.168.1.111/24
static routers=192.168.1.1
static domain_name+servers=8.8.8.8 
interface wlan0
static ip_address=192.168.1.222
static routers=192.168.1.1
static domain_name_servers=8.8.8.8

2020年2月17日 星期一

DMX512 protocol

DMX protocol…
# 1:break + 1:start + 512:channel

python:
import serial

class DMX512:
    def __init__(self, port):
        self.serial = serial.Serial(
        port=port,
        baudrate=250000,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_TWO,
        timeout=0
        )
        self.data=[0]*513   # 513 bytes = 1:start + 512:channel

    def setChannel(self, chan, intensity):
        self.data[chan] = intensity

    def setAll(self,col):
        for i in range(1, 513):
            self.data[i] = col

    def update(self):
        # break use or serial.send_break  or serial.break_condition
        self.serial.send_break(0.0001)  # 100us but not precise on different OSs
        # 513 bytes = 1:start + 512:channel
        self.serial.write(bytes(self.data))

dmx = DMX512( 'COM3' )
dmx.setAll(255)
dmx.update()

stm8s:
====BREAK====:
UART3_Init(
    (u32)45500,
    UART3_WORDLENGTH_9D,
    UART3_STOPBITS_1,
    UART3_PARITY_NO,
    UART3_MODE_TXRX_ENABLE
    );
UART3_SendData9( 0x0100 | 0x00 );

====TX/RX====:
UART3_Init(
    (u32)250000,
    UART3_WORDLENGTH_9D,
    UART3_STOPBITS_1,
    UART3_PARITY_NO,
    UART3_MODE_TXRX_ENABLE
    );
UART3_SendData9( 0x0100 | data ); /// 513 BYTES

====rx====:
u8 dmx_buffer[513];
u16 dmx_buffer_idx; 
BOOL DMX_FLAG = FALSE;
BOOL SC_FLAG = FALSE;

void UART3_RX_IRQHandler( void )
{
    BOOL BREAK_FLAG = FALSE; 
    u8 rx = 0; 

    /// DMX512 = 1:break + 1:start + 512:data
    if(UART3_GetITStatus(UART3_IT_RXNE )!= RESET)
    {
        BREAK_FLAG = UART3_ReceiveData9()>>8;
        rx = UART3_ReceiveData8();

        if(BREAK_FLAG == FALSE) /// 1:break
        {
            if(rx == 0x00)
            {
                SC_FLAG = TRUE;
                return ;           
            }
        }

        if((BREAK_FLAG == TRUE)&&(SC_FLAG == TRUE)) /// 1:start
        {
            SC_FLAG = FALSE;
            if(rx == 0x00)
            {
                DMX_FLAG = TRUE;
            dmx_buffer_idx = 1; /// fill buff start from idx=1
            return;
        }
        }

        if((BREAK_FLAG == TRUE)&&(DMX_FLAG == TRUE)) /// 512:data
        {
            if( dmx_buffer_idx < sizeof(dmx_buffer) )
            {
            dmx_buffer[dmx_buffer_idx] = rx;
                dmx_buffer_idx++;
            }
        }
    }
}

2019年7月18日 星期四

Bluepy Scanner disconnects exist connections

解決 blueby 每次 scan 就會中斷先前連線的問題

困擾了很久
試過各種寫法 thread / lock / wait / pause / sleep 都無效

結果很簡單,只要 scan 時增加 passive=True 就好了

            scanner = Scanner().withDelegate(ScanDelegate())
            devices = scanner.scan(1.0, passive=True)

2019年7月16日 星期二

Raspberry pi 同時使用 藍牙及 UART

sudo raspi-config
Interface > Serial > No

sudo nano /boot/config.txt
新增底下三行
core_freq=250
dtoverlay=pi3-miniuart-bt
enable_uart=1

注意此時 uart 是使用系統時脈產生 baud rate,不能太快

2019年7月15日 星期一

RPI Hash-sum mismatch on apt-get

apt-get update 出現問題

嚐試使用低下方式解決…

sudo rm /var/lib/apt/lists/* -vf

sudo apt-get update

2019年7月9日 星期二

NXP S9KEAZN64 Disable NMI


陷阱題:

KE 系列 MCU,PTB4 腳在 reset 後預設會使用 NMI 功能
導致無法當一般 GPIO 使用
因此要 Disable 掉
不然會 d 到天荒地老

在 system_SKEAZN642.c 中 void SystemInit (void) 函式 增加一行…
SIM->SOPT &= ~SIM_SOPT_NMIE_MASK;                //禁用NMI

2019年7月8日 星期一

Keil C axf 轉 elf

Keil C options-->user-->after build
使用 fromelf 轉換格式…
fromelf --elf --output=$L@L.elf #L


2019年4月10日 星期三

Flutter/Dart神奇的語法

習慣傳統程式語言,這種的初看像謎之符號,細看覺得神奇!!
Future <bool> ShowYesNoDialog(
BuildContext context,
doYes,
doNo
) async
{
return showDialog(
context: context,
builder: (context) => AlertDialog(
actions: <Widget>[
RaisedButton(
onPressed: ((){doYes();}),
),
RaisedButton(
onPressed: ((){doNo();}),
),
],
),
) ??
false;
}

await ShowYesNoDialog(
context, 'SayYesNo', 'Yes or No?',
((){print('yes');}),
((){print('no')}),
);

2019年3月29日 星期五

python 處理 word 表格

# coding=utf-8
import docx
import glob
import os
import csv

#設置檔案路徑
path = '範例檔'
#設置輸出檔名
output = 'output.csv'

#開啟輸出的 CSV 檔案
with open(output, 'w', newline='') as csvfile:
  #建立 CSV 檔寫入器
  writer = csv.writer(csvfile)
  #header
  writer.writerow(['檔名','學校','班級','學生','國語','數學','社會','自然','藝術'])
 
for filename in glob.glob(os.path.join(path, '*.docx')):    #遍歷所有檔案
    #doc = docx.Document("範例檔\su_sn_11122.docx")
    doc = docx.Document(filename)
    for table in doc.tables:    #遍歷所有表格
        print("--------")
        _school = ''
        _class = ''
        _student = ''
        _score1 = ''
        _score2 = ''
        _score3 = ''
        _score4 = ''
        _score5 = ''
        done = False
        i = 0
        for row in table.rows:  #遍歷表格的所有 row
            #row_str = "\t".join([cell.text for cell in row.cells])  # 一行數據
            #print(row_str)
            j = 0
            for cell in row.cells:  #遍歷 row 中所有 cell
                #print( cell.text + "\t" )
                #print( str(i)+":"+str(j)+":"+table.cell( i, j ).text + "\t" )
                if cell.text == '學校':
                    _school = table.cell( i, j+1 ).text #抓右邊的 cell
                if cell.text == '班級':
                    _class = table.cell( i, j+1 ).text #抓右邊的 cell
                if cell.text == '學生':
                    _student = table.cell( i, j+1 ).text #抓右邊的 cell
                if cell.text == '國語':
                    _score1 = table.cell( i+1, j ).text  #抓下面的 cell
                if cell.text == '數學':
                    _score2 = table.cell( i+1, j ).text  #抓下面的 cell
                if cell.text == '社會':
                    _score3 = table.cell( i+1, j ).text  #下面的 cell
                if cell.text == '自然':
                    _score4 = table.cell( i+1, j ).text  #抓下面的 cell
                if cell.text == '藝術':
                    _score5 = table.cell( i+1, j ).text  #抓下面的 cell
                    done = True #這是最後一筆資料
                j = j + 1   #指向下一 cell
                if done:
                    break   #完成
            i = i + 1   #指向下一 row
            if done:
                break   #完成
        print( _school )
        print( _class )
        print( _student )
        print( _score1 )
        print( _score2 )
        print( _score3 )
        print( _score4 )
        print( _score5 )
        with open('output.csv', 'a', newline='') as csvfile:
            #建立 CSV 檔寫入器
            writer = csv.writer(csvfile)
            #內容
            writer.writerow([filename,_school,_class,_student,_score1,_score2,_score3,_score4,_score5])
        break #限制1檔1表

2019年3月15日 星期五

Modbus 傳輸資料型態轉換

Modbus 協議傳輸的資料一般只有基本的 U16 型態,但在實際應用上可能因裝置不同而有不同的應用,例如長整數、浮點數,但又因為硬體 CPU/MCU/OS 實際狀況而有位元順序的問題,底下是 python 轉換函式…

def Convert( theType, values  ):
    if( theType == 'FLOAT(ABCD)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[0],tobytes[1],tobytes[2],tobytes[3])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'FLOAT(CDAB)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[2],tobytes[3],tobytes[0],tobytes[1])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'FLOAT(BADC)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[1],tobytes[0],tobytes[3],tobytes[2])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'FLOAT(DCBA)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[3],tobytes[2],tobytes[1],tobytes[0])
            set_value = struct.unpack('>f', packit)[0]
    elif( theType == 'UINT32(ABCD)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[0],tobytes[1],tobytes[2],tobytes[3])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'UINT32(CDAB)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[2],tobytes[3],tobytes[0],tobytes[1])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'UINT32(BADC)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[1],tobytes[0],tobytes[3],tobytes[2])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'UINT32(DCBA)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[3],tobytes[2],tobytes[1],tobytes[0])
            set_value = struct.unpack('>L', packit)[0]
    elif( theType == 'INT32(ABCD)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[0],tobytes[1],tobytes[2],tobytes[3])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'INT32(CDAB)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[2],tobytes[3],tobytes[0],tobytes[1])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'INT32(BADC)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[1],tobytes[0],tobytes[3],tobytes[2])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'INT32(DCBA)' ):
            packit = struct.pack('>hh',values[0],values[1])
            tobytes = struct.unpack('>4c', packit)
            packit = struct.pack('>4c',tobytes[3],tobytes[2],tobytes[1],tobytes[0])
            set_value = struct.unpack('>l', packit)[0]
    elif( theType == 'UINT16(AB)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[0],tobytes[1])
            set_value = struct.unpack('>H', packit)[0]
    elif( theType == 'UINT16(BA)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[1],tobytes[0])
            set_value = struct.unpack('>H', packit)[0]
    elif( theType == 'INT16(AB)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[0],tobytes[1])
            set_value = struct.unpack('>h', packit)[0]
    elif( theType == 'INT16(BA)' ):
            packit = struct.pack('>h',values[0])
            tobytes = struct.unpack('>2c', packit)
            packit = struct.pack('>cc',tobytes[1],tobytes[0])
            set_value = struct.unpack('>h', packit)[0]
    else:
        set_value = values[0]
    return set_value

#Modbus 讀值可能是 2byte 也可能是 4byte
values = [-4370,-8756]
Convert( 'FLOAT(ABCD)' ,values )
Convert( 'FLOAT(DCBA)' ,values )
Convert( 'FLOAT(BADC)'  ,values )
Convert( 'FLOAT(CDAB)'  ,values )
Convert( 'UINT32(ABCD)'  ,values )
Convert( 'UINT32(DCBA)'  ,values )
Convert( 'UINT32(BADC)'  ,values )
Convert( 'UINT32(CDAB)'  ,values )
Convert( 'INT32(ABCD)'  ,values )
Convert( 'INT32(DCBA)'  ,values )
Convert( 'INT32(BADC)'  ,values )
Convert( 'INT32(CDAB)'  ,values )
Convert( 'UINT16(AB)'  ,values )
Convert( 'INT16(AB)'  ,values )
Convert( 'INT16(BA)'  ,values )
Convert( 'UINT16(BA)'  ,values )

2019年1月23日 星期三

Holtek 使用 HSI 的方式

Holtek 使用 HSI 的方式…

以 HT32f2220 為例
從 project_template 建立專案的話,修改底下 define …

在 system_ht32f5xxxx_02.c 中…
#define HSI_ENABLE        (1)     /*!< 0: DISABLE,  1: ENABLE                                               */
#define HSE_ENABLE        (0)     /*!< 0: DISABLE,  1: ENABLE                                               */
#define LSI_ENABLE        (1)     /*!< 0: DISABLE,  1: ENABLE                                               */
#define LSE_ENABLE        (0)     /*!< 0: DISABLE,  1: ENABLE                                               */
#define PLL_ENABLE        (1)     /*!< 0: DISABLE,  1: ENABLE                                               */
#define PLL_CLK_SRC       (1)     /*!< 0: HSE,      1: HSI                                                  */

再直接使用 example 中的 SysClockConfig_HSI() 函式進入 HIS 模式即可。

這樣 XTALIN、XTALOUT 就能拿來當 gpio 腳了。

2018年11月21日 星期三

Debian Security Bug Tracker

檢查弱點分析的方式

到…
Debian Security Bug Tracker
https://security-tracker.debian.org/tracker/

查詢弱點…
譬如 CVE-2017-3169

Debian / Raspberry Pi 檢查版本
dpkg -l apache2

比較版本號是否有修正此 bug

VirtualBox 空間減肥

@windows vm sdelete64 -z c: @macos VBoxManage  modifymedium  disk  "/Users/fellow/VirtualBox VMs/Win10/Win10.vdi"  --compact *.vdi...