Friday, February 17, 2023

ChatGPT Writes and Explains the Code line by line

ChatGPT Tutorial:

Use chatGPT to help with coding here is one example.

New Chat:

Write code in MicroPython to display temperature reading from internal sensor in celsius and fahrenheit on a SSD1306 display every second. Raspberry Pi Pico board.


Open THONNY IDE copy code from ChatGPT

main.py


import machine

import ssd1306

import utime


# Initialize the I2C bus and the SSD1306 display

i2c = machine.I2C(0, sda=machine.Pin(8), scl=machine.Pin(9), freq=400000)

oled = ssd1306.SSD1306_I2C(128, 32, i2c)


# Define a function to convert Celsius to Fahrenheit

def c_to_f(celsius):

    return (celsius * 1.8) + 32

while True:

    # Read the temperature from the internal sensor

    temp_celsius = machine.ADC(4).read_u16() * 3.3 / 65535 * 100 - 50

    temp_fahrenheit = c_to_f(temp_celsius)

    

    # Clear the display and print the temperature readings

    oled.fill(0)

    oled.text("Temp (C): {:.1f}".format(temp_celsius), 0, 0)

    oled.text("Temp (F): {:.1f}".format(temp_fahrenheit), 0, 10)

    oled.show()

    

    # Wait for 1 second before reading the temperature again

    utime.sleep(1)


ChatGPT explaines the code:


MicroPython code that reads the temperature from the internal sensor and displays it on an SSD1306 OLED display. The code uses the ADC (Analog-to-Digital Converter) to read the temperature and converts it from Celsius to Fahrenheit using the c_to_f function. The temperature readings are then displayed on the OLED display using the oled.text method.

The main loop of the code continuously reads the temperature and updates the display every second using the utime.sleep function.

Here's a step-by-step breakdown of what the code does:

  1. Import the necessary modules:

import machine

import ssd1306

import utime

  1. Initialize the I2C bus and the SSD1306 display:
i2c = machine.I2C(0, sda=machine.Pin(8), scl=machine.Pin(9), freq=400000)

oled = ssd1306.SSD1306_I2C(128, 32, i2c)

  1. Define a function to convert Celsius to Fahrenheit:

def c_to_f(celsius):

    return (celsius * 1.8) + 32

  1. Enter the main loop:
while True:
  1. Read the temperature from the internal sensor using the ADC:
 temp_celsius = machine.ADC(4).read_u16() * 3.3 / 65535 * 100 - 50
  1. Convert the temperature from Celsius to Fahrenheit using the c_to_f function:
 temp_fahrenheit = c_to_f(temp_celsius)
  1. Clear the OLED display using the oled.fill method:
oled.fill(0)
  1. Print the temperature readings on the OLED display using the oled.text method:

oled.text("Temp (C): {:.1f}".format(temp_celsius), 0, 0)

    oled.text("Temp (F): {:.1f}".format(temp_fahrenheit), 0, 10)

  1. Update the OLED display using the oled.show method:
oled.show()
  1. Wait for 1 second before reading the temperature again using the utime.sleep function:
utime.sleep(1)


Pinouts for SSD1306 and Raspberry Pico:











Monday, February 13, 2023

4 Digit TM1637 Display Module For Raspberry Pico

4 Digit Display Module

TM1637 is a chip commonly used to drive 7-segment LED displays and other types of digital displays. It communicates with microcontrollers using a 2-wire interface, and supports various functions such as setting brightness and displaying decimal points.

Pinouts :

  1. CLK
  2. DIO
  3. VCC
  4. GND



Saturday, February 11, 2023

Raspberry Pico W TM1637 display and JSON object

Raspberry Pico W project shows Bitcoin value on TM1637 display from JSON object.  

TM1637 LED 7-segment display you need the tm1627 library. Download it from Thonny plug-ins.

Code in MicroPython Thonny IDE

Data from a JSON object stored in the response variable. The json() method of the response object is used to parse the JSON data and convert it into a MicroPython dictionary.

JSON object:

