I am writing a small test program that attempts to perform a serial.write() followed by a serial.read() within an ISR. The code will eventually be used to prompt an external GSM shield to send an SMS on a regular basis.
ISR(TIMER2_OVF_vect) {
Serial.println("AT+CMGS=\"0123456789\""); // Tell Sim900 To prepare sms to number 01...
while(Serial.read()!='>'); // Wait for Sim900 to respond
Serial.print("A text message"); // the SMS body
Serial.write(0x1A); //Confirm send instruction
Serial.write(0x0D);
Serial.write(0x0A);
}
}
What I have found after a lot of testing is that Serial.read() within an ISR is not capable of reading a live serial prompt, instead it will only read any input that was buffered before the ISR was triggered.
Is there any way around this?
The only solution I have found is to place this code instead within the main loop(). But I want to send the SMS using a timer interrupt.
Thank you
You need to place the code in the loop() but using an IF:
float toBeSent = interval;
loop() {
if (millis() > toBeSent) {
Send();
toBeSent = milli() + interval;
}
}
interval is your sending interval in milliseconds.
I had a similar problem a while ago which I managed to resolve by using the Arduino SoftwareSerial library instead of the hardware based Serial.read.
There are some overheads associated with using SoftwareSerial, and you can only read one port at a time, so I leave it up to those with a better understanding of the Arduino platform to tell you if this is a good idea, but one of the benefits of this library is that you can use it within an ISR.
To use the SoftwareSerial library, add the following two lines of code at the top of your sketch remembering to replqce the rx_pin and tx_pin with the corresponding pin values you want to use:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(rx_pin, tx_pin);
Then replace the key word Serial throughout your sketch with mySerial (or whatever name you have chosen to give your SoftwareSerial instance).
An important thing to keep in mind when using SoftwareSerial is that you can only use certain pins on the Arduino so read the documentation first.
If you wanted to live dangerously you could enable interrupts inside the ISR and use a flag to prevent reentry.
int flag=0;
ISR(TIMER2_OVF_vect) {
flag = 1
if (flag){return;}
sei();
Serial.println("AT+CMGS=\"0123456789\""); // Tell Sim900 To prepare sms to number 01...
while(Serial.read()!='>'); // Wait for Sim900 to respond
Serial.print("A text message"); // the SMS body
Serial.write(0x1A); //Confirm send instruction
Serial.write(0x0D);
Serial.write(0x0A);
}
flag = 0;
}
Related
To the stackoverflow community,
First, let me begin by saying that I'm not a code writer (though I'm quite familiar with LabVIEW). My background is in Laser and optical system design and development. Currently, I'm trying to integrate servos into an optical component used in a long range atmosphere mapping Lidar. The optical component, refereed to as a TR-Swich, is critical in maintaining the alignment between the Transmitted Laser pulse stream and back-scattered Return light. In order to ensure long-term alignment and compensate for optical mount thermal and shock drift, the servos - connected to optical mount pitch and yaw actuators - will allow our customers to adjust the TR-Swich as needed and thereby maintain optimum signal returns. Due to a variety of constraints (time, space, ease of integration into existing hardware, etc.), I'm hoping to use servos, which are small and reliable and can be easily controlled using an Arduino UNO board. I've already proven that they work quite well to move and set the position of the actuators; now I'm trying to get the GUI interface working...which hopefully is where all of you come in...
Since I'm new to Arduino board code (and the related Processing code), I snooped around and found code published on hackster.io (back in 2020) - which is close to what I'm looking for. The code was written by engineerkid (his hackster user name). I copied his code for both the Arduino board and the Processing GUI, but haven't been able to get it to work. I reached out to him (through hackster) but haven't received a reply. The message I sent him was, " Hi Enginnerkid, First, I want to thank you for posting the example! It's very close to what I ultimately need for adjusting optical mounts using servos. I copied your code for both the Arduino and Processing sketches and it's close to working, but something isn't quite right. The servo (practically identical to what you're using in your example) moves to the center position and the display based on the mouse position using the Processing code work just fine. Unfortunately, the servo doesn't respond to the mouse movements. As a heads up, currently I'm only using one servo - are two servos required in order for the code to work? Going on this premise, I deleted the code related to one of the servos, but still wasn't able to achieve any movement. I did some browsing regarding communication problems between Arduino and Processing code and found the following comment (which might be relevant), " The serial monitor in Arduino is like a separate terminal program so it and your Processing sketch are competing for the same serial connection to the Arduino." Any help you can provide would be greatly appreciated! Thanks! Steve"
His Arduino code is:
#include <Servo.h>
char tiltChannel=0, panChannel=1;
Servo servoTilt, servoPan;
char serialChar=0;
void setup()
{
servoTilt.attach(9); //The Tilt servo is attached to pin 9.
servoPan.attach(10); //The Pan servo is attached to pin 10.
servoTilt.write(90); //Initially put the servos both
servoPan.write(90); //at 90 degress.
Serial.begin(57600); //Set up a serial connection for 57600 bps.
}
void loop()
{
while(Serial.available() <=0); //Wait for a character on the serial port.
serialChar = Serial.read(); //Copy the character from the serial port to the variable
if(serialChar == tiltChannel){ //Check to see if the character is the servo ID for the tilt servo
while(Serial.available() <=0); //Wait for the second command byte from the serial port.
servoTilt.write(Serial.read()); //Set the tilt servo position to the value of the second command byte received on the serial port
}
else if(serialChar == panChannel){ //Check to see if the initial serial character was the servo ID for the pan servo.
while(Serial.available() <= 0); //Wait for the second command byte from the serial port.
servoPan.write(Serial.read()); //Set the pan servo position to the value of the second command byte received from the serial port.
}
//If the character is not the pan or tilt servo ID, it is ignored.
}
His Processing code is:
import processing.serial.*;
Serial port; // The serial port we will be using
int xpos=90; // set x servo's value to mid point (0-180)
int ypos=90; // set y servo's value to mid point (0-180)
void setup()
{
size(360, 360);
frameRate(100);
String arduinoPort = Serial.list()[0];
port = new Serial(this, arduinoPort, 57600);
}
void draw()
{
fill(175);
rect(0,0,360,360);
fill(255,0,0); //rgb value so RED
rect(180, 175, mouseX-180, 10); //xpos, ypos, width, height
fill(0,255,0); // and GREEN
rect(175, 180, 10, mouseY-180);
update(mouseX, mouseY);
}
void update(int x, int y)
{
//Calculate servo postion from mouseX
xpos= x/2;
ypos = y/2;
//Output the servo position ( from 0 to 180)
port.write(xpos+"x");
port.write(ypos+"y");
}
If you would like to look at his code, and the really cool example he set up, the site link is:
https://www.hackster.io/engineerkid/servo-motor-control-using-arduino-and-processing-af8225#team
As mentioned above, I simplified the code by removing the pan servo control, but still wasn't able to get any response from the servo using the tilt portion of the code. It does appear to be related to a communication bottleneck, I'm just not sure what small snip-it of code needs to be added to prevent the conflict. By the way, one indication that the communication is at fault is the LED serial com lights on the Arduino board. Prior to using (or trying to use the Processing GUI) I copied published code for moving a servo just with the Arduino code and was able to position the servo at any desired angle (form 0 to 180 degrees). I noticed that with each upload of the code (which would set the servo to any chosen hard coded angle value), the LEDs would flicker and toggle back and forth as the new code uploaded. Now with the GUI, only 1 LED stays on continuously... which is probably not a good sign...
As I mentioned to Engineerkid, any help you can provide would be greatly appreciated!
Thanks for your time.
Steve
The java code does not send what your arduino sketch expects (or vice versa)
You're reading a single control character and compare it with one of two allowed values:
serialChar = Serial.read();
if(serialChar == tiltChannel){
I suggest to change at the Arduino side
char tiltChannel='x', panChannel='y';
And to modify the java side to
port.write("x");
port.write(xpos);
Same for the other servo, too.
And make sure each java port.write sends a single byte only.
I'm pretty new to Arduino and especially ESP32. But - before I receive the tip "use an Arduino" - I decided to go for the ESP32 because of the size and the capability to connect it to the WLAN.
However, I am trying to build some control box for my terrarium which should - in the first design - steer various lamps and the rain pump via remote controlled outlets. For this I got an ESP32 NodeMCU, a RTC time module (which seems to work quite fine) and a 433 Hz receiver/sender set.
I followed several tutorials regarding the wiring and uploaded the example files to the ESP32. No matter which pin I connect the Receiver to (I need to connect the receiver first in order to read out the signals of the 433 Hz control which came with the outlets) I won't receive any signals on the receiver.
I embedded the library RCSwitch and I tried to configure my switch as follows (here with PIN 13 as example - I tried several other pins as well):
mySwitch.enableReceive(13)
As I read in some other blog, there might be the need to convert the pin number to its interrupt address, so I tried the following:
mySwitch.enableReceive(digitalPinToInterrupt(13))
The result is always the same: dead silence on the serial monitor (except the boot messages, etc.).
Am I using the wrong library or what am I doing wrong here?
I read that there should be a library called RFSwitch, but the only version I found only features the 433 Hz sender, not the receiver.
I would be really grateful for any hint concerning this issue - I'm pretty stuck here for many hours now...
I know this is pretty old and maybe you've resolved the issue by now but maybe it will help others. I had the same issue and what helped me was to set the pinMode:
pinMode(GPIO_NUM_35, INPUT);
mySwitch.enableReceive(digitalPinToInterrupt(GPIO_NUM_35));
Have been successful with RCSwitch today on ESP32 Dev Board and a 433MHZ receiver and sender. Here is what I have been stumbling on my journey.
Connecting the receiver (requires 5V)
You can use the ESP32-VIN for 5V if the Micro-USB is used to supply power
You may connect the Receiver-DATA to any ESP-32-Input-PIN BUT you might damage your ESP32 since it only allows ~3.3V
I tried first with some "makeshift" level shifting through resistors but I guess it lowers speed too much => A proper level-shifter (5V => 3.3V) might work out well
When referencing the PIN "xx" I have been just using the PIN-Number "Dxx" written on the ESP32-Dev-Board
You may connect an antenna of ~17.3cm to improve range
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
#define RXD2 27
void setup() {
Serial.begin(115200);
Serial.print("Ready to receive.");
mySwitch.enableReceive(RXD2);
}
void loop() {
if (mySwitch.available()) {
Serial.print("Received ");
Serial.print( mySwitch.getReceivedValue() );
Serial.print(" / ");
Serial.print( mySwitch.getReceivedBitlength() );
Serial.print("bit ");
Serial.print("Protocol: ");
Serial.print( mySwitch.getReceivedProtocol() );
Serial.print(" / ");
Serial.println( mySwitch.getReceivedDelay() );
mySwitch.resetAvailable();
}
}
In your RC and Outlet can be configured by DIP-Switches you might not need to connect the receiver overall - you can directly insert the DIP-Switches levels in the RCSwitch-Library
Connecting the sender (is fine with just 3.3V)
You can use the ESP32-3.3 to supply power
You may want to double check the PIN-Labels - I got confused because the DATA-Label was off and first interpreted as GND | DATA | VCC instead of GND | VCC | DATA
You may connect an antenna of ~17.3cm to improve range
#include <Arduino.h>
#include <WiFi.h>
#include <RCSwitch.h>
#define TXD2 25
RCSwitch mySwitch = RCSwitch();
void setup() {
Serial.begin(115200);
// Transmitter is connected to Arduino Pin #10
mySwitch.enableTransmit(TXD2);
// Optional set protocol (default is 1, will work for most outlets)
// mySwitch.setProtocol(2);
// Optional set pulse length.
mySwitch.setPulseLength(311);
// Optional set number of transmission repetitions.
// mySwitch.setRepeatTransmit(15);
}
void loop() {
/* See Example: TypeA_WithDIPSwitches */
mySwitch.switchOn("01010", "10000");
Serial.println("Switch On");
delay(10000);
mySwitch.switchOff("01010", "10000");
Serial.println("Switch Off");
delay(10000);
}
I have not yet used sender or receiver while WiFi being active. Though I have been reading about issues while WiFi is active and receiving / sending via 433Mhz.
The sender must have 5 V supply to go far, and it has not output pin which can damage the ESP32, and the receiver. Instead, must be connected to 3.3 V because it has an output which goes to ESP2 (3.3 V supply) and the output of the receiver must not be more than 3.3 V, so as not to damage the GPIO input of ESP32.
ESP32
The data sender(input) goes to: GPIO 5: pinMode(5, OUTPUT)
The data receiver (output), goes to GPIO 4: pinMode(4, INPUT)
Sender supply: 5 V
Receiver supply: 3.3 V (not to damage ESP32 GPIO 4)
It's about the RF24 library you can find here. http://maniacbug.github.io/RF24/index.html
I transmit data from one Arduino to another using NRF24L01 radios.
When I use the write-function on the transmitter arduino (joystick is an array) and after that I put in a delay higher then 10, the available function returns false.
Transmitter
radio.write( joystick, sizeof(joystick) );
delay(20);
Receiver
if(!available())
print('No data'); // delay > 10 --> No data will be printed
Why is it working with a delay of 10 but not above? Has it something to do with timeouts which is mentioned in the docs of the library?: http://maniacbug.github.io/RF24/classRF24.html#a4cd4c198a47704db20b6b5cf0731cd58
Thank you for your answers.
I'm doing some experiments with Arduino+Siemens TC35 GSM module and I would like to be able to read an SMS that I send to this device.
I have assembled my device following more or less this scheme:
with the difference that I don't use a buzzer nor a relay, just an LCD display. You can see the full picture here:
The scheme should work, because for example I have been able to send an SMS from Arduino to my mobile phone, but I'm having some problems parsing the SMS I send to my Arduino.
(note: I will hide my number substituting some numbers with ***)
I initialize the GSM module like this:
mySerial.print("AT+CMGF=1\r\n");
and I try to read my SMS like this:
void readSMS()
{
mySerial.print("AT+CMGR=6\r\n");
delay(1000);
char c;
while (mySerial.available()>0){
c = (char)mySerial.read();
Serial.print(c);
}
}
but I always get a truncated SMS. This is what I see in my Serial monitor:
AT+CMGF=1
OK
AT+CMGR=6
+CMGR: "REC READ","AT+CMGR=6
+CMGR: "REC READ","+4475********",,"14/04/25,21:08:AT+CMGR=6
+CMGR: "REC READ","+4475********",,"14/04/25,21:08:AT+CMGR=6
+CMGR: "REC READ","+4475********",,"14/04/25,21:08:AT+CMGR=6
+CMGR: "REC READ","+4475********",,"14/04/25,21:08:AT+CMGR=6
what's wrong with my code?
Thank you so much for any help.
p.s: also other commands that are supposed to work (for example the one to delete all SMS: AT+CMGD=1,4) don't work at all and give me error.
p.p.s: I wish I could use the GSM.h library that is available for Arduino, but I guess it's only compatible with the original Arduino GSM Shield.
I'm not an Arduino expert in any capacity, so there may be better ways to do this in the API, but I'd try something like this (delays can probably be lowered)
void readSMS()
{
mySerial.print("AT+CMGR=6\r\n"); // Send request
int count = 5; // Number of 100ms intervals before
// assuming there is no more data
while(count-- != 0) { // Loop until count = 0
delay(100); // Delay 100ms
while (mySerial.available() > 0){ // If there is data, read it and reset
c = (char)mySerial.read(); // the counter, otherwise go try again
Serial.print(c);
count = 5;
}
}
}
Another - probably better - option would be to just loop without a delay until you get a complete answer. That of course assumes that you know what to look for (<cr><lf>OK<cr><lf> would seem to be the case here, but I'm too weak on the Hayes spec to be sure)
I am having hell with this and I know it is probably really simple. I am trying to read a text message from my Seeed GPRS shield. I have the shield setup as a software serial and I am displaying the information received from the GPRS to the serial monitor. I am currently sending all AT commands over serial while I work on my code. To display the data from the software serial to the serial monitor, I am using the following code.
while(GPRS.available()!=0) {
Serial.write(GPRS.read());
}
GPRS is my software serial obviously. The problem is, the text is long and I only get a few characters from it. Something like this.
+CMGR: "REC READ","1511","","13/12/09,14:34:54-24" Welcome to TM eos8
This text is a "Welcome to T-Mobile" text that is much longer. The last few characters shown are scrambled. I have done some research and have seen that I can mod the serial buffer size to 256 instead of the default 64. I want to avoid this because I am sure there is an easier way. Any ideas?
Have you tried reading into a character array, one byte at a time? See if this helps:
if (GPRS.available()) { // GPRS talking ..
while(GPRS.available()) { // As long as it is talking ..
buffer[count++]=GPRS.read();
// read char into array
if(count == 64) break; // Enough said!
}
Serial.write(buffer,count); // Display in Terminal
clearBufferArray();
count = 0;
}
You need to declare the variables 'buffer' and 'count' appropriately and define the function 'clearBufferArray()'
Let me know if this helps.
Looks like this is simply the result of the lack of flow control in all Arduino serial connections. If you cannot pace your GPRS() input byte sequence to a rate that guarantees the input FIFO can't overflow, then your Serial.write() will block when the output FIFO fills. At that point you will be dropping new GPRS input bytes on the floor until Serial output frees up more space.
Since the captured output is apparently clean up to about 64 bytes, this suggests
a) a 64 byte buffer,
b) a GPRS data rate much higher than the Serial one, and
c) that the garbage data is actually the occasional valid byte from later in the sequence.
You might confirm this by testing the return code from Serial.write. If you get back zero, that byte is getting lost.
If you were using 9600 for Serial and 57600 for GPRS, I would expect somewhat more than 64 bytes to come through before the output gets mangled, but if the GPRS rate is more than 64x the Serial rate, the entire output FIFO could fill up within a single output byte transmission time.
Capturing to an intermediate buffer should resolve your issue, as long as it is large enough for the whole message. Similarly, extending the size of either the source (in conjunction with testing the Serial.write) or destination (without any additional code) FIFOs to the maximum datagram size should work.
I've had the same problem trying to read messages and get 64 characters. I overcame it by adding a "delay(10)" in the loop calling the function that does the read from the GPRS. Seems to be enough to overcome the race scenario. - Using Arduino Mega.
void loop() {
ReadmyGPRS();
delay(10); //A race condition exists to get the data.
}
void ReadmyGPRS(){
if (Serial1.available()){ // if data is comming from GPRS serial port
count = 0; // reset counter
while(Serial1.available()) // reading data into char array
{
buffer[count++]=Serial1.read(); // writing data into array
if(count == 160)break;
}
Serial.write(buffer,count);
}
}