I bought the printer from wol3d’s New Delhi office. I am a electronics guy but i have inclination towards the 3d printing world. The feeling that you can design and make something in front of you. It’s a slow process but this printer comes with a slicer software which is fast.
Build Volume : 220 x 220 x 240 mm
The best thing is the auto bed leveling on this printer. I do not have to adjust the four corner bolts and rub a paper under the nozzle. It is done automatically done.
Till now the results are amazing.
I have noticed that the prints depends upon a lot of things:
Filament Quality : I have used a few filaments samples i got my hand on they were old and new. The old one which are above one year old open packet are just brittle they clog the printer every now and then. and one time it was so break while in the extruder which set my heart racing as i don’t want new printer to clog and change its nozzle. Thankfully the nozzle clogged removed when i inserted the fresh PLA and forced it into the extruder. So yes always use new filament. And also some filament are bad weather they are new or old.
Kartoffeln Bockshornkleeblätter Rezept auf Deutsch
Zutaten:
Kartoffeln (Aloo) – 3 mittelgroße, geschält und in kleine Würfel geschnitten
Bockshornkleeblätter (Methi) – 2 Tassen, frisch und gehackt
Öl – 2-3 Esslöffel
Kreuzkümmelsamen (Jeera) – 1 Teelöffel
Asafoetida (Hing) – eine Prise (optional)
Grüne Chilis – 2, fein gehackt (je nach Geschmack anpassen)
Knoblauch – 3-4 Zehen, gehackt (optional, aber geschmackvoll)
Korianderpulver (Dhaniya) – 1 Teelöffel
Salz – nach Geschmack
Anleitung:
Bockshornkleeblätter vorbereiten: Die Bockshornkleeblätter gründlich waschen, um Schmutz zu entfernen, und fein hacken. Beiseitestellen.
Öl erhitzen: Öl in einer Pfanne oder einem Topf bei mittlerer Hitze erhitzen.
Gewürze hinzufügen: Kreuzkümmelsamen in das heiße Öl geben und anbraten, bis sie anfangen zu knistern. Optional Asafoetida hinzufügen.
Knoblauch und Chilis anbraten: Gehackten Knoblauch und grüne Chilis dazugeben. Anbraten, bis der Knoblauch goldbraun wird.
Kartoffeln kochen: Die gewürfelten Kartoffeln hinzufügen. Gut vermischen und mit Korianderpulver würzen. Alles gleichmäßig vermengen.
Abdecken und kochen: Die Pfanne abdecken und die Kartoffeln bei niedriger bis mittlerer Hitze etwa 7-10 Minuten kochen lassen. Gelegentlich umrühren, damit nichts anbrennt.
Bockshornkleeblätter hinzufügen: Sobald die Kartoffeln halb gar sind, die gehackten Bockshornkleeblätter hinzufügen. Gut vermischen.
Zusammen kochen: Wieder abdecken und weitere 5-7 Minuten kochen lassen, dabei gelegentlich umrühren, bis die Kartoffeln weich sind und die Bockshornkleeblätter gut eingearbeitet sind.
Abschmecken: Mit Salz abschmecken und gut vermischen. Noch eine Minute kochen lassen.
Servieren: Vom Herd nehmen und heiß mit Roti, Paratha oder Reis servieren.
Guten Appetit! 😊
Ingredients:
Potatoes (Aloo) – 3 medium-sized, peeled and diced into small cubes
Fenugreek Leaves (Methi) – 2 cups, fresh and chopped
Oil – 2-3 tablespoons
Cumin Seeds (Jeera) – 1 teaspoon
Asafoetida (Hing) – a pinch (optional)
Green Chilies – 2, finely chopped (adjust to taste)
Garlic – 3-4 cloves, minced (optional but adds flavor)
Coriander Powder (Dhaniya) – 1 teaspoon
Salt – to taste
Instructions:
Prepare Fenugreek Leaves: Wash the methi leaves thoroughly to remove dirt and chop them finely. Set aside.
Heat Oil: Heat oil in a pan or kadai on medium heat.
Add Aromatics: Add cumin seeds and let them splutter. Add a pinch of asafoetida if using.
Sauté Garlic and Chilies: Add the minced garlic and green chilies. Sauté until the garlic turns golden.
Cook Potatoes: Add the diced potatoes to the pan. Mix well and add coriander powder. Stir everything to coat the potatoes evenly with spices.
Cover and Cook: Cover the pan and let the potatoes cook on low-medium heat for about 7-10 minutes, stirring occasionally to prevent sticking.
Add Fenugreek Leaves: Once the potatoes are partially cooked, add the chopped methi leaves. Mix well.
Cook Together: Cover and cook for another 5-7 minutes, stirring occasionally, until the potatoes are fully cooked and the methi leaves are well incorporated.
Season: Add salt and mix well. Cook for another minute.
Serve: Remove from heat and serve hot with roti, paratha, or rice.
#define led 2
void setup() {
// put your setup code here, to run once:
pinMode(2, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(led, 1);
delay(1000);
digitalWrite(led, 0);
delay(200);
}
OpenCV, or Open Source Computer Vision Library, is a powerful and widely-used open-source computer vision and machine learning software library. It provides a plethora of tools and functions for image and video processing, making it an essential resource for developers, researchers, and hobbyists. Installing OpenCV on a Windows system can be a straightforward process when using the Python package manager, pip. In this article, we’ll walk you through the steps to install OpenCV on your Windows machine using pip.
Prerequisites:
Before diving into the installation process, ensure that you have the following prerequisites:
A Windows operating system.
Python installed on your machine. You can download the latest version of Python from the official website: https://www.python.org/downloads/.
Installation Steps:
Follow these step-by-step instructions to install OpenCV using pip in Windows:
Step 1: Open a Command Prompt
Press Win + R to open the Run dialog, type cmd, and press Enter. This will open the Command Prompt.
Step 2: Upgrade pip
Ensure that your pip is up-to-date by running the following command:
pip install --upgrade pip
This ensures that you have the latest version of pip installed.
Step 3: Install NumPy
NumPy is a prerequisite for OpenCV, as it is used for numerical operations. Install it by running:
pip install numpy
Step 4: Install OpenCV
Now, you can install the OpenCV package using the following command:
pip install opencv-python
This command will download and install the latest stable version of OpenCV along with its dependencies.
Step 5: Verify the Installation
To ensure that OpenCV has been successfully installed, open a Python interpreter or create a simple Python script and import the cv2 module:
import cv2
print(cv2.__version__)
This should print the installed OpenCV version, confirming that the installation was successful.
#define m1p 7
#define m1n 6
#define m2p 5
#define m2n 4
#define echopin 9
#define trigpin 10
void motor_forward();
void motor_stop();
void motor_left();
void motor_right();
void motor_back();
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(m1p, OUTPUT);
pinMode(m1n, OUTPUT);
pinMode(m2p, OUTPUT);
pinMode(m2n, OUTPUT);
pinMode(echopin, INPUT);
pinMode(trigpin, OUTPUT);
}
long duration, distance;
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distance = (duration *0.0343 / 2);
Serial.println(distance);
// Serial.println(" cm");
//delay(1000);
//Serial.println(distance); //print data serially
if (distance > 25) { // if distance is more than 25 move bot forward
motor_forward();
delay(20);
motor_forward();
}
else {
// motor_stop();
//delay(500);
// motor_back();
// delay(3000);
motor_stop(); // if distance is less than 25 move bot right
delay(50);
motor_back();
delay(100);
motor_right();
delay(100);
}
}
void motor_back(){
digitalWrite(m1p, LOW);
digitalWrite(m1n, HIGH);
digitalWrite(m2p, HIGH);
digitalWrite(m2n, LOW);
}
void motor_forward(){
digitalWrite(m1p, HIGH);
digitalWrite(m1n, LOW);
digitalWrite(m2p, LOW);
digitalWrite(m2n, HIGH);
}
void motor_stop(){
digitalWrite(m1p, LOW);
digitalWrite(m1n, LOW);
digitalWrite(m2p, LOW);
digitalWrite(m2n, LOW);
}
void motor_left(){
digitalWrite(m1p, HIGH);
digitalWrite(m1n, LOW);
digitalWrite(m2p, LOW);
digitalWrite(m2n, LOW);
}
void motor_right(){
digitalWrite(m1p, LOW);
digitalWrite(m1n, LOW);
digitalWrite(m2p, HIGH);
digitalWrite(m2n, LOW);
}
Code Explanation
The code is a simple obstacle avoidance program for a robot using an ultrasonic sensor and two motors. Let’s break down the code and explain each section:
In this section, the code defines constants for motor pins (m1p, m1n, m2p, m2n) and pins for the ultrasonic sensor (echopin for echo and trigpin for trigger).
Here, the code declares five functions (motor_forward, motor_stop, motor_left, motor_right, motor_back) that will be used to control the movement of the robot.
In the loop function, the ultrasonic sensor is triggered to measure the distance. If the measured distance is greater than 25, the robot moves forward. Otherwise, it stops, moves back a bit, and then turns right.
These functions define the motor control logic for moving the robot in different directions. For example, motor_forward makes the robot move forward by setting the appropriate motor pins.
In summary, this code implements a basic obstacle avoidance mechanism for a robot using an ultrasonic sensor. If the robot detects an obstacle within 25 cm, it stops, moves back a bit, and then turns right. Otherwise, it continues moving forward. The motor control is achieved through the defined functions that set the appropriate pin states for the motor driver.
Arduino, with its user-friendly environment and a vast array of libraries, opens up a world of possibilities for electronic enthusiasts and hobbyists. One of the key features that makes Arduino a versatile platform is the ability to use interrupts. In this blog post, we will explore the use of attachInterrupt() in the Arduino IDE to toggle an LED with the press of a button.
Understanding attachInterrupt()
The attachInterrupt() function in Arduino is a powerful tool that allows you to execute a specified function (interrupt service routine or ISR) when a certain condition occurs on a digital pin. This capability is particularly useful for handling external events without constantly polling the pin in the main loop, thus improving efficiency and responsiveness.
Before we delve into the code, let’s gather the necessary components for this project:
Arduino board (e.g., Arduino Uno)
LED
Resistor (220-330 ohms)
Push button
Jumper wires
Wiring the Circuit
Connect the components as follows:
Connect the longer leg of the LED (anode) to a current-limiting resistor (220-330 ohms) then the other end of the resistor to pin A2 on the Arduino.
Connect the shorter leg of the LED (cathode) GND on the Arduino.
Connect one side of the push button to pin 2 on the Arduino.
Connect the other side of the push button to the GND on the Arduino.
The Arduino Sketch
Now, let’s dive into the Arduino sketch that utilizes attachInterrupt() to toggle the LED state when the button is pressed.
int led=A2;
int button=2;
volatile byte state = LOW;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2),blink,CHANGE);
}
void blink()
{
state = !state;
}
void loop()
{
digitalWrite(led, !state);
}
Breaking Down the Code
We define led and button as the respective pin numbers for the LED and the push button.
volatile byte state is a variable that holds the state of the LED, and it’s marked as volatile to indicate that it can be modified in an ISR.
In the setup() function, we set the LED pin and button pin modes. Additionally, we attach an interrupt to the button using attachInterrupt(), specifying the function blink to be executed on a state change (CHANGE) of the button pin.
The blink() function toggles the state variable when the interrupt is triggered.
In the loop() function, we continuously update the LED state based on the value of the state variable.
1 Tasse Kidneybohnen über Nacht (mindestens 8 Stunden) in 3-4 Tassen Wasser einweichen.
Kochen Sie die Kidneybohnen in einem Schnellkochtopf. Wenn Sie einen Schnellkochtopf im indischen Stil haben, warten Sie mindestens fünf Pfiffe.
Bereiten Sie das Masala vor A. Öl in einer Pfanne erhitzen B. Fügen Sie Kreuzkümmel hinzu und warten Sie, bis er seine Farbe ändert (lassen Sie ihn nicht schwarz werden). C. Gehackten Knoblauch und Ingwer hinzufügen und braten, bis sie eine hellbraune Farbe haben. D. Zwiebeln dazugeben und anbraten, bis sie leicht goldbraun sind. e. Trockene Gewürze, Nelken, schwarzen Pfeffer, rotes Chilipulver, grünes Korianderpulver und Kurkuma hinzufügen F. Lassen Sie die Mischung 30–45 Sekunden lang bei mittlerer Hitze kochen. G. Gehackte Tomaten hinzufügen und die Mischung braten, bis sich das Öl trennt
Die gekochten Kidneybohnen zum Masala hinzufügen
Weitere 10-15 Minuten kochen lassen
Mit Reis oder Roti servieren.
Kidney Bean(Rajma) Recipe
Ingredients
1 cup kidney bean 1 medium onion(chopped) 1 small ginger(chopped) 2-3 cloves of garlic(chopped) 2 Tomatoes(chopped)
Dry Spices: Cumin 2 cloves 5-6 Black pepper red chilli powder green coriander powder turmeric salt
Method
Soak the 1 cup Kidney Bean overnight(at least 8 hours) in 3-4 cup of water.
Cook the Kidney Bean in a pressure cooker. If you have a indian style pressure cooker wait at least 5 whistles.
Prepare the Masala a. Heat Oil in a pan b. Add Cumin and wait till it changes colour(Do not let it turn Black) c. Add chopped garlic and ginger and fry till they are light brown in colour. d. Add Onions and fry till they are slightly golden brown. e. Add dry spices cloves, black pepper, red chilli powder, green coriander powder, turmeric f. Let the mixture cook for 30-45 seconds on a medium heat. g. Add chopped tomatoes and fry the mixture till the oil separates
From the schematics, we see that there are three pins associated with the USB port. 1. PA11 2. PA12 3. PD2
The Pins PA11 and PA12 are PA11 – USB D- PA12 – USB D+
These two pins will be configured by the stm32cube ide when you enable the USB device.
PD2 should be configured as GPIO pin. Because the USB FS implementation says to pull up the D+ line to 3.3V. The pull up is performed by the S8550 PNP transistor. So by making the PD2 pin LOW, we enable the USB FS, since it makes the D+ pull up.
We also need to select the Communication Device Class as Class For FS IP.
After configuring the cube mx project. we can proceed to generate code.
The code needs to add the following header file
/* USER CODE BEGIN Includes */
#include "usbd_cdc_if.h"
#include "string.h"
/* USER CODE END Includes */
and then in the main() function. you can write this code in while loop
/* USER CODE BEGIN 2 */
HAL_GPIO_WritePin(GPIOD, GPIO_PIN_2, GPIO_PIN_RESET);
/* USER CODE END 2 */
/* USER CODE BEGIN WHILE */
uint8_t *data = "Hello World from USB CDC\r\n";
while (1)
{
CDC_Transmit_FS(data, strlen(data));
HAL_Delay (1000);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
After uploading the code to your microcontroller. It will be displayed in your windows device manager as “USB Serial Device”.
You can Connect to the Com port using the serial terminal software such as YAT, Putty or CoolTerm etc. Note: Since it is a virtual com port, you dont have to set a specific baud rate.
To program the AVR microcontroller you use “avrdude” to flash the hex files in the microcontroller. avrdude is a command line tool. Every time you have to flash the microcontroller with a new file you have to write the command. This AVRHexFlashGUI uses the avrdude software to flash the microcontroller but it provides a Graphical User Interface.
There is a special feature I have implemented which is “QuickSet” Toolbar which has a “Quick FLASH” button. This toolbar floats on top of the screen. And provides an easy-to-use button for flashing the firmware files. It has an indicator that turns it’s color to green if the programming is successful or turns red if the programming is unsuccessful. It also has an ‘X’ button to switch off this toolbar. Software such as microchip mplab x ide does not have an option to integrate the avrdude commands like in microchip studio(formerly Atmel Studio). This toolbar provides an easy access to flashing. You do not have to do anything else. Just launch the program and enable the QuickSet toolbar.
AVR microcontrollers are widely used in embedded systems development due to their versatility and ease of programming and also their low cost. Flashing firmware or code onto these microcontrollers is a fundamental task during development. The AVRHexFlashGUI is a graphical user interface (GUI) application built using the Tkinter library in Python.
The AVRHexFlashGUI application streamlines the process of flashing firmware onto AVR microcontrollers using a user-friendly interface. It offers the following features:
Microcontroller Selection: The application allows users to select the target microcontroller from a list of supported devices.
Programmer Configuration: Users can specify the programmer to be used for flashing the firmware. This information is crucial for establishing a connection between the computer and the microcontroller.
HEX File Selection: Users can browse their computer for the HEX file containing the firmware they want to flash onto the microcontroller.
Quick Flash: The application provides a quick flash button that initiates the flashing process using the selected programmer, microcontroller, and HEX file.
Read the Microcontroller Flash Memory: The user can read the unprotected flash memory and save it in the program folder as “HexFromDevice.hex”
AVR Fuse Settings: The application offers the ability to read and display the current fuse settings of the connected AVR microcontroller. Users can also write new fuse settings if needed.
Output Display: The application displays the output of the avrdude tool, which is responsible for flashing the firmware and handling the communication with the microcontroller.
Usage
To use the AVRHexFlashGUI application, follow these steps:
Launch the application.
Select the target microcontroller.
Specify the programmer to be used for flashing.
Load the desired HEX file by clicking the “Browse” button.
Click the “Program AVR” button to start the flashing process.
Monitor the avrdude output to ensure successful flashing.
Optionally, use the “Fuse Setting” section to read, modify, and write fuse settings.
Conclusion
The AVRHexFlashGUI application simplifies the process of flashing firmware onto AVR microcontrollers by providing an intuitive and user-friendly interface. With features for microcontroller selection, programmer configuration, HEX file loading, and fuse settings, developers can efficiently program their microcontrollers. The use of Tkinter and Python makes it easy to create and customize the GUI, enhancing the overall user experience. This application is a valuable tool for both beginners and experienced developers working with AVR microcontrollers. By streamlining the flashing process, it helps save time and ensures accurate firmware deployment.
This is a very simple demonstration of the Unsecured Bluetooth Low Energy technology.
I am using two Raspberry Pi Pico W for this. One will be operated in Central Role and the other will be in the Peripheral Role.
The peripheral device will advertise the temperature data of the rp2040 chip.
The Central device will scan the surrounding and connect to the peripheral device to receive the temperature data. The central device does not use any passcode or pairing methods to connect to the peripheral device.
# This example finds and connects to a peripheral running the
# UART service (e.g. ble_simple_peripheral.py).
import bluetooth
import random
import struct
import time
import micropython
from ble_advertising import decode_services, decode_name
from micropython import const
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)
_IRQ_GATTC_SERVICE_RESULT = const(9)
_IRQ_GATTC_SERVICE_DONE = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE = const(14)
_IRQ_GATTC_READ_RESULT = const(15)
_IRQ_GATTC_READ_DONE = const(16)
_IRQ_GATTC_WRITE_DONE = const(17)
_IRQ_GATTC_NOTIFY = const(18)
_IRQ_GATTC_INDICATE = const(19)
_ADV_IND = const(0x00)
_ADV_DIRECT_IND = const(0x01)
_ADV_SCAN_IND = const(0x02)
_ADV_NONCONN_IND = const(0x03)
_UART_SERVICE_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_RX_CHAR_UUID = bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX_CHAR_UUID = bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E")
class BLESimpleCentral:
def __init__(self, ble):
self._ble = ble
self._ble.active(True)
self._ble.irq(self._irq)
self._reset()
def _reset(self):
# Cached name and address from a successful scan.
self._name = None
self._addr_type = None
self._addr = None
# Callbacks for completion of various operations.
# These reset back to None after being invoked.
self._scan_callback = None
self._conn_callback = None
self._read_callback = None
# Persistent callback for when new data is notified from the device.
self._notify_callback = None
# Connected device.
self._conn_handle = None
self._start_handle = None
self._end_handle = None
self._tx_handle = None
self._rx_handle = None
def _irq(self, event, data):
if event == _IRQ_SCAN_RESULT:
addr_type, addr, adv_type, rssi, adv_data = data
if adv_type in (_ADV_IND, _ADV_DIRECT_IND) and _UART_SERVICE_UUID in decode_services(
adv_data
):
# Found a potential device, remember it and stop scanning.
self._addr_type = addr_type
self._addr = bytes(
addr
) # Note: addr buffer is owned by caller so need to copy it.
self._name = decode_name(adv_data) or "?"
self._ble.gap_scan(None)
elif event == _IRQ_SCAN_DONE:
if self._scan_callback:
if self._addr:
# Found a device during the scan (and the scan was explicitly stopped).
self._scan_callback(self._addr_type, self._addr, self._name)
self._scan_callback = None
else:
# Scan timed out.
self._scan_callback(None, None, None)
elif event == _IRQ_PERIPHERAL_CONNECT:
# Connect successful.
conn_handle, addr_type, addr = data
if addr_type == self._addr_type and addr == self._addr:
self._conn_handle = conn_handle
self._ble.gattc_discover_services(self._conn_handle)
elif event == _IRQ_PERIPHERAL_DISCONNECT:
# Disconnect (either initiated by us or the remote end).
conn_handle, _, _ = data
if conn_handle == self._conn_handle:
# If it was initiated by us, it'll already be reset.
self._reset()
elif event == _IRQ_GATTC_SERVICE_RESULT:
# Connected device returned a service.
conn_handle, start_handle, end_handle, uuid = data
print("service", data)
if conn_handle == self._conn_handle and uuid == _UART_SERVICE_UUID:
self._start_handle, self._end_handle = start_handle, end_handle
elif event == _IRQ_GATTC_SERVICE_DONE:
# Service query complete.
if self._start_handle and self._end_handle:
self._ble.gattc_discover_characteristics(
self._conn_handle, self._start_handle, self._end_handle
)
else:
print("Failed to find uart service.")
elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
# Connected device returned a characteristic.
conn_handle, def_handle, value_handle, properties, uuid = data
if conn_handle == self._conn_handle and uuid == _UART_RX_CHAR_UUID:
self._rx_handle = value_handle
if conn_handle == self._conn_handle and uuid == _UART_TX_CHAR_UUID:
self._tx_handle = value_handle
elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
# Characteristic query complete.
if self._tx_handle is not None and self._rx_handle is not None:
# We've finished connecting and discovering device, fire the connect callback.
if self._conn_callback:
self._conn_callback()
else:
print("Failed to find uart rx characteristic.")
elif event == _IRQ_GATTC_WRITE_DONE:
conn_handle, value_handle, status = data
print("TX complete")
elif event == _IRQ_GATTC_NOTIFY:
conn_handle, value_handle, notify_data = data
if conn_handle == self._conn_handle and value_handle == self._tx_handle:
if self._notify_callback:
self._notify_callback(notify_data)
# Returns true if we've successfully connected and discovered characteristics.
def is_connected(self):
return (
self._conn_handle is not None
and self._tx_handle is not None
and self._rx_handle is not None
)
# Find a device advertising the environmental sensor service.
def scan(self, callback=None):
self._addr_type = None
self._addr = None
self._scan_callback = callback
self._ble.gap_scan(2000, 30000, 30000)
# Connect to the specified device (otherwise use cached address from a scan).
def connect(self, addr_type=None, addr=None, callback=None):
self._addr_type = addr_type or self._addr_type
self._addr = addr or self._addr
self._conn_callback = callback
if self._addr_type is None or self._addr is None:
return False
self._ble.gap_connect(self._addr_type, self._addr)
return True
# Disconnect from current device.
def disconnect(self):
if self._conn_handle is None:
return
self._ble.gap_disconnect(self._conn_handle)
self._reset()
# Send data over the UART
def write(self, v, response=False):
if not self.is_connected():
return
self._ble.gattc_write(self._conn_handle, self._rx_handle, v, 1 if response else 0)
# Set handler for when data is received over the UART.
def on_notify(self, callback):
self._notify_callback = callback
def demo():
not_found = False
def on_scan(addr_type, addr, name):
if addr_type is not None:
print("Found peripheral:", addr_type, addr, name)
central.connect()
else:
nonlocal not_found
not_found = True
print("No peripheral found.")
central.scan(callback=on_scan)
# Wait for connection...
while not central.is_connected():
time.sleep_ms(100)
if not_found:
return
print("Connected")
def on_rx(v):
buf1 = bytearray(v)
print("RX ")
for _ in v:
print(chr(_), end='')
print("")
central.on_notify(on_rx)
#with_response = False
with_response = True
i = 0
while central.is_connected():
try:
v = str(i) + "_"
print("TX", v)
central.write(v, with_response)
except:
print("TX failed")
i += 1
time.sleep_ms(2000 if with_response else 30)
print("Disconnected")
if __name__ == "__main__":
ble = bluetooth.BLE()
central = BLESimpleCentral(ble)
while(1):
demo()
ble_Peripheral_device.py
# This example demonstrates a UART periperhal.
import bluetooth
import random
import struct
import time
from ble_advertising import advertising_payload
from micropython import const
def Temp_sensor():
# Configure the internal temperature sensor
sensor_temp = machine.ADC(machine.ADC.CORE_TEMP)
conversion_factor = 3.3 / 65535
raw_temp = sensor_temp.read_u16() * conversion_factor
temperature = (27 - (raw_temp - 0.706) / 0.001721)
return temperature
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_FLAG_READ = const(0x0002)
_FLAG_WRITE_NO_RESPONSE = const(0x0004)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)
_UART_UUID = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
_UART_TX = (
bluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),
_FLAG_READ | _FLAG_NOTIFY,
)
_UART_RX = (
bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),
_FLAG_WRITE | _FLAG_WRITE_NO_RESPONSE,
)
_UART_SERVICE = (
_UART_UUID,
(_UART_TX, _UART_RX),
)
class BLESimplePeripheral:
def __init__(self, ble, name="mpy-uart"):
self._ble = ble
self._ble.active(True)
self._ble.irq(self._irq)
((self._handle_tx, self._handle_rx),) = self._ble.gatts_register_services((_UART_SERVICE,))
self._connections = set()
self._write_callback = None
self._payload = advertising_payload(name=name, services=[_UART_UUID])
self._advertise()
def _irq(self, event, data):
# Track connections so we can send notifications.
if event == _IRQ_CENTRAL_CONNECT:
conn_handle, _, _ = data
print("New connection", conn_handle)
self._connections.add(conn_handle)
elif event == _IRQ_CENTRAL_DISCONNECT:
conn_handle, _, _ = data
print("Disconnected", conn_handle)
self._connections.remove(conn_handle)
# Start advertising again to allow a new connection.
self._advertise()
elif event == _IRQ_GATTS_WRITE:
conn_handle, value_handle = data
value = self._ble.gatts_read(value_handle)
if value_handle == self._handle_rx and self._write_callback:
self._write_callback(value)
def send(self, data):
for conn_handle in self._connections:
self._ble.gatts_notify(conn_handle, self._handle_tx, data)
def is_connected(self):
return len(self._connections) > 0
def _advertise(self, interval_us=500000):
print("Starting advertising")
self._ble.gap_advertise(interval_us, adv_data=self._payload)
def on_write(self, callback):
self._write_callback = callback
def demo():
ble = bluetooth.BLE()
p = BLESimplePeripheral(ble)
def on_rx(v):
print("RX", v)
p.on_write(on_rx)
i = 0
while True:
if p.is_connected():
# Short burst of queued notifications.
transmit_msg = "Temperature: "+str(Temp_sensor())
p.send(str(transmit_msg))
'''
for _ in range(3):
data = "oz"+ str(i) + "_"
print("TX", data)
p.send(data)
i += 1
'''
i = i + 1
time.sleep_ms(1000)
if __name__ == "__main__":
demo()