Proteus always error at certain time (in this case 1.75 sec) - arduino-uno

I recently using FreeRTOS for college project, but somehow my proteus always had this fatal error (every time its difference error but always fatal error, sometime violation module DSIM.dll, sometime other .dll(s)). At first I thought it has something to do with my code, so I try to use another example code (simple template from the internet that does blinking LED, nothing complex) but its still error at the exact 1.75 sec even though at that guy's demo works splendidly. I think it has to do with xTaskDelay cause when I commented the delay line the tasks (its singular task I suppose cause the only running task is only the one with the higher priority) the program works. Thanks in advance
#include <Arduino_FreeRTOS.h>
void setup()
//Initialize the Serial Monitor with 9600 baud rate
{
Serial.begin(9600);
Serial.println(F("In Setup function"));
//Set the digital pins 8 to 11 as digital output pins
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
//Create three tasks with labels Task1, Task2 and Task3 and assign the priority as 1, 2 and 3 respectively.
//We also create the fourth task labeled as IdelTask when there is no task in
//operation and it has the highest priority.
xTaskCreate(MyTask1, "Task1", 100, NULL, 1, NULL);
xTaskCreate(MyTask2, "Task2", 100, NULL, 2, NULL);
xTaskCreate(MyTask3, "Task3", 100, NULL, 3, NULL);
xTaskCreate(MyIdleTask, "IdleTask", 100, NULL, 0, NULL);}
//We can change the priority of task according to our desire by changing the numeric’s //between NULL texts.
void loop()
{
//There is no instruction in the loop section of the code.
// Because each task executes on interrupt after specified time
}
//The following function is Task1. We display the task label on Serial monitor.
static void MyTask1(void* pvParameters)
{
while(1)
{
digitalWrite(8,HIGH);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);
Serial.println(F("Task1"));
vTaskDelay(100/portTICK_PERIOD_MS);
}
}
//Similarly this is task 2
static void MyTask2(void* pvParameters)
{
while(1)
{ digitalWrite(8,LOW);
digitalWrite(9,HIGH);
digitalWrite(10,LOW);
digitalWrite(11,LOW);
Serial.println(F("Task2"));
vTaskDelay(110/portTICK_PERIOD_MS);
}
}
//Similarly this is task 3
static void MyTask3(void* pvParameters)
{
while(1)
{
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,HIGH);
digitalWrite(11,LOW);
Serial.println(F("Task3"));
vTaskDelay(120/portTICK_PERIOD_MS);
}
}
//This is the idle task which has the lowest priority and calls when no task is running.
static void MyIdleTask(void* pvParameters)
{
while(1)
{
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,HIGH);
Serial.println(F("Idle state"));
delay(50);
}
}
Source for the code

it turns out the Proteus app is kinda corrupted so I went to google to download those .dll(s) files

Related

Statistics collection related values do not increase in OMNeT++

In order to measure the packet transmission/reception count, I declared a scalar variable and wrote a function related to record. It looks like this:
A.h
class VEINS_API A : public DemoBaseApplLayer
{
private:
long StaticsFrsaPacketCount;
cOutVector frsaPacketCountVector;
...
}
A.cc
void A::initialize(int stage)
{
DemoBaseApplLayer::initialize(stage);
if(stage == 0)
{
StaticsFrsaPacketCount = 0;
frsaPacketCountVector.setName("fR_SA packet count");
...
}
}
void A::finish()
{
recordScalar("fR_SA Packet", StaticsFrsaPacketCount);
...
}
void A::handleSelfMsg(cMessage* msg)
{
switch(msg -> getKind())
{
case SEND_FRSA_EVT:
{
...
StaticsFrsaPacketCount++;
frsaPacketCountVector.record(StaticsFrsaPacketCount);
...
sendDelayedDown(wsm, uniform(0.01, 0.50));
}
...
}
}
I wrote the code by referring to the statistics written in the official OMNeT++ Tictoc tutorial. However, the result of the scalar value through the generated .anf file after the simulation is finished is as shown in the image below.
In other words, it seems that the value is incremented 1 time and not incremented after that. What is the cause?
(this part) of your code looks fine. The most likely reason why you have 1 in the result because really just one packet was sent. The statistics are showing what is actually happening. If you expect several packets to be sent, I suggest to start the app in Qtenv and step over the simulation and make sure that it works as you expect.

