CategoriesLed Raspberry Pi Pico Uncategorized

#25 Smart Greenhouse Project with PicoBricks

The rapid changes in climate due to the effect of global warming cause a decrease in productivity in agricultural activities. In the 1500s, Daniel Barbaro built the first known greenhouse in history. Greenhouses are suitable environments for growing plants that can provide controllable air, water, heat and light conditions.

In greenhouses, heaters are used to balance the heat, electric water motors for irrigation, fans are used to regulate humidity and to provide pollination. With the development of technology, the producer can follow the status of the greenhouse with his phone from anywhere and can do the work that needs to be done. The general name of this technology is Internet of Things (IOT).

Special sensors are used to measure temperature, humidity and oxygen content in greenhouses. In addition, special sensors measuring soil moisture are used to decide on irrigation. Electronically controlled drip irrigation systems are used to increase irrigation efficiency.

In this project, we will prepare a simple greenhouse with IOT technology and PicoBricks. We will use PicoBricks with the ESP8266 wifi module in this greenhouse. In this way, we will turn the greenhouse into an object that we can track over the Internet.

Details and Algorithm

The greenhouse model you will prepare will include a soil moisture sensor, and a DHT11 temperature and humidity sensor hanging from the top. A submersible pump will be placed in the water tank outside the model, and the hose coming out of the end of the pump will go to the ground in the greenhouse. Picoboard will be placed in a suitable place outside the greenhouse model.
When Picobricks starts, it starts to broadcast wifi thanks to the ESP8266 wifi module. When we enter the IP address of Esp8266 from the smart phone connected to the same network, we encounter the web page where we will control the Greenhouse. Here we can see the temperature and humidity values. If we wish, we can start the irrigation process by giving the irrigation command.

Components

1X PicoBricks
1X Pump
1X Soil Humidity Sensor
1X ESP8266 Wifi Module
PicoBricks Smart Greenhouse Kit
Jumper Cables
Easy Connection 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

1-Detach the floor of the Greenhouse model from the SR-2 coded part in the Greenhouse kit.

2- Attach the pieces in the middle of the SR-3 piece to the floor of the Greenhouse.

3- Remove the inner walls of the greenhouse from the SR-4 part and attach it to the ground of the greenhouse.

4- Remove the Greenhouse arches in SR-1 and SR-3 and place them on the greenhouse floor.

5-Cover the rectangular area where soil will be placed with cling film. After irrigation, you will protect the model parts. Pour the plant soil into the greenhouse. Fill so that there is no empty space.

6- Insert the parts of the SR-4 into the notches on the greenhouse.

7-Thread the remaining two thin flat pieces of SR-4 through the holes on both sides of the greenhouse from the underside. This process makes the greenhouse more robust.

8- Pass the hose to the submersible pump. You will install an irrigation system similar to the drip irrigation system in the greenhouse. Pass the hose where you want the soil to be irrigated. Remember to cut the hose just enough to reach the water tank.

9- Place the DHT11 temperature and humidity sensor on the greenhouse model and the Soil Moisture Sensor in the soil.

10- Plug the Soil Moisture sensor to the pin number GPIO27 on the Picoboard and connect the 2 pen battery to the power input of the Picoboard. Place the submersible pump and the end of the hose in a deep container of water. Be careful not to get the motor drive wet.

MicroBlocks Codes of the PicoBricks

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

				
					import utime
import uos
import machine 
from machine import Pin, ADC
from picobricks import DHT11  
from utime import sleep 

dht_sensor = DHT11(Pin(11))
smo_sensor=ADC(27)
m1 = Pin(22, Pin.OUT)
m1.low()

print("Machine: \t" + uos.uname()[4])
print("MicroPython: \t" + uos.uname()[3])

uart0 = machine.UART(0, baudrate=115200)
print(uart0)

def Connect_WiFi(cmd, uart=uart0, timeout=5000):
    print("CMD: " + cmd)
    uart.write(cmd)
    utime.sleep(7.0)
    Wait_ESP_Rsp(uart, timeout)
    print()
    
def Rx_ESP_Data():
    recv=bytes()
    while uart0.any()>0:
        recv+=uart0.read(1)
    res=recv.decode('utf-8')
    return res

def Send_AT_Cmd(cmd, uart=uart0, timeout=2000):
    print("CMD: " + cmd)
    uart.write(cmd)
    Wait_ESP_Rsp(uart, timeout)
    print()

def Wait_ESP_Rsp(uart=uart0, timeout=2000):
    prvMills = utime.ticks_ms()
    resp = b""
    while (utime.ticks_ms()-prvMills)<timeout:
        if uart.any():
            resp = b"".join([resp, uart.read(1)])
    print("resp:")
    try:
        print(resp.decode())
    except UnicodeError:
        print(resp)

Send_AT_Cmd('AT\r\n')          #Test AT startup
Send_AT_Cmd('AT+GMR\r\n')      #Check version information
Send_AT_Cmd('AT+CIPSERVER=0\r\n')   
Send_AT_Cmd('AT+RST\r\n')      #Check version information
Send_AT_Cmd('AT+RESTORE\r\n')  #Restore Factory Default Settings
Send_AT_Cmd('AT+CWMODE?\r\n')  #Query the WiFi mode
Send_AT_Cmd('AT+CWMODE=1\r\n') #Set the WiFi mode = Station mode
Send_AT_Cmd('AT+CWMODE?\r\n')  #Query the WiFi mode again
Send_AT_Cmd('AT+CWJAP="ID","Password"\r\n', timeout=5000) #Connect to AP
utime.sleep(3.0)
Send_AT_Cmd('AT+CIFSR\r\n')    #Obtain the Local IP Address
utime.sleep(3.0)
Send_AT_Cmd('AT+CIPMUX=1\r\n')    
utime.sleep(1.0)
Send_AT_Cmd('AT+CIPSERVER=1,80\r\n')    #Obtain the Local IP Address
utime.sleep(1.0)

while True:
    res =""
    res=Rx_ESP_Data()
    utime.sleep(2.0)
    if '+IPD' in res: # if the buffer contains IPD(a connection), then respond with HTML handshake
        id_index = res.find('+IPD')
        
        if '/WATERING' in res:
            print('Irrigation Start')
            m1.high()
            utime.sleep(10)
            m1.low()
            print('Irrigation Finished')
            connection_id =  res[id_index+5]
            print("connectionId:" + connection_id)
            print ('! Incoming connection - sending webpage')
            uart0.write('AT+CIPSEND='+connection_id+',200'+'\r\n')  
            utime.sleep(1.0)
            uart0.write('HTTP/1.1 200 OK'+'\r\n')
            uart0.write('Content-Type: text/html'+'\r\n')
            uart0.write('Connection: close'+'\r\n')
            uart0.write(''+'\r\n')
            uart0.write('<!DOCTYPE HTML>'+'\r\n')
            uart0.write('<html>'+'\r\n')
            uart0.write('<body><center><H1>CONNECTED...<br/></H1></center>'+'\r\n')
            uart0.write('<body><center><H1>Irrigation Complete.<br/></H1></center>'+'\r\n')
            uart0.write('</body></html>'+'\r\n')
        elif '/SERA' in res:
            #sleep(1) # It was used for DHT11 to measure.
            dht_sensor.measure() # Use the sleep() command before this line.
            temp=dht_sensor.temperature
            hum=dht_sensor.humidity
            smo=round((smo_sensor.read_u16()/65535)*100)
            sendStr="\"TEMP\":{}, \"Humidity\":{}, \"S.Moisture\":{}%".format(temp,hum,smo)
            sendText="{"+sendStr+"}"
            strLen=46+len(sendText)
            connection_id =  res[id_index+5]
            print("connectionId:" + connection_id)
            print ('! Incoming connection - sending webpage')
            atCmd="AT+CIPSEND="+connection_id+","+str(strLen)
            uart0.write(atCmd+'\r\n') 
            utime.sleep(1.0)
            uart0.write('HTTP/1.1 200 OK'+'\r\n')
            uart0.write('Content-Type: text/html'+'\r\n')
            uart0.write(''+'\r\n')
            uart0.write(sendText+'\r\n')

        elif '/' in res:
            
            print("resp:")
            print(res)
            connection_id =  res[id_index+5]
            print("connectionId:" + connection_id)
            print ('! Incoming connection - sending webpage')
            uart0.write('AT+CIPSEND='+connection_id+',200'+'\r\n') 
            utime.sleep(3.0)
            uart0.write('HTTP/1.1 200 OK'+'\r\n')
            uart0.write('Content-Type: text/html'+'\r\n')
            uart0.write('Connection: close'+'\r\n')
            uart0.write(''+'\r\n')
            uart0.write('<!DOCTYPE HTML>'+'\r\n')
            uart0.write('<html>'+'\r\n')
            uart0.write('<body><center><H1>CONNECTED.<br/></H1></center>'+'\r\n')
            uart0.write('<center><h4>INFO:Get Sensor Data</br>WATERING:Run Water Pump</h4></center>'+'\r\n')
            uart0.write('</body></html>'+'\r\n')
        utime.sleep(4.0)
        Send_AT_Cmd('AT+CIPCLOSE='+ connection_id+'\r\n') # once file sent, close connection
        utime.sleep(3.0)
        recv_buf="" #reset buffer
        print ('Waiting For connection...')
				
			

Arduino C Codes of the PicoBricks

				
					#include <DHT.h>
#define RX 0
#define TX 1

#define LIMIT_TEMPERATURE     30
#define DHTPIN                11
#define DHTTYPE               DHT11
#define smo_sensor            27
#define motor                 22
#define DEBUG true

DHT dht(DHTPIN, DHTTYPE);
int connectionId;

void setup() {
  Serial1.begin(115200);
  dht.begin();
  pinMode(smo_sensor, INPUT);
  pinMode(motor, OUTPUT);

  sendData("AT+RST\r\n", 2000, DEBUG); // reset module
  sendData("AT+GMR\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CIPSERVER=0\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+RST\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+RESTORE\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWMODE?\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWMODE?\r\n", 1000, DEBUG); // configure as access point
  sendData("AT+CWJAP=\"WIFI_ID\",\"WIFI_PASSWORD\"\r\n", 5000, DEBUG); // ADD YOUR OWN WIFI ID AND PASSWORD
  delay(3000);
  sendData("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
  delay(3000);
  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  delay(1000);
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port 80
  delay(1000);
}

void loop() {
  if (Serial1.find("+IPD,")) {
    delay(300);
    connectionId = Serial1.read() - 48;
    String serialIncoming = Serial1.readStringUntil('\r');
    Serial.print("SERIAL_INCOMING:");
    Serial.println(serialIncoming);

    if (serialIncoming.indexOf("/WATERING") > 0) {
      Serial.println("Irrigation Start");
      digitalWrite(motor, HIGH);
      delay(1000); // 10 sec.
      digitalWrite(motor, LOW);
      Serial.println("Irrigation Finished");
      Serial.println("! Incoming connection - sending WATERING webpage");
      String html = "";
      html += "<html>";
      html += "<body><center><H1>Irrigation Complete.<br/></H1></center>";
      html += "</body></html>";
      espsend(html);
    }
    if (serialIncoming.indexOf("/SERA") > 0) {
      delay(300);

      float smo = analogRead(smo_sensor);
      float smopercent = (460-smo)*100.0/115.0 ; //min ve max değerleri değişken.
      Serial.print("SMO: %");
      Serial.println(smo);

      float temperature = dht.readTemperature();
      Serial.print("Temp: ");
      Serial.println(temperature);

      float humidity = dht.readHumidity();
      Serial.print("Hum: ");
      Serial.println(humidity);
      
      Serial.println("! Incoming connection - sending SERA webpage");
      String html = "";
      html += "<html>";
      html += "<body><center><H1>TEMPERATURE<br/></H1></center>";
      html += "<center><H2>";
      html += (String)temperature;
      html += " C<br/></H2></center>";

      html += "<body><center><H1>HUMIDITY<br/></H1></center>";
      html += "<center><H2>";
      html += (String)humidity;
      html += "%<br/></H2></center>";  
      
      html += "<body><center><H1>SMO<br/></H1></center>";
      html += "<center><H2>";
      html += (String)smopercent;
      html += "%<br/></H2></center>";  
          
      html += "</body></html>";
      espsend(html);
    }
    else
      Serial.println("! Incoming connection - sending MAIN webpage");
    String html = "";
    html += "<html>";
    html += "<body><center><H1>CONNECTED.<br/></H1></center>";
    html += "<center><a href='/SERA'><h4>INFO:Get Sensor Data</a></br><a href='/WATERING'>WATERING:Run Water Pump</a></h4></center>";
    html += "</body></html>";
    espsend(html);
    String closeCommand = "AT+CIPCLOSE=";  ////////////////close the socket connection////esp command
    closeCommand += connectionId; // append connection id
    closeCommand += "\r\n";
    sendData(closeCommand, 3000, DEBUG);

  }

}
//////////////////////////////sends data from ESP to webpage///////////////////////////

void espsend(String d)
{
  String cipSend = " AT+CIPSEND=";
  cipSend += connectionId;
  cipSend += ",";
  cipSend += d.length();
  cipSend += "\r\n";
  sendData(cipSend, 1000, DEBUG);
  sendData(d, 1000, DEBUG);
}

//////////////gets the data from esp and displays in serial monitor///////////////////////

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  Serial1.print(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (Serial1.available())
    {
      char c = Serial1.read(); // read the next character.
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response); //displays the esp response messages in arduino Serial monitor
  }
  return response;
}
				
			

Project Image

Project Proposal 💡

In the smart greenhouse project, by adding an OLED screen to the greenhouse entrance, you can monitor the humidity and temperature values inside, and by adding sensors such as MQ2 gas sensor, carbon dioxide sensor, air quality sensor, you can monitor the weather inside the greenhouse via WiFi with your mobile phone. In addition, by adding a DC fan and relay to the greenhouse, you can turn the ventilation on and off according to the indoor air quality with a mobile phone via WiFi.

CategoriesLed Raspberry Pi Pico Uncategorized

#24 Maze Navigating Robot Project with PicoBricks

Coding education is as old as the history of programming languages. Today, different products are used to popularize coding education and make it exciting and fun. The first of these is educational robots. Preparing and programming robots improves children’s engineering and coding skills. Robotics competitions are organized by institutions and organizations to popularize coding education and encourage teachers and students. One of these competitions is the Maze Solver Robot competitions. These robots learn how to solve the maze by wandering around in the maze and returning to the starting point. Then, when they start the labyrinth again, they try to reach their destination in the shortest way possible. Robots use infrared or ultrasonic distance sensors while learning the maze.

Smart robot vacuums used in homes and workplaces also work with logic close to the algorithms of maze-solver robots. Thanks to their algorithms that constantly check and map the obstacles, they try to complete their tasks without crashing into things. Most of the smart vacuums are equipped with LIDAR and infrared sensors that are designed for  high-precision laser measurements and obstacle detection.

In this project, we will make a simple robot that you can use to navigate your own maze.

Details and Algorithm

In this project, we will use the 2WD robot car kit that comes with the set. We will use the HC-SR04 ultrasonic distance sensor so that the robot can detect the walls in front of it and decide its movements. In the maze, the robot will scan the space in front of the car and move forward if it is empty. If there is a wall (obstacle) within 5 cm’s, the car will turn right and measure the distance again. If the new distance on the right is greater than 5 cm, it will continue on its way. If it is less, it will turn left and move forward. By turning right and left, we will guide the vehicle to make progress and exit the maze.

Components

1X PicoBricks
1X HC-SR04 Ultrasonic Sensor
2X DC Motor
Jumper Cables
Easy Connection 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

You can build the robot car by following the steps for the 2WD robot car assembly in the voice-controlled car project.

We will not use the HC05 bluetooth module in this project.

In order to mount the HC-SR04 ultrasonic distance sensor on the robot, you can download the required parts from the link here and print it on the 3D printer and mount it on the vehicle.

After assembling the robot, you can use cardboard boxes to build the maze. You can make walls out of cardboard, or you can use 3D printed walls to connect the walls with hot glue to build the maze.

MicroBlocks Codes of the PicoBricks

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 utime import sleep
import utime
#define libraries

trigger = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)
#define sensor pins

m1 = Pin(21, Pin.OUT)
m2 = Pin(22, Pin.OUT)
#define dc motor pins

m1.low()
m2.low()
signaloff = 0
signalon = 0

def getDistance():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.low()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   return distance
#calculate distance

measure=0
while True:
    
    measure=int(getDistance())
    print(measure)
    if measure>5:
        m1.high()
        m2.high()
        sleep(1) #if the distance is higher than 5, the wheels go straight
    else:
        m1.low()
        m2.low()
        sleep(0.5)
        m1.high()
        m2.low()
        sleep(0.5)
        measure=int(getDistance())
        if measure<5:
            m1.low()
        m2.low()
        sleep(0.5)
        m1.low()
        m2.high()
        sleep(0.5)
        #If the distance is less than 5, wait, move in any direction; if the distance is less than 5, move in the opposite direction
				
			

Arduino C Codes of the PicoBricks

				
					#include <NewPing.h>

#define TRIGGER_PIN  15
#define ECHO_PIN     14
#define MAX_DISTANCE 400
//define sensor pins

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  pinMode(21,OUTPUT);
  pinMode(22,OUTPUT); //define dc motor pins
}

void loop() {
  
  delay(50);
  int distance=sonar.ping_cm();
  Forward();

  if(distance<5){

    Stop();
    delay(1000);
    Turn_Right();
    delay(1000);
    int distance=sonar.ping_cm();

    if(distance<5){
      Stop();
      delay(1000);
      Turn_Left();
      delay(500);
      // If the distance is less than 5, wait, turn right; if the distance is less than 5 again, move in the opposite direction
    }
  }
}

void Forward(){
  digitalWrite(21,HIGH);
  digitalWrite(22,HIGH); //if the distance is higher than 5, go straight
}
void Turn_Left(){
  digitalWrite(21,LOW);
  digitalWrite(22,HIGH); //turn left
}
void Turn_Right(){
  digitalWrite(21,HIGH);
  digitalWrite(22,LOW);  //turn right
}
void Stop(){
  digitalWrite(21,LOW);
  digitalWrite(22,LOW); //wait
}
				
			

Project Image

Project Proposal 💡

We used a HC-SR04 ultrasonic distance sensor, mounted to the front of the car, to navigate the maze. The algorithm used is very simple and relies on timed movements to navigate. You can enhance the code to use shorter timed movements and combine them with more sensor readings. Turns can be coded in a different way using this method, similar to the straight moves.

By using a servo motor, you can rotate the HC-SR04 module to the right and left, and detect the open paths without the vehicle turning. It will make the car progress faster. Or, you can develop the project by mounting 3 HC-SR04 ultrasonic distance sensors on the front, right and left side of the vehicle, measuring the distances in 3 directions at the same time and directing the vehicle towards the open paths.

CategoriesLed Raspberry Pi Pico Uncategorized

#23 Air Piano Project with PicoBricks

With the development of electronic technology, musical instruments that are difficult to produce, expensive and producing high-quality sound have been digitized. Pianos are one of these instruments. Each key of digital pianos produces electrical signals at a different frequency. Thus, it can play 88 different notes from its speakers. Factors such as the delay time of the keys of digital instruments, the quality of the speaker, the resolution of the sound have appeared as the factors affecting the quality. In electric guitars, vibrations in strings are digitized instead of keys. On the other hand, In wind instruments, the notes played can be converted into electrical signals and recorded thanks to the high-resolution microphones plugged into the sound output. This development in electronic technology has facilitated access to high-cost musical instruments, music education has gained a wider variety and spread to a wider audience.

In this project we will make a simple piano that can play 7 notes with PicoBricks. The speaker of this piano will be the buzzer. The ultrasonic sensor will act as the keys of the piano.

Details and Algorithm

In this project, we will make a piano application using the HC-SR04 Ultrasonic distance sensor and the buzzer module on PicoBricks. We will make the buzzer play different notes according to the values ​​coming from the distance sensor, and we will create melodies by moving our hand closer to the sensor and away from it. In addition, we will instantly print the distance and played note information on the OLED screen.

Components

1X PicoBricks
1X HC-SR04 Ultrasonic Sensor
Jumper Cables
Easy Connection 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

MicroBlocks Codes of the PicoBricks

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, I2C
from utime import sleep
import utime       
from picobricks import SSD1306_I2C  
import _thread
#define the libraries

buzzer=PWM(Pin(20,Pin.OUT))
trigger = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)
#define the input and Output pins

WIDTH  = 128                                            
HEIGHT = 64
#OLED screen settings

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

oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)

measure=0

def getDistance():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.low()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   return distance
#calculate distance

def airPiano():
    while True:
        global measure
        
        if measure>5 and measure<11:
            buzzer.duty_u16(4000)
            buzzer.freq(262)
            sleep(0.4)
           
        elif measure>10 and measure<16:
            buzzer.duty_u16(4000)
            buzzer.freq(294)
            sleep(0.4)
            
        elif measure>15 and measure<21:
            buzzer.duty_u16(4000)
            buzzer.freq(330)
            sleep(0.4)
            
        elif measure>20 and measure<26:
            buzzer.duty_u16(4000)
            buzzer.freq(349)
            sleep(0.4)
            
        elif measure>25 and measure<31:
            buzzer.duty_u16(4000)
            buzzer.freq(392)
            sleep(0.4)
            
        elif measure>30 and measure<36:
            buzzer.duty_u16(4000)
            buzzer.freq(440)
            sleep(0.4)
            
        elif measure>35 and measure<41:
            buzzer.duty_u16(4000)
            buzzer.freq(494)
            sleep(0.4)
        else:
            buzzer.duty_u16(0)

_thread.start_new_thread(airPiano, ())
#play the tone determined by the value of the distance sensor

while True:
    measure=int(getDistance())
    oled.text("Distance " + str(measure)+ " cm", 5,30)
    oled.show()
    sleep(0.01)
    oled.fill(0)
    oled.show()
#write the specified texts to the determined x and ye coordinates on the OLED screen
				
			

Arduino C Codes of the PicoBricks

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

#define TRIGGER_PIN  15
#define ECHO_PIN     14
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

#define T_C 262
#define T_D 294
#define T_E 330
#define T_F 349
#define T_G 392
#define T_A 440
#define T_B 493

const int Buzzer = 20;

void setup() {
  pinMode(Buzzer,OUTPUT);

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

#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
}

void loop() {

  delay(50);
  int distance=sonar.ping_cm();

  if(distance>5 & distance<11)
  {
    tone(Buzzer,T_C);
  }

  else if(distance>10 & distance<16)
  {
    tone(Buzzer,T_D);
  }

  else if(distance>15 & distance<21)
  {
    tone(Buzzer,T_E);
  }

  else if(distance>20 & distance<26)
  {
    tone(Buzzer,T_F);
  }

  else if(distance>25 & distance<31)
  {
    tone(Buzzer,T_G);
  }

  else if(distance>30 & distance<36)
  {
    tone(Buzzer,T_A);
  }

  else if(distance>35 & distance<41)
  {
    tone(Buzzer,T_B);
  }

  else 
  {
    noTone(Buzzer);
  }

  oled.clearDisplay();
  oled.setTextXY(2,4);              
  oled.putString("Distance: ");
  oled.setTextXY(4,6);              
  String string_distance=String(distance);
  oled.putString(string_distance);
  oled.setTextXY(4,8);              
  oled.putString("cm");
}
				
			

Project Image

Project Proposal 💡

There is one instant button on PicoBricks. By connecting 7 buttons to Pico, you can make different notes play when each key is pressed, you can use buttons for octave value and beat times, and you can develop your piano project.

CategoriesLed Raspberry Pi Pico Uncategorized

#22 Digital Ruler Project with PicoBricks

Many tools are used to measure length. One of the first that comes to mind is rulers.Our measuring instrument differs according to the place and size to measure. Tape measures are used in construction and architecture, and calipers are used for small objects that require millimeter precision. In addition, if it is desired to measure an area that needs both large and precise measurement, distance meters working with laser and infrared systems are used. Ultrasonography devices used in the health sector also work with the same logic, but convert their measurements into visuals.

In our project, we will use PicoBricks and an ultrasonic sensor to prepare a digital ruler that will display the distance value on the OLED screen when the button is pressed. Ultrasonic sensors detect distance according to the return times of the sound waves they emit.

