Is it possible to code in a python serial monitor 'display' onto mit?

Helloo, i'm currently using mit app inventor, rpi, and python for a school project (it's pain). The school project in question is a (physical)morse code transceiver, and i need to find a way to show what is being received on the mit device. Currently, it involves the use of http webservers (in order to depict signals with the LED), and google says its possible to do so?

to specify, what i mean is by utilizing the print() command in python to print the translated morse code from the physical morse code device onto python's serial monitor (from the morse code device), and send/show the text on the pythong serial monitor on the mit app inventor.

google says its possible with the use of labels and some other things involving the web component, but it being the ai summary, its quite unreliable and doesnt show full details. Videos just show results for arduino, which we can't use--just rpi and python.

something like this?

use python to encode / decode more code and display ton app inventor

While a Python script cannot run directly in MIT App Inventor, you can use Python to build the core Morse code logic and then call that Python code from your App Inventor app

. The easiest way to do this is by using a web server to host your Python script and having App Inventor communicate with it.

Here is a step-by-step guide and the code you will need.

Step 1: Write the Python Morse code script

This Python script will use a dictionary to map letters to Morse code and will contain two functions: one for encoding and one for decoding. To make it a web service, you will wrap it in a lightweight web framework like Flask.

Python script (app.py)

python

from flask import Flask, request, jsonify

app = Flask(__name__)

# Dictionary for encoding
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...',
                    'C':'-.-.', 'D':'-..', 'E':'.',
                    'F':'..-.', 'G':'--.', 'H':'....',
                    'I':'..', 'J':'.---', 'K':'-.-',
                    'L':'.-..', 'M':'--', 'N':'-.',
                    'O':'---', 'P':'.--.', 'Q':'--.-',
                    'R':'.-.', 'S':'...', 'T':'-',
                    'U':'..-', 'V':'...-', 'W':'.--',
                    'X':'-..-', 'Y':'-.--', 'Z':'--..',
                    '1':'.----', '2':'..---', '3':'...--',
                    '4':'....-', '5':'.....', '6':'-....',
                    '7':'--...', '8':'---..', '9':'----.',
                    '0':'-----', ', ':'--.--', '.':'.-.-.-',
                    '?':'..--..', '/':'-..-.', '-':'-....-',
                    '(':'-.--.', ')':'-.--.-'}

# A reversed dictionary for decoding
REVERSE_MORSE_DICT = {v: k for k, v in MORSE_CODE_DICT.items()}

@app.route('/encode', methods=['POST'])
def encode():
    text = request.json.get('text', '').upper()
    morse_code = []
    for char in text:
        if char != ' ':
            morse_code.append(MORSE_CODE_DICT.get(char, ''))
        else:
            morse_code.append('/')
    return jsonify({'morse_code': ' '.join(morse_code)})

@app.route('/decode', methods=['POST'])
def decode():
    morse_text = request.json.get('morse_code', '')
    morse_words = morse_text.split(' / ')
    decoded_message = []
    for word in morse_words:
        morse_chars = word.split(' ')
        decoded_chars = [REVERSE_MORSE_DICT.get(mc, '') for mc in morse_chars]
        decoded_message.append(''.join(decoded_chars))
    return jsonify({'text': ' '.join(decoded_message)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Use code with caution.


Step 2: Install Flask and run the server

  1. Install Flask: Open a terminal or command prompt and run:

sh

pip install flask

Use code with caution.

  1. Run the script: Navigate to the directory where you saved app.py and run:

sh

python app.py

Use code with caution.

  1. Find your IP address: The Flask server is now running on your computer. You will need your computer's IP address to communicate with it from App Inventor. On most operating systems, you can find this by running ipconfig (Windows) or ifconfig (macOS/Linux). The URL for your service will be http://your_ip_address:5000.

Step 3: Design the App Inventor interface

Create a new project in MIT App Inventor and lay out the components on the Designer tab.

  • User Interface:
    • TextBox_Input: For the user to enter text or Morse code.
    • Button_Encode: To convert text to Morse.
    • Button_Decode: To convert Morse to text.
    • Label_Output: To display the result.
  • Connectivity:
    • Web1: The component that will make the POST requests to your Python server.

Step 4: Program the App Inventor blocks

Switch to the Blocks editor in App Inventor to program the app's logi

1 Like

not quite, i'm using a simpler-ish version based on what was taught at my school. Here's my code for reference;

import RPi.GPIO as GPIO
import time

GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
BUTTON_PIN = 10
BUTTON_PIN2 = 22
BUTTON_PIN3 = 9
buzzersend = 23
buzzerrec = 24
request = None
GPIO.setmode(GPIO.BCM)
# SENDING TO PHYSICAL DEIVCE
class RequestHandler_httpd(BaseHTTPRequestHandler):
  def do_GET(self):
    global request
    messagetosend = bytes('This is my sample QA.',"utf")
    self.send_response(200)
    self.send_header('Content-Type', 'text/plain')
    self.send_header('Content-Length', len(messagetosend))
    self.end_headers()
    self.wfile.write(messagetosend)
    request = self.requestline
    request = request[5 : int(len(request)-9)]
    print(request)
    if request == 'on':
        print('.')
        GPIO.output(17,True)
        buzzerrec.on()
        time.sleep(1)
        GPIO.output(17, False)
    if request == 'off':
        print('-')
        GPIO.output(17,True)
        buzzersend.on()
        time.sleep(3)
        GPIO.output(17, False)
    if request == 'space':
        print('/')
        GPIO.output(17,True)
        buzzerrec.on()
        time.sleep(7)
        GPIO.output(17, False)
    else:
        GPIO.output(17, False)
        buzzerrec.off()
    return

# SENDING TO MIT
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(BUTTON_PIN2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(BUTTON_PIN3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while True:
    time.sleep(0.1)
    if GPIO.input(BUTTON_PIN) == GPIO.HIGH :
        print (".")
        GPIO.output(27,True)
        buzzersend.on()
        time.sleep(1)
        GPIO.output(27, False)
    else:
        GPIO.output(27, False)
    if GPIO.input(BUTTON_PIN2) == GPIO.HIGH :
        print("-")
        GPIO.output(27,True)
        buzzersend.on()
        time.sleep(3)
        GPIO.output(27, False)
    else:
        GPIO.output(27, False)
            if GPIO.input(BUTTON_PIN2) == GPIO.HIGH :
        print("/")
        GPIO.output(27,True)
        buzzersend.on()
        time.sleep(7)
        GPIO.output(27, False)
    else:
        GPIO.output(27, False)
        buzzersend.off()
 
 
GPIO.output(17,True)
server_address_httpd = ('ipaddressreplacement',8080)
httpd = HTTPServer(server_address_httpd, RequestHandler_httpd)
print('Starting')
httpd.serve_forever()  
GPIO.cleanup()

i'd like to note that because the rpi device itself is at school, i haven't been able to test this yet--and parts of the code (namely the button and buzzer) are from youtube tutorials as they weren't taught in school, and its use in the code experimentally tweaked in each if else clause. As for translating of the morse code, i'll likely just add a translating guide image to both the physical device and the app.

As for the components in the app; the original code was simply just for remotely turning on a led, but i tweaked it a bit so it'd be more for morse code.


For what it's worth, here are two Morse samples, purely AI2:

https://groups.google.com/d/msg/mitappinventortest/G20UeeX8M-A/hidVyiwVCAAJ

thank you so much for this !! i'll try to reference this in my project, but i'll need to find out how to connect it to my python code (required) and physical device (also required). I will keep the blocks coding in mind though, thanks again !!

This might be relevant: