Embedded C counter between two values - c++

Please help with my issue.
I am trying to avoid going out of the limit between 0 to 100 for the count up/down value in the program below;
I am using an 8051 microcontroller and 2x16 LCD to display a value between 0 and 100. when pressing the UP button the number increased by one, while when pressing down button it decreased by one.
my code keeps incrementing the value above 100 and less 0.
// This is a code in Embedded C written on MikroC compiler for 8051 microcontroller
// The microcontroller shall count up / down on the LCD when press up / down button.
unsigned int cntr=0; // counter value
char lcdv[6]; // Value to displau on lcd
sbit UP at P3.B7; // declare button UP at port 3 Bit 7.
sbit DN at P3.B6; // declare button UP at port 3 Bit 6.
// LCD module connections
sbit LCD_RS at P2_0_bit; // Declare LCD reset pin.
sbit LCD_EN at P2_1_bit; // Declare LCD Enable pin.
sbit LCD_D4 at P2_2_bit; // Declare LCD D4 pin.
sbit LCD_D5 at P2_3_bit; // Declare LCD D5 pin.
sbit LCD_D6 at P2_4_bit; // Declare LCD D6 pin.
sbit LCD_D7 at P2_5_bit; // Declare LCD D7 pin.
// End LCD module connections
char text[16]; // this is stored in RAM
void main() { // Main program
P3 = 255; // Configure PORT3 as input
Lcd_Init(); // Initialize LCD
cntr=0; // Starting counter value
Lcd_Cmd(_LCD_CLEAR);
Lcd_Cmd(_LCD_CURSOR_OFF);
while(1) {
while ((cntrset<=100)&&(cntrset>=0)) // Not sure how to limit Min and Max value.
{
wordTostr(cntrset,volset);
LCD_Out(2,1,volset);
if (UP==0)
cntrset ++;
while (UP==0);
if (DN==0)
cntrset=--;
while (DN==0);
}
}
}

if (UP==0 && cntrset < 100 ) cntrset++;
while (UP==0);
if (DN==0 cntrset > 0 ) cntrset--;
while (DN==0);
You may still have an issue with switch bounce causing a single press to result in the counter changing by more than one count. But that is a different question.
Regarding comment: If the increment is not by-one and the current value need not be a multiple of the increment, then it is easier to apply saturation instead:
if( UP == 0 ) cntrset += increment;
while (UP==0);
if( DN == 0 ) cntrset -= increment ;
while (DN==0);
if( cntrset < 0 ) cntrset = 0 ;
else if( cntrset > MAX_CNTRSET ) cntrset = MAX_CNTRSET ;
For that to work however you must change cntrset to signed int. If you'd rather not do that then (assuming 16 bit unsigned):
...
if( (cntrset & 0x8000u) != 0 ) cntrset = 0u ;
else if( cntrset > MAX_CNTRSET ) cntrset = MAX_CNTRSET ;

Related

button that turns off all features

