15 night and day project with picobricksCategoriesLed Raspberry Pi Pico Uncategorized

#15 Night and Day Project with PicoBricks

How about playing the Night and Day game you played at school electronically? The game of night and day is a game in which we put our head on the table  when our teacher says night, and raise our heads when our teacher says day. This game will be a game that you will use your attention and reflex. In this project, we will use a 0.96” 128×64 pixel I2C OLED display. Since OLED screens can be used as an artificial light source, you can enlarge the characters on the screen using lenses and mirrors and reflect them on the desired plane. Systems that can reflect road and traffic information on smart glasses and automobile windows can be made using OLED screens.

Light sensors are sensors that can measure the light levels of the environment they are in, also called photodiodes. The electrical conductivity of the sensor exposed to light changes. We can control the light sensor by coding and developing electronic systems that affect the amount of light.

Details and Algorithm

First we will ask the player to press the button to start the game. Then we will make the OLED screen display NIGHT and DAY randomly for 2 seconds each. If the word NIGHT is displayed, the player should cover the LDR sensor; and if the word DAY is displayed, uncover it. The player has 2 secs to act. Each correct response of the player will earn 10 points. In case of wrong response, the game will be over and a different tone will sound from the buzzer. The score will be displayed on the OLED screen. If the player gives a total of 10 correct responses and gets 100 points, the phrase “Congratulations” will be displayed on the OLED screen and the buzzer will play notes in different tones.

Components

1X PicoBricks

Wiring Diagram

You can code and run Picobricks modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

204213242 feab9c4e 59f2 47fa 8106 014c8d9c815b

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button.

MicroPython Codes of the PicoBricks

				
					from machine import Pin, I2C, Timer, ADC, PWM
from picobricks import SSD1306_I2C
import utime
import urandom
#define the libraries
WIDTH = 128
HEIGHT = 64
#OLED Screen Settings
sda=machine.Pin(4)
scl=machine.Pin(5)
#initialize digital pin 4 and 5 as an OUTPUT for OLED Communication
i2c=machine.I2C(0,sda=sda, scl=scl, freq=1000000)
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
buzzer = PWM(Pin(20))
buzzer.freq(440)
ldr=ADC(Pin(27))
button=Pin(10,Pin.IN,Pin.PULL_DOWN)
#define the input and output pins
oled.text("NIGHT and DAY", 10, 0)
oled.text("<GAME>", 40, 20)
oled.text("Press the Button", 0, 40)
oled.text("to START!", 40, 55)
oled.show()
#OLED Screen Texts Settings
def changeWord():
    global nightorday
    oled.fill(0)
    oled.show()
    nightorday=round(urandom.uniform(0,1))
    #when data is '0', OLED texts NIGHT
    if nightorday==0:
        oled.text("---NIGHT---", 20, 30)
        oled.show()
    else:
        oled.text("---DAY---", 20, 30)
        oled.show()
    #waits for the button to be pressed to activate
        
while button.value()==0:
    print("Press the Button")
    sleep(0.01)
    
oled.fill(0)
oled.show()
start=1
global score
score=0
while start==1:
    global gamerReaction
    global score
    changeWord()
    startTime=utime.ticks_ms()
    #when LDR's data greater than 2000, gamer reaction '0'
    while utime.ticks_diff(utime.ticks_ms(), startTime)<=2000:
        if ldr.read_u16()>20000:
            gamerReaction=0
        #when LDR's data lower than 2000, gamer reaction '1'
        else:
            gamerReaction=1
        sleep(0.01)
    #buzzer working
    buzzer.duty_u16(2000)
    sleep(0.05)
    buzzer.duty_u16(0)
    if gamerReaction==nightorday:
        score += 10
    #when score is 10, OLED says 'Game Over'
    else:
        oled.fill(0)
        oled.show()
        oled.text("Game Over", 0, 18, 1)
        oled.text("Your score " + str(score), 0,35)
        oled.text("Press RESET",0, 45)
        oled.text("To REPEAT",0,55)
        oled.show()
        buzzer.duty_u16(2000)
        sleep(0.05)
        buzzer.duty_u16(0)
        break;
    if score==100:
        #when score is 10, OLED says 'You Won'
        oled.fill(0)
        oled.show()
        oled.text("Congratulation", 10, 10)
        oled.text("Top Score: 100", 5, 35)
        oled.text("Press Reset", 20, 45)
        oled.text("To REPEAT", 25,55)
        oled.show()
        buzzer.duty_u16(2000)
        sleep(0.1)
        buzzer.duty_u16(0)
        sleep(0.1)
        buzzer.duty_u16(2000)
        sleep(0.1)
        buzzer.duty_u16(0)
        break;
				
			

Arduino C Codes of the PicoBricks

				
					#include <Wire.h>
#include "ACROBOTIC_SSD1306.h"
//define the library


#define RANDOM_SEED_PIN     28
int Gamer_Reaction=0;
int Night_or_Day=0;
int Score=0;
int counter=0;

double currentTime=0;
double lastTime=0;
double getLastTime(){
  return currentTime=millis()/1000.0-lastTime;
}

void _delay(float seconds){
  long endTime=millis()+seconds*1000;
  while (millis()<endTime) _loop();
}

void _loop(){
}

void loop(){
  _loop();
}
//define variable

void setup() {
  // put your setup code here, to run once:
  pinMode(10,INPUT);
  pinMode(27, INPUT);
  pinMode(20,OUTPUT);
  randomSeed(RANDOM_SEED_PIN);
  Wire.begin();
  oled.init();
  oled.clearDisplay();
  //define the input and output pins

  oled.clearDisplay();
  oled.setTextXY(1,3);
  oled.putString("NIGHT and DAY");
  oled.setTextXY(2,7);
  oled.putString("GAME");
  oled.setTextXY(5,2);
  oled.putString("Press the BUTTON");
  oled.setTextXY(6,4);
  oled.putString("to START!");
  //write "NIGHT an DAY, GAME, Press the BUTTON, to START" on the x and y coordinates determined on the OLED screen

  Score=0;
  //define the score variable

  while(!(digitalRead(10)==1))  //until the button is pressed
  {
    _loop();
  }
  _delay(0.2);

  while(1){  //while loop
    if(counter==0){
      delay(500);
      Change_Word();
      lastTime=millis()/1000.0;
    }
    while(!(getLastTime()>2)){
      Serial.println(analogRead(27));
      if(analogRead(27)>200){
        Gamer_Reaction=0;

      }
      else{
        Gamer_Reaction=1;
      }
    }
   //determine the gamer reaction based on the value of the LDR sensor
   digitalWrite(20,HIGH);   //turn on the buzzer
   delay(250);  //wait
   digitalWrite(20,LOW);  //turn off the buzzer

   if(Night_or_Day==Gamer_Reaction){  //if the user's reaction and the Night_or_Day variable are the same
    Correct();
   
   }
   else{
    Wrong();
   }
   _loop();

   if(Score==100){
      oled.clearDisplay();
      oled.setTextXY(1,1);
      oled.putString("Congratulation");
      oled.setTextXY(3,1);
      oled.putString("Your Score");
      oled.setTextXY(3,13);
      String String_Score=String(Score);
      oled.putString(String_Score);
      oled.setTextXY(5,3);
      oled.putString("Press Reset");
      oled.setTextXY(6,3);
      oled.putString("To Repeat!");
      //write the "Congratulation, Your Score, press Reset, To Repeat!" and score variable on the x and y coordinates determined on the OLED screen
      for(int i=0;i<3;i++){
        digitalWrite(20,HIGH);
        delay(500);
        digitalWrite(20,LOW);
        delay(500);
     
    }
    //turn the buzzer on and off three times
    counter=1;

   }
  }
}

