Mats Van Gestel
Posts: 3
Joined: Sun Jun 21, 2015 10:19 am

Programming a Hall-sensor

Sun Jun 21, 2015 10:27 am

Dear fellow-raspberry users,

I ran into a problem concerning a topic for my university. I am constructing flight mills (for insects) which should automattically record tha amount of times the mill makes a complete turn-around. Based on the e-book found here (https://leanpub.com/RPiMRE/read#leanpub ... ut-sensors GREAT book by the way!) I am now able to upload data to an online server. Problem is: no internet at the University. Does anyone know a way to write data onto a USB-device (maybe via a pre-configured excel file?) the code I am using now includes:
def storeFunction(channel):
print("Signal detected")

con = mdb.connect('localhost', \
'pi_insert', \
'xxxxxxxxxx', \
'measurements');

try:
cur = con.cursor()
cur.execute("""INSERT INTO events(event) VALUES(%s)""", ('catflap'))
con.commit()

except mdb.Error, e:
logger.error(e)

finally:
if con:
con.close()

(off course I adjusted username and pasword (xxxxxxxxx) in order to acces my own database).
So basically what I want to do is change this code to one that writes the data to a USB device in stead of the internet.

Thanks for reading the long post, I hope somebody can help me out...

Cheers,
Mats

Davies
Posts: 150
Joined: Sat Apr 04, 2015 4:24 pm

Re: Programming a Hall-sensor

Sun Jun 21, 2015 11:19 am

there will be many of people here who can give a better answer than I can, but when I want to save or open a file I use

Code: Select all

def file_open():
    t.delete(1.0, END)
    if os.path.isfile(e.get()+".txt"):
        fn = e.get()+".txt"
        f = open(fn, 'r')
        data = f.read()
        f.close()
        t.insert(1.0, data)


def file_save():
    fn = e.get()+".txt"
    f = open(fn, 'w')
    data = t.get(1.0, END)
    f.write(data)
    f.close()

t = Text(root, background='white', font='-weight bold')
t.grid(padx=10, pady=10, row=18, columnspan=70, rowspan=8)
e = Entry(root, width=4, background='white', textvariable=file, justify=CENTER, font='-weight bold')
e.grid(padx=10, pady=5, row=17, column=1, sticky='W,E,N,S')
this would check to see if a text file of a name designated by the user exists then open it,
and save would save in the name designated by the user.
im sure you will be able to make it open an excel file input the info then save

ghp
Posts: 1395
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Programming a Hall-sensor

Sun Jun 21, 2015 11:45 am

Hello,

when writing records to a file, use the 'append'-flag
open("test.txt", "a")
Think it is complicated to write excel format directly, but if you write "csv"-format it is easy to import this into excel. Just separate the values by comma or semicolon; separate the rows by newline. Perhaps you want to add a timestamp in each row.
When you open the file, append a record and close the file, the data will be quite save against program failures.
Regards,
Gerhard

Mats Van Gestel
Posts: 3
Joined: Sun Jun 21, 2015 10:19 am

Re: Programming a Hall-sensor

Sun Jun 21, 2015 1:25 pm

ghp wrote:Hello,

when writing records to a file, use the 'append'-flag
open("test.txt", "a")
Think it is complicated to write excel format directly, but if you write "csv"-format it is easy to import this into excel. Just separate the values by comma or semicolon; separate the rows by newline. Perhaps you want to add a timestamp in each row.
When you open the file, append a record and close the file, the data will be quite save against program failures.
Regards,
Gerhard

Thank you for the reply (also for the first one to reply, at the top here).
I am afraid I don't quite follow though... I'm a biologist and don't know anything about codes (sorry :-/ ). But if I were able to convert the "high"-signals the Hall-sensor sends to the Rpi and store them in any way (a text file would be good enough for sure) in combination with, indeed, a time-stamp (I want to know at what time my flight-mill is turning) I would be able to export the file via a USB device... so basically I would just like to generate a new text file containing the times at which the hall-sensor was trigerred. Do you happen to know any codes I could use? So far, I've been using the code

Code: Select all

#!/usr/bin/python
# -*- coding: utf-8 -*-

# Import the python libraries
import RPi.GPIO as GPIO
import logging
import MySQLdb as mdb
import time

logging.basicConfig(filename='/home/event_error.log',
  level=logging.DEBUG,
  format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger=logging.getLogger(__name__)

# Function called when GPIO.RISING
def storeFunction(channel):
  print("Signal detected")
  
  con = mdb.connect('localhost', \
                    'pi_insert', \
                    'xxxxxxxxxx', \
                    'measurements');
  
  try:
    cur = con.cursor()
    cur.execute("""INSERT INTO events(event) VALUES(%s)""", ('catflap'))
    con.commit()

  except mdb.Error, e:
    logger.error(e)

  finally:
    if con:
      con.close()

print "Sensor event monitoring (CTRL-C to exit)"

# use the BCM GPIO numbering
GPIO.setmode(GPIO.BCM)

# Definie the BCM-PIN number
GPIO_PIR = 2

# Define pin as input with standard high signaal
GPIO.setup(GPIO_PIR, GPIO.IN, pull_up_down = GPIO.PUD_UP)

try:
  # Loop while true = true
  while True :

    # Wait for the trigger then call the function
    GPIO.wait_for_edge(GPIO_PIR, GPIO.RISING)
    storeFunction(2)
    time.sleep(1)

except KeyboardInterrupt:
  # Reset the GPIO settings
  GPIO.cleanup()
which sends data to an internet server

ghp
Posts: 1395
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Programming a Hall-sensor

Sun Jun 21, 2015 4:46 pm

Hello,
modified the code to write to a file.

Code: Select all

#!/usr/bin/python
# -*- coding: utf-8 -*-

# Import the python libraries
import RPi.GPIO as GPIO
import logging
import time
from datetime import datetime

logging.basicConfig(filename='/home/event_error.log',
  level=logging.DEBUG,
  format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger=logging.getLogger(__name__)

count = 0
lastTime = None
# Function called when GPIO.RISING
def storeFunction(channel):
    logger.info("Signal detected")
    global count
    global lastTime
    f = open('/home/data.csv', 'a')
    if lastTime == None:
        tDelta = ''
        lastTime = time.time()
    else:
        t = time.time();
        tDelta = str(t-lastTime)
        lastTime = t
    #
    # write current time (iso), count, delta time 
    #
    f.write("{t:s};{cnt:d};{td:s}\n".format(t=datetime.now().isoformat(),cnt=count, td=tDelta))
    f.close()
    count += 1
    
print "Sensor event monitoring (CTRL-C to exit)"

# use the BCM GPIO numbering
GPIO.setmode(GPIO.BCM)

# Definie the BCM-PIN number
GPIO_PIR = 2

# Define pin as input with standard high signaal
GPIO.setup(GPIO_PIR, GPIO.IN, pull_up_down = GPIO.PUD_UP)

try:
    # Loop while true = true
    while True :
        # Wait for the trigger then call the function
        GPIO.wait_for_edge(GPIO_PIR, GPIO.RISING)
        storeFunction(2)
        time.sleep(1)

except KeyboardInterrupt:
    # Reset the GPIO settings
    GPIO.cleanup()
Be aware that there was a time.sleep(1) in the main loop. Most possibly this was to remove jitter in the input. But it limits the 'turn rate' to 1Hz. Faster turns will be recorded wrong...
Data are written to /home -directory, which is a little bit uncommon, but as the code is running as superuser it is possible.
You can see progress by

Code: Select all

cd /home
tail -f data.csv
Hope this helps,
Gerhard

Return to “Python”