Running a non-blocking, high-performance activity in nativescript/javascript

This question is about running a non-blocking, high-performance activity in nativescript that is needed for the simple task of reading and saving raw audio from the microphone by directly accessing the hardware through the native Android API. I believe I have brought the nativescript framework to the edge of its capabilities, and I need experts' help.
I'm building a WAV audio recorder in Nativescript Android. Native implementation is described here (relevant code below).
In short, this can be done by reading audio steam from an android.media.AudioRecord buffer, and then writing the buffer to a file in a separate thread, as described:
Native Android implementation
startRecording() is triggered by a button press, and starts a new Thread that runs writeAudioDataToFile():
private void startRecording() {
// ... init Recorder
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
#Override
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
Recording is stopped by setting isRecording to false (stopRecording() is triggered by a button press):
private void stopRecording() {
isRecording = false;
recorder.stop();
recorder.release();
recordingThread = null;
}
Reading and saving buffer is stopped if isRecording = false:
private void writeAudioDataToFile() {
// ... init file and buffer
ByteArrayOutputStream recData = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(recData);
int read = 0;
while(isRecording) {
read = recorder.read(data, 0, bufferSize);
for(int i = 0; i < bufferReadResult; i++) {
dos.writeShort(buffer[i]);
}
}
}
My Nativescript javascript implementation:
I wrote a nativescript typescript code that does the same as the native Android code above. The problem #1 I faced was that I can't run while(isRecording) because the javascript thread would be busy running inside the while loop, and would never be able to catch button clicks to run stopRecording().
I tried to solve problem #1 by using setInterval for asynchronous execution, like this:
startRecording() is triggered by a button press, and sets a time interval of 10ms that executes writeAudioDataToFile():
startRecording() {
this.audioRecord.startRecording();
this.audioBufferSavingTimer = setInterval(() => this.writeAudioDataToFile(), 10);
}
writeAudioDataToFile() callbacks are queued up every 10ms:
writeAudioDataToFile() {
let bufferReadResult = this.audioRecord.read(
this.buffer,
0,
this.minBufferSize / 4
);
for (let i = 0; i < bufferReadResult; i++) {
dos.writeShort(buffer[i]);
}
}
Recording is stopped by clearing the time interval (stopRecording() is triggered by button press):
stopRecording() {
clearInterval(this.audioBufferSavingTimer);
this.audioRecord.stop();
this.audioRecord.release();
}
Problem #2: While this works well, in many cases it makes the UI freeze for 1-10 seconds (for example after clicking a button to stop recording).
I tried to change the time interval that executes writeAudioDataToFile() from 10ms to 0ms and up to 1000ms (while having a very big buffer), but then the UI freezes were longer and, and I experienced loss in the saved data (buffered data that was not saved to the file).
I tried to offload this operation to a separate Thread by using a nativescript worker thread as described here, where startRecording() and stopRecording() are called by messages sent to the thread like this:
global.onmessage = function(msg) {
if (msg.data === 'startRecording') {
startRecording();
} else if (msg.data === 'stopRecording') {
stopRecording();
}
}
This solved the UI problem, but created problem #3: The recorder stop was not executed on time (i.e. recording stops 10 to 50 seconds after the 'stopRecording' msg.data is received by the worker thread). I tried to use different time intervals in the setInterval inside the worker thread (0ms to 1000ms) but that didn't solve the problem and even made stopRecording() be executed with greater delays.
Does anyone have an idea of how to perform such a non-blocking high-performance recording activity in nativescript/javascript?
Is there a better approach to solve problem #1 (javascript asynchronous execution) that I described above?
Thanks
I would keep the complete Java implementation in actual Java, you can do this by creating a java file in your plugin folder:
platforms/android/java, so maybe something like:
platforms/android/java/org/nativescript/AudioRecord.java
In there you can do everything threaded, so you won't be troubled by the UI being blocked. You can call the Java methods directly from NativeScript for starting and stopping the recording. When you build your project, the Java file will automatically be compiled and included.
You can generate typings from your Java class by grabbing classes.jar from the generated .aar file of your plugin ({plugin_name}.aar) and generate type declarations for it: https://docs.nativescript.org/core-concepts/android-runtime/metadata/generating-typescript-declarations
This way you have all the method/class/type information available in your editor.

Framerate independent event in Unity3D

I use the libpd4unity package to communicate with Pure Data. I receive a bang from Pure Data with LibPD.Bang. On a bang event I play sound by FMOD.
Problem is, that I receive bangs frequently, for example once every 500 ms but event doesn't trigger in specific length of frame. Usually length change 1 frame less or more.
Is there a solution for this problem? For example a framerate independent event? I want to know if event (delegate) in Unity3D is framerate independent or not.
Because there is tempo for playing each sound and just 1 frame ruins rhythm.
I need to sync sounds for playing by each separate bang.
Regarding your question on whether delegates are dependent or independent from Unity's framerate, there's no straight answer. It depends on how your delegates are called. Are they called from a thread? Are they executed in a thread?
Coroutines are not framerate independent, they are executed in Unity's loop.
The following script should shine a light on the difference between handling delegates in coroutines and in threads.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class DelegatesAndFramerate : MonoBehaviour {
delegate void MyDelegate();
MyDelegate myDelegate1; // done with coroutines
MyDelegate myDelegate2; // done with threads
Thread thread;
bool threadDone = false;
private int frameCount = 0;
private int delegate1CallCount = 0;
private int delegate2CallCount = 0;
private int callerLoopsCount_coroutine = 0;
private int callerLoopsCount_thread = 0;
void Start () {
myDelegate1 += Elab1;
myDelegate2 += Elab2;
StartCoroutine(CallerCoroutine());
thread = new Thread(new ThreadStart(CallerThread));
thread.Start();
}
void Update()
{
frameCount++;
}
void Elab1()
{
delegate1CallCount++;
}
void Elab2()
{
delegate2CallCount++;
}
IEnumerator CallerCoroutine()
{
while(true)
{
callerLoopsCount_coroutine++;
myDelegate1();
yield return null;
}
}
void CallerThread()
{
while(!threadDone)
{
callerLoopsCount_thread++;
myDelegate2();
}
}
void OnDestroy()
{
Debug.Log("Frame Count: " + frameCount);
Debug.Log("Delegate Call Count (Coroutine): " + delegate1CallCount);
Debug.Log("Delegate Call Count (Thread): " + delegate2CallCount);
Debug.Log("Caller Loops Count (Coroutine): " + callerLoopsCount_coroutine);
Debug.Log("Caller Loops Count (Thread): " + callerLoopsCount_thread);
threadDone = true;
thread.Join();
}
}
If you attach it to a GameObject and let Unity play for some seconds you'll see that the times the delegate was called from a coroutine is equal to the number of executed frames whilst the times the delegate was called from the thread will be way bigger.
I have experience in interfacing softwares similar to Pure Data and I think what you need is a (rather typical) thread with all your delegates there, create a queue of commands for Unity and digest it in Unity's Update.
Not knowing libPD in the specific this might not be the best practice for the case but it is a widely used approach. Basically the producer-consumer pattern.
Basing on the example GUITextScript.cs, libPD only requires you to subscribe to the right delegates. You don't have control on when these are executed, the library has; so if you keep having this issue it's worth submitting a bug report to the developers I guess.

Need to send requestImage() some runtime generated URLs. Is this possible?

I'm using a remote url for a PImage. It's a jpg from a cam. I'm grabbing it and sending it to a image() every sec. Switching to a new cam every 10 secs. Every hour or so, the script crashes due to a 502 error, since the image was not successfully downloaded.
I'm attempting to setup a script that looks at the image using requestImage(), does a quick error check, and skips draw of that image if it returns a 0 or -1. Which should be simple enough. But...
How can you send a constantly updating url to requestImage() if its parameters refuse to accept anything other than a static single filename in a string and it lives in setup() / pre-process?
Anyone run into this issue before? Or am I missing something?
Here is the code. Note: cams are not active at the moment, so there are placeholders in the array...;
Thanks for looking!
PImage webImg;
PImage testImg;
int timer;
String[] camlist = {
"random_url_with_JPG_here",
"random_url_with_JPG_here",
"random_url_with_JPG_here"
};
//find length of array
int camListLength = int(random(camlist.length));
void setup() {
testImg = requestImage(webImg, "jpg");
noCursor();
fullScreen();
background(0);
}
void draw() {
if (millis() - timer >= 10000) {
camLoad();
timer = millis();
} else {
displayWebImage();
}
}
void camLoad() {
//find length of array
camListLength = int(random(camlist.length));
}
void displayWebImage() {
// load random cam url into 'webImg'
webImg = loadImage(camlist[camListLength], "jpg");
// test load
println(testImg.width);
if (testImg.width == 0) {
println("Not Loaded");
} else if (testImg.width == -1) {
println("random error");
} else {
// display 'webImage'
image(webImg, 0, 0, 800, 480);
// cache cleanup
g.removeCache(webImg);
delay(1000);
// frame count
println(frameCount+" "+g.getCache(webImg));
}
}
It's true that for 95% of people, it's a very bad idea to create images in the draw() function. Most programs should load all of the images at the beginning, in the setup() function.
But if you're loading images that you don't know ahead of time, then nothing is stopping you from creating images in the draw() function. You can absolutely call requestImage() from inside the draw() function.
But note that the requestImage() function runs in the background, so your code keeps executing while the image is requested. From the reference:
This function loads images on a separate thread so that your sketch doesn't freeze while images load during setup(). While the image is loading, its width and height will be 0. If an error occurs while loading the image, its width and height will be set to -1.
This means that the image won't be loaded until a couple second later, so you can't use your image variable right away. You're fixing this using a call to delay(), but you're probably better off just using the loadImage() function instead. From the reference:
If the file is not available or an error occurs, null will be returned and an error message will be printed to the console. The error message does not halt the program, however the null value may cause a NullPointerException if your code does not check whether the value returned is null.
...
Depending on the type of error, a PImage object may still be returned, but the width and height of the image will be set to -1. This happens if bad image data is returned or cannot be decoded properly. Sometimes this happens with image URLs that produce a 403 error or that redirect to a password prompt, because loadImage() will attempt to interpret the HTML as image data.
That function does not run in the background, so the code only continues after the image is fully loaded.

Not receiving messages after sometime

I am using JNA to access User32 functions (I dont think it has got to do with Java here, more of concept problem). In my application, I have a Java process which communicates with the Canon SDK. To dispatch any messages I am using the below function:
private void peekMessage(WinUser.MSG msg) throws InterruptedException {
int hasMessage = lib.GetMessage(msg, null, 0, 0);
if (hasMessage != 0) {
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
Thread.sleep(1);
}
peekMessage is called in a loop and it all works well. Whenever an Image is taken from camera, I get the event and do the rest.
But I have observed, say after about 15 seconds (sometimes never or sometimes just at start) of no activity with camera, taking picture does not give me any download event. Later the whole application becomes unusable as it doesn't get any events from camera.
What can be the reason for this? Please let me know of any other info needed, I can paste the respective code along.
Edit:
Initialization:
Map<String, Integer> options = new HashMap<String, Integer>();
lib = User32.INSTANCE;
hMod = Kernel32.INSTANCE.GetModuleHandle("");
options.put(Library.OPTION_CALLING_CONVENTION, StdCallLibrary.STDCALL_CONVENTION);
this.EDSDK = (EdSdkLibrary) Native.loadLibrary("EDSDK/dll/EDSDK.dll", EdSdkLibrary.class, options);
private void runNow() throws InterruptedException {
while (!Thread.currentThread().isInterrupted()) {
Task task = queue.poll();
if (task != null) {
int taskResult = task.call();
switch (taskResult) {
case (Task.INITIALIZE_STATE):
break;
case (Task.PROCESS_STATE):
break;
case (Task.TERMINATE_STATE): {
//queue.add(new InitializeTask());
Thread.currentThread().interrupt();
break;
}
default:
;
}
}
getOSEvents();
}
}
WinUser.MSG msg = new WinUser.MSG();
private void getOSEvents() throws InterruptedException {
if (isMac) {
receiveEvents();
} else {
peekMessage(msg);
}
}
Above, whenever I get my camera event, it add's it to the queue and in each loop I check the queue to process any Task. One more important information: This is a process running on cmd and has no window. I just need the events from my camera and nothing else.
The code where I register callback functions:
/**
* Adds handlers.
*/
private void addHandlers() {
EdSdkLibrary.EdsVoid context = new EdSdkLibrary.EdsVoid(new Pointer(0));
int result = EDSDK.EdsSetObjectEventHandler(edsCamera, new NativeLong(EdSdkLibrary.kEdsObjectEvent_All), new ObjectEventHandler(), context).intValue();
//above ObjectEventHandler contains a function "apply" which is set as callback function
context = new EdSdkLibrary.EdsVoid(new Pointer(0));
result = EDSDK.EdsSetCameraStateEventHandler(edsCamera, new NativeLong(EdSdkLibrary.kEdsStateEvent_All), new StateEventHandler(), context).intValue();
//above StateEventHandler contains a function "apply" which is set as callback function
context = new EdSdkLibrary.EdsVoid(new Pointer(0));
result = EDSDK.EdsSetPropertyEventHandler(edsCamera, new NativeLong(EdSdkLibrary.kEdsStateEvent_All), new PropertyEventHandler(), context).intValue();
//above PropertyEventHandler contains a function "apply" which is set as callback function
}
You are getting ALL messages from ALL windows that belong to this thread, that includes all mouse moves, paints etc. if you aren't rapidly calling this function your message queue will overflow and cause the behavior you describe.
The sleep you definitely don't want as GetMessage yields if no message is waiting.
So if there exists a normal message pump(s) (i.e GetMessage/DispatchMessage) loop somewhere else for this threads window(s) then you should let that pump do most of the work, perhaps use wMsgFilterMin, wMsgFilterMax to just get the event message you require; or even better in this case use peekmessage with PM_NOREMOVE (then you will need your sleep
call as peekmessage returns immediately).
Alternatively provide the hWnd of the window that generates the event to reduce the workload.
Use spy++ to look into which windows this thread owns and what messages are being produced.
To take this answer further please provide answers to: what else is this thread doing and what windows does it own; also is this message pump the only one or do you call into the SDK API where it may be pumping messages too?
There is an OpenSource project wrapping EDSDK with JNA and it has a version of your code that is probably working better:
https://github.com/kritzikratzi/edsdk4j/blob/master/src/edsdk/api/CanonCamera.java#L436
Unfortunately this is not platform independent and specifically the way things work on windows. I am currently in the process of trying to get a MacOS version of things working at:
https://github.com/WolfgangFahl/edsdk4j

Resources