Posted on Leave a comment

How to Generate Combinations of the Component from Four Text Files using Python & tkinter

This program generates a random combination of components. This can be a fun program.
It creates the combination of all the components in the four list.

For example; if each list contains 5 words. Then the total number of combinations would be 5 x 5 x 5 x 5 = 625

Code

import random
import tkinter as tk
from tkinter import messagebox
import itertools
import webbrowser


# Create the GUI window
window = tk.Tk()
window.title("List Shuffler")

# Create the text boxes for file names
micros_textbox = tk.Entry(window, width=50)
micros_textbox.insert(0, "micros.txt")
micros_textbox.grid(row = 0, column = 0, pady = 5)

sensors_textbox = tk.Entry(window, width=50)
sensors_textbox.insert(0, "sensor.txt")
sensors_textbox.grid(row = 1, column = 0, pady = 5)

inputs_textbox = tk.Entry(window, width=50)
inputs_textbox.insert(0, "inputs.txt")
inputs_textbox.grid(row = 2, column = 0, pady = 5)

displays_textbox = tk.Entry(window, width=50)
displays_textbox.insert(0, "displays.txt")
displays_textbox.grid(row = 3, column = 0, pady = 5)

# Create the label for the result
result_label = tk.Text(window, height=10, width=50)
result_label.grid(row = 0, column = 1,rowspan = 5, pady = 5)

# Define the function to shuffle the lists
def shuffle_lists():
    # Open the first file and read in its contents
    with open(micros_textbox.get(), "r") as f:
        A = f.read().splitlines()

    # Open the second file and read in its contents
    with open(sensors_textbox.get(), "r") as f:
        B = f.read().splitlines()

    # Open the third file and read in its contents
    with open(inputs_textbox.get(), "r") as f:
        C = f.read().splitlines()

    with open(displays_textbox.get(), "r") as f:
        D = f.read().splitlines()

    # Shuffle the lists
    random.shuffle(A)
    random.shuffle(B)
    random.shuffle(C)
    random.shuffle(D)

    # Select one item from each list and combine them into a string
    result = A[0] + " + " + B[0] + " + " + C[0] + " + " + D[0] +"\n\n"

    # Update the label with the result
    result_label.insert(tk.INSERT,result)
def generate_combinations():
    # Open the first file and read in its contents
    with open(micros_textbox.get(), "r") as f:
        A = f.read().splitlines()

    # Open the second file and read in its contents
    with open(sensors_textbox.get(), "r") as f:
        B = f.read().splitlines()

    # Open the third file and read in its contents
    with open(inputs_textbox.get(), "r") as f:
        C = f.read().splitlines()

    with open(displays_textbox.get(), "r") as f:
        D = f.read().splitlines()

    # Get all the combinations of the lists
    combinations = list(itertools.product(A, B, C, D))

    # Write the combinations to a text file
    with open("combinations.txt", "w") as f:
        for combination in combinations:
            f.write(' + '.join(combination) + "\n")

    # Show a message box with the number of combinations generated
    messagebox.showinfo("Combinations Generated", f"{len(combinations)} combinations were generated and saved to combinations.txt.")


# Create the button to shuffle the lists
shuffle_button = tk.Button(window, text="Shuffle", command=shuffle_lists)
shuffle_button.grid(row = 4, column = 0, pady = 5)
# Add a button to generate the combinations
generate_button = tk.Button(window, text="Generate Combinations", command=generate_combinations)
generate_button.grid(row = 5, column = 0, pady = 5)

def open_website():
    webbrowser.open_new("http://www.exasub.com")

link_label = tk.Label(window, text="exasub.com", font=("Arial", 14), fg="blue", cursor="hand2")
link_label.grid(row=6, column=0, pady=10)
link_label.bind("<Button-1>", lambda event: open_website())
# Run the GUI
window.mainloop()
Posted on Leave a comment

How to setup NodeMCU on Arduino IDE

NodeMCU is an open-source firmware and development board that is based on the ESP8266 Wi-Fi module. It is a popular platform for Internet of Things (IoT) projects due to its low cost, ease of use, and versatility. In this article, we will discuss how to set up NodeMCU on Arduino IDE.

Step 1: Install Arduino IDE
The first step is to install the Arduino IDE on your computer. You can download the latest version of Arduino IDE from the official website https://www.arduino.cc/en/software. Choose the appropriate version for your operating system and follow the installation instructions.

Step 2: Install ESP8266 Board Manager
After installing the Arduino IDE, you need to install the ESP8266 board manager. This is necessary to add the support for NodeMCU to the Arduino IDE.

To do this, open the Arduino IDE and go to File > Preferences. In the Additional Boards Manager URLs field, paste the following URL:

http://arduino.esp8266.com/stable/package_esp8266com_index.json

Click OK and go to Tools > Board > Boards Manager. In the search box, type “esp8266” and select the “esp8266” board by ESP8266 Community. Click Install.

Step 3: Select the NodeMCU Board
After the installation of the ESP8266 board manager is complete, go to Tools > Board and select “NodeMCU 1.0 (ESP-12E Module)”.

Step 4: Select the Port
Next, you need to select the port to which the NodeMCU is connected. Go to Tools > Port and select the appropriate port.

Step 5: Upload Your Sketch
Now, you are ready to upload your sketch to the NodeMCU. In the Arduino IDE, click on File > New to create a new sketch. Write your code and then click on the Upload button to upload the sketch to the NodeMCU.

Step 6: Verify Upload
Once the upload is complete, you can verify that the sketch has been successfully uploaded by opening the Serial Monitor. Go to Tools > Serial Monitor and set the baud rate to 115200. If everything is working properly, you should see the output from your sketch in the Serial Monitor.

Posted on Leave a comment

How to setup C/C++ SDK of Raspberry Pi Pico W On Raspberry Pi Model 3b+

The C/C++ SDK has development tools for both development boards.

There are various methods of the SDK. You can use this in Windows, MAC etc.
But the easiest and simplest method is the use of Raspberry Pi itself.

Step 1: Follow Chapter 1 of the Getting Started with Raspberry Pi Pico https://datasheets.raspberrypi.com/pico/getting-started-with-pico.pdf

Step 2: Follow Chapter 8: Creating your own project
copy the files from pico W folder, which you will find under the pico-examples folder. The blink project will be under the wifi folder.

Step 3: add the following line to your CMakeLists.text file

set(PICO_BOARD pico_w)

Sample CMakeLists.text

