/*
Demo of simple toggle on/off button code
Button toggles two seperate groups of leds
Uses button state 'status' to determine last state of button press
Button connected to PB0
LEDs connected to PB1..PB4
Sketch size: 1444 bytes. Same sketch using Arduino framework: 3274 bytes
Remove Serial.begin and Serial.println and size is 318 bytes
1/12/24 CM: Added debounce code, need to work on this.
*/
#include <avr/io.h>
#include <util/delay.h>
#include <TinyDebug.h>
#define BUTTON PB0
// Function to print value as 8 bit binary number
int binaryNumber[8]; // Empty array to store 8-bit (0 - 255) binary number
void Eight_Bit_Binary_Array(int num);
int main(void) {
Debug.begin();
uint8_t buttonStatus = 0; // button state
uint8_t buttonRead;
uint8_t oldButtonRead = 0;
const uint8_t debounceTime = 10; // milliseconds
DDRB = 0xff; // set all of DDRB as output, 11111111
DDRB &= ~(1 << BUTTON); // set PB0 -> BUTTON as input 11111110
PORTB = 0x00; // set all of PORTB low, 00000000
PORTB |= (1 << BUTTON); // initialize pullup resistor on PB0 -> BUTTON, 00000001
//BUTTON_PORT = 0x01; // same result as above
while (1) {
// Push button 1
buttonRead = digitalRead(PB0); // reads 1 with pull-up
//Debug.print("buttonRead: "); Debug.println(buttonRead);
// Button debounce
if (buttonRead != oldButtonRead) {
oldButtonRead = buttonRead;
_delay_ms(debounceTime);
// PINB contains input state of all B pins. So PINB is 00000001 as PB0 was set with a pullup resistor.
// (1 << PB0) is 00000001,
if ((PINB & (1 << PB0)) == 1) { // using AND, 00000001 AND 00000001 = 1, so this is true and runs code
Debug.print("buttonStatus1 = "); Debug.println(buttonStatus);
Debug.print(F("PINB pullup button")); Eight_Bit_Binary_Array(PINB);
if (buttonStatus == 0) {
Debug.print("buttonStatus2 = "); Debug.println(buttonStatus);
PORTB = 0b00000110; // so this is the beginning state before a button push
buttonStatus = 1; // update the state
Debug.print("buttonStatus3 = "); Debug.println(buttonStatus);
}
}
else { // button is not pressed now
PORTB = 0b00011000; // when button is pushed PINB will be 00000000 AND 00000001 will result in 0
buttonStatus = 0; // update the state
Debug.print("buttonStatus4 = "); Debug.println(buttonStatus);
}
_delay_ms(100);
Debug.print("buttonStatus5 = "); Debug.println(buttonStatus);
Debug.print("PINB = "); Eight_Bit_Binary_Array(PINB);
}
}
return 0;
}
void Eight_Bit_Binary_Array(int num) {
// Convert decimal to binary and store the bits in an array
for (int i = 7; i >= 0; i--) {
binaryNumber[i] = num & 1; // Extract the least significant bit
num >>= 1; // Right-shift the decimal number to get the next bit
}
Debug.print(" = ");
for (int i = 0; i < 8; i++) {
Debug.print(binaryNumber[i]); // Print the binary number only of the array
}
Debug.print("\n");
}