[MarsRover]

MarsRover()

Function Definition: MarsRover(Head = 4, Front Left = 1, Front Right = 7, Back Left = 2, Back Right = 6)

Parameters

NameTypeDescriptionExpected ValuesDefault Value
HeadintServo Port Number at which the Head Servo Motor is connected. 1-84
Front LeftintServo Port Number at which the Front Left Servo Motor is connected. 1-81
Front RightintServo Port Number at which the Front Right Servo Motor is connected. 1-87
Back LeftintServo Port Number at which the Back Left Servo Motor is connected. 1-82
Back RightintServo Port Number at which the Back Right Servo Motor is connected. 1-86

Description

The function initializes the Mars Rover object in Python and maps the 5 servos to the specified pins.

By default the following configuration is added:

  1. Head Servo – 4
  2. Front Left Servo – 1
  3. Front Right Servo – 5
  4. Back Left Servo – 2
  5. Back Right Servo – 6

Example

Discover a unique experience in a Synonym/antonyms World, where the combined powers of Speech Recognition and ChatGPT Extension.

Introduction

Hey! Welcome to the fascinating realm of “Synonym/Antonym World,” where the powers of Speech Recognition and ChatGPT converge. Immerse yourself in an innovative platform that not only recognizes your speech but also provides an extensive collection of synonyms and antonyms for any given word. With this powerful combination, you can effortlessly expand your vocabulary, explore alternative expressions, and delve into the nuances of language. Unleash the potential of speech recognition and ChatGPT as you navigate through a world where words find their perfect counterparts. Get ready to unlock new dimensions of linguistic exploration in the captivating Synonym/Antonym World!

Code

Logic

  1. Open PictoBlox and create a new file.
  2. Choose a suitable coding environment for Block-based coding.
  3. We create an instance of the Speech recognition.This class allows us to convert spoken audio into text.
  4. Next, we create an instance of the ChatGPT model called gpt. ChatGPT is a language model that can generate human-like text responses based on the input it receives. 
  5. Recognize speech for 5 seconds using recognize speech for ()s in the () block.
  6. Save the recognized result in the “input” variable.
  7. Use the “get(synonyms) of ()” function to obtain synonyms of the recognized speech result.
  8. ChatGPT will provide the answers for 10 response synonyms in the “Synonym World” based on the given input.
  9. Use the “get(antonyms) of ()” function to obtain antonyms of the recognized speech result.
  10. The output of the anonymous word of the given input will be displayed by the sprite.
  11. Click on the green flag to run the code.

Output

Read More
Experience an interactive chatbox where you can specify the tone of AI responses. Ask questions or share thoughts on various topics, and receive personalized answers.

Introduction

In this interactive chatbox experience, the user has the freedom to specify the tone in which they would like the AI to respond. The tone can be anything they prefer: Normal, sarcastic, Friend that suits their preference.

Once the user has selected a particular tone, they can provide their input or ask a question. Based on their input, the AI will generate a response that aligns with the chosen tone. This allows for the creation of a conversational atmosphere similar to real-life interactions.

Users are encouraged to ask any question or share their thoughts on various topics. They can also engage in discussions or seek assistance with the information they need. The AI is there to facilitate a meaningful conversation and provide helpful responses based on the tone chosen by the user.

So, the user is requested to let the AI know the specific tone they would like it to adopt, and then they are free to ask any question they have in mind. The AI is here to provide a personalized and engaging chat experience!

Code

Logic

  1. Open PictoBlox and create a new file.
  2. Choose a suitable coding environment for Block-based coding.
  3. We create an instance of the Speech recognition.This class allows us to convert spoken audio into text.
  4. Next, we create an instance of the ChatGPT model called gpt. ChatGPT is a language model that can generate human-like text responses based on the input it receives. 
  5. We create an instance of the Text to Speech.This class allows us to speak the output.
  6. Use the “recognize speech” block to capture the user’s speech for a duration of 5 seconds.
  7. First, ask the user which format they prefer for the answer: normal, sarcastic, or friendly
  8. If the user requests a normal response, the ChatGPT extension will generate feedback in normal mode.
  9. If the user requests a sarcastic response, ChatGPT will generate a sarcastic answer.
  10. If the user requests a friendly response, ChatGPT will generate a friendly answer. Additionally, Sprite will speak the answer.
  11. The “speak” block, which utilizes the text-to-speech recognition extension, will vocalize the answer to the asked question.

In summary, we can describe it as a chatbox that provides answers in three different ways based on the user’s mood and entertainment preferences. When a question is asked, it will respond accordingly.

Output

Read More
Learn about Arduino digital and analog pins and their functions as input or output for voltage levels.

Introduction

Digital pins

Arduino’s digital pins offer two voltage levels: HIGH (5V) or LOW (0V). When set to LOW, a pin provides 0V to external devices, while setting it to HIGH delivers 5V, enabling triggering of relays or LED illumination. Additionally, digital pins can function as input to read data from peripheral devices or as output to power sensors and other devices. On the other hand, analog pins are used to read analog values in the form of voltage levels ranging from 0V to 5V.

Analog pins

These are the pins that are used to read the analog values from devices in the form of voltage levels between 0v to 5v

Circuit Diagram

  1.  Resistance = 220Ω
  2. LED+ to pin 13 
  3. LED – to GND

Code

Now let’s connect our Arduino to Pictoblox and learn to code. 

  1. Open Pictoblox and choose Block coding.
  2. Go to “boards” and select “Arduino Uno” from the list
  3. From “connect,” choose the serial port, and then click on the “connect” button to establish the connection between Arduino Uno and your computer..
  4. Click on the event palette and drag “when the flag clicked.”
  5. From the control palette, drag the “forever” block and add it to the event block.
  6. From the Arduino palette, drag “set digital pin() output as ()” block into the forever block.
  7. Again from the control palette add the wait() block  into the forever block
  8. Repeat steps 6 and 7, setting the output as LOW this time.

Script

Output

 

Read More
Experience interactive control of a robotic arm through arrow keys. Open and close the gripper with ease

Introduction

A robotic arm controlled by arrow keys allows users to manipulate its movements, specifically opening and closing the arm. This type of robotic arm is designed to respond to directional inputs from arrow keys, enabling users to control the arm’s gripping or releasing action. Users can activate the corresponding motors or actuators within the robotic arm by pressing the arrow keys, causing it to perform the desired action. This interactive control mechanism provides a user-friendly interface for operating the robotic arm, offering a hands-on experience in manipulating objects and exploring the capabilities of robotics technology.

Code

sprite = Sprite('Tobi')

