Make a microcontroller always notice a button press even while waiting(Delay) - c

Here im using the stm32l discovery microcontroller.
First i initialize the ports for the gpio ports for the leds and the user button.
I have it working now and the little program i have now makes the led blink.
Every time you press the button the waiting time gets longer making the led blink longer. the problem now is that as soon as the waiting time exeeds 4 seconds or more its to hard for the microcontroller to notice the button press.
Is there a way to make it that it always notices a button press
int main(void) {
char *RCCp = (char*) 0x40023800;
int *PAp = (int *) 0x40020000;
int *PBp = (int *) 0x40020400;
// RCC Config
*((int*) (RCCp + 28)) |= 0x3f;
*((int*) (RCCp + 32)) |= 1;
// Pin config
*PBp = 0x5000;
*PAp = 0x0000;
int speed = 100000;
int i = 0;
while (1) {
while (i++ < speed); // Waiting time
*(int*) (0x40020414) ^= 0xC0;
i = 0;
if ((*(int*) (0x40020010) & 0x0001) != 0x0) {
speed = speed * 2;
if (speed > 400000) {
speed = 100000;
}
}
}
return 0;
}

One small step forward is to poll the switch status within your busy-wait loop. Like this:
int i = 0;
while (1) {
bool wasSwitchClosedThisPeriod = false;
while (i++ < speed) {
// Poll the switch to see if it is closed.
if ((*(int*)(0x40020010) & 0x0001) != 0) {
wasSwitchClosedThisPeriod = true;
}
}
*(int*) (0x40020414) ^= 0xC0;
i = 0;
if (wasSwitchClosedThisPeriod) {
speed = speed * 2;
if (speed > 400000) {
speed = 100000;
}
}
}
But there is still a lot of room for improvement. For example, you may want to debounce the switch. The switch data register should be volatile, i.e. *(int volatile *)(0x40020010UL). And using interrupts could make the code more flexible, efficient and even allow you to put the microcontroller to sleep while it waits (conserving power). If the GPIO input pin can be configured as an interrupt then you wouldn't need to poll the switch. And if there's a hardware timer available then you could configure it to interrupt when it's time to change the LED.

Related

blinking an led using timer interrupt (atmega 128)

