Wednesday, April 17, 2013

New code for the Rear Bike Light

I spent some time last night removing all the debug stuff so it would look cleaner and be easier to follow.

Original post here: http://crumpspot.blogspot.com/2013/04/power-led-bike-tail-light-with-arduino.html
Schmatic here: https://www.circuitlab.com/circuit/b6r5h8/rear-bike-light/


/*--------------------------------------------------------
Rear Bike Light Project                                    
Author: Chris Crumpacker                               
Date: October 2012 

Copyright (c) 2012 Chris Crumpacker.  All right reserved.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
                                                           
Sketch Notes: This version contains 6 modes of blinking with 
multiple speeds for some modes. This works off of a single 
button, with short presses the program steps thru the 
modes/speeds. When long pressed it goes into a "sleep" 
mode where the high powered LEDs are turned off. 
It also has the ablity to store the current mode so when 
leaving sleep mode or being brought back up from a power 
down it will return to the previous mode it was in. 
There is also an interal tempurature sensor that will 
put it into a hidden (at least from the mode scrolling) 
"limp home mode" during a certain temp range or evenshut the 
LEDs down if it gets any higher.
--------------------------------------------------------*/

//-------------------------
// Includes
//-------------------------
#include 
#include 

//-------------------------
// Defines
//-------------------------
#define BUTTON_PIN       11                                                  // Button
#define ledPinl          9                                                   // Left LED
#define ledPinr          10                                                  // Right LED
#define powerPin         13                                                  // Case LED to show that the circuit has power
#define tempSensorPin    A5                                                  // Analog pin the case's Temp36 sensor is on

#define LONGPRESS_LEN    10                                                  // Min numberr of loops for a long press
#define DELAY            10                                                  // Delay per loop in ms
#define CONFIG_VERSION   "rbl1"                                              // ID of the settings block
#define memoryBase       32                                                  // Tell it where to store your config data in EEPROM                                                          //Constructor for the Simple Timer

enum { EV_NONE=0, EV_SHORTPRESS, EV_LONGPRESS };

//-------------------------
// Variables
//-------------------------
boolean ok = true;                                                           // bool for the EEPROM's config setup
int configAdress = 0;

boolean currentButton = LOW;
boolean button_was_pressed = false;
int previousButton;
int button_pressed_counter = 0;
int longPress = LONGPRESS_LEN;
int buttonCount = 0;
long previousMillis = 0;

boolean fromCheckTemp = false;
long previousTempTime = 0;
float tempLimp = 100;                                                         // In degrees (f)
float tempShutdown = 120;                                                     // In degrees (f)
int checkTempInterval = 30000;                                                // In Milliseconds

float freq;
float freqInitial = .002;
float freqChange = .002;
float freqLimit = .006;

int ledStep = 255;                                                            // How much to change the dimming (PWM) between each step for steps 6 to 9 and 10 to 13

int ledState = HIGH;

// The struct for the config saved to the EEPROM
struct StoreStruct {
    char* cVersion;                                                          // This is to detect if the settings stored in the EEPROM are for this config and sketch
    int bc;
} storage = { 
    CONFIG_VERSION,                                                          // Defaults
    0
};

//-------------------------
// Setup
//-------------------------
void setup() {
  Serial.begin(9600);                                                        // Sets up the serial port and speed
  pinMode(BUTTON_PIN, INPUT);                                                // Setting the button pin to an input
  digitalWrite(BUTTON_PIN, HIGH);                                            // Setting the button with a pull-up resistor, the button when grounded or "low" will be thought of as pressed
  pinMode(powerPin, OUTPUT);                                                 // Setting the pin for the LED on the board to show that power is on or will blink if in a sleep mode
  pinMode(ledPinl, OUTPUT);                                                  // External LED control pin 1
  pinMode(ledPinr, OUTPUT);                                                  // External LED control pin 2
  EEPROM.setMemPool(memoryBase, EEPROMSizeATmega328);                        // Set memorypool base to 32, assume Atmega328
  configAdress = EEPROM.getAddress(sizeof(StoreStruct));                     // Size of config object 
  ok = loadConfig();                                                         // Loads the config, and if it loads sets the bool "ok" to true
  buttonCount = storage.bc;                                                  // Sets the variable for the buttonCount to what is brought back from the storage
  checkTemp();                                                               // Checks the intial temp at start up
  freq = setFreq();                                                          // Sets the initial Frequency for the pulsing modes
  ledStep = setLEDStep();                                                    // Sets the initial LED PWM step value for the dimming modes
  digitalWrite(powerPin, ledState);                                          // Turns on the on board LED  
}