roboticArm=RoboticArm(1,2,3,4)
import time
quarky = Quarky()
while True:
  if sprite.iskeypressed("up arrow"):
    roboticArm.gripperaction("open")
    
  if sprite.iskeypressed("down arrow"):
    roboticArm.gripperaction("close")
    

Logic

  1. Open the Pictoblox application.
  2. Select the Python-based environment.
  3. Click on the robotic arm extension available in the left corner.
  4. First initialize the robotic arm‘s pin with pictoblox.
  5. We create a roboticArm object named roboticArm with four parameters. These parameters represent the pins or connections used to communicate with the robotic arm.
  6. We import the time module, which provides functions for working with time-related tasks.
  7. Then creates an infinite loop that will continue running until the program is manually stopped. Everything inside this loop will be repeated indefinitely.
  8. Pressing the up arrow key opens the gripper.
  9. Pressing the down arrow key closes the gripper.
  10. Press Run to run the code.

Output

Read More
Learn how to create a Machine Learning Model to count nuts and bolts from the camera feed or images. See how to open the ML environment, collect and upload data, label images, train the model, and export the python script.

Introduction

In this example project we are going to explore how to create a Machine Learning Model which can count the number of nuts and bolts from the camera feed or images. You will learn how to open the ML environment, collect and upload data, label images, train the model, and export the Python script.

Object Detection in Machine Learning Environment

Object Detection is an extension of the ML environment that allows users to detect images and make bounding boxes into different classes. This feature is available only in the desktop version of PictoBlox for Windows, macOS, or Linux. As part of the Object Detection workflow, users can add classes, upload data, train the model, test the model, and export the model to the Block Coding Environment.

Opening Image Detection Workflow

Alert: The Machine Learning Environment for model creation is available in the only desktop version of PictoBlox for Windows, macOS, or Linux. It is not available in Web, Android, and iOS versions.

Follow the steps below:

  1. Open PictoBlox and create a new file.
  2.  Select the Python Coding Environment.
  3. Select the “Open ML Environment” option under the “Files” tab to access the ML Environment.
  4. You’ll be greeted with the following screen.
    Click on “Create New Project”.
  5. A window will open. Type in a project name of your choice and select the “Object Detection” extension. Click the “Create Project” button to open the Object Detection window.

You shall see the Object Detection workflow. Your environment is all set.

Collecting and Uploading the Data

The left side panel will give you three options to gather images:

  1. Using the Webcam to capture images.
  2. Uploading images from your device’s hard drive.
  3. Downloading images from a repository of images.

Uploading images from your device’s hard drive

  1. Now it’s time to upload the images which you downloaded from another source or captured from your camera. Click on the “Select from device” option from the Import Images block.
  2. Now click on the “Choose images from your computer” and go to the folder where you downloaded your images.
  3. Select all images which you want to upload then click on “open” option.
  4. Now page of PictoBlox looks like this:

Making Bounding Box – Labelling Images

A bounding box is an imaginary rectangle that serves as a point of reference for object detection and creates a collision box for that object.

We draw these rectangles over images, outlining the object of interest within each image by defining its X and Y coordinates. This makes it easier for machine learning algorithms to find what they’re looking for, determine collision paths and conserves valuable computing resources.

  1. Labeling is essential for Object Detection. Click on the “Bbox” tab to make the labels.

    Notes:

    1. Notice how the targets are marked with a bounding box. The labels appear in the “Label List” column on the right.
    2. A single image can have multiple targets. Every target must be enclosed in a bounding box.
    3. The bounding boxes are color coded.
  2. To create the bounding box in the images, click on the “Create Box” button, to create a bounding box. After the box is drawn, go to the “Label List” column and click on the edit button, and type in a name for the object under the bounding box. This name will become a class. Once you’ve entered the name, click on the tick mark to label the object.

  3. Options in Bounding Box:

    1. Auto Save: This option allows you to auto-save the bounding boxes with the labels they are created. You do not need to save the images every time this option is enabled.
    2. Manual Save: This option disables the auto-saving of the bounding boxes. When this option is enabled you have to save the image before moving on to the next image for labeling.
    3. Create Box: This option starts the cursor on the images to create the bounding box. When the box is created, you can label it in the Label List.
    4. Save Box: This option saves all the bounding boxes created under the Label List.
  4. File List: It shows the list of images available for labeling in the project.
  5. Label List: It shows the list of Labels created for the selected image.
  6. Class Info: It shows the summary of the classes with the total number of bounding boxes created for each class.
  7.   You can view all the images under the “Image” tab.

Training the Model

In Object Detection, the model must locate and identify all the targets in the given image. This makes Object Detection a complex task to execute. Hence, the hyperparameters work differently in the Object Detection Extension.

  1. Go to the “Train” tab. You should see the following screen:
  2. Click on the “Train New Model” button.
  3. Select all the classes, and click on “Generate Dataset”.
  4.  Once the dataset is generated, click “Next”. You shall see the training configurations.
  5. Observe the hyperparameters.
    1. Model name- The name of the model.
    2. Batch size- The number of training samples utilized in one iteration. The larger the batch size, the larger the RAM required.
    3. The number of iterations- The number of times your model will iterate through a batch of images.
    4. Number of layers- The number of layers in your model. Use more layers for large models.
  6. Specify your hyperparameters. If the numbers go out of range, PictoBlox will show a message.
  7. Click “Create”, It creates a new model according to inserting the value of the hyperparameter.
  8. Click “Start Training”, If desired performance is reached, click on the “Stop” 
    1. Total Loss
    2. Regularization Loss
    3. Localization Loss
    4. Classification Loss
  9. After the training is completed, you’ll see four loss graphs: 
    Note: Training an Object Detection model is a time taking task. It might take a couple of hours to complete the training.
  10. You’ll be able to see the graphs under the “Graphs” panel. Click on the buttons to view the graph.

    1. The graph between “Total loss” and “Number of steps”
    2. The graph between “Regularization loss” and “Number of steps”.
    3. The graph between “Localization” and “Number of steps”.
    4. The graph between “Classification loss” and “Number of steps”.

Evaluating the Model

Now, let’s move to the “Evaluate” tab. You can view True Positives, False Negatives, and False Positives for each class here along with metrics like Precision and Recall.

Testing the Model

The model will be tested by uploading an Image from the device:

Export in Python Coding

    1. Click on the “PictoBlox” button, and PictoBlox will load your model into the Python Coding Environment if you have opened the ML Environment in the Python Coding.
    2. Make a new folder(name is img) in Python script and add a number of images for testing.
      |
    3. Also, add the same images in the backdrop and delete the default backdrop.
    4. Change in Python script according to requirement.

Code

####################imports####################
# Do not change
sprite = Sprite('Tobi')
sprite1 = Sprite('Stage')
import cv2
import numpy as np
import tensorflow.compat.v2 as tf
import os
import time
# Do not change
####################imports####################

