Internet Of Things

Saturday, 14 June 2014

Accessing Raspberry Pi Directly through the Ethernet Port of PC

The Raspberry pi is a single board minicomputer which has only the essential hardware included so as to meet the goal of low cost. The board is Raspberry pi board runs on ARM11 processor but is available at extremely cheap price. The board is designed with an intention of providing computer education to the remote schools where the PCs are not very commonly used. The idea behind the design is to use the TV screen as the display unit for the Raspberry pi board and hence converting the normal TV into a computer. The board is hence provided with a RCA connector which can be used to connect it directly to a TV screen which is based on PAL and NTSC standard. The board also has a HDMI connector output which can be used to connect the board to a HD TV, but there is no VGA connector assuming that there is no PC or PC monitor in the place where the Raspberry pi is used.
There are situations in which the person using the Raspberry pi has a PC screen but not a HD display device. In such situations one can use remote login to access the Raspberry pi and view the TUI (Text User Interface) on the PC screen. Using a PC to do remote login has other advantages as there is no power adaptor required as  one can power up the Raspberry pi using the USB port of the PC itself and can use the keyboard of the PC to access the TUI. This article discusses how to do remote login in the case where windows is running on the PC and the Ubuntu is installed on Raspberry pi board.

Description:
The only additional hardware required to do the remote login is a “cross-over LAN cable” which comes with connectors at both the end and an internal crossover connection between connectors at both the end. 
 



The remote login can be easily done when there is a router available and the user can access the details of the devices connected to the router. All that required is to connect the one end of the LAN cable to the Ethernet port of the Raspberry pi and the other end to the connector slot of the router. Access the router and find out the IP of the connected devices. The Raspberry pi board will appear in the list with a name of “raspberrypi”. Note the IP and try to login using any remote login software for windows.
In most of the cases there won’t be any router available especially in outdoor conditions with a laptop. In such conditions one has to make a direct connection with the PC and the Raspberry pi. But inside the Ubuntu running in the Raspberry pi board the internet settings are not configured to enable a direct connection with the PC using LAN cable. One has to download server software which will provide an IP to the Raspberry pi board and help the PC to establish a connection with the raspberry pi board. The step-by-step connection process is explained in the following section.
Step: 1 Provide an IP to the windows
The software that can be used with windows7 is DHCP server software which can act as a server for the incoming connections. Before using this software there are few settings to be done in the windows to enable the connection. Go to the control panel > network and internet > network and sharing center > change adapter settings. Right click on the ‘Local Area connection’ and select ‘properties’.
Ethernet Access from Raspberry Pi
Select the Internet protocol version 4 (IPV4) and click on the ‘properties’ button.
LAN Connection Properties
Now provide an IP and subnet mask for the windows. The IP used in this project is “192.168.0.30” and the subnet mask as “255.255.255.0”.
TCP/IP v4
Now click OK and it is always better to reboot the system.
Step: 2 Connect the Raspberry pi
Once the booting process of the windows is completed, connect the Raspberry pi board to the Ethernet port of the PC. Connect a USB data cable to the Raspberry pi’s power port and the other end to the USB port of the PC. Wait for a while and an “Unidentified network” will appear in the “currently connected to” list usually present in the task bar.
Connect the Raspberry Pi
Step: 3 Run the DHCP server software
Unzip the downloaded zip file of the DHCP server software into a folder. Find the executable file “dhcpwiz.exe” inside the folder and run it. Select the network adaptor as the ‘Local Area Connection’ as shown in the following snapshot.
Network Interface
Now click on the ‘Next’ button for this window and for every window that opens up, make sure that the default values are not changed. When the window with a title “writing the INI file” opens up, tick on the “Overwrite existing file” and click the button “Write INI file”.
Writing INI File
Click on the ‘Next’ button again. In the following window that opens up, tick on the “Run DHCP server immediately”.
DHCP Configuration
Click the ‘Finish’ button now and the following window appears.
DHCP Server
Click on the “Continue as tray app.” Button now and click “Yes” on the confirmation window which follows it. Now the DHCP server is running in the windows system and the icon can be found in the task bar normally.
Step: 4 Reconnect the Raspberry pi board
Once the above steps are completed, power off the Raspberry pi board by removing the USB data cable from the PC. Now power on the board again and after the booting process of the Raspberry pi seems to be completed a notification appears from the DHCP server software as shown in the following snap shot.
Assigning IP to Raspberry Pi
Note the IP address as it is required to login to the Raspberry pi board using the software which helps in remote login.
Step: 5 Remote login using PUTTY
PuTTY is an SSH and telnet client software which is commonly used with the Windows platform. Download the latest version of the PuTTY and open the .exe file.
PuTTY Configuration
As shown in the above snapshot, enter the previously noted IP and keep the default port number. Select SSH mode by clicking on the radio button “SSH”. Now click on the button “Open” and click “Yes” to the confirmation window follows and the PuTTY will display the TUI of the Raspberry pi board.
Logging into PuTTY
Type the default login and password and start exploring the Raspberry pi.
The default login and password are:
login as : pi
password : raspberry


