uPY uart not communicating correctly with EG25-G - micropython

I had a motor controller connected to GP0 and GP1 so I know they work, however I cant seem to get a response from the SIM controller. Without the pico attached to the board, I can get it to work, but when I add the pico it seems like it wont send AT commands or translate received data if the pico is getting any at all. I have tried to run the code line by line in a live session and all I get is a single number that is equal to the number of letters inside the string that I am sending to the sim controller. ie uart.write(bytearray(b'ATE1\r\n')) would return >>> 6 6 being the number of characters in the code after b. I'm ordering a new pico to see if just maybe it was my sub par soldering, but in the mean time I could see if anyone more experienced than I can point out a error.
import machine
import os
import utime
import time
import binascii
from machine import UART
pwr_enable = 22 # EG25_4G Power key connected on GP22
uart_port = 0
uart_baud = 115200
# Initialize UART0
uart = machine.UART(uart_port, uart_baud)
print(os.uname())
def wait_resp_info(timeout=3000):
prvmills = utime.ticks_ms()
info = b""
while (utime.ticks_ms()-prvmills) < timeout:
if uart.any():
info = b"".join([info, uart.read(1)])
print(info.decode())
return info
def Check_and_start(): # Initialize SIM Module
while True:
uart.write(bytearray(b'ATE1\r\n'))
utime.sleep(10)
uart.write(bytearray(b'AT\r\n'))
rec_temp = wait_resp_info()
print(wait_resp_info())
print(rec_temp)
print(rec_temp.decode())
utime.sleep(10)
if 'OK' in rec_temp.decode():
print('OK response from AT command\r\n' + rec_temp.decode())
break
else:
power = machine.Pin(pwr_enable, machine.Pin.OUT)
power.value(1)
utime.sleep(2)
power.value(0)
print('No response, restarting\r\n')
utime.sleep(10)
def Network_check():# Network connectivity check
for i in range(1, 3):
if Send_command("AT+CGREG?", "0,1") == 1:
print('Connected\r\n')
break
else:
print('Device is NOT connected\r\n')
utime.sleep(2)
continue
def Str_to_hex_str(string):
str_bin = string.encode('utf-8')
return binascii.hexlify(str_bin).decode('utf-8')
Check_and_start()
Network_check()
Response is
>>> Check_and_start()
b''
b'\x00\x00'
No response, restarting

New Pico fixed my issue, I believe it to be that my inadequate soldering skills created the issue. Symptoms were, no UART data was being transmitted or received through UART pins 0 and 1. Solution was new Pico board was inserted in place of old one, same code was uploaded and ran successfully first time.

Related

TTN (The Things Network) counter and Pycom Lopy4 problem

I have a problem on the counter in TTN. this problem happened after I added machine.deepsleep function in my LoPy4. I have used the nvram_save () and nvram_restore () functions, but the counter in TTN still not increment.
this screenCapture :
So, what's the problem in this case ?
this my code :
enter code here
import ads1x15 as extADC
import gc
import pycom
import socket
from network import LoRa
from uModBus.serial import Serial
from network import LoRa
import machine
import ubinascii
import utime
from machine import RTC, I2C
from machine import Pin
pycom.heartbeat(False)
rtc = RTC()
i2c = I2C(0, I2C.MASTER, pins=('P3', 'P4'), baudrate=100000)
adc = extADC.ADS1115(i2c, gain=1)
pinTrig = Pin('P23', mode=Pin.OUT)
# LoRa Socket Connection with two condition
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
pinTrig.value(1) # enable High (12v)
print("WOKE UP FROM DEEPSLEEP 3 MINUTES !")
utime.sleep(1)
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AS923)
lora.nvram_restore() # Nvram restore function
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
s.setblocking(False)
s.bind(1)
else:
pinTrig.value(1)
utime.sleep(1)
print("I'M PowerOn by Humans or Hard reset !")
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AS923)
lora.nvram_restore() # Nvram restore function
app_eui = ubinascii.unhexlify('********************')
app_key = ubinascii.unhexlify('-----------------------------')
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
while not lora.has_joined():
utime.sleep(2.5)
print('Not yet joined...')
print('Joined')
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
s.setblocking(True)
s.bind(1)
### Begin sensor reading and sending function ##################
def read_data_Sensor () :
### End sensor reading and sending function ####################
try:
read_data_Sensor()
lora.nvram_save()
utime.sleep(1)
pinTrig.value(0)
print("DeepSleep Mode")
utime.sleep(1)
machine.deepsleep(180000)
except OSError:
print("Terjadi Error - Restart")
s.send(b"\xff\xff")
utime.sleep(1)
machine.reset()
My understanding of the nvmram_save/restore methods is that they restore the full state of the lora stack, including the 'joined/not joined' status.
If you explicitly do the join() every time, then this both wastes energy/time in the join exchange, and this process will always reset the counters back to 0.
I think your code should test lora.has_joined() after the nvram_restore(), and only do the join procedure if this returns False.
btw I have also experienced issues with pycom and nvmram_save/restore with TTN v3.