Details and Algorithm

When the program starts, instructions are displayed on the OLED screen. After the user presses the button, a measurement is taken. The red LED stays on during the measurement, and then turns off. The measured value is added to the distance from the tip of the sensor to the back of the box. The final calculated value is displayed on the OLED display.

Components

1X PicoBricks
1X HC-SR04 Ultrasonic Sensor
Jumper Cables
Easy Connection 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

To prepare the project, you need double-sided foam tape, a utility knife, a waste cardboard box of approximately 15x10x5 cm.

1) Cut the holes for the ultrasonic sensor, OLED screen, button LED module, buzzer, battery box to pass the cables with a utility knife.

2) Hang all the cables inside the box and attach the back of the modules to the box with double-sided foam tape. Connect the trig pin of the ultrasonic sensor to the GPIO14 pin and the echo pin to the GPIO15 pin. You should connect the VCC pin to the VBUS pin on the Picoboard.

3) After completing the cable connections of all modules, you can insert the 2-battery box into the power jack of the Picoboard and turn on the switch. That’s it for the digital ruler project!

MicroBlocks Codes of the PicoBricks

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, I2C
from utime import sleep
from picobricks import SSD1306_I2C
import utime
#define the libraries
redLed=Pin(7,Pin.OUT)
button=Pin(10,Pin.IN,Pin.PULL_DOWN)
buzzer=PWM(Pin(20,Pin.OUT))
buzzer.freq(392)
trigger = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)
#define input and output pins
WIDTH  = 128                                            
HEIGHT = 64                                       
#OLED screen settings
sda=machine.Pin(4)
scl=machine.Pin(5)
i2c=machine.I2C(0,sda=sda, scl=scl, freq=1000000)
#initialize digital pin 4 and 5 as an OUTPUT for OLED communication
oled = SSD1306_I2C(128, 64, i2c)
measure=0
finalDistance=0

def getDistance():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.low()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   return distance
#calculate the distance
def getMeasure(pin):
    global measure
    global finalDistance
    redLed.value(1)
    for i in range(20):
        measure += getDistance()
        sleep(0.05)
    redLed.value(0)
    finalDistance = (measure/20) + 1
    oled.fill(0)
    oled.show()
    oled.text(">Digital Ruller<", 2,5)
    oled.text("Distance " + str(round(finalDistance)) +" cm", 0, 32)
    oled.show()
#print the specified distance to the specified x and y coordinates on the OLED screen
    print(finalDistance)
    buzzer.duty_u16(4000)
    sleep(0.05)
    buzzer.duty_u16(0)
    measure=0
    finalDistance=0
 #sound the buzzer  
button.irq(trigger=machine.Pin.IRQ_RISING, handler=getMeasure)
				
			

Arduino C Codes of the PicoBricks

				
					#include <Wire.h>
#include "ACROBOTIC_SSD1306.h"
#include <NewPing.h>
// define the libraries
#define TRIGGER_PIN  15
#define ECHO_PIN     14
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

#define T_B 493

int distance = 0;
int total = 0;

void setup() {
  pinMode(7,OUTPUT);
  pinMode(20,OUTPUT);
  pinMode(10,INPUT); 
  // define input and output pins
  Wire.begin();  
  oled.init();                      
  oled.clearDisplay(); 


}

void loop() {

  delay(50);
  if(digitalRead(10) == 1){

    int measure=0;
    digitalWrite(7,HIGH);
    tone(20,T_B);
    delay(500);
    noTone(20);

    for (int i=0;i<20;i++){

      measure=sonar.ping_cm();
      total=total+measure;
      delay(50);      
    }

    distance = total/20+6; // calculate the distance
    digitalWrite(7,LOW);

    delay(1000);
    oled.clearDisplay();
    oled.setTextXY(2,1);              
    oled.putString(">Digital Ruler<");
    oled.setTextXY(5,1);              
    oled.putString("Distance: ");
    oled.setTextXY(5,10);              
    String string_distance=String(distance);
    oled.putString(string_distance);
    oled.setTextXY(5,12);              
    oled.putString("cm"); // print the calculated distance on the OLED screen

    measure=0;
    distance=0;
    total=0;
  }
}
				
			

Project Image

Project Proposal 💡

You can turn the digital ruler into a height meter by fixing it to the wall or ceiling. Since the height meter will be fixed on the wall or ceiling, it will not be possible to measure by pressing the button. For this, you can add the HC05 bluetooth module to the project and have it measure when a command is received from the mobile application.

CategoriesLed Raspberry Pi Pico Uncategorized

#21 Automatic Trash Bin Project with PicoBricks

The Covid 19 pandemic has changed people’s daily routines. In many areas, such as cleaning, working, shopping and social life, people were introduced to a series of new rules that they had to comply with. Covid-19 has LED to the development of new business areas as well as some products that stand out. At a time when hand hygiene was very important, no one wanted to touch the lid of the trash cans to throw away their garbage.

Trash bins that open automatically when approached, and when full, make bags ready to be thrown away, found buyers at prices far above their cost. In addition, automatic disinfectant machines provided contactless hygiene by pouring a certain amount of liquid into our palms when we held our hands under them. Automatic disinfectant machines took place on the shelves at prices well above their cost. These two products have similarities in terms of their working principles. In automatic disinfectant machines, a pump with an electric motor or a servo motor, dispenses the liquid. In automatic trash bins, a servo motor that opens the lid was used, and infrared or ultrasonic sensors were used to detect hand movement. 

In this project, you will make an automatic stylish trash bin for your room using an ultrasonic sensor and servo motor with PicoBricks.

Details and Algorithm

HC-SR04 ultrasonic distance sensor and SG90 servo motor will be used in this project. When the user puts his hand in front of the lid of the trash can, the distance sensor will detect the proximity and notify  the program. Your program will then open the lid of the garbage can by running a servo motor and will close it again after a short while.

Components

1X PicoBricks
1X HC-SR04 Ultrasonic Sensor
1X Servo Motor
Jumper Cables
Easy Connection 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

You can download the 3D drawing files of the project from this link and get 3D printing.

1: Fix it by screwing it to the trash bin cover of the servo motor apparatus.

2: Fix the ultrasonic distance sensor on the lid of the trash bin with the hot glue.

3: Pass the cables of the ultrasonic distance sensor through the hole in the box and connect them to the pins shown in the PicoBricks circuit diagram, make the servo motor and motor driver connections.

4: Fix the servo motor, PicoBricks and motor driver parts to the box with hot glue.

If everything went well, when you put your hand close to the garbage can, the lid of the bucket will open and it will close again after you throw the garbage away.

MicroBlocks Codes of the PicoBricks

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
from utime import sleep

servo=PWM(Pin(21,Pin.OUT))
trigger = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)

servo.freq(50)
servo.duty_u16(1920) #15 degree

def getDistance():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.low()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   print("The distance from object is ",distance,"cm")
   return distance

while True:
    sleep(0.01)
    if int(getDistance())<=10:
        servo.duty_u16(4010) #70 degree
        utime.sleep(0.3)
        servo.duty_u16(1920)
				
			

Arduino C Codes of the PicoBricks

				
					#include <Servo.h>
#define trigPin 14
#define echoPin 15
Servo servo;
void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  servo.attach(21);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1; 
  if (distance < 80) {
    Serial.print(distance);
    Serial.println(" cm");
    servo.write(179);
  }

  else if (distance<180) {
    Serial.print(distance);
    Serial.println(" cm");
    servo.write(100); 
  }
  

}
				
			

Project Image

Project Proposal 💡

As in this project, where we automate a trash can in our house using sensors and motors, you can have a drawer or a cabinet door open automatically with the help of sensors and motors.

CategoriesLed Raspberry Pi Pico Uncategorized

#20 Secured Entrance Project with PicoBricks

Security systems include technologies that can control access at building and room entrances. Card entry systems, in which only authorized personnel can enter the operating rooms of hospitals, are one of the first examples that come to mind. In addition, many entrance areas are equipped with card and password entry technologies. These electronic systems not only prevent the entrance of unauthorized persons, but also ensure that entry and exit information is recorded. Password entry, card entry, fingerprint scanning, face scanning, retina scanning and voice recognition technologies are the authentication methods used in electronic entry systems.

