////////////////////////////////////////////////////////////////////////////////
// Official name:     BolderbotMiniInterrupts                                 //
// Hardware platform: Bolderbot Mini                                          //
// Pin connections:   Arduino Mega 2560                                       //
// Created by:        HARB rboek2@gmail.com september 2017 GPL copyrights     //
// http://robotigs.nl/robotigs/includes/parts_header.php?idpart=197           //
// This program tests the interrupts on a MEGA 2560, but it should run on any //
// microcontroller that has at least 1 pin available for user interrupts.     //
// Blocking the connected speed encoder will cause the LEDs to toggle         //
////////////////////////////////////////////////////////////////////////////////


// SET PRECOMPILER OPTIONS *****************************************************
// Initialse conditional compiling, uncomment to include, comment to exclude ---
// Do comment for runtime versions
#define RS232                     //Uncomment to include Serial Monitor sections
//  #ifdef RS232     //Only include these lines if the variable has been defined

// Define precompiler variables -----------------(Runs faster & doesn`t use RAM)
// Define PINS -----------------------------------------------------------------
#define    LED    PB7             //Arduino boards contain an onboard LED pin 13
#define    SEL      2       //Speed Encoder Left on pin 21, binds to interrupt 2
#define    SER      3      //Speed Encoder Right on pin 20, binds to interrupt 3
#define buzPin      6   //To which DIO pin is the passiv buzzer KY-006 connected
#define SpeedEncoL 18  //Interrupted input of speed encoder WYC H206, short wire
#define SpeedEncoR 19   //Interrupted input of speed encoder WYC H206, long wire
const int ledRed = 44;         //Define to which PWM pin this color is connected
const int ledGre = 45;         //Define to which PWM pin this color is connected
const int ledBlu = 46;         //Define to which PWM pin this color is connected
//3 COLOR LED breakout, common ground,      connect these pins preferably to PWM

///Define the needed header files for the precompiler, no charge if not used ---
#include <TimerOne.h>      //Currently needed for reading wheel speed per second
//#include <IRremote.h>     //Do never use the default by the IDE but replace it
//#include <AFMotor.h>  //Motors shield, Copyright Adafruit Industries LLC, 2009

//DEFINE VARIABLES -------------------------------------------------------------
int Red = 4;                //Brightness of this color, set by PWM 0=min 255=max
int Gre = 4;                //Brightness of this color, set by PWM 0=min 255=max
int Blu = 4;                //Brightness of this color, set by PWM 0=min 255=max
int inByte = 0;                                       //For incoming serial data
int Color = 'R';                                 //The startup color to be faded
unsigned int cntr1 = 0;                   //Define left wheel counter per second
unsigned int cntr2 = 0;                  //Define right wheel counter per second
bool ledBinVal = LOW;         //You can chose HIGH-on or LOW-off for LED_BUILTIN
//END OF PRECOMPILER OPTIONS ---------------------------------------------------

void toggle_led(void) { //Toggles the default on-board LED on or off ***********
  if bit_is_clear(PORTB, LED) {                 //Test if the onboard LED is off
    PORTB |= (1 << LED);                           //If LED=off then turn LED on
    Red = 0;                //Brightness of this color, set by PWM 0=min 255=max
    Gre = 50;               //Brightness of this color, set by PWM 0=min 255=max
    Blu = 0;                //Brightness of this color, set by PWM 0=min 255=max
  } else {                                             //Else the LED must be on
    PORTB &= ~(1 << LED);                                //Then turn the LED off
    Red = 80;               //Brightness of this color, set by PWM 0=min 255=max
    Gre = 0;                //Brightness of this color, set by PWM 0=min 255=max
    Blu = 0;                //Brightness of this color, set by PWM 0=min 255=max
  } //End of if bit_is_clear(PORTB, LED)                  Or fe: state = !state;
  analogWrite(ledRed, Red);   //Set the brightness of this LED and illuminate it
  analogWrite(ledGre, Gre);   //Set the brightness of this LED and illuminate it
  analogWrite(ledBlu, Blu);   //Set the brightness of this LED and illuminate it
} //Exit toggle_led ------------------------------------------------------------