I'm trying to blink an led without using the delay function.
I came across using the timer interrupt and I tried it, and it compiles fine. But the output is fixed on PORTA = 0x01; so, I believe the ISR function is not working. Is there anything I am missing in the code? Thanks.
#include <asf.h>
#include <avr/interrupt.h>
volatile unsigned int count=0;
volatile unsigned int tTime=0;
void port_init(void) {
PORTA = 0xff;
}
ISR(TIMER0_OVF_vect)
{
TCNT0 = 206;
count++;
if (count < 625) {
PORTA=0x01;
}
else if ((count > 625) && (count < 1250)) {
PORTA=0x00;
}
else {
count=0;
}
}
int main (void)
{
board_init();
port_init();
TCCR0 = 0x06; //setting dispensing ratio
TCNT0 = 206; //initial value of register
TIMSK = 0x01; //enabling interrupt
SREG=0x80;
DDRA=0xff;
while(1){
}
}
You have a logic error in your ISR() function. Once count hits 625 the first two if/else-if clauses will be false (because 625 is neither less than, nor greater than, 625), thus the final else clause will execute and reset count to zero. The result of this is that the else-if clause that sets PORTA=0x00 will never execute.
To fix, change the first if from < to <=, like so:
if (count <= 625) {

Design for a C Program Using Timer2 Interrupts

I'm programming my C code onto a PIC board. My question is how to get my program to count how long a button (RB0) is pressed down. It then displays the time it took and display it on an LCD Display. It counts in ms. Below is my code so far.
// Global Variables
unsigned int COUNTER;
// Subroutine Declarations
#include <pic18.h>
#include "lcd_portd.c"
//LCD routine, modified from previous examples
void LCD_Out(unsigned int STUFF, unsigned char A)
{
unsigned char C[5], i;
for (i=0; i<5; i++)
{
C[i] = STUFF % 10;
STUFF = STUFF / 10;
}
for (i=5; i>0; i--)
{
if (i == A) LCD_Write('.');
LCD_Write(C[i-1] + '0');
}
}
void interrupt IntServe(void)
{
if (TMR2IF)
{
RB0 = !RB0;
TMR2IF = 0;
COUNTER = COUNTER + 1;
}
}
// Main Routine
void main(void)
{
//Instantiate all Ports to ready for Timers and pin sets
LCD_Init();
TRISA = 0;
TRISB = 0;
TRISC = 0;
TRISD = 0;
TRISE = 0;
ADCON1 = 0x0F;
//Timer Interrupt for 1 ms, A = 9, C = 4, B = 250
//Which means PR2 = 249, and # is x1001101 = 0x4D
T2CON = 0x4D;
PR2 = 249;
TMR2IE = 1;
PEIE = 1;
TMR2ON = 1;
TMR2IP = 1;
GIE = 1;
// While Loop displays length of Wait through Counter
while(1)
{
LCD_Move(0,0);
LCD_Out(COUNTER,3);
}
}
you need figure out how your button is connected to your microcontroller and declare that port in you main function. Make sure you are able to read the state of the port (i.e. button up or button down).
Then it your IntServe interrupt check if the button is down, if it is increment COUNTER.
The COUNTER is an integer, so it will only be able to count upto 65,535 ms (about 65 seconds), you may want to implement a second count variable for overflow, so that you can count button presses longer than 65 seconds.

PIC16F883 Led Blink

I need to program a PIC16F883 to blink / light up LED's at the same time. The oscillator is running at 3,2768, and I'm using TIMER0 to help me with the timing.
Right now, I have a prescaler set to 1:256, so I get an interrupt every 50ms, and I have a variable that is calculated from that, to display how many seconds has gone.
If the input is changed, the seconds variable is of course reset again.
Here is the assignment from my teacher:
If Input is 0 (Closed):
The Red And The Green LED should be turned on at the same time for 15 seconds. After this the green LED should be turned
off completely, and the red LED should blink every fifth second for 10 minutes
If input is 1 (Opened):
The red LED should be turned off completely, and the green LED should be turned on for 10 minutes, and after that
it should be turned off too.
My timer is working fine. I have tested that. The program runs fine too and keeps the 2 LED's turned off for 15 seconds, then turns them off, but my red LED isn't blinking. I have been sitting at my desk all day desperately trying to find the error in my code.
Picture of the print:
Here is my C Code. I am using MPLab and the HI-TECH C compiler :)
#include <pic.h>
//Variabler
int B = 0; //Definerer variablen B, used as a flag
int A = 0; //Definerer veriablen A, used as a flag
int E = 0;
int savedstatus = 1; //Definere variablen savedstatus used to check last status for input
int millicounter = 0; //Variabel to calculate seconds
int sec = 0; //Variabel holding seconds gone
int count = 0; //For counting seconds passed, used in input0 subroutine
int onesec = 0; //Used to counting seconds for blinking LED in input0 subroutine
int scount = 0;
//Variabler slut
void interrupt jesper(void)
{
T0IF = 0x00;
TMR0 = 96;
millicounter++;
if(millicounter == 20)
{
sec++;
millicounter = 0;
}
}
//Subrutines
void input0()
{
if(sec<=15 && E==0)
{
PORTA = 0x21;
}
else if(A==0)
{
scount = 0;
sec = 0;
count = sec;
A = 1;
E = 1;
}
else if(sec<=600 && sec>count)
{
count++;
if((scount+5)>=count)
{
if(B==0)
{
onesec = sec;
B = 1;
PORTA = 0x01;
}
else if(sec>onesec)
{
PORTA = 0x00;
B = 0;
scount = count;
scount;
}
else
{
PORTA = 0x01;
}
}
else
{
PORTA = 0x00;
}
}
else PORTA = 0x00;
}
void input1()
{
if(sec<=600)
{
PORTA = 0x20;
}
else
{
PORTA = 0x00;
}
}
//Subrutines over
int main(void)
{
TRISA = 0x00; //Sets all A-PORTS to output
TRISB = 0x01; //Sets all PORTB to output with the exception of BIT0
TRISC = 0x00; //Sets All PORTC to output
ANSEL = 0x00; //Disable Analog ports
ANSELH = 0x00; //Disable Analog ports
//Timer Config
PSA = 0x00;
PS0 = 0x01;
PS1 = 0x01;
PS2 = 0x01;
TMR0 = 0x60;
GIE = 0x01;
T0IE = 0x01;
T0IF = 0x00;
T0CS = 0x00;
//Timer Config Over
while(0x01)
{
if(savedstatus != RB0)
{
savedstatus = RB0;
sec = 0;
E = 0;
A = 0;
}
if(savedstatus == 1)
{
input1();
}
else
{
input0();
}
}
}
I really hope that you can help me here :)
Here is my flowchart for the subroutine input0 where my problem is. Btw some of my variables have different names in the code itself, but it shouldn't be hard to see.
Your main() calls input0() as often as possible. When input0() is in the flashing state it uses the conditional sec > count. I suspect that your intention is that input0() should only change the LED state at intervals of a second. But then on the else side of that conditional you turn both LEDs off. This else side is executing many times because main() is calling input0() so often. Try deleting the else condition where you turn the LEDs off.
void input0()
{
<snip>
else if(sec<=600 && sec>count)
{
<snip>
}
else PORTA = 0x00; // <-- delete this line so you're not always turning the LED off
}