Digital Clock using Inbuilt RTC of LPC2148 (ARM7)

Real Time Clock (RTC) is used to store Time and Date in the system even when the system is not in operation. This is the system used in many devices including Laptop. Mobile phones, Tablet, Digital Cameras etc. RTC is inbuilt part of any electronics device. DS1307 is widely used RTC which we can interface with any controller. Many controllers now has inbuilt RTC to store timing information. In this article, we will learn how to configure inbuilt RTC of controller LPC 2148.

digital clock



Description:
Real Time Clock (RTC) is used to store Time and Date in the system even when the system is not in operation. This is the system used in many devices including Laptop. Mobile phones, Tablet, Digital Cameras etc. RTC is inbuilt part of any electronics device. DS1307 is widely used RTC which we can interface with any controller. Many controllers now has inbuilt RTC to store timing information. In this article, we will learn how to configure inbuilt RTC of controller LPC 2148.
LPC 2148 has inbuilt RTC which can be configured as needed. For this we have to configure the various registers of LPC 2148 architecture. Features of inbuilt RTC of LPC 2148 are as follows.
·         Measures the time to maintain a calendar and clock.
·         Ultra Low Power design to support battery powered systems.
·         Provides Seconds, Minutes, Hours, Day of Month, Month, Year, Day of Week, and Day of Year.
·         Dedicated 32 kHz oscillator or programmable pre-scalar from VPB clock.
·         Dedicated power supply pin can be connected to a battery or to the main 3.3 V.
RTC has 3 dedicated pins.
Pins of LPC 2148 for RTC Pins of LPC 2148 for RTC
Registers for RTC can be divided into four categories mentioned below.
a.   Miscellaneous Register Group
b.   Time Counter Group
c.   Alarm Register Group
d.   Reference Clock Divider
1.   Miscellaneous Type of registers:
This group of register contains few miscellaneous registers which are used for functions like ILR, CTCR, CCR, CIIR, AMR, CTIME, CTIME0, CTIME1 and CTIME2. Functions of each registers are as follows.
ILR – Interrupt location register
The Interrupt Location Register is a 2-bit register. Whenever interrupt occurs from RTC, this register specifies which blocks are generating an interrupt.
CTCR – Clock Tick Counter register (CCR)
The Clock Tick Counter is read only. It can be reset to zero through the Clock Control Register (CCR). The CTC consists of the bits of the clock divider counter
CCR – Clock Control Register
The clock register is a 5-bit register. It is used to control the operation of the clock divide circuit
CIIR – Counter increment interrupt register.
The Counter Increment Interrupt Register (CIIR) gives the ability to generate an interrupt every time a counter is incremented.
AMR – Alarm Mask Register
The Alarm Mask Register (AMR) allows the user to mask any of the alarm registers.
The interrupt will be generated only if the counter comparison first changes from no match to match.
CTIME – Consolidated time register
The values of the Time Counters can optionally be read in a consolidated format which allows the programmer to read all time counters with only three read operations.
CTIME0 – Consolidated time register 0
The Consolidated Time Register 0 contains the low order time values: Seconds, Minutes, Hours, and Day of Week.
CTIME1 – Consolidate Time Register 1
The Consolidate Time register 1 contains the Day of Month, Month, and Year values.
CTIME2 – Consolidate Time Register 2
The Consolidate Time register 2 contains just the Day of Year value.
2.   Time Group Register:
The time group of registers contains the following registers.
TIMER REGISTER TIMER REGISTERS
3.   Alarm Group of Registers:
The alarm group of register contains the following registers:
ALARM GROUP REGISTERS ALARM GROUP REGISTERS
4.   Reference clock divisor register:
The reference clock divider (referred to as the prescaler) allows generation of a 32.768 kHz reference clock from any peripheral clock frequency greater than or equal to 65.536 kHz (2 × 32.768 kHz). This permits the RTC to always run at the proper rate regardless of the peripheral clock rate.
Basically, the Prescaler divides the peripheral clock (PCLK) by a value which contains both an integer portion and a fractional portion. The result is not a continuous output at a constant frequency, some clock periods will be one PCLK longer than others. However, the overall result can always be 32,768 counts per second.
The reference clock divider consists of a 13-bit integer counter and a 15-bit fractional counter.
The reference clock divisor register contains the following registers.
PREINT: Prescalar Integer Register.
PREINT = int (PCLK / 32768) ? 1.
PREFRAC: Prescalar fractional register:
PREFRAC = PCLK ? ((PREINT + 1) × 32768).
4.   Operation:
The basic operation of the On-chip RTC can be divided into three steps as shown below:
a.   RTC Configuration:
Registers responsible for RTC configuration:
RTC Configurations RTC Configurations
Clock Source Configuration:
The foremost thing to be done in order to configure the RTC is to select the clock source for the RTC.
The RTC is supported with two types of clock sources. They are the external oscillator and an internal pre-scalar clock respectively.
The RTC clock can be selected by updating the CLKSRC bit in the CCR register. If the internal prescalar is selected, then the PREINT and PREFRAC register values must be calculated and must be updated. The PREINT and PREFRAC values can be calculated as below:
PREINT = int (PCLK / 32768) ? 1.
PREFRAC = PCLK ? ((PREINT + 1) × 32768).
Once the clock source is selected, the RTC must be reset by setting the CLCRST bit in the CCR register.
Time Configuration:
The time of the RTC clock has to be configured once the RTC clock source is configured.
The RTC time can be configured by updating the Time counter registers with the appropriate register values.
The RTC also features an alarm facility. The alarm registers may also be updated if we want to set the alarm, at this point.
b.   Enable RTC:
The RTC can be enabled by setting the CLKEN bit in the CCR register.
c.   Reading RTC:
The RTC time registers are updated along with the pulse provided by the RTC Source clock.
These registers may be read at regular intervals in order to update the system with the current time and execute any process accordingly.

