Why does S-Function only execute mdlInitializeSizes() and does not execute mdlOutputs(), mdlStart() etc? - matlab

#define S_FUNCTION_NAME myfunction_sFun
#define S_FUNCTION_LEVEL 2
#define MDL_INITIAL_SIZES
#define MDL_INITIALIZE_SAMPLE_TIMES
#include "tmwtypes.h"
#include "simstruc_types.h"
#include "mex.h"
#include "simstruc.h"
void mdlInitializeSizes(SimStruct *S)
{
ssPrintf("Initialize\n");
//My code has been removed from here
ssPrintf("End Initialize\n");
}
void mdlInitializeSampleTimes(SimStruct *S)
{
ssPrintf("Sample Times\n");
}
#define MDL_OUTPUTS
#ifdef MDL_OUTPUTS
void mdlOutputs(SimStruct *S, int_T tid)
{
ssPrintf("Outputs\n");
}
#endif
#define MDL_START
#ifdef MDL_START
void mdlStart(SimStruct *S)
{
ssPrintf("Start\n");
}
#endif
void mdlTerminate(SimStruct *S){}
/=============================
Required S-function trailer *
=============================/
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif

mdlStart and mdlOutputs are option methods that only get called in certain circumstances. For instance, mdlOutputs only gets called if there are any outputs defined - which in your case there aren't. (I am a little surprised that mdlStart is not being called.)
See the documentation Simulink Engine Interaction with C S-Functions for which methods are optional, and their calling sequence.

Related

Same S-Function used twice, one works one doesn't

I have a simulink model and I made a simple s-function block to add to my model and it works.
The catch if if I copy or use that same s-function twice in my model, when I run it only the last s-function called will do what it's supposed to do, the other will output a 0.
#define S_FUNCTION_NAME DivByZero
#define S_FUNCTION_LEVEL 2
#define NUMBER_OF_INPUTS 1
#define NUMBER_OF_OUTPUTS 1
#include "DivByZero.h"
#include "mex.h"
#if !defined(MATLAB_MEX_FILE)
/*
* This file cannot be used directly
*/
# error This_file_can_be_used_only_during_simulation_inside_Simulink
#endif
float32 DivByZeroInput;
float32 DivByZeroOutput;
const void * inputPorts[NUMBER_OF_INPUTS];
const void * outputPorts[NUMBER_OF_OUTPUTS];
static void mdlInitializeSizes(SimStruct *S)
{
uint8 i;
ssSetNumSFcnParams(S, 0);
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S))
{
return; /* Parameter mismatch reported by the Simulink engine */
}
if (!ssSetNumInputPorts(S, NUMBER_OF_INPUTS)) return;
ssSetInputPortWidth(S, 0, 1);
ssSetInputPortDataType(S, 0, SS_SINGLE);
for (i = 0; i < NUMBER_OF_INPUTS; i++)
{
ssSetInputPortDirectFeedThrough(S, i, 1); /* Set direct feedthrough flag */
ssSetInputPortRequiredContiguous(S, i, 1); /*direct input signal access*/
}
if (!ssSetNumOutputPorts(S, NUMBER_OF_OUTPUTS)) return;
ssSetOutputPortWidth(S, 0, 1);
ssSetOutputPortDataType(S, 0, SS_SINGLE);
/* Set Sample Time */
ssSetNumSampleTimes(S, 1);
/* Specify the sim state compliance to be same as a built-in block */
ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);
ssSetOptions(S, SS_OPTION_ALLOW_PORT_SAMPLE_TIME_IN_TRIGSS);
ssSupportsMultipleExecInstances(S, true); //set so the s-function can be used in a for each subsystem block
}
static void mdlInitializeSampleTimes(SimStruct *S)
{
/* Inherits sample time from the driving block */
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
ssSetModelReferenceSampleTimeDefaultInheritance(S);
}
#define MDL_START
#if defined(MDL_START)
static void mdlStart(SimStruct *S)
{
uint8 i;
/* Save Input ports */
for (i = 0; i < NUMBER_OF_INPUTS; i++)
{
inputPorts[i] = ssGetInputPortSignal(S, i);
}
/* Save Output ports */
for (i = 0; i < NUMBER_OF_OUTPUTS; i++)
{
outputPorts[i] = ssGetOutputPortRealSignal(S, i);
}
}
#endif
static void mdlOutputs(SimStruct *S, int_T tid)
{
memcpy(&DivByZeroInput, inputPorts[0], sizeof(DivByZeroInput));//gets the input port info
if (fabs(DivByZeroInput) > 0.00001f)
{
DivByZeroOutput = DivByZeroInput;
}
else
{
if (DivByZeroInput >= 0.0f)
{
DivByZeroOutput = 0.00001f;
}
else
{
DivByZeroOutput= -0.00001f;
}
}
memcpy(outputPorts[0], &DivByZeroOutput, sizeof(DivByZeroOutput));//sets the output port
}
static void mdlTerminate(SimStruct *S)
{
/* MODEL TERMINATE */
}
/* END OF TEMPLATE */
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
The s-function is supposed to provide a simple division by zero protection as you can see from the code.
In the image below, if I delete S-Function1, S-Function will then work as intended.
I tried putting it in a library block and just put 2 library blocks and I got the same result
You are defining these variables:
float32 DivByZeroInput;
float32 DivByZeroOutput;
const void * inputPorts[NUMBER_OF_INPUTS];
const void * outputPorts[NUMBER_OF_OUTPUTS];
These variables are shared across both instances, which means both S-Functions write to the same output addresses.
Side note: Do you really have to use an S-Function? Creating the same from a few native simulink blocks is probably much easier.

