Learning Stm32f407 timer basics. How to use Timer Count register to set LED? - stm32f4discovery

I am learning micro-controller timers. My board is stm32f407vg.
This is how I initialized
void timerInit(void){
RCC->APB2ENR |= RCC_APB2ENR_TIM4EN;
TIM4->PSC = 10000;
TIM4->ARR = 100;
TIM4->CCR1 |= TIM_CR1_CEN;
}
And then in main, i am using Timer4 counter
while(1){
if(TIM4->CNT > 0){
GPIOD->BSRR |= GPIO_BSRR_BS12;
}
}
But led never goes On. Led initialization is correct, it works if i put it outside if condition.

I figured out the answer to my question. I was enabling counter in CCR (Compare Capture Register) instead of CR (Control Register).

Related

C++/Cli Destructors are not called

I am trying to investigate a memory leak problem and I found out that destructors in my library are not even called and I have the following code:
PPCamNET::Native::PpQueue::PpQueue(int capacity) : m_capacity(capacity), m_array(nullptr), m_head(0), m_tail(0)
{
// Quick fix for case when capacity is 1 (single snap)
// and Push function crashes on 1st frame
if (m_capacity == 1)
m_capacity = 2;
m_array = new FrameData[m_capacity];
m_pushes = 0;
m_pops = 0;
}
The above constructor's destructor should be called after PpQueue is destroyed, but it is not stopping at the break point.
PPCamNET::Native::PpQueue::~PpQueue()
{
delete[] m_array; //<==== here I set a break point
}
PPQueue instance is created by AcqCache constructor.
PPCamNET::Internal::AcqCache::AcqCache(AcqBuffer^ acqBuffer)
{
//m_stopWatchPush = Stopwatch::StartNew();
//m_stopWatchPop = Stopwatch::StartNew();
m_acqBuffer = acqBuffer;
m_cacheLock = gcnew Object();
m_processFrameRunning = true;
try
{
m_frameDataCache = new PpQueue(acqBuffer->BufferSize / 2 + 1);
AcqCache destructor removes m_frameDataCache, which is PpQueue.
PPCamNET::Internal::AcqCache::~AcqCache()
{
m_processFrameRunning = false;
delete m_frameDataCache; // <== here another break point but not called
delete[] m_frameInfoBuffer;
}
Finally the constructor of Acqusition creates an instance of m_acqCache with gcnew.
PPCamNET::Internal::Acquisition::Acquisition(AcqBuffer^ acqBuffer,
CameraSettings^ camSettings)
{
m_eofEvent = gcnew AutoResetEvent(false);
m_acqCache = gcnew AcqCache(acqBuffer);
I am puzzled why these destructors aren't called. Is this because GC didn't kick in to clear up m_acqCache causing other desructors not being called ?
Thanks,
GC will not call a destructor. The C++/CLI compiler translates destructors into IDisposable::Dispose() implementation, and has a different syntax (ClassName::!ClassName) which gets translated to Finalize.
C# wrongly confuses this issue by using the name "destructor" for the CLR Finalize function. Finalizers are not deterministic. The Dispose() function is not called automatically by GC. Not difficult once you know what's going on, but the terminology sure leads to confusion.

Is there a race condition in the code of this Parallel Forall blogopost?

I've recently stumbled upon this blogpost in the NVIDIA devblogs:
https://devblogs.nvidia.com/parallelforall/accelerating-graph-betweenness-centrality-cuda/
I´ve implented the edge parallel code and it seems to work as intended, however it seems to me that the code works with a race condition "controlled" with __syncthreads.
This is the code (as shown in the blog):
__shared__ int current_depth;
__shared__ bool done;
if(idx == 0){
done = false;
current_depth = 0;
}
__syncthreads();
// Calculate the number of shortest paths and the
// distance from s (the root) to each vertex
while(!done){
__syncthreads();
done = true;
__syncthreads();
for(int k=idx; k<m; k+=blockDim.x) //For each edge...
{
int v = F[k];
// If the head is in the vertex frontier, look at the tail
if(d[v] == current_depth)
{
int w = C[k];
if(d[w] == INT_MAX){
d[w] = d[v] + 1;
done = false;
}
if(d[w] == (d[v] + 1)){
atomicAdd(&sigma[w],sigma[v]);
}
}
__syncthreads();
current_depth++;
}
}
I think there is a race condition just at the end:
__syncthreads();
current_depth++;
I think the program is relying on the race condition so the variable gets increased only by one, instead of by the number of threads. I don't feel like this is a good idea, but in my tests it seems to be reliable.
Is this really safe? Is there a better way to do it?
Thanks.
As the author of this blog post, I'd like to thank you for pointing out this error!
When I wrote this snippet I didn't use my verbatim edge-traversal code as that used explicit queuing to traverse the graph which makes the example more complicated without adding any pedagogical value. Instead I must have cargo-culted some old code and posted it incorrectly. It's been quite a while since I've touched this code or algorithm, but I believe the following snippet should work:
__shared__ int current_depth;
__shared__ bool done;
if(idx == 0){
done = false;
current_depth = 0;
}
__syncthreads();
// Calculate the number of shortest paths and the
// distance from s (the root) to each vertex
while(!done)
{
__syncthreads();
done = true;
__syncthreads();
for(int k=idx; k<m; k+=blockDim.x) //For each edge...
{
int v = F[k];
// If the head is in the vertex frontier, look at the tail
if(d[v] == current_depth)
{
int w = C[k];
if(d[w] == INT_MAX){
d[w] = d[v] + 1;
done = false;
}
if(d[w] == (d[v] + 1)){
atomicAdd(&sigma[w],sigma[v]);
}
}
}
__syncthreads(); //All threads reach here, no longer UB
if(idx == 0){ //Only one thread should increment this shared variable
current_depth++;
}
}
Notes:
Looks like a similar issue exists in the node parallel algorithm on the blog post
You could also use a register instead of a shared variable for current_depth, in which case every thread would have to increment it
So to answer your question, no, that method is not safe. If I'm not mistaken the blog snippet has the additional issue that current_depth should only be incremented once all vertices at the previous depth were handled, which is at the conclusion of the for loop.
Finally, if you'd like the final version of my code that has been tested and used by people in the community, you can access it here: https://github.com/Adam27X/hybrid_BC

How to add a movieclip to the stage then make it move down?

I am making a game where i want to spawn zombies then make them move down the screen. I also want to have multiple on the screen at once. I have tried multiple ways now but none of them have worked.
Here is my code
if ((zombie == 1)||(zombie == 3)||(zombie == 5)||(zombie == 7))
{
var Z = new Z;
Z.x = 403.25;
Z.y = -86.9;
Z.rotation = 90;
addChild(Z)
zombie += 1;
}
//Functions
function startzombie(event)
{
trace("start zombies")
zombie = 1;
addEventListener(Event.ENTER_FRAME,zombiemove)
}
function zombiemove(event:Event)
{
Z.y += 1;
}
Z is the zombie
You need an Array that will hold references to your zombie instances, instead of a single variable of class Zombie, whatever it is name. Then, in the part of code that moves zombies, you iterate through that array and advance all zombies in there. Also you need to check if some zombies are already defunct so that you need to remove them from screen and from array, and act accordingly.
var za:Array; // initialize elsewhere
....
function addZombie():void {
var z:Zombie=new Zombie();
z.x=Math.random()*600; // position that zombie
z.y=-20; // somewhere
addChild(z);
za.push(z);
}
function advanceZombies():void {
for (var i:int=za.length-1;i>=0;i--) za[i].walkABit();
}
You call a method in Zombie class specially designed for moving the zombie. They can be say stunned or slowed so that this move might not occur, and it's of no deal to your main class to control each and every zombie's alterable behavior, this is what's named "black box concept". You say "move", they move if they are able.

Check If animation is running in cocos2d-x

I am currently learning cocos2D-x and am doing some sprite animation.
My Objective is that when a button is clicked the object moves to left with some animation.
Now if you click multiple times rapidly the animation takes place immediately and it looks like the bear is hoping instead of walking.
The solution to it looks simple that I should check if animation is already running and if running the new animation should not take place.
The following is a part of my code.
CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("AnimBear.plist");
CCSpriteBatchNode* spriteBatchNode = CCSpriteBatchNode::create("AnimBear.png", 8);
this->addChild(spriteBatchNode,10);
CCArray *tempArray = new CCArray();
char buffer[15];
for (int i = 1; i <= 8 ; i++)
{
sprintf(buffer,"bear%i.png", i);
tempArray->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(buffer));
}
CCAnimation *bearWalkingAnimation = CCAnimation::create(tempArray,0.1f);
startAnimation = CCSprite::createWithSpriteFrameName("bear1.png");
startAnimation->setPosition(ccp (350 , CCDirector::sharedDirector()->getWinSize().height/2 -100));
startAnimation->setScale(0.5f);
startAnimation->setTag(5);
//Animation for bear walking
bearAnimate = CCAnimate::create(bearWalkingAnimation);
Here bearAnimate is a global variable and i wish to know if its currently playing the animation.
How do I do it.?Thank you.
Assume the Sprite that runs the action is
CCSprite* bear;
I think you can use something like
bear->numberOfRunningActions()
numberOfRunningActions( ) returns an unsigned integer, so to check if there are no actions, you would have to check if it returns 0
if ( bear -> numberOfRunningActions( ) == 0 ) {
CCLOG( "No actions running." );
} else {
CCLOG( "Actions running." );
}
The bearAnimate (CCAnimate) has a method to check that.
if (bearAnimate.isDone())
doWhatYouWant();
The method is inherited from CCAction. Good luck.

Minimax with Alpha-beta pruning, getting the result

I have followed the pseducode on the wikipedia article, and I think I got it working. However, it returns the score, and that doesn't exactly help when I want to know what move I want to make.
I tried what I think would be a way to get the best move, but I don't think it is working as when I actually try to play against it (chess), the AI makes somewhat retarded moves with a depth level of 3.
Here is my function:
public static function alphaBeta(node, depth, alph, beta, team, tellTheMove:Boolean = false):* {
var pointer:ChessMove;
if (depth == 0) {
return scoreOf(node);
}
var childrenOf:Vector.<ChessMove > = returnPossibleMoves(node,team);
if (childrenOf.length == 0) {
return scoreOf(node);
}
if (team == 0) {
for (var i in childrenOf) {
var that:Number = alphaBeta(childrenOf[i],depth - 1,alph,beta,1);
if(tellTheMove){
}
if (that > alph) {
alph = that;
if(tellTheMove){
pointer = childrenOf[i];
}
}
if (beta <= alph) {
break;
}
}
if(tellTheMove){
return pointer; //Returns the move that's score last exceeded alpha.
}
return alph;
} else {
for (var j in childrenOf) {
var that2:Number = alphaBeta(childrenOf[j],depth - 1,alph,beta,0);
if (that2 < beta) {
beta = that2;
}
if (beta <= alph) {
break;
}
}
return beta;
}
}
Depth 3 is very little for a problem like chess. At this depth most of the power depends on your final evaluation function. This evaluation function is very hard to do in way that it can predict the value of the board efficiently.
Try something simpler, which can be solved efficiently at a lower depth. Tic-Tac-Toe is a very good game for a first attempt at Min-Max. This is because the final outcome is well known. If you get your algorithm correctly you should not be able to beat it at all. If you do Tic-Tac-Toe and the algorithm is loosing, you know that you have a mistake.
Also note that in some cases Min-Max plays optimal, but still will look retarded to a human opponent. For example if there is no chance at winning, Min-Max will start to play randomly and do very dumb moves. This is the case , because Min-Max expects the opponent to also play perfect, which is usually not the case with humans. There are some simple changes that can be done to the algorithm to change this behavior and have min-max play "less retarded" in such cases.