Circuit Diagram: 



CODE:

//Program to Configure RTC




 #include<lpc21xx.h>

 #include"lcd4bit.h"


unsigned char flag=0;


void rtc_int(void)__irq{

ILR = 0X01;

flag = 1;

VICVectAddr = 0X00000000;

}



void init_rtc(){

ILR = 0X01;

CCR  = 0X13;

CCR =  0X11;

CIIR = 0X01;

SEC = 0X00;

HOUR =0X00;

MIN = 0X00;

VICIntEnable = 0x00002000;

VICVectCntl0 = 0x0000002D;

VICVectAddr0 = (unsigned)rtc_int;

}



int main(void){

init_lcd(); 

init_rtc();

while(1){

if(flag){

lcd_command(0x80);

flag=0;

lcd_data(HOUR/10 + '0');

lcd_data(HOUR%10 + '0'); 

lcd_data(':') ;

lcd_data(MIN/10 + '0');

lcd_data(MIN%10 + '0');

lcd_data(':') ;

lcd_data(SEC/10 + '0');

lcd_data(SEC%10 + '0');

}

  }

}

CAN (Controller Area Network Protocol)

Controller Area Network or CAN protocol is a method of communication between various electronic devices like engine management systems, active suspension, ABS, gear control, lighting control, air conditioning, airbags, central locking etc embedded in an automobile. An idea initiated by Robert Bosch GmbH in 1983 to improve the quality of automobiles thereby making them more reliable, safe and fuel efficient. With the developments taking place in the electronics and semiconductor industry the mechanical systems in an automobile were being replaced by more robust electronics system which had an improved performance. New technologies, products and inventions with added or improved functions started to shape a complete new era for the automobile industry which promised more robust vehicles with use of electronics. The increasing number of electronic devices used communication signals with more complex interrelations between them. Thereby making the life difficult for automobile engineers when they designed systems wherein one electronic device needs to communicate with others to operate. Realizing the problem of communication between different electronic modules Robert Bosch came up with this new protocol called CAN which was first released in 1986. CAN provide a mechanism which is incorporated in the hardware and the software by which different electronic modules can communicate with each other using a common cable.  

Need for CAN
A vehicle contains a network of electronic devices to share information/data with each other. For example A spark ignition engine requires a spark to initiate the combustion chamber at the correct time so it communicates with engine control unit that adjusts the exact timing for ignition  to provide better power and fuel efficiency.. Another example is of a transmission control unit that changes the ratio of gear automatically with the changing speed. It uses information from engine control unit and various sensors in the system. Every electronic device has an ECU/MCU (electronic/microcontroller control unit) with its own set of rules to share/transfer information. For two or more devices to interact they should have the necessary hardware and software which allows them to communicate with each other. Before CAN was introduced in the automobiles, each electronic device was connected to other device using the wires (point to point wiring) which worked fine, when the functions in the system were limited.  The figure below is the pictorial view of the point to point wiring connection.
System without CAN
One of the major problems for automotive engineers was linking the ECUs of the different devices so that real time information can be exchanged. CAN protocol was designed to address this problem. It laid down the rules through which the various electronic devices can exchange information with each other over a common serial bus. This in turn reduced the wiring connections to a great extend thereby reducing the bulkiness and complexity of the system.  The image below shows how the different devices are connected using the CAN protocol.
CAN System in a Car