void doEncIsr() { //Increases the left wheel speed sensor by 1 *****************
  cntr1++;                                       //Increase +1 the counter value
  toggle_led();                     //Toggles the default on-board LED on or off
} //Exit docntLdoEncIsr---------------------------------------------------------

void timerIsr() { //Timer has reached its maximum *Interrupt Service Routine ***
  Timer1.detachInterrupt();                                     //Stop the timer
  toggle_led();                     //Toggles the default on-board LED on or off
  Serial.print(cntr1, DEC);
  Serial.println(" pulses per 10 s");
  cntr1 = 0;
  Timer1.attachInterrupt( timerIsr );                   //Enable the timer again
} //Exit timerIsr --------------------------------------------------------------

void setup() {
  //disable_jtag();              //Disable jtag to free port C, enabled by default
  //pinMode(SEL, INPUT);  //Redundant, set Speed Encoder Left as input (default)
  //digitalWrite(20, HIGH);                               //Enable pullup resistor
  //digitalWrite(21, HIGH);                               //Enable pullup resistor  
  Timer1.initialize(10000000);     //Timer creates an interrupt every 10 seconds
  Timer1.attachInterrupt( timerIsr );                //Starts the timer counting

  attachInterrupt(SER, doEncIsr, CHANGE);     //Increase left cntr on any change
  
  Serial.begin(9600);   //Nothing more needed for the Serial Monitor to function 
  pinMode(ledRed, OUTPUT);                //Make the LED connections output pins
  pinMode(ledGre, OUTPUT);                //Make the LED connections output pins
  pinMode(ledBlu, OUTPUT);                //Make the LED connections output pins
  pinMode(LED_BUILTIN, OUTPUT);  //Arduino boards contain an onboard LED_BUILTIN
  //pinMode(SpeedEncoL, INPUT_PULLUP);  //Interrupted input speed encoder WYC H206
  //pinMode(SpeedEncoR, INPUT_PULLUP);  //Interrupted input speed encoder WYC H206
  analogReference(DEFAULT);                //Accurate enough for Battery Monitor
  //irrecv.enableIRIn();                                  // Start the IR receiver
  //Timer1.initialize(100000);  //This timer will create an interrupt every 10 s
  //Timer1.attachInterrupt( timerIsr );                        //Start the timer
  //attachInterrupt(2, docntrL, RISING);      //Increase left cntr on any change
  //attachInterrupt(3, docntrR, FALLING);    //Increase right cntr on any change
  //toggle_ledBin();                                         //Show we are awake
  beep(50);         //Give 0-255 mSec an annoying beep with KY-012 active buzzer
}//--(end setup )---------------------------------------------------------------


void loop() { //KEEP ON RUNNING THIS LOOP FOREVER ******************************
  ledBinVal = digitalRead(SpeedEncoR);                           //Read WYC H206
  digitalWrite(LED_BUILTIN, ledBinVal);         //Set Arduino boards onboard LED
  //toggle_ledBin();                //Toggles the default on-board LED on or off
} //End of void loop()                       //KEEP ON RUNNING THIS LOOP FOREVER
//345678911234567892123456789312345678941234567895123456789612345678971234567898



void disable_jtag(void) { //Disable jtag to free port C, enabled by default ****
#if defined(JTD)                           //Not all AVR controller include jtag
  MCUCR |= ( 1 << JTD );                                //Write twice to disable
  MCUCR |= ( 1 << JTD );                                       //So stutter once
#endif                                            //End of conditional compiling
} //Exit jtag_disable ----------------------------------------------------------

void beep(byte ms) { //Create a beep with KY-006 active buzzer *****************
  while (ms > 0){                            //Timer of the duration of the beep
    digitalWrite(buzPin, HIGH);                 //Push the speaker conus outward
    delay(2);                                    //Determins the fixed frequency
    digitalWrite(buzPin, LOW);                   //Pull the speaker conus inward
    delay(2);                                    //Determins the fixed frequency
    ms--;                                     //Countdown untill we reached zero
  }            //Timer of the duration of the beep has been counted down to zero
} //Exit beep ------------------------------------------------------------------