is it possible compare a 16-bit value with a 8-bit compare match ISR

I am trying to make a servo controller that have a higher resolution than the ATtiny85 8-bit timer/counter. So far I have managed to get about 2000 positions on my servo (1µs/step) within a time frame of 21'000 µs. I have also managed to move 5 servos sequential and with different speed, but now I want to move them synchronous.
My biggest problem is that I don't get how I should make it happen! I have looked around on other servo codes including servo8bit library and tried to find a way. It seems that most of the examples uses compare match ISR to move the servos "at the same time", my problem is that I have a 16-bit integer that I want to compare.
Is there a way to do some magic so I can use the 8-bit compare match ISR with my 16-bit integer? Or does anyone of you have some other suggestions on how I can move my servos synchronous without using compare match ISR?
I hope my questions make sense!
Since I don't really have any code to show yet (only flawed attempts without compar match ISR that makes no sense) I post the link to my TinyServo code if it helps.
EDIT 1:
Here is the part of the code I mentioned and didn't post the first time:
void servoMove(void)
{
uint16_t nextPulse = hPulse[0];
timerSetup (); //16-bit setup for counter
for (i = 0; i < sizeof(servo)/sizeof(servo[0]); i++)
{
if ( (oTime > nextPulse) && (channel < sizeof(servo)/sizeof(servo[0])) ) //check if HIGH pulse (pos) is done
{
PORTB &= ~(1 << servo[channel]);
if (i+1 < sizeof(hPulse)/sizeof(hPulse[0]))
{
nextPulse += hPulse[i+1];
}
channel++;
}
else
{
channel = 0;
oTime = 0; //resets 16-bit variable
tot_overflow = 0; //resets tot_overflow variable
TIFR |= (1 << TOV1); // clear counter1 overflow-flag
TCNT1 = 0; //resets Timer/Counter1
}
}
for (i = 0; i < sizeof(servo)/sizeof(servo[0]); i++)
{
if ( (oTime > tPulse - nextPulse) && (channel < sizeof(servo)/sizeof(servo[0])) ) //check if LOW pulse (period) is done
{
PORTB |= (1 << servo[channel]);
nextPulse -= hPulse[i];
channel++;
}
}
}
void servoPosSet(volatile uint16_t pos[], uint8_t size)
{
for (i = 0; i < size; i++)
{
hPulse[i] = pos[i];
}
}
int main(void)
{
TCCR1 |= (1 << CS12); //set Timer/Counter1 prescaler to increment every 1 µs (PCK/8)
for (channel = 0; channel < size); channel++)
{
DDRB |= (1 << servo[channel]); //sets PB0-PB4 as output pins
}
channel = 0;
uint16_t pos[] = {2000, 1500, 1900, 1300, 1700};
uint8_t size = 5;
while(1)
{
servoPosSet(pos);
servoMove();
}
}
EDIT 2:
This is an illustration of how I think the code should work:
...but it does not!
If you have nothing else to do during the pulse, you could use a busy
loop instead of interrupts:
#include <avr/io.h>
#include <util/delay_basic.h>
/* Send a pulse of width = 4*count cycles. */
void pulse(uint16_t count, uint8_t channel)
{
uint8_t mask = 1 << channel,
old_port = PORTB,
high = old_port | mask,
low = old_port & ~mask;
PORTB = high;
_delay_loop_2(count);
PORTB = low;
}
This will give you a resolution of 4 clock cycles, or 0.5 µs with a
8 MHz clock.
Sending the pulses to the 5 servos should take at most 10 ms. Since
you repeat the pulse train every 21 ms, this leaves you 11 ms
to compute the next set of positions, which should be plenty. You could
program a timer to wake you up every 21 ms, then your main() may
look like:
int main(void)
{
static uint16_t pos[] = {4000, 3000, 3800, 2600, 3400};
uint8_t i;
/* Wake up every 21 ms. */
setup_timer();
sleep_enable();
for (;;) {
/* Update the servos. */
for (i = 0; i < 5; i++) pulse(pos[i], i);
/* Compute the next set of positions. */
...
/* Wait for timer interrupt. */
sleep_cpu();
}
}