Also the standard technology of time, asynchronous transmitter/receiver did not support multi domain communications. Domain is a group of electronic devices that have almost similar requirements to work in the system. For example CD/DVD PLAYER, GPS system, monitors and displays etc. form a single domain. Similarly air conditioning and climate control, dashboards, wipers, lights doors etc. form another domain. Hence the electronic devices implanted in a vehicle can be classified under different domain. CAN facilitates multi-domain communication for the engineers.
The table below shows the different domains









CAN_Domains
What is CAN protocol and how is it implemented?
CAN protocol can be defined as the set of rules for transmitting and receiving messages in a network of electronic devices. It means that it defines how data is transferred from one device to another in a network. It was designed specifically looking into the needs of the automobile industry. However CAN's robust architecture and advantages has forced many industries like Railway, Aircrafts, medical etc to adopt CAN protocol in their systems.
CAN Nodes
Every electronic device (also known as the node) which needs to communicate using the CAN protocol is connected with each other via a common serial bus to transmit and receive messages.
For data exchange to happen among the nodes they must have the necessary hardware and the software embedded inside them.
CAN_Nodes
As shown in the above figure a typical CAN network consists of various nodes. Every node has a Host controller (ECU/MCU) which is responsible for the functioning of the respective node. In addition to the host controller every node has a CAN controller and CAN transceiver. CAN controller convert the messages of the nodes in accordance with the CAN protocols to be transmitted via CAN transceiver over the serial bus and vice versa. CAN controller is a chip which can either be added separately or embedded inside the host controller of the node.

CAN does not follow the master-slave architecture which means every nodes has the access to read and write data on the CAN bus. When the node is ready to send data, it checks availability of the bus and writes a CAN frame onto the network. A frame is defined structure, carrying meaningful sequence of bit or bytes of data within the network. CAN transmitted frame does have address neither of transmitting node or the receiving node. CAN is a message based protocol. A message can be defined as a packet of data which carries information. A CAN message is made up of 10 bytes of data. The data is organized in a specific structure called frame and the information carried in every byte is defined in the CAN protocol. Protocols are generally of two types: address based and message based. In an address based protocol the data packets contain the address of the destination device for which the message is intended. In a message based protocol every message is identified by a predefined unique ID rather than the destination addresses. All nodes on CAN receive the CAN frame and depending on ID on the node CAN decides whether to accept it or not. If multiple nodes send the message at the same time than the node with highest priority (lowest arbitration ID) gets the bus access. Lower priority nodes wait till the bus is available.

BENEFITS
·         Low cost:  As CAN serial bus uses two wires, it offers good price/performance ratio. Also, driven by high volume production of low cost protocol devices, they are relatively cheap.
·         Reliable: Because of excellent error detection and error handling mechanisms used by CAN, it offers high reliability transmission. It is also highly immune to Electromagnetic Interference
·       Flexibility:  CAN Nodes can be easily connected / disconnected. Also, the number of nodes is not limited by the protocol
·         Good Speed: CAN supports data rate of 1 MBit/s @ 40m bus length.
·         Multi-master communication: Any node can access the bus
·        Fault Confinement: Faulty nodes do not disturb the communication.
·         Broadcast capability: Messages can be sent to one /many/all nodes.
·         Standardized: ISO has standardized CAN via ISO-DIS 11898 high speed applications) and ISO-DIS 11519-2 (low speed applications). CAN protocol is also standardized by industry organizations such as SAE-Society of Automotive Engineers.


CAN Architecture
CAN uses the existing OSI reference model to transfer data among nodes connected in a network. The OSI reference model defines a set of seven layers through which the data passes during communication between devices connected in a network. The 7-layered structure of the OSI model is a very robust approach widely adopted in many communication protocols. The figure below gives the clear picture of OSI model.
OSI Layers in CAN


