Need help writing script for Digital DAQ

Hello,
I am trying to write an aquisition program for digital input coming from a hall sensor.  I will be passing a magnet over a hall sensor on a motor and want to record the number of rotations.  I have pasted together a script based on various websites, but it isn't functioning the way I want.  I would like to be able to collect data points indefinately, or fixed, and then print out the resulting count.  I have attepted to use the ctypes wrapper in Python.  The NI functions remain unchanged though, so if you don't know Python it shouldn't be a problem to read.  I am using a NI PCI-6503. 
NI PCI-6503
NI PCI-6503
NI PCI-6503
The code:
# C:\Program Files\National Instruments\NI-DAQ\Examples\DAQmx ANSI C\Analog In\Measure Voltage\Acq-Int Clk\Acq-IntClk.c
import ctypes
import numpy
nidaq = ctypes.windll.nicaiu # load the DLL
# Setup some typedefs and constants
# to correspond with values in
# C:\Program Files\National Instruments\NI-DAQ\DAQmx ANSI C Dev\include\NIDAQmx.h
# the typedefs
int32 = ctypes.c_long
uInt32 = ctypes.c_ulong
uInt64 = ctypes.c_ulonglong
float64 = ctypes.c_double
TaskHandle = uInt32
# the constants
DAQmx_Val_ChanForAllLines = int32(0)
def CHK(err):
"""a simple error checking routine"""
     if err < 0:
          buf_size = 200
          buf = ctypes.create_string_buffer('\000' * buf_size)
          nidaq.DAQmxGetErrorString(err,ctypes.byref(buf),buf_size)
          raise RuntimeError('nidaq call failed with error %d: %s'%(err,repr(buf.value)))
# initialize variables
taskHandle = TaskHandle(0)
max_num_samples = 1000
# array to gather points
data = numpy.zeros((max_num_samples,),dtype=numpy.float64)
# now, on with the program
CHK(nidaq.DAQmxCreateTask("",ctypes.byref(taskHandle)))
CHK(nidaq.DAQmxCreateDIChan(taskHandle,'Dev1/port1/line1',"", DAQmx_Val_ChanForAllLines))
CHK(nidaq.DAQmxStartTask(taskHandle))
read = int32()
CHK(nidaq.DAQmxReadDigitalU32(taskHandle,int32(-1),float64(1),DAQmx_Val_GroupByChannel,data.ctypes.data,max_num_samples,ctypes.byref(read),None))
print "Acquired %d points"%(read.value)
if taskHandle.value != 0:
     nidaq.DAQmxStopTask(taskHandle)
     nidaq.DAQmxClearTask(taskHandle)
print "End of program, press Enter key to quit"
raw_input()
This script returns "Acquired 1 points" immediately, regardless of how many times the hall sensor has been switched.  
I apologize for the sloppy code, but I understand very little of the underlying principles of these DAQ functions, despite reading their documentation.  Seeing as how the code does not return an error, I am hoping there is just a minor tweak or two that will be farily obvious to someone with more experience.  
Thanks

Hey Daniel,
Most of this script is from http://www.scipy.org/Cookbook/Data_Acquisition_with_NIDAQmx. 
I needed to run the ReadDigitalU32 function in Python loop because my DAQ device did not support timed aquistion and I don't have LabView.  
import numpy
import time
import ctypes
nidaq = ctypes.windll.nicaiu # load the DLL
# Setup some typedefs and constants
# to correspond with values in
# C:\Program Files\National Instruments\NI-DAQ\DAQmx ANSI C Dev\include\NIDAQmx.h
# the typedefs
int32 = ctypes.c_long
uInt32 = ctypes.c_ulong
uInt64 = ctypes.c_ulonglong
float64 = ctypes.c_double
TaskHandle = uInt32
# the constants
DAQmx_Val_Cfg_Default = int32(-1)
DAQmx_Val_Volts = 10348
DAQmx_Val_Rising = 10280
DAQmx_Val_FiniteSamps = 10178
DAQmx_Val_GroupByChannel = 0
DAQmx_Val_ChanForAllLines = int32(0)
# initialize variables
taskHandle = TaskHandle(0)
max_num_samples = 10000
data = numpy.zeros((max_num_samples,),dtype=numpy.float64)
read = uInt32()
bufferSize = uInt32(10000)
def CHK(err):
"""a simple error checking routine"""
     if err < 0:
          buf_size = 200
          buf = ctypes.create_string_buffer('\000' * buf_size)
          nidaq.DAQmxGetErrorString(err,ctypes.byref(buf),buf_size)
          raise RuntimeError('nidaq call failed with error %d: %s'%(err,repr(buf.value)))