void Correct(){
  Score+=10;
  oled.clearDisplay();
  oled.setTextXY(3,4);
  oled.putString("10 Points");
  //increase the score by 10 when the gamer answers correctly
}

void Change_Word(){
  
  oled.clearDisplay();
  Night_or_Day=random(0,2);
  if(Night_or_Day==0){
    oled.setTextXY(3,6);
    oled.putString("NIGHT");

  }
  else{
    oled.setTextXY(3,7);
    oled.putString("DAY");
  }
 
}
//write "NIGHT" or "DAY" on random OLED screen

void Wrong(){
  oled.clearDisplay();
  oled.setTextXY(1,3);
  oled.putString("Game Over");
  oled.setTextXY(3,1);
  oled.putString("Your Score");
  oled.setTextXY(1,13);
  String String_Score=String(Score);
  oled.putString(String_Score);
  oled.setTextXY(5,3);
  oled.putString("Pres Reset");
  oled.setTextXY(6,3);
  oled.putString("To Repeat");
  // write the score variable and the expressions is quotation marks to the coordinates determined on the OLED screen.

  digitalWrite(20,HIGH);  //turn on the buzzer
  delay(1000);   //wait
  digitalWrite(20,LOW); //turn off the buzzer
  counter=1;
}
				
			

Project Image

Project Proposal 💡

You can modify the project based on the LDR sensor values, and automatically determine the limit via calibration of the sensor in code. You can add a difficulty level to the game. The difficulty level can be selected with the potentiometer as easy, medium and hard. The change time for words can be 2 seconds for Easy, 1.5 seconds for Medium, and 1 second for Hard.

14 dinosaur game project with picobricksCategoriesLed Raspberry Pi Pico Uncategorized

#14 Dinosaur Game Project with PicoBricks

If the electronic systems to be developed will fulfill their duties by pushing, pulling, turning, lifting, lowering, etc., pneumatic systems or electric motor systems are used as actuators in the project. PicoBricks supports two different motor types: DC motors and Servo motors. Servo motors are DC motors whose movements are regulated electronically. Servo motors are motors that can rotate to an angle. In RC vehicles, servo motors are used with the same logic to control the steering and change the direction of the vehicle. In addition, advanced servo motors known as smart continuous servos, which can rotate 360 deg, are also used in the wheels of the smart vacuum cleaners we use in our homes.

In this project you will learn how to control Servo motors with PicoBricks.

Details and Algorithm

In this project, we will automatically play Google Chrome offline dinosaur game with PicoBricks. In the game, PicoBricks will automatically control the dinosaur’s movements by detecting obstacles. We will use the PicoBricks LDR sensor to detect the obstacles in front of the dinosaur. LDR can send analog signals by measuring the amount of light touching the sensor surface. By fixing the sensor on the computer screen and monitoring the difference in the amount of light between the white and black colors, we can detect if there is an obstacle in front of the dinosaur. When an obstacle is detected, we can use a servo motor to automatically press the spacebar on the keyboard and make the dinosaur overcome the obstacles. We will attach the LDR sensor to the computer screen and read the sensor data on the white and black background. Then, based on the data, we write the necessary code for the servo motor to move.

Components

1X PicoBricks
1X Servo Motor
3X Easy Connection Cables

Wiring Diagram

Note: PicoBricks motor control module is used to control both DC and SERVO motors. The selection is done with a 3-pin jumper block. The end pins of the jumper block are marked with DC MOTOR and SERVO. Place the jumper to match the type of motor you are using in your project – SERVO in our case.

You can code and run Picobricks modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

204212948 5c168792 f88f 49ff 8608 3f9e9bf0cb9e

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button.

MicroPython Codes of the PicoBricks

				
					from machine import Pin, ADC, PWM#to access the hardware on the pico
from utime import sleep #time library

ldr=ADC(27) #initialize digital pin 27 for LDR
servo=PWM(Pin(21)) #initialize digital PWM pin 27 for Servo Motor
servo.freq(50)

while True:
    sleep(0.01)
    #When LDR data higher than 40000
    if ldr.read_u16()>4000:
        servo.duty_u16(2000)# sets position to 180 degrees
        sleep(0.1)#delay
        servo.duty_u16(1350) # sets position to 0 degrees
        sleep(0.5)#delay
				
			

Arduino C Codes of the PicoBricks

				
					#include <Servo.h>
Servo myservo;

void setup() {
  // put your setup code here, to run once:
  myservo.attach(22);
  myservo.write(20);
  pinMode(27,INPUT);

  

}

void loop() {
  // put your main code here, to run repeatedly:
  int light_sensor=analogRead(27);

  if(light_sensor>100){

    int x=45;
    int y=20;
    
    myservo.write(x);
    delay(100);
    myservo.write(y);
    delay(500);
  }


}
				
			

Project Image

Project Proposal 💡

At first in the game, the ground color is white and the figures are black. After a certain stage, the colors are reversed. For this reason, LDR sensor data changes. To solve this problem, you can use variables and functions to run one code group when the game is on a white background, another code group when it is on a black background, or you can install a second LDR sensor to detect this difference.

PicoBricks and its modules allow us to develop many projects from simple to complex, that we can use in different games such as minecraft.

13 buzz wire game project with picobricksCategoriesRaspberry Pi Pico Uncategorized

#13 Buzz Wire Game Project with PicoBricks

Projects don’t always have to be about solving problems and making things easier. You can also prepare projects to have fun and develop yourself. Attention and concentration are traits that many people want to develop. The applications that we can do around these are quite interesting. How about making Buzz Wire Game with PicoBricks?

You must have heard the expression that computers work with 0s and 1s. 0 represents the absence of electricity and 1 represents its presence. 0 and 1’s combine to form meaningful data. In electronic systems, 0s and 1s can be used to directly control the system. Is the door closed or not? Is the light on or off? Is the irrigation system on or not? In order to obtain such information, a status check is carried out. 

In this project, we will electronically make an attention and concentration developer Buzz Wire Game. It will use a conductor wire, the buzzer,  and the LED module with PicoBricks. While preparing this project, you will learn an input technique that is not a button but will be used like a button.

