Protecting critical section in interrupt - c

I want a solution for this problem than disabling interrupts while if condition being executed. I'm working on pic16f877a. and want very simple and basic solution.
static int counter=0;
void main()
{
while(1)
{
if(counter)
{
counter--;
//code
}
}
InterruptSerial()
{
counter++;
//code
}
To execute counter--; it is translated into
load counter value
decrement loaded value
assign new value in counter register
If an interrupt happened while executing this code before reaching the assign instruction this will result in wrong behavior.
Normal solution will be
void main()
{
while(1)
{
if(counter)
{
disableInterrupts();
counter--;
//code
enableInterrupts();
}
}
How to solve this without disabling interrupts ?

Related

Delay within a timer (what is the correct approach)

I'm in a pickle regarding concepts relating to timers. How can I can I operate a "delay" inside a timer? This is the best way I can frame the question knowing full well what I'm trying to do is nonsense. The objective is: I wish to test the pinState condition 2 times (once initially and then 4 seconds later) but this all needs to happen periodically (hence a timer).
The platform is NodeMCU running a WiFi (ESP8266 chip) and coding done inside Arduino IDE.
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;
char auth[] = "x"; //Auth code sent via Email
char ssid[] = "x"; //Wifi name
char pass[] = "x"; //Wifi Password
int flag=0;
void notifyOnFire()
{
int pinState = digitalRead(D1);
if (pinState==0 && flag==0) {
delay(4000);
int pinStateAgain = digitalRead(D1);
if (pinStateAgain==0) {
Serial.println("Alarm has gone off");
Blynk.notify("House Alarm!!!");
flag=1;
}
}
else if (pinState==1)
{
flag=0;
}
}
void setup()
{
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
pinMode(D1,INPUT_PULLUP);
timer.setInterval(1000L,notifyOnFire);
}
void loop()
{
//Serial.println(WiFi.localIP());
Blynk.run();
timer.run();
}
an easy fix would be to set the periodicity of the timer to be 4000L timer.setInterval(4000L,notifyOnFire); and in notifyOnFire use a static variable and toggle its value whenever notifyOnFire is called
void notifyOnFire()
{
static char state = 0;
if( state == 0)
{
/* Write here the code you need to be executed before the 4 sec delay */
state = 1;
}
else
{
/* Write here the code you need to be executed after the 4 sec delay */
state = 0;
}
}
The nice thing about static variables is that they are initialized only once at compile time and they retain their values after the scope of code changes (In this case function notifyOnFire exits).

The ISR executed once even when the event not happened

I am using PIC24FJ128GA204 microcontroller in PIC24F Curiosity Development Board.
The ISR is executed at least once even when the event not happened.
Here is the code:
#include <xc.h>
int Random_mode_condition=0;
void __attribute__((__interrupt__, __shadow__)) _INT1Interrupt(void) {
Random_mode_condition = 44;
_INT1IF = 0;
}
void RC9_Switch_Config() {
_TRISC9 = 1; // Switch input
RPINR0bits.INT1R = 25;
IFS1bits.INT1IF=0;//Clear the interrupt flag
IPC5bits.INT1IP1=1;//Choose a priority
INTCON2bits.INT1EP=0;//rising edge
IEC1bits.INT1IE=1;//enable INT1 interrupt
}
int main() {
LATC=0x0000;
RC9_Switch_Config();
while(1){
if(Random_mode_condition==44){ TRISC=0x0000; LATC=0xffff;}
}
return 0;
}
Random_mode_condition will equal 44 then the if statement will be executed.
Please help

Peterson's Algorithm to avoid race condition between threads

Details:
I am implementing Peterson's Algorithm(below) to avoid race condition. The way I want to do it, is to declare a global integer variable, and create threads one and two. Whenever the thread one had access to the global variable it should print a and add one to the global variable counter. When the thread two have access to this global variable it should print b and add one to the global variable counter. This should continue until the global variable reaches a certain number(let's say 10). After that I want the thread(which ever of the two threads that makes the last addition to the global variable) to reset the global variable to 1 and both threads should exit. The code that I have implemented so far kinda does the job,it avoids race condition, but I can't exit both threads when counter reaches limit.
Question:
How can I quit both threads when the counter reaches a specific limit.
Whats the proper form of quitting a thread, right now I am using exit(), which I don't think is very efficient.
Peterson's Algorithm
boolean flag [2];
int turn;
void P0()
{
while (true) {
flag [0] = true;
turn = 1;
while (flag [1] && turn == 1) /* do nothing */;
/* critical section */;
flag [0] = false;
/* remainder */;
}
}
void P1()
{
while (true) {
flag [1] = true;
turn = 0;
while (flag [0] && turn == 0) /* do nothing */;
/* critical section */;
flag [1] = false;
/* remainder */
}
}
void main()
{
flag [0] = false;
flag [1] = false;
parbegin (P0, P1);
}
My Code:
EDIT: I realized that I have to put the if-statement, that is checking for the counter limit value, should be in the critical section(before it changes the flag to false).
#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
int counter = 0;
int flag[2];
int turn;
void *func1(void *);
void *func2(void *);
int main(int argc,char *argv[]){
pthread_t thread1,thread2;
//int rt1,rt2;
flag[0] = 0;
flag[1] = 0;
//rt1 = pthread_create(&thread1,NULL,&func1,"a");
//rt2 = pthread_create(&thread2,NULL,&func2,"c");
pthread_create(&thread1,NULL,&func1,"a");
pthread_create(&thread2,NULL,&func2,"b");
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}// End of main function
void *func1(void *message){
while(1){
flag[0] = 1;
turn = 1;
while(flag[1] && turn == 1);
printf("%s %d\n",(char *)message,counter);
counter++;
flag[0] = 0;
if(counter == 10){
counter = 1;
printf("exited at func1, with counter %d\n",counter);
exit(0);
}
}
return 0;
}
void *func2(void *message){
while(1){
flag[1] = 1;
turn = 0;
while(flag[0] && turn == 0);
printf("%s %d\n",(char *)message,counter);
counter++;
flag[1] = 0;
if(counter == 10){
counter = 1;
printf("exited at func2, with counter %d\n",counter);
exit(0);
}
}
return 0;
}
Obviously, when one thread resets the global counter, the other thread may never see the global counter reaching e.g.10, so it will never quit. What if you simply don't reset the global counter, and let it thread quit whenever it finds the global counter e.g. 10? If you really want to reset the counter, you do that in the parent (main) thread (which is also where you define the global counter).
As for quitting a thread, you can either simply return from the primary thread function (this will end the thread by itself), call pthread_exit from within the thread, or you can use phtread_cancel from the main function.

Move robot set number of steps (Arduino)

I want to move my robot a set number of steps and then have it stop. However the loop just seems to run on infinitely. Is there a mistake in the way that I am using void loop() or perhaps in the way that I have written my 'for' loop?
// walkerForward.pde - Two servo walker. Forward.
// (c) Kimmo Karvinen & Tero Karvinen http://BotBook.com
// updated - Joe Saavedra, 2010
#include <Servo.h>
Servo frontServo;
Servo rearServo;
int centerPos = 90;
int frontRightUp = 75;
int frontLeftUp = 120;
int backRightForward = 45;
int backLeftForward = 135;
void moveForward(int steps)
{
for (int x = steps; steps > 0; steps--) {
frontServo.write(centerPos);
rearServo.write(centerPos);
delay(100);
frontServo.write(frontRightUp);
rearServo.write(backLeftForward);
delay(100);
frontServo.write(centerPos);
rearServo.write(centerPos);
delay(100);
frontServo.write(frontLeftUp);
rearServo.write(backRightForward);
delay(100);
}
}
void setup()
{
frontServo.attach(2);
rearServo.attach(3);
}
void loop()
{
moveForward(5);
}
the loop() function is executed within an infinite loop (if you check the main cpp file that ships with the Arduino IDE, you'll see something like this:
int main()
{
setup();
for (;;) {
loop();
}
return 0;
}
So either put the call to your moveForward() function to setup() and make loop() an empty function, or call exit(0); from within loop() after moveForward(). The first approach looks like this:
void setup()
{
frontServo.attach(2);
rearServo.attach(3);
moveForward(5);
}
void loop()
{
}
And the second one looks like this:
void setup()
{
frontServo.attach(2);
rearServo.attach(3);
}
void loop()
{
moveForward(5);
exit(0);
}
Since you probably will want to eventually do more than move the robot just 5 steps, I'd suggest using a variable flag to hold the robot state. It only executes the movement routine when the flag has been set to true.
If you are using serial, when a move command is received (and the number of steps, direction perhaps?) you set the flag to true and then issue the move command. If you are using sensors or buttons, the same logic applies.
You will need some logic to handle an incoming movement command while a movement is occurring (though with your tight movement loop you actually won't be able to respond to incoming commands unless you use interrupts - but you want to consider this sort of thing if you are planning to build out a full movement bit of firmware).
boolean shouldMove;
void setup()
{
shouldMove = true;//set the flag
}
void loop()
{
if (shouldMove){
moveForward(5);
}
}
void moveForward(int steps)
{
shouldMove = false; //clear the flag
for (int x = steps; steps > 0; steps--) {
// tight loop controlling movement
}
}
}

How to break an infinite for(;;) loop in C?

I have a vital infinite for loop that allows a sensor to keep updating its values. However I would like to break that for loop when another sensor brings in new values. How can I switch from one infinite for loop to another?
Current code:
for(;;){
SON_Start();
// Wait 65ms for max range time
delay10ms(7);
// Read Range
i = SON_Read(SON_ADDRESSES[sonarReading]);
// pause
delayMs(100);
if(i<15)
drive(200, RadCW);
}
What I would like to add:
If Sensor2 returns a reading (e.g. Sensor2 > 20), then I want to break the loop and goto another infinite for loop to begin a new function.
If you are looking for "switching between 2 infinite loops" it could be "wrapped" by third loop and this "switching" could be done by simple break.
But since you want your program to stop some day, this loop could be placed within the function and you could use return; for ending it:
void myMagicLoop()
{
for(;;)
{
for(;;)
{
if ( I should stop )
return;
if ( I should switch to second loop )
break;
}
for(;;)
{
if ( I should stop )
return;
if ( I should switch back to first loop)
break;
}
}
}
And somewhere you just call:
myMagicLoop();
Hope this helps.
This will switch between loop A and loop B.
for (;;)
{
// Loop A
for (;;)
{
if WANT_TO_SWITCH
{
break;
}
}
// Loop B
for (;;)
{
if WANT_TO_SWITCH
{
break;
}
}
}
You use break; to break a loop and pass control beyond its closing brace. For example
for(;;) {
if( whatever ) {
break;
}
}
//break gets you here
Alternatively you could consider rewriting this with an event-driven approach. This will of course depend on what your hardware is capable of, but at the very least you should be able to produce some timer events.
Then the code would go something like this:
static volatile bool sensor_1_ready;
static volatile bool sensor_2_ready;
for(;;)
{
switch(state_machine)
{
case READING_SENSOR_1:
if(sensor_2_ready)
{
state_machine = READING_SENSOR_2;
}
else if(sensor_1_ready)
{
process sensor 1
}
break;
case READING_SENSOR_2:
if(!sensor_2_ready && some_timeout_etc)
{
state_machine = READING_SENSOR_1;
}
else if(sensor_2_ready)
{
process sensor 2
}
break;
}
}
void callback_sensor_1 (void) // some sort of interrupt or callback function
{
sensor_1_ready = true;
}
void callback_sensor_2 (void) // some sort of interrupt or callback function
{
sensor_2_ready = true;
}
(Before commenting on the volatile variables, please note that volatile is there to prevent dangerous compiler optimizations and not to serve as some mutex guard/atomic access/memory barrier etc.)
The "break" command should do what you need?
The best way to do that is to change the for statement to something like:
for (; Sensor2 <= 20;) {
...
Alternatively you can change it from a for to a while statement:
while (Sensor2 <= 20) {
...
If that doesn't suite your needs you can always use a break instead.
Another option could be to use signals (SIGUSR1,SIGUSR2) to switch from one loop to another.
Something of this sort:
void sensor2(int signum)
{
for (; ;)
...
/* Need to process sensor 1 now */
kill(pid, SIGUSR1);
}
void sensor1(int signum)
{
for (; ;)
...
/* Need to process sensor 2 now */
kill(pid, SIGUSR2);
}
int main()
{
/* register the signal handlers */
signal(SIGUSR1, sensor1);
signal(SIGUSR2, sensor2);
...
}

Resources