Micropython webserver stops working when add code to read data from dht11

I've downloaded webserver code from https://docs.micropython.org/en/v1.8/esp8266/esp8266/tutorial/network_tcp.html, it worked well. But after adding code reading dht11 values, webserver stops responding. What's wrong with my code?
import machine
import dht
import socket
import network
sta_if = network.WLAN(network.STA_IF)
sta_if.connect(SSID, PASS)
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
d = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
def measure():
d.measure()
temp = d.temperature()
hum = d.humidity()
return temp, hum
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = measure()
cl.send(response)
cl.close()
I see two problems with your code:
First, to read the DHT11 sensor you need to use a DHT object. Try replacing
d = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
with
d = dht.DHT11(machine.Pin(5))
Second, the output of your measure() function is a numeric tuple and you're passing that directly to cl.send(), but that method needs a bytes object. You need to encode the two values into a string then convert that into bytes first. Instead of
cl.send(response)
you probably want something like
message = 'Temperature {} Humidity {}'.format(response[0], response[1])
cl.send(bytes(message, 'utf-8'))

Running different commands with different words in PocketSphinx

I have found ways to make pocketsphinx activate using multiple keywords, but I want to run diffrent commands depending on which keyword was said. I have already made it connect to Amazon's Alexa server when "Alexa" is said and now I want to add a command when I say "TV Off" and "TV On."
The best thing is to use python, something like this:
import sys, os
from pocketsphinx.pocketsphinx import *
from sphinxbase.sphinxbase import *
import pyaudio
modeldir = "../../../model"
# Create a decoder with certain model
config = Decoder.default_config()
config.set_string('-hmm', os.path.join(modeldir, 'en-us/en-us'))
config.set_string('-dict', os.path.join(modeldir, 'en-us/cmudict-en-us.dict'))
config.set_string('-kws', 'keyword.list')
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)
stream.start_stream()
# Process audio chunk by chunk. On keyword detected perform action and restart search
decoder = Decoder(config)
decoder.start_utt()
while True:
buf = stream.read(1024)
if buf:
decoder.process_raw(buf, False, False)
else:
break
if decoder.hyp() == "tv on":
print ("Detected keyword tv on, turning on tv")
os.system('beep')
decoder.end_utt()
decoder.start_utt()
if decoder.hyp() == "tv off":
print ("Detected keyword tv off, turning off tv")
os.system('beep beep')
decoder.end_utt()
decoder.start_utt()

OMNET++ wireless communication client-server