Details and Algorithm

The objective of the game is to move a cable looped around another one, without touching it.

Due to the conductivity of the cables, when they touch each other, they will close the circuit and cause a sound to be emitted.

The player will be asked to press the button to start the game. We reset the timer after the user presses the button.

Then we will set the conductor wire connected to the GPIO1 pin to HIGH status. One end of the cable held by the player will be connected to the GND pin on the PicoBricks. If the player touches the jumper cable in his hand to the conductive wire, the GPIO1 pin will ground and drop to LOW status. PicoBricks will detect this and give an audible and written warning.

Then, it will announce that the game is over, and there will be feedback with light, text, and audio. The elapsed time will be shown on the OLED screen in milliseconds. After 5 seconds, the player will be prompted to press the button to restart.

Components

1X PicoBricks
1X 15-20 cm conductive wire with a thickness of 0.8 mm
2X Male-Male Jumper Cables

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

Construction Stages of the Project

Along with the PicoBricks base kit,

1: 2 20 cm male-male jumper cables. One end of the cable to be attached to the GND will be stripped 4-5 cm and made into a ring.

2: 15-20 cm conductive wire with a thickness of 0.8 mm. Prepare your materials.

12 1

Bend the conductor wire on the protoboard as you wish and pass it through the holes, before passing one end, you must pass the male end, which is connected to the GND pin on the PicoBoard, the other end of the cable you have made into a ring.

3: Conductor Wire

4: Jumper cable with one end connected to the GND pin with a looped end.

5: One end of the jumper cable, which has both male ends, into the hole right next to the end of the conductive wire you placed on the protoboard

6: Twist the end of the jumper wire and the end of the conductor wire together under the protoboard.

7: Bend the other end of the conductor wire placed on the protoboard so that it does not come out.

8: Connect the other male end of the jumper cable that you wrapped around the end of the conductor wire in step 6 to the pin no. GPIO1 on the Picoboard

If you have completed the installation, you can start the game after installing the code. Have fun. 🙂

MicroBlocks Codes of the PicoBricks

buzz wire game microblocks

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button.

MicroPython Codes of the PicoBricks

				
					from machine import Pin, I2C, Timer #to access the hardware on the pico
from picobricks import SSD1306_I2C #OLED Screen Library
from utime import sleep # time library

#OLED Screen Settings
WIDTH  = 128                                            
HEIGHT = 64

sda=machine.Pin(4)#initialize digital pin 4 and 5 as an OUTPUT for OLED Communication
scl=machine.Pin(5)
i2c=machine.I2C(0,sda=sda, scl=scl, freq=1000000)
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)

wire=Pin(1,Pin.OUT)#initialize digital pin 1 as an OUTPUT 
led = Pin(7,Pin.OUT)#initialize digital pin 7 and 5 as an OUTPUT for LED
buzzer=Pin(20, Pin.OUT)#initialize digital pin 20 as an OUTPUT for Buzzer
button=Pin(10,Pin.IN,Pin.PULL_DOWN)#initialize digital pin 10 as an INPUT for button
endtime=0


while True:
    led.low()
    oled.fill(0)
    oled.show()
    oled.text("<BUZZ WIRE GAME>",0,0)
    oled.text("Press the button",0,17)
    oled.text("TO START!",25,35)
    oled.show()
    #When button is '0', OLED says 'GAME STARTED'
    while button.value()==0:
        print("press the button")
    oled.fill(0)
    oled.show()
    oled.text("GAME",25,35)
    oled.text("STARTED",25,45)
    oled.show()
    wire.high()
    timer_start=utime.ticks_ms()
     #When wire is '1', OLED says 'GAME OVER'
    while wire.value()==1:
        print("Started")
    endtime=utime.ticks_diff(utime.ticks_ms(), timer_start)
    print(endtime)
    oled.fill(0)
    oled.show()
    oled.text("GAME OVER!",25,35)
    oled.text(endtime + "ms" ,25,45)
    oled.show()
    led.high()#LED On
    buzzer.high()#Buzzer On
    sleep(5)#Delay
				
			

Arduino C Codes of the PicoBricks

				
					#include <Wire.h>
#include "ACROBOTIC_SSD1306.h"

int Time=0;
unsigned long Old_Time=0;

void setup() {
  // put your setup code here, to run once:
  pinMode(20,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(1,OUTPUT);
  pinMode(10,INPUT);

  Wire.begin();  
  oled.init();                      
  oled.clearDisplay();
   
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif  


}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(7,LOW);

  oled.setTextXY(2,1);              
  oled.putString("BUZZ WIRE GAME"); 
  oled.setTextXY(4,2);              
  oled.putString("Press Button"); 
  oled.setTextXY(5,3);              
  oled.putString("TO START!");

  while (!(digitalRead(10)==1)){
    
  }

  oled.clearDisplay();
  oled.setTextXY(3,6);              
  oled.putString("GAME"); 
  oled.setTextXY(5,4);              
  oled.putString("STARTED");

  digitalWrite(1,HIGH);
  Old_Time=millis();
  
  while(!(digitalRead(1)==0)){

    Time=millis()-Old_Time;   
  }

  String(String_Time)=String(Time);
  
  oled.clearDisplay();
  oled.setTextXY(3,4);              
  oled.putString("GAME OVER"); 
  oled.setTextXY(5,4);              
  oled.putString(String_Time);
  oled.setTextXY(5,10);              
  oled.putString("ms"); 

  digitalWrite(7,HIGH);
  digitalWrite(20,HIGH);
  delay(500);
  digitalWrite(20,LOW);
  delay(5000);
  
  Time=0;
  Old_Time=0;
  oled.clearDisplay();


}
				
			

Project Image

Project Proposal 💡

You can make physical and software improvements to the project. By covering the start and end points with insulating tape, you can prevent the player from having problems starting and finishing the game. In terms of software, when the player brings the cable to the other end without touching the wire, press the button and you can see the score on the OLED screen.

12 smart cooler project with picobricksCategoriesLed Raspberry Pi Pico Uncategorized

#12 Smart Cooler Project with PicoBricks

Air conditioners are used to cool in the summer and warm up in the winter. Air conditioners adjust the degree of heating and cooling according to the temperature of the environment. While cooking the food, the ovens try to raise the temperature to the value set by the user and maintain it. These two electronic devices use special temperature sensors to control the temperature. In addition, temperature and humidity are measured together in greenhouses. In order to keep these two values in balance at the desired level, it is tried to provide air flow with the fan.

In PicoBricks, you can measure temperature and humidity separately and interact with the environment based on these measurements. In this project, we will prepare a cooling system that automatically adjusts the fan speed according to the temperature. You will learn the DC motor operation and motor speed adjustment.

Details and Algorithm

First, our code will display the temperature values ​​measured by the DHT11 temperature and humidity sensor on PicoBricks. Then, we will define a temperature limit for the DC motor connected to PicoBricks to start running when the temperature value reaches this limit, and to stop when the temperature value falls below the limit.

