Show Posts
Pages: [1] 2 3 ... 8
1  Using Arduino / Programming Questions / Debounce multiple push buttons on: November 20, 2013, 05:35:34 am
Below is the code for De-bouncing taken from the arduino Examples.

My question is this, If I want to De-bounce say 10 push buttons, will I have to write the De-bounce code 10 times


Code:
/*
 Debounce
 
 Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 a minimum delay between toggles to debounce the circuit (i.e. to ignore
 noise). 
 
 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached from pin 2 to +5V
 * 10K resistor attached from pin 2 to ground
 
 * Note: On most Arduino boards, there is already an LED on the board
 connected to pin 13, so you don't need any extra components for this example.
 
 
 created 21 November 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Limor Fried
 modified 28 Dec 2012
 by Mike Walters
 
 This example code is in the public domain.
 
 http://www.arduino.cc/en/Tutorial/Debounce
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise: 

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}


2  Using Arduino / Programming Questions / Re: From this to That on: November 14, 2013, 08:32:05 am
Quote
Well, this compiles fine for me:
It was how to implement your code I had trouble with. Thanks for showing how to implement.

-stowite
Quote
What is the problem with using interrupts?
It interferes with my other code. The sketch currently under discussion is a small part of a bigger sketch, and interrupts aren't required for what I want to do.

-stowite
Have you used the code you pointed to without interupts and if so what pins have you used on th emega 2560
3  Using Arduino / Programming Questions / Re: From this to That on: November 14, 2013, 06:09:36 am
-majenko

looks interesting, I tired putting the code in but keep getting errors, How should you de-bounce code go with this

Code:
/* Read Quadrature Encoder
  * Connect Encoder to Pins encoder0PinA, encoder0PinB, and +5V.
  *
  * Sketch by max wolf / www.meso.net
  * v. 0.1 - very basic functions - mw 20061220
  *
  */ 

 int encoder0PinA = 2;
 int encoder0PinB = 3;
 int encoder0Pos = 0;
 int encoder0PinALast = LOW;
 int n = HIGH;

 void setup() {
   pinMode (encoder0PinA,INPUT);
   pinMode (encoder0PinB,INPUT);
   Serial.begin (9600);
 }

 void loop() {
   n = digitalRead(encoder0PinA);
   if ((encoder0PinALast == HIGH) && (n == LOW)) {
     if (digitalRead(encoder0PinB) == LOW) {
       encoder0Pos--;
     } else {
       encoder0Pos++;
     }
     Serial.print (encoder0Pos);
     Serial.print ("/");
   }
   encoder0PinALast = n;
 }

-stowite

thanks, I have seen this code before and cant get it to work on mega 2560, not sure what pins to use, prefer not to use interupts.
4  Using Arduino / Programming Questions / From this to That on: November 14, 2013, 04:27:27 am
How do I write this de-bounce code into this encoder code.

Code:
/*
 Debounce
  created 21 November 2006  by David A. Mellis modified 30 Aug 2011 by Limor Fried modified 28 Dec 2012 by Mike Walters
  */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise: 

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

encoder code

Code:
/* Read Quadrature Encoder
 * Connect Encoder to Pins encoder0PinA, encoder0PinB, and +5V.
 *
 * Sketch by max wolf / www.meso.net
 * v. 0.1 - very basic functions - mw 20061220
 *
 */
int encoder0PinA = 2;
int encoder0PinB = 3;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = HIGH;

void setup() {
  pinMode (encoder0PinA,INPUT);
  pinMode (encoder0PinB,INPUT);
  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == HIGH) && (n == LOW)) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Pos--;
    }
    else {
      encoder0Pos++;
    }
    Serial.print (encoder0Pos);
    Serial.print ("/");
  }
  encoder0PinALast = n;
}

5  Using Arduino / Project Guidance / High or Low on: November 13, 2013, 06:35:04 am
So I have got myself really confused. If I set a pin as High does that mean arduino supplies 5 volts to that pin.

If I set it Low does that mean there is 0 volts on the pin.

I have read the reference section on these, but I'm getting confused by input/output and what and when volts are supplied or If I supply the volts to the pins?

6  Using Arduino / Programming Questions / Re: A strange Case on: October 30, 2013, 01:08:50 am
Thank you all

I shall revisit my code with your suggestions. I used serial.print to debug but know now that just adds more bugs.

karma awarded.
7  Using Arduino / Programming Questions / A strange Case on: October 29, 2013, 05:31:34 pm
I am trying to iron out some bugs in my code. Its a small menu but what is happening after 10 seconds the LCD displays "top line" and "bottom line". When the "BUTTON" is pressed the LCD displays  "Turn a knob to select an option".

When I turn the encoder and select "Change units" by pressing "BUTTONR" the LCD then prints "select unit", I then press "BUTTONR" again but nothing happens, it just hangs till I reset the board.

If I select "Backlight on off" it hangs without giving the options in the switch cases.

Code:
/*
 Switch case menu system using a rotary encoder with built in push button and one separte push button
 */

// Include Standard Library
#include <stdlib.h>

