Tuesday, February 14, 2017

[CAN] Controller Area Network (CAN) Overview

Source URL: http://www.ni.com/white-paper/2732/en/

1. CAN History
Bosch originally developed the Controller Area Network in 1985 for in-vehicle networks. In the past automotive manufacturers connected electronic devices in vehicles using point-to-point wiring system. Manufactures began using more and more electronics in vehicles, which resulted in bulky wire harnesses that were heavy and expensive. They, then, replaced dedicated wiring with in-vehicle networks, which reduced wiring cost, complexity, and weight.

2. CAN Benefits
Low-Cost, Lightweight Network
CAN provides an inexpensive, durable network that helps multiple CAN devices communicate with one another. An advantage to this is that electronic control units (ECUs) can have a single CAN interface rather than analog and digital inputs to every device in the system. This decreases overall cost and weight automobiles.

Broadcast Communication
Each of the devices on the network has a CAN controller chip and is therefore intelligent. All devices on the network see all transmitted messages. Each device can decide if a message is relevant or if it should e filtered This structure allows modifications to CAN networks with minimal impact. Additional non-transmitting nodes can be added without modification to the network.

Priority
Every message has a priority, so if two nodes try to send messages simultaneously, the one with the higher priority gets transmitted and the one with the lower priority gets postponed. This arbitration is non-destructive and results in non-interrupted transmission of the highest priority message. This also allows networks to meet deterministic timing constraints.

Error Capabilities
The CAN specification includes a Cyclic Redundancy Code (CRC) to perform error checking on each frame's contents. Frames with errors are disregarded by all nodes, and an error frame can be transmitted to signal the error to the network. Global and local errors are differentiated by the controller, and if too many errors are detected, individual nodes can stop transmitting errors or disconnect itself from the network completely.

3. CAN Terminology
CAN devices send data across the CAN network in packets called frames. A CAN frame consists of the following sections.


  • SOF (Start of Frame) indicates the beginning of a message with a dominant(logic 0) bit.
  • Arbitration ID identifies the message and indicates the message's priority. Frames come in two formats - standard, which uses an 11-bit arbitration ID, and extended, which uses a 29-bit arbitration ID. 
  • IDE (identifier extension) bit allows differentiation between standard and extended frames.
  • RTR (remote transmission request) bit serves to differentiate a remote frame from a data frame A dominant (logic 0) RTR bit indicates a data frame. A recessive (logic 1) RTR bit indicates a remote frame.
  • DLC (data length code) indicates the number of bytes the data field contains.
  • Data Field contains 0 to 8 bytes of data.
  • CRC (cyclic redundancy check) contains 15-bit cyclic redundancy check code and a recessive delimiter bit. The CRC field is used for error detection.
  • ACK (ACKnowledgement) slot - any CAN controller that correctly receives the message sends an ACK bit at the end of the message. The transmitting node checks for the presence of the ACK bit on the bus on the bus and reattempts transmission if no acknowledge is detected. 
  • CAN signal - an individual piece of data contained within the CAN frame data filed.
4. CAN Database files
CAN database files are text files that contain scaling information for CAN frames and signal definition. For each signal, CAN database define rules for conversion to engineering units. The following data is stored in databases.
  • Channel name
  • Location (start bit) and size(number of bit) of the channel within a given message
  • Byte order (Intel/Motorola)
  • Data type (signed, unsigned, and IEEE float)
  • Scaling and units string
  • Range
  • Default value
  • Comment

5. How CAN communication works
As stated earlier, CAN is a peer-to-peer network. This means that there is no master that controls when individual nodes have access to read and write data on the CAN bus. When a CAN node is ready to transmit data, it checks to see if the bus is busy and then simply writes a CAN frame onto the network. The CAN frames that are transmitted do not contain addresses of either the transmitting node or any of the intended receiving node(s). Instead, an arbitration ID that is unique throughout the network labels the frame All nodes on the CAN network receive the CAN frame, and, depending on the arbitration ID of that transmitted ID of that transmitted frame, each CAN node on the network decides whether to accept the frame.

If multiple nodes try to transmit a message onto the CAN bus at the same time, the node with the highest priority (lowest arbitration ID) automatically gets bus access. Lower-priority nodes must wait until the bus becomes available before trying to transmit again. 










Monday, February 13, 2017

[CAN] Determine the min. and max. of CAN signals

1. 16 bit, unsigned, resolution 10(scaling factor), offset 100

16bit = 0 ~ 2^16-1
0 * resoultion 10 = 0
1 * resolution 10 = 10
2 * 10 = 20
:     :  =   :
65535 * 10 = 65535

Besides, because the offset is 100, the minimum value becomes 0 + offset(100) and the maximum value becomes 65535 + offset(100)=65635.