#Following are the model and video capture configurations
# Do not change

detect_fn = tf.saved_model.load(
    "saved_model")

# cap = cv2.VideoCapture(0)                                          # Using device's camera to capture video
# if (cap.isOpened()==False):
#   print("Please change defalut value of VideoCapture(k)(k = 0, 1, 2, 3, etc). Or No webcam device found")

folder="img"
for filename in os.listdir(folder):
  img = cv2.imread(os.path.join(folder,filename))
  if img is not None:
    x=filename
    

    a=0
    b=0
    y=x.split('.')
   
      
  
    font = cv2.FONT_HERSHEY_SIMPLEX
    fontScale = 1
    color_box = (50,50,255)
    color_text = (255,255,255)
    thickness = 2
    
    
    class_list = ['Bolt','Nut',]                        # List of all the classes 
  
  #This is the while loop block, computations happen here
    image_np=img
    height, width, channels = image_np.shape                       # Get height, wdith  
    image_resized = cv2.resize(image_np,(320,320))                   # Resize image to model input size  
    image_resized = cv2.cvtColor(image_resized, cv2.COLOR_BGR2RGB) # Convert bgr image array to rgb image array  
    input_tensor = tf.convert_to_tensor(image_resized)             # Convert image to tensor
    input_tensor = input_tensor[tf.newaxis, ...]                   # Expanding the tensor dimensions
    
    detections = detect_fn(input_tensor)                           #Pass image to model
    
    num_detections = int(detections.pop('num_detections'))         #Postprocessing
    detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()}
    detections['num_detections'] = num_detections
    detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
    width=320
    height=320
    # Draw recangle around detection object
    for j in range(len(detections['detection_boxes'])):
      # Set minimum threshold to 0.3
      if(detections['detection_scores'][j] > 0.3):
        # Starting and end point of detected object
        starting_point = (int(detections['detection_boxes'][j][1]*width),int(detections['detection_boxes'][j][0]*height))
        end_point = (int(detections['detection_boxes'][j][3]*width),int(detections['detection_boxes'][j][2]*height))
        # Class name of detected object
        className = class_list[detections['detection_classes'][j]-1]
        # Starting point of text
        print(className)
        if(className=="Bolt"):
          a=a+1
        elif(className=="Nut"):
          b=b+1
        starting_point_text = (int(detections['detection_boxes'][j][1]*width),int(detections['detection_boxes'][j][0]*height)-5)
        # Draw rectangle and put text
        image_resized = cv2.rectangle(image_resized, starting_point, end_point,color_box, thickness)
        image_resized = cv2.putText(image_resized,className, starting_point_text, font,fontScale, color_text, thickness, cv2.LINE_AA)
        # Show image in new window
    cv2.imshow("Detection Window",image_resized)
    sprite1.switchbackdrop(y[0])
    print(a)
    print(b)

    if cv2.waitKey(25) & 0xFF == ord('q'):                          # Press 'q' to close the classification window
      break
    time.sleep(2)
    sprite.say("Total number of bolts is "+str(a))
    time.sleep(1)
    sprite.say("Total number of Nuts is "+str(b))
    time.sleep(5)
    sprite.say("")
cv2.waitKey(5)                                               
cv2.destroyAllWindows()                                             # Closes input window

Logic

The example demonstrates how to count nuts and bolts from an image of a stage. Following are the key steps happening:

  1. Creates a sprite object named “Tobi”. A sprite is typically a graphical sprite that can be animated or displayed on a screen.
  2. Creates another sprite object named ‘Stage’. It represents the backdrop.
  3. Imports the ‘time’ module, which provides functions to work with time-related operations using import time.
  4. Imports the ‘os’ module, which provides functions to work with outside folders and images inside them.
  5. Make a new folder in the project files and upload testing images from your computer, as well as the same images in the backdrop.
  6. One by one, go through all uploaded images using the ‘for’ loop.
  7. Store images in the variable ‘img’ and their labels in the variable ‘filename’.
  8. Initialize two count variables named ‘a’ and ‘b’ with a 0 value, which stores the count of nuts and bolts in the image.
  9. Split the label of the image and store only the name of the image in a variable (name y), which is used to change the backdrop.
  10. Define the new height (which is equal to 320) and width (which is equal to 320) of the detection window so we can easily see bounding boxes on the detected image.
  11. Write a condition in the code to count the number of nuts and bolts.
  12. If a nut is detected, it will increase the count of the nut variable (a), and if a bolt is detected, it will increase the count of the bolt variable (b).
  13. Switch backdrop according to image name using a predefined function (sprite1.switchbackdrop()) for changing backdrop in PictoBlox.
  14. Show an updated detection window in the output, which contains bounding boxes for detected objects.
  15. Write a predefined function (sprite.say()) by which ‘Tobi’ will say the number of nuts and bolts.
  16. Also adds waiting time so we can clearly see the output of the model.

Final Result

Conclusion

Creating a Machine Learning Model to count nuts and bolts can be both complex and time-consuming. Through the steps demonstrated in this project, you can create your own Machine Learning Model that can detect and count nuts and bolts in an image. Once trained, you can export the model into the Python Coding Environment, where you can tweak it further to give you the desired output. Try creating a Machine Learning Model of your own today and explore the possibilities of Object Detection in PictoBlox!

Read More
Discover how a robotic arm playing chess combines robotics, AI, and computer vision to make smart and accurate moves on the chessboard.

Introduction

robotic arm playing chess is a great example of how robots and AI can work together to do complex tasks. Chess is a game that needs smart thinking and careful moves. The robotic arm is like a human arm and can move pieces on the chessboard.

The robotic arm has different parts like joints, actuators, sensors, and a gripper. The joints let the arm move in different ways, just like a human arm. The actuators control the arm’s movements, so it can make precise and planned moves during the game.

The robotic arm uses AI and computer vision to play chess. The AI algorithms study the chessboard, figure out where the pieces are, and decide on the best moves. They consider things like how valuable each piece is and where they are on the board. The arm’s sensors tell it where it is, so it can pick up the pieces and put them in the right places accurately.

When the AI finds the best move, the robotic arm carefully grabs the chosen piece, lifts it up, and puts it on the right square of the chessboard. The gripper has sensors to handle the pieces gently and not damage them.

The robotic arm playing chess is an amazing example of how robots, AI, and computer vision can work together. It shows how we can use complex algorithms and physical abilities to do tasks that people usually do. This technology can be useful in many fields like manufacturing, logistics, and healthcare, where we need precise and automated movements.

