레이블이 Written in English인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Written in English인 게시물을 표시합니다. 모든 게시물 표시

2017년 4월 29일 토요일

(E)Silicon Labs C8051 LED Blinky Example Explained(C8051 chip 기본동작 LED 예제로 설명하기)

Purpose
for newbie(software engineer) to understand basic concept of embedded programming.
line by line explanation.

Preparation
board: C8051F560 Development Kit
part(Chip): C8051F568-ACK06Z
datasheet: C8051F55x/56x/57x
development kit document: C8051F560 DEVELOPMENT KIT USER ’S GUIDE
development Tool: Simplicity Studio v4
silicon labs debugger
PC(notebook)

Prerequisite
install simplicity studio v4
connect PC-board-debugger

Create (example) project
simplicity IDE - File - New - Project - Silicon Labs MCU Project
select board
select part
select project type:example
select f55x-57x Blinky
copy contents

Explanation
1. Program Description:
  This program flashes the green LED on the C8051F560 target board about
  five times a second using the interrupt handler for Timer2.

2. How To Test:
  1) Download code to the 'F560 target board
  2) Ensure that the P1.3 pins are shorted together on the J19 header
  3) Run the program.  If the LED flashes, the program is working
  J19: Side A: Connects P1.3_A LED and P1.4_A Switch to MCU port pins


3. Code:
  // Includes
  // Global CONSTANTS -> set system clock speed, and select pin to connect to LED
  // Function PROTOTYPES
  //// OSCILLATOR_Init -> set oscillator speed
  //// PORT_Init -> set pin to manipulate LED
  //// TIMER2_Init -> set timer speed, init(&reload) value, enable interrupt and start timer
  // Interrupt Service Routines
  //// Timer2_ISR -> set interrupt service routine function when timer executed
  // MAIN Routine -> initialize and execute while not to exit firmware.

4. line by line code explanation.
    1) Total 175 line of Code
        - 93 lines of Comments
        - 16 lines of new line
        - 66 line of (meaningful) code
    2) will be continued

37: #include <SI_C8051F550_Defs.h>
-> SFR(Special Function Register) address
-> (IRN) Interrupt Request Numbers

38: #include <SI_C8051F550_Register_Enums.h>
-> Register Names

44: #define SYSCLK       24000000/8        // SYSCLK frequency in Hz
SYSCLK : System  Clock
Processor Clock: Chip Clock
-> more explanation needed
reference: Link

46: SBIT (LED, SFR_P1, 3);                 // LED='1' means ON
LED is variable to connect SFR_P1(port 1), pin 3 with rear LED.
so LED=1 make LED light on

52: void OSCILLATOR_Init (void);
initialize oscillator for oscillation of the crystal

53: void PORT_Init (void);
set pin to execute the chip for purpose
in this case LED pin

54: void TIMER2_Init (U16 counts);
configuration timer 2 to execute chip.
configure consists Interrupt Service Routine, Auto-reload, Timer base

59 ~ 75: Main
explained later

88 ~ 96: OSCILLATOR_Init function
88: void OSCILLATOR_Init (void)
89: {
90:    U8 SFRPAGE_save = SFRPAGE;
To read or modifying the SFR value, we need to contact the register.
the steps are
1. Select the appropriate SFR page number using the SFRPAGE register.
2. Use direct accessing mode to read or write the special function register (MOV instruction).

SFR has pages, for C8051F55x/56x/57x family of devices utilizes three SFR pages: 0x00, 0x0C, and 0x0F (ref: datasheet 12.1. SFR Paging)

91:    SFRPAGE = CONFIG_PAGE;
CONFIG_PAGE is 0x0F, and to modify OSCICN register this address should be accessed
92:
93:    OSCICN = 0xC4;                      // Set oscillator divide to /8
OSCICN: Internal Oscillator Control
0xC4 saids 100: SYSCLK derived from Internal Oscillator divided by 8.
datasheet saids SFR Address = 0xA1; SFR Page = 0x0F
so this makes system clock to 24000000(default) / 8 (line 44)
94:
95:    SFRPAGE = SFRPAGE_save;
return pre-sfrpage
96: }