cmake_minimum_required(VERSION 3.13)
include(pico_sdk_import.cmake)
project(test_project C CXX ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
set(PICO_BOARD pico_w)
pico_sdk_init()
add_executable(test
test.c
)
pico_enable_stdio_usb(test 1)
pico_enable_stdio_uart(test 0)
pico_add_extra_outputs(test)

target_link_libraries(test 
					pico_stdlib
					pico_cyw43_arch_none
					)

NOTE: you can set the pico board to pico w. when you issue cmake ..
Only use one method of setting the pico w board.

cmake -DPICO_BOARD=pico_w ..
Posted on Leave a comment

How to view PDF in Raspberry Pi model 3b+

Both Okular and QPDF are great PDF viewers that can be used on a Raspberry Pi Model 3b+. Okular is a graphical application that is easy to use and has a wide range of features, while QPDF is a command-line tool that is lightweight and can be used to quickly view PDF files. Regardless of which tool you choose, both are easy to install and use on your Raspberry Pi Model 3b+.

Okular

Okular is a free and open-source document viewer developed by the KDE community. It is known for its ability to handle a wide range of document formats, including PDF, EPUB, and MOBI. To install Okular on your Raspberry Pi Model 3b+, follow these steps:

  1. Open a terminal window on your Raspberry Pi Model 3b+.
  2. Type the following command to update the package list:
sudo apt-get update
  1. Type the following command to install Okular:
sudo apt-get install okular

Once Okular is installed, you can use it to open PDF files by right-clicking on the file and selecting “Open With” -> “Okular”. Alternatively, you can open Okular from the Applications menu and then select “File” -> “Open” to browse for your PDF file.

QPDF

QPDF is another popular PDF viewer for Raspberry Pi Model 3b+. It is a command-line tool that can be used to manipulate and view PDF files. To install QPDF on your Raspberry Pi Model 3b+, follow these steps:

  1. Open a terminal window on your Raspberry Pi Model 3b+.
  2. Type the following command to update the package list:
sudo apt-get update
  1. Type the following command to install QPDF:
sudo apt-get install qpdf

Once QPDF is installed, you can use it to view PDF files by typing the following command in the terminal: qpdf –qdf <filename>.pdf

Posted on Leave a comment

Functions in MicroPython on Raspberry Pi Pico

Functions are a way to make your code more organized and easier to understand. They are like little machines that you can use over and over again in your code.

To create a function, you need to give it a name and then write what it does. You can also give it some inputs, like numbers or strings, that it will use to do its job.

For example, imagine you wanted to make a function that adds two numbers together. You could call it “add” and write the code like this:

def add(num1, num2):
    result = num1 + num2
    return result

Now, whenever you want to add two numbers together, you can just call the “add” function and give it the two numbers you want to add:

result = add(5, 7)

The “add” function will take those two numbers, add them together, and then return the result, which you can store in a variable called “result”.

Functions are really helpful because they can make your code shorter, easier to read, and easier to test.

Examples to try

Here are some more examples of functions in MicroPython on Raspberry Pi Pico:

Example 1: Adding Two Numbers

def add_numbers(a, b):
    result = a + b
    return result

# Test the function
print(add_numbers(2, 3)) # Output: 5
print(add_numbers(5, 10)) # Output: 15

Example 2: Counting Even Numbers

def count_even_numbers(numbers):
    count = 0
    for num in numbers:
        if num % 2 == 0:
            count += 1
    return count

# Test the function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(count_even_numbers(numbers)) # Output: 5

Example 3: Finding the Maximum Number in a List

def find_max(numbers):
    max_num = numbers[0]
    for num in numbers:
        if num > max_num:
            max_num = num
    return max_num

# Test the function
numbers = [3, 9, 2, 5, 1, 8, 4, 7, 6]
print(find_max(numbers)) # Output: 9
Posted on Leave a comment

How to interface 0.96″ OLED display with Raspberry Pi Pico without library using I2C in Micropython

The 0.96-inch OLED screen is monochromatic blue. Which means it has only blue light. You can either switch on the led to make the text blue or you can invert the in which background is blue and the text black.

The OLED uses a ssd1306 IC. Which is a 128 x 64 Dot Matrix OLED/PLED Segment/Common Driver with Controller.

The code written does not need any library to be installed.

I made the following connections

OLED		RPI Pico

SDA	->	RP0
SCK	->	RP1
VDD	->	3v3
GND	->	GND
		
Note: RP0 and RP1 are pin number 0 and 1 on the pico develeopment board.

Code

# MicroPython SSD1306 OLED driver, I2C and SPI interfaces
import machine
import time
import framebuf
import utime

# register definitions
SET_CONTRAST        = const(0x81)
SET_ENTIRE_ON       = const(0xa4)
SET_NORM_INV        = const(0xa6)
SET_DISP            = const(0xae)
SET_MEM_ADDR        = const(0x20)
SET_COL_ADDR        = const(0x21)
SET_PAGE_ADDR       = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP       = const(0xa0)
SET_MUX_RATIO       = const(0xa8)
SET_COM_OUT_DIR     = const(0xc0)
SET_DISP_OFFSET     = const(0xd3)
SET_COM_PIN_CFG     = const(0xda)
SET_DISP_CLK_DIV    = const(0xd5)
SET_PRECHARGE       = const(0xd9)
SET_VCOM_DESEL      = const(0xdb)
SET_CHARGE_PUMP     = const(0x8d)


class SSD1306:
    def __init__(self, width, height, external_vcc):
        self.width = width
        self.height = height
        self.external_vcc = external_vcc
        self.pages = self.height // 8
        # Note the subclass must initialize self.framebuf to a framebuffer.
        # This is necessary because the underlying data buffer is different
        # between I2C and SPI implementations (I2C needs an extra byte).
        self.poweron()
        self.init_display()

    def init_display(self):
        for cmd in (
            SET_DISP | 0x00, # off
            # address setting
            SET_MEM_ADDR, 0x00, # horizontal
            # resolution and layout
            SET_DISP_START_LINE | 0x00,
            SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
            SET_MUX_RATIO, self.height - 1,
            SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
            SET_DISP_OFFSET, 0x00,
            SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
            # timing and driving scheme
            SET_DISP_CLK_DIV, 0x80,
            SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
            SET_VCOM_DESEL, 0x30, # 0.83*Vcc
            # display
            SET_CONTRAST, 0xff, # maximum
            SET_ENTIRE_ON, # output follows RAM contents
            SET_NORM_INV, # not inverted
            # charge pump
            SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
            SET_DISP | 0x01): # on
            self.write_cmd(cmd)
        self.fill(0)
        self.show()

    def poweroff(self):
        self.write_cmd(SET_DISP | 0x00)

    def contrast(self, contrast):
        self.write_cmd(SET_CONTRAST)
        self.write_cmd(contrast)

    def invert(self, invert):
        self.write_cmd(SET_NORM_INV | (invert & 1))

    def show(self):
        x0 = 0
        x1 = self.width - 1
        if self.width == 64:
            # displays with width of 64 pixels are shifted by 32
            x0 += 32
            x1 += 32
        self.write_cmd(SET_COL_ADDR)
        self.write_cmd(x0)
        self.write_cmd(x1)
        self.write_cmd(SET_PAGE_ADDR)
        self.write_cmd(0)
        self.write_cmd(self.pages - 1)
        self.write_framebuf()

    def fill(self, col):
        self.framebuf.fill(col)

    def pixel(self, x, y, col):
        self.framebuf.pixel(x, y, col)

    def scroll(self, dx, dy):
        self.framebuf.scroll(dx, dy)

    def text(self, string, x, y, col=1):
        self.framebuf.text(string, x, y, col)


class SSD1306_I2C(SSD1306):
    def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
        self.i2c = i2c
        self.addr = addr
        self.temp = bytearray(2)
        # Add an extra byte to the data buffer to hold an I2C data/command byte
        # to use hardware-compatible I2C transactions.  A memoryview of the
        # buffer is used to mask this byte from the framebuffer operations
        # (without a major memory hit as memoryview doesn't copy to a separate
        # buffer).
        self.buffer = bytearray(((height // 8) * width) + 1)
        self.buffer[0] = 0x40  # Set first byte of data buffer to Co=0, D/C=1
        self.framebuf = framebuf.FrameBuffer1(memoryview(self.buffer)[1:], width, height)
        super().__init__(width, height, external_vcc)

    def write_cmd(self, cmd):
        self.temp[0] = 0x80 # Co=1, D/C#=0
        self.temp[1] = cmd
        self.i2c.writeto(self.addr, self.temp)

    def write_framebuf(self):
        # Blast out the frame buffer using a single I2C transaction to support
        # hardware I2C interfaces.
        self.i2c.writeto(self.addr, self.buffer)

    def poweron(self):
        pass







i2c = machine.SoftI2C(scl=machine.Pin(1), sda=machine.Pin(0))

pin = machine.Pin(16, machine.Pin.OUT)
pin.value(0) #set GPIO16 low to reset OLED
pin.value(1) #while OLED is running, must set GPIO16 in high

oled_width = 128
oled_height = 64
oled = SSD1306_I2C(oled_width, oled_height, i2c)

oled.fill(0)
oled.text('hallo, ', 0, 0)
oled.text('exasub.com!', 0, 10)
def toggle(i):
    if i == 0:
        i = 1
    else:
        i = 0
    return i

i=0

while True:
    i = toggle(i)
    oled.invert(i)
    oled.show()
    utime.sleep(1)
    


Posted on 1 Comment

Using Loops to Iterate Over Data Structures in MicroPython on Raspberry Pi Pico

MicroPython on Raspberry Pi Pico provides several data structures for storing and manipulating data. These include lists, tuples, sets, and dictionaries. Loops are a powerful tool for iterating over these data structures and performing operations on their elements.

Let’s take a look at some examples of how loops can be used to iterate over data structures in MicroPython.

  1. Iterating over a List

A list is a collection of items, and we can iterate over it using a for loop. Here’s an example:

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Iterate over the list and print each number
for number in numbers:
    print(number)

In this example, we create a list of numbers and then iterate over it using a for loop. For each number in the list, we print it to the console.

  1. Iterating over a Tuple

A tuple is similar to a list, but it is immutable, which means it cannot be modified once it is created. Here’s an example of how to iterate over a tuple using a for loop:

# Create a tuple of fruits
fruits = ('apple', 'banana', 'cherry')

# Iterate over the tuple and print each fruit
for fruit in fruits:
    print(fruit)

In this example, we create a tuple of fruits and then iterate over it using a for loop. For each fruit in the tuple, we print it to the console.

  1. Iterating over a Set

A set is an unordered collection of unique items. We can iterate over a set using a for loop just like we do with lists and tuples. Here’s an example:

# Create a set of colors
colors = {'red', 'green', 'blue'}

# Iterate over the set and print each color
for color in colors:
    print(color)

In this example, we create a set of colors and then iterate over it using a for loop. For each color in the set, we print it to the console.

  1. Iterating over a Dictionary

A dictionary is a collection of key-value pairs. We can iterate over a dictionary using a for loop, but we need to use the items() method to access both the keys and values. Here’s an example:

# Create a dictionary of students and their grades
grades = {'Alice': 85, 'Bob': 90, 'Charlie': 95}

# Iterate over the dictionary and print each student and their grade
for student, grade in grades.items():
    print(f'{student}: {grade}')

In this example, we create a dictionary of students and their grades and then iterate over it using a for loop. For each student and their corresponding grade, we print them to the console.

Posted on Leave a comment

Loop Control Statements in MicroPython on Raspberry Pi Pico

Loop control statements are used to alter the normal flow of execution within loops. They can be used to skip iterations or terminate loops prematurely based on certain conditions. In MicroPython on Raspberry Pi Pico, there are three loop control statements: break, continue, and pass.

  1. Break statement:
    The break statement is used to terminate a loop prematurely. When a break statement is encountered within a loop, the loop is immediately exited and program execution continues with the statement immediately following the loop. The break statement can be used with both for and while loops.

Here’s an example:

for i in range(1, 11):
    if i == 5:
        break
    print(i)

In this example, the loop will iterate over the values from 1 to 10. However, when i equals 5, the break statement is encountered and the loop is terminated prematurely. As a result, only the values from 1 to 4 will be printed.

  1. Continue statement:
    The continue statement is used to skip the current iteration of a loop and move on to the next iteration. When a continue statement is encountered within a loop, the remaining statements within the loop for that iteration are skipped and the loop moves on to the next iteration. The continue statement can be used with both for and while loops.

Here’s an example:

for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(i)

In this example, the loop will iterate over the values from 1 to 10. However, when i is even, the continue statement is encountered and the remaining statements for that iteration are skipped. As a result, only the odd values from 1 to 10 will be printed.

  1. Pass statement:
    The pass statement is used to do nothing. It can be used as a placeholder when a statement is required syntactically, but no action is needed. The pass statement is typically used when a block of code is not yet implemented but is required for the program to run without error.

Here’s an example:

for i in range(1, 11):
    pass

In this example, the loop will iterate over the values from 1 to 10. However, the pass statement does nothing, so the loop will simply run through all iterations without doing anything. The pass statement can be used with both for and while loops.

Loop control statements are a useful tool in programming, as they allow us to alter the normal flow of execution within loops based on certain conditions. The break statement can be used to terminate a loop prematurely, the continue statement can be used to skip the current iteration and move on to the next iteration, and the pass statement can be used as a placeholder when no action is needed.

Sure, here is an example of how you can use continue, pass, and break statements in a loop:

# Example of using loop control statements in MicroPython

# Loop from 1 to 10
for i in range(1, 11):
    # If i is even, skip to the next iteration
    if i % 2 == 0:
        continue

    # If i is 5, do nothing and continue to the next iteration
    if i == 5:
        pass

    # If i is greater than 8, break out of the loop
    if i > 8:
        break

    # Print the value of i
    print(i)

In this example, the continue statement is used to skip over even numbers in the loop. The pass statement is used to do nothing and simply continue to the next iteration when the value of i is 5. Finally, the break statement is used to exit the loop when the value of i becomes greater than 8.

When you run this code, you will see the following output:

1
3
7

As you can see, the even numbers (2, 4, 6, 8, and 10) are skipped over with the continue statement. The value of 5 does nothing with the pass statement, and the loop stops when the value of i reaches 9 because of the break statement.

Posted on Leave a comment

Nested Loops in MicroPython on Raspberry Pi Pico

Nested loops in MicroPython on Raspberry Pi Pico refer to the use of one loop inside another loop. The inner loop is executed multiple times for each iteration of the outer loop. This technique is useful when we want to perform repetitive tasks or calculations on a set of data.

To create nested loops in MicroPython on Raspberry Pi Pico, we simply need to place one loop inside another loop. Here’s an example:

for i in range(3):
    for j in range(2):
        print(i, j)

In this example, we have an outer loop that iterates from 0 to 2, and an inner loop that iterates from 0 to 1. For each iteration of the outer loop, the inner loop is executed twice. The output of this code would be:

0 0
0 1
1 0
1 1
2 0
2 1

We can also use nested loops to access and modify elements of a two-dimensional list or array. Here’s an example:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for element in row:
        print(element)

In this example, we have a two-dimensional list called matrix. The outer loop iterates over each row of the matrix, while the inner loop iterates over each element in the current row. The output of this code would be:

1
2
3
4
5
6
7
8
9

Nested loops can also be used to perform more complex calculations or operations.

Posted on Leave a comment

For Loops in MicroPython on Raspberry Pi Pico

For loops are one of the most commonly used loops in programming, including MicroPython on Raspberry Pi Pico. They allow you to repeat a set of instructions a specific number of times, making your code more efficient and concise.

In MicroPython, a for loop is used to iterate over a sequence of values, such as a list, tuple, or string. The general syntax for a for loop in MicroPython is as follows:

for variable in sequence:
    # Code to execute for each item in the sequence

Here, variable is a temporary variable that takes on the value of each item in the sequence. The code block under the for statement is executed for each item in the sequence, with variable taking on the value of each item in turn.

For example, let’s say we have a list of numbers and we want to print each number in the list:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)

In this code, num takes on the value of each item in the numbers list, and the print statement outputs each number in turn.

In addition to lists, for loops can also be used with other sequences such as tuples and strings. For example:

name = "John"

for char in name:
    print(char)

This code outputs each character in the string name, one character per line.

You can also use the built-in range() function with for loops in MicroPython. The range() function returns a sequence of numbers starting from 0 (by default) and incrementing by 1, up to a specified number. For example:

for i in range(5):
    print(i)

This code outputs the numbers 0 through 4, one number per line.

You can also specify a starting value and a step size for the range() function. For example:

for i in range(1, 10, 2):
    print(i)

This code outputs the odd numbers from 1 to 9, one number per line.