2. 16 bit, unsigned, resolution 0.031, offset -230

0 ~ 65535 ( 2^16-1)
0 * 0.031 = 0
1 * 0.031 = 0.031
:      :    =  :
200 * 0.031 = 6.2
:      :    =  :
65535 * 0.031 = 2031.585

Therefore, the minimum is 0 + (-230) = -230, and the maximum is 2031.585 + (-230) = 1801.585.

3. 8 bit, signed, resolution 0.123, offset -1300

1 bit of 8 bit represents a sign of a number.
Therefore, signed 8 bit returns from -(2^7-1) to 2^7-1.
Minimum : -127 * 0.123 + (-1300) = -1315.62
Maximum : 127 * 0.123 + (-1300) = -1284.38



Friday, February 10, 2017

[Matlab / Simulink] How to input a value to the constant block of Simulink using m script.

1. Syntax
 set_param( 'model name/subsystem name/block name' , 'Value' , 'number' )

2. Simulink Model
- Model name : Notebook
- Subsystem : Blog
- Constant block : speed

3. Command
set_param('Notebook/Blog/speed', 'Value', '3')

With the above command, a value of a specified constant block will be changed to 3.

4. Application
It might be useful when changing or entering hundreds of values of the constant blocks.

% model name
model = 'Notebook/';
% subsystem name
sub = 'Blog/'
% block names
block = { 'spd1'; 'spd2'; 'spd3'};
% values
val = [2; 3; 4];

% size of values
[n,~] = size(val);

% Execution 1
for N = 1:1:n
    path = sprintf('%s%s%s', model,sub,block{N,1});
    set_param(path,'Value', num2str(val(N,1)));
end

Instead of the Execution 1, the following code also is applicable.
%Execution 2
for N = 1:1:n
    path = sprintf('%s%s%s', model,sub,block{N,1});
 
   % Catch errors.
   try
      set_param(path,'Value', num2str(val(N,1)));
   catch
       % If there is an error while doing this command,
       % the path where an error has occured is displayed on the command window.
     disp(path);
   end
end








Saturday, February 4, 2017

[Matlab GUI] Introduction to MATLAB GUIDE

엔지니어로 일을 하다 보면 주어진 시간 내에 반복적인 시뮬레이션이나 수치해석 등을 장시간하고 결과로 생긴 수많은 데이타를 예쁘게 그래프로 그려서 누군가에게 보고해야하거나 발표해야하는 경우가 종종 있다.
필요한 경우 직접 간단한 코드를 작성해서 결과물을 만들어도 되지만, 여러 번 반복해서 작업을 해야하는 경우 매번 코드를 조금씩 수정하면서 일을 하면 시간도 오래 걸리고 실수가 발생할 수도 있다. 이럴 경우 간단하지만 수치 정도라도 간단하게 입력해서 결과물을 낼 수 있는 간단하고 가벼운 GUI를 만들어 놓으면 매우 쓸모있게 활용할 수 있다.
GUI을 개발할 수 있는 소프트웨어나 프로그래밍 언어들이 여러가지 있는데 전문 프로그래머가 아닌 일반 엔지니어들이나 공대생이 접근하기 가장 쉽고 하기 쉬운 소프트웨어 중 하나가 매트랩이다.

매트랩에서는 GUI를 만드는 방법이 두 가지 있다.
하나는 m script에서 처음부터 텍스트 코딩으로 모든 것을 하나 하나씩 만드는 방법이 있고, 다른 하나는 GUIDE라는 매트랩 앱을 이용해서 손쉽게 원하는 GUI를 만들 수 있다.
m script에서 텍스트 코딩으로 만들 수 있는 GUI는 GUIDE로도 대부분 크게 어렵지 않게 만들 수 있지만, GUI 디자인을 자유자재로 하고자 한다면 제한이 아직까지 많이 있다.
Matlab R2014.b 버전부터는 tab 생성 기능도 공식적으로 제공하고 있지만 여전히 부족한 부분이 많다. 답답함에 결국 자바 라이브러리까지 어느 정도 사용해야 하는 경우까지 발생한다.

 우선 간단하게 GUIDE를 실행하는 방법은 아래 그림과 같이 command windows에서 guide를 입력하면 된다.

실행하면 아래와 같은 화면이 나타나고
왼쪽 화면에 보이는 버튼 등을 오른쪽 작업창에 원하는 위치에 나열하면 간단히 GUI를 디자인할 수 있다. 


원하는 디자인을 만든 후 Ctrl + T 또는 화면상의 플레이 버튼을 누르면 m script파일과 함께 디자인한 GUI화면도 나타난다. 

여기까지 했으면 벌써 GUIDE는 반은 끝났음.