111: void PORT_Init (void)
112: {
113:    U8 SFRPAGE_save = SFRPAGE;
114:    SFRPAGE = CONFIG_PAGE;
115:
116:    P1MDOUT |= 0x08;                 // Enable LED as a push-pull output
P1MDOUT was declared as
SFR (P1MDOUT,     0xA5); ///< Port 1 Output Mode
0xA5 address's value is assigned to P1MDOUT
to configure P1MDOUT(Port 1 mode Out)
it can be done with config2.exe
0x08 is 00001000 as binary and this means port 1 pin 3 is push-pull output
117:    P1SKIP  |= 0x08;                    // Skip the LED pin on the crossbar
skip port 1 pin 3 not to connect any peripheral
119:    XBR2     = 0x40;                    // Enable crossbar and weak pull-ups
see ref1 below
121:    SFRPAGE = SFRPAGE_save;
122: }

137: void TIMER2_Init (U16 counts)
138: {
139:    U8 SFRPAGE_save = SFRPAGE;
140:    SFRPAGE = LEGACY_PAGE;

142:   TMR2CN  = 0x00;                  // Stop Timer2; Clear TF2;
                                                 // use SYSCLK/12 as timebase
144:   CKCON  &= ~0x60;               // Timer2 clocked based on T2XCLK; <- same as above comment(SYSCLK/12 as timebase)

146:   TMR2RL  = -counts;              // Init reload values
timebase is 250,000 hz(250,000 cycles in 1 second)
counts value is 25,000(number, cycles) so
25,000 times takes 25,000 / 250,000 * 1seconds = 1/10 seconds.
this means 10hz frequency
147:   TMR2    = 0xFFFF;                // Set to reload immediately
148:   IE_ET2  = 1;                        // Enable Timer2 interrupts
149:   TMR2CN_TR2 = 1;               // Start Timer2

151:   SFRPAGE = SFRPAGE_save;
152:}

Timer 2
-> check the block diagram related to each register
-> understand datasheet register definition


166: INTERRUPT(TIMER2_ISR, TIMER2_IRQn)
when timer2 interrupt occurs(TIMER2_IRQn, 5 as constant) this TIMER2_ISR function(interrupt service routine) executed
167: {
168:    TMR2CN_TF2H = 0;               // Clear Timer2 interrupt flag
clear flag for next interrupt, because this function already executed.
169:    LED = !LED;                         // Change state of LED
LED represents LED pin
toggle means once on and once off when this interrupt service routine occurs
170: }

ref1: Link
Basically, it gives the designer the flexibility to chose which pins the desired peripheral is routed to. Let's say you have a UART devices that needs to connect to pins P1.0 and P1.1. The crossbar allows you to bring that signal out to that pin or a different supported pin in another design. Think of it as a multiplexer. Each physical pin is an output and all the peripherals are the inputs.

Hope that helps. Every micro controller has this sort of functionality, though usually a pin is limited to a few peripherals it can connect to. This is generally called "pin muxing".

2016년 3월 30일 수요일

(E)How to create hierarchy labels(tree structure) in blogger, blogspot

This is How to make sublabels in tree structure tutorial
Main Idea is from this blog(How to create Sublabels / Hierarchical Labels in Blogspot) and I modify to use my blog
I'm new to web programming(and Javascript), so I'm hardly understand these codes, so just enough to make dTree

Sequece

1. Add Gadgets
    * blog-layout click
        1) sidebar-right-1, add 'HTML/JavaScript' gadget
            - title: 'Labels'
            - content: "." temporary
        2) sidebar-right-1, add 'tag' gadget
            - title: 'tag'
        => 'tag' gadget must be before 'HTML/JavaScript' gadget
             so change order if it's not
2. Add Template HTML Code
    * blog-template-HTML edit click
        1) add below code right after <head>
        these codes must work before dTree code usage
          I change location from reference blog.
<link href='https://sites.google.com/site/efekefek/file-js/dtree.css' rel='StyleSheet' type='text/css'/>
<script src='https://sites.google.com/site/efekefek/file-js/createdtree.js' type='text/javascript'/>
        2) find below code    