It's the first time I'm using OMNET++.
I want to start from the very basic stuff to understand how it works.
I successuffly created my first simulation with two hosts continuosly exhanging mesagges (from tictoc example).
What I would like to do now is to simulate a simple client-server wireless communication between one AP and one wireless node. I'm trying to do that using elements from the inet class but I'm stuck and it is not working.
import inet.networklayer.configurator.base.NetworkConfiguratorBase;
import inet.networklayer.configurator.ipv4.IPv4NetworkConfigurator;
import inet.networklayer.configurator.ipv4.IPv4NodeConfigurator;
import inet.node.inet.WirelessHost;
import inet.node.wireless.AccessPoint;
import inet.physicallayer.common.packetlevel.RadioMedium;
import inet.physicallayer.contract.packetlevel.IRadioMedium;
import inet.physicallayer.ieee80211.packetlevel.Ieee80211RadioMedium;
//
// TODO documentation
//
network net
{
string mediumType = default("IdealRadioMedium");
#display("bgb=620,426");
submodules:
wirelessHost1: WirelessHost {
#display("p=423,164");
}
accessPoint1: AccessPoint {
#display("p=147,197");
}
iRadioMedium: <mediumType> like IRadioMedium {
#display("p=523,302");
}
iPv4NetworkConfigurator: IPv4NetworkConfigurator {
#display("p=270,324");
assignDisjunctSubnetAddresses = false;
}
}
and then I created a wirelessHost.cc source file using the tictoc beahviour to make the two nodes communicate.
But it is not working, I get this error:
<!> Error in module (inet::IPv4NodeConfigurator) infrastructure.wirelessHost1.networkLayer.configurator (id=13) during network initialization: Configurator module 'configurator' not found (check the 'networkConfiguratorModule' parameter).
But before doing something, it was another error about the Access Point (could not find wlan[0] module).
Can someone help me to understand how to configure this model?
EDIT
Here's the configuration .ini file
[General]
network = infrastructure
#cmdenv-output-file = omnetpp.log
#debug-on-errors = true
tkenv-plugin-path = ../../../etc/plugins
#record-eventlog = true
**.constraintAreaMinX = 0m
**.constraintAreaMinY = 0m
**.constraintAreaMinZ = 0m
**.constraintAreaMaxX = 600m
**.constraintAreaMaxY = 500m
**.constraintAreaMaxZ = 0m
**.mobility.typename = "StationaryMobility"
**.mobilityType = "StationaryMobility"
# access point
*.accessPoint.wlan[0].mac.address = "004444444444"
*.accessPoint.wlan[0].radio.channelNumber = 11
# host1 is associated with AP1 on channel 0
**.wirelessHost1.wlan[0].mgmt.accessPointAddress = "004444444444"
*.wirelessHost1.**.mgmtType = "Ieee80211MgmtSTASimplified"
# global data rates
**.wlan*.bitrate = 11Mbps
# application level: host1 pings host2
**.numPingApps = 1
*.wirelessHost1.pingApp[0].destAddr = "accessPoint"
*.wirelessHost1.pingApp[0].sendInterval = 10ms
but running the simulation I get
<!> Error in module (inet::ICMP) infrastructure.wirelessHost1.networkLayer.icmp (id=17) at event #4, t=0.008442657441: check_and_cast(): cannot cast (inet::GenericNetworkProtocolControlInfo*) to type 'inet::IPv4ControlInfo *'.
An instance of IPv4NetworkConfigurator in network has to be named configurator. After changing its name your second problem should be resolved too.
Moreover, the name of RadioMedium instance module has to be: radioMedium (instead of iRadioMedium).
EDIT
You have made two mistakes.
AccessPoint does not have network layer, because it only relays and sends MAC frames using MAC layer and MAC addresses - like in real network. As a consequence, it does not have an IP address and it is impossible to send ICMP ping to it.
OMNeT++ allows to use module's name instead of an IP address in ini file, for example **.destAddr = "wirelessHost1". In your ini you are trying to use non existing accessPoint instead of accessPoint1 (which is incorrectly because of the first error).
I suggest adding a new WirelesHost (for example wirelessHost2) and sending ping towards it, i.e.
*.wirelessHost1.pingApp[0].destAddr = "wirelessHost2"

Problem reading Serial Port C#.net 2.0 to get Weighing machine output

I'm trying to read weight from Sartorius Weighing Scale model No BS2202S using the following code in C#.net 2.0 on a Windows XP machine:
public string readWeight()
{
string lastError = "";
string weightData = "";
SerialPort port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 9600;
port.Parity = Parity.Even;
port.DataBits = 7;
port.StopBits = StopBits.One;
port.Handshake = Handshake.RequestToSend;
try {
port.Open();
weightData = port.ReadExisting();
if(weightData == null || weightData.Length == 0) {
lastError = "Unable to read weight. The data returned form weighing machine is empty or null.";
return lastError;
}
}
catch(TimeoutException) {
lastError = "Operation timed out while reading weight";
return lastError;
}
catch(Exception ex) {
lastError = "The following exception occurred while reading data." + Environment.NewLine + ex.Message;
return lastError;
}
finally {
if(port.IsOpen == true) {
port.Close();
port.Dispose();
}
}
return weightData;
}
I'm able to read the weight using Hyperterminal application (supplied with Windows XP) with the same serial port parameters given above for opening the port. But from the above code snippet, I can open the port and each time it is returning empty data.
I tried opening port using the code given this Stack Overflow thread, still it returns empty data.
Kindly assist me.
I know this is probably old now ... but for future reference ...
Look at the handshaking. There is both hardware handshaking and software handshaking. Your problem could be either - so you need to try both.
For hardware handshaking you can try:
mySerialPort.DtrEnable = True
mySerialPort.RtsEnable = True
Note that
mySerialPort.Handshake = Handshake.RequestToSend
I do not think sets the DTR line which some serial devices might require
Software handshaking is also known as XON/XOFF and can be set with
mySerialPort.Handshake = Handshake.XOnXOff
OR
mySerialPort.Handshake = Handshake.RequestToSendXOnXOff
You may still need to enable DTR
When all else fails - dont forget to check all of these combinations of handshaking.
Since someone else will probably have trouble with this in the future, hand shaking is a selectable option.
In most of the balances you will see the options for Software, Hardware 2 char, Hardware 1 char. The default setting for the Sartorius balances is Hardware 2 Char. I usually recommend changing to Software.
Also if it stops working all together it can often be fixed by defaulting the unit using the 9 1 1 parameter. And then resetting the communication settings.
An example of how to change the settings can be found on the manual on this page:
http://www.dataweigh.com/products/sartorius/cpa-analytical-balances/