In summary, a robotic arm playing chess is a cool combination of robotics, AI, and computer vision. It can make smart and accurate moves on a chessboard. It’s a big achievement in robotics and shows how automation and AI can do complex tasks in different industries.

Code

sprite = Sprite('Tobi')


roboticArm = RoboticArm(1,2,3,4)


roboticArm.setoffset(0,-10)
roboticArm.setgripperangle(0,50)
roboticArm.sethome()
roboticArm.gripperaction("open")
roboticArm.movexyzonebyone(110,130,20,1000)
roboticArm.gripperaction("close")
roboticArm.movebyinoneaxis(40,"Z",1000)
roboticArm.movetoxyz(-100,190,30,200)
roboticArm.movexyzonebyone(-50,180,30,1000)
roboticArm.gripperaction("open")
roboticArm.movebyinoneaxis(-30,"Y",1000)
roboticArm.gripperaction("close")
roboticArm.sethome()
roboticArm.gripperaction("open")
roboticArm.movexyzonebyone(80,220,30,1000)
roboticArm.gripperaction("close")
roboticArm.movebyinoneaxis(50,"Z",1000)
roboticArm.movexyzonebyone(-70,190,30,1000)
roboticArm.gripperaction("open")
roboticArm.movebyinoneaxis(-30,"Y",1000)
roboticArm.gripperaction("close")
roboticArm.sethome()

Logic

  1. Open the Pictoblox application.
  2. Select the Python-based environment.
  3. Click on the robotic arm extension available in the left corner.
  4. First initialize the robotic arm‘s pin with pictoblox.
  5. Sets the offset of the robotic arm to (0, -10) from its current position.
  6. Sets the angle of the gripper to (0, 50).
  7. Moves the robotic arm to its home position.
  8. Opens the gripper of the robotic arm.
  9. Moves the robotic arm in the XY plane within a specified zone using movexyzonebyone().
  10. Closes the gripper of the robotic arm using gripperaction(“close”).
  11. Moves the robotic arm in the Z-axis by a specified amount using movebyinoneaxis().
  12. Moves the robotic arm to a specific position in the XYZ coordinates using movetoxyz().
  13. Moves the robotic arm in the XY plane within a specified zone using movexyzonebyone().
  14. Opens the gripper of the robotic arm using gripperaction(“open”).
  15. Moves the robotic arm in the Y-axis by a specified amount using movebyinoneaxis() .
  16. Closes the gripper of the using movebyinoneaxis().
  17. Moves the robotic arm to its home position using sethome().
  18. Opens the gripper of the robotic arm using gripperaction(“open”) .
  19. Moves the robotic arm in the XY plane within a specified zone using movexyzonebyone().
  20. Closes the gripper of the robotic arm using gripperaction(“close”).
  21. Moves the robotic arm in the Z-axis by a specified amount using movebyinoneaxis().
  22. Moves the robotic arm in the XY plane within a specified zone using movexyzonebyone().
  23. Opens the gripper of the robotic arm using gripperaction(“open”).
  24. Moves the robotic arm in the Y-axis by a specified amount using movebyinoneaxis().
  25. Closes the gripper of the robotic arm using gripperaction(“close”).
  26. Moves the robotic arm to its home position using sethome().
  27. Press Run to run the code.

Output

Read More
Explore the world of gesture-controlled robotic arms, an innovative and interactive system that allows users to control robotic arm movements using hand gestures.

Introduction

A gesture-controlled robotic arm is an innovative and interactive system that allows users to control the movements and actions of a robotic arm using hand gestures. Instead of relying on traditional input methods such as buttons or joysticks, this technology utilizes computer vision or sensor-based techniques to recognize and interpret specific hand movements or gestures.

The purpose of a gesture-controlled robotic arm is to provide a more intuitive and natural way of interacting with automatic systems. By mimicking human arm movements, users can command the robotic arm to perform various tasks, such as picking and placing objects, manipulating tools, or performing precise movements in a specific direction.

Gesture-controlled robotic arms find applications in various fields, including industrial automation, medical assistance, prosthetics, and virtual reality. They offer advantages such as enhanced dexterity, improved human-robot interaction, and increased accessibility for individuals with limited mobility.

 

Hand Gesture Classifier Workflow

Follow the steps below:

  1. Open PictoBlox and create a new file.
  2. You can click on “Machine Learning Environment” to open it.
  3. Click on “Create New Project“.
  4. A window will open. Type in a project name of your choice and select the “Hand Gesture Classifier” extension. Click the “Create Project” button to open the Hand Pose Classifier window.
  5. You shall see the Classifier workflow with two classes already made for you. Your environment is all set. Now it’s time to upload the data.

Class in Hand Gesture Classifier

There are 2 things that you have to provide in a class:

  1. Class Name: It’s the name to which the class will be referred as.
  2. Hand Pose Data: This data can either be taken from the webcam or by uploading from local storage.

Note: You can add more classes to the projects using the Add Class button.
Adding Data to Class

You can perform the following operations to manipulate the data into a class.

  1. Naming the Class: You can rename the class by clicking on the edit button.
  2. Adding Data to the Class: You can add the data using the Webcam or by Uploading the files from the local folder.
    1. Webcam:
Note: You must add at least 20 samples to each of your classes for your model to train. More samples will lead to better results.
Training the Model

After data is added, it’s fit to be used in model training. In order to do this, we have to train the model. By training the model, we extract meaningful information from the hand pose, and that in turn updates the weights. Once these weights are saved, we can use our model to make predictions on data previously unseen.

The accuracy of the model should increase over time. The x-axis of the graph shows the epochs, and the y-axis represents the accuracy at the corresponding epoch. Remember, the higher the reading in the accuracy graph, the better the model. The range of accuracy is 0 to 1.

Testing the Model

To test the model, simply enter the input values in the “Testing” panel and click on the “Predict” button.

The model will return the probability of the input belonging to the classes.

Export in Python Coding

Click on the “Export Model” button on the top right of the Testing box, and PictoBlox will load your model into the Python Coding Environment if you have opened the ML Environment in Python Coding.

 

Code

The following code appears in the Python Editor of the selected sprite.

####################imports####################
# Do not change

import numpy as np
import tensorflow as tf
import time
RoboticArm=RoboticArm(1,2,3,4)

# Do not change
####################imports####################

#Following are the model and video capture configurations
# Do not change

model=tf.keras.models.load_model(
    "num_model.h5",
    custom_objects=None,
    compile=True,
    options=None)
pose = Posenet()                                                    # Initializing Posenet
pose.enablebox()                                                    # Enabling video capture box
pose.video("on",0)                                                  # Taking video input
class_list=['Right','Left']                  # List of all the classes