Each layer has its specific function that supports the layer above and below as described under-
·         Application layer
It serves as a window for users and application processes to access network services. The common functions of the layers are resource sharing, remote file access, network management, electronic messages and so on. 
·        Presentation layer
The most important function of this layer is defining data formats such as ASCII text, EBCDIC text BINARY, BCD and JPEG. It acts as a translator for data into a format used by the application layer at the receiving end of the station.
·         Session layer
It allows to establishing, communicating and terminating sessions between processes running on two different devices performing security, name recognition and logging. 
·         Transport layer
The transport layer ensures that messages are delivered error-free, in sequence, and without loss or duplication. It relieves the higher layer from any concern with the transfer of data between them and their peers.
·        Network layer
It provides end to end logical addressing system so that a packet of data can be routed across several layers and establishes, connects and terminates network connections.
·         Data link layer
It packages raw data into frames transferred from physical layer. This layer is responsible for transferring frames from one device to another without errors. After sending the frame it waits for the acknowledgement from receiving device. Data link layer has two sub layers:
{C1.       MAC (Medium Access Control) layer:  It performs frame coding, error detection, signaling, serialization and de-serialization.  
 LLC (Logical Link Control) layer: The LLC sub layer provides multiplexing mechanisms that make it possible for several network protocols (IPDecnet and Appletalk) to coexist within a multipoint network and to be transported over the same network medium. It performs the function of multiplexing protocols transmitted by MAC layer while transmitting and decoding when receiving and providing node-to-node flow and error control.
·       Physical layer
The physical layer transmits bit from one device to another and regulates the transmission of bit streams. It defines the specific voltage and the type of cable to be used for transmission protocols. It provides the hardware means of sending and receiving data on a carrier defining cables, cards and physical aspects.
CAN protocol uses lower two layers of OSI i.e. physical layer and data link layer. The remaining five layers that are communication layers are left out by BOSCH CAN specification for system designers to optimize and adapt according to their needs.
CAN_OSI
Function of each part is shown with the figure below.

Control Area Network
The concept of the CAN protocol can be understood using the figure above. Every node has a Host controller also known as micro-controller which is a small and low-cost computer .Host controller implements application layer of OSI model. Micro-controller gathers information from other electronic control units like braking, steering, power windows etc. to communicate with other nodes and transfers it to CAN controller.  CAN controller incorporate logical link control and MAC medium access control of data link layer. LLC allows filtering of messages by using unique ID on each message then MAC sub layer frames the message.  Once, framing is done it is followed by arbitration, error detection and acknowledgement that all comes under MAC sub layer of data link. The frame is transferred to CAN trans-receiver, for encoding and decoding. Finally CAN trans-receiver synchronizes with the CAN bus to send the message to anther node.

Terms associated with CAN protocol.
BUS VALUES
Binary values in CAN protocol are termed as dominant and recessive bits.

·          CAN define the logic “0” as dominant bit.
·         CAN define the logic “1” as recessive bit.
In the CAN system dominant bit always overwrites the recessive bit.
Message based communication
A Message is packet of data that carries the information to be exchanged between the nodes. Each message in CAN has a unique identification number. The identification number is specified according to the content of the message and stored in message identifier. This identification number is also unique within the network so when the transmitting node places the data on the network for access to all nodes it checks unique ID number to allow the message to pass through the filter and rest are ignored. This is done to save the time spent on sorting. With message based protocol other nodes can be added without re-programming since the units connected to the bus have no identifying information like node addressing. So there is no change needed in the software and hardware of any of the units connected on the bus.




CAN_Bus
Message framing
Messages in CAN are sent in a format called frames. A frame is defined structure, carrying meaningful sequence of bit or bytes of data within the network. Framing of message is done by MAC sub layer of Data Link Layer .There are two type of frames standard or extended .These frames can be differentiated on the basis of identifier fields. A  CAN frame with 11 bit identifier fields called Standard CAN and with 29 bit identifier field is called extended frame.
Standard frame
CAN_Standard Frame
Various fields in standard CAN are as follows-
{C·         SOF - Start of Frame bit. It indicates  start of message and used to synchronize the nodes on a bus. A dominant bit in the field marks the start of frame.
·         IDENTIFIER - It serves dual purpose one, to determine which node has access to the bus and second to identify the type of message.
·       RTR - Remote Transmission Request. It identifies whether it’s a data frame or a remote frame .RTR is dominant when it is a data frame and recessive when it is a remote frame.
{C}{·         IDE – Identifier Extension. It is used to specify the frame format. Dominant bit is for standard frame and recessive for extended frame.
{C}·        R0 - Reversed bit.  Not used currently and kept for future use.
{C·        DLC – Data Length Code. It is 4 bit data length code that contains the number of bytes being transmitted.
{·          DATA– Used to store up to 64 data bits of application data to be transmitted.
{C}·        CRC– Cyclic Redundancy Check. The 16-bit (15 bits plus delimiter) cyclic redundancy check (CRC) contains the checksum of the preceding application data for error detection.
{·         ACK – Acknowledge (ACK) field. It compromises of the ACK slot and the ACK delimiter. When the data is received correctly the recessive bit in ACK slot is overwritten as dominant bit by the receiver.
{C}·         EOF– End of Frame (EOF). The  7-bit field marks the end of a CAN frame (message) and disables
Bit - stuffing, indicating a stuffing error when dominant.
{C}·         IFS - Inter Frame Space that specifies minimum number of bits separating consecutive messages. It provides the intermission between two frames and consists of three recessive bits known as intermission bits. This time allows nodes for internal processing before the start of next frame.
EXTENDED CAN
Extended CAN
It is same as 11-bit identifier with some added fields
{C·        SRR- Substitute Reverse Request. The SRR bit is always transmitted as a recessive bit to ensure that, in the case of arbitration between a Standard Data Frame and an Extended Data Frame, the Standard Data Frame will always have priority if both messages have the same base (11 bit) identifier. 
{·         R1- It is another bit not used currently and kept for future use.
Message frame
There are four different frames which can be used on the bus.
Data frames- These are most commonly used frame and used when a node transmits information to any or all other nodes in the system.  Data Frames consist of fields that provide additional information about the message as defined by the CAN specification. Embedded in the Data Frames are Arbitration Fields, Control Fields, Data Fields, CRC Fields, a 2-bit Acknowledge Field and an End of Frame.

CAN Data Frame
·        Remote frames - The purpose of the remote frame is to seek permission for the transmission of data from another node. This is similar to data frame without data field and RTR bit is recessive.  For example, the microprocessor controlling the central locking on your car may need to know the state of the transmission gear selector from the power train controller.
·         Error frames – If transmitting or receiving node detects an error, it will immediately abort transmission and send error frame consisting of an error flag made up of six dominant bits and error flag delimiter made up of eight recessive bits.  The CAN controller ensures that a node cannot tie up a bus by repeatedly transmitting error frame.
Error Frame_CAN
·         Overload frame-It is similar to error frame but used for providing extra delay between the messages.  An Overload frame is generated by a node when it becomes too busy and is not ready to receive.
Overload Frame_CAN
Arbitration
It is a mechanism which resolves the conflict when two or more nodes try to send the message at the same time. In this technique whenever the bus is free any unit can transmit a message. If two or more units starts transmitting at the same time access to the bus is conflicted, but this problem can be solved by arbitration using identifier. During arbitration every transmitter compares the value of transmitted bit with bit value on the bus. If the bit value is same, the node continues to send the bits. But at any time if transmitted bit value is different from bus value the dominant bit overwrites the recessive bits. The arbitration field of the CAN message consists of an 11- or 29-bit identi?er and a remote transmission (RTR) bit. The identifier having lowest numerical value has the highest priority. RTR simply distinguishes between remote frame for which RTR is recessive and data frame for which RTR is dominant. If both data frame and remote frame with the same identifier is initiated at the same time data frame will prevail over remote frame. With the concept of arbitration neither information nor time is lost.

CAN as a CSMA protocol
CSMA is a carrier sense, multiple-access protocol in which node verifies the absence of traffic before transmitting on a shared medium such as electrical bus.  In CSMA each node on a bus waits for a specific time before sending the message. Once this wait period is over every node has equal opportunity to send the message. Based on pre-programmed priority of each message in identifier field i.e. highest priority identifier wins the bus access. It is implemented on the physical layer of OSI model. Let us understand CSMA with an example. In a discussion every person gets an equal opportunity to voice their thoughts however when a person is talking others keep quiet and listens and waits for their chance to speak (carrier sense). But if two or more people start speaking at the same time then they detect the fact and quit speaking (collision detection).


Error Checking and Fault Confinement
This is one of the attributes of CAN that makes it robust. CAN protocol has five methods of error checking, out of which three are at message level while other two are at bit level. Every frame is simultaneously accepted or rejected by every node in the network. If a node detects an error it transmits an error flag to every node and destroys the transmitted frame and the transmitting node resends the frame
Message level
CRC check
In this stage a 15-bit cyclic redundancy check value is calculated by transmitting node and is transmitted in the CRC field. This value is received by all nodes. Then all the nodes calculate CRC value and matches the results with the transmitted value. If values differ than an Error Frame is generated. Since one of the nodes did not receive the message properly it is resent.
ACK slots
When transmitting node sends a message, a recessive bit is sent in acknowledgement slot. After message is received acknowledge slot is replaced by dominant bit which would acknowledge that at least one node correctly received the message. If this bit is recessive, then none of the node has received the message properly.
Form Error
End of frame, Inter-frame space, Acknowledge Delimiter are fields that are always recessive, if any node detects dominant bit in one of these fields than CAN protocol calls it a violation and a Form Frame is generated and original message is resent after certain period.
Bit level
Stuff error
Bit stuffing - It is a very common technique used in telecommunication and data transmission to insert non -informative bits to have same  bit rates or to fill the frames .These extra bits are removed by data link layer to retrieve the original message. This same technique is used in bit error.CAN bus is never idle because it uses NRZ method. After five consecutive bits of the same value, a bit with a complement or opposite value is stuffed into the bit stream. If six bits of the same value are detected between SOF and CRC delimiter, error frame is generated. Upon detection of errors, the transmission is aborted and frame is repeated.  If errors continue, then the station or node may switch itself off to prevent the bus from being tied up.
Bit error
A node that is sending the bit always monitors the bus. If the bit sent by transmitter differs from the bit value on the bus then error frame is generated. But there is an exception in case of arbitration field or Acknowledge slot where a recessive bit is sent and a dominant bit is received. Then no Bit Error is occurs when dominant bit is monitored.

Conclusion
CAN protocol initially developed for in-vehicle networking of automobiles has expanded its applications in various other industries. The application started for luxurious cars is now being used in heavy duty vehicles like trucks, buses, trains and rail vehicles. The unique feature of CAN that allows various electronic units to communicate with each other made it important in healthcare domain. For example intensive care units and operating rooms where time and communication is of utmost importance. Entertainment industry also used CAN protocols to improve features in studios to control lights and door system and to control stage of theatres, event halls etc. Gambling machines and toys are other examples in entertainment field. In the field of science the high energy experiments and astronomical telescope use CAN in embedded network.

Sunday, 8 June 2014

Using the Raspberry Pi for web based Home Automation.....

In this tutorial I will show you how to use Raspberry Pi for home automation, as well as how to access your home automation systems from anywhere. : you are going to learn how you can control a relay that is attached to your Raspberry Pi, from any device like your computer or smartphone, and from anywhere in the world.
In this project, we will connect the relay to a simple LED, but of course this LED could be replaced by anything like a lamp, some lights on the ceiling, or the motor of your electric curtains. And to control this relay from anywhere, we are going to run a web server based on Node.js to control the relay from a web browser. Sounds exciting ? Let’s dive in !

Hardware requirements

For this tutorial, of course you will need a Raspberry Pi board. The version of the board or the model (A or B) doesn’t really matter, but keep in mind that you will have to connect it to your local network, so you will need a WiFi dongle if you are using the A model which doesn’t have an Ethernet port. In this tutorial, I used a Raspberry Pi model B with the WiPi dongle.
For the components, you will need a small 5V relay, a P2N2222A transistor (but any similar NPN transistor will do the job), a 1N4001 diode, a 1K ohm resistor, a 220 ohm resistorone LED, and of course a breadboard and some jumper wires. To connect the Raspberry Pi to the breadboard, I also used the Adafruit cobbler kit, but any cobbler kit for the Raspberry Pi will work fine.

Software requirements

You will need a fully usable Raspberry Pi. And by usable I mean already configured with the Raspbian Linux distribution installed on it. There are many tutorials on the web that will guide you through the installation of Raspbian on your Pi, but I recommend this one:
http://elinux.org/RPi_Easy_SD_Card_Setup
You also have to check that your Raspberry Pi is connected to the Internet. Again, this will depend on your configuration (Ethernet or WiFi) and your router, but is usually really easy. If you are using the Ethernet connection, simply connect a cable to your router and it should work automatically. If you’re using a WiFi dongle, the easiest solution is to use the GUI that comes with Raspbian to find your wireless network and enter your WEP/WPA password.
The server part is based on Node.js, so you will need to install it on your Pi with:
sudo apt-get install nodejs npm
Then, you will need to install the gpio-admin package. To do so, follow these steps in a terminal (if pi is your default username):
git clone git://github.com/quick2wire/quick2wire-gpio-admin.git
cd quick2wire-gpio-admin
make
sudo make install
sudo adduser pi gpio
After that, you’ll need to log out and in again.
Now, you need to download the GitHub repository of the project somewhere on your Pi:
git clone https://github.com/openhomeautomation/pi-node-relay
Finally, you need to go into the folder you just downloaded, and install the node.js module to interface directly with the GPIO pins of the Pi:
npm install pi-gpio
If it doesn’t work, just restart the Pi and try again the same operation. You are now ready to go to build the hardware!

Hardware configuration

There is quite a lot of hardware to connect for this project, so pay attention to this paragraph. First, let’s speak about the relay itself. A relay is an electromagnetic switch. The one I used in this project basically has 2 parts. The first part, the coil, is the low-power part of the circuit, and will be controlled by the Raspberry Pi. The second part of the relay is the switch, which can sustain higher powers. This part is actually mechanical on the relay I used, so you should hear a “click” when the relay is switching to another state. Activating the low-power part by applying 5V on the coil will activate the switch and change the state of the relay. To monitor in which state the relay is, I used one LED on one part of the switch. Of course, the LED can be replaced by any device you want to switch on or off, for example a lamp.
But … there is still a problem. The relay is rated at 5V to switch, and the Raspberry Pi GPIO port can only deliver 3.3V. This is why we need a transistor in between to activate the relay. The transistor is basically a solid-state switch, which will be activated via the digital output of the Raspberry Pi board. When the transistor is on, the 5V pin of the Raspberry Pi board will directly power the relay, thus making the relay switch.
We still need to place one component I haven’t spoken about yet: the diode. The role of this diode will be to protect the low-power circuit when the relay is switching. In case any current is flowing through the input of the relay because of the switching of the high-power part, it will just flow through this diode instead of destroying the transistor or the output of the Raspberry Pi. Just place this diode in parallel of the input part of the relay, with the cathode connected to the positive 5V power supply.
This schematic describes the whole project:
Relay_schem_small

Connecting the relay to the network

Now it’s time to connect our project to the local network of your home. Again, make sure that the Raspberry Pi is connected to the local network, for example by pinging your own computer in a terminal. Also, check the IP of your Raspberry Pi, you will need it for later. You can do this by typing ifconfig in a terminal. This is the result for my Pi:
Screen Shot 2013-05-28 at 9.18.49 AM
You will use this address (192.168.0.47) to access the web page later on from your computer. What we have to do now is to build the Node.js script that will create our server on the Raspberry Pi. And from this server, we’ll be able to control the relay from your web browser.
All the files are included into a script file called server.js. Let’s see the details of this file. It starts by including all the required libraries, to start the web server and to control the GPIO pins:
Then, we create a function to handle the incoming requests. This function will be called every time you access the project from your browser:
Inside this function, we get the data that is passed in the URL inside the state variable:
Then, we apply the command on the GPIO pin accordingly. For example, if the received state is “on”, we apply it to the GPIO pin where the relay is connected:
Finally, we send an answer to the browser, and close the connection:
And we end the script by actually starting the server:
It’s now time to test the project. To do so, simply go over to the folder where you downloaded the files from the Github repository for this project, and type in a terminal:
nodejs server.js
You should see the following message in your terminal:
Server has started.
You can now go to the web browser of your Pi, and type:
localhost/command?state=on
And the relay should turn on instantly. You can also check that the command was received inside the terminal. You can also do the same from your computer using the address of the Pi. For example, in my case:
192.168.0.47/command?state=off
This should turn the relay off again. Congratulations, you can now command your relay directly from your web browser!

Access the interface from anywhere

Now this is how to command a relay remotely, from your computer or your phone, from anywhere … in your home. Which is already nice, but I have been asked a lot about how to access this project from anywhere in the world. Wouldn’t it be cool to just access your home automation projects from wherever you are in the world, to check for example the status of your alarm system ? This is actually quite simple (depending on your router), and I will show you how.
Of course I can’t do a tutorial for every router in this world, but I will tell you how I did with mine (which is a router made by my Internet Service Provider). Generally you have to activate a mode named “remote access” on your router. Some routers will even give you an URL so you can access the router, but for mine I had to use the IP address. Be careful, I am not talking about the local IP address of your router (for example 192.168.0.254 for me), but the IP of the router on the web. It is generally easy to find in the interface of your router.
Then, you need to route the port corresponding to your Apache server on the Raspberry Pi (usually 80 if you didn’t change anything), so that every external access to this port goes directly to the Raspberry Pi. Usually, there is a “routing” menu in the interface of your router, where you can specify the external port (put 80), the internal port (80 as well) and the IP address (the one of the Raspberry Pi). Save the setting, and then it should just work out of the box if you type in the IP address of your router in any browser, wherever you are in the world !
One last word: be careful with this. Right now anyone can access this interface with the right IP address, and now it is just connected to a relay that is actually not connected to anything, but don’t do this if your whole alarm system is connected to the Raspberry Pi ! In this case, you better put a solid login/password system on your server so that only you can access it. I will show you how to do this in an upcoming article.
Update 06/05/14: Many of you had problems with the initial version of the project which was using a combination of HTML, Javascript and PHP. This was mainly due to file permissions inside the Apache web server on the Pi. That’s why I completely re-written the project using modern technologies like Node.js. Enjoy!
Finally, here is the list of the components that have been used in this tutorial:
- Raspberry Pi Model B
- Cobbler kit
- 5V relay
- 2N2222 transistor (or any equivalent NPN transistor)
1N4001 diode
- Red LED
- 1K ohm and 220 ohm resistors
- Breadboard and some jumper wires