Components

1X PicoBricks
1X Sound Sensor
3X Jumper Cable

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

smart cooler microblocks

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button.

MicroPython Codes of the PicoBricks

				
					from machine import Pin
from picobricks import DHT11
import utime

LIMIT_TEMPERATURE = 20 #define the limit temperature

dht_sensor = DHT11(Pin(11, Pin.IN, Pin.PULL_DOWN))
m1 = Pin(21, Pin.OUT)
m1.low()
dht_read_time = utime.time()
#define input-output pins

while True:
    if utime.time() - dht_read_time >= 3:
        dht_read_time = utime.time()
        dht_sensor.measure()
        temp= dht_sensor.temperature
        print(temp)
        if temp >= LIMIT_TEMPERATURE:     
            m1.high()
            #operate if the room temperature is higher than the limit temperature
        else:
            m1.low()
				
			

Arduino C Codes of the PicoBricks

				
					#include <DHT.h>

#define LIMIT_TEMPERATURE     27
#define DHTPIN 11
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);
float temperature;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  dht.begin();
  pinMode(21,OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  delay(100);
  temperature = dht.readTemperature();
  Serial.print("Temp: ");
  Serial.println(temperature);
  if(temperature > LIMIT_TEMPERATURE){
    digitalWrite(21,HIGH);
  } else{
    digitalWrite(21,LOW);    
  }


}
				
			

Project Image

Project Proposal 💡

Using the OLED screen on PicoBricks, you can print the temperature on the screen and keep track of the temperature at which the fan is activated.

PicoBricks has a modular structure, modules can be separated by breaking and can be used by connecting to Pico board with Grove cables. By mounting the smart cooling circuit we made onto the robot car chassis, you can develop a project that navigates autonomously in your environment and cools the environment at the same time.

11 magic lamp project with picobricksCategoriesLed Raspberry Pi Pico Uncategorized

#11 Magic Lamp Project with PicoBricks

Most of us have seen lamps flashing magically or doors opening and closing with the sound of clapping in movies. There are set assistants who close these doors and turn off the lamps in the shootings. What if we did this automatically? There are sensors that convert the sound intensity change that we expect to occur in the environment into an electrical signal. These are called sound sensors.

Details and Algorithm

In this project, we will turn the LED module on the picobricks board on and off with the sound. In our project, which we will build using the Picobricks sound level sensor, we will perform the on-off operations by making a clap sound. As in previous projects, in projects where sensors are used, before we start to write the codes, it will make your progress easier to see what values ​​the sensor sends in the operations we want to do by just running the sensor, and then writing the codes of the project based on these values.

Components

1X PicoBricks
1X Sound Sensor
3X Jumper Cable

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

magic lamp microblocks

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button.

MicroPython Codes of the PicoBricks

				
					from machine import Pin #to access the hardware on the pico
sensor=Pin(1,Pin.IN) #initialize digital pin 1 as an INPUT for Sensor
led=Pin(7,Pin.OUT)#initialize digital pin 7 as an OUTPUT for LED
while True:
    #When sensor value is '0', the relay will be '1'
    print(sensor.value())
    if sensor.value()==1:  
        led.value(1)  
    else:
        led.value(0)
           
				
			

Arduino C Codes of the PicoBricks

				
					void setup() {
  // put your setup code here, to run once:
  pinMode(1,INPUT);
  pinMode(7,OUTPUT);
  //define the input and output pins
}

void loop() {
  // put your main code here, to run repeatedly:
  
  
  Serial.println(digitalRead(1));

  if(digitalRead(1)==1){
    digitalWrite(7,HIGH);
    delay(3000);
  }
  else{
    digitalWrite(7,LOW);
    delay(1000);
  }
}
				
			

Project Image

Project Proposal 💡

You can present the player with instructions and notifications on the OLED screen.

10 know your color project with picobricks2CategoriesRaspberry Pi Pico

#10 Know Your Color Project with PicoBricks

LEDs are often used on electronic systems. Each button can have small LEDs next to each option. By making a single LED light up in different colors, it is possible to do the work of more than one LED with a single LED. LEDs working in this type are called RGB LEDs. It takes its name from the initials of the color names Red, Green, Blue. Another advantage of this LED is that it can light up in mixtures of 3 primary colors. Purple, turquoise, orange…

In this project you will learn about the randomness used in every programming language. We will prepare a enjoyable game with the RGB LED, OLED screen and button module of Picobricks.

In this project, we will create a timer alarm that adjusts for daylight using the light sensor in Picobricks.

Details and Algorithm

The game we will build in the project will be built on the user knowing the colors correctly or incorrectly. One of the colors red, green, blue and white will light up randomly on the RGB LED on Picobricks, and the name of one of these four colors will be written randomly on the OLED screen at the same time. The user must press the button of Picobricks within 1.5 seconds to use the right of reply. The game will be repeated 10 times, each repetition will get 10 points if the user presses the button when the colors match, or if the user does not press the button when they do not match. If the user presses the button even though the colors do not match, he will lose 10 points. After ten repetitions, the user’s score will be displayed on the OLED screen. If the user wishes, he may not use his right of reply by not pressing the button.

Components

1X PicoBricks

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

microblock

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button.

MicroPython Codes of the PicoBricks

				
					from machine import Pin, I2C, ADC, PWM  #to access the hardware on the pico
from picobricks import SSD1306_I2C  #OLED Screen Library
import utime
from picobricks import WS2812   #ws8212 library

#OLED Screen Settings
WIDTH  = 128                                            
HEIGHT = 64

sda=machine.Pin(4)
scl=machine.Pin(5)
#initialize digital pin 4 and 5 as an OUTPUT for OLED Communication

i2c=machine.I2C(0,sda=sda, scl=scl, freq=1000000)
neo = WS2812(pin_num=6, num_leds=1, brightness=0.3)#initialize digital pin 6 as an OUTPUT for NeoPixel

oled = SSD1306_I2C(128, 64, i2c)
ldr = ADC(Pin(27))#initialize digital pin 6 as an OUTPUT for NeoPixel
button = Pin(10,Pin.IN,Pin.PULL_DOWN)#initialize digital pin 10 as an INPUT for button
buzzer = PWM(Pin(20, Pin.OUT))#initialize digital pin 20 as an OUTPUT for buzzer
buzzer.freq(1000)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
#RGB black and white color code
oled.fill(0)
oled.show()

neo.pixels_fill(BLACK)
neo.pixels_show()

if ldr.read_u16()<4000:
    wakeup = True
else:
    wakeup = False
    
