hawkesley
Posts: 113
Joined: Tue Jan 12, 2016 10:16 am

Uses for accelerometer

Tue Jan 31, 2017 12:15 pm

I would like to build a pedometer using the sense hat, to incorporate into a Hiking Assistant project.
Before I spend a lot of time on this I wonder if anyone knows if the sense hat accelerometer would provide enough data for it work.
My inspiration for this type of project comes from an article by Dessy Daskalov, 'A Pedometer in the Real World'. A brilliant article I think.
The link is :- http://www.aosabook.org/en/500L/a-pedom ... world.html
Any comments welcome.

scotty101
Posts: 3599
Joined: Fri Jun 08, 2012 6:03 pm

Re: Uses for accelerometer

Tue Jan 31, 2017 5:47 pm

It should do. Easiest was to test is to record the data from the accelerometer at the fastest rate possible whilst walking around and then graph it after to see if you can clearly see the steps or not.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

hawkesley
Posts: 113
Joined: Tue Jan 12, 2016 10:16 am

Re: Uses for accelerometer

Wed Feb 01, 2017 11:03 am

Yes, I will try that, thanks.

hawkesley
Posts: 113
Joined: Tue Jan 12, 2016 10:16 am

Re: Uses for accelerometer

Wed Feb 22, 2017 12:05 pm

Following on from the past post I have know a data logger that will record the sense hat accelerometer output. I am stuck on how to graph this data and need a pointer.
I am still keen to convert the code from 'http://www.aosabook.org/en/500L/a-pedom ... world.html' to either php or python but it is a challenge.
Below I have posted a class from the the article and wonder if anybody can deduce what language is being used here. I think it might be Ruby, and if so are there any conversion aids to PHP or Python that anybody is aware of.
Many thanks.

Code: Select all

class Parser

  attr_reader :parsed_data

  def self.run(data)
    parser = Parser.new(data)
    parser.parse
    parser
  end

  def initialize(data)
    @data = data
  end

  def parse
    @parsed_data = @data.to_s.split(';').map { |x| x.split('|') }
                   .map { |x| x.map { |x| x.split(',').map(&:to_f) } }

    unless @parsed_data.map { |x| x.map(&:length).uniq }.uniq == [[3]]
      raise 'Bad Input. Ensure data is properly formatted.'
    end

    if @parsed_data.first.count == 1
      filtered_accl = @parsed_data.map(&:flatten).transpose.map do |total_accl|
        grav = Filter.low_0_hz(total_accl)
        user = total_accl.zip(grav).map { |a, b| a - b }
        [user, grav]
      end

      @parsed_data = @parsed_data.length.times.map do |i|
        user = filtered_accl.map(&:first).map { |elem| elem[i] }
        grav = filtered_accl.map(&:last).map { |elem| elem[i] }
        [user, grav]
      end
    end
  end

end

scotty101
Posts: 3599
Joined: Fri Jun 08, 2012 6:03 pm

Re: Uses for accelerometer

Wed Feb 22, 2017 12:31 pm

In my professional life I would use MATLAB to plot the data.

For Hobby purposes I would try using Octave https://www.gnu.org/software/octave/doc ... Plots.html
Octave should be able to read in the data you've logged. Should be simple if you have comma separated values.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
bensimmo
Posts: 4075
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Uses for accelerometer

Wed Feb 22, 2017 12:33 pm

You could graph it in a spreadsheet, you could use on online site (Plotly ? or others)
https://www.raspberrypi.org/learning/as ... worksheet/

You could use Mathmatica (or others like Mathcad)
There are various python module for maths and analysis.

But none of it helps if you don't know what you are trying to do and look for.
I would guess you need to find the varying frequencies of peaks? Just count the peaks?
(Could do that in real time or afterwards)
E.g. go through the data, when it reaches a threshold, count, when it drops below, enable the count again etc)

hawkesley
Posts: 113
Joined: Tue Jan 12, 2016 10:16 am

Re: Uses for accelerometer

Wed Feb 22, 2017 1:01 pm

Hi Thanks for that.
Yes the object is to measure the peaks and troughs but filtered as per the article.
'To count steps, we're interested in the bounces created by the user in the direction of gravity. That means we're interested in isolating the 1-dimensional time series which describes user acceleration in the direction of gravity from our 3-dimensional acceleration signal (Figure 16.4).'
I will try some basic graphing.
Is the code I posted Ruby?

hawkesley
Posts: 113
Joined: Tue Jan 12, 2016 10:16 am

Re: Uses for accelerometer

Fri Feb 24, 2017 10:44 am

Just to confirm that the code I have referred to is Ruby and if I convert it I will post back here.
I do need some help with my data logger.
It works fine from IDLE but as a cron job it runs but does not write the file to /home/pi where the logger resides.
I have made the logger executable with chmod +x.
Can any one help please.

Code: Select all

#!/usr/bin/env python3
##### Libraries #####
from datetime import datetime
from sense_hat import SenseHat
from time import sleep
from threading import Thread

