Weekend Hack using python and CANMate

My weekend hack using our company’s(http://www.dthoughts.com) product CANMate (a high performance low cost CAN Analyzer) along with Python programming language.I wrote a python program to use CANMate in GNU/Linux and Windows which is freely vailable.I used Pythons Matplotlib library to plot the real time CAN message from a vehicle’s OBD port.

Happy Hacking 🙂

Advertisements

Burning IMX28 Ltib image to SD card and booting

After successful creation of bootable image as per previous post we need to do some hack in order to get the OS booted from the IMX28EVK board.

Most probably inside ypur Ltib folder there will be a scrpt named mk_mx28_sd .This is the utility used to burn the image to sdcard it will reduce us the difficulty of partitioning etc.he BSP includes the mk_mx28_sd shell script that makes it very easy to place the build output onto an SD/MMC card. The script will write the
selected boot stream, the rootfs.

The mk_mx28_sd script should always be run from the LTIB install directory. It knows how to find the boot stream files and rootfs from this
directory.Before running the script, you need to determine the device for your SD/MMC card. Find the device id of your SD card.

ls /dev/sd?

Try issuing the above command without inserting the SD card and with inserting the SD card then you will get the device id.The SD/MMC card will be the new /dev/sdX device in the output. Where X value changes as a,b,c etc.Once you already know your card’s device, updating the card contents with a new build image

cd ~/ltib
mk_mx28_sd /dev/sdX

If you dont have mk_mx28_sd in your ltib folder then download L2.6.35_10.12.01_SDK_scripts.tar.gz from Freescale site and extract it.

cp mk_hdr.sh ~/ltib  
cp mk_mx28_sd ~/ltib  
cd ~/ltib

Here you need to do a small change in order to make the script work

Edit mk_mx28_sd script and add the ‘u’ at line 177 then the o command after. This changes cylinders to sectors.

OLD:
echo “o
n

NEW:
echo “u
o
n

Once updated to create the SD card which is at /dev/sdX:

./mk_mx28_sd /dev/sdX  

mk_mx

Next, set the boot mode on the i.MX28 EVK board for MMC/SD on SSP0. The boot mode DIP switch settings are shown in the table below.

Screenshot from 2014-07-11 18:54:56

Then, insert the SD/MMC card into the SSP0 card socket. This is the rightmost socket on the bottom of the EVK board.

Finally, connect power to the board and press the Power button. You will see serial output over the debug UART if you have a terminal program
running.

you will reach the login promt

boot_screen

Login using the username root

Happy Hacking 🙂

i.MX28 LTIB on UBUNTU 13.04

I tried Ltib installation in Ubuntu 13.04 for i.MX28 board which completed successfully

First install required packages

sudo apt-get update
sudo apt-get install build-essential zlib1g-dev rpm libncurses5-dev m4 bison liblzo2-dev uuid-dev tcl

Configure sudo

The LTIB installation script runs several commands with sudo where the user should not be prompted for a password. sudo without password must be configured for the current user to execute the script correctly.

sudo visudo

the file /etc/sudoers is opened for editing.

The following line should be inserted in the file, where user has to be changed to your user name:

# Allow user to run commands for ltib.
user ALL = NOPASSWD: /usr/bin/rpm, /opt/freescale/ltib/usr/bin/rpm

Save with Ctrl+o, then close with Ctrl+x.

Download BSP source for Ltib for iMX281

http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=i.MX281&nodeId=018rH3ZrDRA24A&fpsp=1&tab=Design_Tools_Tab#

Extract it

tar -xvf L2.6.35_1.1.0_130130_source.tar.gz

cd L2.6.35_1.1.0_130130_source

./install

The installer will ask you to read and accept a EULA and then ask you for the install directory. For this example, choose your home directory.
After the installation, there will be a new directory named “ltib” under the install directory you specified. This new directory contains the actual
ltib Perl script, config files, package specs, and utilities.

so now change directory to newly created ltib directory

cd ~/ltib

Now we must patch some files of the folder.Note that ,this must be done from ltib folder itself.

wget https://community.freescale.com/servlet/JiveServlet/downloadBody/93455-102-2-2825/patch-ltib-ubuntu12.04.sh

./patch-ltib-ubuntu12.04.sh

It will download ubuntu-ltib-patch.tgz

tar -xzvf ubuntu-ltib-patch.tgz

./install-patches.sh 

You can download the shell script and files from this link

https://github.com/ganeshredcobra/Ltib

Configure and Build

To configure and build your LTIB installation the first time, run this command from the ~/ltib directory:

./ltib

This command invokes LTIB with its default behavior of performing a build. Since the installation has not yet been configured, LTIB will present
the ncurses configuration screen before building. Then, when you exit the configuration screen, LTIB will build the target image.you can see installed host tools in /opt/freescale/ .

When you invoke ./ltib the screen will be like this and a log file will be created inside the ltib folder

01

If there is any dependency problem the the building process may stop like this
02
Here the issue is that zlib is missing then you must install zlib

Then you will get the first time configuration window
04
05
Because the i.MX BSP contains only the i.MX platform, you don’t need to change anything on this screen.
When is selected, you can hit the return key to exit the current screen. On most main screens, exiting will bring up the following dialog
asking if you want to save changes.Here, use the right and left arrow keys to select between and . Press return to activate your selection. Selecting will cause LTIB to not continue to the following step. We must save the configuration when asked. This will bring up another sub-platform screen

06

The first option available on this screen is used to choose the sub-platform type. For the i.MX platform, the sub-platform is the specific chip family combined with the board type. For the i.MX28, this is the EVK board. The second option on this screen, under the Choose the packages profile item, lets you select the default set of packages. Individual packages can be enabled and disabled later, as you need. The default choice is sufficient for now.
If you need to change the sub-platform later, use the command:

./ltib -m selectype

Move the cursor down to the Selection item below the Choose the platform type line and press return to open up a platform selection
menu,
07

Select the imx28 platform, which is near the top of the list, and press return to return to the main screen.Exit the sub-platform selection screen and save the configuration. This will bring you to the main LTIB configuration screen.

Here you can change the settings such as packages kernel version build parameters etc
08

09

10

After modifying the parameters you must exit from configuration menu saving the settings and run ltib again without any arguments

./ltib

Possibly you may get an error like this

Can’t get: gcc-4.6.2-glibc-2.13-linaro-multilib-2011.12-1.i386.rpm at ./ltib line 2560.

CONFIG_TOOLCHAIN forced a full rebuild
Installing: gcc-4.6.2-glibc-2.13-linaro-multilib-2011.12-1.i386.rpm
Testing network connectivity
OK GPP:
 
Try gcc-4.6.2-glibc-2.13-linaro-multilib-2011.12-1.i386.rpm.md5 from the GPP
http://bitshrine.org/gpp/gcc-4.6.2-glibc-2.13-linaro-multilib-2011.12-1.i386.rpm.md5:
21:59:11 ERROR 404: Not Found.
Try gcc-4.6.2-glibc-2.13-linaro-multilib-2011.12-1.i386.rpm from the GPP
http://bitshrine.org/gpp/gcc-4.6.2-glibc-2.13-linaro-multilib-2011.12-1.i386.rpm:
21:59:11 ERROR 404: Not Found.
Can't get: gcc-4.6.2-glibc-2.13-linaro-multilib-2011.12-1.i386.rpm at ./ltib line 2560.
Died at ./ltib line 2560.
traceback:
main::check_toolchain_setup:2560
  main::pre_build_checks:1465
   main:569
 
 
Started: Sun Mar  3 21:17:48 2013
Ended:   Sun Mar  3 21:59:11 2013
Elapsed: 2483 seconds
 
 
Build Failed
 
Exiting on error or interrupt

11

To fix this error chnage the toolchain configuration

./ltib -m config

in the Toolchain selection choose “ARM, gcc-4.4.4, multilib, neon optimized” instead of default “ARM, gcc-4.6.2, multilib, neon optimized, gnueabi/eglibc2.13”.

12

13

One more serious error that you will encounter is this

Couldn’t link to symbol lroundf@@GLIBC_2.2.5

15

To avoid this error you need to edit makefile.rules of elftosb-2.6.35.3-1.1.0.tar.gz

cp /opt/freescale/pkgs/elftosb-2.6.35.3-1.1.0.tar.gz ~/Desktop
tar -zxvf elftosb-2.6.35.3-1.1.0.tar.gz
cd elftosb-2.6.35.3-1.1.0/
vim makefile.rules

Inside that file there is a line that reads

 LIBS = -lstdc++

change it to

LIBS = -lstdc++ -lm

to add the standard math library to the build.
make
After editing compress the folder back to tar.gz and place it in pkgs folder

tar -zcvf elftosb-2.6.35.3-1.1.0.tar.gz elftosb-2.6.35.3-1.1.0/
cp  ~/Desktop /opt/freescale/pkgs/elftosb-2.6.35.3-1.1.0.tar.gz

Now delete the old file from BUILD folder.Else you will get an error saying delete that file.

rm -rf /opt/freescale/ltib/usr/src/rpm/BUILD/elftosb-2.6.35.3-1.1.0.tar.gz

Now again start building using the command

./ltib

After sucessful build you will be seeing this

17

After you have completed a build by using LTIB, you will have a target root filesystem in the rootfs directory inside the LTIB install directory. For instance, if you installed LTIB in your home directory, there will be a ~/ltib/rootfs directory containing the target rootfs.
Inside the ~/ltib/rootfs/boot directory, you will find a set of .sb files. These are the boot streams that the i.MX28 ROM interprets to boot the system.

18

Happy Hacking 🙂

Avr interfacing a switch

In this tutorial we check how to interface a push button to an Atmega8.

Here we will connect an external button to give input to a AVR. Button is connected to 5v if button pressed then delay of led lights changes if released then.here the program is configured in such a way that one pin B1 of Port B is configured as input and pin B0 as output.The input pin checks whether high or low is received and toggles the output pin.

Circuit Diagram

switch

Program

#include <avr/io.h>
#include <avr/delay.h>

int main()
{
	DDRB |= 1<<PINB0;
	DDRB &= ~(1<<PINB1);
	PORTB |= 1<<PINB1;
	while(1)
	{
		PORTB ^= 1<<PINB0;
		if(bit_is_set(PINB,1))
		{
			_delay_ms(100);
		}
		else
		{
			_delay_ms(500);
		}
	}
}

Use  the  same  Makefile
Change the TARGET name with the file name of the above program
Use the  commands  in  sequence

make elf

make hex

make flash

Switch in action

Happy Hacking 🙂

Avr LED Blinking

This program explains hello world LED blinking program.In this program an LED is connected through a resistor to PINB0.

#include <avr/io.h>
#include <avr/delay.h>

int main()
{
	DDRB |= 1<<PINB0;
	while(1)
	{
		PORTB |= 1<<PINB0;
		_delay_ms(100);
		PORTB &= ~(1<<PINB0);
		_delay_ms(100);
	}
}

The above program makes PINB0 blink with 100ms delay.
Compile and upload the hex file.You can use the blow make file for the whole process

CC = avr-gcc
OBJCOPY = avr-objcopy
OBJDUMP = avr-objdump
AVRDUDE = avrdude
REMOVE = rm -f

MCU =atmega8

TARGET = blink
SRC = $(TARGET).c

AVRDUDE_PROGRAMMER = dapa
AVRDUDE_PORT = /dev/parport0 
AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex

elf:
	$(CC) -mmcu=$(MCU) -Os -o $(TARGET).elf $(SRC)
hex:
	$(OBJCOPY) -j .text -j .data -O ihex  $(TARGET).elf $(TARGET).hex
flash:
	$(AVRDUDE) -p m8 -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) $(AVRDUDE_WRITE_FLASH)