while True:
    while wakeup==False:
        oled.fill(0)
        oled.show()
        oled.text("Good night",25,32)
        oled.show()
        #Show on OLED and print "Good night"
        utime.sleep(1)
        if ldr.read_u16()<4000:
            while button.value()==0:
                oled.fill(0)
                oled.show()
                oled.text("Good morning",15,32)
                oled.show()
                #Print the minutes, seconds, milliseconds and "Goog morning" values ​​to the X and Y coordinates determined on the OLED screen.
                neo.pixels_fill(WHITE)
                neo.pixels_show()
                buzzer.duty_u16(6000)
                utime.sleep(1)
                #wait for one second
                buzzer.duty_u16(0)
                utime.sleep(0.5)
                #wait for half second
                wakeup=True
            neo.pixels_fill(BLACK)
            neo.pixels_show()
    oled.fill(0)
    oled.show()
    oled.text("Have a nice day!",0,32)
    #Print the minutes, seconds, milliseconds and "Have a nice day!" values ​​to the X and Y coordinates determined on the OLED screen.
    oled.show()
    if ldr.read_u16()>40000:
        wakeup= False
        
    utime.sleep(1)
    #wait for one second
				
			

Arduino C Codes of the PicoBricks

				
					from machine import Pin, I2C
from picobricks import SSD1306_I2C
import utime
import urandom
import _thread
from picobricks import WS2812

WIDTH  = 128                                            
HEIGHT = 64                                          
sda=machine.Pin(4)
scl=machine.Pin(5)
i2c=machine.I2C(0,sda=sda, scl=scl, freq=1000000)
ws = WS2812(pin_num=6, num_leds=1, brightness=0.3)

oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)

button = Pin(10,Pin.IN,Pin.PULL_DOWN)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

oled.fill(0)
oled.show()

ws.pixels_fill(BLACK)
ws.pixels_show()

global button_pressed
score=0
button_pressed = False

def random_rgb():
    global ledcolor
    ledcolor=int(urandom.uniform(1,4))
    if ledcolor == 1:
        ws.pixels_fill(RED)
        ws.pixels_show()
    elif ledcolor == 2:
        ws.pixels_fill(GREEN)
        ws.pixels_show()
    elif ledcolor == 3:
        ws.pixels_fill(BLUE)
        ws.pixels_show()
    elif ledcolor == 4:
        ws.pixels_fill(WHİTE)
        ws.pixels_show()

def random_text():
    global oledtext
    oledtext=int(urandom.uniform(1,4))
    if oledtext == 1:
        oled.fill(0)
        oled.show()
        oled.text("RED",45,32)
        oled.show()
    elif oledtext == 2:
        oled.fill(0)
        oled.show()
        oled.text("GREEN",45,32)
        oled.show()
    elif oledtext == 3:
        oled.fill(0)
        oled.show()
        oled.text("BLUE",45,32)
        oled.show()
    elif oledtext == 4:
        oled.fill(0)
        oled.show()
        oled.text("WHITE",45,32)
        oled.show()

def button_reader_thread():
    while True:
        global button_pressed
        if button_pressed == False:
            if button.value() == 1:
                button_pressed = True
                global score
                global oledtext
                global ledcolor
                if ledcolor == oledtext:
                    score += 10
                else:
                    score -= 10
        utime.sleep(0.01)

_thread.start_new_thread(button_reader_thread, ())

oled.text("The Game Begins",0,10)
oled.show()
utime.sleep(2)

for i in range(10):
    for j in range (10):
        random_text()
        random_rgb()
    button_pressed=False
    utime.sleep(1.5)
    oled.fill(0)
    oled.show()
    ws.pixels_fill(BLACK)
    ws.pixels_show()
utime.sleep(1.5)
oled.fill(0)
oled.show()
oled.text("Your total score:",0,20)
oled.text(str(score), 30,40)
oled.show()
				
			

Project Image

Project Video

Project Proposal 💡

You can make the game more enjoyable by making it a little more difficult. For example, you can speed up the game by reducing the repetition time of the colors. Or, instead of losing points when the user presses the button in the wrong place, you can finish the game and start it again.

9 alarm clock project with picobricksCategoriesRaspberry Pi Pico

#9 Alarm Clock Project with PicoBricks

Global warming is affecting the climate of our world worse every day. Countries take many precautions and sign agreements to reduce the effects of global warming. The use of renewable energy sources and the efficient use of energy is an issue that needs attention everywhere, from factories to our rooms. Many reasons such as keeping road and park lighting on in cities due to human error, and the use of high energy consuming lighting tools reduce energy efficiency. Many electronic and digital systems are developed and programmed by engineers to measure the light, temperature and humidity values ​​of the environment and ensure that they are used only when needed and in the right amounts.

In this project, we will create a timer alarm that adjusts for daylight using the light sensor in Picobricks.

Details and Algorithm

In this project we will make a simple alarm application. The alarm system we will design is designed to sound automatically in the morning. For this, we will use LDR sensor in the project..At night, the OLED screen will display a good night message to the user, in the morning, an alarm will sound with a buzzer sound, a good morning message will be displayed on the screen, and the RGB LED will light up in white for light notification. The user will have to press the button of Picobricks to stop the alarm. After these processes, which continue until the alarm is stopped, when the button is pressed, the buzzer and RGB LED will turn off and a good day message will be displayed on the OLED screen.

Components

1X PicoBricks

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

192686873 f86215fe 5804 45fe a7a2 9736ca5244e0

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button.

MicroPython Codes of the PicoBricks

				
					from machine import Pin, I2C, ADC, PWM  #to access the hardware on the pico
from picobricks import SSD1306_I2C  #OLED Screen Library
import utime
from picobricks import WS2812   #ws8212 library

#OLED Screen Settings
WIDTH  = 128                                            
HEIGHT = 64

sda=machine.Pin(4)
scl=machine.Pin(5)
#initialize digital pin 4 and 5 as an OUTPUT for OLED Communication

i2c=machine.I2C(0,sda=sda, scl=scl, freq=1000000)
neo = WS2812(pin_num=6, num_leds=1, brightness=0.3)#initialize digital pin 6 as an OUTPUT for NeoPixel

oled = SSD1306_I2C(128, 64, i2c)
ldr = ADC(Pin(27))#initialize digital pin 6 as an OUTPUT for NeoPixel
button = Pin(10,Pin.IN,Pin.PULL_DOWN)#initialize digital pin 10 as an INPUT for button
buzzer = PWM(Pin(20, Pin.OUT))#initialize digital pin 20 as an OUTPUT for buzzer
buzzer.freq(1000)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
#RGB black and white color code
oled.fill(0)
oled.show()

neo.pixels_fill(BLACK)
neo.pixels_show()

if ldr.read_u16()<4000:
    wakeup = True
else:
    wakeup = False
    
