0

I want to interface rpi2 with gsm module, below is the code for it in python. After running the code i am not getting anything as output except newlines. I have enabled serial interfacing for rpi2 and the connections are proper. Please help.

import serial
import RPi.GPIO as GPIO
import os, time
def find(str, ch):
    for i, ltr in enumerate(str):
        if ltr == ch:
            yield i

GPIO.setmode(GPIO.BOARD)
port = serial.Serial("/dev/ttyAMA0",baudrate=115200, timeout=1)   #set timeout to x secs,returns immediately when the requested
print("connected")
port.write('hello'.encode('utf-8'))
rcv = port.read(10)
print(rcv)
time.sleep(1)
port.write('AT'+'\r\n')
port.write("\x0D\x0A")
rcv = port.read(10)
print(rcv)
time.sleep(1)

port.write('ATE0'+'\r\n')
rcv = port.read(10)
print(rcv)
time.sleep(1)

port.write('AT+CMGF=1'+'\r\n')
rcv = port.read(10)
print(rcv)
time.sleep(1)

port.write('AT+CNMI=2,1,0,0,0'+'\r\n')
rcv = port.read(10)
print(rcv)
time.sleep(1)

ck=1
while ck==1:
    rcv = port.read(10)
    print(rcv)
    fd=rcv
    if len(rcv)>3:
        ck=12
        for i in range(5):
            rcv = port.read(10)
            print(rcv)
            fd=fd+rcv

        p=list(find(fd,","))
        q=list(find(fd,'\r'))
        MsgNo=fd[p[0]+1:q[1]]

        rd=port.write('AT+CMGR='+MsgNo+'\r\n')
        msg=''
        for j in range(10):
            rcv = port.read(20)
            msg=msg+rcv
        print(msg)
    time.sleep(0.1)

I also tried a simpler code just to write and read from ttyAMA0 port but even for this code ,nothing is displayed on console :-

import serial
import RPi.GPIO as GPIO
import os, time

GPIO.setmode(GPIO.BOARD)
port = serial.Serial("/dev/ttyAMA0", baudrate=115200, timeout=1)   #set timeout to x secs,returns immediately when the requested

print("connected")
port.write('hello'.encode('utf-8'))
rcv = port.read(10)
print(rcv)
1

The GSM module cannot understand the port.write('hello'.encode('utf-8')).

Check if the module is plugged in /dev/ttyAMA0.

  • Connect your GSM Module to USB-to-TTL and check it directly by interfacing it with your computer. You can use Software like Docklight, TMFT, etc for serial communication with COM port.

  • Or you can always use Putty serial to access COM port.

  • Send AT command to COM Port after connecting it in putty serial. If it sends OK reply then the module is working and you need to check that the module is connected with Raspberry Correctly.

  • Or else you can try changing Baud Rate. (9600, 15200, etc...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.