2017年2月15日 星期三

使用 C# 判斷有那些 Serial Port

    
    SerialPort ComPort = new SerialPort();
    string[] ports = SerialPort.GetPortNames();
    foreach(string portName in ports)
    {
        ComPort.PortName = portName;
        ComPort.BaudRate = 115200;
        ComPort.Parity = Parity.None;
        ComPort.StopBits = StopBits.One;
        ComPort.ReadTimeout = 500;
        ComPort.WriteTimeout = 500;
        try
        {
            ComPort.Open();
            ...
        }
        catch
        {
            ComPort.Close()
         
        }
    }

2016年11月22日 星期二

7zip batch file (add data into filename)


將 7zip 的壓縮指令寫成 batch file. 方便使用

setlocal
set hh=%time:~0,2%
if "%time:~0,1%"==" " set hh=0%hh:~1,1%
set yyyymmdd_hhmm=%date:~0,4%%date:~5,2%%date:~8,2%_%hh%%time:~3,2%

7z a zip_file%yyyymmdd_hhmm%.7z *.* -x!*.obj -r -x!obj
move zip_file%yyyymmdd_hhmm%.7z ..\backup\


其中 -x 是排除檔案的選項.
 -x!*.obj    --- *.obj 不加入到壓縮檔裡
 -x!obj    --- obj 檔名(或目錄名)不加入到壓縮檔裡

 而 -r 是包含子目錄

C# 呼叫 win32 API

在呼叫的函式前加入 win32API 的宣告

[DllImport("Kernel.dll")]
static extern uint QueryDosDevice(string lpDeviceName, IntPtr lpTargetPath, uint ucchMax);

public int queryFunc()
{   ...
    QueryDosDevice(...);
    ...
}

2016年11月3日 星期四

如何一次設定一個 Click Event Handler 到同一 StackPanel 裡的所有Button

ref : http://stackoverflow.com/questions/37876936/event-handler-formatting-multiple-buttons-wpf?noredirect=1&lq=1

有這樣的做法, 在前面指定 Button.Click :

<StackPanel Button.Click="button_Click" Grid.RowSpan="20">
     <Button Grid.Column="0" Grid.Row="0" FontWeight="Bold" BorderBrush="Black" Style="{StaticResource greenButton}">LT 1</Button>
     <Button x:Name="btn100" Grid.Column="0" Grid.Row="2" Style="{StaticResource greenButton}">100</Button>
     <Button x:Name="btn101" Grid.Column="0" Grid.Row="3" Style="{StaticResource greenButton}">101</Button>
     <Button x:Name="btn102" Grid.Column="0" Grid.Row="4" Style="{StaticResource greenButton}">102</Button>
 </StackPanel>
 
但是這樣會有 null exception 跑出來, 當然可以用 (e.OriginalSource as Button) 來避這個問題, 
也可以在 Style 裡用 EventSetter :
 
<Style x:Key="greenButton" TargetType="Button">
    ...
    <EventSetter Event="Click" Handler="button_Click"/>
</Style> 

WPF Binding

將 TextBox 裡的值隨著 ListBox 的選項改變

<ListBox x:Name="listBox" HorizontalAlignment="Left" Height="100" Margin="401,312,0,0" VerticalAlignment="Top" Width="100" >
    <ListBoxItem>Line 1</ListBoxItem>
    <ListBoxItem>Line 2</ListBoxItem>
</ListBox>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="207,290,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
    <TextBox.Text>
        <Binding ElementName="listBox" Path="SelectedItem.Content"></Binding>
    </TextBox.Text>
</TextBox>

如下圖, TextBox 裡顯示 ListBox 選的項目:


2016年10月24日 星期一

MSP430 LaunchPad Timer_0 Interrupt

Using Timer_0 Interrupt to Toggle LED on MSP430 LaunchPad


#include <msp430.h>

#define OUTPUT_PIN  BIT0
/*
 * main.c
 *
 *  Testing timer_0 interrupt to toggle LED (P1.0)
 */

int main(void) {
    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    P1DIR |= OUTPUT_PIN; // Set P1.0 and P1.6 to output direction
    P1OUT |= OUTPUT_PIN;
    P1OUT ^= (OUTPUT_PIN);


    BCSCTL1 = CALBC1_8MHZ;
    DCOCTL = CALDCO_8MHZ;

    CCTL0 = CCIE;
    TACTL = TASSEL_2 + ID_3 + MC_1;     // Set the timer A to SMCLCK, UP to TACCR0, Input Divider: /8
    TACCR0 = 50000-1;       // 50ms @(8MHz/8)

    __enable_interrupt();

    __bis_SR_register(LPM0 + GIE); // LPM0 with interrupts enabled
    while(1);
}

// Timer A0 interrupt service routine
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
    static unsigned char ucCount = 0;
    if(ucCount++ >= 20){
        P1OUT ^= OUTPUT_PIN;
        ucCount = 0;
    }

}

2016年8月25日 星期四

LME288 的處理方法

  1. Run command prompt as Administrator.
  2. Type (without quotes) "bcdedit /set IncreaseUserVa 3072"
  3. Reboot computer.

2016年7月19日 星期二

在 Batch File 中使用 findstr 比對 log 檔中的訊息

當 Batch File 需要判斷某個程式輸出的 log 檔內容時,  findstr 是一個可用的工具.

目前用過的參數:

參數說明:
findstr /?

比對檔案中的文字
findstr /c:string filename

可用 ERRORLEVEL 判斷是否有符合字串.

ERRORLEVEL 為 0 時, 有符合字串.
ERRORLEVEL 為 1 時, 沒有找到符合字串.

--
ERRORLEVEL 的用法:

IF ERRORRLEVEL N to check if the errorlevel is >= N. 
IF NOT ERRORLEVEL N to check if errorlevel is < N