def runQuarky(predicted_class):
  if predicted_class == "Left":
    RoboticArm.moveincircleanticlockcise()
        
  if predicted_class == "Right":
    RoboticArm.moveincircleclockwise()
      # Do not change
###############################################

#This is the while loop block, computations happen here
# Do not change

while True:
  pose.analysehand()                                             # Using Posenet to analyse hand pose
  coordinate_xy=[]
    
    # for loop to iterate through 21 points of recognition
  for i in range(21):
    if(pose.gethandposition(1,i,0)!="NULL"  or pose.gethandposition(2,i,0)!="NULL"):
      coordinate_xy.append(int(240+float(pose.gethandposition(1,i,0))))
      coordinate_xy.append(int(180-float(pose.gethandposition(2,i,0))))
    else:
      coordinate_xy.append(0)
      coordinate_xy.append(0)
            
  coordinate_xy_tensor = tf.expand_dims(coordinate_xy, 0)        # Expanding the dimension of the coordinate list
  predict=model.predict(coordinate_xy_tensor)                    # Making an initial prediction using the model
  predict_index=np.argmax(predict[0], axis=0)                    # Generating index out of the prediction
  predicted_class=class_list[predict_index]                      # Tallying the index with class list
  print(predicted_class)
  runQuarky(predicted_class)  
  # Do not change

 

Note: You can edit the code to add custom code according to your requirement.

Logic

  1. When the identified class is right, the robotic arm will move clockwise.
  2. When the identified class is left, the robotic arm will move counterclockwise.
def runQuarky(predicted_class):
  if predicted_class == "Left":
    RoboticArm.moveincircleanticlockcise()
        
  if predicted_class == "Right":
    RoboticArm.moveincircleclockwise()

Output

Read More
interfacing of DC motor with Arduino and it's control.

Motor driver and it’s working

Arduino Uno is a controlling device which is capable to control the things we are connected to it, it is not a power source. motors works on the principle of electromagnetism so draws a lot of load current which can’t be maintained by Arduino, for this we need a motor driver which is integrated circuited (IC) which maintains this load current for the motors.

this is of 16 pin chip among which 2 are enable pins used to control the speed of the motor, 4 for the input pins are 4 for  output pins for the motors, remaining are GND and VCC.

Circuit

connection. 

Arduino uno            Motor driver

D5                             IN1

D4                             IN2

D6                             EN1

GND                          GND

In this example, we will be controlling the direction of rotation of the motor using the motor driver.

code

  • From the actuators palette drag connect motor () direction 1 () direction 2() and PWM()
  • from control palette add forever block

  • From the actuator palette add run motor () in direction () with speed()

  •    from the control palette Add a wait block

  • Repeat the above 2 steps and change the direction from forward to backward

  • Now add when flag clicked event 

Script

OUTPUT

Read More
Learn how to control speed of the motor using Arduino and motor driver.
interfacing motor driver with Arduino

Arduino is a controlling device not a power source on the other hand, motors work on the principle of electromagnetism and hence draw a lot of load current which can’t be maintained by Arduino. To overcome this, we need a motor driver which maintains this load current along with the speed and direction control of the motor.

Circuit

connections

connection. 

Arduino uno            Motor driver

D5                             IN1

D4                             IN2

D6                             EN1

GND                          GND

Code

  • Create a variable as speed and set it 0

  • From actuators drag connect motor () direction 1() direction 2() and PWM()

  • from controls palette add a forever block

  • again from controls palette add if-then-else block in the forever block

  • We will be changing the speed using th up and down arrow. For this goto sensing and check for the key pressed.

  •  from Acturatos add run motor() direction () with speed()

  • Inset the value of the speed variable as motor speed

  • Repeat the above steps for the down arrow to reduce the speed. 

  • Add a wait block for a time of 0.25 seconds in forever block outside the if-then-else block.

  • now from the event palette add when flag clicked event at the start of the script.

Script

Output

Read More
Discover the fundamentals of Arduino Serial Communication using Pictoblox and the importance of setting the correct baud rate for proper data exchange.
Introduction

If you are here willingly, it means you already possess knowledge about programming and project-making. In various programming languages, data from users is often required, and useful information needs to be displayed for users. Similarly, when writing Arduino codes and creating projects, dealing with valuable information is a common requirement. This information is termed serial data, and the process of sending or receiving data to/from the user is known as serial communication. Arduino’s Serial monitor is the interface used to display or receive data from the user.

In this example, we will delve into Serial communication for Arduino using the Pictoblox communication extension.

Extension Setup:

go to extension and add communication extension.

after adding the extension change the mode from stage to upload mode

code

  1. Add the “when Arduino starts up” block from the Arduino palette.
  2. From the communication palette, enable Serial communication using the “Set Serial() baud rate()” block. Set the baud rate to 9600 from the drop-down menu.
  3. After configuring the baud rate, data can be sent or received from the user easily. To send data to the Serial monitor, go to the communication extension and add the “write () on Serial  ()” block.

Output

When observing the output, you may notice that it is not as expected. This issue is due to the change in the baud rate. It is crucial to set the same baud rate for the Serial monitor to ensure proper data exchange. From the highlighted space below, set the baud rate to 9600.

After adjusting the baud rate, observe the output again to ensure proper data display and transmission.

Here is the result after changing the baud rate.

Troubleshooting:

If you encounter any unexpected output or issues with the Serial monitor, verify that the baud rate is correctly configured to avoid data discrepancies. In this comprehensive introduction, you have learned about Arduino Serial Communication with Pictoblox, including baud rate configuration and troubleshooting. Master the art of seamless data exchange between Arduino and the user, further enhancing your programming knowledge and project-making capabilities.

Read More
Discover the fascinating world of Arduino Serial Communication and how it enables data exchange between the Arduino board and the user.
introduction

If you are here willingly, it means you already possess knowledge about programming and project-making. In programming, data from users is often needed, and valuable information needs to be displayed for users. Similarly, when coding for Arduino and creating projects, dealing with useful information is common. This information is referred to as serial data, and the process of sending or receiving data through the Serial monitor in Arduino is known as serial communication.

In this example, we will learn how to read Serial input for Arduino using the communication extension in Pictoblox.

Extension

  1. Go to the extensions section and add the communication extension.
  2. Change the mode from “stage” to “upload.”

Code

  1. Add the “when Arduino starts up” block from the Arduino palette
  2. From the communication palette, enable Serial communication using the “Set Serial() baud rate()” block. Set the baud rate to 9600 from the drop-down menu.
  3. From controls add forever block.
  4. Create a variable of type “string” and name it “input.”
  5. Add the “set input to ()” block from “my variables” into the forever block.
  6. Use the “Read byte as string from serial ()” block to read the collection of data (as a single word or sentence) from the Serial monitor.
  7. Set “input” to the value read from the Serial monitor using the “Read byte as string from serial ()” block.
  8. To display the user input on the screen, use the “write() on serial()” block and input the value of “input” as the output.