// Include LCD Library Code
#include <LiquidCrystal.h>

// Include Rotary Encoder Library
#include <QuadEncoder.h>

#include <Button.h>

// control
#define ROTENCA 43 //encoder pin A
#define ROTENCB 45 //encoder pin B
#define BUTTONR 2 // Intr 0 = Pin 2
#define BUTTON  1 // Intr 1 = Pin 3

LiquidCrystal lcd( 7, 8, 9, 10, 11, 12 );

// initialize the encoder
QuadEncoder encoder(ROTENCA,ROTENCB); // initialize the encoder
// has the encoder moved on this loop?
boolean moved = false;
Button buttonR(BUTTONR);
unsigned long timeSinceLastDisplay = 0;

void setup() {
  // setup interrupts
  attachInterrupt(BUTTON, displayMenu, RISING);

  // set the LCD's number of cols and lines
  lcd.begin(16, 2);

  Serial.begin(115200);
  lcd.print("initialising");


}

void loop() {

  displayData();
}

// Displays the current values on the LCD YET TO BE EDITED
void displayData() {
  if (displayOk()) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("top line");
    lcd.setCursor(0,1);
    lcd.print("bottom line");
  }
}


void displayMenu() {

  int selected = 0;// 0 = back light, 1 = logging on and off, 2 = exit settings, 3 = change units

  lcd.setCursor(0,0);
  lcd.clear();
  lcd.print("Turn the knob to");
  lcd.setCursor(0,1);
  lcd.print("select an option");

  // display options
  while (!buttonR.isPressed()) {
    selected += readEncoder();
    if (selected<0) selected=3;// less than
    if (selected>3) selected=0;//more than
    if (moved){
      lcd.clear();
      lcd.setCursor(0,0);
      switch(selected){
      case 0:
        lcd.print("Change units");
        break;
      case 1:
        lcd.print("Backlight On/Off");
        Serial.println("Backlight On/Off");
        break;
      case 2:
        lcd.print("Logging On/Off  ");
        Serial.println("Logging On/Off  ");
        break;
      case 3:
        lcd.print("Exit Settings   ");
        Serial.println("Exit Settings   ");
        break;
      }
    }
  }

  // when button is isPressed...
  lcd.clear();
  switch(selected){
  case 0:
    settingsChangeUnits();
    Serial.println("jump to step 2");
    break;
  case 1:
    settingsChangeBacklight();
    break;
  case 2:
    displayData();
    break;
  }
}

void settingsChangeUnits() {

  int selected = 2;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Select Unit     ");
  while (!buttonR.isPressed()) {
    selected += readEncoder();
    if (selected<0) selected=2;
    if (selected>2) selected=0;
    if (moved) {
      lcd.clear();
      lcd.setCursor(0,1);
      switch(selected) {
      case 0:
        lcd.print("Celcius         ");
        Serial.print("step 3");
        break;
      case 1:
        lcd.print("Fahrenheit      ");
        Serial.print("step 3b");
        break;
      case 2:
        lcd.print("Cancel          ");
        Serial.print("step 3c");
        break;
      }
    }
  }
  // when button isPressed...
  switch(selected) {
    lcd.clear();
  case 0:
    lcd.print("temperature c");
    Serial.print("step 4");
    break;
  case 1:
    lcd.print("temperature c");
    Serial.print("step 4a");
    break;
  }
}

void settingsChangeBacklight() {

  int selected = 2;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Backlight On/Off");
  while (!buttonR.isPressed()) {
    selected += readEncoder();
    if (selected<0) selected=2;
    if (selected>2) selected=0;
    if (moved) {
      lcd.setCursor(0,1);
      lcd.print("On  Off  Cancel");
      switch(selected) {
      case 0:
        lcd.setCursor(0,1);
        ledOn();
        break;
      case 1:
        lcd.setCursor(4,1);
        ledOff();
        break;
      case 2:
        lcd.setCursor(9,1);
        lcd.print("ledOn : ledOff");
        break;
      }

    }
  }
}

boolean displayOk() {
  unsigned long now = millis();
  if (now - timeSinceLastDisplay >= 10000) {
    timeSinceLastDisplay = now;
    return true;
  }
  else return false;
}


// returns 1 for right, -1 for left, or 0 for no movement
int readEncoder() {
  moved = true;
  switch(encoder.hb()) {
  case '>':
    return 1;
  case '<':
    return -1;
  }
  moved = false;
  return 0;
}

// turns on the backlight
void ledOn() {
  lcd.print("led on");
  Serial.print("led on");
}

// turns off the backlight
void ledOff() {
  lcd.print("led off");
  Serial.print("led off");
}


and a final thought