The value of the "USD" rate is then being accessed using the following line of code: data["bpi"]["USD"]["rate_float"]. This line accesses the "bpi" key of the dictionary, then accesses the "USD" key within that dictionary, and finally accesses the "rate_float" key within the "USD" dictionary. The resulting value is stored in the price variable.

Create a new script by clicking the new button on Thonny IDE. Copy and paste the following code.

CODE secrets.py

SSD="SSID" PASS="PASSWORD"

Replace SSID and PASSWORD with your own Wi-Fi credentials.


CODE main.py

import network

import utime

from machine import I2C, Pin

import tm1637 

import secrets

import time

import urequests


led = machine.Pin("LED", machine.Pin.OUT)


wlan = network.WLAN(network.STA_IF)

wlan.active(True)

wlan.connect(secrets.SSD, secrets.PASS)

print(wlan.isconnected())


# Get the current Bitcoin price

def get_price():

    url = "https://api.coindesk.com/v1/bpi/currentprice/BTC.json"

    response = urequests.get(url)

    data = response.json()

    price = data["bpi"]["USD"]["rate_float"]

    return price


def round_to_even(n):

    if n % 2 == 0.5:

        return round(n) + 1 if round(n) % 2 == 1 else round(n)

    return round(n)


display = tm1637.TM1637(clk=Pin(0), dio=Pin(1)) # put the right pins


while True:

    price = get_price()

    result = round_to_even(price)

    if price is None:

        for i in range(3):

            led.value(not led.value())

            utime.sleep(0.5)

    else:

       led.value(1)

       print(result) # print result in Shell

       display.scroll(str(result))

       time.sleep(20)


Raspberry Pico W Pinouts and TM1637





Wednesday, February 8, 2023

BME280 temperature,pressure and humidity sensor

BME280 is an integrated sensor that combines measurements of temperature, humidity, and pressure.

It's often used in IoT and wearable devices for weather monitoring. The BME280 is based on a MEMS sensor, which allows for compact and low-power measurements. The device communicates with other systems using I2C or SPI interfaces.



Input voltage: 1.8 - 5V DC
Interface: I2C (up to 3.4 MHz), SPI (up to 10 MHz)

 

Area of operation:
- Temperature: -40 to +85°C
- Humidity: 0-100%
- Pressure: 300-1100 hPa
Resolution:
- Temperature: 0.01°C
- Moisture: 0.008%
- Pressure: 0.18 Pa
Accuracy:
- Temperature: +-1°C
- Humidity: +-3%
- Pressure: +-1Pa
I2C address
SDO LOW: 0x76
SDO HIGH: 0x77






Monday, February 6, 2023

Raspberry Pico Project Data Logger

Raspberry Pi Pico demo project data logger.

Battery power for Raspberry Pico , battery 18650 shield BME280 temperature and pressure sensor and start button You need BME280 library in MicroPython Thonny IDE.

Code:

from machine import Pin, I2C 
import time
import BME280 

# PICO - Pins
sda=machine.Pin(16)
scl=machine.Pin(17)
i2c=machine.I2C(0,sda=sda, scl=scl, freq=400000)

led1 = Pin(25, Pin.OUT)
button_start = Pin(2, Pin.IN, Pin.PULL_DOWN) # Start button

# Data logging time in seconds
LOGt = 600 
 
# Data logging interval in seconds 
LOGi = 10

i=0

while button_start.value() == 0:
    led1.value(0) # Board led off 
else:
    tpfile=open("TempPres.txt","w")  # w Opens a file for writing only and will create a new file       

    while i < (LOGt/LOGi):
         led1.value(1) # Board led on          
         bme = BME280.BME280(i2c=i2c)
         temp = bme.temperature
  ##     hum = bme.humidity  No humidity in BMP280
         pres = bme.pressure
  ##   tempf temperature in Fahrenheit
  ##     tempf = (bme.read_temperature()/100) * (9/5) + 32
  ##     tempf = str(round(tempf, 2)) + 'F'
  ##     print('Temperature:', temp ,tempf, '  Pressure: ',pres)  
  ##     print('Humidity: ', hum)
     
         tpfile.write(str(temp + ' , ' + pres) + "\n")
         tpfile.flush()
  
         time.sleep(LOGi)
         i += 1
              
         led1.value(0) # Board led off
  