//-------------------------
// Functions
//-------------------------

   
// Loads the Config from EEPROM
bool loadConfig() {                                             
  EEPROM.readBlock(configAdress, storage);
  return (storage.cVersion == CONFIG_VERSION);
}

// Saves Config changes to the EEPROM
void saveConfig() {                                              
   EEPROM.writeBlock(configAdress, storage);
}

//--Button Handling--
// This function determines if the button press is short or long and is made to report back to a switch case
void handle_button(int longPress, int modeType)
{
  int button_now_pressed = !digitalRead(BUTTON_PIN);                         // pin low -> pressed
  
  if (!button_now_pressed && button_was_pressed) {
//Short press
    if (button_pressed_counter < longPress) { 
        if (modeType == 1){
          /*Short press from one of the pulsing modes. This increments the button count, 
          updates the Frequency and possibly the LEDStep and also stores the new buttonCount away in the EEPROM*/
          previousButton = buttonCount;
          ++buttonCount;
          storage.bc = buttonCount;
          saveConfig();
          setFreq();
          setLEDStep();
        } else if (modeType == 2){
          /*Short press from one of the dimming PWM modes. This increments the button count, 
          updates the Frequency and the LEDStep and also stores the new buttonCount away in the EEPROM*/
          previousButton = buttonCount;
          ++buttonCount; 
          storage.bc = buttonCount;
          saveConfig(); 
          setFreq();
          setLEDStep(); 
        } else if (modeType == 3) { 
          /*Short press for the sleep modes 14 and 15. This starts us back to the first mode (0) and sets 
          the frequency and the LED step as well as store the button count to the EEPROM*/ 
          buttonCount = 0;
          storage.bc = buttonCount;                                        //Stores the buttonCount to EEPROM
          saveConfig();
          setFreq(); 
          setLEDStep();
          fromCheckTemp = false;
        }
//Long Press
    } else { 
      if (modeType == 1 || modeType == 2){
        /*Long press for any of the "awake" modes. It puts the external LEDs to sleep in mode 14 or sleep mode. 
        Also it sets the previous button so when exiting the sleep mode it knows what to go back to*/
        previousButton = buttonCount;                              
        buttonCount = 14;
      } else if (modeType == 3) {   
        /*Long press from one of the sleep modes. This sets the button count back to the previous button, 
        updates the Frequency and the LEDStep and also stores the new buttonCount away in the EEPROM*/ 
        buttonCount = previousButton;
        storage.bc = buttonCount; 
        saveConfig();
        setFreq(); 
        setLEDStep();
        fromCheckTemp = false;
      }
    }
  } 

  if (button_now_pressed){
    ++button_pressed_counter;
  } else {
    button_pressed_counter = 0;
  }
    
  button_was_pressed = button_now_pressed;
}