Code:
void displayMenu() {

  int selected = 0;// 0 = back light, 1 = logging on and off, 2 = exit settings, 3 = change units

if I change int selected = 1 then the switch case  goes to "back light" not "change units" even though case 1 is "change units" is that correct. I thought selected number would call the same case. I have commented the various selected positions
8  Using Arduino / Programming Questions / what is happening in this code snippet on: October 22, 2013, 09:53:37 am
Can someone explain what is happening in this code snippet, And does this make sense?

Code:
void displayMenu() {
  int selected = 3;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Turn the knob to");
  lcd.setCursor(0,1);
  lcd.print("select an option");
  // display options
  while (!buttonR.isPressed()) {
    selected += readEncoder();
    if (selected<0) selected=3;
    if (selected>3) selected=0;
    if (moved) {
      lcd.clear();
      lcd.setCursor(0,0);
      switch(selected) {
      case 0:
        lcd.print("Change Units    ");
        break;
      case 1:
        lcd.print("Backlight On/Off");
        break;
      case 2:
        lcd.print("Logging On/Off  ");
        break;
      case 3:
        lcd.print("Exit Settings   ");
        break;
      }
    }
  }
  // when button is pressed...
  lcd.clear();
  switch(selected) {
  case 0:
    settingsChangeUnits();
    break;
  case 1:
    settingsChangeBacklight();
    break;
  case 2:
    settingsChangeLogging();
  }
}
9  Using Arduino / Programming Questions / Re: code fail on: August 29, 2013, 02:30:12 pm
I have attached the original persons sketch at the bottom with their comments, I have probably taken some code that is not required for my purposes.
and below is the original code snippet taken from the original code.

Quote
Edit:
I don't understand why dealWithButton() contains a while loop that continues while buttonPressed() returns false, since dealWithButton() is only called when buttonPressed() returned true.

This might shed light on the issue.
Code:
boolean ButtonPressed() {
  // I'm using the internal pull-up resistors on the Arduino, so
  // logic is inverted. LOW means the button is pressed.
  // This routine, however, returns true if button has been pressed and false
  // otherwise. It's sensitive to the transition between unpressed and pressed.
  boolean WasIt;  // as in, "Was It pressed?"
  NewButtonState = !digitalRead(Button);
  if ((!OldButtonState) && (NewButtonState)) {
    // Button was unpressed and is now pressed
    WasIt = true;
  }
  else {
    WasIt = false;
  }
  OldButtonState = NewButtonState;
  return(WasIt);
}

void DealWithButton() {
  // Function to deal with button presses.

  // Otherwise, it starts the whole "set time/date/alarm" routine.

  byte Next=0;    // flag to keep track of next action.

  // User must be trying to set the clock or the alarm.
  for (byte j=0;j<MESSAGE_LENGTH;j++) {
    TopLine[j] = SetMessage[j];
    // BottomLine[j] = MESSAGE_LENGTH[j];
  }
  Rotor=0;
  TopLine[0] = '*';
  writeLCD(0,TopLine);
  writeLCD(1,BottomLine);

  // Now wait for selection.
  unsigned long StartTimeOut = millis();
  while (!ButtonPressed()) {
    delay(UIDelay);     // user interface delay
    Rotor = Rotor % 2;

    // move selection display according to current rotor position.
    if (Rotor == 1) {
      TopLine[0] = ' ';
      BottomLine[0] = '*';
      Next = 1;
    }
    else {
      TopLine[0] = '*';
      BottomLine[0] = ' ';
      Next = 0;
    }
    writeLCD(0,TopLine);
    writeLCD(1,BottomLine);

    // Check for time-out
    if ((millis()-StartTimeOut) > (unsigned long)3000) {
      // No buttonpress for 30 seconds, go back to keeping time.
      Next = 2;
      // Since it skips SetClock() or SetAlarm() here, we need
      // to reset the bottom line display.
      oldDay = 255;
      break;
    }
  }
  if (Next == 0) {
    // Set clock
    SetClock();
  }

}

I am trying to edit the code so I can use a new menu system, but I am using the original to a degree to get my code to work the way I want it.


see attachment..
Edit: anymore help.
10  Using Arduino / Programming Questions / Re: code fail on: August 28, 2013, 03:33:33 pm
Code:
 if (buttonPressed()){
    dealWithButton();
  }
The hint was to add a Serial.print() statement to the block, to show when the switch is actually pressed. Either that matches your expectations or it doesn't. Different troubleshooting paths, either way.

I have put the Serial.print into various parts of the sketch and this has helped to show how the sketch flows. I'll use this in future sketches

Quote
why does this ignore the functions.
Quote
What does that function do with the data passed to it? Nothing that I can see.

I have removed this at the moment, as I don't understand the difference between things like Byte hour and hour.
Removing the function has not made any difference. I might revisit this if its required.  

Code:
 pinMode(encoderPushButton, INPUT);// initialize the button pin as a input:
Quote
Is there an external pullup or pulldown resistor wired with the switch? I don't understand the inverted logic you are using in buttonPressed(). Some comments might be a good idea.
This was a good observation. Indeed the encoderPushButton does have an external resistor for De-bouncing. The "inverted" logic you see ties in with comments from the original author of the boolean buttonPressed(). in his code he wrote.

Quote
"I'm using the internal pull-up resistors on the arduino, so logic is inverted. Low means the button is pressed.
This routine, however, returns true if button has been pressed and false otherwise. It's sensitive to the transition between unpressed and pressed."

is that something else I need to look at.

Code:
 if (digitalRead(B)){
Quote
digitalRead() does not return a boolean. It makes code difficult to follow when you write code like this. My recommendation is that you not do so.

Does (digitalRead(B)) use any off the boolean buttonPressed code. I cant see any link or reference to in in my code?

Taking on-board your comments, what I have now is getting better. Using the Serial.print it shows me when the encoderPushButton has been pressed. It also shows (prints) the variables for hour, minute, seconds, etc on each press of the encoderPushButton. If I rotate the encoder in any one of the variables I don't see the variable increment or decrement. but after the last variable is called the LCD shows the changes made. I put displayLcdTime(); in each of the Time variables thinking it would call the new settings and display them but it does not.

I have attached the new code below. I'm using arduino version 1.0.5
11  Using Arduino / Programming Questions / Re: code fail on: August 27, 2013, 05:17:41 pm
Code:
 if (buttonPressed()){
    dealWithButton();
  }
Well, was it?
I see the point you make but I cant see it in my code, based on the whole sketch, is there a better way to do this,

Quote
Code:
 if ((encoder0PinALast == HIGH) && (n == LOW)) {
    if (digitalRead(encoder0PinB) == LOW) {
      Rotor--;
    }
    else {
      Rotor++;
    }

  }
  encoder0PinALast = n;
What should happen if encoder0PinALast is LOW and n is HIGH? Just ignore that case? I don't think so.
I have removed this and redone using different code

Quote
Code:
 delay(1000);// delay for clock seconds
More crap. Look at the blink without delay example, without delay().
I have replaced this with the blink without delay sketch.

Quote
Code:
void updateTimeDisplayPlus(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year){
  displayLcdTime();
}
Why does this function take 7 arguments that it ignores?
why does this ignore the functions.

The sketch below contains some of the modifications from above comments.

Code:
// Example 54.1 - PCF8563 RTC write/read demonstration

#include "Wire.h"
#define PCF8563address 0x51
#include <LiquidCrystal.h>
LiquidCrystal lcd( 7, 8, 9, 10, 11, 12 );

// encoder connections
byte encoderPushButton = 45;    // the pin that the pushbutton is attached to
byte A = 2;
byte B = 3;

volatile byte Rotor = 0;

// Variables will change: Push Buttons
boolean oldButtonState = false;
boolean newButtonState = false;

long previousMillis = 0;        // will store last time Lcd was updated
long interval = 1000;           // interval at which to blink (milliseconds)

byte uiDelay = 100;//delay for debounce
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

String days[] = {
  "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };


//Binary coded decimal calculation
byte bcdToDec(byte value)
{
  return ((value / 16) * 10 + value % 16);
}

byte decToBcd(byte value){
  return (value / 10 * 16 + value % 10);
}

void setup()
{
  Wire.begin();
  lcd.begin(16, 2);
  //encoder pins
  pinMode (A, INPUT);
  pinMode (B, INPUT);
  pinMode(encoderPushButton, INPUT);// initialize the button pin as a input:

  //attach interrupt to pin A of rotary encoder
  attachInterrupt(0, updateRotation, FALLING);

  // change the following to set your initial time
  second = 0;
  minute = 42;
  hour = 20;
  dayOfWeek = 6;
  dayOfMonth = 24;
  month = 8;
  year = 13;
  // comment out the next line and upload again to set and keep the time from resetting every reset
  //setPCF8563();
}

void loop()
{

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;  

    displayLcdTime();

  }
  if (buttonPressed()){
    dealWithButton();
  }
}

void updateRotation (){
  //this is a subroutine that runs everytime pin 2 goes LOW.

  if (digitalRead(B)){
    Rotor++;
  }
  else {
    Rotor--;
  }

}

boolean buttonPressed(){// without this we cant get to deal with button

  boolean wasItPressed;

  newButtonState = !digitalRead(encoderPushButton);

  if ((!oldButtonState) && (newButtonState)) {
    //button was unpressed and is now pressed
    wasItPressed = true;
  }
  else {

    wasItPressed = false;
  }
  oldButtonState = newButtonState;
  return(wasItPressed);
}

void dealWithButton(){

  byte next = 0;

  Rotor = 0;
  lcd.clear();
  lcd.setCursor(0,0);//COL,ROW
  lcd.print("* set clock");
  lcd.setCursor(2,1);//COL,ROW
  lcd.print("blank");

  //now wait for selection.
  unsigned long startTimeOut = millis();
  while (!buttonPressed()){
    Rotor = Rotor % 2;

    //move selection display according to current rotor position
    if (Rotor == 1){
      lcd.setCursor(0,1);
      lcd.print(" set clock");
      lcd.print("* blank");
      next = 1;
    }
    else {
      lcd.setCursor(0,0);
      lcd.print("* set clock");
      lcd.setCursor(0,1);
      lcd.print(" blank");
    }
    //check for time-out
    if ((millis()-startTimeOut) > (unsigned long)10000) {
      // no button press for 10 seconds, go back to keeping time.
      next = 2;
      break;
    }
  }
  if (next == 0) {
    //set clock
    setClock();
  }
  else if (next ==1){
    // currently blank at moment)
    lcd.print("Blank");
  }

}

void updateTimeDisplayPlus(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year){
  displayLcdTime();
}

void displayLcdTime(){

  readPCF8563();//get time from pcf8563 then format it below

  lcd.clear();
  lcd.setCursor(2,1);
  lcd.print(days[dayOfWeek]);
  lcd.print(" ");  
  lcd.print(dayOfMonth, DEC);
  lcd.print("/");
  lcd.print(month, DEC);
  lcd.print("/");
  lcd.print(year, DEC);

  lcd.setCursor(4,0);
  lcd.print(hour, DEC);
  lcd.print(":");
  if (minute < 10)
  {
    lcd.print("0");
  }
  lcd.print(minute, DEC);
  lcd.print(":");  
  if (second < 10)
  {
    lcd.print("0");
  }  
  lcd.print(second, DEC);  
}

void setClock() {
  // This is the user interface routine for setting the clock.
  updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);


  // Here's where we set the hour
  Rotor = hour + 48;      // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    hour = Rotor % 24;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);

  }

  // Here we set the minute
  Rotor = minute + 120;   // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    minute = Rotor % 60;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);

  }

  // Here's where we set the seconds
  Rotor = second + 120;      // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    second = Rotor % 60;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);

  }

  // Here we set the year
  Rotor = year;
  while (!buttonPressed()) {
    delay (uiDelay);
    year = Rotor;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);

  }


  // Set the day of the week
  Rotor = dayOfWeek + 16;   // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    dayOfWeek = constrain((Rotor % 8), 1, 7);

  }

  // Set the Month
  Rotor = month + 26; // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    month = constrain((Rotor % 13),1,12);

  }

  // Set the Date
  Rotor = dayOfMonth;
  while (!buttonPressed()) {
    delay (uiDelay);
    switch (month) {
      // Thirty days hath November,
      // All the rest I can't remember.
    case 1://jan
    case 3://mar
    case 5://may
    case 7://jul
    case 8://aug
    case 10://oct
    case 12://Dec
      dayOfMonth = Rotor % 32;
      break;
    case 4://apr
    case 6://jun
    case 9://sep
    case 11://nov
      dayOfMonth = Rotor % 31;
      break;
    case 2://feb
      dayOfMonth = Rotor % 30;
      break;
    }
    if (dayOfMonth==0) {
      dayOfMonth++;
    }

  }

  // Turn cursor off
  lcd.noCursor();

  // Save the new stuff, with second set to zero
  setPCF8563();//year, month, dayOfWeek, dayOfMonth,  hour, minute, second);//0x00);

}

