I am reading the data from a "Torque Wrench" using "USB Host Shield2.0" and Arduino UNO. I am receiving correct data from my "Torque Wrench" Data is receiving in a array.
But when I started reading data after "for" loop inside Void loop() I am receiving incorrect data. I attached Both output pictures correct and incorrect data.
Basically I am read data from Torque Wrench and send to receiver using Nrf24l01. I am receiving incorrect data.
My question is :- Why I am reading Incorrect data outside "for" loop.
Correct Data inside "for" loop :- enter image description here
Incorrect Data outside "for" loop :- enter image description here
#include <SPI.h> // for SPI communication
#include <nRF24L01.h>
#include <RF24.h>
#include <cdcacm.h>
#include <usbhub.h>
//#include "pgmstrings.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = {'R','x','A','A','A','B'}; // the address the the module
class ACMAsyncOper : public CDCAsyncOper
{
public:
uint8_t OnInit(ACM *pacm);
};
uint8_t ACMAsyncOper::OnInit(ACM *pacm)
{
uint8_t rcode;
// Set DTR = 1 RTS=1
rcode = pacm->SetControlLineState(3);
if (rcode)
{
ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
return rcode;
}
LINE_CODING lc;
lc.dwDTERate = 9600;
lc.bCharFormat = 0;
lc.bParityType = 0;
lc.bDataBits = 8;
rcode = pacm->SetLineCoding(&lc);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
return rcode;
}
USB Usb;
//USBHub Hub(&Usb);
ACMAsyncOper AsyncOper;
ACM Acm(&Usb, &AsyncOper);
void setup() {
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MAX);
radio.stopListening();
#if !defined(__MIPSEL__)
while (!Serial);
#endif
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("USB Not Connected");
delay( 200 );
}
void loop() {
Usb.Task();
if( Acm.isReady()) {
uint8_t rcode;
/* reading the keyboard */
if(Serial.available()) {
uint8_t data= Serial.read();
/* sending to the phone */
rcode = Acm.SndData(1, &data);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
}
delay(10);
uint8_t buf[64];
uint16_t rcvd = 64;
char text[64];
rcode = Acm.RcvData(&rcvd, buf);
if (rcode && rcode != hrNAK)
ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
if ( rcvd ) {
for(uint16_t i=0; i < rcvd; i++ )
{
// Serial.print((char)buf[i]); // correct Data read from torque wrench
text[i] = (char)buf[i];
}
Serial.println(text); // reading wrong data here
//radio.write(&text, sizeof(text));
//Serial.println(text);
}
delay(10);
}
}
Character arrays must be null-terminated to count as C strings.
After the for loop, add text[rcvd] = '\0';
Also, your rcvd is fixed at 64. It needs to be one less than the array size for the null terminator to fit.
I am trying to publish the array of 786 to the MQTT Topic using ESP32 Wrover module but at the MQTT box, I am only receiving an array of 249. I am using PubSubClient Library,
What I tried in the PubSubClient library MQTT_MAX_PACKET_SIZE increase size 512 bytes still receiving the same bytes of 249 on MQTT protocol.
Code:
//#include <ArduinoJson.h>
#include <WiFi.h>
//#include <PubSubClient.h>
#include <Wire.h>
#include "MLX90640_API.h"
#include "MLX90640_I2C_Driver.h"
//#ifndef MQTT_MAX_PACKET_SIZE
////#define MQTT_MAX_PACKET_SIZE 256
//#define MQTT_MAX_PACKET_SIZE 1000
//#endif
#define MQTT_MAX_PACKET_SIZE 1000
const byte MLX90640_address = 0x33; //Default 7-bit unshifted address of the MLX90640
#define TA_SHIFT 8 //Default shift for MLX90640 in open air
float mlx90640To[768];
//char mlx90640To[768];
paramsMLX90640 mlx90640;
// Replace the next variables with your SSID/Password combination
//const char* ssid = "TP-Link_63DD";
//const char* password = "123456";
//
//const char* mqtt_server = "broker.emqx.io";
const char* ssid = "TP-Link_63DD";
const char* password = "123456";
const char* mqttServer = "broker.emqx.io";
//const char* mqttServer =" mqtt.dioty.co";
const int mqttPort = 1883;
const char* mqttUser = "******";
const char* mqttPassword = "12345";
//const char* mqttServer ="broker.hivemq.com";
//const int mqttPort = 1883;
//const char* mqttUser = "***********";
//const char* mqttPassword = "12345";
const byte led_gpio = 27;
#define row 24
#define clom 32
#define pixel 768
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
char msg[765];
int value = 0;
#define cap 800
//int lastMsg = 0;
//int value = 0;
void setup()
{
Wire.begin();
Wire.setClock(400000); //Increase I2C clock speed to 400kHz
Serial.begin(115200); //Fast serial as possible
// setup_wifi();
// client.setServer(mqtt_server, 1883);
// client.setCallback(callback);
pinMode(led_gpio, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
while (!Serial); //Wait for user to open terminal
//Serial.println("MLX90640 IR Array Example");
if (isConnected() == false)
{
Serial.println("MLX90640 not detected at default I2C address. Please check wiring. Freezing.");
while (1);
}
Serial.println("MLX90640 online!");
//Get device parameters - We only have to do this once
int status;
uint16_t eeMLX90640[832];
status = MLX90640_DumpEE(MLX90640_address, eeMLX90640);
if (status != 0)
Serial.println("Failed to load system parameters");
status = MLX90640_ExtractParameters(eeMLX90640, &mlx90640);
if (status != 0)
Serial.println("Parameter extraction failed");
//Once params are extracted, we can release eeMLX90640 array
//MLX90640_SetRefreshRate(MLX90640_address, 0x02); //Set rate to 2Hz
MLX90640_SetRefreshRate(MLX90640_address, 0x03); //Set rate to 4Hz
//MLX90640_SetRefreshRate(MLX90640_address, 0x07); //Set rate to 64Hz
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
//delay(1000);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
// Changes the output state according to the message
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("\n Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe
client.subscribe("esp32/output");
// client.subscribe("esp32/temperature");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// StaticJsonBuffer<200> JSONbuffer;
void loop()
{
int boardArray [pixel];
int boardArrayTwo [row][clom];
client.loop();
//char mlx90640To[768];
// long startTime = millis();
for (byte x = 0 ; x < 2 ; x++)
{
uint16_t mlx90640Frame[834];
int status = MLX90640_GetFrameData(MLX90640_address, mlx90640Frame);
float vdd = MLX90640_GetVdd(mlx90640Frame, &mlx90640);
float Ta = MLX90640_GetTa(mlx90640Frame, &mlx90640);
float tr = Ta - TA_SHIFT; //Reflected temperature based on the sensor ambient temperature
float emissivity = 0.95;
MLX90640_CalculateTo(mlx90640Frame, &mlx90640, emissivity, tr, mlx90640To);
//Serial.print("vdd= "); Serial.print(vdd);Serial.println("\n"); // used to print vdd
// Serial.print("Ta= "); Serial.print(Ta);Serial.println("\n"); // used to print Ta
// Serial.print("tr= "); Serial.print(tr);Serial.println("\n"); // used to print tr
//
Serial.println(" ");
}
//long stopTime = millis();
//
// StaticJsonBuffer<5000> JSONbuffer;
/*******************DynamicJsonDocument*****************************/
DynamicJsonDocument doc(13000);
//JsonObject& JSONencoder = JSONbuffer.createObject();
// JSONencoder["device"] = "ESP32";
// JSONencoder["sensorType"] = "T-Scanner";
// JsonArray& values = JSONencoder.createNestedArray("v");
doc["device"] = "ESP32";
doc["sensorType"] = "T-Scanner";
char arr[786];
for (int x = 0 ; x < 768 ; x++) //768 384
{
//if(x % 8 == 0) Serial.println();
Serial.print(mlx90640To[x],0); //value from sensor print on com port
// boardArray[x] = mlx90640To[x];
// values.add((uint8_t)mlx90640To[x]);
// array.add((uint8_t)mlx90640To[x]);
doc["values"][x] = (uint8_t)mlx90640To[x]; // AARAY value of 786 is store in values
Serial.print(",");
//delay(1000);
}
/* for (int x = 0; x < row; ++x)
{
for (int k = 0; k < clom; ++k){
boardArrayTwo[x][k] = boardArray[clom*x + k];
// tempData=boardArrayTwo[x][k];
// values.add(boardArrayTwo[x][k]);
// printf("%d ", boardArrayTwo[x][k]);
//n=sprintf(reply_buff," number %d ",tempData);
} } */
digitalWrite(led_gpio, HIGH);
//serializeJson(doc, Serial);
// JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println("\nSending message to MQTT topic..");
// Serial.println(JSONmessageBuffer);
char JSONmessageBuffer[cap]; // JSON MESSAGE CHAR BUFFER
Serial.println(serializeJson(doc, Serial));
size_t n = serializeJson(doc, JSONmessageBuffer); // formation of serialization of data
size_t sizeq = sizeof(JSONmessageBuffer) / sizeof(JSONmessageBuffer[0]);
Serial.println(" JSONmessageBuffer_size");
Serial.println(sizeq);
// delay(1000);
// snprintf(JSONmessageBuffer,768,"%d",serializeJson(doc, Serial));
//snprintf(JSONmessageBuffer,768,"%ld",serializeJson(doc, Serial));
Serial.println("\nJSONmessageBuffer:::");
Serial.println(JSONmessageBuffer);
//Serial.println("\nJSONmessageBuffer_size");
//Serial.println(n);
//*************************Data send to PUBLISH TO MQTT TOPIC******************************/
//if (client.publish("ev8051/esp32/temperature",JSONmessageBuffer) == true) // sending JSONmessageBuffer data to topic "ev8051/esp32/temperature"
// boolean beginPublish(const char* topic, unsigned int plength, boolean retained);
// boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
if(client.publish("ev8051/esp32/temperature",JSONmessageBuffer,n) == true)
{
Serial.println("\nSuccess sending message");
} else {
Serial.println("\nError sending message");
}
client.endPublish();
if (!client.connected()) {
reconnect();
}
client.loop();
Serial.println("-------------");
//delay(1000);
delay(1000);
}
//Returns true if the MLX90640 is detected on the I2C bus
boolean isConnected()
{
Wire.beginTransmission((uint8_t)MLX90640_address);
if (Wire.endTransmission() != 0)
return (false); //Sensor did not ACK
return (true);
}
Please help...
Thanks in advance.
I have created a program to display realtime firebase data sent from nodemcu ESP8266 + PZEM-004T, but the data does not appear in the realtime database, but on the serial monitor Arduino IDE it works fine.
My output:
My sketch:
#include <PZEM004Tv30.h>
#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#define FIREBASE_HOST "iotmonitor-d8aee-default-rtdb.firebaseio.com" //Firebase url non SSL(https://)
#define FIREBASE_AUTH "C7j...Gid" //Secret Key Database
#define WIFI_SSID "IKWAN_BRILink" //Nama WiFi
#define WIFI_PASSWORD "Orbit121" // Password Wifi
PZEM004Tv30 pzem(12, 13);
float harga_KWh = 1.444; //Biaya per KWh
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("connected: ");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
void loop() {
float voltage = pzem.voltage();
float current = pzem.current();
float power = pzem.power();
float energy = pzem.energy();
if (isnan(voltage) ) {
voltage = 0;
}
if (isnan(current) ) {
current = 0;
}
if (isnan(power) ) {
power = 0;
}
if (isnan(energy) ) {
energy = 0;
}
float totalHarga = energy * harga_KWh;
Firebase.setString("volt", String(voltage));
Firebase.setString("current", String(current));
Firebase.setFloat("watt", power);
Firebase.setString("kwh", String(energy, 1));
Firebase.setString("rp", String(totalHarga, 3));
Serial.print("Voltage = ");
Serial.print(voltage);
Serial.println("v");
Serial.print("Current = ");
Serial.print(current, 2);
Serial.println("A");
Serial.print("Watt = ");
Serial.print(power);
Serial.println("watt");
Serial.print("KWh = ");
Serial.print(energy, 1);
Serial.println("KWh");
Serial.print("Harga = Rp ");
Serial.print(totalHarga, 3);
Serial.println();
delay(2000);
}
i'm trying to make a live tracking for car. i used GPS Shield and GPRS Shield. it works to get GPS latitude and longatitude, and it works to store the data to my database. But, the problem is, when it get the gps coordinates, then my GPS Shield Turning off automatically when the GPRS Shield finished store the data in my database.
I use GPS/GSM/GPRS Shield from DFRobotcan and GPRS Shield from SeedStudio. i can't used my GPRS from DFRobot because i can't get signal. it's not the problem for me.
the problem is why my GPS shield shuting down when the GPRS Shield done to store the data? anyone help me
Here's my amateur code.
#include <SoftwareSerial.h>
#include <String.h>
double lati, longati, latitudefix, longatitudefix;
String latu, longatu, latdir, londir, latitudebener, longatitudebener;
SoftwareSerial mySerial(7, 8);
String id="1310220001";
void setup()
{
mySerial.begin(19200); // the GPRS baud rate
pinMode(3,OUTPUT);//The default digital driver pins for the GSM and GPS mode
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
digitalWrite(5,HIGH);
delay(1500);
digitalWrite(5,LOW);
digitalWrite(3,LOW);//Enable GSM mode
digitalWrite(4,HIGH);//Disable GPS mode
delay(2000);
Serial.begin(9600);
delay(5000);//GPS ready
Serial.println("AT");
delay(2000);
//turn on GPS power supply
Serial.println("AT+CGPSPWR=1");
delay(1000);
//reset GPS in autonomy mode
Serial.println("AT+CGPSRST=1");
delay(1000);
digitalWrite(4,LOW);//Enable GPS mode
digitalWrite(3,HIGH);//Disable GSM mode
delay(2000);
Serial.println("$GPGGA statement information: ");
}
void loop()
{
while(1)
{
Serial.print("UTC:");
UTC();
Serial.print("Lat:");
latitude();
Serial.print("Dir:");
lat_dir();
Serial.print("Lon:");
longitude();
Serial.print("Dir:");
lon_dir();
Serial.print("Alt:");
altitude();
convert();
//Serial.println(latitudebener);
//Serial.println(longatitudebener);
Serial.println(' ');
Serial.println(' ');
if(latitudebener!="0.00000"&&longatitudebener!="0.00000"){
sendlocation();
}
else{
};
}
}
void convert(){
char bufferlat[20];
latitudebener=dtostrf(latitudefix,5,5,bufferlat);
char bufferlon[20];
longatitudebener=dtostrf(longatitudefix,5,5,bufferlon);
}
void sendlocation(){
mySerial.println("AT+CSQ");
delay(100);
mySerial.println("AT+CGATT?");
delay(100);
mySerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
delay(1000);
mySerial.println("AT+SAPBR=3,1,\"APN\",\"AXIS\"");//setting the APN, the second need you fill in your local apn server
delay(4000);
mySerial.println("AT+SAPBR=1,1");//setting the SAPBR, for detail you can refer to the AT command mamual
delay(2000);;
mySerial.println("AT+HTTPINIT"); //init the HTTP request
delay(2000);
mySerial.println("AT+HTTPPARA=\"URL\",\"www.hamasa.cu.cc/editlocation.php?id="+id+"&latitude="+latitudebener+"&longatitude="+longatitudebener+"&latdir="+latdir+"&londir="+londir+"\"");
delay(2000);
mySerial.println("AT+HTTPACTION=0");//submit the request
Serial.println("8");
delay(5000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.
mySerial.println("AT+HTTPREAD");// read the data from the website you access
delay(300);
mySerial.println("");
delay(100);
}
//void sms()
//{
// mySerial.println("AT+CMGF=1\r"); //Because we want to send the SMS in text mode
// delay(100);
// ShowSerialData();
// mySerial.println("AT + CMGS = \"+6283815535385\"");//send sms message,
// //be careful need to add a country code before the cellphone number
//
// delay(100);
// ShowSerialData();
// mySerial.println("bisa bil, latitudenya:"+latitudebener+""+latdir+", terus longatitudenya:"+longatitudebener+""+londir);//the content of the message
// delay(100);
// ShowSerialData();
// mySerial.println((char)26);//the ASCII code of the ctrl+z is 26
// delay(100);
// ShowSerialData();
// mySerial.println();
// ShowSerialData();
//}
void ShowSerialData()
{
while(mySerial.available()!=0)
Serial.write(mySerial.read());
}
double Datatransfer(char *data_buf,char num)//convert the data to the float type
{ //*data_buf:the data array
double temp=0.0; //the number of the right of a decimal point
unsigned char i,j;
if(data_buf[0]=='-')
{
i=1;
//process the data array
while(data_buf[i]!='.')
temp=temp*10+(data_buf[i++]-0x30);
for(j=0;j<num;j++)
temp=temp*10+(data_buf[++i]-0x30);
//convert the int type to the float type
for(j=0;j<num;j++)
temp=temp/10;
//convert to the negative numbe
temp=0-temp;
}
else//for the positive number
{
i=0;
while(data_buf[i]!='.')
temp=temp*10+(data_buf[i++]-0x30);
for(j=0;j<num;j++)
temp=temp*10+(data_buf[++i]-0x30);
for(j=0;j<num;j++)
temp=temp/10 ;
}
return temp;
}
char ID()//Match the ID commands
{
char i=0;
char value[6]={
'$','G','P','G','G','A' };//match the gps protocol
char val[6]={
'0','0','0','0','0','0' };
while(1)
{
if(Serial.available())
{
val[i] = Serial.read();//get the data from the serial interface
if(val[i]==value[i]) //Match the protocol
{
i++;
if(i==6)
{
i=0;
return 1;//break out after get the command
}
}
else
i=0;
}
}
}
void comma(char num)//get ','
{
char val;
char count=0;//count the number of ','
while(1)
{
if(Serial.available())
{
val = Serial.read();
if(val==',')
count++;
}
if(count==num)//if the command is right, run return
return;
}
}
void UTC()//get the UTC data -- the time
{
char i;
char time[9]={
'0','0','0','0','0','0','0','0','0'
};
double t=0.0;
if( ID())//check ID
{
comma(1);//remove 1 ','
//get the datas after headers
while(1)
{
if(Serial.available())
{
time[i] = Serial.read();
i++;
}
if(i==9)
{
i=0;
t=Datatransfer(time,2);//convert data
t=t+70000.00;//convert to the chinese time GMT+8 Time zone
Serial.println(t);//Print data
return;
}
}
}
}
void latitude()//get latitude
{
char i;
char lat[10]={
'0','0','0','0','0','0','0','0','0','0'};
if( ID())
{
comma(2);
while(1)
{
if(Serial.available())
{
lat[i] = Serial.read();
i++;
}
if(i==10)
{
i=0;
char buzz[20];
lati=Datatransfer(lat,5);
latu=dtostrf(lati,5,5,buzz);
String latijam=latu.substring(0,1);
String latimin=latu.substring(1,3);
String latidet=latu.substring(4,9);
double latijamd = latijam.toInt();
double latimind = latimin.toInt();
double latidetd = latidet.toInt();
double latmin = latimind+(latidetd*0.00001);
latitudefix= latijamd+(latmin/60);
Serial.println(latitudefix,5);
return;
}
}
}
}
void lat_dir()//get dimensions
{
char i=0,val;
if( ID())
{
comma(3);
while(1)
{
if(Serial.available())
{
val = Serial.read();
latdir=String(val);
Serial.print(latdir);
Serial.println();
i++;
}
if(i==1)
{
i=0;
return;
}
}
}
}
void longitude()//get longitude
{
char i;
char lon[11]={
'0','0','0','0','0','0','0','0','0','0','0' };
if( ID())
{
comma(4);
while(1)
{
if(Serial.available())
{
lon[i] = Serial.read();
i++;
}
if(i==11)
{
i=0;
//Serial.println(Datatransfer(lon,5),5);
char buffer[20];
longati=Datatransfer(lon,5);
longatu=dtostrf(longati,5,5,buffer);
String longatijam=longatu.substring(0,3);
String longatimin=longatu.substring(3,5);
String longatidet=longatu.substring(6,11);
double longatijamd = longatijam.toInt();
double longatimind = longatimin.toInt();
double longatidetd = longatidet.toInt();
double longmin = longatimind+(longatidetd*0.00001);
longatitudefix= longatijamd+(longmin/60);
Serial.println(longatitudefix,5);
return;
}
}
}
}
void lon_dir()//get direction data
{
char i=0,val;
if( ID())
{
comma(5);
while(1)
{
if(Serial.available())
{
val = Serial.read();
londir=String(val);
Serial.print(londir);
Serial.println();
i++;
}
if(i==1)
{
i=0;
return;
}
}
}
}
void altitude()//get altitude data
{
char i,flag=0;
char alt[8]={
'0','0','0','0','0','0','0','0'
};
if( ID())
{
comma(9);
while(1)
{
if(Serial.available())
{
alt[i] = Serial.read();
if(alt[i]==',')
flag=1;
else
i++;
}
if(flag)
{
i=0;
Serial.println(Datatransfer(alt,1),1);//print altitude data
return;
}
}
}
}
try to use external power. is that works?
actually it should be :
digitalWrite(3,LOW);//Enable GSM mode
digitalWrite(4,HIGH);//Disable GPS mode
The problem may be a software serial port conflict, because GPS and GSM shields both use serial ports. In your case you have coupled shields. While receiving a GPS signal, GSM is switched off, and when a signal is acquired, the GPS turns off and GSM begin to work.
char rcv[10];
void main()
{
UART1_Init(9600);
Delay_ms(2000);
TRISB=0x00;
UART1_Write_Text("at");
UART1_Write(13); //Enter key = CF + LF
UART1_Write(10);
delay_ms(500);
while (1)
{ PORTB.RB0=1; // Endless loop
while(!UART1_Data_Ready()); // If data is received,
rcv[0]=UART1_Read();
rcv[1]=UART1_Read();
rcv[2]='\0';
UART1_Write_Text(rcv);
PORTB.RB0=0;
}
}
Compiler used : MikroC
I get the rcv output as ATTTTTTTTT. Pls help me out here to receive OK response from GSM Modem as this works with Hyperterminal.
Using PIC 18F4520 in PICPLC16v6 development board from Mikroelectronika.
It seems that you have the modem echo set on, so you'll receive each caracter you send it.
I would rewrite your code to something like :
void main(void)
{
uint8_t cmd[10];
uint8_t answer[20];
uint16_t timeout = 500; //max miliseconds to wait for an answer
UART1_Init(9600);
Delay_ms(1000);
TRISB=0;
cmd[0]='A';
cmd[1]='T';
cmd[2]=13;
cmd[3]=10;
cmd[4]=0;//marks end of CMD string
while(1)
{
uint8_t answer_len = SendModemCMD(cmd,answer,timeout);
UART1_Write_Text(answer);
Delay_ms(500);//not really needed ...
}
}
uint8_t SendModemCMD(uint8_t *cmd,uint8_t* answer,uint16_t timeout)
{
uint16_t local_timeout;
uint8_t answer_len=0;
while(*cmd!=0)
{
UART1_Write(*cmd++);
local_timeout=timeout;
while(local_timeout>0 && !UART1_Data_Ready())
{
Delay_ms(1);
local_timeout--;
}
if(UART1_Data_Ready())
{
UART1_Read();//discard echoed character
}
}
uint8_t finished=0;
while(finished==0)
{
local_timeout=timeout;
while(local_timeout>0 && !UART1_Data_Ready())
{
Delay_ms(1);
local_timeout--;
}
if(UART1_Data_Ready())
{
*answer++=UART1_Read();
answer_len++;
}
else
{
finished=1;
}
}
*answer=0;
return answer_len;
}