例如:

findstr /C:FFFF info_1.hex
IF ERRORLEVEL 1 goto NOT_MATCH
echo MATCH
goto END

:NOT_MATCH

echo NOT_MATCH

:END

Batch file 指令太長如何換行

當 Batch File 的一行太長要換行時, 加入 "^" (不含 ") , 緊接著換行就可以了.
例如:

echo off
IF "%1"=="" goto end
echo %1

:end

寫成:


echo off
IF "%1"=="" ^
goto end

echo %1

:end

注意 "^" 一定要緊接著換行碼, 不能有空格!

2016年7月5日 星期二

python 中使用 enum


from enum import Enum
class Color(Enum):
    red = 1
    green = 2
    blue = 3

python 如何安裝 .whl 檔

在命令列中執行:

 pip install some-package.whl

就可以了

2016年7月1日 星期五

把 list 的資料寫入到 file


bytesToWrite=[125,3,255,0,101]
newfile=open("hello.bin",'wb')
newfile.write(bytes(bytesToWrite))
newfile.close()

2016年6月6日 星期一

Atmel Studio 7 啟動時 Error ("ErrorListPackage did not load correctly") 解決方式

參考:
http://atmel.force.com/support/articles/en_US/Workaround/Installing-Visual-Studio-2015-Update-1-leads-to-Atmel-Studio-no-longer-starting

Root Cause
The Visual Studio 2015 Update 1 updates a dll that is shared between Atmel Studio and Visual Studio, without providing the correct dll load redirect information. Until we have had the chance to verify that this new dll (version 1.1.37) works with Atmel Studio, we suggest downloading the previous version (1.1.36) and place it in a load path for Atmel Studio with higher load precedence than the Visual Studio load path.
Workaround
This issue is fixed in Atmel Studio 7.0.790 and newer.

If you are using an older version, use to following workaournd:
  1. Download System.Collections.Immutable (1.1.36) from nuget.org
  2. The file downloaded is a zip file with a .nupkg extension, rename the file to .zip 
  3. Open the zip file, go to the lib folder and into a folder called portable-net45%2Bwin8%2Bwp8%2Bwpa81
  4. Copy the System.Collection.Immutable.dll file into one of the Atmel Studio load folders
    1. We suggest using '<installdir>\Extensions\Application', which might be 'C:\Program Files (x86)\Atmel\Studio\7.0\Extensions\Application' on your machine

使用 python 計算加入天數後的日期


要算出 2000/1/1 後的 100 天是幾月幾號?

import datetime
first_date = datetime.date(2000,1,1)
delta_day = datetime.timedelta(days=100)
cal_date = first_date+delta_day
print(cal_date)

2016年5月4日 星期三

Raspberry Pi 的版本

顯示目前 raspberry pi 的版本:

$ uname -a
   Linux RPi 3.1.19 #1 PREEMPT Fri Jun 1 14:16:38 CEST 2012 armv6l GNU/Linux

顯示目前  firmware 的版本:

$ /opt/vc/bin/vcgencmd version
Feb  4 2015 21:04:27
Copyright (c) 2012 Broadcom
version 115f63aa0915cdb5b6dff23822eb16699b72ae8b (clean) (release)



ref: http://elinux.org/R-Pi_Troubleshooting#Check_your_firmware_version

讀取特定的行數

要讀取文字檔中的特定行數, 除了 for line in file(file) 之外;
使用內建函式 enumerate()

    for i, line in enumerate(fin,1):
        if i == 5:
            #do something
            break
    fin.close()


enumerate(iterable, start=0), 預設 start 是 0; 但是行數從 1 開始, 所以把 start 設為 1

2016年4月27日 星期三

開啟 csv 檔

要把 CSV 檔裡的欄位抓出來, 例如:
Time [s],Value,Parity Error,Framing Error
0,0xFF,,
0.0066405,0x00,,Error
0.513227,0x40,,

把 Value 這個欄位印出來:
import csv
fin = open('csvfile.csv')
for row in csv.DictReader(fin):
    print row['Value']

fin.close()

2016年3月23日 星期三

8051 Timer0 Mode0 (13 bits)

8051 Timer0 Mode0 (TMOD = 0x00) 是 13 bit timer, 要注意的是這裡 TL0 是 5 bits !!

TH0 (8 bits): 0~255
TL0 (5 bits): 0~31

所以在計算 overflow 時, 把計算值除 32 才是要給 TH0, 餘數給 TL0.
例如要在 1000 count overflow :

TH0 = (8192-1000)/32;
TL0 = (8192-1000)%32;

利用 python 經由 serial port 輸出資料


Python 需安裝 Python Serial Port Extension
  https://pypi.python.org/pypi/pyserial

安裝方式:
. 下載 pyserial-3.0.1.tar.gz
. 解開 pyserial-3.0.1.tar.gz
. 進入解開壓縮檔的目錄下, 執行:
  python setup.py install
 
開始寫程式:
# coding=UTF-8

import time
import serial


ptn = [0xAA,0x50,0x60,0x70]

def main():
   
    ser = serial.Serial('COM3', 2400, timeout=0.5)
    ary = bytearray(ptn)
    ser.write(ary)
    time.sleep(0.1)
    ser.close()   

if __name__ == "__main__":
    main()














ref : https://learn.adafruit.com/arduino-lesson-17-email-sending-movement-detector/installing-python-and-pyserial

2016年3月21日 星期一

Arduino bootloader hex file

Arduino bootloader hex code 就位在 arduino 安裝目錄下的 \hardware\arduino\avr\bootloaders 中
至於要選擇那一個檔案, 參考 boards.txt 裡的設定
例如 Arduino Uno:
..
uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0x05
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex
...