Script

Output

in the serial terminal, change the baud rate to 9600. enter the input in the place marked yellow. to fed this input hit the button marked in blue.

 

here you will notice that there are a lot of empty lines (space marked in red ) between the outputs you are entering. in the next example we will learn how to avoid such a problem.

Read More
learn how to customize your output, so that you can deal with the data correctly.
introduction

if you are here by your own will, this means you already know about programming and project-making. in all the programming languages need some data from the user and also we are required to display some useful information for the user. in the same way, while writing the codes for Arduino and making projects, we are dealing with a lot of useful information. this data is called serial data and sending this data to the user or receiving data from the user is called serial communication. for Arduino, we are having Serial monitor from where we can show whatever the data we want to display or receive from the user.

in this example, we learn how to read the Serial input for Arduino using the communication extension of Pictoblox.

Extension

Go to extension and add communication extension.

Now change the mode from stage to upload.

Code

  • from Arduino palette add when Arduino starts-up.

  • from communication palette enable the Serial communication using Set Serial() baud rate() block and from drop-down set the baud rate as 9600.
  • From controls add forever block.

  • from the control palette add wait until () block in forever block.

  • from operators add not operator in wait until() block.

  • now we will wait until user enters any input and we will take that input and move further otherwise, we continue to wait there. for this add bytes available on serial ()? block in not operator.

  • create a variable of type string and name it as input.

  • now store the user data in input variable.

  • now use the write () on serial () block to print user data on the serial monitor.

Script

Output

here you can see that the null spaces are gone now.

 

 

Read More
Discover the fascinating LDR (Light Dependent Resistor), an analog-type sensor that alters its resistance with varying light intensity
Introduction

LDR, also known as a Light Dependent Resistor, is an analog-type sensor renowned for its ability to modify its resistance based on the intensity of incident light. As the surrounding light changes, the resistance of the LDR fluctuates, making it an essential component in various light-sensing applications. While generally designed as a two-pin sensor, it is also available in a three-pin module, providing enhanced features and flexibility.

circuit

How To Use An LDR Sensor With Arduino Tutorial 1

in this example, we will interface our sensor module with Arduino and we’ll be reading the change in it’s resistance upon the change of light.

Code

  1. Add a “when flag clicked” event from the events palette.
  2. Place a “forever” block from the controls palette after the event block.
  3. Within the “forever” block, add a “say()” block from the looks palette.
  4. From the Arduino sensor palette, drag the “read analog sensor () at ()” block and insert it in place of “hello” in the “say()” block.

Output

Read More
Discover the fascinating world of touch sensors and how they operate based on changes in capacitance caused by static charges from conductive objects.
introduction

Touch sensors are innovative devices that respond to changes in capacitance resulting from static charges generated by conductive objects. Their unique working principle enables them to detect touch interactions, making them ideal for various applications, including touch-sensitive buttons and interactive surfaces.

Circuit

Code

  1. Add an “if” block from the controls palette into the scripting area.
  2. From the Arduino sensor palette, add “read digital sensor () at pin()” inside the “if” block. Choose “touch sensor” from the drop-down menu
  3. Create a variable and name it “count.” Increment the count by 1 inside the “if” block, which helps keep track of touch interactions.
  4. Now use an “if then else” block inside the “if” block to check whether the count variable is even or odd. The modulo (mod) block from the Arduino palette can be utilized for this purpose.
  5. Based on the condition, control the LED to turn it ON for even counts and OFF for odd counts.
  6. Add the “set digital pin () output as ()” block from the Arduino palette within the “if” and “else” blocks, respectively.
  7. Set the “count” variable to 0 at the beginning of the code to ensure accurate counting from the start.
  8. Add a “when flag clicked” block from the events palette to initiate the code execution.

Script

  • Output

Read More
Learn how to interface an MQ sensor with Arduino to detect multiple gases like CO2, LPG, and more.
introduction

The MQ series of sensors offers a diverse range of gas detectors used for detecting multiple gases like CO2, LPG, and more. These sensors have numerous applications, from detecting smoke caused by fires in buildings to identifying gas leaks and natural gases in mining operations.

Buy MQ-137 NH3 Gas Sensor Module Online in India | Robocraze

In this example, we will interface an MQ sensor with Arduino to detect gas levels above a certain threshold. When the gas levels surpass the set limit, Arduino will trigger a buzzer alarm. Let’s delve into the exciting world of gas detection using Arduino!

Circuit

connection

Sensor                                Arduino

VCC                                        5V

GND                                      GND

A0                                           A0

buzzer+                                   D13

Buzzer-                                    GND

Code

  1. From the event palette, add the “when flag clicked” block into the scripting area.
  2. Add the “forever” block from the controls palette.
  3. Inside the “forever” block, add the “if-else” block from the control palette.
  4. From the operator palette, add the “greater than” operator into the “if” conditional part.
  5. In the first space of the “greater than” operator, use the “read analog sensor () at ()” block from the Arduino sensor palette and insert the MQ sensor value from A0.
  6. In the second space of the “greater than” operator, set a specific value as the threshold for gas detection.

Script.

Output

Read More
A relay is an electromagnetic switch which is used to control high voltage appliances using microcontrollers.
Introduction

A relay is an electromagnetic switch that works on the principle of electromagnetic induction. A Realy is used to control the high voltage appliances using the microcontrollers.

5V Single-Channel Relay Module - Pin Diagram, Specifications, Applications, Working

a relay has a primary side which is need to be connected to the controller and the secondary side is need to be connected with the load, for example, motor, light bulb, fan, etc. primary side has 3 pins named as VCC, GND, and IN.  secondary also has connections named as Common(COM), Normally Open(NO), and Normally Closed (NC).

Circuit

connection

relay              Arduino

VCC                 5V

GND               GND

IN                  D7

COM             battery-

NO                1 leg of the bulb

Code

  1. From  event palette,  add when  flag clicked  into the scripting area
  2. From controls add a forever block
  3. Now go to actuator palette, and drag set relay at pin () to () into forever loop.
  4. Add a wait block from control palette.
  5. Repeat above 2 steps and change relay state from OFF to ON

 

Script

Output

Read More
Explore the functionality of a raindrop sensor, an analog-type sensor that detects changes in resistance upon contact with water.
introduction

The raindrop sensor is an analog-type sensor that effectively measures changes in resistance when it encounters water. This property makes it an ideal choice for detecting rain and water presence in various applications. While typically designed with two pins, there are also versions available with a controller module, effectively converting it into a three-pin sensor for enhanced functionality.

