Question

conversion LARGE_INTEGER to _int64; or operating with LARGE_INTEGER

Asked by: jutzki

Hello,
I am trying to use an alternative Sleep() function in C that has a better solution. (The solution of sleep() is only 15 ms). I need 1 ms. My teacher gave me the above code


static double esperaH(double *temp) //sleep in ms
{

bool resultado;
unsigned _int64 *now, *frec,goal;
//LARGE_INTEGER *now, *frec, goal;

now = (unsigned _int64*)calloc(1,sizeof(now));
//now = (LARGE_INTEGER*)calloc(1,sizeof(now));
resultado = QueryPerformanceCounter(now);

frec = (unsigned _int64*)calloc(1,sizeof(frec));
//frec = (LARGE_INTEGER*)calloc(1,sizeof(frec));
resultado=QueryPerformanceFrequency(frec);

goal = *now + (unsigned _int64)((*temp*1.0e-3)*(*frec));

while (goal > *now)
resultado = QueryPerformanceCounter(now);
return ((double)*now/(double)*frec)*1000;
//return ((LARGE_INTEGER)*now/(LARGE_INTEGER)*frec)*1000;

}

if I compile it like this I get the following warnings/errors:
--------------------Configuration: pci 1784 configuration5 - Win32 Debug--------------------
Compiling...
pci 1784 configuration5.cpp
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(110) : warning C4305: 'argument' : truncation from 'const double' to 'float'
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(55) : warning C4101: 'num_contador' : unreferenced local variable
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(387) : warning C4244: 'argument' : conversion from 'unsigned long' to 'unsigned short', possible loss of data
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(426) : warning C4244: 'argument' : conversion from 'const double' to 'unsigned char', possible loss of data
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(728) : error C2664: 'QueryPerformanceCounter' : cannot convert parameter 1 from 'unsigned __int64 *' to 'union _LARGE_INTEGER *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(732) : error C2664: 'QueryPerformanceFrequency' : cannot convert parameter 1 from 'unsigned __int64 *' to 'union _LARGE_INTEGER *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(737) : error C2664: 'QueryPerformanceCounter' : cannot convert parameter 1 from 'unsigned __int64 *' to 'union _LARGE_INTEGER *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
Error executing cl.exe.

pci 1784 configuration5.obj - 3 error(s), 4 warning(s)


If I compile it using _int

If I use the other code version:

static double esperaH(double *temp) //sleep in ms
{

bool resultado;
//unsigned _int64 *now, *frec,goal;
LARGE_INTEGER *now, *frec, goal;

//now = (unsigned _int64*)calloc(1,sizeof(now));
now = (LARGE_INTEGER*)calloc(1,sizeof(now));
resultado = QueryPerformanceCounter(now);

//frec = (unsigned _int64*)calloc(1,sizeof(frec));
frec = (LARGE_INTEGER*)calloc(1,sizeof(frec));
resultado=QueryPerformanceFrequency(frec);

goal = *now + (LARGE_INTEGER)((*temp*1.0e-3)*(*frec));

while (goal > *now)
resultado = QueryPerformanceCounter(now);
return ((double)*now/(double)*frec)*1000;
//return ((LARGE_INTEGER)*now/(LARGE_INTEGER)*frec)*1000;

}

...I get the following compiler warnings/errors:
--------------------Configuration: pci 1784 configuration5 - Win32 Debug--------------------
Compiling...
pci 1784 configuration5.cpp
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(110) : warning C4305: 'argument' : truncation from 'const double' to 'float'
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(55) : warning C4101: 'num_contador' : unreferenced local variable
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(387) : warning C4244: 'argument' : conversion from 'unsigned long' to 'unsigned short', possible loss of data
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(426) : warning C4244: 'argument' : conversion from 'const double' to 'unsigned char', possible loss of data
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(728) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(732) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(734) : error C2677: binary '*' : no global operator defined which takes type 'union _LARGE_INTEGER' (or there is no acceptable conversion)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(736) : error C2678: binary '>' : no operator defined which takes a left-hand operand of type 'union _LARGE_INTEGER' (or there is no acceptable conversion)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(736) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.

pci 1784 configuration5.obj - 3 error(s), 6 warning(s)


I don´t know what to do. The Query-fungtions seem to only accept large_integer, but large_integer cannot operate with +,*,/
Does anyone have a suggestion what could be my error or how I could solve my problem?? I would be so glad since I am very unexperienced in programming.

Judith

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-02-22 at 05:43:35ID22406155
Tags

large_integer

Topics

C / C++ / C# Editors and IDEs

,

C++ Builder

,

Microsoft Visual C++