##### Logging Settings #####
FILENAME = ""
WRITE_FREQUENCY = 100
TEMP_H=True
TEMP_P=False
HUMIDITY=True
PRESSURE=True
ORIENTATION=True
ACCELERATION=True
MAG=True
GYRO=True
DELAY=0

##### Functions #####
def file_setup(filename):
    header =[]
    if TEMP_H:
        header.append("temp_h")
    if TEMP_P:
        header.append("temp_p")
    if HUMIDITY:
        header.append("humidity")
    if PRESSURE:
        header.append("pressure")
    if ORIENTATION:
        header.extend(["pitch","roll","yaw"])
    if MAG:
        header.extend(["mag_x","mag_y","mag_z"])
    if ACCELERATION:
        header.extend(["accel_x","accel_y","accel_z"])
    if GYRO:
        header.extend(["gyro_x","gyro_y","gyro_z"])
    header.append("timestamp")

    with open(filename,"w") as f:
        f.write(",".join(str(value) for value in header)+ "\n")

def log_data():
    output_string = ",".join(str(value) for value in sense_data)
    batch_data.append(output_string)


def get_sense_data():
    sense_data=[]

    if TEMP_H:
        sense_data.append(sense.get_temperature_from_humidity())

    if TEMP_P:
        sense_data.append(sense.get_temperature_from_pressure())

    if HUMIDITY:
        sense_data.append(sense.get_humidity())

    if PRESSURE:
        sense_data.append(sense.get_pressure())

    if ORIENTATION:
        o = sense.get_orientation()
        yaw = o["yaw"]
        pitch = o["pitch"]
        roll = o["roll"]
        sense_data.extend([pitch,roll,yaw])

    if MAG:
        mag = sense.get_compass_raw()
        mag_x = mag["x"]
        mag_y = mag["y"]
        mag_z = mag["z"]
        sense_data.extend([mag_x,mag_y,mag_z])

    if ACCELERATION:
        acc = sense.get_accelerometer_raw()
        x = acc["x"]
        y = acc["y"]
        z = acc["z"]
        sense_data.extend([x,y,z])

    if GYRO:
        gyro = sense.get_gyroscope_raw()
        gyro_x = ["x"]
        gyro_y = ["y"]
        gyro_z = ["z"]
        sense_data.extend([gyro_x,gyro_y,gyro_z])

    sense_data.append(datetime.now())

    return sense_data

def timed_log():
    while True:
        log_data()
        sleep(DELAY)




##### Main Program #####
sense = SenseHat()
batch_data= []

##### Show Start Up Message #####
sense.show_message(
                "Accelerometer Running",
                scroll_speed=0.10,
                text_colour=(150,150,150)
                  )

if FILENAME == "":
    filename = "SenseLog-"+str(datetime.now())+".csv"
else:
    filename = FILENAME+"-"+str(datetime.now())+".csv"

file_setup(filename)

if DELAY > 0:
    sense_data = get_sense_data()
    Thread(target= timed_log).start()

while True:
    sense_data = get_sense_data()

    if DELAY == 0:
        log_data()

    if len(batch_data) >= WRITE_FREQUENCY:
        print("Writing to file..")
        with open(filename,"a") as f:
            for line in batch_data:
                f.write(line + "\n")
            batch_data = []

User avatar
bensimmo
Posts: 4075
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Uses for accelerometer

Fri Feb 24, 2017 12:25 pm

Have you tried it from rc.local as per the worksheet.
While that doesn't help you schedule a time like cron, it will work for running after boot.

Are there any error messages, are you running as pi via cron.
I would guess they would need to see your cron setup.

hawkesley
Posts: 113
Joined: Tue Jan 12, 2016 10:16 am

Re: Uses for accelerometer

Fri Feb 24, 2017 2:39 pm

Hi Thanks for that.
I have now used rc.local and it is now writing to the file.
I would prefer to use cron so as to schedule a time in.
I will try cron again.
Does any one know how to stop a program like this programtically?
It would be very useful to start and to exit the program from the joystick functions as the project will be headless.
I can ssh in from a phone but it is not so easy when outside on a small screen.
I have used this but it would be much easier from the joystick i think:-

Code: Select all

ps aux | grep /home/pi/Sense-Data-Logger.py
//to find the process and 
sudo kill 'process'
Any ideas?

User avatar
bensimmo
Posts: 4075
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Uses for accelerometer

Fri Feb 24, 2017 3:13 pm

On the Datalogging sheet the last thing was, if I remember right, to implement the joystick. It could well have been for some other SenseHat lesson.

Ok found it, I've never used it as never had the need (didn't know it was there when I was datalogging)
But
https://github.com/raspberrypilearning/ ... r_Final.py

That's the final version.
Though it uses an old method for the joystick and hasn't been updated for the newer implementation.
https://pythonhosted.org/sense-hat/api/#joystick


sudo killall python3
Would also kill all python3 instances

hawkesley
Posts: 113
Joined: Tue Jan 12, 2016 10:16 am

Re: Uses for accelerometer

Fri Feb 24, 2017 4:15 pm

Hi,
Thanks, I had completely missed there was another work sheet.
I'll give it a go.

Return to “Astro Pi”