<b:widget id='Label1' locked='false' title='Labels' type='Label'>
<b:includable id='main'>
 ... 
</b:includable>
</b:widget>
          -> and change  ... to below code
          these code get each label count to be used at dTree
<script type='text/javascript'>
  var labelCountMap = {};
  <b:loop values='data:labels' var='label'>
     labelCountMap ["<data:label.name/>"] = "<data:label.count/>";
   </b:loop>
</script>
            - blue 'Label1' can be changed by the Label gadget number

3. Add 'HTML/JavaScript' Gadget content
    - add below code to Gadget content and change blue code by your own labels
     '<!--' and  '//-->' are erased. at first time I thought it should be there, but doesn't work
<div class="dtree">
<p><a href="javascript: d.openAll();">open all</a> | <a href="javascript: d.closeAll();">close all</a></p>
<script type="text/javascript">
function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

function addMap(d, startingNode, parentNode, map) {
 for (var key in map) {
  if (isEmpty(map[key])) {
   d.add(startingNode++,parentNode,key+' ('+labelCountMap[key]+')','/search/label/'+key);
  } else {
   d.add(startingNode++,parentNode,key+' ('+labelCountMap[key]+')','/search/label/'+key);
   startingNode = addMap(d, startingNode, startingNode-1, map[key]);
  }
  
 }
 return startingNode; 
}

var data = {
    'label1' : {
        'label2' : {}
    }
};
d = new dTree('d');
d.config.useLines = true;
d.config.useIcons = false;
d.config.inOrder = true;

d.add(0,-1,'');   
addMap(d, 1, 0, data);

document.write(d);
</script>
</div>

4. Result












2016년 3월 20일 일요일

(E+K) Windows 폴더접근 단축키(Folder Short cuts)

'내 컴퓨터' 혹은 'c:' 에 빨리 접근하는 방법이 필요해서 찾아보았습니다.
I needed to open 'c:' faster, so I collected methods


정의(Definition)
    Win: window key(Windows), Command(Mac)
    Enter: press Enter
    "문자열(글자)": 글자 입력
 
내컴퓨터(My Computer)
    1. Win + e

특정 드라이브 (Specific Drive ex>c:, d:, e: ...)
    1. Win + r -> "c:" -> Enter