Systems such as RFID and NFC are the basic forms of contactless payment technologies today. Although the contactless payment technology used with credit cards is technically different, the working logic is the same. The maximum distance between the reader and the card is one of the features that distinguishes the technologies from each other. When leaving the shopping stores, especially clothing stores, NFC tags on the products will beep if they are detected by the readers at the entrance. A kind of RFID technology is used in those systems.

In this project, we will prepare a card entry system on a model house. The electronic components we will use are MFRC522 RFID reader and 13.56 Mhz cards.

Details and Algorithm

Place the MFRC522 reader near the door of the model so that it is visible from the outside. Place the RGB LED and the buzzer on the wall where the door is visible from the outside. Picoboard can remain in the model. The entrance door of the model should be connected to the door of the servo, while the servo is set to 0 degrees, the door should be closed. You should determine the serial number of the RFID / NFC tag that will open the door, create the homeowner variable and assign the serial number to this variable.

Set the door to the closed position when the program starts. Make the buzzer beep when a card is shown to the RFID reader. If the serial number of the card being read matches the serial number in the homeowner variable, turn the RGB LED on green. Then let the door open. Make sure the door is closed 3 seconds after the door is opened. If the serial number of the card being read does not match the homeowner variable, turn the RGB LED on red and play a different tone from the buzzer.

Components

1X PicoBricks
1X Servo Motor
1X RC522-RFID Card
Jumper Cables
Easy Connection 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

We will make the project on the house model you used in the Smart Home project number 18.

Click for Smart Home project

Drill holes for the RGB LED, Buzzer and RC522 RFID reader on the house model.

Attach double-sided foam tape on the back of the RGB LED and Buzzer and attach it on the box. Place the RC522 inside the model as in the image.

Attach the servo motor to the inside of the model with double-sided tape as a hinge in the upper left corner of the door. Attach the servo head to the door with hot glue or liquid glue.

Finally, place the Pico board and the 2-key battery box inside the model house and complete the cable connections. After making the final checks of your project, it is ready to work.

MicroBlocks Codes of the PicoBricks

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

The code to be run to learn the Card ID:

				
					from machine import Pin, SPI
from mfrc522 import MFRC522
import utime
#define libraries
sck = Pin(18, Pin.OUT)
mosi = Pin(19, Pin.OUT)
miso = Pin(16, Pin.OUT)
sda = Pin(17, Pin.OUT)
rst = Pin(15, Pin.OUT)
spi = SPI(0, baudrate=100000, polarity=0, phase=0, sck=sck, mosi=mosi, miso=miso)
rdr = MFRC522(spi, sda, rst)
#define MFRC522 pins

while True:
    (stat, tag_type) = rdr.request(rdr.REQIDL)
    if stat == rdr.OK:
        (stat, raw_uid) = rdr.anticoll()
        if stat == rdr.OK:
            uid = ("0x%02x%02x%02x%02x" % (raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3]))
            print(uid)
            utime.sleep(1)
            #read the card and give the serial number of the card
				
			

Project code:

				
					from machine import I2C, Pin, SPI, PWM
from mfrc522 import MFRC522
from ws2812 import NeoPixel
from utime import sleep 

servo = PWM(Pin(21))
servo.freq(50)
servo.duty_u16(1350) #servo set 0 angle 8200 for 180.

buzzer = PWM(Pin(20, Pin.OUT))
buzzer.freq(440)

neo = NeoPixel(6, n=1, brightness=0.3, autowrite=False)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)

sck = Pin(18, Pin.OUT)
mosi = Pin(19, Pin.OUT)
miso = Pin(16, Pin.OUT)
sda = Pin(17, Pin.OUT)
rst = Pin(15, Pin.OUT)
spi = SPI(0, baudrate=100000, polarity=0, phase=0, sck=sck, mosi=mosi, miso=miso)
homeowner = "0x734762a3"
rdr = MFRC522(spi, sda, rst)

while True:
    
    (stat, tag_type) = rdr.request(rdr.REQIDL)
    if stat == rdr.OK:
        (stat, raw_uid) = rdr.anticoll()
        if stat == rdr.OK:
            buzzer.duty_u16(3000)
            sleep(0.05)
            buzzer.duty_u16(0)
            uid = ("0x%02x%02x%02x%02x" % (raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3]))
            print(uid)
            sleep(1)
            if (uid==homeowner):
                neo.fill(GREEN)
                neo.show()
                servo.duty_u16(6000)
                sleep(3)
                servo.duty_u16(1350)
                neo.fill(BLACK)
                neo.show()
               
            else:
                neo.fill(RED)
                neo.show()
                sleep(3)
                neo.fill(BLACK)
                neo.show()
                servo.duty_u16(1350)
				
			

Arduino C Codes of the PicoBricks

The code to be run to learn the Card ID:

				
					#include <SPI.h>
#include <MFRC522.h>
//define libraries

int RST_PIN = 26;
int SS_PIN = 17;
//define pins

MFRC522 rfid(SS_PIN, RST_PIN);

void setup()
{
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
}

void loop() {

  if (!rfid.PICC_IsNewCardPresent())
    return;
  if (!rfid.PICC_ReadCardSerial())
    return;
    rfid.uid.uidByte[0] ;
    rfid.uid.uidByte[1] ;
    rfid.uid.uidByte[2] ;
    rfid.uid.uidByte[3] ; 
    printid();
  rfid.PICC_HaltA();
//Reading your ID.
}
void printid() 
{
  Serial.print("Your ID: ");
  for (int x = 0; x < 4; x++) {
    Serial.print(rfid.uid.uidByte[x]);
    Serial.print(" ");
  }
  Serial.println("");
}
				
			

Project code:

				
					#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <Adafruit_NeoPixel.h>
//Define libraries.


#define RST_PIN    26
#define SS_PIN     17
#define servoPin   22
#define PIN        6 
#define NUMPIXELS  1
#define buzzer     20
//define pins of servo,buzzer,neopixel and rfid.

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
Servo motor;
MFRC522 rfid(SS_PIN, RST_PIN);

byte ID[4] = {"Write your own ID."};

void setup() { 
  pixels.begin();
  motor.attach(servoPin);
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
  pinMode(buzzer, OUTPUT);
  
}
 
void loop()
{
  pixels.clear();
  
  if ( ! rfid.PICC_IsNewCardPresent())
    return;
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  if 
  (
    rfid.uid.uidByte[0] == ID[0] &&
    rfid.uid.uidByte[1] == ID[1] &&
    rfid.uid.uidByte[2] == ID[2] &&
    rfid.uid.uidByte[3] == ID[3] ) 
  {
        Serial.println("Door Opened.");
        printid();
        tone(buzzer,523);
        delay(200);
        noTone(buzzer);
        delay(100);
        tone(buzzer,523);
        delay(200);
        noTone(buzzer);
        pixels.setPixelColor(0, pixels.Color(0, 250, 0));
        delay(200);
        pixels.show();
        pixels.setPixelColor(0, pixels.Color(0, 0, 0));
        delay(200);
        pixels.show();
        motor.write(180);
        delay(2000);
        motor.write(0);
        delay(1000);
     //RGB LED turns green and the door opens thanks to the servo motor if the correct card is read to the sensor.
    }
    else
    {
      Serial.println("Unknown Card.");
      printid();
      tone(buzzer,494);
      delay(200);
      noTone(buzzer);
      delay(100);
      tone(buzzer,494);
      delay(200);
      noTone(buzzer);
      pixels.setPixelColor(0, pixels.Color(250, 0, 0));
      delay(100);
      pixels.show();
      pixels.setPixelColor(0, pixels.Color(0, 0, 0));
      delay(100);
      pixels.show();
      //RGB LED turns red and the door does not open if the wrong card is read to the sensor
    }
  rfid.PICC_HaltA();
}
void printid()
{
  Serial.print("ID Number: ");
  for(int x = 0; x < 4; x++){
    Serial.print(rfid.uid.uidByte[x]);
    Serial.print(" ");
  }
  Serial.println("");
}
				
			

Project Proposal 💡

You can assign personal names to RFID cards and add an OLED screen to the project. When the card is read, you can print the name of the person to whom the card belongs, on the OLED screen.

CategoriesLed Raspberry Pi Pico Uncategorized

