I'm currently working with an Arduino trying to build an ad hoc network to which a device can connect to and send web requests to. The problem I am currently having is that I can only set up one connection and then when that connection is terminated (with client.stop()), all subsequent connections are not picked up by the server, even a cURL command just sits there spinning. The first connection I start when I reset the server works fine, and I am able to talk to the server; but after that, the Arduino can no longer find new clients (even though it's trying with the library given).
I`m using the SparkFun library for the WiFly shield cloned from GitHub, along with an Arduino Uno.
My current code is based off their default example 'WiFly_AdHoc_Example', but I had to remove a few things to get the network to start up which might be the cause of this problem.
Here is the .ino file that I am running.
#include <SPI.h>
#include <WiFly.h>
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial( 5, 4); //Part from example not used (see below)
WiFlyServer server(80); //Use telnet port instead, if debugging with telnet
void setup()
{
Serial.begin(9600);
//The code below is from the example, but when I run it the WiFly will hang
// on Wifly.begin(). Without it, the WiFly starts up fine.
//mySerial.begin(9600);
//WiFly.setUart(&mySerial); // Tell the WiFly library that we are not
// using the SPIUart
Serial.println("**************Starting WiFly**************");
// Enable Adhoc mod
WiFly.begin(true);
Serial.println("WiFly started, creating network.");
if (!WiFly.createAdHocNetwork("wifly"))
{
Serial.print("Failed to create ad hoc network.");
while (1)
{
// Hang on failure.
}
}
Serial.println("Network created");
Serial.print("IP: ");
Serial.println(WiFly.ip());
Serial.println("Starting Server...");
server.begin();
Serial.print("Server started, waiting for client.");
}
void loop()
{
delay(200);
WiFlyClient client = server.available();
if (client)
{
Serial.println("Client Found.");
// A string to store received commands
String current_command = "";
while (client.connected())
{
if (client.available())
{
//Gets a character from the sent request.
char c = client.read();
if (c=='#' || c=='\n') //End of extraneous output
{
current_command = "";
}
else if(c!= '\n')
{
current_command+=c;
}
if (current_command== "get")
{
// output the value of each analog input pin
for (int i = 0; i < 6; i++)
{
client.print("analog input ");
client.print(i);
client.print(" is ");
client.print(analogRead(i));
client.println("<br />");
}
}
else if(current_command== "hello")
{
client.println("Hello there, I'm still here.");
}
else if (current_command== "quit")
{
client.println("Goodbye...");
client.stop();
current_command == "";
break;
}
else if (current_command == "*OPEN*")
{
current_command == "";
}
}
}
// Give the web browser time to receive the data
delay(200);
// close the connection
client.stop();
}
}
This script is just a mini protocol I set up to test. Once connected with the wifly module you can send text such as "get" "hello" or "quit" and the wifly module should respond back.
Using Telnet I can successfully connect (the first time) and send commands to the Arduino including "quit" to terminate the connection (calls the client.stop() method). But when I try to reconnect though Telnet, it says the connection was successful, but on the Arduino it's still looping thinking the client is still false. What??
I know right, I'm getting mixed messages from Telnet vs Arduino. None of the commands work obviously since the Ardunio is still looping waiting for a client that evaluates to true. I'm going to take a look at WiFlyServer from the library I imported and see if I can dig up the problem, because somehow that server.available() method isn't finding new clients.
I am noticing a lot of TODO's in the library code....
So I found the reason for the problem. It was in the WiFlyServer.cpp file from the SparkFun library. The code that was causing the reconnect issue was in fact the server.availible() method. Right at the top of the method, there is a check:
// TODO: Ensure no active non-server client connection.
if (!WiFly.serverConnectionActive) {
activeClient._port = 0;
}
For some reason when I comment this out, I can connect and reconnect perfectly fine and everything works as it should. I will now dive into the library and see if I can fix this, I'm not exactly sure what this is doing, but it gets called when the server connection is not active and is somehow blocking subsequent connections. The problem with this solution is that the Arduino always thinks it has found a client since client and client.connected() evaluate to true even if one doesn't exist. Even client.available() evaluates to true right when the connection is terminated and the ghost "client" is found, but after that first run through the if-statement the ghost "client" is no longer available(). Even with this flaw it still picks up a new client when it comes along which is why it works.
How might I get to the root of this problem without using this commenting hack?
Are their any risks or future problems I might run into doing it this way?
What is the purpose of the block that I commented out in the first place?
Well, when you're calling client.stop(); how does the Arduino know whether the client has to start again?
Remember setup() executes only once.
Have you tried to include the following code in your loop to tell the Arduino to create the WiFly AdHoc network again? This may or may not work. I don't have one myself and haven't played with the Wifly shield but it's worth a try.
Remember to only ever execute the code once every time you need to connect again since it's sitting inside a loop that's always going to be running.
WiFly.begin(true);
Serial.println("WiFly started, creating network.");
if (!WiFly.createAdHocNetwork("wifly"))
{
Serial.print("Failed to create ad hoc network.");
while (1)
{
// Hang on failure.
}
}
Related
When the socket times out while waiting for a read it occasionally fails. But when it does fail, it continuously fails, and the log message in slotDisconnected never gets reported despite mpSocket's disconnected signal being connected to slotDisconnect(). It's as if the return statement in slotConnected isn't being hit and it's going round in a continous loop.
void Worker::slotDisconnected()
{
// Attempt to reconnect
log("Disconnected from Server. Attempting to reconnect...");
// fires mpSocket's connect signal (which is connected to slotConnected)
connectToServer();
}
void Worker::slotConnected()
{
// Loop forever while connected and receiving messages correctly
while(1)
{
if(mpSocket->bytesAvailable())
{
// A message is ready to read
}
else if(!mpSocket->waitForReadyRead(mSocketTimeOut))
{
// waitForReadyRead returned false - instead of continuing and trying again, we must disconnect as sometimes
// (for some unknown reason) it gets stuck in an infinite loop without disconnecting itself as it should
log("Socket timed out while waiting for next message.\nError String: " + mpSocket->errorString());
msleep(3000);
mpSocket->disconnect();
return;
}
}
}
The signals/slots are connected like so:
connect(mpSocket, &QAbstractSocket::disconnected, this, &TRNGrabberWorker::slotDisconnected);
connect(mpSocket, &QAbstractSocket::connected, this, &TRNGrabberWorker::slotConnected);
Anyone have any idea's what's going on? Would be much appreciated
To disconnect from server use mpSocket->disconnectFromHost(); instead of mpSocket->disconnect();.
Actually mpSocket->disconnect(); disconnects all signals/slots of object mpSocket.
I am quite rusty when it comes to Serial ports. I want to send an AT command to a GSM/ GPRS shield connected to my Arduino UNO. The AT command I want to pass in particular is the command to get a networks signal strength.
I am using the SIM900 and SoftwareSerial library to send the command as the GSM library does not compile correctly for me. Meaning I have to use the SoftwareSerial library.
I have this example code from the SIM900 library working that relies on reading inputs from the serial monitor to carry out commands but I need it to be automated and the command to be passed in hardcoded. In this example code, the place of interest is the simplehwread() method.
#include "SIM900.h"
#include <SoftwareSerial.h>
int numdata;
char inSerial[40];
int i=0;
void setup()
{
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield testing.");
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(9600))
Serial.println("\nstatus=READY");
else Serial.println("\nstatus=IDLE");
};
void loop()
{
//Read for new byte on serial hardware,
//and write them on NewSoftSerial.
serialhwread();
//Read for new byte on NewSoftSerial.
serialswread();
};
void serialhwread()
{
i=0;
if (Serial.available() > 0) {
while (Serial.available() > 0) {
inSerial[i]=(Serial.read());
delay(10);
i++;
}
inSerial[i]='\0';
if(!strcmp(inSerial,"/END")) {
Serial.println("_");
inSerial[0]=0x1a;
inSerial[1]='\0';
gsm.SimpleWriteln(inSerial);
}
//Send a saved AT command using serial port.
if(!strcmp(inSerial,"TEST")) {
Serial.println("SIGNAL QUALITY");
gsm.SimpleWriteln("AT+CSQ");
} else {
Serial.println(inSerial);
gsm.SimpleWriteln(inSerial);
}
inSerial[0]='\0';
}
}
void serialswread()
{
gsm.SimpleRead();
}
No matter how I modify this code, the command does not get passed in and response displayed while the method here does it but not the way I want it to be done. i.e Direct input. Could anyone assist here?
i have dealt with exactly this scenario at a company with a cellular radio on board. there are many status signals that come over and if not dealt with appropriately these status flags from the cell modem will be lost
you need to look at the data sheets associated with your cell modem and its protocol so you know what flags to watch for at the various steps taken along the way from configuration, to eventual connection to cellular service.
multi-threaded coding techniques must be followed as well.
keep in mind that the comm channel is not ideal and there WILL be failures. provided your coding techniques are sound and you follow protocol requirements, then it should work.
Ron
Boise, ID
I'm working on a project that has to turn a pump off upon sending an sms to the microcontroller. This code below has to be able to read and download the message so it can turn the pump off but it is not working. Can someone please check the code and let me know the problem. The microcontroller used is atmega32 and the software to program it is atmel studio 6.1.
while(1)
{
//check_sensor();
/*uint8_t x=0;
while(GSMWaitForMsg(&id)!=GSM_OK)
{
if(x)
{
LCDWriteStringXY(10,3,"%3"); //LOVE SYMBOL TILL MSG COMES CHECK MYUTILS.H
x=0;
}
else
{
LCDWriteStringXY(10,3,"%4"); //ARROW TO SHOW MESSAGE DOWNLOAD
x=1;
}
}
LCDWriteStringXY(10,3,"%2");
_delay_ms(1000);
//function to read message
char msg[300];
int8_t r=GSMReadMsg(id,msg); //ID=NUMBER MSg=MESSAGE OA=THE REPLY
if(r==GSM_OK)
{
if(strcasecmp(msg,"STOP")==0) // checking if message read is stop
{
PORTC|=(1<<PC7);
LCDClear();
LCDWriteStringXY(0,1,"PUMP TURNED OFF"); // displaying on the lcd screen
RelayOff(); // turning the relay off
_delay_ms(2000);
goto comehomeboy; // going back to home
}
}
}
The message received for GSM module (on UART of controller) are merely ASCII characters.Mostly there is no NULL(\0) appended to the data.
For strcasecmp() function you need NULL terminated strings as Input.
Please make sure 'msg' array is terminated with NULL.
I Am using Arduino UNO and SIM900A module for GSM + ARDUINO based communication.I used following code to call a specific number but nothing happens,
void setup()
{
Serial.begin(9600);
delay(10000);
}
void loop()
{
Serial.println("ATDTxxxxxxxxxx;"); //where xxxxxxxxxx is a 10 digit mobile number
delay(30000); // wait 20 seconds.
Serial.println("ATH"); // end call
do // remove this loop at your peril
{
delay(1);
}
while (1>0);
}
whereas when i used ATDTxxxxxxxxxx; in minicom while communicating with SIM900A module, i was able to call(AS ATDxxxxxxxxxx was giving No carrier error, so i used " ; ").Similr is the case with Sending message. I am getting "+CMS ERROR: 302" while i am using
AT+ CMGF=1
AT+CMGS="Mobno." //after this i get the error.
I am not able to send the message through minicom + SIM900A GSM module and i want to test it with Arduino.I think i am having some problem with settings of SIM or either module.I even tried to reset the settings of SIM , but nothing worked out.
First of all: never, never ever use delay instead of proper waiting by parsing the actual response given by the modem. And you must read back the responses given by the modem and wait for the final result code before proceeding to the next command. See this answer and this answer for more details (especially regarding proper AT+CMGS handling).
A list of all the CMS ERRORs are defined in 27.005 in the section 3.2.5 Message Service Failure Result Code +CMS ERROR. Does your subscription allow sending SMS (most likely, but just to be sure check this. Test sending an sms using this sim inserted into another mobile phone)? What message storage are you using? Are you sure the gsm module supports text mode?
I solve the problem just use this code:
void setup()
{
Serial.begin(9600);
delay(10000);
}
void loop()
{
Serial.println("ATD+60148266823;"); //where xxxxxxxxxx is a 10 digit mobile number
delay(30000); // wait 20 seconds.
Serial.println("ATH"); // end call
do // remove this loop at your peril
{
delay(1);
} while (1>0);
}
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println("AT");
delay(500);
Serial.print("ATD");
Serial.println("99XXXXXXX8;");
delay(20000);
Serial.println("ATH");
}
I have a simple sketch on my Seeeduino Mega 1.22 which just displays the serial input on a LCD Display. Using lynx term and the arduino serial monitor works fine: sent input is being displayed. The trouble starts when I want to start serial communication between my Java programm, running in Eclipse on a Win7 x64 machine, and the Seeeduino. I'm using the RXTX x64 build. The programm is intended to send and receive some string.getBytes() via the open port. Receiving on the Java side works, but receiving on the Arduino side fails.
It seems that the problem is the proper Flow Control setting. I saw that some people had the same issue like here Issues receving in RXTX
But this solution does not work for me. If I set the FlowControl to None, than I get only a block icon on the display, indicating, that the serial connection has been established, but nothing else. If I set the FlowControl to RCTS_IN | RCTS_OUT, then I get the string bytes only on the display when I close the established connection.
Why is the data only send when I close the connection (Flushing the out stream did not help as well) ? What am I doing wrong with the Flow Controll settings?
This is the modified connect() method I'm using.
void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
try {
serialPort.setFlowControlMode(
// SerialPort.FLOWCONTROL_NONE);
// OR
// If CTS/RTS is needed
//serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
} catch (UnsupportedCommOperationException ex) {
System.err.println(ex.getMessage());
}
serialPort.setRTS(true);
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
(new Thread(new SerialWriter(out))).start();
serialPort.addEventListener(new SerialReader(in, this));
serialPort.notifyOnDataAvailable(true);
} else {
System.out.println("Error: Only serial ports are to use!");
}
}
}
Thanks in advance for your time
Solved it. It was not the buffer, as many suggested it. The problem was, that the Seeeduinos RST Switch on the board was set to automatic. Setting it to manual, solved the problem.
No Flow-Controll needed.