void toggle_ledBin(void) { //Toggles the LED_BUILTIN on-board LED on or off ****
  ledBinVal = !ledBinVal;                                         //Toggle value
  digitalWrite(LED_BUILTIN, ledBinVal);         //Set Arduino boards onboard LED
} //Exit toggle_ledBin ---------------------------------------------------------



////////////////////////////////////////////////////////////////////////////////
// PIN ALLOCATIONS TABLE ARDUINO MEGA 2560                                    //
// Board  -Atmel- PIN - IDE - Function          - External Connection    FUNC //
//                                                                            //
// CONNECTIONS RAILS TOP LEFT: DIGITAL PWM<~> ******************************* //
//? SCL   -  28 - PC5 -19/A5- ADC5/SCL/PCINT13  -                         TWI //
//? SDA   -  27 - PC4 -18/A4- ADC4/SDA/PCINT12  -                         TWI //
// AREF   -  31 - REF -     - AREF              -                         REF //
// GND    -  32 - GND -     - GND               -                         GND //
// 13 PWM -  26 - PB7 -  13 - OC0A/OC1C/PCINT17 - LED Arduino LED_BUILTIN PWM //
// 12 PWM -  18 - PB6 -  12 - OC1B/PCINT16      - Motorshield             PWM //
// 11 PWM -  17 - PB3 -  11 - MOSI/OC2A/PCINT3  - Motorshield             PWM //
// 10 PWM -  16 - PB2 -  10 - SS/OC1B/PCINT2    - Motorshield             PWM //
//  9 PWM -  15 - PB1 -   9 - OC1A/PCINT1       - Motorshield             PWM //
//  8 PWM -  14 - PB0 -   8 - PCINT0/CLK0/ICP1  - Motorshield             DIO //
//                                                                            //
// CONNECTIONS RAILS TOP MIDDLE: DIGITAL PWM<~> ***************************** //
//  7 PWM -  13 - PD7 -   7 - PCINT23/AIN1      - Motorshield             PWM //
//  6 PWM -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 - Motorshield M4 => FREE  PWM //
//  5 PWM -  11 - PD5 -   5 - PCINT21/OC0B/T1   - Motorshield M3=> Buzzer PWM //
//  4 PWM -   6 - PD4 -   4 - PCINT20/XCK/T0    - Motorshield             PWM //
//  3 PWM -   5 - PD3 -   3 - PCINT19/OC2B/INT1 - Motorshield             PWM //
//  2 PWM -   4 - PD2 -   2 - PCINT18/INT0      - IR TV remote receiver   INT //
//  1 TX0 -   3 - PD1 -   1 - PCINT17/TXD       - Serial monitor          TX0 //
//  0 RX0 -   2 - PD0 -   0 - PCINT16/RCD       - Serial Monitor          RC0 //
//                                                                            //
// CONNECTIONS RAILS TOP RIGHT: DIGITAL PWM<~> ****************************** //
// 14 TX3 -  13 - PD7 -   7 - PCINT23/AIN1      -                         DIO //
// 15 RX3 -  12 - PD6 -   6 - PCINT22/OCA0/AIN0 -                         PWM //
// 16 TX2 -  11 - PD5 -   5 - PCINT21/OC0B/T1   - Brains RX1 Yellow       TX2 //
// 17 RX2 -   6 - PD4 -   4 - PCINT20/XCK/T0    - Brains TX1 Blue         RX2 //
// 18 TX1 -   5 - PD3 -   3 - PCINT19/OC2B/INT1 - Speed encoder Right     INT //
// 19 RX1 -   4 - PD2 -   2 - PCINT18/INT0      - Speed encoder Left      INT //
// 20 SDA -   3 - PD1 -   1 - PCINT17/TXD       - SDA Yellow SRF10        SDA //
// 21 SCL -   2 - PD0 -   0 - PCINT16/RCD       - SCL White  SRF10        SCL //
//                                                                            //
// CONNECTIONS RAILS BOTTOM LEFT: POWER ************************************* //
// 5V    -   7 - VCC -     - VCC               -                          VCC //
// RES   -   1 - RES -     - PCINT14/RESET     -                          RES //
// 3.3V  -     -     -     -                   -                              //
// 5V    -     -     -     -                   -                              //
// GND   -     -     -     -                   -                              //
// GND   -     -     -     -                   -                              //
// Vin   -     -     -     -                   -                              //
//                                                                            //
// CONNECTIONS RAILS BOTTOM CENTER: ANALOG IN ******************************* //
// A0    -  23 - PC0 -A0/14- ADC0/PCINT8       -                          ADC //
// A1    -  24 - PC1 -A1/15- ADC1/PCINT9       -                          ADC //
// A2    -  25 - PC2 -A2/16- ADC2/PCINT10      -                          ADC //
// A3    -  26 - PC3 -A3/17- ADC3/PCINT12      -                          ADC //
// A4    -  27 - PC4 -A4/18- ADC4/SDA/PCINT12  -                          TWI //
// A5    -  28 - PC5 -A5/19- ADC5/SCL/PCINT13  -                          TWI //
//                                                                            //
// CONNECTIONS RAILS BOTTOM RIGHT: ANALOG IN ******************************** //
// A11   -  89 - PK0 -     - ADC1 4/PCINT?     -                          ADC //
// A12 = 88 = PK1 ADC15/PCINT?     =                                      ADC //
// A13 = 87 = PK2 ADC14/PCINT?     = IR line follow OUT1                  ADC //
// A15 = 86 = PK3 ADC15/PCINT?     = IR line follow OUT2                  ADC //
// A12 = 85 = PK4 ADC14/PCINT?     = IR line follow OUT3                  ADC //
// A13 = 84 = PK5 ADC15/PCINT?     = IR line follow OUT4                  ADC //
// A14 = 83 = PK6 ADC14/PCINT22    = Battery monitor H=1/2 6Vdc pack      ADC //
// A15 = 82 = PK7 ADC15/PCINT23    = Battery monitor H=1/3 9Vdc battery   ADC //
//                                                                            //