void setPCF8563()
// this sends the time and date to the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.write(decToBcd(second));  
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));    
  Wire.write(decToBcd(dayOfMonth));
  Wire.write(decToBcd(dayOfWeek));  
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.endTransmission();
}

void readPCF8563()
// this gets the time and date from the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.endTransmission();
  Wire.requestFrom(PCF8563address, 7);
  second     = bcdToDec(Wire.read() & B01111111); // remove VL error bit
  minute     = bcdToDec(Wire.read() & B01111111); // remove unwanted bits from MSB
  hour       = bcdToDec(Wire.read() & B00111111);
  dayOfMonth = bcdToDec(Wire.read() & B00111111);
  dayOfWeek  = bcdToDec(Wire.read() & B00000111);  
  month      = bcdToDec(Wire.read() & B00011111);  // remove century bit, 1999 is over
  year       = bcdToDec(Wire.read());
}

12  Using Arduino / Programming Questions / Re: code fail on: August 26, 2013, 04:14:19 pm
Somethings are heading in the right direction.

Quote
A non-void function MUST MUST MUST return a value!
I have changed this.

what happens now is after the encoderPushButton is pressed lcd displays

* set clock
 blankk

if i press the encoderPushButton again the lcd displays time and date.(as below)

  20:42:00
sat 24/8/13

