The functionality should be:
Attiny should always be a sleep (save battery).
But when my son knock on the piezo element the servo motor should go from 0 to 90 degrees and back. After that attiny should go to sleep again waiting for the next knock.
I found several codes online but it is hard for me to combined them into one working code.
This is the servo code:
include <Servo_ATTinyCore.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(1); // attaches the servo on pin 9 to the servo object
}
void loop() {
//for (pos = 0; pos <= 90; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(90); // tell servo to go to position in variable 'pos'
delay(3000); // waits 15ms for the servo to reach the position
// }
//for (pos = 90; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(0); // tell servo to go to position in variable 'pos'
delay(3000); // waits 15ms for the servo to reach the position
//}
}
This is the sleep code:
#include <avr/sleep.h>
#include <avr/interrupt.h>
// Variables related to the button.
int switchPin = 3;
// Variables related to the leds.
int ledPin1 = 0;
int ledPin2 = 1;
int blinkTime = 300; // This is in milliseconds and controls how long the leds remain on between blinks.
// Setup runs 1 time when the microcontroller first boots up.
void setup()
{
// Setup the pins that control the button and leds.
pinMode(switchPin, INPUT_PULLUP);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
}
// Loop runs over and over, but only when the microcontroller is awake.
void loop()
{
// This function will put the microcontroller into a lower power sleep state
// and it will stop processing code, waiting for the button to be pressed.
sleep();
// After the button is pressed and wakes up the microcontroller, this function will blink the leds.
blinkyBlinky(3, blinkTime);
}
ISR(PCINT0_vect)
{
// This is the interrupt service routine, the code that will run when the microcontroller
// wakes from sleep due to the button press. We don't need to do anything here but having
// this function is required.
}
void sleep()
{
GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts
PCMSK |= _BV(PCINT3); // Use PB3 as interrupt pin
ADCSRA &= ~_BV(ADEN); // ADC off (saves power)
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable(); // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
sei(); // Enable interrupts
sleep_cpu(); // Put the microcontroller to sleep
// Code execution stops here since the microcontroller is now asleep. When the button connected to PB3
// is pressed the microcontroller will awake, run the code in the interrupt service routine (ISR),
// and then continue executing the code starting from here.
cli(); // Disable interrupts
PCMSK &= ~_BV(PCINT3); // Turn off PB3 as interrupt pin
sleep_disable(); // Clear SE bit
ADCSRA |= _BV(ADEN); // ADC on (we turned it off the save power)
sei(); // Enable interrupts
}
void blinkyBlinky(int repeats, int time)
{
for (int i = 0; i < repeats; i++)
{
// Led 1
digitalWrite(ledPin1, HIGH);
delay(time);
digitalWrite(ledPin1, LOW);
delay(time);
// Led 2
digitalWrite(ledPin2, HIGH);
delay(time);
digitalWrite(ledPin2, LOW);
delay(time);
}
}
The online sleep code is now blinkking 2 led's but it should run my servo code.
Also when i test the online sleep code on startup it always bliks and i have to press de interrupt button first to get it to go sleep mode.
I would like if someone could tell me how to make the attiny go to sleep immediately after startup and only wakeup and do 1 servo sweep (0 to 90 degrees and back) and go to sleep again.
Hope some can help me. Me and my son would appriciate it a lot.
Merging the setup code is simple: copy one of them and paste it in front of or at the end of the other. If any pins or LEDs, etc, are the same, change one to be different.
The loop code is a bit more complicated, but one approach is to create a new loop and have it run loop1 and loop2. You create loop1 and 2 by copying the loops from the 2 sketches paste and rename as needed. Don't forget to adjust the loop code for any changes made in setup, like pins or LEDs.
It may fail to compile but just work through them obne at a time.
NOTE: This is not the recommended way but it can work.
This is mine working code with servo en piezo element.
this works fine. But it consumes to much power.
/*
Controlling a servo with Push button with Arduino
this is code #1 to control servo with push button by Robojax (Robojax.com )
code #1 when push button the servo goes from 0° to 180° (or set your angle) and returns back
Watch video for code #1: https://youtu.be/fPrPRZlGdvA
*/
#include <DigiKeyboard.h>
#include <Servo_ATTinyCore.h>
Servo myservo; // create servo object to control a servo
#define servoPin 0 //~
#define ledPin 1
const int knockSensor = 1; // the piezo is connected to analog pin 3
const int threshold = 150;
// these variables will change:
int sensorReading = 0; // variable to store the value read from the sensor pin
int ledState = LOW; // variable used to store the last LED status, to toggle the light
////////////////////SERVO//////////////////////////////////
int angle =1; // initial angle for servo (beteen 1 and 179)
int angleStep =2;
const int minAngle = 1;
const int maxAngle = 90;
const int type =2;//watch video for details. Link is at the top of this code (robojax)
int buttonPushed =0;
void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
//DigiKeyboard.delay(2000);
//DigiKeyboard.println("In Setup"); // setup serial
myservo.attach(servoPin); // attaches the servo on pin 3 to the servo object
myservo.write(angle);//initial position
}
void loop() {
sensorReading = analogRead(knockSensor);
//DigiKeyboard.println(buttonPushed);
//DigiKeyboard.println(sensorReading);
//DigiKeyboard.println("In de loop");
if (sensorReading >= threshold) {
ledState = !ledState;
buttonPushed = 1;
// myservo.attach(servoPin);
digitalWrite(1, ledState);
//DigiKeyboard.println("Knock!");
}
//delay(10); // delay to avoid overloading the serial port buffer
while( buttonPushed ){
// DigiKeyboard.println(buttonPushed);
angle = angle + angleStep;
if (angle >= maxAngle) {
angleStep = -angleStep;
if(type ==1)
{
buttonPushed =0;
}
}
if (angle <= minAngle) {
angleStep = -angleStep;
if(type ==2)
{
buttonPushed =0;
myservo.write(angle);
// delay(800);
}
}
myservo.write(angle); // move the servo to desired angle
// Serial.print("Moved to: ");
// Serial.print(angle); // print the angle
// Serial.println(" degree");
delay(100); // waits for the servo to get there
}
}
Now i only need to combine his code with the sleep code.
My only worry is that because of the piezo element attiny wil always be interrapted i.e. wil never go to sleep. On the serial i see small readings without me touching the piezo element. Can i INPUT_PULLUP the piezo element? would it make pin 3 clean and only wakeup after knocking piezo element?
Cannot study this much now but later I'd like to try to reproduce your sketch. I assume your latest is now the full version? However I do not have and cannot find your library: #include <DigiKeyboard.h>
Also to fully understand your project we will need a circuit schematic.
Meanwhile I assume the 'Related Topics' below were of no help?
When i upload this code to my attiny with no changes,the precedure that im experiencing is:
When i boot-up Attiny the leds go blinking.
Then i have to press the interrupt button and after yet another 30x blinking the attiny goes to sleep. im i correct? is this also whats in the code?
im trying to get the attiny to go to sleep imidiately after first boot.
but i don't know wich prat of the code is responsible for this.
What is the model of the board used to provide the 5V? Is it powerful enough to power the loaded servo?
I don't see any interrupt button on the schematic nor on the Arduino picture. EDIT: or is it the piezo? There's no interrupt declared in the sketch post #4 anyway.
I don't see any sleep() instruction in the sketch post #4.
If you want to save power, don't use analogRead() as the ADC will have to stay active during 'sleep' and frequently tested. Make it so that a knock on the piezo will generate a valid 1 (or 0) logic state stable long enough for the µC to detect and run (restart) again (a few ms, it should be easy but has to be tested).
Sleep modes are detailed in the µC datasheet page 34 and following. You don't need to understand it all but to get an idea of how it works and what can be done or not.
I’m still unclear about your circuit. My ATtiny85 is an 8-pin chip, which I program with a Uno as ISP. Is yours in a development module?
I assume the DigiKeyboard library is to support a keyboard that doesn’t appear on your schematic? I will ignore it.
EDIT: Try this which I've finally got working, although I'd be hard pressed to explain some of the code. Uses LED instead of servo for now. On power-up, goes straight to sleep. Every 20 seconds (waitTime), wakes up. Lights LED for 2 seconds (wokenTime), then returns to sleep. No button or other user interaction. but shouldn't be too difficult to add your piezo trigger.
Will tomorrow try transferring to ATtiny85.
/*
Tue 5 Aug 2025
Uses LED instead of servo for now
On power-up, goes straight to sleep.
Every 20 seconds (waitTime), wakes up.
Lights LED for 2 seconds (wokenTime), then returns to sleep.
No button, no user interaction.
Will tomorrow try transferring to ATtiny85
*/
#include <avr/sleep.h>
#include <avr/wdt.h>
const int led = 3;
const unsigned long waitTime = 20000UL; // 20 seconds
const unsigned long wokenTime = 2000UL; // 2 seconds
volatile bool wokeUp = false;
unsigned long accumulatedTime = 0;
void setup() {
ADCSRA &= ~_BV(ADEN); // Disable ADC
ACSR |= _BV(ACD); // Disable analog comparator
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
pinMode(led, OUTPUT);
digitalWrite(led, LOW); // Ensure LED is off
// Set up WDT interrupt every ~1 second
setup_watchdog();
// Go to sleep immediately
sleepNow();
}
void loop() {
if (!wokeUp) return;
wokeUp = false;
accumulatedTime += 1000; // ~1s steps
if (accumulatedTime >= waitTime) {
digitalWrite(led, HIGH);
delay(wokenTime);
digitalWrite(led, LOW);
accumulatedTime = 0;
}
sleepNow();
}
void sleepNow() {
sleep_enable();
sleep_cpu();
sleep_disable();
}
ISR(WDT_vect) {
wokeUp = true;
}
// WDT interrupt setup for ~1s interval
void setup_watchdog() {
cli();
// Set WDT to interrupt every ~1 second
WDTCSR = (1 << WDCE) | (1 << WDE);
WDTCSR = (1 << WDIE) | (1 << WDP2) | (1 << WDP1); // ~1.0s
sei();
}
It simply flashes the Led for 0.2s each time the piezo is knocked as can be tested here:
In case it helps, here is an example:
The Wokwi code:
Code
/**
Simon Game for ATTiny85
Copyright (C) 2018, Uri Shaked
Licensed under the MIT License.
*/
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include "pitches.h"
/* Constants - define pin numbers for leds, buttons and speaker, and also the game tones */
byte buttonPins[] = {1, 2, 3, 4};
#define SPEAKER_PIN 0
#define MAX_GAME_LENGTH 100
int gameTones[] = { NOTE_G3, NOTE_C4, NOTE_E4, NOTE_G5};
/* Global variales - store the game state */
byte gameSequence[MAX_GAME_LENGTH] = {0};
byte gameIndex = 0;
/**
Set up the GPIO pins
*/
void setup() {
// The following line primes the random number generator. It assumes pin A0 is floating (disconnected)
randomSeed(analogRead(1));
// Disable ADC - saves about 324.5uA in sleep mode!
ADCSRA = 0;
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
for (int i = 0; i < 4; i++) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(SPEAKER_PIN, INPUT);
}
ISR(PCINT0_vect) {
GIMSK &= ~0b00100000; // Turn off pin change interrupts
sleep_disable();
}
void sleep() {
sleep_enable();
noInterrupts();
GIMSK |= 0b00100000; // Turn on pin change interrupts
for (byte i = 0; i < 4; i++) {
PCMSK |= 1 << buttonPins[i];
}
interrupts();
sleep_cpu();
}
// The sound-producing function
void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
{ // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
int x;
long delayAmount = (long)(1000000 / frequencyInHertz);
long loopTime = (long)((timeInMilliseconds * 1000) / (delayAmount * 2));
pinMode(speakerPin, OUTPUT);
for (x = 0; x < loopTime; x++) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(delayAmount);
digitalWrite(speakerPin, LOW);
delayMicroseconds(delayAmount);
}
pinMode(speakerPin, INPUT);
}
/**
Lights the given led and plays the suitable tone
*/
void lightLedAndPlaySound(byte ledIndex) {
pinMode(buttonPins[ledIndex], OUTPUT);
digitalWrite(buttonPins[ledIndex], LOW);
beep(SPEAKER_PIN, gameTones[ledIndex], 300);
pinMode(buttonPins[ledIndex], INPUT_PULLUP);
}
/**
Plays the current sequence of notes that the user has to repeat
*/
void playSequence() {
for (int i = 0; i < gameIndex; i++) {
byte currentLed = gameSequence[i];
lightLedAndPlaySound(currentLed);
delay(50);
}
}
/**
Waits until the user pressed one of the buttons, and returns the index of that button
*/
byte readButton() {
for (;;) {
for (int i = 0; i < 4; i++) {
byte buttonPin = buttonPins[i];
if (digitalRead(buttonPin) == LOW) {
return i;
}
}
sleep();
}
}
/**
Plays the tone associated with a specific button + debouncing mechanism
*/
void playButtonTone(byte buttonIndex) {
beep(SPEAKER_PIN, gameTones[buttonIndex], 150);
// Wait until button is released.
while (digitalRead(buttonPins[buttonIndex]) == LOW);
delay(50);
}
/**
Play the game over sequence, and report the game score
*/
void gameOver() {
gameIndex = 0;
delay(200);
// Play a Wah-Wah-Wah-Wah sound
beep(SPEAKER_PIN, NOTE_DS5, 300);
beep(SPEAKER_PIN, NOTE_D5, 300);
beep(SPEAKER_PIN, NOTE_CS5, 300);
for (int i = 0; i < 200; i++) {
beep(SPEAKER_PIN, NOTE_C5 + (i % 20 - 10), 5);
}
delay(500);
}
/**
Get the user input and compare it with the expected sequence. If the user fails, play the game over sequence and restart the game.
*/
void checkUserSequence() {
for (int i = 0; i < gameIndex; i++) {
byte expectedButton = gameSequence[i];
byte actualButton = readButton();
playButtonTone(actualButton);
if (expectedButton == actualButton) {
/* good */
} else {
gameOver();
return;
}
}
}
/**
Plays an hooray sound whenever the user finishes a level
*/
void levelUp() {
beep(SPEAKER_PIN, NOTE_E4, 150);
beep(SPEAKER_PIN, NOTE_G4, 150);
beep(SPEAKER_PIN, NOTE_E5, 150);
beep(SPEAKER_PIN, NOTE_C5, 150);
beep(SPEAKER_PIN, NOTE_D5, 150);
beep(SPEAKER_PIN, NOTE_G5, 150);
}
/**
The main game loop
*/
void loop() {
// Add a random color to the end of the sequence
gameSequence[gameIndex] = random(0, 4);
gameIndex++;
playSequence();
checkUserSequence();
delay(300);
if (gameIndex > 0) {
levelUp();
delay(300);
}
}