I am new to coding and embedded systems and I wanted to make a button that turns off and on a LED and at the same time turn off all other futures in the system.
So far I had the button turn off and on but I cant seem to get it to also update the Potentiometer. For some reason the code would check if the button is pressed and if so then the LED would turn on and then check if the LED is on and if so then turn on the other LEDs but when I change the value of the Potentiometer( which should switch to other LEDs) it would not update and stay on the same LED. So my question is how can I put another if statement that would keep updating in the while loop?
the code that I wanted to keep updating while the first LED is on is the "else if code"
Hope that made sense.
:)
note:
I don't know if my approach is right as I am looking at the LED and not the button it self, as my code checks if the LED is on rather then if the button is pressed.
(btw its not a switch which would have made my life a lot easier :( )
#include "mbed.h"
DigitalIn userButton (PC_10);
DigitalOut led (PC_0);
bool buttonDown = false;
BusOut leds_bus (PC_1, PB_0, PA_4);
AnalogIn pot1 (PA_5);
void init_leds ();
int cntl_val = 0;
int main ()
{
cntl_val = pot1.read_u16 () / 32768;
while (true)
{
// run forever
if (userButton.read () == true)
{
// button is pressed
if (!buttonDown)
{
// a new button press
led = !led; // toogle LED
buttonDown = true; // record that the button is now down so we don't count one press lots of times
ThisThread::sleep_for (100);
}
else if (led.read () == true)
{
if (cntl_val < 1 / 3)
{
leds_bus.write (4);
}
if (cntl_val > (1 / 3) && cntl_val < (2 / 3))
{
leds_bus.write (2);
}
if (cntl_val > (2 / 3))
{
leds_bus.write (1);
}
}
}
else
{
// button isn't pressed
buttonDown = false;
}
}
}
You need to fix your math. int cntl_val is an integer so comparing it with the fractions 1/3 and 2/3 is not going to do what you expect. And cntl_val = pot1.read_u16()/32768; can set cntl_val to only 0 or 1. If the max value returned by pot.read_u16() is less than 32768 then cntl_val will only be 0.
You could maybe change cntl_val to a float but that's probably not the best option.
Instead, try setting cntl_val = pot1.read_u16(); (don't divide by 32768). And then compare cntl_val with (32768/3) and (32768*2/3). That's still ugly but better.
It is not clear from your description, but I am assuming that you have:
An on/off indicator LED
A three-LED level indicator
A momentary action button for on/off control
A potentiometer to control the input level.
And that when the system is in the "on" state you wish to indicate the potentiometer level on the level indicator? That being the case, I suggest:
Deal with button input/debounce separately from LED state determination.
Simplify the level setting; you have a level 0, 1 or 2 which you can calculate by unsigned level = (InputLevel * 3) / 32768 ;. You can then use that level value in a bit-shift (1 << level) to determine the LED to be set. Note that you had the low level set the high bit in your LED level indicator - that would require (4 >> level), which is somewhat clumsy if you were to ever increase the number of LEDs. It is easier to reverse the order of the GPIO in the BusOut object.
Additional advice:
Apply the rule of "minimal scope", localising variables to the minimum necessary scope (you have a number of unnecessary globals.
In "big-loop" scheduling, avoid thread delays during which useful work might otherwise be done. Your debounce delay unnecessarily determines the rate at which other work can be done in the loop. The advice would be different if you were polling the button and setting the LEDs in separate threads.
For example (not this is coded blind/untested - treat it as illustrative of the general principles - it may need debugging):
#include "mbed.h"
int main ()
{
static const unsigned DEBOUNCE_MS = 20u ;
static const unsigned NUMBER_OF_LEVELS = 3u ;
DigitalIn OnOffButton( PC_10 ) ;
DigitalOut OnOffLed( PC_0 ) ;
BusOut LevelIndicator( PA_4, PB_0, PC_1 ) ;
AnalogIn InputLevel( PA_5 ) ;
bool isOn = false ;
int previous_button_state = OnOffButton ;
std::uint64_t button_change_time = 0 ;
for(;;)
{
// If debounce time expired check for button state change
if( Kernel::get_ms_count() - button_change_time > DEBOUNCE_MS )
{
int current_button_state = OnOffButton ;
// If button state changed
if( current_button_state != previous_button_state )
{
// If button-down
if( current_button_state != 0 )
{
// Toggle isOn
isOn = !isOn ;
}
// Change of state and debounce update
previous_button_state = current_button_state ;
button_change_time = Kernel::get_ms_count() ;
}
}
// Set the LEDs depending on On/Off state and input level
if( isOn )
{
OnOffLed = 1 ;
// Set level indicator
LevelIndicator = 1 << (InputLevel.read_u16() * NUMBER_OF_LEVELS / 32768u) ;
}
else
{
// System inactive (Off)
LevelIndicator = 0 ;
OnOffLed = 0 ;
}
}
}
You might also consider separating out the button and indicator processing into separate functions to increase cohesion, minimise coupling, simplify testing and improve maintainability and comprehensibility.
#include "mbed.h"
void updateIndicators( bool isOn ) ;
bool getOnOffState() ;
int main ()
{
for(;;)
{
updateIndicators( getOnOffState() ) ;
}
}
bool getOnOffState()
{
static const unsigned DEBOUNCE_MS = 20u ;
static DigitalIn OnOffButton( PC_10 ) ;
static bool state = false ;
static int previous_button_state = OnOffButton ;
static std::uint64_t button_change_time = 0 ;
// If debounce time expired check for button state change
if( Kernel::get_ms_count() - button_change_time > DEBOUNCE_MS )
{
int current_button_state = OnOffButton ;
// If button state changed
if( current_button_state != previous_button_state )
{
// If button-down
if( current_button_state != 0 )
{
// Toggle isOn
state = !state ;
}
// Change of state and debounce update
previous_button_state = current_button_state ;
button_change_time = Kernel::get_ms_count() ;
}
}
return state ;
}
void updateIndicators( bool isOn )
{
static const unsigned NUMBER_OF_LEVELS = 3u ;
static DigitalOut OnOffLed( PC_0 ) ;
static BusOut LevelIndicator( PA_4, PB_0, PC_1 ) ;
static AnalogIn InputLevel( PA_5 ) ;
// Set the LEDs depending on On/Off state and input level
if( isOn )
{
OnOffLed = 1 ;
// Set level indicator
LevelIndicator = 1 << (InputLevel.read_u16() * NUMBER_OF_LEVELS / 32768u) ;
}
else
{
// System inactive (Off)
LevelIndicator = 0 ;
OnOffLed = 0 ;
}
}

Arduino millis() print values one after other

I don't know if someone else asked this before.
I'm trying to print in Serial screen the number 1 - 6, ONE number every 5 seconds (I'm trying only with number 1 and number 2 for smaller and easier to undestand and modify code). I could use delay function, but i want to use millis function, because i don't want to block the code using delay in loop.
This code problem is a part of bigger project.
I tryied to print the numbers using different interval times (eventTime_1 and eventTime_2), but it didn't work.
The code is
/* Two independant timed evenets */
const unsigned long eventTime_1 = 1000; // interval in ms
const unsigned long eventTime_2 = 5000;
unsigned long previousTime_1 = 0;
unsigned long previousTime_2 = 0;
void setup() {
// To Do: Serial communication
Serial.begin(9600);
}
void loop() {
/* Updates frequently */
unsigned long currentTime = millis();
// To Do: Event 1 timing
/* This is event 1 stuff */
if ( currentTime - previousTime_1 >= eventTime_1 ) {
Serial.println (" 1 ");
// Serial.println(currentTime);
// Serial.println(previousTime_1);
/* Update the timing for the next event */
previousTime_1 = currentTime;
}
// To Do: Event 2 timing
/* This is event 2 stuff */
if (currentTime - previousTime_2 >= eventTime_2 ) {
Serial.println ("2");
// Serial.println( analogRead(tempSensor) );
/* Update the timing for the next event */
previousTime_2 = currentTime;
}
}
As a result, prints 5 times the number 1 and after 5 seconds 1 time the number 2.
This is what i ecpect:
12:16:53.212 -> 1
12:16:58.225 -> 2
12:17:03.233 -> 1
12:17:08.238 -> 2
12:17:13.203 -> 1
12:17:18.272 -> 2
This is the final working code. From this code you can print 1 and 2 alternating every X second (x depends from you, in eventTime = X ; In my code is 5000).
// To Do: Variables for Timed Events
/* Create timed evenets */
const unsigned long eventTime = 5000;
unsigned long previousTime = 0;
/* Create a flag */
boolean flag1 = false;
void setup() {
// To Do: Serial communication
Serial.begin(9600);
}
void loop() {
/* Updates frequently */
unsigned long currentTime = millis();
if (currentTime - previousTime >= eventTime ) {
if (flag1 == false) {
Serial.println("1");
flag1 = true;
}
else if (flag1 == true) {
Serial.println ("2");
flag1 = false;
}
/* Update the timing for the next event */
previousTime = currentTime;
}
}
And the results are:
15:32:46.342 -> 1
15:32:51.402 -> 2
15:32:56.327 -> 1
15:33:01.325 -> 2
15:33:06.328 -> 1
15:33:11.325 -> 2
15:33:16.327 -> 1

Why does debounce code not work with 2 or more objects?

I have written a debounce class to debounce inputs.
The idea was that a state of a certain input may be ON, OFF, FALLING or RISING.
the object.debounceInputs() is to be called with a fixed interval
With the the function object.readInput() the correct state of the object could be read in. A FALLING or RISING state only lasts for 1 interval time (usually set at 20ms) and these states can only be read once.
Ofcourse I tested the software and it worked without flaw, now I started using the software in other projects and a peculiar bug came to light.
The software works perfectly fine... if you have just one input object. If you debounce more than 1 object, the inputs are affecting each other which should not be possible as every object uses private variables.
The source code:
#include "debounceClass.h"
Debounce::Debounce(unsigned char _pin) {
pinMode(_pin, INPUT_PULLUP); // take note I use a pull-up resistor by default
pin = _pin;
}
unsigned char Debounce::readInput() {
byte retValue = state;
if(state == RISING) state = ON; // take note I use a pull-up resistor
if(state == FALLING) state = OFF; // rising or falling may be returned only once
return retValue;
}
void Debounce::debounceInputs() {
static bool oldSample = false, statePrev = false;
bool newSample = digitalRead(pin);
if(newSample == oldSample) { // if the same state is detected atleast twice in 20ms...
if(newSample != statePrev) { // if a flank change occured return RISING or FALLING
statePrev = newSample ;
if(newSample) state = RISING;
else state = FALLING;
}
else { // or if there is no flank change return PRESSED or RELEASED
if(newSample) state = ON;
else state = OFF;
}
}
oldSample = newSample;
return 255;
}
The corresponding header file:
#include <Arduino.h>
#ifndef button_h
#define button_h
//#define
#define ON 9 // random numbers, RISING and FALLING are already defined in Arduino.h
#define OFF 10
class Debounce {
public:
Debounce(unsigned char _pin);
unsigned char readInput();
void debounceInputs();
private:
unsigned char state;
unsigned char pin;
};
#endif
I have had this bug with 2 separate projects, so the fault definitely lies in my Debounce class.
An example program to illustrate the program:
#include "debounceClass.h"
const int pin3 = 3 ;
const int pin4 = 4 ;
Debounce obj1( pin3 ) ;
Debounce obj2( pin4 ) ;
byte previousState1, previousState2;
unsigned long prevTime = 0, prevTime1 = 0, prevTime2 = 0;
void setup()
{
Serial.begin( 115200 ) ;
// CONSTRUCTOR OF OBJECTS SETS THE PINMODE TO INPUT_PULLUP
pinMode( pin3, OUTPUT ) ;
pinMode( pin4, OUTPUT ) ;
}
const int interval = 20, interval1 = 1000, interval2 = 2000;
void loop() {
unsigned long currTime = millis() ;
if( currTime > prevTime + interval ) {
prevTime = currTime ;
obj1.debounceInputs(); // comment one of these 2 out, and the other debounces perfectly
obj2.debounceInputs();
#define printState(x) case x: Serial.print(#x); break
byte state = obj1.readInput() ;
if( state != previousState1 ) {
previousState1 = state ;
Serial.print("state of obj1 = ") ;
switch ( state ) {
printState( ON ) ;
printState( OFF ) ;
printState( RISING ) ;
printState( FALLING ) ;
}
Serial.println();
}
state = obj2.readInput() ;
if( state != previousState2 ) {
previousState2 = state ;
Serial.print("state of obj2 = ") ;
switch ( state ) {
printState( ON ) ;
printState( OFF ) ;
printState( RISING ) ;
printState( FALLING ) ;
}
Serial.println();
}
}
if( currTime > prevTime1 + interval1 ) {
prevTime1 = currTime ;
digitalWrite( pin3, !digitalRead( pin3 ) );
}
if( currTime > prevTime2 + interval2 ) {
prevTime2 = currTime ;
digitalWrite( pin4, !digitalRead( pin4 ) );
}
}
This program automatically toggles both pins so you do not need physical inputs. If you comment out one of the indicated lines, you'll see that the other pin is debounced just fine. But when both pins are debounced the result is catastrophic. There is a weird link between the 2 objects which I cannot explain. I have reached a point at which I start doubting the compiler, so that was the moment I realized that I need to ask others.
Why is this happening and what did I do wrong here?
I found the problem.
I cannot use a static variable within a class method. These static variables are seen by all objects which caused the problem.
I moved the static variables to the private variable section

Temp Sensors Max and Min

(Referring to the last if statement)I have some code here that keeps giving me the T_High always the same as T. If I am looking for the highest temperature that the code has seen, I am not sure if I need to add another variable and adjust my code or what my current problem is. I have tried looking this up online about max and mins, but even with multiple different sources I was not able to get it to work. I understand that after my if statement I have them being equaled to each other, but I thought that the if statement would take care of this. This is in particle IDE (very similar to Arduino).`
#include <math.h>
const int thermistor_output = A1;
void setup() {
Serial.begin(9600);
}
void loop() {
float T_Low = 999;
float T_High;
int x=0;
int thermistor_adc_val;
double a,b,c,d,e,f,g,h,i,j,T;
double output_voltage, thermistor_resistance, therm_res_ln, temperature_celsius;
while (x < 10 )
{
thermistor_adc_val = analogRead(thermistor_output);
output_voltage = ( (thermistor_adc_val * 3.3) / 4095.0 );
thermistor_resistance = ( ( 3.3 * ( 10.0 / output_voltage ) ) - 10 ); /* Resistance in kilo ohms */
thermistor_resistance = thermistor_resistance * 1000 ; /* Resistance in ohms */
therm_res_ln = log(thermistor_resistance);
/* Steinhart-Hart Thermistor Equation: */
/* Temperature in Kelvin = 1 / (A + B[ln(R)] + C[ln(R)]^3) */
/* where A = 0.001129148, B = 0.000234125 and C = 8.76741*10^-8 */
temperature_celsius = ( 1 / ( 0.001129148 + ( 0.000234125 * therm_res_ln ) + ( 0.0000000876741 * therm_res_ln * therm_res_ln * therm_res_ln ) ) ); /* Temperature in Kelvin */
temperature_celsius = temperature_celsius - 273.15; /* Temperature in degree Celsius */
T = temperature_celsius * 1.8 + 29; /* Temperature in degree Fahrenheit */
delay(100);
x ++ ;
if (x==1){a=T;}
if (x==2){b=T;}
if (x==3){c=T;}
if (x==4){d=T;}
if (x==5){e=T;}
if (x==6){f=T;}
if (x==7){g=T;}
if (x==8){h=T;}
if (x==9){i=T;}
}
j=a+b+c+d+e+f+g+h+i;
T=j/9;
x=0;
delay(2000);
if (T > T_High) {
T_High = T;
}
Particle.publish ("Temp", String(T));
Particle.publish ("High", String(T_High));
}
`
T_High is a local variable in loop(). It exists only until the loop() function exits. In the next iteration there will be a new instance of the T_High variable that has no relation to the previous one. Therefore you are not saving T_High's value throughout calls to loop().
Move the variable into file scope (i.e. outside the function definitions), so that it has static storage duration and survives throughout the whole program execution.
Also, you never initialize T_High to a value or assign to it before you do the test T > T_High. At this point T_High has indeterminate value and using an indeterminate value in almost any way causes the program to have undefined behavior, as is the case here.
If you move the variable to file scope, this particular problem will be remedied automatically, because static storage duration objects are always zero-initialized, but still it is advisable to initialize T_High to a sensible value, e.g.:
float T_High = 0;
or whatever works for your use case.

Controling Light With Photoresistor And Serial Communication - Arduino

I'm trying to turn a light "On" and "Off" with Arduino using a Relay, Photo-resistor and Serial Communication. The problem come in to play when I try to turn the light Off when the Photo-resistor is receiving a low value and has received an instruction via Serial Communication to prevent the "IF" statement from activating, it simply doesn't not work as the light is kept on.
I'm using 4 "IF" statement to control the light: auto light using Photo-resistor and serial value resumed in "ON/OFF", turn light on using serial value "h", turn light off using serial value "l" and another serial value to control the auto light statement using "a" to control the first statement.
How can I use a value to control light based on a sensor and serial output at the same time. In other words, how can I stop light from turning on automatically?? What I'm doing wrong or what I left?
Here is my simple code:
char val;
boolean setAuto=true; // Automatic Light Status Value
int ldr;
int relayPin=4;
void setup() {
pinMode(relayPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
ldr = analogRead(A0); // Read value from Photoresistor
if ( Serial.available()) {
val = Serial.read(); // Get serial value
}
if ( setAuto == true && ldr < 50 ) { // Here is the main problem
digitalWrite(relayPin, HIGH);
}
else if ( val == 'h' ) {
digitalWrite(relayPin, HIGH); // Work
}
else if ( val == 'l') {
digitalWrite(relayPin, LOW); // Work
}
else if (val == 'a') { // Here is the other part of the problem
setAuto = !setAuto; // Changing value for automatic light
}
}
The first if statement:
if ( setAuto == true && ldr < 50 ) { // Here is the main problem
digitalWrite(relayPin, HIGH);
} else {
takes precedence over the next two if statements. Since setAuto is ALWAYS true and so when ldr < 50 the light thru relayPin is ON.
Think about how you might want to setAuto to false.
Hint. You might want to evaluate val just after it is read:
if ( Serial.available()) {
val = Serial.read(); // Get serial value
if (val == ..... logic to affect the course of events.....
}