# Start up DAQ
CHK(nidaq.DAQmxCreateTask("",ctypes.byref(taskHandle)))
CHK(nidaq.DAQmxCreateDIChan(taskHandle,"Dev?/port?/line?","", DAQmx_Val_ChanForAllLines))
CHK(nidaq.DAQmxStartTask(taskHandle))
#initialize lists and time 1 
t1 = time.time()
times = []
points = []
while True:
     try:
          CHK(nidaq.DAQmxReadDigitalU32(taskHandle,int32(-1),float64(1),
          DAQmx_Val_GroupByChannel,data.ctypes.data,uInt32(2*bufferSize.value)
         ,ctypes.byref(read), None))
          t2 = time.time()
         #data[0] is the position in the numpy array 'data' that holds the value aquired
         #from your device
         points.append(data[0])
         times.append(t2 - t1) 
         t1 = time.time()
         #Choose time interval between data aquisition
         time.sleep(.02)
     except KeyboardInterrupt:
          break
#process the lists of points and time intervals as you so choose
Thanks for the help!
Paul

Similar Messages

  • Need Help with scripting for Automator/AppleScript.

    Hi everybody,
    I am building a small app for my mac, What I need is a script that can rename a file that I drop on it.
    and example being:
    example.jpg
    (when I drop it on the app, I want the app to change the filename of the document to "Image.jpg"
    I have tried this with Automator, but it requires that I specify the file to be changed, what I need is something that will change the name of any file I drag onto it.
    I am using it for application specific files.
    Kind regards,
    Pete.
    iBook G4; 60GB Hard Drive, 512MB RAM, Airport Extreme    

    Open the Script Editor in the
    /Applications/AppleScript/ folder and enter the
    following:
    on open(the_file)
    tell application "Finder"
    set name of the_file to "Image"
    end tell
    end open
    Save this script as an application.
    (11347)
    this script compiled correctly; however when run it returned the following error "Can't set name of (the_file) to "Image.jpg"
    I am also given the option of editing the script or just quitting.
    thanks for your help

  • Need help creating script for specific instance

    I am having trouble coming up with a working script for this part of the pricing form I am editing. I am trying to get the calculation fields to the right to change and populate in the respective field based on the selection in the Material Type dropdown. Would it be less of a headache if I made another text field to calculate the LE versions separately instead of trying to merge them into one field? I have attached screenshots below to give you an example of what I'm working with. Any help with this is greatly appreciated!
    Script I'm tinkering with at the moment:
    //Dropdown37 = Quantity Field
    //Type of Door IB = Material Type dropdown
    var x = this.getField("Type of Door IB").value;
    if ( x = 1468 ) event.value = x * this.getField("Dropdown37").value;
    if (x = 1202) event.value = x * this.getField("Dropdown37").value;
    else event.value = 0;

    The comparison operator in JS is "==", so change this line:
    if ( x = 1468 )
    To this:
    if ( x == 1468 )
    (as well as the other if-statement).

  • Need help writing script to change version control for all document libraries in all sites

    Hello,
    I found this script, http://get-spscripts.com/2010/10/changing-sharepoint-list-settings-using.html that
    changes versions control for a document library.  However, many sites have many document libraries with different names.  The script below just changes a the settings to a document library that is named "Shared Documents", but does not
    change one if its named something else.  How can change the script to loop through all document libraries so their settings are changed?
    $site = Get-SPSite http://site
    $listName = "Shared Documents"
    #Walk through each site in the site collection
    $site | Get-SPWeb | 
    ForEach-Object {
    #Get the list in this site
    $list = $_.Lists[$listName]
    #Create a version each time you edit an item in this list (lists)
    #Create major versions (document libraries)
    $list.EnableVersioning = $true
    #Create major and minor (draft) versions (document libraries only)
    $list.EnableMinorVersions = $true
    #Keep the following number of versions (lists)
    #Keep the following number of major versions (document libraries)
    $list.MajorVersionLimit = 7
    #Keep drafts for the following number of approved versions (lists)
    #Keep drafts for the following number of major versions (document libraries)
    $list.MajorWithMinorVersionsLimit = 5
    #Update the list
    $list.Update()
    #Dispose of the site object
    $site.Dispose()
    Paul

    Sorry, I agree. It will update Style Library and other out of the box ones. Include the library titles in a collection and run the update against them provided these libraries are common across all sites. If not, you will have to first get an extract of
    all such libraries in all sites say in a CSV file and then update the script below to refer to the CSV records.
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction Stop;
    #List of Libraries to be updated.
    $Libraries = @("Shared Documents","My Document Library");
    $spAssgn = Start-SPAssignment;
    $site = Get-SPSite http://site -AssignmentCollection $spAssgn
    #Walk through each site in the site collection
    $site | Get-SPWeb -Limit ALL -AssignmentCollection $spAssgn |
    ForEach-Object {
    #Enumerate through all document libraries
    $_.Lists|Where{$_.BaseTemplate -eq "DocumentLibrary" -and $Libraries -contains $_.Title}|Foreach-Object{
    #Get the list in this site
    $list = $_;
    #Create a version each time you edit an item in this list (lists)
    #Create major versions (document libraries)
    $list.EnableVersioning = $true
    #Create major and minor (draft) versions (document libraries only)
    $list.EnableMinorVersions = $true
    #Keep the following number of versions (lists)
    #Keep the following number of major versions (document libraries)
    $list.MajorVersionLimit = 7
    #Keep drafts for the following number of approved versions (lists)
    #Keep drafts for the following number of major versions (document libraries)
    $list.MajorWithMinorVersionsLimit = 5
    #Update the list
    $list.Update()
    Stop-SPAssignment $spAssgn;
    This post is my own opinion and does not necessarily reflect the opinion or view of Slalom.

  • Need Help with script For Bulk Users Name & Description Updation

    Hi Guys,
    I have below requirement :
    We are having one windows 2008 stand alone server with 200+ local users (No Active Directory Account).
    1. Requirement is to update each account's "Full name" and "Description field" with same text. Which means , Full name and Description field will be same with same text. No other changes are required. )Attached the screenshot)
    Can you guys pls help me out with any scripting (vbs , powershell , DOS .etc etc) method to accomplish this task quickly as manual process is very troublesome and take long time.
    Any help will be highly appreciated,
    Thanks,
    Suvajit Basu

    Hi,
    I dont have any script but seeking for a help.
    Thanks,
    Suvajit Basu
    In that case you should read this first:
    https://social.technet.microsoft.com/Forums/scriptcenter/en-US/a0def745-4831-4de0-a040-63b63e7be7ae/posting-guidelines?forum=ITCG
    Prewritten scripts can be found in the repository (Brent has already suggested one for you):
    https://gallery.technet.microsoft.com/scriptcenter
    If you can't find what you need and you can't write your own, you can request a script here:
    https://gallery.technet.microsoft.com/scriptcenter/site/requests
    Let us know if you have any specific questions.
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Need help writing client for WSE 1.0 Web Service

    Hello all,
    I am attempting to write Java clients against a .Net service that uses WSE 1.0. I can't seem to get any of toolkits I have tried to work with this service. Unfounately, I do not own the service, so I cannot upgrade it to WSE 2.0. The problem seems to be that the WSE 1.0 expects namespaces from the July 2002 version of WS-Security, while all the libraries I have tried (JWSDP, Oracle Web Service Wizard, etc) use the oasis namepsace from January 2004.
    Can he one suggest an alternative? Is there a way to set the namespace sent in XWS-Security? I think this might solve the problem...
    Thanks,
    KS

    Hi,
    firstly JWSDP 1.5 is pretty old, the latest release of JWSDP is JWSDP 2.0 that happened late last year.
    The problem is most likely happening due to a bug in JWSDP 1.5. If you dump the Message that is going over the wire you will probably see
    SOAPAction : ""
    SOAPAction : "<the correct action value>"
    And this is the reason for the failure. I believe you are using SOAP 1.1 messages right ?
    What you will need to do is upgrade to
    JWSDP 2.0 and more important also upgrade your SAAJ jars in the JWSDP installation to SAAJ 1.3
    https://saaj.dev.java.net/files/documents/52/32730/saaj1.3.zip
    Alternatively, you can use Sun's Project Tango (Sun's Next Generation WebServices Interoperability Technology Offering) which has been tested to interoperate with Microsoft WCF.
    http://java.sun.com/developer/technicalArticles/glassfish/ProjectTango/
    You can download Project Tango by visiting the following page :
    https://wsit.dev.java.net/
    Look at the Try It section for instructions on how to use it.
    Using the Netbeans Plugin you can develop a java client which can securely communicate with the .Net WebService. All you need to do for that is use Netbeans to create a Java WebService Client by pointing it to the WSDL of the .Net Service.
    Let us know if this helped.
    Thanks...
    Message was edited by:
    kumar_at_sun

  • Need help writing script to have dbms_stats delete and collect schema

    I am working on a script to collect stats for Oracle 8i with dbms_stats.
    Since the bug in Oracle 8i requires me to first delete stats for all tables in the schema and
    then to re-run dbms_stats to collect the stats, how can I write a script to do the cleanup and collection stats process for Oracle 8i on Unix?
    Scott

    Something like this (Linux) :
    $ cat stats.sh
    . $HOME/.bash_profile
    ORACLE_SID=orcl; export ORACLE_SID
    echo "Deleting statistics..."
    sqlplus -s "/ as sysdba" << EOF
    exec dbms_stats.delete_schema_stats('SCOTT');
    exit
    EOF
    echo "Gathering statistics..."
    sqlplus -s "/ as sysdba" << EOF
    exec dbms_stats.gather_schema_stats('SCOTT',cascade=>true);
    exit
    EOF
    $ ./stats.sh
    Deleting statistics...
    PL/SQL procedure successfully completed.
    Gathering statistics...
    PL/SQL procedure successfully completed.
    $                                                    Change .bash_profile with .profile if you are using korn shell or bourne shell.

  • I need help writing a script that finds the first instance of a paragraph style and then changes it

    I need help writing a script that finds the first instance of a paragraph style and then changes it to another paragraph style.  I don't necessarily need someone to write the whole thing, by biggest problem is figuring how to find just the first instance of the paragraph style.  Any help would be greatly appreciated, thanks!

    Hi,
    Do you mean first instance of the paragraph style
    - in a chosen story;
    - on some chosen page in every text frames, looking from its top to the bottom;
    - in a entire document, looking from its beginning to the end, including hidden layers, master pages, footnotes etc...?
    If story...
    You could set app.findTextPreferences.appliedParagraphStyle to your "Style".
    Story.findText() gives an array of matches. 1st array's element is a 1st occurence.
    so:
    Story.findText()[0].appliedParagraphStyle = Style_1;
    //==> this will change a paraStyle of 1st occurence of story to "Style_1".
    If other cases...
    You would need to be more accurate.
    rgds

  • Need  Bookmark creation script for Paragraph style. Anybody can help me pl?

    Need  Bookmark creation script for Paragraph style. Anybody can help me pl?

    Hi hasvi,
    I wrote a similar script which creates a bookmark on each page in the "main" text frame at the begining of the frame (the 1st insertion point). Here I attached the script and a couple of sample documents: before and after. It's more complex than what you want but you can use it as a starting point. In fact, you have to find a certain paragraph style, loop through every found item and insert a bookmark, say, at the beginning of the found text.
    The dialog box
    Bookmarks added
    Regards,
    Kas

  • Need help writing host program using LabView.

    Need help writing host program using LabView.
    Hello,
    I'm designing a HID device, and I want to write a host program using National Instrument's LabView. NI doesn't have any software support for USB, so I'm trying to write a few C dll files and link them to Call Library Functions. NI has some documentation on how to do this, but it's not exactly easy reading.
    I've written a few C console programs (running Win 2K) using the PC host software example for a HID device from John Hyde's book "USB by design", and they run ok. From Hyde's example program, I've written a few functions that use a few API functions each. This makes the main program more streamlined. The functions are; GetHIDPath, OpenHID, GetHIDInfo, Writ
    eHID, ReadHIC, and CloseHID. As I mentioned, my main program runs well with these functions.
    My strategy is to make dll files from these functions and load them into LabView Call Library Functions. However, I'm having a number of subtle problems in trying to do this. The big problem I'm having now are build errors when I try to build to a dll.
    I'm writing this post for a few reasons. First, I'm wondering if there are any LabView programmers who have already written USB HID host programs, and if they could give me some advice. Or, I would be grateful if a LabView or Visual C programmer could help me work out the programming problems that I'm having with my current program. If I get this LabView program working I would be happy to share it. I'm also wondering if there might already be any USB IHD LabView that I could download.
    Any help would be appreciated.
    Regards, George
    George Dorian
    Sutter Instruments
    51 Digital DR.
    Novato, CA 94949
    USA
    [email protected]
    m
    (415) 883-0128
    FAX (415) 883-0572

    George may not answer you.  He hasn't been online here for almost eight years.
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice

  • Need Help Writing Server side to submit form via API

    Hey
    I need help writing a serverside application to submit
    information via API to a separate server.
    I have a client that uses constant contact for email
    campaigns. We want to add to her website a form taht submits the
    information needed to subscribe to her email list, to constant
    contact via API.
    FORM.asp :: (i got this one under control)
    name
    email
    and submits to serverside.asp
    SERVERSIDE.ASP
    In serverside.asp i need to have
    the API URL
    (https://api.constantcontact.com/0.1/API_AddSiteVisitor.jsp)
    username (of the constant contact account)
    password (of the constant contact account)
    name (submited from form.asp)
    email (submitted from form.asp)
    redirect URL (confirm.asp)
    Can anyone help get me going in the right direction?
    i have tried several things i found on the net and just cant
    get anyone to work correctly.
    One main issue i keep having is that if i get it to submit to
    the API url correctly - i get a success code, it doesnt redirect to
    the page i am trying to redirect to.
    ASP or ASP.NET code would be find.
    THANKS
    sam

    > This does require server side programming.
    > if you dont know what that is, then you dont know the
    answer to my question. I
    > know what i need to do - i just dont know HOW to do it.
    If you are submitting a form to a script on a remote server,
    and letting
    that script load content to the browser, YOU have no control
    over what it
    loads UNLESS there is some command you can send it that it
    will understand.
    No amount of ASP on your server is going to change what the
    remote script
    does.
    http://www.constantcontact.com/services/api/index.jsp
    they only allow their customers to see the instructions for
    the API so i
    can't search to see IF there is a redirect you can send with
    the form info.
    But posts on their support board say that there is.
    Alan
    Adobe Community Expert, dreamweaver
    http://www.adobe.com/communities/experts/

  • Need help writing small program!

    Hi. I'm learning Java programming, and I need help writing a small program. Please someone help me.
    Directions:
    Create a program called CerealCompare using an if-then-else structure that obtains the price and number of ounces in a box for two boxes of cereal. The program should then output which box costs less per ounce.

    class CerealCompare {
        public static void main(String[] args) {
            // your code goes here
    }Hope that helps.
    P.S. Java does not have an if-then-else statement.

  • I am in need of ai script for arcing text

    i am in need of ai script for arcing text

    A little vague aren't we… Is this the kind of arcing you mean? Text along a curve or do you mean distorting into an arch like some plug-in can?
    #target illustrator
    var doc = app.activeDocument;
    doc.defaultFilled = false, doc.defaultStroked = true;
    var textPath = doc.pathItems.ellipse( 0, 0, doc.width, doc.height );
    textPath.pathPoints[3].selected = PathPointSelection.ANCHORPOINT;
    app.cut();
    doc.selection = null;
    app.redraw();
    var tp = doc.textFrames.pathText( doc.pathItems[0], 0, 0, TextOrientation.HORIZONTAL );
    tp.textRange.paragraphAttributes.justification = Justification.CENTER;
    tp.textRange.characterAttributes.size = 60;
    tp.contents = 'I am in need of ai script…';
    var tpd = tp.duplicate();
    tpd.translate( 0, -150 );
    tpd.textRange.characterAttributes.size = 90;
    tpd.contents = '…for arcing text?';

  • I need help choosing RAM for MSI PM8PM-V 7222 VER. 2.0 MB

    hey everyone as you know my MB is in the subject and i need help buying ram for it. on the MSI website it says it can surpport max. 2GB so 1GB in each slot? it only has 2 slots also what DDR and MHZ clock, DRAM fequency etc does the ram have to be and both single sided or double sided or 1 single and 1 double?
    thanks

    Quote
    also what DDR and MHZ clock, DRAM fequency etc does the ram have to be
    http://global.msi.eu/index.php?func=proddesc&maincat_no=1&prod_no=1039
    Quote
    • Supports DDR2 533/400 memory interface.
    Check the memory support list for best compatibility:
    http://global.msi.eu/uploads/test_report/TR10_1039.pdf

  • I need help finding cases for the ipod touch thrid gen help.

    i need help finding case for ipod touch thrid gen help.

    - Try another cable.
    - Try another USB port
    - Inspect the dock connector on the iPod for bent or missing contacts, foreign material, corroded contacts, broken, missing or cracked plastic.
    - Try on another computer. Just backup a couple of times. Do not sync.

Maybe you are looking for

  • 3GS Voice Chat Application

    Hey I'm looking for a specific voice chat application. I would like an app that would allow multiple users to join a chat room and talk via voice with each other on the iphone. I would like this app to also allow users on a PC to join into this voice

  • Big time library trouble

    Help me out please.....having trouble with my iTunes library let me give a bit of background.... I just bought a new Samsung laptop....running windows 7. Previously, I was running iTunes on my old HP laptop, running WIndows XP. I backed up my iTunes

  • Why does installing Flash Drive fail every time on my MacBook Pro (OS X 10.5.8)?

    For many months now, I have not been able to update my Flash Drive. I finally tried to uninstall it. I followed the uninstall guidelines on this site. I still cannot install Flash Drive. The same failed message report pops up that popped up when I wo

  • How can I deploy a .pkg file that requires a folder with customizations?

    I am attempting to deploy a pkg file with ARD.  The customizations for this pkg are stored in a folder called custom.  If the PKG and Custom folder are in the same directory the Pacage will apply those customizations.  What would be the best way to a

  • How to disable graphics and/or java in Firefox 23.0.1

    In previous versions of Firefox, like 19.0, it is a simply matter to disable graphics and/or java. Simply go to Firefox "Tools", "Options", "Content", unclick "Load images Automatically", unclick "Enable JavaScript". With Firefox 23.0.1, I don't see