clean:
	$(REMOVE) $(TARGET).hex $(TARGET).elf $(TARGET).c~

When your program name changes change name of the TARGET variable in Makefile.
Use the commands in sequence

make elf

make hex

make flash

HelloWorld in action

Happy Hacking 🙂

Linux USB Serial sending 0x0D receiving 0x0A issue

Am using a FTDI serial to USB converter , today i encountered with a strange issue.When am sending an hexadecimal  0xD it is received as 0xA.

I tried to debug the code but was in vain,finaly i got a solution from stackoverflow the same issue was reported for a java program.

Typing these commands solved the issue

"stty -F /dev/ttyUSB0 -onclr"
"stty -F /dev/ttyUSB0 -icrnl"

icrnl – translate carriage return to newline

If you have a c program to open /dev/ttyUSB0 then add the below iflag


tty.c_iflag &= ~(INLCR | ICRNL);

Happy Hacking 🙂

Plotting real-time data from Arduino using Python

The below Arduino sketch reads the values from analog pins A0 and A1 and prints it to the serial port.
This is the code

void setup()
{
  Serial.begin(9600); 
}

void loop()
{
  // read A0
  int val1 = analogRead(0);
  // read A1
  int val2 = analogRead(1);
  // print to serial
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  // wait 
  delay(50);
}