//Checks the tempurature inside the circuit enclosure, 
void checkTemp() {
  unsigned long currentTempTime = millis();                                  // Set the current time
  if(currentTempTime - previousTempTime > 20000){
    previousTempTime = currentTempTime;
    float Vcc = readVcc();                                                   // Calculating the Supply Voltage
    Vcc = Vcc / 1000;                                                        // Converting from mV to Volts
    int reading = analogRead(tempSensorPin);                                 // Reading the voltage from the sensor pin
      
//  Converting that reading to voltage
    float voltage = reading * Vcc;
    voltage /= 1024.0; 
    
//  Print out the temperature in Celcius
    float temperatureC = (voltage - 0.5) * 100 ;                    //converting from 10 mv per degree wit 500 mV offset to degrees ((volatge - 500mV) times 100)
    
//  Now convert to Fahrenheight
    float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
     
    if (temperatureF > tempLimp && temperatureF < tempShutdown) {
      //To Hot but not shutting down send to limp home mode
      buttonCount = 15;
      fromCheckTemp = true;
    } else if (temperatureF >= tempShutdown && buttonCount != 14) {
      //Shutting down
      buttonCount = 14;
      fromCheckTemp = true;
    } else if (fromCheckTemp) {
      fromCheckTemp = false;
      buttonCount = previousButton;
    } else {
      fromCheckTemp = false;
    }
  } else {
    //Holder for stuff to do while waiting on the time to check temp again
  }
}

//When starting up with a stored button count we need to find and set the appropriate Frequency "freq" for the button count
float setFreq() { 
  if (buttonCount == 0 || buttonCount == 3) {
    freq = freqInitial;
  } 
  else if (buttonCount == 1 || buttonCount == 4) {
    freq = freqInitial + freqChange;
  } 
  else if (buttonCount == 2 || buttonCount == 5) {
    freq = freqInitial + freqChange + freqChange;
  }
  else {
    freq = freqInitial;
  }
  return freq;
}

//When starting up with a stored button count we need to find and set the appropriate LED brightness "ledStep" for the button count
int setLEDStep() { 
  if (buttonCount == 6 || buttonCount == 10){
    ledStep = 255;
  } 
  else if (buttonCount == 7 || buttonCount == 11) {
    ledStep = 191;
  } 
  else if (buttonCount == 8 || buttonCount == 12) {
    ledStep = 127;
  } 
  else if (buttonCount == 9 || buttonCount == 13) {
    ledStep = 64;
  }
  else {
    ledStep = 255;
  }
  return ledStep;
}

//***************************//
//******Blinking Modes*******//
//***************************//

//"bothFlipFlopPulse" The LEDs pulse back and forth (3 speeds)
void bothFlipFlopPulse() {
  float ledIn;
  float ledOutL;
  float ledOutR;
  longPress = 10;
  checkTemp();
  setFreq();  
  for (ledIn = 4.712; ledIn < 10.995; ledIn = ledIn + freq)      // This sets the start of the LED (ledOutL) pulse on the sin wave to the first zero crossing 4.712 and ends it on the next 10.995.
    {
      ledOutL = sin(ledIn) * 127.5 + 127.5;                      // Making the sin wave all positive numbers and setting it to a scale of 0-255 for the PWM range
      ledOutR = 255 - (sin(ledIn) * 127.5 + 127.5);              // This inverts ledOutR so it pulses to the high as ledOutR pulses to the low
      analogWrite(ledPinl, ledOutL);
      analogWrite(ledPinr, ledOutR);
    }
    
    handle_button(longPress,1);                    // Sets the Button function to run and read the button state, then returns the event, EV_SHORT, EV_LONG, or EV_NONE    
}

//"bothPulse" Like "bothFlipFlopPulse" but with both LEDs on the same sin wave (3 speed)
void bothPulse() {
  float ledIn;
  float ledOutL;
  float ledOutR;
  longPress = 10; 
  for (ledIn = 4.712; ledIn < 10.995; ledIn = ledIn + freq)      //This sets the start of the LED (ledOutL) pulse on the sin wave to the first zero crossing 4.712 and ends it on the next 10.995.
    {
      int out = sin(ledIn) * 127.5 + 127.5;                      //Both LEDs will follow the sin wave but we also have to make it all positive numbers and set to a scale of 0-255 for the PWM range
      analogWrite(ledPinl, out);
      analogWrite(ledPinr, out);
    }
    
  handle_button(longPress,1);
}

//"bothStepped" - Both LEDs on, stepping down the brightness with each button press (4 settings from full bright to rather dim)
void bothStepped() {
  longPress = 75;
  checkTemp();
  setLEDStep();
  analogWrite(ledPinl, ledStep);                                //Turns them both on together 
  analogWrite(ledPinr, ledStep);
  
  handle_button(longPress,2);
  delay(DELAY);
}

//"singleStepped" - Just one LED on, stepping down the brightness with each button press (4 settings from full bright to rather dim)
void singleStepped(){
  longPress = 75;
  checkTemp();
  setLEDStep();
  analogWrite(ledPinl, ledStep);
  digitalWrite(ledPinr, LOW);
    
  handle_button(longPress,2);
  delay(DELAY);
}

//"sleep" external LEDs off but blink the power led on the circuit board.
void sleep() {
  longPress = 75;                     
  checkTemp();
  digitalWrite(ledPinl, LOW);                                    //Turns off both High Power LEDs
  digitalWrite(ledPinr, LOW); 
  
  // Blinks the powerPin light by checking the current time vs. the last time it went thru, once it is over the 1000 ms limit it changes the light's state
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > 1000){
    previousMillis = currentMillis;
    if (ledState == LOW){
      ledState = HIGH;
    }
    else {
      ledState = LOW;
    }
    digitalWrite(powerPin, ledState);
  }
      
  handle_button(longPress,3); 
  delay(DELAY);    
}

//"limpHome" The limp home mode, Like mode 1 the LEDs pulse back and forth, But slowly and only to half brightness.
void limpHome() {
  float ledIn;
  float ledOutL;
  float ledOutR;
  checkTemp();
  longPress = 75;
  for (ledIn = 4.712; ledIn < 10.995; ledIn = ledIn + .002)      // This sets the start of the LED (ledOutL) pulse on the sin wave to the first zero crossing 4.712 and ends it on the next 10.995.
    {
      ledOutL = sin(ledIn) * 100 + 127.5;                        // Making the sin wave all positive numbers and setting it to a scale of 0-255 for the PWM range
      ledOutR = 255 - (sin(ledIn) * 127.5 + 127.5);              // This inverts ledOutR so it pulses to the high as ledOutR pulses to the low
      analogWrite(ledPinl, ledOutL);
      analogWrite(ledPinr, ledOutR);
    }
    
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > 1000){
    previousMillis = currentMillis;
    
    if (ledState == LOW){
      ledState = HIGH;
    }
    else {
      ledState = LOW;
    }
    digitalWrite(powerPin, ledState);
  }
    
  handle_button(longPress,3);
  delay(DELAY); 
}

//-------------------------
// THE LOOP
//-------------------------
void loop(){  
  //Set what mode the LEDs are in based on how many times the button is pressed.
  while (buttonCount < 3)
  {
    bothFlipFlopPulse();
  }
  while (buttonCount >= 3 && buttonCount < 6)
  {
    bothPulse();
  }
  while (buttonCount >= 6 && buttonCount < 10)
  {
    bothStepped();
  }
  while (buttonCount >= 10 && buttonCount < 14)
  {
    singleStepped();
  }
  while (buttonCount == 14)
  {
    sleep(); 
  }
  while (buttonCount == 15)
  {
    limpHome(); 
  }
  delay(DELAY);
}

25 comments:

  1. I definitely love every bit of this article thus, saved this to my favorite so I can read it again every time I have free time to do so. Thanks a lot. Anyhow, click this site if you want to have a good time 바카라사이트

    ReplyDelete
  2. Acknowledges for paper such a beneficial composition, I stumbled beside your blog besides decipher a limited announce. I want your technique of inscription.. 먹튀검증

    ReplyDelete
  3. Goodness! Such an astounding and supportive post this is. I outrageously cherish it. It's so great thus amazing. I am simply flabbergasted. I trust that you keep on doing your work like this later on moreover. 메이저놀이터

    ReplyDelete
  4. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing 먹튀검증

    ReplyDelete
  5. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it. 파워볼전용사이트

    ReplyDelete
  6. 그것은 훌륭한 사고 방식입니다. 그럼에도 불구하고 그 수학에 대해 설교하는 것이 무엇이든간에 모든 문장을 만드는 데 도움이되는 것은 아닙니다. 사실상 어떤 방법 으로든 본인의 글을 델리 시우스로 홍보하기 위해 노력한 것 외에도 많은 노력을 기울 였음에도 불구하고 귀하의 정보 사이트를 사용하는 것이 딜레마 인 것 같습니다. 아이디어를 다시 확인해 주시면 감사하겠습니다. 다시 한 번 감사합니다 먹튀안전사이트

    ReplyDelete
  7. Nice knowledge gaining article. This post is really the best on this valuable topic. 먹튀폴리스

    ReplyDelete
  8. I'm constantly searching on the internet for posts that will help me. Too much is clearly to learn about this. I believe you created good quality items in Functions also. Keep working, congrats! 먹튀검증

    ReplyDelete
  9. It’s very informative and you are obviously very knowledgeable in this area. You have opened my eyes to varying views on this topic with interesting and solid content. casino24

    ReplyDelete
  10. 블로그 주문 시스템에 댓글을 달 수 있습니다. 멋진 채팅을해야합니다. 귀하의 블로그 감사는 방문자를 증가시킬 것입니다. 이 사이트를 발견하게되어 매우 기뻤습니다. 읽어 주셔서 감사합니다 !! 먹튀검증

    ReplyDelete
  11. Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post.Keep up your work 먹튀검증

    ReplyDelete
  12. https://www.toto-casino.net/%EC%9D%B4%EA%B8%B0%EC%9E%90%EB%B2%B3 Very interesting, good job and thanks for sharing such a good blog. your article is so convincing that I never stop myself to say something about it. You’re doing a great job. Keep it up 이기자벳

    ReplyDelete
  13. I got a web site from where I be capable of really obtain valuable information regarding my study and knowledge.
    Great Article… Good Job… Thanks For Sharing…

    Website:강남출장안마

    ReplyDelete
  14. Hi there, I found your website via Google while looking for a related topic, your web site came up, it looks good. I’ve bookmarked it in my google bookmarks.오피사이트


    ReplyDelete
  15. I got a web site from where I be capable of really obtain valuable information regarding my study and knowledge.
    Great Article… Good Job… Thanks For Sharing…

    Website:강남출장


    ReplyDelete
  16. A betting site list to play online sports betting in Turkey here, visit immediately. 먹튀검증

    ReplyDelete
  17. I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me .. Thanks for all your help and wishing you all the success in your business 먹튀검증

    ReplyDelete
  18. This is an extraordinary element for sharing this useful message. I am dazzled by the information you have on this blog. It causes me from multiple points of view. A debt of gratitude is in order for posting this once more. 먹튀폴리스

    ReplyDelete
  19. The looks really great. Most of these smaller details are usually created employing wide range of heritage knowledge. I would like all of it substantially 토토

    ReplyDelete
  20. Hahaha, good, good. The writing is interesting.토토사이트 Look at my writing.

    ReplyDelete
  21. I’ve been absent for a while, but now I remember why 대구출장

    I used to love this website. Thanks, I will try and check back more often. How frequently you update your site?

    ReplyDelete
  22. It's been a while since I've read this heart-throbbing post.사설토토사이트 I look forward to your kind cooperation.

    ReplyDelete
  23. It's amazing that you figured all this out on your own, and I need to learn how to do it like you.메이저토토사이트

    ReplyDelete