while True:
    while wakeup==False:
        oled.fill(0)
        oled.show()
        oled.text("Good night",25,32)
        oled.show()
        #Show on OLED and print "Good night"
        utime.sleep(1)
        if ldr.read_u16()<4000:
            while button.value()==0:
                oled.fill(0)
                oled.show()
                oled.text("Good morning",15,32)
                oled.show()
                #Print the minutes, seconds, milliseconds and "Goog morning" values ​​to the X and Y coordinates determined on the OLED screen.
                neo.pixels_fill(WHITE)
                neo.pixels_show()
                buzzer.duty_u16(6000)
                utime.sleep(1)
                #wait for one second
                buzzer.duty_u16(0)
                utime.sleep(0.5)
                #wait for half second
                wakeup=True
            neo.pixels_fill(BLACK)
            neo.pixels_show()
    oled.fill(0)
    oled.show()
    oled.text("Have a nice day!",0,32)
    #Print the minutes, seconds, milliseconds and "Have a nice day!" values ​​to the X and Y coordinates determined on the OLED screen.
    oled.show()
    if ldr.read_u16()>40000:
        wakeup= False
        
    utime.sleep(1)
    #wait for one second
				
			

Arduino C Codes of the PicoBricks

				
					#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> 
#endif
#define PIN        6 

#define NUMPIXELS 1 
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
#include <Wire.h>
#include "ACROBOTIC_SSD1306.h"
int button;
void setup() {
  // put your setup code here, to run once:
   Wire.begin();  
  oled.init();                      
  oled.clearDisplay(); 
  
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
  pinMode(10,INPUT);
  pinMode(27,INPUT);
  pinMode(20,OUTPUT);
  
  pixels.begin();
  pixels.setPixelColor(0, pixels.Color(0, 0, 0));
  pixels.show();

}

void loop() {
  // put your main code here, to run repeatedly:
  oled.setTextXY(4,3);              
    oled.putString("Good night");
    
    if (analogRead(27)<200){

      while(!(button == 1)){
        
        button=digitalRead(10);
       
        oled.setTextXY(4,2);              
        oled.putString("Good morning");
        pixels.setPixelColor(0, pixels.Color(255, 255, 255));
        pixels.show();
        tone(20,494);
      }
        oled.clearDisplay();
        oled.setTextXY(4,1);              
        oled.putString("Have a nice day");
        noTone(20);
        pixels.setPixelColor(0, pixels.Color(0, 0, 0));
        pixels.show();
        delay(10000);
    }


}
				
			

Project Image

Project Video

Project Proposal 💡

You can improve the project by adding a melody as an alarm sound instead of a beep. Or, instead of an alarm set according to daylight with the LDR sensor, you can develop an alarm that sounds at the specified time, where the time information is arranged via the button and OLED screen.

8 my timer project with picobricksCategoriesRaspberry Pi Pico

#8 My Timer Project with PicoBricks

Measuring time is a simple but important task that we do in our daily lives without realizing it. A surgeon in surgery, a business person trying to catch up with a meeting, an athlete trying to win, a student trying to finish an exam or a chess match… Smart wrist watches, phones and even professional chronometers are used to measure time. Time is a variable that should be used very accurately in electronic systems. For example, a washing machine; how long the drum will rotate clockwise, how much counterclockwise, how many seconds water must flow in order to dissolve the detergent are tasks done by measuring time. To develop projects where time is of the essence, you need to know how to use it. 

In this project, you will make your own time measuring device using PicoBricks, OLED display, button and potentiometer modules. A Timer…

Details and Algorithm

When Picobricks starts, let’s put a statement on the screen that introduces the project and contains instructions. As the user turns the potentiometer, it will set a time in the range of 0-60 minutes. When the user presses the button of Picobricks after deciding the time with the potentiometer, it will start counting down in minutes and seconds on the screen. If the button is pressed while the time is running backwards, the Timer will stop and show the remaining time on the screen. If the minute, second and second value reaches zero without pressing the button, a notification stating that the time has expired will be displayed on the screen and the program will be stopped.

Components

1X PicoBricks

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

197472516 ae340b4b 1e9e 44ee 873d c8d1e7af4d79

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button

MicroPython Codes of the PicoBricks

				
					from machine import Pin, I2C, ADC, Timer #to acces the hardware picobricks
from picobricks import SSD1306_I2C #oled library
import utime #time library

WIDTH  = 128                                            
HEIGHT = 64
#define the width and height values

sda=machine.Pin(4)
scl=machine.Pin(5)
#we define sda and scl pins for inter-path communication
i2c=machine.I2C(0,sda=sda, scl=scl, freq=1000000)#determine the frequency values

oled = SSD1306_I2C(128, 64, i2c)
pot = ADC(Pin(26))
button = Pin(10,Pin.IN,Pin.PULL_DOWN)
#determine our input and output pins

oled.fill(0)
oled.show()
#Show on OLED

time=Timer()
time2=Timer()
time3=Timer()
#define timers

def minute(timer):
    global setTimer
    setTimer -=1
    
def second(timer):
    global sec
    sec-=1
    if sec==-1:
        sec=59
        
def msecond(timer):
    global msec
    msec-=1
    if msec==-1:
        msec=99
#We determine the increments of the minute-second and millisecond values.
sec=59
msec=99

global setTimer

while button.value()==0:
    setTimer=int((pot.read_u16()*60)/65536)+1
    oled.text("Set timer:" + str(setTimer) + " min",0,12)
    oled.show()
    utime.sleep(0.1)
    oled.fill(0)
    oled.show()
#If the button is not pressed, the value determined by the potentiometer
is printed on the OLED screen.
    
setTimer-=1

time.init(mode=Timer.PERIODIC,period=60000, callback=minute)
time2.init(mode=Timer.PERIODIC,period=1000, callback=second)
time3.init(mode=Timer.PERIODIC,period=10, callback=msecond)
#We determine the periods of minutes, seconds and milliseconds.
utime.sleep(0.2)#wait for 0.2 second

while button.value()==0:#burda hata var 0>>>>1 olucak çalıştıramadığım için denemedim.
    oled.text("min:" + str(setTimer),50,10)
    oled.text("sec:" + str(sec),50,20)
    oled.text("ms:" + str(msec),50,30)
    oled.show()
    utime.sleep(0.01)
    oled.fill(0)
    oled.show()
    if(setTimer==0 and sec==0 and msec==99):
        utime.sleep(0.1)
        msec=0
        break;
#When the button is pressed, it prints the min-sec-ms values
to the OLED screen in the determined x and y coordinates.
    
oled.text(str(setTimer),60,10)
oled.text(str(sec),60,20)
oled.text(str(msec),60,30)
oled.text("Time is Over!",10,48)
oled.show()
#Print the minutes, seconds, milliseconds and "Time is Over" values
to the X and Y coordinates determined on the OLED screen.
				
			

Arduino C Codes of the PicoBricks

				
					#include <Wire.h>
#include "ACROBOTIC_SSD1306.h"

int minute;
int second = 59;
int milisecond = 9;
int setTimer;

void setup() {
  // put your setup code here, to run once:
  pinMode(10,INPUT);
  pinMode(26,INPUT);

  Wire.begin();  
  oled.init();                      
  oled.clearDisplay(); 


}