#19 Hungry Piggy Bank Project with PicoBricks

Ultrasonic sensors send out sound waves at a frequency that our ears cannot detect and produce distance information by calculating the return time of the reflected sound waves. We, the programmers, develop projects by making sense of the measured distance and the changes in distance. Parking sensors in the front and back of the cars are the places where ultrasonic sensors are most common in daily life. Do you know the creature that finds its way in nature with this method? Because bats are blind, they find their way through the reflections of the sounds they make.

Many of us like to save money. It is a very nice feeling that the money we save little by little is useful when needed. In this project, you will make yourself a very enjoyable and cute piggy bank. You will use the servo motor and ultrasonic distance sensor while making the piggy bank.

Details and Algorithm

HC-SR04 ultrasonic distance sensor and SG90 servo motor will be used in this project. As the user places money in the hopper of the piggy bank, the distance sensor will detect the proximity and signal PicoBricks. PicoBricks will operate the servo motor and raise the arm, drop the money into the piggy bank, and then the arm will go down again.

Components

1X PicoBricks
1X HC-SR04 Ultrasonic Sensor
1X Servo Motor
Jumper Cables
Easy Connection 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

You can access the original files and construction stages of the project by clicking here. Unlike the project in this link, we will use the HC-SR04 ultrasonic distance sensor. You can download the updated 3D drawing files according to the HC-SR04 ultrasonic distance sensor from this link and get 3D printing.

1: Fix the plastic apparatus of the servo motor to the piggy bank arm with 2 screws.

2: Fix the second part of the piggy bank arm with the M3 screw and nut to the first part where the hopper is.

3: Pass the servo motor cable and place it in its slot.

4: Place the servo motor and its housing on the body of the piggy bank. You can use hot glue here.

5: Place the ultrasonic distance sensor in the piggy bank body and fix it with hot glue.

6: Attach the piggy bank arm to the servo motor and fix it to the top cover with M3 screws.

7: Fix the piggy bank arm to the body with M2 screw.

8: Plug the cables of the servo motor and ultrasonic distance sensor and connect the power cables.

9: According to the circuit diagram, connect the cables of the servo motor and ultrasonic distance sensor to the pico.

10: Plug Pico’s USB cable and reassemble the cables and attach the bottom cover. That is all.

MicroBlocks Codes of the PicoBricks

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
import utime
#define the libraries

servo=PWM(Pin(21,Pin.OUT))
trigger = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)
#define the input and output pins

servo.freq(50)
servo.duty_u16(6750)

def getDistance():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.low()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   print("The distance from object is ",distance,"cm")
   return distance
#calculate distance
while True:
    utime.sleep(0.01)
    if int(getDistance())<=5:  #if the distance variable is less than 5
        servo.duty_u16(4010) 
        utime.sleep(0.3)  #wait
        servo.duty_u16(6750)  
				
			

Arduino C Codes of the PicoBricks

				
					#include <Servo.h>
#define trigPin 15
#define echoPin 14
//define the libraries
Servo servo;
void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  //define the input and output pins
  servo.attach(21); //define the servo pin
}
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  //calculate distance
  if (distance < 5) {    //if the distance variable is less than 5
    Serial.print(distance);
    Serial.println(" cm");
    servo.write(179);
  }
  else if (distance>5) {   // if the distance variable is greater than 5
    Serial.print(distance);
    Serial.println(" cm");
    servo.write(100);
  }
}
				
			

Project Image

Project Proposal 💡

By adding an RGB LED module to the project, you can turn on the light in any color you want for each coin drop. By using the buzzer, a sound can be emitted every time a coin is dropped. You can also print the number of coin drops on the OLED screen.

smart-house-headerCategoriesRaspberry Pi Pico Uncategorized

#18 Smart House Project with PicoBricks

Workplaces, factories, homes and even animal shelters… There are different electronic systems that can be used to protect our living spaces against intruders. These systems are produced and marketed as home and workplace security systems. There are systems where the images produced by security cameras are processed and interpreted, as well as security systems that detect the human body and its movements with sensors and take action. Security systems are set up like a kind of alarm clock and give audible and visual warnings when an unidentified activity is detected in the specified zone. It notifies the business or the homeowner, and it can also make automatic notifications to the security companies.

 In cases of gas leakage, fire etc., gas sensors are used in homes and workplaces to prevent poisoning. In a problem situation, people living in the environment are alerted by a loud alarm.

We will prepare a model smart home project with PicoBricks using the HC-SR501 and MQ-2 gas sensor. This sensor HC-SR501, is also known as PIR sensor. Passive infrared (PIR) sensors use a pair of pyroelectric sensors to detect heat energy in the surrounding environment. These two sensors sit beside each other, and when the signal differential between the two sensors changes (if a person enters the room, for example), the sensor will engage.

Details and Algorithm

When the HC-SR501 PIR sensor detects motion, it gives digital output for 3 seconds. We will use a Picoboard, buzzer and button LED module in the project. All parts must be in the model.

When the program starts, the button must be pressed to activate the alarm system. After pressing the button, we must wait 3 seconds to allow for the hand to be pulled out of the model. At the end of 3 seconds, the red LED lights up and the alarm system is activated. When the alarm system detects a movement, the red LED will start to flash and the buzzer will sound the alarm. To mute it, PicoBricks must be restarted.

The MQ-2 sensor is always on. When it detects a toxic gas, it will notify you with a buzzer and flashing red LED.

Components

1X PicoBricks
1X HC-SR501 PIR sensor
1X MQ-2 Gas sensor
1X Mini breadboard
Jumper Cables
Easy Connection 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

To run the project, you have to turn a cardboard box into a model house. You will need scissors, pencils, tape, glue, and a utility knife. Draw windows and doors on the box with a pencil. Cut the door section with a utility knife.

You can use another cardboard to make the roof part.

Attach double-sided foam tape under the PicoBricks pieces.

Place pieces of PicoBricks inside the model house. Position the PIR sensor to see the door directly from the inside. attach the button module just above the door from the inside.

When you connect the battery case to Picoboard and turn it on, the code will start to run. 3 seconds after pressing the button, the alarm system will be activated and the red LED will turn on. As soon as you put your hand in the door, the buzzer will start to sound.

When you hold the lighter gas inside the house, the alarm system is expected to be activated again.

MicroBlocks Codes of the PicoBricks

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
from utime import sleep
# define libraries
PIR=Pin(14, Pin.IN)
MQ2=Pin(1,Pin.IN)
buzzer=PWM(Pin(20,Pin.OUT))
redLed=Pin(7,Pin.OUT)
button=Pin(10,Pin.IN,Pin.PULL_DOWN)
# define output and input pins

activated=0
gas=0

while True:
    if button.value()==1:
        activated=1
        gas=0 
        sleep(3)
        redLed.value(1)
        buzzer.duty_u16(0)
    if MQ2.value()==1:
        gas=1
    if activated==1:
        if PIR.value()==1:
            buzzer.duty_u16(6000)
            buzzer.freq(440)
            sleep(0.2)
            buzzer.freq(330)
            sleep(0.1)
            buzzer.freq(494)
            sleep(0.15)
            buzzer.freq(523)
            sleep(0.3)
    if gas==1:
        buzzer.duty_u16(6000)
        buzzer.freq(330)
        sleep(0.5)
        redLed.value(1)
        buzzer.freq(523)
        sleep(0.5)
        redLed.value(0)
        # LED will light and buzzer will sound when PIR detects motion or MQ2 detects toxic gas
				
			

Arduino C Codes of the PicoBricks

				
					void actived (){
  digitalWrite(7,1);
  while(!(digitalRead(14) == 1))
  {
    _loop();
  }
  motion_detected();
}

void motion_detected (){
  while(1) {
      // buzzer settings 
      tone(20,262,0.25*1000);
      delay(0.25*1000);
      tone(20,330,0.25*1000);
      delay(0.25*1000);
      tone(20,262,0.25*1000);
      delay(0.25*1000);
      tone(20,349,0.25*1000);
      delay(0.25*1000);
// sound the buzzer when PIR detected a motion 
      _loop();
  }
}

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

void _loop() {
}

void loop() {
  _loop();
}