if i turn the encoder nothing happens, if i press the encoderPushButton nothing appears to happen until the 5th press, at that point the seconds stop, only when i press 3 more times do the seconds restart but nothing has changed and the time is not effected.

here is the updated code.

Code:
// Example 54.1 - PCF8563 RTC write/read demonstration

#include "Wire.h"
#define PCF8563address 0x51
#include <LiquidCrystal.h>
LiquidCrystal lcd( 7, 8, 9, 10, 11, 12 );

const int ledPin = 13;       // the pin that the LED is attached to

// encoder settings
const int  encoderPushButton = 45;    // the pin that the pushbutton is attached to
const int encoder0PinA = 2;
const int encoder0PinB = 3;
int Rotor = 0;
int encoder0PinALast = LOW;
int n = HIGH;

// Variables will change: Push Buttons
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
boolean oldButtonState = false;
boolean newButtonState = false;
byte uiDelay = 100;//delay for debounce
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

String days[] = {
  "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

//Binary coded decimal calculation
byte bcdToDec(byte value)
{
  return ((value / 16) * 10 + value % 16);
}

byte decToBcd(byte value){
  return (value / 10 * 16 + value % 10);
}


void setup()
{
  Wire.begin();

  //encoder pins
  pinMode (encoder0PinA,INPUT);
  pinMode (encoder0PinB,INPUT);
  pinMode(encoderPushButton, INPUT);// initialize the button pin as a input:
  pinMode(ledPin, OUTPUT);// initialize the LED as an output:

  lcd.begin(16, 2);

  // change the following to set your initial time
  second = 0;
  minute = 42;
  hour = 20;
  dayOfWeek = 6;
  dayOfMonth = 24;
  month = 8;
  year = 13;
  // comment out the next line and upload again to set and keep the time from resetting every reset
  //setPCF8563();
}

void loop()
{
  displayLcdTime();

  if (buttonPressed()){
    dealWithButton();
  }

  // encoder
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == HIGH) && (n == LOW)) {
    if (digitalRead(encoder0PinB) == LOW) {
      Rotor--;
    }
    else {
      Rotor++;
    }

  }
  encoder0PinALast = n;


  delay(1000);// delay for clock seconds
}