void loop() {
  // put your main code here, to run repeatedly:
  oled.setTextXY(1,2);              
  oled.putString("<<My Timer>>");
  oled.setTextXY(3,1);              
  oled.putString("Please use the");
  oled.setTextXY(4,1);              
  oled.putString("Potantiometer");
  oled.setTextXY(5,0);              
  oled.putString("to set the Timer");
  delay(3000);
  oled.clearDisplay(); 
  
    while(!(digitalRead(10) == 1))
  {
    setTimer = (analogRead(26)*60)/1023;
    oled.setTextXY(3,1);              
    oled.putString("set to:");
    oled.setTextXY(3,8);              
    oled.putString(String(setTimer));
    oled.setTextXY(3,11);              
    oled.putString("min.");
  }
    oled.clearDisplay(); 
    oled.setTextXY(1,1);              
    oled.putString("The Countdown");
    oled.setTextXY(2,3);              
    oled.putString("has begin!");
    
    while(!(digitalRead(10) == 1))
  {
    milisecond = 9- (millis()%100)/10;
    second = 59-(millis()%60000)/1000;
    minute = (setTimer-1)-((millis()%360000)/60000);
    
    oled.setTextXY(5,3);              
    oled.putString(String(minute));
    oled.setTextXY(5,8);              
    oled.putString(String(second));
    oled.setTextXY(5,13);              
    oled.putString(String(milisecond));
    oled.setTextXY(5,6);              
    oled.putString(":");
    oled.setTextXY(5,11);              
    oled.putString(":");
  }
    oled.setTextXY(5,3);              
    oled.putString(String(minute));
    oled.setTextXY(5,8);              
    oled.putString(String(second));
    oled.setTextXY(5,13);              
    oled.putString(String(milisecond));
    oled.setTextXY(5,6);              
    oled.putString(":");
    oled.setTextXY(5,11);              
    oled.putString(":");
    delay(10000);

    if (minute==0 & second==0 & milisecond==0){

    oled.setTextXY(5,3);              
    oled.putString(String(minute));
    oled.setTextXY(5,8);              
    oled.putString(String(second));
    oled.setTextXY(5,13);              
    oled.putString(String(milisecond));
    oled.setTextXY(5,6);              
    oled.putString(":");
    oled.setTextXY(5,11);              
    oled.putString(":");  
    oled.putString("-finished-");
    oled.setTextXY(7,5); 
    delay(10000);
    }


}
				
			

Project Image

Project Video

Project Proposal 💡

You can add a beep to the start of the Timer. When the time is reset, you can give different and high tone warnings with the buzzer and announce that the time is up from afar.

7 show your reaction project with picobricksCategoriesRaspberry Pi Pico

#7 Show Your Reaction Project with PicoBricks

Now we will prepare a game that develops attention and reflexes. Moving quickly and being able to pay attention for a long time are important developmental characteristics of children. Preschool and primary school children do activities that increase their attention span and reflexes, as they are liked by their parents and teachers. The electronic system we will prepare will be a game that increases attention and develops reflexes. After finishing the project, you can compete with your friends. 🙂 

In this project you will learn about the randomness used in every programming language. With Picobricks, we will develop an electronic system using OLED display, Button-LED and Buzzer module.

Details and Algorithm

A timer starts running as soon as the Picobricks is turned on. With this timer, we can measure 1 thousandth of a second. One thousandth of a second is called a millisecond. Timers are used in many electronic systems in daily life. Timed lighting, ovens, irons, food processors…

When our project starts working, we will display a welcome message on the OLED screen. Then we will print on the screen what the user has to do to start the game. In order to start the game, we will ask the player to prepare by counting backwards from 3 on the screen after the button is pressed. After the end of the countdown, the red LED will turn on in a random time between 2-10 seconds. We will reset the timer immediately after the red LED lights up. We will measure the timer as soon as the button is pressed again. This value we get will be in milliseconds. We will display this value on the screen as the player’s reaction time.

Components

1X PicoBricks

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

192533930 0e60027a bb45 4aa0 b008 aeaa0483411f

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button

MicroPython Codes of the PicoBricks

				
					from machine import Pin, I2C,Timer
from picobricks import SSD1306_I2C
import utime
import urandom
#define the library
WIDTH=128
HEIGHT=64
#define the width and height values
sda=machine.Pin(4)
scl=machine.Pin(5)
i2c=machine.I2C(0,sda=sda, scl=scl, freq=2000000)
oled= SSD1306_I2C(128, 64, i2c)
button = Pin(10,Pin.IN,Pin.PULL_DOWN)
led=Pin(7,Pin.OUT)
#define our input and output pins
while True:
    led.value(0)
    oled.fill(0)
    oled.text("press the button",0,10)
    oled.text("TO START!",25,25)
    oled.show()
    #print "Press the button" and "TO START!" on the OLED screen
    while button.value()==0:
        pass
    oled.fill(0)
    oled.text("Wait For LED",15,30)
    oled.show()
    #write "wait for LED" on the screen when the button is pressed
    utime.sleep(urandom.uniform(1,5))
    led.value(1)
    timer_start=utime.ticks_ms()
    #wait for a rondom second and turn on the led
    while button.value()==0:
        pass
    timer_reaction=utime.ticks_diff(utime.ticks_ms(), timer_start)
    pressed=True
    oled.fill(0)
    oled.text("Your Time",25,25)
    oled.text(str(timer_reaction),50,50)
    oled.show()
    led.value(0)
    utime.sleep(1.5)
    #print the score and "Your Time" to the screen when the button is pressed.
				
			

Arduino C Codes of the PicoBricks

				
					#include <Wire.h>
#include "ACROBOTIC_SSD1306.h"
//define the library

int buzzer=20;
int button=10;
int led=7;
int La=440;

int old_time=0;
int now_time=0;
int score=0;
String string_score;
//define our integer and string veriables


void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  oled.init();
  oled.clearDisplay();

  pinMode(led,OUTPUT);
  pinMode(buzzer,OUTPUT);
  pinMode(button,INPUT);
  Serial.begin(9600);
  //define the input and output pins

}

void loop() {
  // put your main code here, to run repeatedly:
  oled.setTextXY(3,0);
  oled.putString("Press the button");
  oled.setTextXY(5,4);
  oled.putString("TO START");

  if(digitalRead(button)==1){
    for(int i=3; i>0; i--){

      String string_i=String(i);
      oled.clearDisplay();
      oled.setTextXY(4,8);
      oled.putString(string_i);
      delay(1000);
      
    }
    //count backwards from three

    oled.clearDisplay();
    oled.setTextXY(4,6);
    oled.putString("GO!!!");
    //print "GO!!" on the OLED at x=4 y=6

    int random_wait= random(1000, 5000);
    delay(random_wait);
    //wait for a random second between 1 and 5

    digitalWrite(led, HIGH);
    old_time=millis();
    //turn on LED
    while(!(digitalRead(button)==1)){

      now_time=millis();
      score=now_time-old_time;
      string_score= String(score);
      //save score as string on button press
      
    }
    digitalWrite(led, HIGH);
    tone(buzzer, La);
    delay(200);
    noTone(buzzer);
    //turn on LED and buzzer

    oled.clearDisplay();
    oled.setTextXY(1,4);
    oled.putString("Press the");
    //print "Press the" on the OLED at x=1 Y=4

    oled.setTextXY(2,3);
    oled.putString("RESET BUTTON");
    //print "RESET BUTTON" on the OLED at X=1 Y=4

    oled.setTextXY(3,3);
    oled.putString("To Repeat!");
    //print "To Repeat!" on the OLED at X=3 Y=3

    oled.setTextXY(6,3);
    oled.putString("Score: ");
    oled.setTextXY(6,9);
    oled.putString(string_score);
    oled.setTextXY(6,13);
    oled.putString(" ms");
    Serial.println(score);
    //print score value to screen

    delay(10000);
    oled.clearDisplay();
    //wait ten seconds and clear the screen
  }

}
				
			