Code optimizations in 8051

So, I have to do this challenge, which is to implement a camera surveillance system for a 8051 microcontroller.
These are the specifications:
Each camera is related to a movement sensor, and each time it detects a movement, the recording of this camera will be among the ones that will be registered and saved. If the sensor doesn't capture any movement for more than 5 seconds, this camera will not be recorded anymore;
If there's no camera on, the video recorder must be on "pause";
If more than one camera is on, a multiplexer (mux) have to be used to select the camera signals in a way so each camera is recorded during 3 seconds. This way, all the active cameras must be recorded during 3 seconds. If just one camera is active, it's signal must be the only one in the mux.
This I have already accomplished in the code below. And what we have to do now is to optimize the size of the code without the compiler optimizations. The code is 198 bytes by now, but I'm trying to get below 180 bytes.
Is it possible? I already tried to do the calculations of the #define, but the compiler already optimize that for me.
#include <REG51F.h>
#define TIMEOUT 50
#define TIMEOUT_REC 30
#define FrClk 12000000
#define FreqTimer0_emHz 10
#define VALOR_TH0 ((65536 - (FrClk /(12 * FreqTimer0_emHz ))) >> 8)
#define VALOR_TL0 ((65536 - (FrClk /(12 * FreqTimer0_emHz ))) & 0xFF)
data bit PAUSE_INT;
data bit PAUSE_TMP;
sbit PAUSE = P0^0;
sbit SENSOR1 = P0^1;
sbit SENSOR2 = P0^2;
sbit SENSOR3 = P0^3;
sbit SENSOR4 = P0^4;
sbit MUX0 = P0^5;
sbit MUX1 = P0^6;
data unsigned char CAM[4];
data unsigned char REC;
data unsigned char index;
data unsigned char count;
void timer0_int (void) interrupt 1 using 2 {
for (index = 0; index < 4; index++)
if(CAM[index])
CAM[index]--;
if (!PAUSE_INT && REC)
REC--;
else
{
REC = TIMEOUT_REC;
index = (index + 1) & 0x03;
for (count = 0; !CAM[index] && count < 4; index = (index + 1) & 0x03, count++);
MUX0 = index & 0x1;
MUX1 = index & 0x2;
PAUSE_INT = 0;
}
}
int main(void)
{
PAUSE_TMP = 1;
PAUSE_INT = 0;
index = 0;
//timer0_init
EA = 1;
TR0 = 0;
TMOD = (TMOD & 0xF0) | 0x01;
TH0 = VALOR_TH0;
TL0 = VALOR_TL0;
ET0 = 1;
TR0 = 1;
while(1) {
if (SENSOR1)
{
CAM[0] = TIMEOUT;
}
if (SENSOR2)
{
CAM[1] = TIMEOUT;
}
if (SENSOR3)
{
CAM[2] = TIMEOUT;
}
if (SENSOR4)
{
CAM[3] = TIMEOUT;
}
if (CAM[0] || CAM[1] || CAM[2] || CAM[3])
{
if (PAUSE_TMP)
PAUSE_INT = 1;
PAUSE_TMP = 0;
}
else {
PAUSE_TMP = 1;
}
PAUSE = PAUSE_TMP;
}
}
You're probably going to have to look at the generated assembly code for this in order to wring the last few bytes out of it. It's probably possible to shave a few here and there by reusing a variable or combining operations. The resulting code won't be pretty - or maintainable - but it just might get you below your cutoff.
I think a switch case instead of if(sensor1,2,3,4) could help some.

Resources