void setup() {
  
  pinMode(10,INPUT);
  pinMode(1,INPUT);
  pinMode(20,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(14,INPUT);
  // define input and output pins
  
  while(1) {
      if(digitalRead(10) == 1){
          _delay(3);
          actived();
      }
      if(digitalRead(1) == 1){
          while(!(digitalRead(10) == 1))
          {
            _loop();
            tone(20,349,0.5*1000);
            delay(0.5*1000);
            digitalWrite(7,1);
            _delay(0.5);
            tone(20,392,0.5*1000);
            delay(0.5*1000);
            digitalWrite(7,0);
            _delay(0.5);
          }
      }
      _loop();
  }
}
				
			

Project Image

Project Proposal 💡

You can install fire extinguishing pipes on the ceiling of the house with a submersible pump, so that when there is a fire in the house, you can automatically extinguish it.

After completing the #25 Smart Greenhouse project, you will learn how to use the ESP01 WIFI module. Afterwards, you can enhance this project with the ESP01 as an IOT project, and send a notification to the home owner’s phone when any of the alarms are triggered. However, this would be a very complicated enhancement and will require research into a few more additional topics like MQTT etc to complete successfully.

two-axis-robot-arm-headerCategoriesRaspberry Pi Pico Uncategorized

#17 Two Axis Robot Arm Project with PicoBricks

Robot arms have replaced human power in the industrial field. In factories, robotic arms undertake the tasks of carrying and turning loads of weights and sizes that cannot be carried by a human. Being able to be positioned with a precision of one thousandth of a millimeter is above the sensitivity that a human hand can exhibit. When you watch the production videos of automobile factories, you will see how vital the robot arms are. The reason why they are called robots is that they can be programmed to do the same work with endless repetitions. The reason why it is called an arm is because it has an articulated structure like our arms. How many different directions a robot arm can rotate and move is expressed as axes. Robot arms are also used for carving and shaping aluminum and various metals. These devices, which are referred to as 7-axis CNC Routers, can shape metals like a sculptor shapes mud.

Depending on the robot arm’s purpose, stepper motors and servo motors can be  used. PicoBricks allows you to make projects with servo motors. 

Details and Algorithm

When an object is detected on the LDR sensor, RGB LED will turn RED and the robot arm will execute the following maneuvers:

  • open the gripper
  • move downwards
  • close the gripper
  • move upwards

At the completion of the arm movement, the RGB LED will turn  GREEN.

Based on these motions, the initial positions of the two servos should be as such:

  • Servo1 controlling gripper should be in CLOSED position
  • Servo 2 controlling up/down movement should be in UP position

Four different motion control logic is needed:

  • UP: execute a 90 degree movement in 2 degree increments
  • DOWN: execute a 90 degree movement in -2 degree increments
  • OPEN: position gripper to 90 degrees
  • CLOSE: position gripper to -60 degrees

All movements will be accompanied by sound feedback and displayed on the IDE for troubleshooting purposes. Later you can remove the say blocks, if desired.

Servo motor movements are very fast. In order to slow down the movement, we will move the servo motors 2 degrees at a time at 30 millisecond intervals, to complete a 90 degree motion. We’re not going to do this for the gripper to close.

3D Print and assemble the necessary parts for the Gripper from the link here.

Components

1X PicoBricks
2X Servo Motor
4X Easy connection Cables
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

Prepare the parts of the Pan-Tilt kit to prepare the project. Carry your 3D printed parts, waste cardboard pieces, hot silicone glue and scissors with you.

1) First of all, we will prepare the fixed arm of the robot arm. Make an 8 cm high cardboard cylinder into the rounded part of part D. Place it on the D part and attach or glue it with silicone.

2) Place the head that came out of the servo motor package on the C part by shortening it a little. Fix with the smallest screws from the Pan Tilt kit.

3) Fix parts A and C together with 2 pointed screws.

4) Internally attach the servo motor to part C. Then place the servo motor on part B and screw it.

5) For the holder, cut one of the servo motor heads in the middle of the gear part that you printed on the 3D printer and place it into the gear. Then screw it to the servo motor.

6) Adhere together the 3D printed Linear gear and the handle with strong adhesive.

7) Place the servo in the 3D print holder and fix it. You can do this with hot silicone or by screwing. When placing the servo gear on the linear gear, make sure it is fully open.

8) Attach the holding servo system to part B with silicone.

9) Pass the piece we prepared in step 3 over the cylinder we prepared from cardboard in the first step and fix it with silicone.

10) Put the motor drive jumpers on the Servo pins. Connect the cable of the holding servo to the GPIO21 and the cable of the tilting servo to the GPIO22.

11) Place the motor driver, buzzer, LDR and RGB LED module on a platform and place the robot arm on the platform accordingly. With the 3D Pen printer, you can customize your project as you wish.

12) You can operate the Robot arm if you feed PicoBricks with USB or 3 pen batteries from the power jack on the Picoboard.

MicroBlocks Codes of the PicoBricks

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

Robot Arm Code:

				
					from machine import Pin, PWM, ADC
from utime import sleep
from picobricks import WS2812
#define libraries

ws = WS2812(6, brightness=0.3)
ldr=ADC(27)
buzzer=PWM(Pin(20, Pin.OUT))
servo1=PWM(Pin(21))
servo2=PWM(Pin(22))
# define LDR, buzzer and servo motors pins

servo1.freq(50)
servo2.freq(50)
buzzer.freq(440)
# define frequencies of servo motors and buzzer

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0) # RGB color settings
angleupdown=4770
angleupdown2=8200

def up():
    global angleupdown
    for i in range (45):
        angleupdown +=76 
        servo2.duty_u16(angleupdown)
        sleep(0.03)
    buzzer.duty_u16(2000)
    sleep(0.1)
    buzzer.duty_u16(0)
    # servo2 goes up at specified intervals
def down():
    global angleupdown
    for i in range (45):
        angleupdown -=76
        servo2.duty_u16(angleupdown)
        sleep(0.03)
    buzzer.duty_u16(2000)
    sleep(0.1)
    buzzer.duty_u16(0)
    # servo2 goes down at specified intervals

def open():
    global angleupdown2
    for i in range (45):
        angleupdown2 +=500
        servo1.duty_u16(angleupdown2)
        sleep(0.03)
    buzzer.duty_u16(2000)
    sleep(0.1)
    buzzer.duty_u16(0)
    # servo1 works for opening the clamps
def close():
    global angleupdown2
    for i in range (45):
        angleupdown2 -=500
        servo1.duty_u16(angleupdown2)
        sleep(0.03)
    buzzer.duty_u16(2000)
    sleep(0.1)
    buzzer.duty_u16(0)
    # servo1 works for closing the clamps
open()
servo2.duty_u16(angleupdown)
ws.pixels_fill(BLACK)
ws.pixels_show()
while True:
    if ldr.read_u16()>20000:
        ws.pixels_fill(RED)
        ws.pixels_show()
        sleep(1)
        buzzer.duty_u16(2000)
        sleep(1)
        buzzer.duty_u16(0)
        open()
        sleep(0.5)
        down()
        sleep(0.5)
        close()
        sleep(0.5)
        up()
        ws.pixels_fill(GREEN)
        ws.pixels_show()
        sleep(0.5)
        # According to the data received from LDR, RGB LED lights red and green and servo motors move
				
			

Robot Arm Servo Code:

				
					from machine import Pin, PWM
servo1=PWM(Pin(21))
servo2=PWM(Pin(22))

servo1.freq(50)
servo2.freq(50)

servo1.duty_u16(8200) # 180 degree
servo2.duty_u16(4770) # 90 degree 
				
			

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);
#define DELAYVAL 500
// define required libraries
#include <Servo.h>
Servo myservo1;
Servo myservo2;

int angleupdown;

void setup() {

  pinMode(20,OUTPUT);
  pinMode(27,INPUT);
  // define input and output pins

  pixels.begin();
  pixels.clear();

  myservo1.attach(21);
  myservo2.attach(22); // define servo motor pins
  Open();
  angleupdown=180;
  myservo2.write(angleupdown);
  
}

