Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8041

General • Re: Connecting a Pi Pico directly to the internet with SIM modules

$
0
0
Hello. I need help connecting to the io.adafruit.com server via a GPRS SIM modem.
I have been able to do it via wifi, but not with the modem.

The SIM module is the SIM800L.
The Micropython card is the Raspberry Pi Pico 2W.

Code:

import timeimport machinefrom machine import UARTfrom umqtt.simple import MQTTClient# Configuración de la interfaz UART (reemplazar con los pines apropiados para tu placa)uart = UART(0, baudrate=9600, tx=16, rx=17)# Función para enviar comandos AT y esperar respuestadef send_at_command(command, timeout=5000):    print("Enviando:", command)    uart.write(command + '\r\n')    time.sleep_ms(100)    start_time = time.ticks_ms()    response = ""    while time.ticks_diff(time.ticks_ms(), start_time) < timeout:        if uart.any():            response += uart.read().decode('utf-8')            if "OK" in response or "ERROR" in response:                break    print("Respuesta:", response)    return response# Inicializa el módulo SIMdef initialize_sim_module():    send_at_command('AT')  # Test AT startup    send_at_command('AT+CSQ')  # Signal quality test    send_at_command('AT+CREG?')  # Network registration    send_at_command('AT+CGATT?')  # GPRS attachment    send_at_command('AT+CIPSHUT')  # Shut down previous connections    send_at_command('AT+CIPSTATUS')  # Get connection status    send_at_command('AT+CIPMUX=0')  # Configure for single connection        send_at_command('AT+CSTT="your_apn","your_user","your_pass"')  # Set APN, replace with your APN, user, and password    time.sleep(2)  # Agrega un pequeño retraso    send_at_command('AT+CIICR')  # Bring up wireless connection    time.sleep(2)  # Agrega un pequeño retraso    send_at_command('AT+CIFSR')  # Get local IP address    time.sleep(2)  # Agrega un pequeño retraso    response = send_at_command('AT+CIPSTART="TCP","your.iot.server",1883')  # Start TCP connection to MQTT server    if "ERROR" in response:        raise Exception("No se pudo establecer la conexión TCP")    print("Conexión TCP establecida con éxito")# Función principaldef main():    try:        initialize_sim_module()        # Configuración del cliente MQTT        client = MQTTClient('client_id', "your.iot.server", port=1883, user="username", password="your_password")   mqtt_connect('client_id', 'your_username', 'your_password')         # Conectar al servidor MQTT        client.connect()        print("Conectado al servidor MQTT")        # Función de callback para mensajes recibidos        def sub_cb(topic, msg):            print(f"Mensaje recibido en el topic {topic}: {msg}")        # Suscribirse a un topic        client.set_callback(sub_cb)        client.subscribe(b"Topic/feeds/rizq")        print("Suscrito al topic: Tirejas/feeds/rizq")        # Publicar mensajes en un topic        while True:            client.publish(b"Topic/feeds/presionizq", b"12.3")            print("Publicado en el topic: Tirejas/feeds/presionizq, Mensaje: 12.3")            time.sleep(10)  # Publicar cada 10 segundos    except Exception as e:        print("Error:", str(e))if __name__ == '__main__':    main()
Response to the Tonny console
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot
Sending: AT
Response: AT
OK
Sending: AT+CSQ
Response: AT+CSQ
+CSQ: 27.0
OK
Sending: AT+CREG?
Response: AT+CREG?
+CREG: 0.1
OK
Sending: AT+CGATT?
Response: AT+CGATT?
+CGATT: 1
OK
Sending: AT+CIPSHUT
Response: AT+CIPSHUT
SHUT OK
Sending: AT+CIPSTATUS
Response: AT+CIPSTATUS
OK
STATE: IP INITIAL
Sending: AT+CIPMUX=0
Response: AT+CIPMUX=0
OK
Sending: AT+CSTT="telefonica.es","User_name","pass_word"
Response: AT+CSTT="telefonica.es","User_name","pass_word"
OK
Sending: AT+CIICR
Response: AT+CIICR
OK
Sending: AT+CIFSR
Response: AT+CIFSR
AA.AA.AAA.AA
Sending: AT+CIPSTART="TCP","your.iot.server",1883
Response: AT+CIPSTART="TCP","your.iot.server",1883
OK
TCP connection established successfully
Error: -6
>>>
It seems that we are communicating with TCP but not with the server.
Hello, As you can see, TCP connection established successfully but I have an Error: -6 connecting to the server. I will hard appreciate any idea to solve this matter

Statistics: Posted by Tirejas — Thu Apr 10, 2025 12:34 pm



Viewing all articles
Browse latest Browse all 8041

Trending Articles