boolean buttonPressed(){// without this we cant get to deal with button

  boolean wasItPressed;

  newButtonState = !digitalRead(encoderPushButton);

  if ((!oldButtonState) && (newButtonState)) {
    //button was unpressed and is now pressed
    wasItPressed = true;
  }
  else {

    wasItPressed = false;
  }
  oldButtonState = newButtonState;
  return(wasItPressed);
}

void dealWithButton(){

  byte next = 0;

  Rotor = 0;
  lcd.clear();
  lcd.setCursor(0,0);//COL,ROW
  lcd.print("* set clock");
  lcd.setCursor(2,1);//COL,ROW
  lcd.print("blank");

  //now wait for selection.
  unsigned long startTimeOut = millis();
  while (!buttonPressed()){
    Rotor = Rotor % 2;

    //move selection display according to current rotor position
    if (Rotor == 1){
      lcd.setCursor(0,1);
      lcd.print(" set clock");
      lcd.print("* blank");
      next = 1;
    }
    else {
      lcd.setCursor(0,0);
      lcd.print("* set clock");
      lcd.setCursor(0,1);
      lcd.print(" blank");
    }
    //check for time-out
    if ((millis()-startTimeOut) > (unsigned long)3000) {
      // no button press for 30 seconds, go back to keeping time.
      next = 2;
      break;
    }
  }
  if (next == 0) {
    //set clock
    setClock();
  }
  else if (next ==1){
    // currently blank at moment)
    lcd.print("Blank");
  }

}

void updateTimeDisplayPlus(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year){
  displayLcdTime();
}


void displayLcdTime(){

  readPCF8563();//get time from pcf8563 then format it below

  lcd.clear();
  lcd.setCursor(2,1);
  lcd.print(days[dayOfWeek]);
  lcd.print(" ");  
  lcd.print(dayOfMonth, DEC);
  lcd.print("/");
  lcd.print(month, DEC);
  lcd.print("/");
  lcd.print(year, DEC);


  lcd.setCursor(4,0);
  lcd.print(hour, DEC);
  lcd.print(":");
  if (minute < 10)
  {
    lcd.print("0");
  }
  lcd.print(minute, DEC);
  lcd.print(":");  
  if (second < 10)
  {
    lcd.print("0");
  }  
  lcd.print(second, DEC);  
}

void setClock() {
  // This is the user interface routine for setting the clock.
  updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
  //UpdateTimeDisplay(Hour, Minute, Year);
  //SetBottomLine(Weekday, Month, Day);
  //  writeLCD(0,TopLine);
  //  writeLCD(1,BottomLine);

  // Here's where we set the hour
  Rotor = hour + 48;      // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    hour = Rotor % 24;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
    //lcd.cursor();
  }

  // Here we set the minute
  Rotor = minute + 120;   // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    minute = Rotor % 60;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
    // UpdateTimeDisplayPlus(Hour, Minute, Second, Year);
    // writeLCD(0,TopLine);
    //lcd.setCursor(3,0);
    // lcd.cursor();
  }

  // Here's where we set the seconds
  Rotor = second + 120;      // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    second = Rotor % 60;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
    
  }

  // Here we set the year
  Rotor = year;
  while (!buttonPressed()) {
    delay (uiDelay);
    year = Rotor;
    updateTimeDisplayPlus(second, minute, hour, dayOfWeek, dayOfMonth, month, year);
    // UpdateTimeDisplayPlus(Hour, Minute, Second, Year);
    // writeLCD(0,TopLine);
    // lcd.setCursor(10,0);
    // lcd.cursor();
  }


  // Set the day of the week
  Rotor = dayOfWeek + 16;   // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    dayOfWeek = constrain((Rotor % 8), 1, 7);
    // SetBottomLine(Weekday, Month, Day);
    //  writeLCD(1, BottomLine);
    // lcd.setCursor(0,1);
    // lcd.cursor();
  }

  // Set the Month
  Rotor = month + 26; // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    delay (uiDelay);
    month = constrain((Rotor % 13),1,12);
    //  SetBottomLine(Weekday, Month, Day);
    //  writeLCD(1, BottomLine);
    // lcd.setCursor(11,1);
    // lcd.cursor();
  }

  // Set the Date
  Rotor = dayOfMonth;
  while (!buttonPressed()) {
    delay (uiDelay);
    switch (month) {
      // Thirty days hath November,
      // All the rest I can't remember.
    case 1://jan
    case 3://mar
    case 5://may
    case 7://jul
    case 8://aug
    case 10://oct
    case 12://Dec
      dayOfMonth = Rotor % 32;
      break;
    case 4://apr
    case 6://jun
    case 9://sep
    case 11://nov
      dayOfMonth = Rotor % 31;
      break;
    case 2://feb
      dayOfMonth = Rotor % 30;
      break;
    }
    if (dayOfMonth==0) {
      dayOfMonth++;
    }
    //  SetBottomLine(Weekday, Month, Day);
    //   writeLCD(1, BottomLine);
    // lcd.setCursor(14,1);
    // lcd.cursor();
  }

  // Turn cursor off
  lcd.noCursor();

  // Save the new stuff, with second set to zero
  setPCF8563();//year, month, dayOfWeek, dayOfMonth,  hour, minute, second);//0x00);

  // Mark that things have changed so the next loop() does
  // what is needed, if needed.
  // oldSecond = 255;
  //  oldMinute = 255;
  //  oldHour = 255;
  //  oldDay = 255;
}

void setPCF8563()
// this sends the time and date to the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.write(decToBcd(second));  
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));    
  Wire.write(decToBcd(dayOfMonth));
  Wire.write(decToBcd(dayOfWeek));  
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.endTransmission();
}

void readPCF8563()
// this gets the time and date from the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.endTransmission();
  Wire.requestFrom(PCF8563address, 7);
  second     = bcdToDec(Wire.read() & B01111111); // remove VL error bit
  minute     = bcdToDec(Wire.read() & B01111111); // remove unwanted bits from MSB
  hour       = bcdToDec(Wire.read() & B00111111);
  dayOfMonth = bcdToDec(Wire.read() & B00111111);
  dayOfWeek  = bcdToDec(Wire.read() & B00000111);  
  month      = bcdToDec(Wire.read() & B00011111);  // remove century bit, 1999 is over
  year       = bcdToDec(Wire.read());
}

What have I done wrong.
13  Using Arduino / Programming Questions / code fail on: August 25, 2013, 02:02:37 pm
I have the code below and it works to a point. I can get it to display the time and date but unable to change any of the setting. The code is an amalgamation of two programs, an RTC sketch and Encoder sketch. I think I have most things in their but need some guidance on how to change setting of the RTC. Would really appreciate help on this.

Code:
// Example 54.1 - PCF8563 RTC write/read demonstration

#include "Wire.h"
#define PCF8563address 0x51
#include <LiquidCrystal.h>
LiquidCrystal lcd( 7, 8, 9, 10, 11, 12 );

const int ledPin = 13;       // the pin that the LED is attached to

// encoder settings
const int  EncoderPushButton = 45;    // the pin that the pushbutton is attached to
const int encoder0PinA = 2;
const int encoder0PinB = 3;
int Rotor = 0;
int encoder0PinALast = LOW;
int n = HIGH;

// Variables will change: Push Buttons
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button


byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

String days[] = {
  "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

//Binary coded decimal calculation
byte bcdToDec(byte value)
{
  return ((value / 16) * 10 + value % 16);
}

byte decToBcd(byte value){
  return (value / 10 * 16 + value % 10);
}

void setup()
{
  Wire.begin();

  //encoder pins
  pinMode (encoder0PinA,INPUT);
  pinMode (encoder0PinB,INPUT);
  pinMode(EncoderPushButton, INPUT);// initialize the button pin as a input:
  pinMode(ledPin, OUTPUT);// initialize the LED as an output:

  lcd.begin(16, 2);

  // change the following to set your initial time
  second = 0;
  minute = 42;
  hour = 20;
  dayOfWeek = 6;
  dayOfMonth = 24;
  month = 8;
  year = 13;
  // comment out the next line and upload again to set and keep the time from resetting every reset
  //setPCF8563();
}

void loop()
{
  LcdDisplayTime();

  if (buttonPressed()){
    dealWithButton();
  }

  // encoder
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == HIGH) && (n == LOW)) {
    if (digitalRead(encoder0PinB) == LOW) {
      Rotor--;
    }
    else {
      Rotor++;
    }
    lcd.print (Rotor);

  }
  encoder0PinALast = n;

  delay(1000);// delay for clock seconds
}

boolean buttonPressed(){

  boolean wasPressed;
  // read the state of the pushbutton value:
  buttonState = digitalRead(EncoderPushButton);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {    
    // turn LED on:

    //digitalWrite(ledPin, HIGH);  
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }  
}

void dealWithButton(){

  // read the EncoderPushButton input pin:
  buttonState = digitalRead(EncoderPushButton);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, SetClock();
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      digitalWrite(ledPin, HIGH);
      SetClock();

    }
    else {
      // if the current state is LOW then the button
      // wend from on to off:
      LcdDisplayTime();
      digitalWrite(ledPin, LOW);

    }
  }
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;
}


void LcdDisplayTime(){

  readPCF8563();//get time from pcf8563 then format it below
  // date
  lcd.clear();
  lcd.setCursor(2,1);
  lcd.print(days[dayOfWeek]);
  lcd.print(" ");  
  lcd.print(dayOfMonth, DEC);
  lcd.print("/");
  lcd.print(month, DEC);
  lcd.print("/");
  lcd.print(year, DEC);

  //time
  lcd.setCursor(4,0);
  lcd.print(hour, DEC);
  lcd.print(":");
  if (minute < 10)
  {
    lcd.print("0");
  }
  lcd.print(minute, DEC);
  lcd.print(":");  
  if (second < 10)
  {
    lcd.print("0");
  }  
  lcd.print(second, DEC);  
}

void setPCF8563()
// this sets the time and date to the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.write(decToBcd(second));  
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));    
  Wire.write(decToBcd(dayOfMonth));
  Wire.write(decToBcd(dayOfWeek));  
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.endTransmission();
}

void readPCF8563()
// this gets the time and date from the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.endTransmission();
  Wire.requestFrom(PCF8563address, 7);
  second     = bcdToDec(Wire.read() & B01111111); // remove VL error bit
  minute     = bcdToDec(Wire.read() & B01111111); // remove unwanted bits from MSB
  hour       = bcdToDec(Wire.read() & B00111111);
  dayOfMonth = bcdToDec(Wire.read() & B00111111);
  dayOfWeek  = bcdToDec(Wire.read() & B00000111);  
  month      = bcdToDec(Wire.read() & B00011111);  // remove century bit, 1999 is over
  year       = bcdToDec(Wire.read());
}

void SetClock() {
  // This is the user interface routine for setting the clock.

  // Here's where we set the hour
  Rotor = hour + 48;      // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    // delay(UIDelay);
    hour = Rotor % 24;
    lcd.setCursor(4,0);
    lcd.print(hour, DEC);
    lcd.print(":");
    if (minute < 10)
    {
      lcd.print("0");
    }
    lcd.print(minute, DEC);
    lcd.print(":");  
    if (second < 10)
    {
      lcd.print("0");
    }  
    lcd.print(second, DEC);
    lcd.cursor();
  }

  // Here we set the minute
  Rotor = minute + 120;   // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    minute = Rotor % 60;
    lcd.setCursor(3,0);
    lcd.cursor();
  }

  // Here's where we set the seconds
  Rotor = second + 120;      // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    second = Rotor % 60;
    lcd.setCursor(6,0);
    lcd.cursor();
  }

  // Here we set the year
  Rotor = year;
  while (!buttonPressed()) {
    year = Rotor;
    lcd.setCursor(10,0);
    lcd.cursor();
  }


  while (!buttonPressed()) {
    lcd.setCursor(13,0);
    lcd.cursor();
  }

  // Set the day of the week
  Rotor = dayOfWeek + 16;   // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    dayOfWeek = constrain((Rotor % 8), 1, 7);
    lcd.setCursor(0,1);
    lcd.cursor();
  }

  // Set the Month
  Rotor = month + 26; // The extra value on rotor allows easier turn-back.
  while (!buttonPressed()) {
    month = constrain((Rotor % 13),1,12);
    lcd.setCursor(11,1);
    lcd.cursor();
  }

  // Set the Date
  Rotor = dayOfMonth;
  while (!buttonPressed()) {

    switch (month) {
    case 1://jan
    case 3://mar
    case 5://may
    case 7://jul
    case 8://aug
    case 10://oct
    case 12://Dec
      dayOfMonth = Rotor % 32;
      break;
    case 4://apr
    case 6://jun
    case 9://sep
    case 11://nov
      dayOfMonth = Rotor % 31;
      break;
    case 2://feb
      dayOfMonth = Rotor % 30;
      break;
    }
    if (dayOfMonth==0) {
      dayOfMonth++;
    }
    lcd.setCursor(14,1);
    lcd.cursor();
  }

  // Turn cursor off
  lcd.noCursor();

  // Save the new stuff
  setPCF8563();//year, month, dayOfWeek, dayOfMonth,  hour, minute, second);//0x00);

}
14  Topics / Education and Teaching / Re: New tutorial - Arduino and the NXP PCF8563 real time clock IC on: August 24, 2013, 12:21:37 pm
I like this, karma awarded. smiley

oh, does your e-book have color photos?

15  Using Arduino / Programming Questions / Re: help needed with code on: July 14, 2013, 05:03:12 am
Quote
bump
What has changed in the intervening month or so?

absolutely nothing.

Hopefully their are some new people online able to help.

Rather than submit a new post I bumped this back up the list where it might get viewed.
Pages: [1] 2 3 ... 8