### Audio Playback Example Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/AudioClass/reference_unihiker_audio_playback_play This example demonstrates a full audio playback sequence: playing a track, starting another in the background, checking remaining time, pausing, resuming, and finally stopping playback. Ensure audio files are in the same directory and a USB speaker is connected. ```python from unihiker import Audio import time audio = Audio() print("Playing 7s Audio") audio.play('7s.wav') print("Playback Completed") print("Start Playing 8s Audio") audio.start_play('8s.wav') for i in range(2): remain_time = audio.play_time_remain() print("Remaining Time: " + str(remain_time)) time.sleep(1) print("Pause Playback") audio.pause_play() for i in range(2): remain_time = audio.play_time_remain() print("Remaining Time: " + str(remain_time)) time.sleep(1) print("Resume Playback") audio.resume_play() for i in range(2): remain_time = audio.play_time_remain() print("Remaining Time: " + str(remain_time)) time.sleep(1) print("Stop Playback") audio.stop_play() print("Playback Ended") ``` -------------------------------- ### Camera Image Overlay Example Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/ScreenDisplay/reference_unihiker_draw_image?q= This example demonstrates capturing video from a camera, processing it, and displaying it on the UNIHIKER screen, overlaying real-time light sensor values. ```APIDOC ## draw_image() with Camera Input ### Description Captures camera image and displays it on the UNIHIKER screen, overlaying the on-board light sensor value. ### Syntax **GUI.draw_image(image, x, y, ...)** ### Parameters * **image** (Image object) - The processed camera image to be displayed. * **x** (int) - The x-coordinate where the image is displayed. * **y** (int) - The y-coordinate where the image is displayed. ### Example Code ```python # -*- coding: UTF-8 -*- import cv2 from PIL import Image from unihiker import GUI from pinpong.board import Board, Pin from pinpong.extension.unihiker import * u_gui = GUI() Board().begin() # Turn on the camera vd = cv2.VideoCapture(0) vd.set(cv2.CAP_PROP_FRAME_WIDTH, 240) vd.set(cv2.CAP_PROP_FRAME_HEIGHT, 320) vd.set(cv2.CAP_PROP_BUFFERSIZE, 1) bgImg = u_gui.draw_image(image="", x=0, y=0) ltTxt = u_gui.draw_text(text="", x=10, y=10, font_size=28, color="#00FF00") while True: ret, img = vd.read() if ret: img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) # Rotate 90 degrees img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # Convert the opecv image format to the UNIHIKER library image format bgImg.config(image=img) ltTxt.config(text=(str(light.read()))) ``` ``` -------------------------------- ### Initialize and Power On Bluetooth Source: https://www.unihiker.com/wiki/Troubleshooting/How_to_connect_a_Bluetooth_speaker?q= Start the `bluetoothctl` utility and enable the Bluetooth agent. Then, power on the Bluetooth adapter to make it discoverable. ```bash bluetoothctl default-agent power on ``` -------------------------------- ### Hello Unihiker Example for UNIHIKER K10 Source: https://www.unihiker.com/wiki/K10/GettingStarted/gettingstarted_platformio?q= A basic C++ example for the UNIHIKER K10 using the Platform IO framework. This code initializes the Unihiker, sets up the screen, and displays text messages with different colors and positions. ```cpp #include "unihiker_k10.h" UNIHIKER_K10 k10; uint8_t screen_dir = 2; void setup() { k10.begin(); k10.initScreen(screen_dir); k10.creatCanvas(); k10.setScreenBackground(0xFFFFFF); k10.canvas->canvasText("UNIHIKER", 1, 0x0000FF); k10.canvas->updateCanvas(); delay(1000); k10.canvas->canvasText("UNIHIKER", 2, 0xFF0000); k10.canvas->updateCanvas(); delay(1000); k10.canvas->canvasText("UNIHIKER", 3, 0x00FF00); k10.canvas->updateCanvas(); delay(1000); k10.canvas->canvasText("UNIHIKER", 4, 0x000000); k10.canvas->updateCanvas(); delay(1000); } void loop() { } ``` -------------------------------- ### Install PuTTY on Linux Source: https://www.unihiker.com/wiki/GettingStarted/gettingstarted_ssh Use this command to install the PuTTY SSH client on Linux systems. ```bash sudo apt-get install putty ``` -------------------------------- ### Full Example: UNIHIKER Button and Key Press Handling Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/MouseAndKeyboard/reference_unihiker_on_key_click This example demonstrates how to instantiate the GUI class, define callback functions for 'A', 'B', and space key presses, and register these callbacks using `on_a_click()`, `on_b_click()`, and `on_key_click()`. It includes a loop to continuously check button states and print messages, with a delay to manage execution. ```python from unihiker import GUI # Import the package gui = GUI() # Instantiate the GUI class bt = "null" # Callback function called when button A is clicked def on_a_click(): global bt bt = "a" print(bt) # Callback function called when button B is clicked def on_b_click(): global bt bt = "b" print(bt) # Callback function called when the space key is pressed def on_space_click(): global bt bt = "space" print(bt) # Register the callback functions for button clicks gui.on_a_click(on_a_click) gui.on_b_click(on_b_click) # Register a callback function for the 'c' key press event using a lambda function gui.on_key_click('c', lambda: print("C key pressed")) # Register the on_space_click function for the space key press event gui.on_key_click('', on_space_click) import time while True: if bt == "a": print("A button pressed") bt = "null" elif bt == "b": print("B button pressed") bt = "null" elif bt == "space": print("Space key pressed") bt = "null" # Add a delay to prevent the program from exiting and to observe the effects time.sleep(1) ``` -------------------------------- ### Audio.start_record() Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/AudioClass/reference_unihiker_recording_audio_record Starts sound recording in the background and saves it to a specified file. ```APIDOC ## Audio.start_record(file) ### Description Start sound recording. ### Parameters - **file** (string) - Required - The name of the file where the recording was saved. ### Return Remaining duration in seconds (number) ``` -------------------------------- ### Example Usage of on_key_click() Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/MouseAndKeyboard/reference_unihiker_on_key_click?q= Demonstrates how to use the `on_key_click` function along with `on_a_click` and `on_b_click` to handle button presses and display output. ```Python from unihiker import GUI gui = GUI() bt = "null" # Callback function called when button A is clicked def on_a_click(): global bt bt = "a" print(bt) # Callback function called when button B is clicked def on_b_click(): global bt bt = "b" print(bt) # Callback function called when the space key is pressed def on_space_click(): global bt bt = "space" print(bt) # Register the callback functions for button clicks gui.on_a_click(on_a_click) gui.on_b_click(on_b_click) # Register a callback function for the 'c' key press event using a lambda function gui.on_key_click('c', lambda: print("C key pressed")) # Register the on_space_click function for the space key press event gui.on_key_click('', on_space_click) import time while True: if bt == "a": print("A button pressed") bt = "null" elif bt == "b": print("B button pressed") bt = "null" elif bt == "space": print("Space key pressed") bt = "null" # Add a delay to prevent the program from exiting and to observe the effects time.sleep(1) ``` -------------------------------- ### Unihiker GUI Setup and BLE Integration Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/IntermediateExamples/10_Bluetooth_Unihiker2BLEAPP Initializes the Unihiker GUI, draws text elements, adds a button to trigger BLE data transmission, and starts the BLE device manager in a separate thread. It also includes a loop to continuously update a text display with received BLE data. ```Python # Initialize the UNIHIKER GUI u_gui=GUI() txt=u_gui.draw_text(text="test",x=20,y=50,font_size=20, color="#0000FF") # Add a button to the GUI bt=u_gui.add_button(text="send",x=20,y=150,w=80,h=50,onclick=button_click1) txt2=u_gui.draw_text(text="test",x=120,y=150,font_size=20, color="#00FF00") # Run the device manager in a new thread threading.Thread(target=run_device_manager).start() while True: # Update the text with the received value txt.config(text=recv_value) ``` -------------------------------- ### List All Installable Python Versions Source: https://www.unihiker.com/wiki/Troubleshooting/How_to_Install_Multiple_Python_Versions_on_Unihiker?q= Shows a comprehensive list of all Python versions that can be installed using pyenv. This is useful for identifying available versions before installation. ```bash pyenv install --list ``` -------------------------------- ### Install PinPong Library Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/pinpong_library_introduction?q= Use pip to install the PinPong library. This step can be skipped if the library is already integrated into the UNIHIKER's factory firmware. ```bash pip install pinpong ``` -------------------------------- ### Initialize and Connect to Siot IoT Platform Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/AdvanceExamples/10_IoT_Smart_Home?q= Initialize the Siot client with credentials and connect to the platform. Subscribe to specific topics to receive data and start the client loop. ```Python siot.init(CLIENT_ID, SERVER, user=IOT_UserName,password=IOT_PassWord) # Initialize and ensure that the entered username and password are correct siot.connect() # Connect to the Siot IoT platform siot.subscribe(IOT_pubTopic1, sub_cb) # Subscribe to Topic Data siot.subscribe(IOT_pubTopic2, sub_cb) siot.subscribe(IOT_pubTopic3, sub_cb) siot.loop() # circulate ``` -------------------------------- ### Example Code Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/DigitalIOAndAnlogIO/3_Analog_Input_ADC_?q= Demonstrates how to read the analog value from the P21 pin using both methods. ```APIDOC # -*- coding: UTF-8 -*- # Experiment Effect: Print the analog value of the UNIHIKER P21 pin # Wiring: Connect a potentiometer module to the UNIHIKER P21 pin import time from unihiker.board import Board ,Pin ,ADC Board().begin() # Initialize the UNIHIKER # ADC analog input pins supported: P0 P1 P2 P3 P4 P10 P21 P22 # adc21 = ADC(Pin(Pin.P21)) # Use Pin object with ADC to enable analog input - Method 1 adc21 = Pin(Pin.P21, Pin.ANALOG) # Initialize the pin as an analog input - Method 2 while True: # v = adc21.read() # Read the analog signal value from pin A0 - Method 1 v = adc21.read_analog() # Read the analog signal value from pin A0 - Method 2 print("P21 =", v) time.sleep(0.5) # Wait for 0.5 seconds ``` -------------------------------- ### Initialize and Run BLE Device Manager Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/IntermediateExamples/10_Bluetooth_Unihiker2BLEAPP Sets up and starts the BLE device manager to begin discovering and connecting to devices. It uses 'hci0' as the Bluetooth adapter. ```Python def run_device_manager(): # Start the device manager manager = AnyDeviceManager(adapter_name='hci0') manager.start_discovery() manager.run() ``` -------------------------------- ### Python Audio Playback Example Source: https://www.unihiker.com/wiki/Troubleshooting/How_to_connect_a_Bluetooth_speaker This Python script demonstrates recording a 6-second audio clip and then playing it back. It utilizes the `unihiker` library for audio operations. ```python # -*- coding: UTF-8 -*- from unihiker import Audio import time audio = Audio() print("Preparing to record for 6 seconds") time.sleep(2) print("Starting recording...") audio.record('6s.wav', 3) print("Recording completed") time.sleep(2) print("Playing the 6-second audio") audio.play('6s.wav') print("Playback completed") ``` -------------------------------- ### MicroPython Screen Display Example Source: https://www.unihiker.com/wiki/K10/GettingStarted/gettingstarted_mpy This MicroPython code initializes the camera and screen, then draws various shapes and text before displaying the camera feed. Save as main.py to run on the device. ```python from unihiker_k10 import screen import time from k10_base import Camera camera = Camera() camera.init() screen.init(dir=2) screen.show_camera(camera) screen.show_bg(color=0xFFFF00) screen.set_width(width=5) screen.draw_line(x0=0,y0=0,x1=80,y1=80,color=0x0000FF) screen.draw_point(x=100,y=10,color=0xFF0000) screen.draw_rect(x=120,y=100,w=80,h=120,bcolor=0xFF6666,fcolor=0x0000FF) screen.draw_rect(x=120,y=100,w=40,h=60,bcolor=0x012345) screen.draw_circle(x=80,y=80,r=40,bcolor=0x00FF00,fcolor=0x0000FF) screen.draw_circle(x=80,y=80,r=20,bcolor=0xFF0000) screen.draw_text(text="Hello\n23",x=10,y=0,font_size=24,color=0xFF0000) screen.draw_text(text="line\n456\nhgjh\n",line=2,font_size=24,color=0xFF0000) screen.show_draw() time.sleep(2) screen.clear() while True: time.sleep(1) ``` -------------------------------- ### Python Audio Recording and Playback Example Source: https://www.unihiker.com/wiki/Troubleshooting/How_to_connect_a_Bluetooth_speaker?q= This Python script demonstrates how to record audio for a specified duration and then play it back. It utilizes the `unihiker` library for audio operations. ```python # -*- coding: UTF-8 -*- from unihiker import Audio import time audio = Audio() print("Preparing to record for 6 seconds") time.sleep(2) print("Starting recording...") audio.record('6s.wav', 3) print("Recording completed") time.sleep(2) print("Playing the 6-second audio") audio.play('6s.wav') print("Playback completed") ``` -------------------------------- ### GUI Setup with Button Actions Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/AdvanceExamples/10_IoT_Smart_Home This snippet sets up the GUI for the IoT smart home application, including drawing a background, title, and displaying LED status and sensor readings. It also defines callback functions `click_A` and `click_B` to publish commands to the IoT platform when buttons are pressed. Ensure `GUI` and `siot` are imported. ```python gui=GUI() gui.fill_rect(x=0, y=0, w=240, h=320, color="#99CCFF") title = gui.draw_text(x=50, y=10, text='IoT Smart Home', font_size=14, color='blue') gui.draw_round_rect(x=20, y=40, w=200, h=42, r=8, width=1) gui.draw_text(x=30, y=52, text='The state of LED:', font_size=11) text_mode = gui.draw_text(x=160, y=52, color="red", text="close", font_size=11) gui.draw_round_rect(x=20, y=90, w=200, h=80, r=8,width=1) text1 = gui.draw_text(x=30, y=95, text='humidity:', font_size=11, color='black') text_value1 = gui.draw_text(x=100, y=95, color="red", text="", font_size=12) gui.draw_text(text="%RH",x=140,y=95,font_size=12, color="red") text3 = gui.draw_text(x=30, y=135, text='temperature:', font_size=11, color='black') text_value2 = gui.draw_text(x=130, y=135, color="red", text="", font_size=12) gui.draw_text(text="℃",x=170,y=135,font_size=12, color="red") ``` -------------------------------- ### Start Clock and Print Threads with UNIHIKER Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/MultiThreading/reference_unihiker_start_thread This example demonstrates starting two threads: one to update a clock display and another for simple print statements. Thread functions do not loop by default; explicit looping within the function is required for continuous execution. Adding a sleep in a thread loop prevents the program from becoming unresponsive. ```python import time from unihiker import GUI # Import Package gui=GUI() # Instantiating GUI classes clock = gui.draw_clock(x=120, y=160, r=100, h=3, m=4, s=5, color=(255, 0, 0), onclick=lambda: print("clock clicked")) def clock_update(): print("Thread 1 starts") while True: # loop execution t = time.localtime() clock.config(h=time.strftime("%H", t), m=time.strftime("%M", t), s=time.strftime("%S", t)) time.sleep(0.5) # Adding a sleep in a thread loop can prevent the program from getting stuck or slowing down print("Thread 1 stopped") def print_test(): print("Thread 2 starts") time.sleep(1) print("Thread 2") time.sleep(1) print("Thread 2 ends") # Thread 1 starts clock_thread = gui.start_thread(clock_update) # Thread 2 starts gui.start_thread(print_test) while True: time.sleep(0.1) ``` -------------------------------- ### Camera Feed and Sensor Data Overlay Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/ScreenDisplay/reference_unihiker_draw_image Capture camera feed using OpenCV, read on-board light sensor data using pinpong, and overlay them on the UNIHIKER screen. This example demonstrates real-time image display and data visualization. Ensure necessary libraries (opencv-python, pinpong) are installed. ```python # -*- coding: UTF-8 -*- import cv2 from PIL import Image from unihiker import GUI from pinpong.board import Board,Pin from pinpong.extension.unihiker import * u_gui=GUI() Board().begin() #Turn on the camera vd = cv2.VideoCapture(0) vd.set(cv2.CAP_PROP_FRAME_WIDTH,240) vd.set(cv2.CAP_PROP_FRAME_HEIGHT,320) vd.set(cv2.CAP_PROP_BUFFERSIZE, 1) bgImg=u_gui.draw_image(image="",x=0,y=0) ltTxt=u_gui.draw_text(text="",x=10,y=10,font_size=28, color="#00FF00") while True: ret, img = vd.read() if ret: img = cv2.rotate(img,cv2.ROTATE_90_CLOCKWISE) #Rotate 90 degrees img= Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) #Convert the opecv image format to the UNIHIKER library image format bgImg.config(image=img) ltTxt.config(text=(str(light.read()))) ``` -------------------------------- ### Audio Playback Example Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/AudioClass/reference_unihiker_audio_playback_play?q= Demonstrates sequential playback, background playback, checking remaining time, pausing, resuming, and stopping audio. Ensure audio files are in the same directory and a USB speaker is connected. ```Python from unihiker import Audio import time audio = Audio() print("Playing 7s Audio") audio.play('7s.wav') print("Playback Completed") print("Start Playing 8s Audio") audio.start_play('8s.wav') for i in range(2): remain_time = audio.play_time_remain() print("Remaining Time: " + str(remain_time)) time.sleep(1) print("Pause Playback") audio.pause_play() for i in range(2): remain_time = audio.play_time_remain() print("Remaining Time: " + str(remain_time)) time.sleep(1) print("Resume Playback") audio.resume_play() for i in range(2): remain_time = audio.play_time_remain() print("Remaining Time: " + str(remain_time)) time.sleep(1) print("Stop Playback") audio.stop_play() print("Playback Ended") ``` -------------------------------- ### Install UNIHIKER Library Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/unihiker_library_introduction Use pip to install the UNIHIKER library. This command is used for initial installation. ```bash pip install unihiker ``` -------------------------------- ### Record Audio and Measure Sound Level Source: https://www.unihiker.com/wiki/LanguageReference/UNIHIKER_Library/AudioClass/reference_unihiker_recording_audio_record This example demonstrates how to initialize the Audio class, measure ambient sound levels in a loop, record a short audio clip directly to a file, and manage a background recording session. ```python from unihiker import Audio import time audio = Audio() # Instantiating audio print("Ambient sound size") for i in range(30): print(audio.sound_level()) time.sleep(0.1) print("Record for 3 seconds") audio.record('3s.wav', 3) # Record for 3 seconds and save to file 3s.wav print("start recording") audio.start_record('6s.wav') # Start recording in the background and save it to file 6s.wav print("Wait for 6 seconds") time.sleep(6) # Wait for 6 seconds audio.stop_record() # stop recording print("stop recording") ``` -------------------------------- ### Install a Specific Python Version Source: https://www.unihiker.com/wiki/Troubleshooting/How_to_Install_Multiple_Python_Versions_on_Unihiker?q= Installs a specified Python version (e.g., 3.9.7) using pyenv. Replace '' with the desired Python version. After installation, run 'pyenv rehash' to update the environment. ```bash pyenv install ``` -------------------------------- ### IoT Smart Home Configuration and GUI Setup Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/AdvanceExamples/10_IoT_Smart_Home?q= This code snippet sets up the necessary parameters for connecting to the IoT platform and initializes the graphical user interface. It defines callback functions for button presses to control the LED. ```python from unihiker import GUI import time import siot '''Set IoT platform connection parameters''' SERVER = "192.168.9.24" CLIENT_ID = "" IOT_UserName = 'siot' IOT_PassWord = 'dfrobot' IOT_pubTopic1 = 'LED' IOT_pubTopic2 = 'moisture' IOT_pubTopic3 = 'temperature' global moisture_value moisture_value = 0 global temperature_value temperature_value = 0 global LED_state LED_state = 0 # Define callback function def click_A(): siot.publish(IOT_pubTopic1, 'relay on') text_mode.config(text = "open") def click_B(): siot.publish(IOT_pubTopic1, 'relay off') text_mode.config(text = "close") '''Display screen page''' gui=GUI() gui.fill_rect(x=0, y=0, w=240, h=320, color="#99CCFF") title = gui.draw_text(x=50, y=10, text='IoT Smart Home', font_size=14, color='blue') gui.draw_round_rect(x=20, y=40, w=200, h=42, r=8, width=1) gui.draw_text(x=30, y=52, text='The state of LED:', font_size=11) text_mode = gui.draw_text(x=160, y=52, color="red", text="close", font_size=11) gui.draw_round_rect(x=20, y=90, w=200, h=80, r=8,width=1) text1 = gui.draw_text(x=30, y=95, text='humidity:', font_size=11, color='black') text_value1 = gui.draw_text(x=100, y=95, color="red", text="", font_size=12) gui.draw_text(text="%RH",x=140,y=95,font_size=12, color="red") text3 = gui.draw_text(x=30, y=135, text='temperature:', font_size=11, color='black') text_value2 = gui.draw_text(x=130, y=135, color="red", text="", font_size=12) gui.draw_text(text="℃",x=170,y=135,font_size=12, color="red") ``` -------------------------------- ### Install PuTTY on MacOS Source: https://www.unihiker.com/wiki/GettingStarted/gettingstarted_ssh Use this command to install the PuTTY SSH client on macOS systems using Homebrew. ```bash brew install putty ``` -------------------------------- ### Initialize and Use USB Speaker Source: https://www.unihiker.com/wiki/LanguageReference/USBDevices/USB_Speaker?q= This snippet demonstrates how to initialize the pyttsx3 library, set speech properties like volume and rate, make the USB speaker say a phrase, save the audio to a file, and then run the engine to complete the tasks. Ensure pyttsx3 is installed. ```Python '''Voice Play Text''' import pyttsx3 # Import pyttsx3 library engine = pyttsx3.init() # Initialize TTS engine and create engine objects engine.setProperty('volume',1) # Set the pronunciation volume (within the range of 0-1) engine.setProperty('rate',120) # Set the reading speed (within the range of 0-200) engine.say("hello, i am unihiker") # Read the content aloud in English engine.save_to_file("hello, i am unihiker", "test.mp3") # Save the content as audio (named test. mp3) engine.runAndWait() # Run the TTS engine and wait for the reading to complete ``` -------------------------------- ### Color Recognition Example Code Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/PopularModules/6_Color_recognition Example code demonstrating how to initialize and use the TCS34725 color sensor to read RGB values. ```APIDOC # -*- coding: UTF-8 -*- # Experimental effect: Reading the value of I2C TCS34725 color sensor import time from pinpong.board import Board from pinpong.libs.dfrobot_tcs34725 import TCS34725 # Import tcs34725 library from libs Board("uno").begin() # Initialize, select board type and port number, automatically recognize without entering port number tcs = TCS34725() # Sensor initialization print("Color View Test!") while True: if tcs.begin(): # Search for sensors and return True if detected print("Found sensor") break # Find it, jump out of the loop else: print("No TCS34725 found ... check your connections") time.sleep(1) while True: r,g,b,c = tcs.get_rgbc() # Obtain RGBC data print(r,g,b,c) print("C=%d\tR=%d\tG=%d\tB=%d\t"%(c,r,g,b)) ''' # Data conversion, quantifying the monitored RGB values. r /= c g /= c b /= c r *= 256 g *= 256 b *= 256; print("------C=%d\tR=%d\tG=%d\tB=%d\t"%(c,r,g,b)) ''' time.sleep(1) ``` -------------------------------- ### Color Recognition Example Code Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/PopularModules/6_Color_recognition?q= Example demonstrating how to initialize the TCS34725 color sensor, detect its presence, and continuously read RGB color values. ```Python # -*- coding: UTF-8 -*- # Experimental effect: Reading the value of I2C TCS34725 color sensor import time from pinpong.board import Board from pinpong.libs.dfrobot_tcs34725 import TCS34725 # Import tcs34725 library from libs Board("uno").begin() # Initialize, select board type and port number, automatically recognize without entering port number tcs = TCS34725() # Sensor initialization print("Color View Test!"); while True: if tcs.begin(): # Search for sensors and return True if detected print("Found sensor") break # Find it, jump out of the loop else: print("No TCS34725 found ... check your connections") time.sleep(1) while True: r,g,b,c = tcs.get_rgbc() # Obtain RGBC data print(r,g,b,c) print("C=%d\tR=%d\tG=%d\tB=%d\t"%(c,r,g,b)) ''' # Data conversion, quantifying the monitored RGB values. r /= c g /= c b /= c r *= 256 g *= 256 b *= 256; print("------C=%d\tR=%d\tG=%d\tB=%d\t"%(c,r,g,b)) ''' time.sleep(1) ``` -------------------------------- ### Initialize and Control Servo with GUI Buttons Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/PopularModules/3_Servo?q= This example demonstrates initializing a servo motor and controlling its angle via GUI buttons. It requires the UNIHIKER board, a servo motor, and the PinPong library. The GUI provides virtual buttons to set the servo to specific angles (10°, 90°, 170°) or to cycle through a range of motion. ```python # -*- coding: utf-8 -*- # Experimental effect: Servo control # Wiring: Use a computer to connect a UNIHIKER main control board and P10 to connect a servo motor import time from pinpong.board import Board,Pin,Servo from unihiker import GUI import time Board("UNIHIKER").begin() # Initialize, select board type, do not input board type for automatic recognition gui=GUI() s1 = Servo(Pin(Pin.P21)) # Input Pin into Servo to initialize servo pins, supporting P0 P2 P3 P8 P9 P10 P16 P21 P22 P23 def click_A(): # Define the action when clicking button A s1.angle(10) # Control the servo to turn to the 0 degree position print("10") time.sleep(1) def click_B(): # Define the action when clicking button B s1.angle(90) # Control the servo to turn to the 90 degree position print("90") time.sleep(1) def click_C(): # Define the action when clicking button C s1.angle(170) # Control the servo to turn to the 170 degree position print("170") time.sleep(1) def click_D(): # Define the action when clicking button C for i in range(10, 171, 10): s1.angle(i) time.sleep(0.5) for i in range(171, 10, -10): s1.angle(i) time.sleep(0.5) # Control the servo to turn to the 0-170 degree position print("circulate") time.sleep(1) txt=gui.draw_text(text="servo",x=120,y=10,font_size=20,origin="center",color="#0000FF") botton_A = gui.add_button(x=120, y=100, w=100, h=30, text="10°", origin='center', onclick=click_A) botton_B = gui.add_button(x=120, y=150, w=100, h=30, text="90°", origin='center', onclick=click_B) botton_C = gui.add_button(x=120, y=200, w=100, h=30, text="170°", origin='center', onclick=click_C) botton_D = gui.add_button(x=120, y=250, w=100, h=30, text="circulate", origin='center', onclick=click_D) while True: time.sleep(1) ``` -------------------------------- ### GUI Setup for IoT Smart Home Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/AdvanceExamples/10_IoT_Smart_Home This snippet sets up the graphical user interface for the IoT smart home application. It initializes the GUI, draws various elements like images, text, and shapes to display status and sensor readings. Ensure the `GUI` module is imported. ```python gui = GUI() img = gui.draw_image(w=240, h=320, image='img/close LED.png') title = gui.draw_text(x=50, y=10, text='IoT Smart Home', font_size=14, color='red') gui.draw_round_rect(x=20, y=40, w=200, h=42, r=8, width=1) gui.draw_text(x=30, y=52, text='The state of LED:', font_size=11) text_mode = gui.draw_text(x=160, y=47, color="red", text="close", font_size=14) gui.draw_round_rect(x=20, y=230, w=200, h=80, r=8,width=1) gui.draw_text(x=30, y=235, color="black", text='humidity:') gui.draw_text(x=30, y=270, color="black", text='temperature:') text_value1 = gui.draw_text(x=120, y=238, color="red", text="", font_size= 11) gui.draw_text(text="%RH",x=160,y=238,font_size=12, color="red") text_value2 = gui.draw_text(x=150, y=272, color="red", text="", font_size= 11) gui.draw_text(text="℃",x=190,y=272,font_size=12, color="red") ``` -------------------------------- ### Example: UNIHIKER as Receiver Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/Communication/1_Serial_Port_UART_?q= Example code demonstrating UNIHIKER as a receiver using UART communication, with a computer as the sender. This code initializes UART, reads incoming data, and prints it. ```APIDOC ## Example Code 1: UNIHIKER as Receiver ### Description This code snippet shows how to configure the UNIHIKER to receive data via UART from a computer. It initializes the UART, then enters a loop to continuously check for and print any incoming bytes. ### Code ```python # -*- coding: utf-8 -*- import time from pinpong.board import Board, UART Board("UNIHIKER").begin() # Initialize the UNIHIKER board. # Initialize UART (Hardware Serial 1) on bus 0 (P0-RX, P3-TX) uart1 = UART(bus_num=0) # Configure UART parameters: baud rate, data bits, parity, stop bits uart1.init(baud_rate=115200, bits=8, parity=0, stop=1) print("UNIHIKER is ready to receive data...") while True: # Check if any data is available to read while uart1.any() > 0: # Read one byte at a time and print it received_byte = uart1.read(1) if received_byte: print(f"Received: {received_byte}") time.sleep(0.1) # Small delay to prevent high CPU usage # To deinitialize UART (optional, usually at the end of the program): # uart1.deinit() ``` ``` -------------------------------- ### Initialize and Use TTS Engine Source: https://www.unihiker.com/wiki/LanguageReference/USBDevices/USB_Speaker This snippet demonstrates initializing the pyttsx3 TTS engine, setting volume and speech rate, speaking text, saving audio to an MP3 file, and running the engine to completion. Ensure the pyttsx3 library is installed. ```Python import pyttsx3 engine = pyttsx3.init() engine.setProperty('volume',1) engine.setProperty('rate',120) engine.say("hello, i am unihiker") engine.save_to_file("hello, i am unihiker", "test.mp3") engine.runAndWait() ``` -------------------------------- ### Subscribe to MQTT Topics and Start Loop Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/AdvanceExamples/10_IoT_Smart_Home Subscribe to specific MQTT topics to receive data and start the client loop to process incoming messages. A continuous loop with a small delay is used to keep the connection active. ```Python siot.subscribe(IOT_pubTopic1, sub_cb) # Subscribe to Topic Data siot.subscribe(IOT_pubTopic2, sub_cb) siot.subscribe(IOT_pubTopic3, sub_cb) siot.loop() # circulate while True: # circulate time.sleep(0.5) # Delay by 0.5 seconds ``` -------------------------------- ### Analog Input and PWM Output Example Source: https://www.unihiker.com/wiki/K10/Examples/examples_arduinoide Initializes serial communication and sets up PWM output on P0 using analogWrite, mapping a value of 512 to the PWM range. Reads and prints the analog input from P1 in a loop. ```cpp void setup() { Serial.begin(9600); analogWrite(P0, map(512, 0, 1023, 0, 255)); } void loop() { Serial.println((analogRead(P1))); } ``` -------------------------------- ### Check Available Bytes Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/Communication/1_Serial_Port_UART_?q= Gets the number of bytes available to read from UART. ```APIDOC ## any() ### Description Get the number of bytes available to read from UART. ### Parameters - None ### Return - int - The number of data bytes that can be read. ``` -------------------------------- ### Initialize and Connect to Siot IoT Platform Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/AdvanceExamples/10_IoT_Smart_Home Initialize the Siot IoT client with credentials and connect to the platform. Ensure the username and password are correct. ```Python siot.init(CLIENT_ID, SERVER, user=IOT_UserName,password=IOT_PassWord) # Initialize and ensure that the entered username and password are correct siot.connect() # Connect to the Siot IoT platform ``` -------------------------------- ### Initialize and Use pyttsx3 for Speech Synthesis Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/AdvanceExamples/2_Speech_Synthesis_Assistant Initializes the pyttsx3 engine, sets volume and speech rate, speaks a phrase, and saves audio to a file. Ensure pyttsx3 is installed and a USB speaker is connected. ```Python # -*- coding: UTF-8 -*- import pyttsx3 # Import pyttsx3 library engine = pyttsx3.init() # Initialize TTS engine and create engine objects engine.setProperty('volume',1) # Set the pronunciation volume (within the range of 0-1) engine.setProperty('rate',120) # Set the reading speed (within the range of 0-200) engine.say("hello, i am unihiker") # Read the content aloud in English engine.save_to_file("hello, i am unihiker", "test.mp3") # Save the content as audio (named test. mp3) engine.runAndWait() # Run the TTS engine and wait for the reading to complete ``` -------------------------------- ### I2C Scan Example Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/Communication/2_I2C_Inter_Integrated_Circuit_ Demonstrates how to scan for I2C devices on the bus using the `i2cdetect` command. ```APIDOC ## I2C Scan ### Description After upgrading the Pinpong library to version 0.6.0 and above, you can use the `i2cdetect` tool for I2C scanning. The I2C interface number on the UNIHIKER is typically 4. ### Usage Run the following command in the terminal: ```bash i2cdetect -y 4 ``` ### Example Output ``` 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- 3c -- -- -- 40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- -- ``` ``` -------------------------------- ### Record and Play Audio Source: https://www.unihiker.com/wiki/K10/Examples/examples_mpy Demonstrates recording audio using the system microphone for 5 seconds and playing it back, then records to the TF card and plays it back. Requires 'mic' and 'speaker' modules. ```python from unihiker_k10 import mic,speaker import time print("begin sys recode") mic.recode_sys(name="sound.wav",time=5) print("recode sys done") time.sleep(1) print("begin sys play") speaker.play_sys_music("sound.wav") print("end sys play") time.sleep(1) print("begin tf recode") mic.recode_tf(name="sound.wav",time=5) print("recode tf done") time.sleep(1) print("begin tf play") speaker.play_tf_music("sound.wav") print("end tf play") while True: pass ``` -------------------------------- ### TCS34725 Get RGBc Source: https://www.unihiker.com/wiki/LanguageReference/PinPong_Library/PopularModules/6_Color_recognition Obtains the detected color parameter values (Red, Green, Blue, and Clear/Infrared). ```APIDOC ## get_rgbc() ### Description Obtains the detected color parameter values. ### Syntax r,g,b,c = Object.get_rgbc() ### Parameters None ### Return - **r** (int): Red color value. - **g** (int): Green color value. - **b** (int): Blue color value. - **c** (int): Filtered original infrared light value. ``` -------------------------------- ### Stop Buzzer Playback Source: https://www.unihiker.com/wiki/Examples/PythonCodingExamples/BasicExamples/examples_py_digital_piano Stop any currently playing sound on the buzzer, regardless of whether it was started in the foreground or background. ```python buzzer.stop() # Stop playback ``` -------------------------------- ### Initialization Source: https://www.unihiker.com/wiki/K10/CodeReference/CodeReference_arduinoide Initializes the UNIHIKER K10 board. ```APIDOC ## begin ### Description Initialize UNIHIKER K10 board ### Signature ```cpp void begin(void); ``` ``` -------------------------------- ### Digital Input/Output Example Source: https://www.unihiker.com/wiki/K10/Examples/examples_arduinoide Configures P0 as an output and P1 as an input. Initializes serial communication and sets the output of P0 to HIGH. Reads and prints the digital state of P1 in a loop. ```cpp void setup() { pinMode(P0, OUTPUT); pinMode(P1, INPUT); Serial.begin(9600); digitalWrite(P0, HIGH); } void loop() { Serial.println((digitalRead(P1))); } ```