// 20  = 44 = PD1 SDA/INT1         = Speed encoder Right                  TWI //
// 21  = 43 = PD0 SCL/INT0         = Speed encoder Left                   TWI //

// CONNECTIONS RAILS QUER RIGHT ********************************************* //
// 44  = 40 = PL5 OC5C             = 3 Color led Blue                     PWM //
// 45  = 39 = PL4 OC5B             = 3 Color led Red                      PWM //
// 46  = 38 = PL3 OC5A             = 3 Color led Green                    PWM //
// 50  = 22 = PB3 MISO/PCINT3      =                                      SPI //
// 51  = 21 = PB2 MOSI/PCINT2      =                                      SPI //
// 52  = 20 = PB1 SCK/PCINT1       =                                      SPI //
// 53  = 19 = PB1 SS/PCINT0        =                                      SPI //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898
// EEPROM MEMORY MAP:                                                         //
// Start End  Number Description                                              //
// 0000  0000      1 Never use this memory location to be AVR compatible      //
////////////////////////////////////////////////////////////////////////////////
//345678911234567892123456789312345678941234567895123456789612345678971234567898
////////////////////////////////////////////////////////////////////////////////
// FUSES (can always be altered by using the STK500)                          //
// On-Chip Debug Enabled: off                            (OCDEN=0)            //
// JTAG Interface Enabled: off                           (JTAGEN=0)           //
// Preserve EEPROM mem through the Chip Erase cycle: On  (EESAVE = 0)         //
// Boot Flash section = 2048 words, Boot startaddr=$3800 (BOOTSZ=00)          //
// Boot Reset vector Enabled, default address=$0000      (BOOTSTR=0)          //
// CKOPT fuse (operation dependent of CKSEL fuses        (CKOPT=0)            //
// Brown-out detection level at VCC=2,7V;                (BODLEVEL=1)         //
// Ext. Cr/Res High Freq.; Start-up time: 16K CK + 64 ms (CKSEL=1111 SUT=11)  //
// LOCKBITS (are dangerous to change, since they cannot be reset)             //
// Mode 1: No memory lock features enabled                                    //
// Application Protect Mode 1: No lock on SPM and LPM in Application Section  //
// Boot Loader Protect Mode 1: No lock on SPM and LPM in Boot Loader Section  //
////////////////////////////////////////////////////////////////////////////////