Participating Experts
3
Points
500
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Using Int64 as a bit container
    Hi there, I've recently written a DES (cryptography) in Delphi which uses a record to store each block (this record contains a BitCount field and an array of Bytes for the actual data). This record-method is really slow because I access these bits ALOT in sevral nested l...
  2. Casting an unsigned __int64  to a _variant_t(VT_DEC…
    I'm currently working on a project storing unsigned _int64 (BigInt) values in a database and accessing this data via ADO This is returned to me as a variant containing a DECIMAL datatype. What I need to know is how do I go about casting and assigning an __unsigned int64 t...
  3. convert from unsigned char to float
    Hi, I have a .wav audio file which I read in as an array of 'unsigned char' values, I then need to convert these values to float so that I can perform an FFT on them, how would I do this? Is it as simples as (float)unsignedCharValue ??
  4. Convert char* to unsigned __int64
    Hello guys I am trying to convert a char* variable to an unsigned __int64 variable. I found the documentation on strtoul and tried this code: char *string, *stopstring; unsigned long ul; string = "3.1415926This stopped it"; ul = strtoul( string, &stop...
  5. Read/Write Int64 from/to the registry
    I can't seem to find any function that reads/writes Int64 numbers from/to the registry. I currently have a number there that was saved using WriteInteger (2167501190) that reads as -2127466106. It's odd that a number greater that Integer was written using WriteInteger. ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: KdoPosted on 2007-02-22 at 06:14:16ID: 18587543


Hi Judith,

It's a bit of a challenge to take these error messages (which cover the entire program or module) and relate them to this small piece of code.  Still, I think that I can tie them together.  :)

One of the things that you can do to simplify the program is to use scalar variables instead of pointers within the function.  Here's a quick edit to demonstrate:

static double esperaH(double *temp) //sleep in ms
{

bool resultado;
//unsigned _int64 *now, *frec,goal;
LARGE_INTEGER now, frec, goal;

resultado = QueryPerformanceCounter(&now);

resultado=QueryPerformanceFrequency(&frec);

goal = now + (LARGE_INTEGER)((*temp*1.0e-3)*(frec));

while (goal > now)
resultado = QueryPerformanceCounter(&now);
return ((double)now/(double)frec)*1000;
//return ((LARGE_INTEGER)now/(LARGE_INTEGER)frec)*1000;

}


I'm curious as to why you pass a pointer to a double instead of just passing a double.

Kent

 

by: JoseParrotPosted on 2007-02-22 at 06:33:35ID: 18587814

Hi, Judith,

By looking just to the syntax, all the warnings can be ignored.
The real problem is with  unsigned __int64.
The conversion from unsigned __int64 to double isn't implemmented in the compiler.

Specificaly to Builder C++, seems the question is still open, as you may look at:
http://qc.borland.com/wc/qcmain.aspx?d=2254

The workaround is to use __int64 as signed, if you don't really need the most significant bit.
Let me suggest also to clean the code, as it uses intensively type conversions, with no apparent mandatory reason (as per the piece of code post in the question).

Jose

 

by: jutzkiPosted on 2007-02-22 at 06:34:02ID: 18587819

Hello Kent,
thank you for viewing my question. I am only concerned about the error messages in this part of the program because the rest works...using solution I still get the same error messages...that the operators is not defined for the LARGE_INTEGER_TYPE:


C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(110) : warning C4305: 'argument' : truncation from 'const double' to 'float'
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(55) : warning C4101: 'num_contador' : unreferenced local variable
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(387) : warning C4244: 'argument' : conversion from 'unsigned long' to 'unsigned short', possible loss of data
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(426) : warning C4244: 'argument' : conversion from 'const double' to 'unsigned char', possible loss of data
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(752) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(754) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(756) : error C2677: binary '*' : no global operator defined which takes type 'union _LARGE_INTEGER' (or there is no acceptable conversion)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(758) : error C2678: binary '>' : no operator defined which takes a left-hand operand of type 'union _LARGE_INTEGER' (or there is no acceptable conversion)
C:\datos\judith\proyecto_judith\pci 1784\pci 1784 configuration5.cpp(758) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.

pci 1784 configuration5.obj - 3 error(s), 6 warning(s)

Qour question: I only copied an existing code...I am afraid my programming knowledge is so poor that I cannot even see a real difference.

Judith

 

by: jutzkiPosted on 2007-02-22 at 06:42:56ID: 18587891

Hello Jose,
I tried to use the signed _int64 instead of unsigned int_64 but it gives me the same errors...
cannot convert parameter 1 from '__int64 *' to 'union _LARGE_INTEGER *'
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
??
Judith

 

by: KdoPosted on 2007-02-22 at 06:52:42ID: 18587983

Hi Judith,

_LARGE_INTEGER is a structure or union.  It is not a base type like int, float, etc.

Dereference the 64-bit values.


static double esperaH(double *temp) //sleep in ms
{

  bool resultado;
  LARGE_INTEGER now, frec, goal;

  resultado = QueryPerformanceCounter(&now);

  resultado=QueryPerformanceFrequency(&frec);

  goal.QuadPart = now.QuadPart + (LONGLONG)(((*temp)*(1.0e-3))*(frec.QuadPart));

  while (goal.QuadPart > now.QuadPart)
    resultado = QueryPerformanceCounter(&now);
  return ((double)now.QuadPart/(double)frec.QuadPart)*1000;
}


Kent

 

by: jutzkiPosted on 2007-02-22 at 07:09:27ID: 18588157

Hi Kent,
thank you very much...now I don´t get errors anymore...
1 more question...when I want to compile the whole program now the compiler tells me the following:

pci 1784 configuration5.obj : error LNK2001: unresolved external symbol _mexPrintf
Debug/pci 1784 configuration5.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

pci 1784 configuration5.exe - 2 error(s), 0 warning(s)

although I put #include "mex.h"....I think I didn´t include a library maybe??
Judith

 

by: KdoPosted on 2007-02-22 at 07:18:48ID: 18588248


mexPrintf can come from any of several places.  (MATLAB is probably the biggest reference to it.)

You're going to need to link the correct library.  Not knowing your application, I don't have any idea what the library is.


Kent

 

by: jutzkiPosted on 2007-02-22 at 07:28:18ID: 18588349

#include <Afxwin.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <time.h>
#include <winsock2.h>
#include <mmsystem.h>
#include <math.h>
#include "driver.h"
#include "os.h"
#include "dask.h"
#include "jr3ft.h"
#include "stdafx.h"

#include <windows.h>
#include "mex.h"
#include <windows.h>
#include <windef.h>
#include <stdio.h>
#include <conio.h>
#include "ADS1784.h"

void ConfiguraTargetes(void);
void TancaTarjetes(void);
void EscriuTau(int quin, float valor);
long Devicehandler1720;
static double esperaH(double temp);


void main(void)
{      
    BYTE byBoard_ID;
UCHAR byCounter,num_contador;
      DWORD status;
      DWORD lpCntValue;
      CHAR  *texto;

      
    byBoard_ID = 0;
    byCounter = CNT_0;
      
      
    printf(" The card selected is %d   ", byBoard_ID);
      if (byCounter==CNT_0)
      {
         texto="Contador 0";
      }
      printf(" \n\n %s   ", texto);
    ConfiguraTargetes();
      
      printf("empiezo el bucle");
      
      int i;      
      i=0;
      lpCntValue=0;
      while (i<1000) //&& (lpCntValue < 0xfffee920))
      {

            status = P1784CounterRead(byBoard_ID,byCounter,&lpCntValue);
      
      if (status != ERROR_SUCCESS) //ERROR_SUCCESS = function success
    {
            printf("\n\n La lectura es NO OK");
            if (status = CounterNumErr)
            {
                  printf("\n\n Counter number Error");
                  printf("\n Press any key to exit....");
                  getch();//espera que se pulse una tecla e inmediamente después devuelve un valor
                  exit(1); //se puede salir anticipadamente de un programa usando la función exit()
            }
                  else
                  {
                        printf("\n\n Input parameter error!");
                        getch();//espera que se pulse una tecla e inmediamente después devuelve un valor
                        exit(1); //se puede salir anticipadamente de un programa usando la función exit()
                  }
      }
      
      printf("\n\n Counter value read: %x  ", lpCntValue);
      
      EscriuTau(1,0.2);

      //if (lpCntValue >= 0xfec3d74b) //counter too high; girar clockwise in order to disminuir contador
      //      EscriuTau(1,-0.2); //para girar en otro dirección
      //if (lpCntValue<= 0xfec2b441) //counter too little; girar anticlockwise in order to aumentar contador
      //      EscriuTau(1,0.2); //para girar en otro dirección
      
      
            i++;
      

      esperaH(10.0);

      }
      //printf("\n\n Counter value read: %x  ", lpCntValue);
      /*
      printf("\n Press any key to exit....");
      
      getch();
      TancaTarjetes();
      exit(1);
      */

      TancaTarjetes();
      
      
}




void ConfiguraTargetes()
{
      //CONFIGURAR TARJETA PCI 1784:

      BYTE byBoard_ID;

      byBoard_ID = 0;
      //Check how many PCI-1784 card in this system:
      //P1784DevAvailable(DWORD *lpReturnBoardStatus) //evy. in EscriuTau!!!


      //PCI1784 available status.  Bit value : 0 for non avaliable, 1 for available        
      //*lpReturnBoardStatus:  

      //Value   Meaning  
      //Bit 0        For board ID 0
      //Bit 1        For board ID 1
      //Bit 2   For board ID 2
      //.....
 
      //Bit 15  For board ID15



   
   
   
      


      //Device Open:
      //Initial the PCI-1784 and system resource for operation.
      //Before using any P1784 DLL function except P1784DevAvailable,
      //user must use this function first.
      //BYTE byBoard_ID;
      DWORD dwReturnCode;
      dwReturnCode = P1784DevOpen(byBoard_ID);
      //status1784 = P1784DevOpen(BYTE 0); // (BYTE byBoard_ID) O-15

      if (dwReturnCode != ERROR_SUCCESS) //ERROR_SUCCESS = function success
    {
        printf("\n\n Program Fail %4x",dwReturnCode);
        printf("\n Board 0 doesn't exsit !");
        printf("\n Press any key to exit....");
        getch();//espera que se pulse una tecla e inmediamente después devuelve un valor
        exit(1); //se puede salir anticipadamente de un programa usando la función exit()
    }


      //Configure counters:


      //counter mode:
//Select counter mode, PCI1784 counter have 5 modes. X1,X2,X4 is quadrature input mode.
//Quadrature input consists of two square wave inputs(A and B) which are 90 degree out of phase.
      //The PCI1784 counts the square wave transitions and determines the direction by comparing channel A
      //is leading channel B or vice versa.
      
      

      UCHAR byCounter;
      //      Counter 0
      byCounter=CNT_0;

      P1784SelectCntMode(byBoard_ID,byCounter,X4);  //(BYTE byBoard_ID, BYTE byCounter, WORD wMode)
      //P1784SelectCntMode(0,CNT_1,X4);
      //P1784SelectCntMode(0,CNT_2,X4);
      //P1784SelectCntMode(0,CNT_3,X4);
      
      
      //BYTE CNT_0, CNT_1, CNT_2, CNT_3;
      //WORD X4;

      //wMode:
      //DISABLE:PCI1784 will not accept input, but you can still access all its registers.
      //X1:The counter will increment (or decrement) the counter whenever a rising edge occurs on input channel A
       //X2:The counter will increment (or decrement) the counter whenever a rising edge occurs or falling edge
      //   occurs on input channel A
       //X4:The counter will increment (or decrement) the counter whenever a rising or falling edge occurs on input channel A or B
       //_2_PULSE:In 2 pulse mode the PCI1784 uses two input pulses as counting sources: one for clockwise(CW)
      //               and one for counterclockwise(CCW)counting. The counter will decrement whenever a rising edge
      //               occurs on channel A. It will increment whenever a rising edge occurs on channel B
       //_1_PULSE:In pulse/direction mode the PCI1784 uses one input line(A) for pulse input and one line (B) for direction.
      //               If channel B is high (1), the counter will decrement whenever a rising edge occurs on channel A.
      //               If channel B is low (0), the counter will increment whenever a rising edge occurs on channel A.
 

      //CNT_0: Select counter 0
      //CNT_1: Select counter 1
      //CNT_2: Select counter 2
      //CNT_3: Select counter 3




      //counter latch:
      //When you read a counter, you are actually reading a value latched into a buffer.
      //The PCI1784 provides five different latching modes, only one of which is active
      //at any given time. Make sure that you know which latching mode is current one
      //whenever you read the counter. Otherwise, you may read an old value or one that
      //was latched at a different time that you except.
      
      
      P1784SetLatchSource(0,CNT_0,SOFTWARE);//(BYTE byBoard_ID, BYTE byCounter, WORD wLatchSource)  
      //P1784SetLatchSource(0,CNT_1,SOFTWARE);
      //P1784SetLatchSource(0,CNT_2,SOFTWARE);
      //P1784SetLatchSource(0,CNT_3,SOFTWARE);

      //wLatchSource:
      //SOFTWARE:Whenever you read a channels data registers, the counter values will be latched in buffer.
      //               The S/W latch will  only take effect when you read the the counter.
       //INDEX:A rising edge on the channels index input line will latch the channels counter value
       //TIMER:The Card latches the counter value on a rising edge of pulses from the cards on-board timer.
       //DI_0:A rising edge on the boards DI0 line will latch the counter value for the channel.
      //DI_1:A rising edge on the boards DI1 line will latch the counter value for the channel.
      //DI_2:A rising edge on the boards DI2 line will latch the counter value for the channel.
      //DI_3:A rising edge on the boards DI3 line will latch the counter value for the channel.
 


      //counter lock overflow:
      //Set counter locked when counter overflows.
      
      P1784EnableOverFlowLock(0,CNT_0,FALSE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)
      //P1784EnableOverFlowLock(0,CNT_1,FALSE);
      //P1784EnableOverFlowLock(0,CNT_2,FALSE);
      //P1784EnableOverFlowLock(0,CNT_3,FALSE);
      //bValue:
      //Specifies counter locked when counter overflows.
      //If TRUE, counter locked when counter overflows.
      //If FALSE, Counter continues counting (wraps over) when counter overflow.


      //counter lock underflow:
      //Set counter locked when counter underflows.

      P1784EnableUnderFlowLock(0,CNT_0,FALSE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)  
      //P1784EnableUnderFlowLock(0,CNT_1,FALSE);
      //P1784EnableUnderFlowLock(0,CNT_2,FALSE);
      //P1784EnableUnderFlowLock(0,CNT_3,FALSE);

      //bValue:
      //Specifies counter locked when counter underflows.
      //If TRUE, counter locked when counter underflows. If FALSE,
      //Counter continues counting (wraps over) when counter underflows.
      //reset value:

      //Set the reset value when counter reset.
      P1784EnableResetValue(0,CNT_0,FALSE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)
      //P1784EnableResetValue(0,CNT_1,FALSE);
      //P1784EnableResetValue(0,CNT_1,FALSE);
      //P1784EnableResetValue(0,CNT_3,FALSE);

            
      //bValue:
      //The reset value when counter reset.
      //If TRUE, the reset value is 80000000h. If FALSE, it is  00000000h



      //digital filter:

      //digital filter clock:
      //Set digital filter clock frequency.
      DWORD wMode;
      wMode = _8MHZ;
      P1784SelectFilterClock(byBoard_ID,wMode);//(BYTE byBoard_ID, DWORD wMode);  

      //wMode: sampling clock mode; _8MHZ/_4MHZ/_2MHZ/_1MHZ


      //enable digital filter:
      //Set quadrature input (channel A, B) with digital filter.
      
      P1784EnableDigitalFilter(0,CNT_0,TRUE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)  
      //P1784EnableDigitalFilter(0,CNT_1,TRUE);
      //P1784EnableDigitalFilter(0,CNT_2,TRUE);
      //P1784EnableDigitalFilter(0,CNT_3,TRUE);

      //bValue:
      //Specifies quadrature input frequency with digital filter.
      //If TRUE, Quadrature input frequency with digital filter.
      //If FALSE, quadrature input frequency without digital filter



      
      
      
      

      
      
      //Configure Timer:
      


      //Set divide value and timer base of Timer.
      //When you use Timer Latch on a rising edge of pulses from the cards on board timer,
      //You can set timer cycle periods from 0.02 ms to 51 seconds.
      //The cycle time is the product of the timer base period and a multiplier.
      //Timer base periods are 0.02, 0.2, 2, 20 or 200 ms. The multiplier ranges from 1 to 255.
      //The divider can range from 1 to 255.


      P1784SetTimerPeriod(0,0.5,_5KHZ);//(BYTE byBoard_ID, BYTE byDivideValue, BYTE byTimerBase)  
      

      //byDivideValue:The divider value 1-255; to create different timer periods!!
      //byTimerBase:
      //_50KHZ:Timer base periods is 0.02ms
      //_5KHZ :Timer base periods is 0.2ms
      //_500HZ:Timer base periods is 2ms
      //_50HZ :Timer base periods is 20ms
      //_5HZ  :Timer base periods is 200ms
      //example:
      //For example, to set a timer period of 20 ms, you would set the timer base to 1ms and the divider to 20.
      //That is :
      //Timer period = Base Time * divider
      //20 ms = 1 ms * 20




      



      //Configure Comparator:
      
            
      //Read current comparator.
      //DWORD *dwCntValue;


      //P1784ComparatorRead(byBoard_ID,CNT_0,dwCntValue); //(BYTE byBoard_ID, BYTE byCounter, DWORD *dwCntValue)
      //P1784ComparatorRead(byBoard_ID,CNT_1,dwCntValue);
      //P1784ComparatorRead(byBoard_ID,CNT_2,dwCntValue);
      //P1784ComparatorRead(byBoard_ID,CNT_3,dwCntValue);

      //*dwCntValue:The value of the data in current comparator


      
      //Set the comparing condition. Comparing condition consists of 2 parts,
      //P1784SetTriggerComp(0,CNT_0,0,1000);//(BYTE byBoard_ID, BYTE byCounter, BYTE byMode, ULONG dwData)
      //P1784SetTriggerComp(0,CNT_0,0,1000);
      //P1784SetTriggerComp(0,CNT_0,0,1000);
      //P1784SetTriggerComp(0,CNT_0,0,1000);

      //byCounter:CNT_0 or CNT_1 or CNT_2 or CNT_3
      //comparing mode:0 for ">", 1 for "<"      
      //dwData:the value to be compared


      

      

      //Event monitor/interrupt:

      //Enable or Disable the event for 4 counters; starts or stops counter operation
      //P1784EnableEvent(byBoard_ID,CNT_0,1);//(BYTE byBoard_ID, BYTE byCounter, WORD wIntSource)


      //wIntSource:The interrupt event source
      //CNT_OVERFLOW:counter overflow
      //CNT_UNDERFLOW:counter underflow
      //CNT_INDEX:counter index in
      //DI0_TRI:DI0 input, When set this value, the byCounter parameter will be ignore.
      //DI1_TRI:DI1 input, When set this value, the byCounter parameter will be ignore.
      //DI2_TRI:DI2 input, When set this value, the byCounter parameter will be ignore.
      //DI3_TRI:DI3 input, When set this value, the byCounter parameter will be ignore.
      //CNT_OVERCOMP:counter over-compare
      //CNT_UNDERCOMP:counter under-compare
      //INT_TIMER:The card's on-board timer's pulse come
      //INT_ALL:All of the events enabled
 





        

      //You can use the CheckEvent function to monitor the event status.
      //The CheckEvent function is a synchronous method to check the event.
      //You have to specify a period for the time out.
      //When an event occurs, it returns the event status(dwRetEventStatus) immediately.
      //If no event occurs in this period, it returns a time out error.  
      //It uses an efficient polling method to check the event.
      //Your CPU can then simultaneously perform other functions.

      //checks status; when it reaches a count it will return a hardware event

      //DWORD *dwRetEventStatus;
      //DWORD dwMillisecond;
      //P1784CheckEvent(byBoard_ID,dwRetEventStatus,dwMillisecond);
      
      //dwMillisecond: Time-out interval in milliseconds
      //*dwRetEventStatus: Current Event status; The status of interrupt. When some interrupt comes into existence,
      //                               the relative bit of Interrupt status register will become 1, otherwise 0.  
      //The status of interrupt. When some interrupt comes into existence, the relative bit of Interrupt status register
      //will become 1, otherwise 0.  

      //D15  D14  D13  D12  D11  D10  D9  D8  D7  D6  D5  D4  D3  D2  D1  D0  
      //DI3  DI2  DI1  DI0  IX3  IX2  IX1 IX0 UN3 UN2 UN1 UN0 OV3 OV2 OV1 OV0

      //D31  D30  D29  D28  D27  D26  D25 D24  D23  D22  D21  D20  D19  D18  D17  D16  
      //IF                   TM                                   UC3  UC2  UC1  UC0  OC3  OC2  OC1  OC0
 
      //1. OVn = Counter overflow flag
      //2. UNn = counter underflow flag
      //3. IXn = Index input flag
      //4. DIn = Digital input flag
      //5. OCn = Counter over compare register flag
      //6. UCn = Counter under compare register flag
      //7. TM  = Timer pulse flag
      //8. IF = Interrupt flag
      //   (n = 0 to 3)


      


      //Digital Input/Output functions:

      //Digital Input:
      //BYTE *lpReturnValue;
      //P1784DI(0,lpReturnValue);//(BYTE byBoard_ID, BYTE *lpReturnValue)  

      //*lpReturnValue: Data received (0/1) from each 4 input channel

      

      //Set Digital Output Mode:
      //The function is to change the digital output mode into Indicated or normal output, and control the pulse width.
      //BYTE byDOMode;
      //byDOMode = 0; // set DO mode to normal
      //dwReturnCode = P1784SetDOMode(byBoard_ID,byDOMode);
      //P1784SetDOMode(0,0);//(BYTE byBoard_ID, BYTE byDOMode);  

       //byDOMode:
      //D7      D6      D5  D4  D3  D2  D1  D0
      //DM3 DM2 DM1 DM0 LE3 LE2 LE1 LE0
 
      
      //1. LEn = Digital output level control
      //      0        Pulse with counter clock
      //      1        Level with clear interrupt
      //2. DMn = Digital output mode control
      //      0        Normal
      //      1           Indicated
      //      (n = 0 to 3)

      //if(dwReturnCode != ERROR_SUCCESS)
    //{
      //  printf("\n Set DO mode fail %4x",dwReturnCode);
        //printf("\n Press any key to exit....");
        //getch();
        //exit(1);
    //}







      //Get Digital Output Status:
      //P1784GetDOStatus(byBoard_ID,lpReturnValue);

      //*lpReturnValue: Output;The output data status of each channel

      
      //digital output/output data:
      //BYTE byWriteValue;
      //byWriteValue = 1; //in bits: 00000001
      //P1784DO(byBoard_ID,byWriteValue);//(BYTE byBoard_ID, BYTE byWriteValue)
      //byWriteValue:input; output data
 
      // Output data
   
    //while(byWriteValue<=8)
    //{
      //  printf("\nDigital Output Data : 0x%1x",byWriteValue);

        // Write Digital Output Data
        //dwReturnCode = P1784DO(byBoard_ID,byWriteValue);
        //if (dwReturnCode != ERROR_SUCCESS)
        //{
          //  printf("\n\n Program Fail %4x",dwReturnCode);
            //printf("\n Press any to exit....");
            //getch();
            //exit(1);
        //}
        //printf("\n Output data is %d",byDOValue);
        //byWriteValue=byWriteValue<<1; //1 shifts one position to the left: 00000010-->00000100-->00001000 usw.
    //}

    //printf("\n\n Press any key to quit\n");
    //getch();





      


      //CONFIGURAR TARJETA PCI 1720:

      int status1720;
      status1720 = DRV_DeviceOpen(0,&Devicehandler1720); //tarjeta 0 advantechautomation-->device manager --> Advantech device manager




}
 



      





void TancaTarjetes(void)
{      
      
      //PARA TARJETA PCI 1784:
      //Release the PCI-1784 and system resource, before end application,
      //user has to use this function to release the resource from system.  
      BYTE byBoard_ID;



    byBoard_ID = 0;
      DWORD status;
      status = P1784DevClose(byBoard_ID); //(BYTE byBoard_ID) 0-15
      if (status != ERROR_SUCCESS)
    {
        printf("\n\n Program Fail %4x",status);
        printf("\n Press any key to exit....");
        getch();
        exit(1);
    }
 


      //PARA TARJETA PCI 1720:
      for(int i=0;i<4;i++)
      {
        EscriuTau(i,0.0);
      }
      
      DRV_DeviceClose(&Devicehandler1720);

      

}


//FEED SPECIFIC CHANNEL WITH SPECIFIC VOLTAGE:

void EscriuTau(int quin, float valor)
{
      // tarjeta 1720
      PT_AOVoltageOut ptAOVoltageOut;


      if(valor>10.0) valor=10.0;
      if(valor<-10.0) valor=-10.0;

      //AO_VWriteChannel(Devicehandler6208,quin,valor);

      ptAOVoltageOut.chan = quin;
//      ptAOVoltageOut.chan = 0;
      ptAOVoltageOut.OutputValue = valor;
//      ptAOVoltageOut.OutputValue = -2.2;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);

      /*ptAOVoltageOut.chan = 0;
      ptAOVoltageOut.OutputValue = -7.33;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);

            ptAOVoltageOut.chan = 1;
      ptAOVoltageOut.OutputValue = 8.11;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);

            ptAOVoltageOut.chan = 2;
      ptAOVoltageOut.OutputValue = -9.22;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);*/
}

/*
static double esperaH(double *temp) //sleep in ms
{

bool resultado;
//unsigned _int64 *now, *frec,goal;
//LARGE_INTEGER *now, *frec, goal;
signed _int64 *now, *frec,goal;


now = (signed _int64*)calloc(1,sizeof(now));
//now = (LARGE_INTEGER*)calloc(1,sizeof(now));
resultado = QueryPerformanceCounter(now);

frec = (signed _int64*)calloc(1,sizeof(frec));
//frec = (LARGE_INTEGER*)calloc(1,sizeof(frec));
resultado=QueryPerformanceFrequency(frec);

goal = *now + (signed _int64)((*temp*1.0e-3)*(*frec));

while (goal > *now)
resultado = QueryPerformanceCounter(now);
return ((double)*now/(double)*frec)*1000;
//return ((LARGE_INTEGER)*now/(LARGE_INTEGER)*frec)*1000;

}
*/


/*
static double esperaH(double *temp) //sleep in ms
{

bool resultado;
//unsigned _int64 *now, *frec,goal;
LARGE_INTEGER now, frec, goal;

resultado = QueryPerformanceCounter(&now);

resultado=QueryPerformanceFrequency(&frec);

goal = now + (LARGE_INTEGER)((*temp*1.0e-3)*(frec));

while (goal > now)
resultado = QueryPerformanceCounter(&now);
return ((double)now/(double)frec)*1000;
//return ((LARGE_INTEGER)now/(LARGE_INTEGER)frec)*1000;

}

*/



static double esperaH(double temp) //sleep in ms
{

  bool resultado;
  LARGE_INTEGER now, frec, goal;

  resultado = QueryPerformanceCounter(&now);

  resultado=QueryPerformanceFrequency(&frec);

  goal.QuadPart = now.QuadPart + (LONGLONG)(((temp)*(1.0e-3))*(frec.QuadPart));

  while (goal.QuadPart > now.QuadPart)
    resultado = QueryPerformanceCounter(&now);
  return ((double)now.QuadPart/(double)frec.QuadPart)*1000;
}

 

by: jutzkiPosted on 2007-02-22 at 07:29:33ID: 18588367

#include <Afxwin.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <time.h>
#include <winsock2.h>
#include <mmsystem.h>
#include <math.h>
#include "driver.h"
#include "os.h"
#include "dask.h"
#include "jr3ft.h"
#include "stdafx.h"
#include <windows.h>
#include "mex.h"
#include <windows.h>
#include <windef.h>
#include <stdio.h>
#include <conio.h>
#include "ADS1784.h"

void ConfiguraTargetes(void);
void TancaTarjetes(void);
void EscriuTau(int quin, float valor);
long Devicehandler1720;
static double esperaH(double temp);


void main(void)
{      
      
    BYTE byBoard_ID;
UCHAR byCounter,num_contador;
      DWORD status;
      DWORD lpCntValue;
      CHAR  *texto;

      //lpCntValue = new DWORD;
      //BYTE byDOValue;
    //DWORD dwReturnCode;

    byBoard_ID = 0;
    byCounter = CNT_0;
      
      //status=-1;  // Initialization to a diiferent value that the values returned by the DLL
      
      // byDOValue = 0x05;

    printf(" The card selected is %d   ", byBoard_ID);
      if (byCounter==CNT_0)
      {
         texto="Contador 0";
      }
      printf(" \n\n %s   ", texto);
    ConfiguraTargetes();
      
      printf("empiezo el bucle");
      
      int i;      
      i=0;
      lpCntValue=0;
      while (i<1000) //&& (lpCntValue < 0xfffee920))
      {

      //status=P1784CounterRead(byBoard_ID,byCounter,&lpCntValue); //(BYTE byBoard_ID, BYTE byCounter, DWORD *lpCntValue)
      status = P1784CounterRead(byBoard_ID,byCounter,&lpCntValue);
      
      if (status != ERROR_SUCCESS) //ERROR_SUCCESS = function success
    {
            printf("\n\n La lectura es NO OK");
            if (status = CounterNumErr)
            {
                  printf("\n\n Counter number Error");
                  printf("\n Press any key to exit....");
                  getch();//espera que se pulse una tecla e inmediamente después devuelve un valor
                  exit(1); //se puede salir anticipadamente de un programa usando la función exit()
            }
                  else
                  {
                        printf("\n\n Input parameter error!");
                        getch();//espera que se pulse una tecla e inmediamente después devuelve un valor
                        exit(1); //se puede salir anticipadamente de un programa usando la función exit()
                  }
      }
      
      printf("\n\n Counter value read: %x  ", lpCntValue);
      
      EscriuTau(1,0.2);

      //if (lpCntValue >= 0xfec3d74b) //counter too high; girar clockwise in order to disminuir contador
      //      EscriuTau(1,-0.2); //para girar en otro dirección
      //if (lpCntValue<= 0xfec2b441) //counter too little; girar anticlockwise in order to aumentar contador
      //      EscriuTau(1,0.2); //para girar en otro dirección
      
      
            i++;
      

      esperaH(10.0);

      }
      //printf("\n\n Counter value read: %x  ", lpCntValue);
      /*
      printf("\n Press any key to exit....");
      
      getch();
      TancaTarjetes();
      exit(1);
      */

      TancaTarjetes();
      
      //Device open

    //dwReturnCode = P1784DevOpen(byBoard_ID);
    //if (dwReturnCode != ERROR_SUCCESS) //ERROR_SUCCESS = function success
    //{
      //      printf("\n\n Program Fail %4x",dwReturnCode);
      //      printf("\n Board 0 doesn't exsit !");
      //  printf("\n Press any key to exit....");
    //    getch();//espera que se pulse una tecla e inmediamente después devuelve un valor
    //    exit(1); //se puede salir anticipadamente de un programa usando la función exit()
    //}
    // Set DO mode to normal
    //dwReturnCode = P1784SetDOMode(byBoard_ID,0);
    //if(dwReturnCode != ERROR_SUCCESS)
    //{
      //      printf("\n Set DO mode fail %4x",dwReturnCode);
      //  printf("\n Press any key to exit....");
        //getch();
       // exit(1);
    //}


      //Digital Input:
      //BYTE *lpReturnValue;
      //DWORD DigitalInput;
      //DigitalInput = P1784DI(0,lpReturnValue);//(BYTE byBoard_ID, BYTE *lpReturnValue)  

      //*lpReturnValue: Data received (0/1) from each 4 input channel
      //printf("\nDigital Input Data:  %4x", DigitalInput);
      //printf("\nDigital Input Data  ");
      //Read current comparator.
      //DWORD *dwCntValue;
      //DWORD ComparatorRead;

      //P1784ComparatorRead(byBoard_ID,CNT_0,dwCntValue); //(BYTE byBoard_ID, BYTE byCounter, DWORD *dwCntValue)
      //P1784ComparatorRead(byBoard_ID,CNT_1,dwCntValue);
      //P1784ComparatorRead(byBoard_ID,CNT_2,dwCntValue);
      //P1784ComparatorRead(byBoard_ID,CNT_3,dwCntValue);

      //*dwCntValue:The value of the data in current comparator
      //printf("\nCurrent comparator data: ",ComparatorRead);




    // Output data
    //byDOValue=1;//in bits: 00000001
    //while(byDOValue<=8)
    //{
      //      printf("\nDigital Output Data : 0x%1x",byDOValue);

            //Write Digital Output Data
      //      dwReturnCode = P1784DO(byBoard_ID,byDOValue);
      //  if (dwReturnCode != ERROR_SUCCESS)
     
            //{
            //      printf("\n\n Program Fail %4x",dwReturnCode);
            //      printf("\n Press any to exit....");
                  //  getch();
           // exit(1);
        //}
        //printf("\n Output data is %d",byDOValue);
        //byDOValue=byDOValue<<1; //1 shifts one position to the left: 00000010-->00000100-->00001000 usw.
    //}

    //printf("\n\n Press any key to quit\n");
    //getch();
      
      //Sleep(5000);

      //void TancaTarjetes();

     //Device close
    //dwReturnCode = P1784DevClose(byBoard_ID);
    //if (dwReturnCode != ERROR_SUCCESS)
      //{
      //  printf("\n\n Program Fail %4x",dwReturnCode);
        //printf("\n Press any key to exit....");
        //getch();
        //exit(1);
    //}

}




void ConfiguraTargetes()
{
      //CONFIGURAR TARJETA PCI 1784:

      BYTE byBoard_ID;

      byBoard_ID = 0;
      //Check how many PCI-1784 card in this system:
      //P1784DevAvailable(DWORD *lpReturnBoardStatus) //evy. in EscriuTau!!!


      //PCI1784 available status.  Bit value : 0 for non avaliable, 1 for available        
      //*lpReturnBoardStatus:  

      //Value   Meaning  
      //Bit 0        For board ID 0
      //Bit 1        For board ID 1
      //Bit 2   For board ID 2
      //.....
 
      //Bit 15  For board ID15



   
   
   
      


      //Device Open:
      //Initial the PCI-1784 and system resource for operation.
      //Before using any P1784 DLL function except P1784DevAvailable,
      //user must use this function first.
      //BYTE byBoard_ID;
      DWORD dwReturnCode;
      dwReturnCode = P1784DevOpen(byBoard_ID);
      //status1784 = P1784DevOpen(BYTE 0); // (BYTE byBoard_ID) O-15

      if (dwReturnCode != ERROR_SUCCESS) //ERROR_SUCCESS = function success
    {
        printf("\n\n Program Fail %4x",dwReturnCode);
        printf("\n Board 0 doesn't exsit !");
        printf("\n Press any key to exit....");
        getch();//espera que se pulse una tecla e inmediamente después devuelve un valor
        exit(1); //se puede salir anticipadamente de un programa usando la función exit()
    }


      //Configure counters:


      //counter mode:
      //Select counter mode, PCI1784 counter have 5 modes. X1,X2,X4 is quadrature input mode.
      //Quadrature input consists of two square wave inputs(A and B) which are 90 degree out of phase.
      //The PCI1784 counts the square wave transitions and determines the direction by comparing channel A
      //is leading channel B or vice versa.
      
      

      UCHAR byCounter;
      //      Counter 0
      byCounter=CNT_0;

      P1784SelectCntMode(byBoard_ID,byCounter,X4);  //(BYTE byBoard_ID, BYTE byCounter, WORD wMode)
      //P1784SelectCntMode(0,CNT_1,X4);
      //P1784SelectCntMode(0,CNT_2,X4);
      //P1784SelectCntMode(0,CNT_3,X4);
      
      
      //BYTE CNT_0, CNT_1, CNT_2, CNT_3;
      //WORD X4;

      //wMode:
      //DISABLE:PCI1784 will not accept input, but you can still access all its registers.
      //X1:The counter will increment (or decrement) the counter whenever a rising edge occurs on input channel A
       //X2:The counter will increment (or decrement) the counter whenever a rising edge occurs or falling edge
      //   occurs on input channel A
       //X4:The counter will increment (or decrement) the counter whenever a rising or falling edge occurs on input channel A or B
       //_2_PULSE:In 2 pulse mode the PCI1784 uses two input pulses as counting sources: one for clockwise(CW)
      //               and one for counterclockwise(CCW)counting. The counter will decrement whenever a rising edge
      //               occurs on channel A. It will increment whenever a rising edge occurs on channel B
       //_1_PULSE:In pulse/direction mode the PCI1784 uses one input line(A) for pulse input and one line (B) for direction.
      //               If channel B is high (1), the counter will decrement whenever a rising edge occurs on channel A.
      //               If channel B is low (0), the counter will increment whenever a rising edge occurs on channel A.
 

      //CNT_0: Select counter 0
      //CNT_1: Select counter 1
      //CNT_2: Select counter 2
      //CNT_3: Select counter 3




      //counter latch:
      //When you read a counter, you are actually reading a value latched into a buffer.
      //The PCI1784 provides five different latching modes, only one of which is active
      //at any given time. Make sure that you know which latching mode is current one
      //whenever you read the counter. Otherwise, you may read an old value or one that
      //was latched at a different time that you except.
      
      
      P1784SetLatchSource(0,CNT_0,SOFTWARE);//(BYTE byBoard_ID, BYTE byCounter, WORD wLatchSource)  
      //P1784SetLatchSource(0,CNT_1,SOFTWARE);
      //P1784SetLatchSource(0,CNT_2,SOFTWARE);
      //P1784SetLatchSource(0,CNT_3,SOFTWARE);

      //wLatchSource:
      //SOFTWARE:Whenever you read a channels data registers, the counter values will be latched in buffer.
      //               The S/W latch will  only take effect when you read the the counter.
       //INDEX:A rising edge on the channels index input line will latch the channels counter value
       //TIMER:The Card latches the counter value on a rising edge of pulses from the cards on-board timer.
       //DI_0:A rising edge on the boards DI0 line will latch the counter value for the channel.
      //DI_1:A rising edge on the boards DI1 line will latch the counter value for the channel.
      //DI_2:A rising edge on the boards DI2 line will latch the counter value for the channel.
      //DI_3:A rising edge on the boards DI3 line will latch the counter value for the channel.
 


      //counter lock overflow:
      //Set counter locked when counter overflows.
      
      P1784EnableOverFlowLock(0,CNT_0,FALSE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)
      //P1784EnableOverFlowLock(0,CNT_1,FALSE);
      //P1784EnableOverFlowLock(0,CNT_2,FALSE);
      //P1784EnableOverFlowLock(0,CNT_3,FALSE);
      //bValue:
      //Specifies counter locked when counter overflows.
      //If TRUE, counter locked when counter overflows.
      //If FALSE, Counter continues counting (wraps over) when counter overflow.


      //counter lock underflow:
      //Set counter locked when counter underflows.

      P1784EnableUnderFlowLock(0,CNT_0,FALSE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)  
      //P1784EnableUnderFlowLock(0,CNT_1,FALSE);
      //P1784EnableUnderFlowLock(0,CNT_2,FALSE);
      //P1784EnableUnderFlowLock(0,CNT_3,FALSE);

      //bValue:
      //Specifies counter locked when counter underflows.
      //If TRUE, counter locked when counter underflows. If FALSE,
      //Counter continues counting (wraps over) when counter underflows.
      //reset value:

      //Set the reset value when counter reset.
      P1784EnableResetValue(0,CNT_0,FALSE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)
      //P1784EnableResetValue(0,CNT_1,FALSE);
      //P1784EnableResetValue(0,CNT_1,FALSE);
      //P1784EnableResetValue(0,CNT_3,FALSE);

            
      //bValue:
      //The reset value when counter reset.
      //If TRUE, the reset value is 80000000h. If FALSE, it is  00000000h



      //digital filter:

      //digital filter clock:
      //Set digital filter clock frequency.
      DWORD wMode;
      wMode = _8MHZ;
      P1784SelectFilterClock(byBoard_ID,wMode);//(BYTE byBoard_ID, DWORD wMode);  

      //wMode: sampling clock mode; _8MHZ/_4MHZ/_2MHZ/_1MHZ


      //enable digital filter:
      //Set quadrature input (channel A, B) with digital filter.
      
      P1784EnableDigitalFilter(0,CNT_0,TRUE);//(BYTE byBoard_ID, BYTE byCounter, BOOL bValue)  
      //P1784EnableDigitalFilter(0,CNT_1,TRUE);
      //P1784EnableDigitalFilter(0,CNT_2,TRUE);
      //P1784EnableDigitalFilter(0,CNT_3,TRUE);

      //bValue:
      //Specifies quadrature input frequency with digital filter.
      //If TRUE, Quadrature input frequency with digital filter.
      //If FALSE, quadrature input frequency without digital filter



      
      
      
      

      
      
      //Configure Timer:
      


      //Set divide value and timer base of Timer.
      //When you use Timer Latch on a rising edge of pulses from the cards on board timer,
      //You can set timer cycle periods from 0.02 ms to 51 seconds.
      //The cycle time is the product of the timer base period and a multiplier.
      //Timer base periods are 0.02, 0.2, 2, 20 or 200 ms. The multiplier ranges from 1 to 255.
      //The divider can range from 1 to 255.


      P1784SetTimerPeriod(0,0.5,_5KHZ);//(BYTE byBoard_ID, BYTE byDivideValue, BYTE byTimerBase)  
      

      //byDivideValue:The divider value 1-255; to create different timer periods!!
      //byTimerBase:
      //_50KHZ:Timer base periods is 0.02ms
      //_5KHZ :Timer base periods is 0.2ms
      //_500HZ:Timer base periods is 2ms
      //_50HZ :Timer base periods is 20ms
      //_5HZ  :Timer base periods is 200ms
      //example:
      //For example, to set a timer period of 20 ms, you would set the timer base to 1ms and the divider to 20.
      //That is :
      //Timer period = Base Time * divider
      //20 ms = 1 ms * 20




      



      //Configure Comparator:
      
            
      //Read current comparator.
      //DWORD *dwCntValue;


      //P1784ComparatorRead(byBoard_ID,CNT_0,dwCntValue); //(BYTE byBoard_ID, BYTE byCounter, DWORD *dwCntValue)
      //P1784ComparatorRead(byBoard_ID,CNT_1,dwCntValue);
      //P1784ComparatorRead(byBoard_ID,CNT_2,dwCntValue);
      //P1784ComparatorRead(byBoard_ID,CNT_3,dwCntValue);

      //*dwCntValue:The value of the data in current comparator


      
      //Set the comparing condition. Comparing condition consists of 2 parts,
      //P1784SetTriggerComp(0,CNT_0,0,1000);//(BYTE byBoard_ID, BYTE byCounter, BYTE byMode, ULONG dwData)
      //P1784SetTriggerComp(0,CNT_0,0,1000);
      //P1784SetTriggerComp(0,CNT_0,0,1000);
      //P1784SetTriggerComp(0,CNT_0,0,1000);

      //byCounter:CNT_0 or CNT_1 or CNT_2 or CNT_3
      //comparing mode:0 for ">", 1 for "<"      
      //dwData:the value to be compared


      

      

      //Event monitor/interrupt:

      //Enable or Disable the event for 4 counters; starts or stops counter operation
      //P1784EnableEvent(byBoard_ID,CNT_0,1);//(BYTE byBoard_ID, BYTE byCounter, WORD wIntSource)


      //wIntSource:The interrupt event source
      //CNT_OVERFLOW:counter overflow
      //CNT_UNDERFLOW:counter underflow
      //CNT_INDEX:counter index in
      //DI0_TRI:DI0 input, When set this value, the byCounter parameter will be ignore.
      //DI1_TRI:DI1 input, When set this value, the byCounter parameter will be ignore.
      //DI2_TRI:DI2 input, When set this value, the byCounter parameter will be ignore.
      //DI3_TRI:DI3 input, When set this value, the byCounter parameter will be ignore.
      //CNT_OVERCOMP:counter over-compare
      //CNT_UNDERCOMP:counter under-compare
      //INT_TIMER:The card's on-board timer's pulse come
      //INT_ALL:All of the events enabled
 





        

      //You can use the CheckEvent function to monitor the event status.
      //The CheckEvent function is a synchronous method to check the event.
      //You have to specify a period for the time out.
      //When an event occurs, it returns the event status(dwRetEventStatus) immediately.
      //If no event occurs in this period, it returns a time out error.  
      //It uses an efficient polling method to check the event.
      //Your CPU can then simultaneously perform other functions.

      //checks status; when it reaches a count it will return a hardware event

      //DWORD *dwRetEventStatus;
      //DWORD dwMillisecond;
      //P1784CheckEvent(byBoard_ID,dwRetEventStatus,dwMillisecond);
      
      //dwMillisecond: Time-out interval in milliseconds
      //*dwRetEventStatus: Current Event status; The status of interrupt. When some interrupt comes into existence,
      //                               the relative bit of Interrupt status register will become 1, otherwise 0.  
      //The status of interrupt. When some interrupt comes into existence, the relative bit of Interrupt status register
      //will become 1, otherwise 0.  

      //D15  D14  D13  D12  D11  D10  D9  D8  D7  D6  D5  D4  D3  D2  D1  D0  
      //DI3  DI2  DI1  DI0  IX3  IX2  IX1 IX0 UN3 UN2 UN1 UN0 OV3 OV2 OV1 OV0

      //D31  D30  D29  D28  D27  D26  D25 D24  D23  D22  D21  D20  D19  D18  D17  D16  
      //IF                   TM                                   UC3  UC2  UC1  UC0  OC3  OC2  OC1  OC0
 
      //1. OVn = Counter overflow flag
      //2. UNn = counter underflow flag
      //3. IXn = Index input flag
      //4. DIn = Digital input flag
      //5. OCn = Counter over compare register flag
      //6. UCn = Counter under compare register flag
      //7. TM  = Timer pulse flag
      //8. IF = Interrupt flag
      //   (n = 0 to 3)


      


      //Digital Input/Output functions:

      //Digital Input:
      //BYTE *lpReturnValue;
      //P1784DI(0,lpReturnValue);//(BYTE byBoard_ID, BYTE *lpReturnValue)  

      //*lpReturnValue: Data received (0/1) from each 4 input channel

      

      //Set Digital Output Mode:
      //The function is to change the digital output mode into Indicated or normal output, and control the pulse width.
      //BYTE byDOMode;
      //byDOMode = 0; // set DO mode to normal
      //dwReturnCode = P1784SetDOMode(byBoard_ID,byDOMode);
      //P1784SetDOMode(0,0);//(BYTE byBoard_ID, BYTE byDOMode);  

       //byDOMode:
      //D7      D6      D5  D4  D3  D2  D1  D0
      //DM3 DM2 DM1 DM0 LE3 LE2 LE1 LE0
 
      
      //1. LEn = Digital output level control
      //      0        Pulse with counter clock
      //      1        Level with clear interrupt
      //2. DMn = Digital output mode control
      //      0        Normal
      //      1           Indicated
      //      (n = 0 to 3)

      //if(dwReturnCode != ERROR_SUCCESS)
    //{
      //  printf("\n Set DO mode fail %4x",dwReturnCode);
        //printf("\n Press any key to exit....");
        //getch();
        //exit(1);
    //}







      //Get Digital Output Status:
      //P1784GetDOStatus(byBoard_ID,lpReturnValue);

      //*lpReturnValue: Output;The output data status of each channel

      
      //digital output/output data:
      //BYTE byWriteValue;
      //byWriteValue = 1; //in bits: 00000001
      //P1784DO(byBoard_ID,byWriteValue);//(BYTE byBoard_ID, BYTE byWriteValue)
      //byWriteValue:input; output data
 
      // Output data
   
    //while(byWriteValue<=8)
    //{
      //  printf("\nDigital Output Data : 0x%1x",byWriteValue);

        // Write Digital Output Data
        //dwReturnCode = P1784DO(byBoard_ID,byWriteValue);
        //if (dwReturnCode != ERROR_SUCCESS)
        //{
          //  printf("\n\n Program Fail %4x",dwReturnCode);
            //printf("\n Press any to exit....");
            //getch();
            //exit(1);
        //}
        //printf("\n Output data is %d",byDOValue);
        //byWriteValue=byWriteValue<<1; //1 shifts one position to the left: 00000010-->00000100-->00001000 usw.
    //}

    //printf("\n\n Press any key to quit\n");
    //getch();





      


      //CONFIGURAR TARJETA PCI 1720:

      int status1720;
      status1720 = DRV_DeviceOpen(0,&Devicehandler1720); //tarjeta 0 advantechautomation-->device manager --> Advantech device manager




}
 



      





void TancaTarjetes(void)
{      
      
      //PARA TARJETA PCI 1784:
      //Release the PCI-1784 and system resource, before end application,
      //user has to use this function to release the resource from system.  
      BYTE byBoard_ID;



    byBoard_ID = 0;
      DWORD status;
      status = P1784DevClose(byBoard_ID); //(BYTE byBoard_ID) 0-15
      if (status != ERROR_SUCCESS)
    {
        printf("\n\n Program Fail %4x",status);
        printf("\n Press any key to exit....");
        getch();
        exit(1);
    }
 


      //PARA TARJETA PCI 1720:
      for(int i=0;i<4;i++)
      {
        EscriuTau(i,0.0);
      }
      
      DRV_DeviceClose(&Devicehandler1720);

      

}


//FEED SPECIFIC CHANNEL WITH SPECIFIC VOLTAGE:

void EscriuTau(int quin, float valor)
{
      // tarjeta 1720
      PT_AOVoltageOut ptAOVoltageOut;


      if(valor>10.0) valor=10.0;
      if(valor<-10.0) valor=-10.0;

      //AO_VWriteChannel(Devicehandler6208,quin,valor);

      ptAOVoltageOut.chan = quin;
//      ptAOVoltageOut.chan = 0;
      ptAOVoltageOut.OutputValue = valor;
//      ptAOVoltageOut.OutputValue = -2.2;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);

      /*ptAOVoltageOut.chan = 0;
      ptAOVoltageOut.OutputValue = -7.33;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);

            ptAOVoltageOut.chan = 1;
      ptAOVoltageOut.OutputValue = 8.11;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);

            ptAOVoltageOut.chan = 2;
      ptAOVoltageOut.OutputValue = -9.22;
    DRV_AOVoltageOut(Devicehandler1720, (LPT_AOVoltageOut)&ptAOVoltageOut);*/
}

/*
static double esperaH(double *temp) //sleep in ms
{

bool resultado;
//unsigned _int64 *now, *frec,goal;
//LARGE_INTEGER *now, *frec, goal;
signed _int64 *now, *frec,goal;


now = (signed _int64*)calloc(1,sizeof(now));
//now = (LARGE_INTEGER*)calloc(1,sizeof(now));
resultado = QueryPerformanceCounter(now);

frec = (signed _int64*)calloc(1,sizeof(frec));
//frec = (LARGE_INTEGER*)calloc(1,sizeof(frec));
resultado=QueryPerformanceFrequency(frec);

goal = *now + (signed _int64)((*temp*1.0e-3)*(*frec));

while (goal > *now)
resultado = QueryPerformanceCounter(now);
return ((double)*now/(double)*frec)*1000;
//return ((LARGE_INTEGER)*now/(LARGE_INTEGER)*frec)*1000;

}
*/


/*
static double esperaH(double *temp) //sleep in ms
{

bool resultado;
//unsigned _int64 *now, *frec,goal;
LARGE_INTEGER now, frec, goal;

resultado = QueryPerformanceCounter(&now);

resultado=QueryPerformanceFrequency(&frec);

goal = now + (LARGE_INTEGER)((*temp*1.0e-3)*(frec));

while (goal > now)
resultado = QueryPerformanceCounter(&now);
return ((double)now/(double)frec)*1000;
//return ((LARGE_INTEGER)now/(LARGE_INTEGER)frec)*1000;

}

*/



static double esperaH(double temp) //sleep in ms
{

  bool resultado;
  LARGE_INTEGER now, frec, goal;

  resultado = QueryPerformanceCounter(&now);

  resultado=QueryPerformanceFrequency(&frec);

  goal.QuadPart = now.QuadPart + (LONGLONG)(((temp)*(1.0e-3))*(frec.QuadPart));

  while (goal.QuadPart > now.QuadPart)
    resultado = QueryPerformanceCounter(&now);
  return ((double)now.QuadPart/(double)frec.QuadPart)*1000;
}

 

by: jutzkiPosted on 2007-02-22 at 07:49:09ID: 18588580

Sorry for posting it many times...
it is a program to configure 1 card which is an digital analog converter and one card which is the counter of a motor. I need the Sleep or the EsperaH function to get counter values every milisecond...
The problem is EsperaH()

Judith

 

by: KdoPosted on 2007-02-22 at 07:56:16ID: 18588653


How are you compiling this?  (What command and options?)

 

by: jutzkiPosted on 2007-02-22 at 08:05:09ID: 18588740

I compile it with the Microsoft Visual C++ Compiling button...I do`n´t use command or options actually

 

by: KdoPosted on 2007-02-22 at 08:16:53ID: 18588896



>  I don´t use command or options actually

Actually, you do.   :)   The IDE compiles the source program based on flags and options that are selected within the IDE instead of on a command line.  You just don't see them (or have to rememeber them or deal with them, etc.)

Some place in the GUI (IDE) are options to include other source program, libraries, etc.  


Your program doesn't call mexPrint directly so it must be assumed that one of the library routines that you're loading is responsible for it getting called.  What is defined in mex.h that you need?

 

by: jutzkiPosted on 2007-02-22 at 08:24:22ID: 18588964

This is the mex.h file...but I cannot find mexPrint in this file...

/*
 * @(#)mex.h    generated by: makeheader 4.21  Mon Aug 16 03:25:12 2004
 *
 *            built from:      ../../src/include/copyright.h
 *                        ../../src/include/pragma_interface.h
 *                        mex_typedefs.h
 *                        ./fmexapi.cpp
 *                        ./fmexapiv5.cpp
 *                        ./globals.cpp
 *                        ./mexapi.cpp
 *                        ./mexapiv4.cpp
 *                        ./mexapiv5.cpp
 *                        ./mexcbk.cpp
 *                        ./mexdispatch.cpp
 *                        ./mexintrf.cpp
 *                        mexdbg.h
 */

#ifndef mex_h
#define mex_h


/*
 * Copyright 1984-2003 The MathWorks, Inc.
 * All Rights Reserved.
 */



/* Copyright 2003 The MathWorks, Inc. */

/*
 * Prevent g++ from making copies of vtable and typeinfo data
 * in every compilation unit.  By allowing for only one, we can
 * save space and prevent some situations where the linker fails
 * to coalesce them properly into a single entry.
 *
 * References:
 *    http://gcc.gnu.org/onlinedocs/gcc/Vague-Linkage.html#Vague%20Linkage
 *    http://gcc.gnu.org/onlinedocs/gcc/C---Interface.html
 */

#ifdef __cplusplus
#  ifdef GLNX86
#    pragma interface
#  endif
#endif



/* Copyright 1999-2001 The MathWorks, Inc. */

/* $Revision: 1.7.4.1 $ */
#ifndef mex_typedefs_h
#define mex_typedefs_h
typedef struct impl_info_tag *MEX_impl_info;

#include "matrix.h"

typedef struct mexGlobalTableEntry_Tag
{
    const char *name;             /* The name of the global */
    mxArray    **variable;        /* A pointer to the variable */
} mexGlobalTableEntry, *mexGlobalTable;

#if defined(MSWIND)
#define cicompare(s1,s2) utStrcmpi((s1),(s2))
#else
#define cicompare(s1,s2) strcmp((s1),(s2))
#endif
#define cscompare(s1,s2) strcmp((s1),(s2))

typedef struct mexFunctionTableEntry_tag {
  const char *  name;
  mxFunctionPtr f;
  int           nargin;
  int           nargout;
  struct _mexLocalFunctionTable *local_function_table;
} mexFunctionTableEntry, *mexFunctionTable;

typedef struct _mexLocalFunctionTable {
  size_t           length;
  mexFunctionTable entries;
} _mexLocalFunctionTable, *mexLocalFunctionTable;

typedef struct {
  void (*initialize)(void);
  void (*terminate)(void);
} _mexInitTermTableEntry, *mexInitTermTableEntry;

#define MEX_INFORMATION_VERSION 1

typedef struct {
  int                   version;
  int                   file_function_table_length;
  mexFunctionTable      file_function_table;
  int                   global_variable_table_length;
  mexGlobalTable        global_variable_table;
  int                   npaths;
  const char **         paths;
  int                   init_term_table_length;
  mexInitTermTableEntry init_term_table;
} _mex_information, *mex_information;

typedef mex_information(*fn_mex_file)(void);

typedef void (*fn_clean_up_after_error)(void);
typedef const char *(*fn_simple_function_to_string)(mxFunctionPtr f);

typedef void (*fn_mex_enter_mex_library)(mex_information x);
typedef fn_mex_enter_mex_library fn_mex_exit_mex_library;

typedef mexLocalFunctionTable (*fn_mex_get_local_function_table)(void);
typedef mexLocalFunctionTable (*fn_mex_set_local_function_table)(mexLocalFunctionTable);

#endif


/*
 * This header file "mex.h" declares all the types, macros and
 * functions necessary to interface mex files with the current
 * version of MATLAB.  See the release notes for information on
 * supporting syntax from earlier versions.
 */  
#include "matrix.h"

#include <stdio.h>



#ifdef __cplusplus
extern "C" {
#endif
/*
 * mexFunction is the user defined C routine which is called upon invocation
 * of a mex function.
 */
void mexFunction(
    int           nlhs,           /* number of expected outputs */
    mxArray       *plhs[],        /* array of pointers to output arguments */
    int           nrhs,           /* number of inputs */
    const mxArray *prhs[]         /* array of pointers to input arguments */
);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Issue error message and return to MATLAB prompt
 */
extern void mexErrMsgTxt(
    const char      *error_msg      /* string with error message */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Issue formatted error message with corresponding error identifier and return to MATLAB
 * prompt.
 */
extern void mexErrMsgIdAndTxt(
    const char * identifier, /* string with error message identifier */
    const char * err_msg,    /* string with error message printf-style format */
    ...                      /* any additional arguments */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Invoke an unidentified warning. Such warnings can only be affected by the M-code
 * 'warning * all', since they have no specific identifier. See also mexWarnMsgIdAndTxt.
 */
extern void mexWarnMsgTxt(
    const char      *warn_msg      /* string with warning message */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Invoke a warning with message identifier 'identifier' and message derived from 'fmt' and
 * subsequent arguments. The warning may either get printed as is (if it is set to 'on'), or
 * not actually get printed (if set to 'off'). See 'help warning' in MATLAB for more
 * details.
 */
extern void mexWarnMsgIdAndTxt(
    const char * identifier,    /* string with warning message identifer */
    const char * warn_msg,      /* string with warning message printf-style format */
    ...                         /* any additional arguments */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * mex equivalent to MATLAB's "disp" function
 */
extern int mexPrintf(
    const char      *fmt,      /* printf style format */
    ...                        /* any additional arguments */
    );
#ifdef __cplusplus
}
#endif


#define printf mexPrintf

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Remove all components of an array plus the array header itself
 * from MATLAB's memory allocation list.  The array will now
 * persist between calls to the mex function.  To destroy this
 * array, you will need to explicitly call mxDestroyArray().
 */
extern void mexMakeArrayPersistent(
    mxArray *pa              /* pointer to array */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Remove memory previously allocated via mxCalloc from MATLAB's
 * memory allocation list.  To free this memory, you will need to
 * explicitly call mxFree().
 */
extern void mexMakeMemoryPersistent(void *ptr);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Look up a function and return an opaque handle for use with
 * mexCallMATLABFunction.
 */
extern void mexGetFunctionHandle(void);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Call a function whose handle was determined by mexGetFunctionHandle.
 */
extern void mexCallMATLABFunction(void);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Register a function pointer as a MATLAB-callable function.
 */
extern void mexRegisterFunction(void);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * mex equivalent to MATLAB's "set" function
 */
extern int mexSet(double handle, const char *property, mxArray *value);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/* API interface which mimics the "get" function */
extern const mxArray *mexGet(double handle, const char *property);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * call MATLAB function
 */
extern int mexCallMATLAB(
    int            nlhs,                  /* number of expected outputs */
    mxArray      *plhs[],            /* pointer array to outputs */
    int            nrhs,                  /* number of inputs */
    mxArray      *prhs[],            /* pointer array to inputs */
    const char      *fcn_name            /* name of function to execute */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * set or clear mexCallMATLAB trap flag (if set then an error in  
 * mexCallMATLAB is caught and mexCallMATLAB will return a status value,
 * if not set an error will cause control to revert to MATLAB)
 */
extern void mexSetTrapFlag(int flag);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Perform in-place subscript assignment.
 */
extern void mexSubsAssign(
      mxArray *plhs, /* pointer to lhs, to be modified in-place */
      const mxArray *prhs, /* pointer to rhs */
      const mxArray *subs[], /* array of subscripts for lhs */
      int nsubs     /* number os subscripts */
      );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Retrieve a specified subset of an array.
 */
extern mxArray *mexSubsReference(
      const mxArray *prhs, /* pointer to rhs */
      const mxArray *subs[], /* array of subscripts for rhs */
      int nsubs /* number of subscripts */
      );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Print an assertion-style error message and return control to the
 * MATLAB command line.
 */
extern void mexPrintAssertion(
            const char *test,
            const char *fname,
            int linenum,
            const char *message);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Tell whether or not a mxArray is in MATLAB's global workspace.
 */
extern bool mexIsGlobal(const mxArray *pA);
#ifdef __cplusplus
}
#endif


#define mexGetGlobal()    mexGetGlobal_is_obsolete
#define mxSetString()     mxSetString_is_obsolete
#define mxSetDispMode()   mxSetDispMode_is_obsolete
#define mexGetMatrixPtr() mexGetMatrixPtr_is_obsolete
#define mexGetMatrix()    mexGetMatrix_is_obsolete
#define mexPutMatrix()    mexPutMatrix_is_obsolete
#define mexPutFull()      mexPutFull_is_obsolete
#define mexGetFull()      mexGetFull_is_obsolete
#define mexGetEps()       mexGetEps_is_obsolete
#define mexGetInf()       mexGetInf_is_obsolete
#define mexGetNaN()       mexGetNaN_is_obsolete
#define mexIsFinite()     mexIsFinite_is_obsolete
#define mexIsInf()        mexIsInf_is_obsolete
#define mexIsNaN()        mexIsNaN_is_obsolete


/*
 * mexAddFlops is no longer allowed.  
 */
#define mexAddFlops(x) mexAddFlops_is_obsolete

#if defined(V5_COMPAT)
#define mexPutArray(parray, workspace) mexPutVariable(workspace, mxGetName(parray), parray)
#define mexGetArray(name, workspace) mexGetVariable(workspace, name)
#define mexGetArrayPtr(name, workspace) mexGetVariablePtr(workspace, name)
#else
#define mexPutArray() mexPutArray_is_obsolete
#define mexGetArray() mexGetArray_is_obsolete
#define mexGetArrayPtr() mexGetArrayPtr_is_obsolete
#endif /* defined(V5_COMPAT) */

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Place a copy of the array value into the specified workspace with the
 * specified name
 */
extern int mexPutVariable(
    const char *workspace,
    const char *name,
    const mxArray *parray            /* matrix to copy */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * return a pointer to the array value with the specified variable
 * name in the specified workspace
 */
extern const mxArray *mexGetVariablePtr(
    const char *workspace,
    const char *name            /* name of symbol */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * return a copy of the array value with the specified variable
 * name in the specified workspace
 */
extern mxArray *mexGetVariable(
    const char      *workspace,            
    const char  *name                /* name of variable in question */
    );
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Lock a MEX-function so that it cannot be cleared from memory.
 */
extern void mexLock(void);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Unlock a locked MEX-function so that it can be cleared from memory.
 */
extern void mexUnlock(void);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Return true if the MEX-function is currently locked, false otherwise.
 */
extern bool mexIsLocked(void);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Return the name of a the MEXfunction currently executing.
 */
extern const char *mexFunctionName(void);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Parse and execute MATLAB syntax in string.  Returns zero if successful,
 * and a non zero value if an error occurs.
 */
extern int mexEvalString(
   const char *str         /* matlab command string */
);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Register Mex-file's At-Exit function (accessed via MEX callback)
 */
extern int mexAtExit(
    void      (*exit_fcn)(void)
    );
#ifdef __cplusplus
}
#endif


#define NEW_DISPATCHER_EVAL_CALLER 1


/* Copyright 1996-1999 The MathWorks, Inc. */

/* $Revision: 1.9.4.1 $ */
#ifdef ARGCHECK

#include "mwdebug.h" /* Prototype _d versions of API functions */

#define mexAtExit(exitfcn)                         mexAtExit_d(exitfcn, __FILE__, __LINE__)
#define mexCallMATLAB(nlhs, plhs, nrhs, prhs, fcn) mexCallMATLAB_d(nlhs, plhs, nrhs, prhs, fcn, __FILE__, __LINE__)
#define mexErrMsgTxt(errmsg)                  mexErrMsgTxt_d(errmsg, __FILE__, __LINE__)
#define mexEvalString(str)                         mexEvalString_d(str, __FILE__, __LINE__)
#define mexGet(handle, property)             mexGet_d(handle, property, __FILE__, __LINE__)
#define mexGetVariable(workspace, name)       mexGetVariable_d(workspace, name, __FILE__, __LINE__)
#define mexGetVariablePtr(workspace, name)      mexGetVariablePtr_d(workspace, name, __FILE__, __LINE__)
#define mexIsGlobal(pa)                 mexIsGlobal_d(pa, __FILE__, __LINE__)
#define mexMakeArrayPersistent(pa)             mexMakeArrayPersistent_d(pa, __FILE__, __LINE__)              
#define mexMakeMemoryPersistent(ptr)       mexMakeMemoryPersistent_d(ptr, __FILE__, __LINE__)
#define mexPutVariable(workspace, name, pa)       mexPutVariable_d(workspace, name, pa, __FILE__, __LINE__)
#define mexSet(handle, property, value) mexSet_d(handle, property, value, __FILE__, __LINE__)
#define mexSetTrapFlag(value)           mexSetTrapFlag_d(value, __FILE__, __LINE__)
#define mexSubsAssign(plhs, sub, nsubs, rhs)    mexSubsAssign_d(plhs, sub, nsubs, rhs, __FILE__, __LINE__)
#define mexSubsReference(prhs, sub, nsubs)    mexSubsReference_d(prhs, sub, nsubs, __FILE__, __LINE__)
#define mexWarnMsgTxt(str)                         mexWarnMsgTxt_d(str, __FILE__, __LINE__)
#endif

#endif /* mex_h */

 

by: KdoPosted on 2007-02-22 at 08:43:24ID: 18589154


  :)

In matrix.h is a curious definition:

#ifdef __cplusplus
extern "C" {
#endif
/*
 * mex equivalent to MATLAB's "disp" function
 */
extern int mexPrintf(
    const char      *fmt,      /* printf style format */
    ...                        /* any additional arguments */
    );
#ifdef __cplusplus
}
#endif


#define printf mexPrintf


This suggests that if the compilation is for a C++ program, an external library will be used to satisfy the mexPrintf function.  If the C source code is being compiled, mexPrintf is just another name for printf.

Some place within the IDE (probably your project) is a setting that indicates that the program should be compiled as C++ code.  See if you can find the setting, change it to C, and recompile.  This might work.  It might make a LOT of things not compile.

Alternatively, after the #include statements, include the line:

#define printf mexPrintf


That's a short-term work-around and NOT intended to really fix the problem.

Kent

 

by: jutzkiPosted on 2007-02-22 at 08:53:43ID: 18589257

Hello KEnt...it still doexn´t work...but I have to leave now since my lab is being closed down...I will try again on Monday...thank you for your help so far
Judith

 

by: JoseParrotPosted on 2007-02-22 at 09:24:12ID: 18589544

Hello, Judith,

You may want try the code below to put esperaH to work properly.

#include "stdafx.h" // Visual C++ stuff
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

///////////////////////////////////////// these simulate your functions
bool QueryPerformanceFrequency(__int64 *largeint)
{
      largeint[0] = 10;
      return (largeint[0] == 10);
}
bool QueryPerformanceCounter(__int64 *largeint)
{
      largeint[0] = 20;
      return (largeint[0] == 10);
}

///////////////////////////////////////// modified code
static double esperaH(double *temp) //sleep in ms
{

bool resultado;
__int64 *now, *frec,goal; //unsigned

now = (__int64*)calloc(1,sizeof(now));
resultado = QueryPerformanceCounter(now);

frec = (__int64*)calloc(1,sizeof(frec));
resultado=QueryPerformanceFrequency(frec);

goal = *now + *temp*1.0e-3**frec; // warning: possible loss of data

while (goal > *now)
resultado = QueryPerformanceCounter(now);
return (double)*now/(double)*frec*1000;

}


///////////////////////////////////////// this simulates your main
void main(void)
{
      double       temp1[1] = {1.2};

      temp1[0] = esperaH(temp1);
      printf("\n%f\n",temp1[0]);
}


The output should be 2000.000000.
Let me suggest to simplify, that is, to pass parameters to functions by value, as suggested by Kdo.
Hope it helps,

Jose

 

by: JoseParrotPosted on 2007-02-22 at 10:22:43ID: 18590006

Oooops, right now I see the comments on other pace... I was seeing just Kdo's comment... anyway, the code I post works properly in MS Visual C++ for the function in question.
On Monday, if you want to follow on this approach, please feel free to ask more in detail.

Jose

 

by: Computer101Posted on 2007-11-17 at 12:22:59ID: 20305273

Forced accept.

Computer101
EE Admin

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...