void loop() {
  if(analogRead(27)>150){

    pixels.setPixelColor(0, pixels.Color(255, 0, 0));
    pixels.show();
    delay(1000);
    tone(20,700);
    delay(1000);
    noTone(20);

    Open();
    delay(500);
    Down();
    delay(500);
    Close();
    delay(500);
    Up();
    pixels.setPixelColor(0, pixels.Color(0, 255, 0));
    pixels.show();
    delay(10000);
    pixels.setPixelColor(0, pixels.Color(0, 0, 0));
    pixels.show();
    Open();
    angleupdown=180;
    myservo2.write(angleupdown);
    // If the LDR data is greater than the specified limit, the buzzer will sound, the RGB will turn red and servo motors will work
    // The RGB will turn green when the movement is complete
    
  }
}

void Open(){
  myservo1.write(180);
}

void Close(){
  myservo1.write(30);
}

void Up(){

  for (int i=0;i<45;i++){

    angleupdown = angleupdown+2;
    myservo2.write(angleupdown);
    delay(30);
  }
}

void Down(){

  for (int i=0;i<45;i++){

    angleupdown = angleupdown-2;
    myservo2.write(angleupdown);
    delay(30);
  }
}
				
			

Project Image

Project Proposal 💡

By adding the HC05 module to the 2 axis robot arm project, you can modify it to be controlled from your mobile phone with the mobile application.

 

CategoriesLed Raspberry Pi Pico Uncategorized

#16 Voice Controlled Robot Car Project with PicoBricks

Artificial intelligence applications are attempting to recognize human characteristics and learn and try to behave like people. We can define artificial intelligence crudely as software that can learn. Learning can happen through images, sound, and data collected  from the sensors. Algorithms used help in the decision-making processes in various areas AI is deployed. Artificial intelligence applications are now used in situations where the decision-making process needs to be done quickly and without errors. From the marketing to the defense industry, from education to health, from economy to entertainment, artificial intelligence increases efficiency and reduces costs. 

In this PicoBricks project, we will make a 2WD car that you can control by talking. PicoBricks bluetooth module allows you to control wirelessly 2 6V DC motors.

Details and Algorithm

The robot car kit that comes with the set will be assembled. The car is controlled via a mobile phone APP. The HC05 bluetooth module enables us to communicate wirelessly between PicoBricks and a mobile phone. Thanks to a mobile application installed on the mobile phone, the commands spoken into the phone will be transmitted to PicoBricks via Bluetooth  and the robot car will move according to this data. We can direct the robot car with the forward, backward, right, left, stop  voice commands.

Components

1X PicoBricks
2X 6V DC Motor
1X HC05 Bluetooth Module

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

1) Screw the first motor to the chassis of the 2WD robot car that comes out of the set and fix it.

2) Fix the second motor by screwing it to the chassis.

3) Attach the wheels to the motors.

4) Fix the caster under the chassis using spacers.

5) Fix the spacer with the nut from the top of the chassis.

6) Fix 4 spacers on the four corners of the lower chassis.

7) Fix the upper chassis with plug and nuts.

8) Connect the cables of the motors to the terminals on the motor driver.

9) Fix the motor driver, Bluetooth module, PicoBricks board and battery box to the chassis using hot silicone.

In this project, we move the robot car by giving it voice commands via a mobile application.

Instead of the car, you can also control the pan-tilt mechanism in the two-axis robot arm project using the same method. Likewise, you can try a mobile application where you can use buttons instead of voice commands, or you can develop your own application with the MIT Appinventor.

With the HC05 Bluetooth module, you can operate not only the motor driver and motor, but also other modules on PicoBricks. For example, you can light the RGB LED in any color you want, read the temperature and humidity values from the DHT11 module, the light values on the LDR sensor, and print text on the OLED screen.

There is a special mobile application written with the MIT Appinventor, and one in Microblocks to demonstrate this interactivity. You can test all these features by downloading the ZIP file from the link below.

There are two files in the ZIP archive:

  1. A MicroBlocks program  – PicoBricks BT Demo2
  2. An Android APK – PicoBricks_Remote_BKGND.apk

Extract and install the APK file to your mobile phone. Extract and save the MicroBlocks program to your PC. You need to run both of them at the same time and have a Bluetooth module installed in its slot on the PicoBricks board.

DOWNLOAD Link for the Android APP and associated MicroBlocks program

 

For the Android APP:

The screen layout of the APP resembles the PicoBricks board layout, with buttons representing the modules and a module map at the bottom of the screen. When you select a module to test, its name will turn yellow in the button and the corresponding module location on the map will display in orange color the module you are exercising.

First thing you need to do is to PAIR your phone Bluetooth settings with the HC-05. Refer to your device’s instructions on how to do that. Once you are paired, you can start using the Demo APP.

In the APP, click CONNECT to establish the bluetooth connection to the PicoBricks. You’ll see your BT module lights switch to a double blink every two seconds. Now you are ready to test.

Modules LED, DHT, RELAY, LDR, BUZZER operate with a single click of their respective buttons on the phone. LED and RELAY will turn on when tapped, and turn off at next tap. DHT, LDR will provide a sensor readout when tapped, which are displayed on the phone. BUZZER will make a short buzz sound.

Module POT will prompt to operate the potentiometer on the PicoBoard and display pot values on the OLED and the phone.Tap the POT button again when done.

Module NEO will display three sliders to control the RGB colors. As you adjust them, the NEOPixel on the PicoBricks and the NEO button background will change color simultaneously, showing you the resulting color selection. Tap the NEO button again when done.

Module OLED opens up a text entry area where you can type short messages. As you start typing, the Android keyboard will pop up for data entry. When you are done entering text, hide the keyboard and then tap the “SEND TO OLED” button. your message will be displayed on the OLED display of the PicoBricks. Tap the OLED button again when done.

Module MOTOR will display a slider that will let you control a SERVO motor attached to the PicoBricks. NOTE that the demo only operates SERVO #2. You can exercise a -90 to +90 degrees of motion with the servo motor. Tap the MOTOR button again when done.

It is possible that during the operation BT connection may drop or you may experience message synch problems between the phone and the PicoBricks unit. These programs were written to demo the concepts and do not contain rigorous error checking. Best course of action is to restart everything and try again.

 

Mobile companion APP:

You can download the mobile application for android devices from the link below and install it on the phone.

Download Link

 

 

Remember that since this is a Bluetooth APP, you need to set your phone Bluetooth option on and pair it with the HC05 on the PicoBricks. See your phone’s instruction manual on how to do this.

You can change the language of the APP with the Language button and select another one from the menu. Just remember that the project code in MicroBlocks is programmed to expect English commands. If you change your voice control language in the APP, then you also need to change the command strings in the MicroBlocks program.

MicroBlocks Codes of the PicoBricks

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, UART
from utime import sleep

uart = UART(0,9600) #If connection cannot be established, try 115200.
m1 = Pin(21, Pin.OUT)
m2 = Pin(22, Pin.OUT)

m1.low()
m2.low()

while True:
    sleep(0.05)
    if uart.any():
        cmd = uart.readline()
    if cmd==b'F':
        m1.high()
        m2.high()
    elif cmd==b'R':
        m1.high()
        m2.low()
    elif cmd==b'L':
        m1.low()
        m2.high()
    elif cmd==b'S':
        m1.low()
        m2.low()
    cmd=""
				
			

Arduino C Codes of the PicoBricks

				
					void setup() {
  Serial1.begin(9600);
}

void loop() {
  if (Serial1.available() > 0) {
 
      char sread = Serial1.read();
      Serial.println(sread);
      
      if (sread == 'f') {
      Forward();
    } else if(sread == 'r'){
      Turn_Right();
    } else if(sread == 'l'){
      Turn_Left();
    } else if(sread == 's'){
      Stop();
    }
  }
}

void Forward(){
  digitalWrite(21,HIGH);
  digitalWrite(22,HIGH);
  delay(1000);
  digitalWrite(21,LOW);
  digitalWrite(22,LOW);
}
void Turn_Left(){
  digitalWrite(21,LOW);
  digitalWrite(22,HIGH);
  delay(500);
  digitalWrite(21,LOW);
  digitalWrite(22,LOW);
}
void Turn_Right(){
  digitalWrite(21,HIGH);
  digitalWrite(22,LOW);
  delay(500);
  digitalWrite(21,LOW);
  digitalWrite(22,LOW);
}
void Stop(){
  digitalWrite(21,LOW);
  digitalWrite(22,LOW);
  delay(1000);
}
				
			

Project Image