Matlab S-Function crashing when set to dynamically sized

i have following problem. I have created a S-Function which should read a matrix from a text file, where the output size of the output port is not known and therefore set as dynamically sized. Matlab is then crashing. When setting for fixed size, there is no problem. I hope someone could help me out
#define S_FUNCTION_NAME Data_Input
#define S_FUNCTION_LEVEL 2
/*---- Define size of input ports ---------------------------------------------------*/
#define OUTPUTSIZE 50
/*-----------------------------------------------------------------------------------*/
#include <stdio.h>
#include "simstruc.h"
int_T in;
/*---- Define data types ------------------------------------------------------------*/
typedef struct SBufferData
{
real32_T data[50];
int32_T number;
} SBuffer;
/*==== mdlCheckParameters ===========================================================*/
#undef MDL_CHECK_PARAMETERS /* Change to #undef to remove function */
#if defined(MDL_CHECK_PARAMETERS) && defined(MATLAB_MEX_FILE)
static void mdlCheckParameters(SimStruct *S)
{
}
#endif /* MDL_CHECK_PARAMETERS */
/*===================================================================================*/
/*=== mdlInitializeSizes ============================================================*/
static void mdlInitializeSizes(SimStruct *S)
{
ssSetNumSFcnParams(S,1); /* number of expected parameters */
ssSetSFcnParamTunable(S, 0, 0); /* sets parameter 1 to be non-tunable */
ssSetSFcnParamTunable(S, 1, 0); /* sets parameter 2 to be non-tunable */
ssSetNumContStates(S,0); /* number of continuous states */
ssSetNumDiscStates(S,0); /* number of discrete states */
ssSetNumInputPorts(S,0); /* number of input ports */
ssSetNumOutputPorts(S,1); /* number of output ports */
ssSetOutputPortWidth(S,0,DYNAMICALLY_SIZED); /* first output port width */
ssSetOutputPortDataType(S,0,SS_SINGLE); /* first output port data type */
ssSetNumSampleTimes(S,0); /* number of sample times */
ssSetNumRWork(S,0); /* number real work vector elements */
ssSetNumIWork(S,0); /* number int_T work vector elements */
ssSetNumPWork(S,1); /* number ptr work vector elements */
ssSetNumModes(S,0); /* number mode work vector elements */
ssSetNumNonsampledZCs(S,0); /* number of nonsampled zero crossing */
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
return; /* Parameter mismatch reported by the Simulink engine*/
}
}
/*===================================================================================*/
/*==== mdlInitializeSampleTimes =====================================================*/
static void mdlInitializeSampleTimes(SimStruct *S)
{
real_T dSampleTime=(mxGetPr(ssGetSFcnParam(S,0))[0]);
ssSetSampleTime(S, 0, dSampleTime);
ssSetOffsetTime(S, 0, 0.0);
}
/*===================================================================================*/
/*==== mdlStart =====================================================================*/
#define MDL_START /* Change to #undef to remove function */
#if defined(MDL_START)
static void mdlStart(SimStruct *S)
{
FILE *fp;
int_T i, index=0;
SBuffer *buffer;
float temp;
/*---- Retrieve pointer to pointers work vector -------------------------------------*/
void **PWork = ssGetPWork(S);
buffer = (SBuffer *)malloc(OUTPUTSIZE * sizeof(SBuffer));
PWork[0] = (void *)buffer;
/*---- Read from text-file ----------------------------------------------------------*/
fp = fopen("myfile.txt", "r");
while(feof(fp)==0)
{
fscanf(fp,"%f",&temp);
buffer -> data[index] = temp;
index++;
}
buffer -> number = (int32_T) index;
fclose(fp);
}
#endif /* MDL_START */
/*===================================================================================*/
/*==== mdlOutputs ===================================================================*/
static void mdlOutputs(SimStruct *S, int_T tid)
{
/*---- Get input ports --------------------------------------------------------------*/
real_T *y1=(real_T *)ssGetOutputPortSignal(S,0);
int_T i;
SBuffer *buffer;
/*---- Retrieve pointer to pointers work vector -------------------------------------*/
void **PWork = ssGetPWork(S);
buffer = PWork[0];
for (i = 0; i < buffer->number; i++)
{
y1[i] = buffer->data[i];
}
}
/*===================================================================================*/
/*==== mdlTerminate =================================================================*/
static void mdlTerminate(SimStruct *S)
{
SBuffer *buffer;
/*---- Retrieve pointer to pointers work vector -------------------------------------*/
void **PWork = ssGetPWork(S);
buffer = PWork[0];
/*---- Deallocate structure 'info' and 'buffer' -------------------------------------*/
free(buffer);
}
/*===================================================================================*/
/*==== Required S-function trailer ==================================================*/
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
/*===================================================================================*/

GTK basics : learning from sources

I am new at programming Gtk gnome linux C application, and I am trying to learn from some source reagind and online gnome documentation but I can't do it because this is in my opinion very poor and bad. I have a problem understanding this following source: after creating a GObject of GApplication type, how can this main function call other parts of programs? (This is from gedit source) I learnt that GApplication doesn't include any pointer to some code.
/*
* gedit.c
* This file is part of gedit
*
* Copyright (C) 2005 - Paolo Maggi
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "gedit-app.h"
#ifdef OS_OSX
#include "gedit-app-osx.h"
#else
#ifdef G_OS_WIN32
#include "gedit-app-win32.h"
#else
#include "gedit-app-x11.h"
#endif
#endif
#include <glib.h>
#include <locale.h>
#include <libintl.h>
#include "gedit-dirs.h"
#include "gedit-debug.h"
#ifdef G_OS_WIN32
#include <gmodule.h>
static GModule *libgedit_dll = NULL;
/* This code must live in gedit.exe, not in libgedit.dll, since the whole
* point is to find and load libgedit.dll.
*/
static gboolean
gedit_w32_load_private_dll (void)
{
gchar *dllpath;
gchar *prefix;
prefix = g_win32_get_package_installation_directory_of_module (NULL);
if (prefix != NULL)
{
/* Instead of g_module_open () it may be possible to do any of the
* following:
* A) Change PATH to "${dllpath}/lib/gedit;$PATH"
* B) Call SetDllDirectory ("${dllpath}/lib/gedit")
* C) Call AddDllDirectory ("${dllpath}/lib/gedit")
* But since we only have one library, and its name is known, may as well
* use gmodule.
*/
dllpath = g_build_filename (prefix, "lib", "gedit", "libgedit.dll", NULL);
g_free (prefix);
libgedit_dll = g_module_open (dllpath, 0);
if (libgedit_dll == NULL)
{
g_printerr ("Failed to load '%s': %s\n",
dllpath, g_module_error ());
}
g_free (dllpath);
}
if (libgedit_dll == NULL)
{
libgedit_dll = g_module_open ("libgedit.dll", 0);
if (libgedit_dll == NULL)
{
g_printerr ("Failed to load 'libgedit.dll': %s\n",
g_module_error ());
}
}
return (libgedit_dll != NULL);
}
static void
gedit_w32_unload_private_dll (void)
{
if (libgedit_dll)
{
g_module_close (libgedit_dll);
libgedit_dll = NULL;
}
}
#endif
int
main (int argc, char *argv[])
{
GType type;
GeditApp *app;
gint status;
const gchar *dir;
#ifdef OS_OSX
type = GEDIT_TYPE_APP_OSX;
#else
#ifdef G_OS_WIN32
if (!gedit_w32_load_private_dll ())
{
return 1;
}
type = GEDIT_TYPE_APP_WIN32;
#else
type = GEDIT_TYPE_APP_X11;
#endif
#endif
/* NOTE: we should not make any calls to the gedit api before the
* private library is loaded */
gedit_dirs_init ();
/* Setup locale/gettext */
setlocale (LC_ALL, "");
dir = gedit_dirs_get_gedit_locale_dir ();
bindtextdomain (GETTEXT_PACKAGE, dir);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
textdomain (GETTEXT_PACKAGE);
app = g_object_new (type,
"application-id", "org.gnome.gedit",
"flags", G_APPLICATION_HANDLES_COMMAND_LINE | G_APPLICATION_HANDLES_OPEN,
NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
/* Break reference cycles caused by the PeasExtensionSet
* for GeditAppActivatable which holds a ref on the GeditApp
*/
g_object_run_dispose (G_OBJECT (app));
g_object_add_weak_pointer (G_OBJECT (app), (gpointer *) &app);
g_object_unref (app);
if (app != NULL)
{
gedit_debug_message (DEBUG_APP, "Leaking with %i refs",
G_OBJECT (app)->ref_count);
}
#ifdef G_OS_WIN32
gedit_w32_unload_private_dll ();
#endif
return status;
}
/* ex:set ts=8 noet: */

How High the Pin of Parallel Port

/* Necessary includes for drivers */
#include <linux/init.h>
//#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h> /* printk() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/fs.h> /* everything... */
#include <linux/errno.h> /* error codes */
#include <linux/types.h> /* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h> /* O_ACCMODE */
#include <linux/ioport.h>
#include <asm/system.h> /* cli(), *_flags */
#include <asm/uaccess.h> /* copy_from/to_user */
#include <asm/io.h> /* inb, outb */
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Nikunj");
/* Function declaration of parlelport.c */
int parlelport_open(struct inode *inode, struct file *filp);
int parlelport_release(struct inode *inode, struct file *filp);
ssize_t parlelport_read(struct file *filp, char *buf, size_t count, loff_t *f_pos);
ssize_t parlelport_write(struct file *filp, char *buf, size_t count, loff_t *f_pos);
void parlelport_exit(void);
int parlelport_init(void);
/* Structure that declares the common */
/* file access fcuntions */
struct file_operations parlelport_fops = {
read : parlelport_read,
write : parlelport_write,
open : parlelport_open,
release : parlelport_release
};
/* Driver global variables */
/* Major number */
int parlelport_major = 61;
/* Control variable for memory */
/* reservation of the parallel port*/
int port;
module_init(parlelport_init);
module_exit(parlelport_exit);
int parlelport_init(void)
{
int result;
/* Registering device */
result = register_chrdev(parlelport_major, "parlelport", &parlelport_fops);
if (result < 0)
{
printk("<1>parlelport: cannot obtain major number %d\n",parlelport_major);
return result;
}
/* Registering port */
port = check_region(0x378, 1);
if (port)
{
printk("<1>parlelport: cannot reserve 0x378\n");
result = port;
goto fail;
}
request_region(0x378, 1, "parlelport");
printk("<1>Inserting parlelport module\n");
return 0;
fail:
parlelport_exit();
return result;
}
void parlelport_exit(void)
{
/* Make major number free! */
unregister_chrdev(parlelport_major, "parlelport");
/* Make port free! */
if (!port)
{
release_region(0x378,1);
}
printk("<1>Removing parlelport module\n");
}
int parlelport_open(struct inode *inode, struct file *filp)
{
/* Success */
return 0;
}
int parlelport_release(struct inode *inode, struct file *filp)
{
/* Success */
return 0;
}
ssize_t parlelport_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
/* Buffer to read the device */
char parlelport_buffer;
/* Reading port */
parlelport_buffer = inb(0x378);
/* We transfer data to user space */
copy_to_user(buf,&parlelport_buffer,1);
/* We change the reading position as best suits */
if (*f_pos == 0)
{
*f_pos+=1;
return 1;
}
else
{
return 0;
}
}
ssize_t parlelport_write( struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
char *tmp;
/* Buffer writing to the device */
char parlelport_buffer;
tmp=buf+count-1;
copy_from_user(&parlelport_buffer,tmp,1);
/* Writing to the port */
outb(parlelport_buffer,0x378);
return 1;
}
this is the code of parallel port device driver and this is my first c code for that.
Please help me to solve the below problem
i have successfully compile the code and create the .ko file successfully and successfully load in the ubuntu 9.10 OS but thee is no high or low the pin so please help me
How you are checking answer?? After installed module do
dmesg
Actually you can not acquire region at 0x378. Because by default system allocate this one to parport0.
Do cat /proc/ioports so you will find that at 0x378 there is parport0.
You can directly write on that address (0x378), without using that checking and requesting.
My suggestion is that don't directly go in complex form. In write function just write
outb(0x378,1) and check (by inserting hardware having LEDs) LED on/off on data pins.