Thonny shell use for open the file file=open("TempPres.txt") print (file.read())

Pinouts for the project:







Sunday, February 5, 2023

ChatGPT writes MicroPython code for Raspberry Pi PicoW

See how ChatGPT writes MicroPython code for Raspberry Pi Pico W

ChatGPT is a language model developed by OpenAI, which is capable of generating text based on a given prompt.

Test text for ChatGPT:

Write code in micropython Thonny for Raspberry pi Pico W with sensor BME280 and web server print IP, with homepage for temperature, pressure and humidity.


ChatGPT code:

from machine import I2C, Pin

import bme280 import network import usocket as socket i2c = I2C(0,scl=Pin(1), sda=Pin(0)) # put the right pins bme = bme280.BME280(i2c=i2c) def get_temp(): return bme.temperature def get_pressure(): return bme.pressure def get_humidity(): return bme.humidity def get_html(): html = """<html> <head> <title>Raspberry Pi Pico W with BME280</title> </head> <body> <h1>Temperature: {} C</h1> <h1>Pressure: {} hPa</h1> <h1>Humidity: {} %</h1> </body> </html> """.format(get_temp(), get_pressure(), get_humidity()) return html def main(): sta_if = network.WLAN(network.STA_IF) sta_if.active(True) sta_if.connect("<SSID>", "<Password>")

# Replace <SSID> and <PASSWORD> with your own Wi-Fi credentials.

print("Connected to network with IP: {}".format(sta_if.ifconfig()[0])) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 80)) s.listen(5) while True: conn, addr = s.accept() print("Got a connection from %s" % str(addr)) request = conn.recv(1024) request = str(request) print("Content = %s" % request) response = get_html() conn.send("HTTP/1.1 200 OK\n") conn.send("Content-Type: text/html\n") conn.send("Connection: close\n\n") conn.sendall(response) conn.close() main()



Raspberry Pi Pico W Pinouts

I2C communication

GO0 = SDA GP1 = SCL
GND and 3V3(OUT)



Demo project video:










Friday, February 3, 2023

Raspberry Pico and I2C Communication Oled Display SSD1306 and sensor BME280

Raspberry Pi Pico project demo I2C serial communication.

Oled display SSD1306 128x64 and sensor BME280 in same bus.
Thonny micropython code and bus scan address command on the shell.

SCL (Serial Clock Line) and SDA (Serial Data Line) are two of the most important signals used in the Inter-Integrated Circuit (I2C) communication protocol.
I2C is a popular communication protocol used for short-distance communication between microcontrollers, sensors, and other peripherals in embedded systems.

Thonny sample code: from machine import Pin, I2C from time import sleep from ssd1306 import SSD1306_I2C import BME280 i2c = I2C(0,sda=Pin(0), scl=Pin(1), freq=400000) oled = SSD1306_I2C(128,64,i2c) ## Oled Display pixel size 128x64 oled.fill(0) while True: bme = BME280.BME280(i2c=i2c) temp = bme.temperature ## hum = bme.humidity No humidity in BMP280 pres = bme.pressure ## tempf temperature in Fahrenheit tempf = (bme.read_temperature()/100) * (9/5) + 32 tempf = str(round(tempf, 2)) + 'F' ##print('Temperature:', temp ,tempf, ' Pressure: ',pres) ##print('Humidity: ', hum) oled.fill(0) oled.text("TEMPERATURE",20,0) oled.text(temp, 20,15) ### tempf Farenheit oled.text("PRESSURE",20,35) oled.text(pres, 20,50) oled.show() sleep(0.3)

Thursday, February 2, 2023

BH1750 light sensor

Common module used in Raspberry Pico

The BH1750 is a digital ambient light sensor device that measures the intensity of light in lux units. It uses an I2C interface to communicate with microcontrollers and is often used in lighting control systems, display dimming, and various other applications that require ambient light sensin



Oled Display SSD1306

Common module

The SSD1306 is OLED display controller integrated circuit, commonly used in small electronic devices and displays. It´s used to drive small OLED displays 128x64 and provides an I2C interface for communication. It´s commonly used in small projects.