Project Image

Project Video

Project Proposal 💡

Picobricks needs to be reset to be able to restart the game. You can develop your project by asking the button to be pressed again to start the game again. You can also have the highest score and the last scorer printed on the screen at the end of the game.

6 dominate the rhythm project with picobricksCategoriesRaspberry Pi Pico

#6 Dominate the Rhythm Project with PicoBricks

Many events in our lives have been digitized. One of them is sounds. The tone and intensity of the sound can be processed electrically. So we can extract notes electronically. The smallest unit of sounds that make up music is called a note. Each note has a frequency and intensity. With the codes we will write, we can adjust which note should be played and how long it should last by applying frequency and intensity.

In this project, we will prepare a music system that will play the melody of a song using the buzzer module and adjust the rhythm with the potentiometer module with Picobricks. You will also learn the use of variables, which has an important place in programming terminology, in this project.

Details and Algorithm

With Picobricks you can play any song whose notes we know. We will use the button-LED module to start the song, the potentiometer module to adjust the speed of the song, and the buzzer module to play the notes.

Potentiometer is analog input module. It is variable resistance. As the amount of current flowing through it is turned, it increases and decreases like opening and closing a faucet. We will adjust the speed of the song by controlling this amount of current with codes. Buzzers change the sound levels according to the intensity of the current passing over them, and the sound tones according to the voltage frequency. With Microblock’s, we can easily code the notes we want from the buzzer module by adjusting their tones and durations.

We will check the button press status in the project. We will make the melody start playing when the button is pressed. During the playing of the melody, we will use a variable called rhythm to increase or decrease the playing times of the notes at the same rate. After Picobricks starts, we will enable the user to adjust the rhythm variable with the potentiometer, either while playing the melody or before playing it. As long as Picobricks is on, we will divide the potentiometer value (0-1023) by 128 and assign it to the rhythm variable. Variables are data structures that we use when we want to use values ​​that can be changed by the user or sensors in our codes. When the user presses the button to start the song, we will prepare the note codes that will allow the notes to play for the duration calculated according to the rhythm variable.

Components

1X PicoBricks

Wiring Diagram

You can code and run Picobricks’ modules without wiring. If you are going to use the modules by separating them from the board, you should make the module connections with grove cables.

MicroBlocks Codes of the PicoBricks

192519503 fbac60e0 1ad1 41a8 afaf 2c315acff592

You can access the Microblocks codes of the project by dragging the image to the Microblocks Run tab or click the button

MicroPython Codes of the PicoBricks

				
					from machine import Pin,PWM,ADC #to acces the hardware picobricks
from utime import sleep #time library

button= Pin(10,Pin.IN,Pin.PULL_DOWN)
pot=ADC(Pin(26))
buzzer= PWM(Pin(20))
#determine our input and output pins
global rithm
pressed = False

tones = {
"A3": 220,
"D4": 294,
"E4": 330,
"F4": 349
}
#define the tones

mysong = ["A3","E4","E4","E4","E4","E4","E4","F4","E4","D4","F4","E4"]#let's define the tones required for our song in the correct order into a sequence
noteTime = [1,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,1]#define wait times between tones into an array

def playtone(frequency):
    buzzer.duty_u16(6000)
    buzzer.freq(frequency)
#define the frequencies of the buzzer
def playsong(pin):
    global pressed
    
    if not pressed:
        pressed = True
        for i in range(len(mysong)):
                playtone(tones[mysong[i]])
                sleep(noteTime[i]/rithm+1)
        buzzer.duty_u16(0)
#play the tones with the right cooldowns
#An finally we need to tell the pins when to trigger, and the function to call when they detect an event:       
button.irq(trigger=Pin.IRQ_RISING, handler=playsong)
while True:
    rithm= pot.read_u16()
    rithm= int(rithm/6400)+1
				
			

Arduino C Codes of the PicoBricks

				
					#include <Wire.h>
#include "ACROBOTIC_SSD1306.h"

int buzzer = 20;
int pot =26;
int button= 10;
//define the buzzer, pot and button 

int Re = 294;
int Mi = 330;
int Fa = 349;
int La = 440;
//DEFİNE THE TONES
void setup()
{
  Wire.begin();  
  oled.init();                      
  oled.clearDisplay();              

  pinMode(buzzer,OUTPUT);
  pinMode(26,INPUT);
  pinMode(button,INPUT);
//determine our input and output pins
}

void loop()
{
  int rithm = (analogRead(pot))/146;
  String char_rithm = String(rithm);
  oled.setTextXY(3,4);              
  oled.putString("Speed: ");
  oled.setTextXY(3,10);              
  oled.putString(char_rithm);
  
  //print "Speed: "  and speed value on the OLED at x=3 y=4

  delay(10); 

  if (digitalRead(button) == 1){

    oled.clearDisplay(); 
    oled.setTextXY(3,2);              
    oled.putString("Now playing...");
//print "Speed: "  and speed value on the OLED at x=3 y=4
    tone(buzzer, La); delay (1000/(rithm+1));
    tone(buzzer, Mi); delay (500/(rithm+1));
    tone(buzzer, Mi); delay (500/(rithm+1));
    tone(buzzer, Mi); delay (500/(rithm+1));
    tone(buzzer, Mi); delay (500/(rithm+1));
    tone(buzzer, Mi); delay (500/(rithm+1));
    tone(buzzer, Mi); delay (500/(rithm+1));
    tone(buzzer, Fa); delay (500/(rithm+1));
    tone(buzzer, Mi); delay (500/(rithm+1));
    tone(buzzer, Re); delay (500/(rithm+1));
    tone(buzzer, Fa); delay (500/(rithm+1));
    tone(buzzer, Mi); delay (1000/(rithm+1));
//play the notes in the correct order and time when the button is pressed

    oled.clearDisplay();
    //clear the screen
  }
  noTone(buzzer);
  //stop the buzzer
}
				
			

Project Image

Project Video

Project Proposal 💡

To make your project more visual, you can light a different color LED according to the played note, show the note names and playing speed on the OLED screen.