rain drop sensor

Circuit

To set up the raindrop sensor circuit, make the following connections:

  • Sensor:
    • VCC: Connect to the 5V power supply
    • GND: Connect to ground (GND)
    • A0: Connect to analog input pin A0
  • Buzzer:
    • Buzzer+: Connect to digital pin D13
    • Buzzer-: Connect to ground (GND)

Code

  1. Add an “if-else” block from the controls palette.
  2. Insert a comparison operator into the “if” block from the operators palette
  3. Check whether the value of the raindrop sensor is below a certain threshold, let’s say 800. From the Arduino sensor palette, add “read analog sensor () at pin ()” and place it in the blank space of the operator. Choose “raindrop sensor” from the drop-down menu.
  4. If the value is below the set limit, activate the buzzer (alarm) connected to pin 13. Add set digital pin () output as () from Arduino palette within the “if” block. In the “else” part, ensure the alarm remains off when the raindrop sensor value is above the set limit.
  5. Add the above set of code inside a “forever” block to continuously monitor the sensor’s readings.
  6. Finally, add a “when flag clicked” block at the start of the code to initiate the raindrop sensor monitoring.

Script

Output

 

Read More
Explore the innovative flex sensor, utilizing carbon on a plastic strip to function as a variable resistor, with its resistance changing upon flexing the component
INTRODUCTION

The flex sensor is an ingenious device employing carbon on a plastic strip to serve as a variable resistor. As the sensor bends in one direction, its resistance varies accordingly. The more it bends, the higher the resistance becomes. This unique property makes it an ideal choice for applications where detecting bending or flexing is necessary.

Circuit Diagram

 

Code

  1. Create a variable called “sensor value” and set it to 0
  2. Add a “forever” block from the control palette. 
  3. Inside the “forever” block, set “sensor value” to read analog sensor at A0.
  4. Since the Arduino’s ADC channel is 8-bit, the generated value will range from 0 to 1023. To convert this range to 0-180 for controlling the servo motor, use the “map” block from the Arduino palette.
  5. Set the mapped value as the angle for the servo motor.
  6. connect servo at pin 3 and fed variable servo angle as for the servo motor.
  7. Add these three blocks inside the “forever” block to continuously read the flex sensor’s value and control the servo motor’s angle accordingly.
  8. Finally, add a “when flag clicked” event to complete the script and initiate the servo control with the flex sensor.

OUTPUT

 

 

 

Read More
Learn about A force sensor, also known as a load cell or force transducer, is a device designed to measure the force or load applied to it.

Introduction

A force sensor, also known as a load cell or force transducer, is a device designed to measure the force or load applied to it. It’s used in various applications to quantify the magnitude of forces in different directions. Force sensors are utilized in fields such as engineering, manufacturing, robotics, healthcare, and more.

 

Circuit Diagram

 

Code

  1. Select “when flag clicked” from the event palette.
  2. Use the “forever” block from the control palette.
  3. Add the “if – else” block from the control palette.
  4. Read the analog sensor at A0 to obtain pressure readings.
  5. If the value of the analog sensor at A0 is greater than 200, set the output pin 13 to High.
  6. if the value of the analog sensor at A0 is less than 200, set the output pin 13 to Low.
  7. Now the script has been completed.

OUTPUT

 

Read More
Learn how to interface an MPU6050 accelerometer, a popular 6-axis accelerometer and gyroscope module, with Arduino
Introduction

Accelerometers are vital sensors used to measure acceleration in one, two, or three axes, finding applications in robotics, gaming, and motion-sensing projects. In this example, we will guide you through connecting an MPU6050 accelerometer, a widely available 6-axis accelerometer and gyroscope module, to an Arduino board.

Our goal is to interface the accelerometer with Arduino and determine the angular movements of an object along the x-axis and y-axis.

Circuit Diagram

Connection

  1. Connect sensor VCC to 5V of the Arduino
  2. GBD to Arduino GND
  3.  SCL  to A5 of the Arduino.
  4. SDA to A4 of the Arduino.
Code 
  1. Open PictoBlox and create a new file.
  2. Change the scripting mode from “stage” mode to “upload” mode.
  3. Click on the extension button and add the communication extension.
  4. From the Arduino palette, drag the “when Arduino starts up” block into the scripting area.
  5. click on communication extensions and drag  “set serial () baud rate to () ”  into the scripting area.
  6. Set the baud rate to 9600.
  7. From the controls palette, add the “forever” block.
  8. Since the sensor is connected to Arduino, communication is enabled. Now, to write/print information on the serial monitor, go to the communication palette, drag the “write () on serial ()” block, and put it inside the forever block.
  9. Insert the “join” block in place of “Hello World” from the operators palette.
  10. To find the angle along the x-axis, change “Apple” with “x =” and in place of “Banana,” add the “get () with weight constant ()” block and choose “filtered angle in x-axis.”
  11. Repeat the above steps for the y-axis
  12. Add a “wait” block to read the values clearly..
  13. Now, upload the code into the board and check for the output on the serial monitor.

 

Final Script 

 

Output

 

 

Read More
"Save Earth" and "Preserve Future" are two powerful messages that we will bring to life using Python with Pictoblox.

Introduction:

Welcome to the fascinating realm of Python Programming! In this world, we can create Python programs and save them as files with a .sb3 extension. To bring these programs to life, we’ll employ the Pictoblox interface for execution. In this particular program, we will be focusing on a simple task: printing a statement. Once our masterpiece is crafted and saved, a mere click of the [Run] button will set the script in motion, and the magic will unfold before our eyes. So, let’s dive in and embark on this exciting journey of Python programming!

Code:

print("Save Earth")
print("Preserve Future")

Logic:

The logic of the given Python code is quite straightforward. It consists of two separate `print` statements that each display a specific message on the screen:

1. `print(“Save Earth”)`: This line of code prints the message “Save Earth” to the console or output screen.

2. `print(“Preserve Future”)`: The second line of code prints the message “Preserve Future” to the console or output screen.

When this code is executed, the two messages will be displayed one after the other, as separate lines on the output screen, conveying the important messages: “Save Earth” and “Preserve Future.”

Output:

>> Save Earth

>> Preserve Future

Read More
Discover how to print messages like 'Keep Smiling' and user numbers in Python with this beginner-friendly code snippet

Introduction:

Discover Python’s simplicity and versatility in this code excerpt. Learn to print messages, like “Keep Smiling,” and display user numbers. Perfect for beginners, this foundational skill opens doors to more complex coding tasks. Engage users with Python’s readability and unlock its potential to convey meaningful messages and data. Start your journey today!

Code:

message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)

Logic:

  1. Declare a variable ‘message’ and assign the string value “Keep Smiling” to it.
  2. Use the ‘print’ function to display the value of the ‘message’ variable, which will output “Keep Smiling” to the console.
  3. Declare a variable ‘userNo’ and assign the integer value 101 to it.
  4. Use the ‘print’ function again to display the message “User Number is” followed by the value of the ‘userNo’ variable. This will output “User Number is 101” to the console.

Output:

In summary, this Python code sets a message as “Keep Smiling” and prints it, then sets a user number as 101 and prints it along with a custom message. The output will be:

>> Keep Smiling

>> User Number is 101

 

 

Read More
Learn how to find the area of a rectangle using Python with this simple code using the formula length * breadth.

Introduction:

Learn how to calculate the area of a rectangle with Python! Our code example shows you how to find the area by multiplying the length with the breadth. See the result for a given length of 10 and breadth of 20. Start mastering rectangle area calculations now!”

Code:

length = 10
breadth = 20
area = length * breadth
print(area)

Logic:

  1. Assign the value 10 to the variable “length” to represent the length of the rectangle.
  2. Assign the value 20 to the variable “breadth” to represent the breadth (width) of the rectangle.
  3. Calculate the area of the rectangle by multiplying the values of “length” and “breadth” and store the result in the variable “area.”
  4. Print the calculated area using the “print” function.

Output:

In summary, the code calculates the area of a rectangle with a length of 10 and breadth of 20 and displays the result, which would be 200.

>> 200

 

Read More
Learn how to find the sum of two numbers using Python with this straightforward code example. Add num1 and num2 to calculate the result.

Introduction:

Discover the Python magic of finding the sum of two numbers! This code snippet showcases how to add 10 and 20 (num1 and num2) effortlessly, resulting in the sum displayed as the output. Unlock the power of Python’s simple yet essential arithmetic operation with this concise and enlightening example.

Code:

num1 = 10
num2 = 20
result = num1 + num2
print(result)

Logic:

  1. Assign the value 10 to the variable “num1” to represent the first number.
  2. Assign the value 20 to the variable “num2” to represent the second number.
  3. Calculate the sum of the two numbers by adding the values of “num1” and “num2” together and store the result in the variable “result.”
  4. Print the calculated result using the “print” function.

Output:

In summary, the code adds the values of “num1” and “num2” (10 and 20, respectively) and displays the sum, which would be 30.

>> 30

 

Read More
Convert integer to a float using explicit type conversion which convert the result to a float, also check types before/after the conversion.

Introduction:

In Python, you can convert an integer to a float using explicit type conversion. This allows you to perform mathematical operations with integers and then convert the result to a float if needed. By doing so, you can work with decimal values and have more control over the precision of your calculations.

Code:

num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))

Logic:

The Python code provided demonstrates how to explicitly convert an integer to a float.

  1. It starts by defining two variables, “num1” and “num2,” and assigning them the values of 10 and 20, respectively.
  2. The next line adds “num1” and “num2” together, resulting in “num3.”
  3. The code then prints the value of “num3” and its type.
  4. To convert the sum to a float, the code assigns the result of “num1 + num2” to “num4” and explicitly converts it to a float using the “float()” function
  5. The code then prints the value of “num4” and its type.

Output:

>> 30

>> <class ‘int’>

>> 30.0

>> <class ‘float’>

 

Read More
Convert a float to an integer in Python using explicit type conversion. Explore output and the difference in data types after the conversion.

Introduction:

This Python code demonstrates how to convert a float to an integer using explicit type conversion. It showcases the difference in data types before and after the conversion.

Code:

num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))

Logic:

  1. The program assigns the values 10.2 and 20.6 to two float variables, num1 and num2 respectively.
  2. It then calculates the sum of num1 and num2 and assigns the result to num3.
  3. The program then prints the value of num3 and its data type.
  4. Next, the sum of num1 and num2 is converted to an integer using the int() function, and the resulting value is assigned to num4.
  5. Finally, the program prints the value of num4 and its data type.

Output:

>> 30.8

>> <class ‘float’>

>> 30

>> <class ‘int’>

Read More
Convert numbers and strings in Python. How to perform addition on numbers and concatenate strings to get the desired result.

Introduction:

This Python code demonstrates the process of type conversion between numbers and strings. It showcases how to add two numbers and concatenate a string to display the total price.

Code:

priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total is Rs." + totalPrice )

Logic:

1. The code defines two variables, priceIcecream and priceBrownie, with their respective values.

2. It then performs addition on these variables to calculate the total price.

3. Next, it uses string concatenation to display the result as a sentence.

Output:

The output of the code will be an error due to a type mismatch. To fix this, you need to convert the totalPrice variable to a string using the str() function.

#There will be one TypeError: can only concatenate str (not “int”) to str
#Failed to execute script ‘main’ due to unhandled exception!

Read More
Learn how to use explicit type casting in Python to calculate the total price by adding two price variables. Example code included

Introduction:

This Python code demonstrates the concept of explicit type casting. It calculates the total price by adding two price variables, priceIcecream and priceBrownie, and then converts the result to a string for display.

Code:

priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total in Rs." + str(totalPrice))

Logic:

  1. The code initializes two variables, priceIcecream and priceBrownie, with the respective prices.
  2. It then adds the two variables together and stores the result in the totalPrice variable.
  3. Finally, it converts the totalPrice to a string using the str() function and concatenates it with the string “The total in Rs.” to form the desired output.

Output:

>> The total in Rs.70

Read More
This Python code demonstrates explicit type conversion and string concatenation using the variables 'icecream' and 'brownie'.

Introduction:

This Python code showcases how to perform explicit type conversion and string concatenation. It uses the variables ‘icecream’ and ‘brownie’ to calculate the total price of both items.

Code:

#Explicit type conversion
icecream = '25'
brownie = '45'
#String concatenation
price = icecream + brownie
print("Total Price Rs." + price)
#Explicit type conversion - string to integer
price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))

Logic:

1. The code initializes two variables, ‘icecream’ and ‘brownie’, with string values representing the respective prices.
2. The code performs string concatenation using the ‘price’ variable, combining the values of ‘icecream’ and ‘brownie’.
3. The code then prints the total price in a formatted message.
4. Next, the code performs explicit type conversion by converting the values of ‘icecream’ and ‘brownie’ from strings to integers.
5. The code adds the converted values of ‘icecream’ and ‘brownie’ to calculate the total price as an integer.
6. The code converts the total price back to a string and concatenates it with the message to display the total price in a formatted message.

Output:

>> Total Price Rs.2545

>> Total Price Rs.70

Read More
All articles loaded
No more articles to load
Table of Contents
[PythonExtension]