The serial port sends values in this format

Screenshot--dev-ttyUSB5

Using python and Matplotlib am plotting this data as a function of time.I wanted to display this as a scrolling graph that moves to the right as data keeps coming in. For that, I am using the Python deque class to keep and update a fixed number of data points for each time frame.

import sys, serial
import numpy as np
from time import sleep
from collections import deque
from matplotlib import pyplot as plt

# class that holds analog data for N samples
class AnalogData:
  # constr
  def __init__(self, maxLen):
    self.ax = deque([0.0]*maxLen)
    self.ay = deque([0.0]*maxLen)
    self.maxLen = maxLen

  # ring buffer
  def addToBuf(self, buf, val):
    if len(buf) < self.maxLen:
      buf.append(val)
    else:
      buf.pop()
      buf.appendleft(val)

  # add data
  def add(self, data):
    assert(len(data) == 2)
    self.addToBuf(self.ax, data[0])
    self.addToBuf(self.ay, data[1])
    
# plot class
class AnalogPlot:
  # constr
  def __init__(self, analogData):
    # set plot to animated
    plt.ion() 
    self.axline, = plt.plot(analogData.ax)
    self.ayline, = plt.plot(analogData.ay)
    plt.ylim([0, 1023])

  # update plot
  def update(self, analogData):
    self.axline.set_ydata(analogData.ax)
    self.ayline.set_ydata(analogData.ay)
    plt.draw()

# main() function
def main():
  # expects 1 arg - serial port string
  if(len(sys.argv) != 2):
    print 'Example usage: python showdata.py "/dev/tty.usbmodem411"'
    exit(1)

 #strPort = '/dev/tty.usbserial-A7006Yqh'
  strPort = sys.argv[1];

  # plot parameters
  analogData = AnalogData(100)
  analogPlot = AnalogPlot(analogData)

  print 'plotting data...'

  # open serial port
  ser = serial.Serial(strPort, 9600)
  while True:
    try:
      line = ser.readline()
      data = [float(val) for val in line.split()]
      #print data
      if(len(data) == 2):
        analogData.add(data)
        analogPlot.update(analogData)
    except KeyboardInterrupt:
      print 'exiting'
      break
  # close serial
  ser.flush()
  ser.close()

# call main
if __name__ == '__main__':
  main()

The program must be run in this format

python showdata.py /dev/ttyUSB5

Instead of ttyUSB5 add your ttyUSB device.And this is how the plot looks like.

Screenshot-Figure 1

Happy Hacking 🙂