특정 폴더(Specific Drive)
    1. 특정 폴더의 경로를 복사(ex>"C:\Users\user\Downloads")
    2. 환경변수(내컴퓨터->오른쪽 마우스버튼-> 고급시스템설정 -> 환경변수 -> path 항목에 추가
    3. Win + r -> "downloads" -> Enter

그 외 방법(etc..)
    - 즐겨찾기에 추가
        
    - 바탕화면에 바로가기 생성 -> 바로가기 아이콘에 단축키 추가(ex> F10 key)
    - make shortcut at desktop -> make shortcut key in shortcut(ex>F10 key)

    - 'q-dir' 과 같은 폴더 관리 프로그램 사용
    - use 'q-dir' explorer management program
        -> 하나의 창에 4개의 폴더를 한번에 띄우고, 하나의 폴더에는 탭을 여러개 두어 자주 여는 폴더는 모두 열어 둘 수 있다.
        -> it can open 4 explorer on one window, even in one explorer you can make tabs

2016년 3월 9일 수요일

(E+K) Python for Social Scientists(사회과학자를 위한 파이썬)

파이썬에 대해서 잘 정리해 놓은 블로그가 있어서 읽고, 일부를 한글로 옮겨 보았습니다.
가면 갈수록 더 좋은 Quality 의 블로그 들이 나오는 것 같군요.

언젠가 직접.. 깔끔한 블로그를 구성해 보고 싶네요 ㅎㅎ

---

Python for Social Scientists



This is a guest blog post by Nick Eubank​, a Ph.D. Candidate in Political Economy at the Stanford Graduate School of Business
글은 Nick Eubank, 스탠포드 비즈니스 대학원에서 정치경제 박사과정, 글입니다.


 Python is an increasingly popular tool for data analysis in the social scientists. Empowered by a number of libraries that have reached maturity, R and Stata users are increasingly moving to Python in order to take advantage of the beauty, flexibility, and performance of Python without sacrificing the functionality these older programs have accumulated over the years.
파이썬은 사회과학자들의 데이터 분석툴로서 점점  인기가 높아지고 있습니다.. 성숙도가 높은 많은 라이브러리들로 인하여 더욱 강해지고 있고, R Stata 사용자들도 오래된 툴들의 장점들을 잃지 않으면서도파이썬의 아름다움유연함그리고 성능 으로 대변되는 장점들을 취하기 위해서 파이썬으로 옮겨오고 있습니다.
But while Python has much to offer, existing Python resources are not always well-suited to the needs of social scientists. With that in mind, I’ve recently created a new resource —www.pythonforsocialscientists.org (PSS) — tailored specifically to the goals and desires of the social scientist python user.
하지만 파이썬이 많은것을 제공하는 반면,  사회과학자들의 필요에 맞는 형태로는 있지 않습니다. 그런 생각을 바탕으로 최근에 저는 사회과학자들에 맞춘 새로운 싸이트를 만들었습니다.

The site is not a new set of tutorials, however — there are more than enough Python tutorials in the world. Rather, the aim of the site is to curate and annotate existing resources, and to provide users guidance on what topics to focus on and which to skip.
사이트는 새로운 형태의 tutorial 아닙니다, 파이썬 튜토리얼은 충분할 만큼 세상에 많이 있습니다. 대신에, 싸이트에서는 이미 있는 내용들을 모으고 자세한 설명을 해서 사용자들에게 어느 토픽에 집중을 해야 하고, 어떤 것에 하지 않을 것인지를 알리기 위함 입니다.

Why a Site for Social Scientists?
 Social scientists – and indeed, most data scientists – spend most of their time trying to wrestle individual, idiosyncratic datasets into the shape needed to run statistical analyses. This makes the way most social scientists use Python fundamentally different from how it is used by most software developers. Social scientists are primarily interested in writing relatively simple programs (scripts) that execute a series of commands (recoding variables, merging datasets, parsing text documents, etc.) to wrangle their data into a form they can analyze. And because they are usually writing their scripts for a specific, idiosyncratic application and set of data, they are generally not focused on writing code with lots of abstractions.
사회과학자들은 그리고 대부분의 데이터 과학자들 많은 시간을 개별적이고, 특이한 데이터 세트를 통계적 분석이 가능하도록 변환 하는데 쓰고 있습니다. 부분이 사회과학자들이 파이썬을 쓰는 방법이 개발자들이 쓰는 것과 다른 이유 입니다. 사회 과학자들은 비교적 간단한 프로그램 명령 (변수 저장, 텍스트 문서를 구문 분석, 데이터 세트 병합 ) 분석 있는 형태로 데이터를 다루는 일련의 명령 (스크립트) 작성에 주로 관심이 있습니다. 그들은 일반적으로 데이터의 특정, 특이한 프로그램과 데이터 세트에 대한 자신의 스크립트를 작성하기 때문에, 그들은 일반적으로 코드 작성시에 추상화에 초점을 맞추지 않습니다.

Social scientists, in other words, tend to be primarily interested in learning to use existing toolseffectively, not develop new ones.
 다른말로 하면, 사회과학자들은 현재 있는 들을 효율적으로 쓰는데 관심이 있다는 것입니다. 새로운 것을 만드는 것이 아니라.

 Because of this, social scientists learning Python tend to have different priorities in terms of skill development than software developers. Yet most tutorials online were written for developers or computer science students, so one of the aims of PSS is to provide social scientists with some guidance on the skills they should prioritize in their early training. In particular, PSS suggests:
 이런 이유 때문에파이썬을 배우는 사회과학자들은 스킬을 익힐  소프트웨어 개발자들과는 다른 종류의 우선순위가 생깁니다하지만 온라인의 많은 튜토리얼들은 개발자나 컴퓨터 과학과의 학생들을 위한 것이기 때문에, PSS 목표는 사회과학자들에게 파이썬 배울 때의 우선순위를 가이드 하려고 합니다구체적으로는 

Need immediately:
  • Data types: integers, floats, strings, booleans, lists, dictionaries, and sets (tuples are kinda optional)
  • Defining functions
  • Writing loops
  • Understanding mutable versus immutable data types
  • Methods for manipulating strings
  • Importing third party modules
  • Reading and interpreting errors
Things you’ll want to know at some point, but not necessary immediately:
  • Advanced debugging utilities (like pdb)
  • File input / output (most libraries you’ll use have tools to simplify this for you)
Don’t need:
  • Defining or writing classes
  • Understanding Exceptions

즉시 필요:
  • 데이터 타입: integer, float, string, boolean, list, dictionary, and set (tuple 옵션)
  • 함수 선언
  • 루프
  • Mutable immutable 데이터 타입(const 이야기 하는 같음)
  • 문자열을 다루는 방법들
  • third party 모듈을 사용하는
  • 에러를 해석하는
알면 좋음, 하지만 즉시는 아님:
  • 높은 수준의 디버깅 하는 (pdb 같은 )
  • 파일을 읽고 쓰는 (대부분 라이브러리들에서 쉽게 있게 놓았다.)
필요 없음:
  • 클래스 쓰는
  • 예외처리 하는 방법

Pandas
 Today, most empirical social science remains organized around tabular data, meaning data that is presented with a different variable in each column and a different observation in each row. As a result, many social scientists using Python are a little confused when they don’t find a tabular data structure covered in their intro to Python tutorial. To address this confusion, PSS does its best to introduce users to the pandas library as fast as possible, providing links to tutorials and a few tips on gotchas to watch out for.
 현재, 대부분의 실증적인 사회과학은 표의 형태(row column 각각 의미를 가지고 이들의 교차도 의미를 가지는) 사용되고 있습니다. As a result, many social scientists using Python are a little confused when they don’t find a tabular data structure covered in their intro to Python tutorial. 이런 혼란을 해결하기 위해서, PSS 최대한 빨리 pandas 라이브러리를 소개하려고 한다, 튜토리얼들과 들에 링크를 걸면서 ( 문단은 제대로 해석 안됨 )
 The pandas library replicates much of the functionality that social scientists are used to finding in Stata or R — data can be represented in a tabular format, column variables can be easily labeled, and columns of different types (like floats and strings) can be combined in the same dataset.
 Pandas 라이브러리는 사회과학자들이 주로 사용했었던 Stata R 에서 사용했었던 기능들을 그대로 사용할 있도록 만들어져 있습니다. – 데이터는 표이며, 컬럼은 쉽게 이름이 붙을 있고, 컬럼에 서로 다른 타입이 들어있을 있는 (가량 소수, 문자열)

pandas is also the gateway to many other tools social scientists are likely to use, like graphing libraries (seaborn and ggplot2) and the statsmodels econometrics library.
Pandas 사회과학자들이 많이 사용하는 다른 (그래프를 그리거나(seabornggplot2) 계량경제학과 관련된 사용하는) 사용하도록 하는 gateway 입니다.

Other Libraries by Research Area
 While all social scientists who wish to work with Python will need to understand the core language and most will want to be familiar with pandas, the Python eco-system is full of application-specific libraries that will only be of use to a subset of users. With that in mind, PSS provides an overview of libraries to help researchers working in different topic areas, along with links to materials on optimal use, and guidance on relevant considerations:
 사회과학자들이 파이썬에서 가장 기본적인 내용과 pandas 가지고 일하기를 원하기는 할테지만, 파이썬은 풍부한 기능을 가진 언어입니다. PSS에서는 분야의 연구자들이 사용할 있는 라이브러리 들도 공유 하려고 합니다..
Want to Get Involved?
 This site is young, so we are anxious for as much input as possible on content and design. If you have experience in this area you want to share please drop me an email or comment on Github.
 이 싸이트는 젊습니다. 그래서 내용과 전체 설계에 더욱 많은 input 필요합니다. 당신이 만약 분야에 경험이 있고 그것을 공유하고 싶다면 나에게 보내거나 Github 남겨 주기 바랍니다.



Reference
    원글: https://realpython.com/blog/python/python-for-social-scientists/
    Python for Social Scientists: http://www.pythonforsocialscientists.org/