To declare a CString function inside a header file

How to properly declare this function inside this header file?
CString ExecuteExternalProgram(CString pictureName);
#pragma warning( disable: 4049 ) /* more than 64k source lines */
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
#include "rpc.h"
#include "rpcndr.h"
CString ExecuteExternalProgram(CString pictureName); //<---- THIS LINE IS ERROR?
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef __Example1_h__
#define __Example1_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifdef __cplusplus
extern "C"{
#endif
#ifndef __Example1_INTERFACE_DEFINED__
#define __Example1_INTERFACE_DEFINED__
void Output(
/* [string][in] */ const char *szOutput);
extern handle_t hExample1Binding;
extern RPC_IF_HANDLE Example1_v1_0_c_ifspec;
extern RPC_IF_HANDLE Example1_v1_0_s_ifspec;
#endif /* __Example1_INTERFACE_DEFINED__ */
#ifdef __cplusplus
}
#endif
#endif
I created an Empty Project in Visual Studio and I didn't have any problem compiling:
#include <atlstr.h>
#include "Example1.h" // Direct copy of your code from above
int main(int argc, char **argv) {
return 0;
}
I was tipped off about atlstr.h from http://www.codeguru.com/forum/showthread.php?t=231164.
Is that what you mean by "properly" declare?