# Question
Title: How to use 2 serial port when WifiEsp library uses one of both
I try without success to receive datas from DataPort and transmit them to my computer via WifiPort, using ESP8266 wifi module. Each second, serial datas income on DataPort from another device.

Initialization as follow:

```
#include <SoftwareSerial.h>
#include "WiFiEsp.h"
SoftwareSerial DataPort(10, 11); // RX, TX
SoftwareSerial WifiPort(8, 9); // RX, TX

```

In setup:

```
Serial.begin(9600);
DataPort.begin(9600);
WifiPort.begin(9600);
WiFi.init(&WifiPort);

```

In loop, i do:

```
//WIFI PART
WifiPort.listen();
WiFiEspClient client = server.available();
if (client) {
 //.... bla...bla...bla...
}

//INCOMING SERIAL PART
DataPort.listen();
while (DataPort.available() > 0)
{
   char c = DataPort.read();
   str += c;
   if(c == '/')
   {
      Serial.println(str);
      str="";
      break;
   }
}

```

WIFI PART runs fine if i isolate INCOMING SERIAL PART and INCOMING SERIAL PART runs fine without WIFI PART. So how can i receive datas on DataPort and transmit them when my computer ask them via the ESP8266 on WifiPort ?

# Answer
> 1 votes
The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to received data over hardware Serial, if you only receive on DataPort and only print to SerialMonitor.

---
Tags: arduino-uno, serial, esp8266, softwareserial
---


title: Parsing data in arduino?

text:
# Question
Title: Parsing data in arduino?
I just started working with Arduino and in my project I am trying to achieve the COMM between two Arduino using HC-05 in master and slave mode respectively, I configured it all successfully.

Now I want to send three HCSR-04 distance sensors data from master Arduino to slave Arduino via HC-05. I am sending each sensor data separated by " | ". following is the example format., which I got in serial monitor by connecting the master Arduino directly to PC via USB.

168|200|76

167|200|68

166|200|76

168|200|77

Now the problem is I am not able to read and parse this on the slave side. I tried with serail.readbytesuntill but I could not succeed. Please help me out that how I can read it and parse it.

Thanks in advance.

# Answer
> 1 votes
As you can see from the comments Birender Brar, we need more information to be able to help you.

One way to accomplish your goal would be to:

Use `Serial.readBytesUntil('\n', buffer, length)` on the slave device to "read" the data in to a `char` array. The serial monitor can be set to automatically send a `\n` character for testing purposes, but your code on the master will have to do this. Send the data **168|200|76** with a **\n** appended to the end of the data: **168|200|76\n**

Parse the data. Here is a example sketch that parses the data in to a `integer` array.

```
// Use Serial.readBytesUntil('\n', buffer, length)
// to fill the char array / string.
char str[] = "168|200|76\n";

// Set array size to maximum number of integers you will receive.
uint16_t myArray[3];

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(str, "|");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "|");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }
}

void loop(){}

```

---
Tags: serial, serial-data
---


# Question
Title: Any idea why my LED fails to operate with the if statement
I have tried several workarounds without success.

```
#include <LiquidCrystal.h>
float tempC;
int tempPin = 0;// BS E D4 D5 D6 D7
int buzzer = 4;
int LED =2;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
unsigned char i;
void setup()
{
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Temp        C ");
pinMode(LED, OUTPUT);
pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
}
void loop()
{
tempC = getTemperature();
lcd.setCursor(6, 0); // Display Temperature in C
lcd.print(tempC);
delay(500);
}
float getTemperature()
{
int tempReading = analogRead(tempPin); // This is OK
double tempK = log(1000000.0 * ((1024.0 / tempReading - 1)));
//Temperature in Kelvin
tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
return (tempK - 273.15);

if (tempC>0)
digitalWrite(LED,HIGH);
else
digitalWrite(LED, LOW);
}

```

# Answer
> 0 votes
The LED fails to operate with the if statement because calling the `return` statement Terminates a function and returns a value from a function to the calling function, if desired. Try your sketch with the `return` statement as the "last thing" in the function.

```
#include <LiquidCrystal.h>

float tempC;
int tempPin = 0; // BS E D4 D5 D6 D7
int buzzer = 4;
int LED = 2;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
unsigned char i;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Temp C ");
  pinMode(LED, OUTPUT);
  pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
}

void loop() {
  tempC = getTemperature();
  lcd.setCursor(6, 0); // Display Temperature in C
  lcd.print(tempC);
  delay(500);
}

float getTemperature() {
  int tempReading = analogRead(tempPin); // This is OK
  double tempK = log(1000000.0 * ((1024.0 / tempReading - 1))); //Temperature in Kelvin
  tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
  if (tempC>0) digitalWrite(LED,HIGH); else digitalWrite(LED, LOW);
  return (tempK - 273.15);
}

```

---
Tags: programming
---


# Question
Title: Simple code to define pins used for Shift Register control - Error: a function-definition is not allowed here before '{' token
I'm simply trying to light up some pins on a customized circuit board via Arduino. My code below has the seemingly common error "a function-definition is not allowed here before '{' token". I've scoured my code for open/close curly brackets and semi-colons. I also regularly do a quick ctrl+T to format it. Now I am at a loss - any info/advice greatly appreciated! The error occurs at the '{' after the 'void loop()' line towards the bottom:

```
// serially read in 32 bytes at a time to send to shift registers.
// currently updating every 0.1s in Matlab

// Define which pins will be used for the Shift Register control
int dataPin = 2;
int latchPin = 3;
int clockPin = 4;

#include <SPI.h>

void setup()
{
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);

  SPI.setClockDivider(SPI_CLOCK_DIV16);
  SPI.begin();

  //Configure each IO Pin
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);

  Serial.begin(115200);
  delay(1000);

  int seq
  [32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

  int timeElapsed = 2000;
  int timeOld = 0;
  int interval = 100;

  void loop()
  {
    Serial.flush();
    Serial.println('K');
    for (int i = 0; i < 32; i++)
    {
      while (Serial.available() == 0);
      {
        seq[i] = Serial.read();
      }
    }
    digitalWrite(latchPin , HIGH);
    digitalWrite(latchPin , LOW);
    for (int i = 0; i < 32; i++)
    {
      SPI.transfer(seq[i]);
    }
    digitalWrite(latchPin , HIGH); //necessary to tramsit to board
  }

```

# Answer
There's no closing bracket for your `setup()` function and your `loop()` function is inside `setup()`. Close off `setup()` with a `}`and then start `loop()`!
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Control Air Pump Depending on Pressure Sensor
I am working with an Arduino Mega, a 12V micro air pump, and a MP3V5050 air pressure sensor. The sensor outputs an analog voltage depending on the pressure reading in an inflatable member. I'd like to turn on the micro air pump when the pressure is too low and turn off the pump when the pressure exceeds a determined threshold (exact pressure ranges are currently undetermined).

I have been looking for similar tutorials but this is my first experience working with Arduinos and most existing tutorials are either sensing or pump control, not both. I only have minor coding experience with MATLAB, so any help with this is appreciated. Thank you!

# Answer
> 2 votes
So you basically want a hysteresis control for the air pump.

```
const int lowerLimit;//fill in as needed
const int upperLimit;

void loop(){
    int pressure = readPressureSensor();
    if(pressure < lowerLimit) turnPumpOn();
    if(pressure > upperLimit) turnPumpOff();

}

```

The helper functions I used should be easy to implement based on the tutorials you found.

---
Tags: arduino-mega, pressure
---


title: Program Upload Loading problem

text:
# Question
Title: Program Upload Loading problem
Please help me about this program uploading problem. Arduino: 1.6.13 (Windows 10), Board: "Arduino Nano, ATmega328P"

Sketch uses 930 bytes (3%) of program storage space. Maximum is 30,720 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes. avrdude: ser\_open(): can't open device "\\.\COM1": The system cannot find the file specified.

Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences.

# Answer
> 0 votes
It can have many options, the main reason is it cannot communicate with the Nano.

I try to create a list with options:

* Hardware issues
    + Nano is broken (solution: change Nano)
    + USB cable is broken (solution: change cable)
    + USB port is broken (solution: change USB port)
* Software issues
    + USB port 'corrupt' (solution: use another USB port)
    + USB connection incorrect (solution: reconnect USB cable)
    + IDE is corrupt (solution: reinstall IDE)
    + Nano in illegal state (solution: reset/reconnect power of Nano)
    + Serial communication is used (remove RX/TX wires)

---
Tags: arduino-nano
---


title: Correct Pins for Nodemcu 8266

text:
# Question
Title: Correct Pins for Nodemcu 8266
I am building a small electronic project, and I am incorporating module nodeMcU 8266 in a box. I would like to know which pins are for "flash" and for "reset" I know there are 2 buttons on the module for those 2 actions, but I would like to add 2 external buttons for those function on the case of the project, like that I will not need to open the box everytime. I looked on the net, and I guess that for "reset", I must connect to pin "Rst" and pin "Grd", I mean those 2 pin must be shorted, but I prefere to get confirmation before to go further. And also for the "flash", what are both pins that I must connect the external push button to, to replicate the button present on the module itself.

Also I would like to connect an external LED to the module, following the state of the blue SMD led. The thing is that there is an SMD blue led on the module, I want to know what are the 2 pins that are similar to the contacts of the blue SMD led. I want the External LED that I plan to incorporate to the case of the project, to light up when the SMD blue led on the module is on, and when the led to be off when the blue SMD led is off. I want that both follow the same state. Blue SMD led "On" \>\>\> external led "On" and Blue SMD led "Off" \>\>\> external led "Off"

Sorry for the little confused explanation, and thanx in advance for any help and support.

# Answer
The v0.9 and v1.0 NodeMCU boards have 2 LEDs: One on the AIthinker module, and one on the actual NodeMCU board.

The AIthinker module's LED is connected between Vcc (3.3V) and `GPIO2` (labeled `D4` on nodeMCU). It turns ON when `D4` is set `LOW`.

The NodeMCU LED is connected between Vcc (3.3V) and `GPIO16` (labeled `D0` on nodeMCU). It turns ON when `D0` is set `LOW`.

The pin labeled `RST` is the Reset signal from the AIthinker module, and is active-high, meaning you connect `RST` to `GND` to put the device in a reset state.

The pushutton labeled `FLASH` is connected between GND and `GPIO0` (labeled `D3` on nodeMCU). When the this pin is `LOW` when the ESP8266 comes out of a reset state, the chip is in flash-bootloader mode, meaning it is ready to receive a new sketch. On a NodeMCU, however, the ESP8266 chip is placed in flash mode by the USB chip and the flashing software, so there is not a need to manually press this button.
> 1 votes

---
Tags: esp8266
---


title: Compare incoming message from ESP8266

text:
# Question
Title: Compare incoming message from ESP8266
If there's one thing I never managed to do: it's comparing strings. So I have the incoming message saved here

```
String Message2 = IClient[i].readStringUntil('\n');

```

And every time I try to compare it with

```
strcmp(Message2.c_str(),"Red"); //Hopefully comparing the Message2 with "Red"

```

I never get 0 returned.

I know from printing the Message2 to Serial that Message2 contains the word "Red".

I've tried using different methods (`string.equal(string2);` etc.) but it never said that they are equal. What am I missing out on?

# Answer
> 1 votes
Found the answer!

After testing around with changing the terminator of the `readStringUntil('\n')` method it appears that there were leading and trailing white spaces, though not being displayed on the serial monitor they still had an impact on the `strcmp(string1, string2)` method.

I could solve this problem by "trimming" the received string before comparing it by using the `String1.trim();` method.

In the end looking like:

```
String Message2 = IClient[i].readStringUntil('\n');

Message2.trim();

strcmp(Message2.c_str(),"Red");

```

---
Tags: esp8266
---


# Question
Title: Motor shield power from Arduino pro mini 5v RAW Pin 150mAh cannot run servo
linked to my old question, Pro Mini 5v with Adafruit motor shield v1 power sharing problems

I figured out and use one 7.2v battery (6 AA cells), and link it with RAW pin to Pro mini and join its 5v pin to motor shield 5v. It works but as I have a servo on this shield, 2 distance sensors so servo does not work well all the times. Stops or does not move as directed, shaking etc. I figured out that pro mini output 5v but only 150mAh which is not sufficient to run a servo which while sharing same 5v for motor shield. I need to know if I want to supply 5v 2000mAh from AA cells or 5v regulator, should I use these pins on motor shield (5v, Gnd, 9v)? I tried but it did not work. I did not find it anywhere on net.

1. How can I use these pins shown in the picture.
2. What is the min/max mAh value of current I can provide at these pins?
3. If supplying input current at these pins, should I connect/disconnect power jumper?

I am totally stuck. Need help. And here is the quick diagram how things are attached. All other pins are attached at shield connects to UNO when stack on it.

# Answer
You can't, or at least you can't do it the way you want to. Each pin can give you a maximum of 40mA. You may try using more than one pin but that possibly wont work for you. I suggest you supply additional power from a separate source and control On/Off from Arduino. It would be like a relay. Or simply buy a relay to do this.
> 1 votes

---
Tags: power, shields, arduino-pro-mini, adafruit
---


title: Verifiy NTP server update - at start

text:
# Question
Title: Verifiy NTP server update - at start
I have function to start an NTP service, right after obtaining wifi connection ( using ESP8266 board ).

from time to time, I get an error saying date and time is`01-01-1970`... which I assume is due to not reaching the server as intended.

A retry counter was added to give few more retries, but somehow I does not do the trick since I never get the expected message `NTP CHECK: #` and retry number ( while get an invalid date ). I know that `NTP.begin()` returns a bool to describe success/ failure obtaining a NTP server

**EDIT1**: using `NtpClientLib`

How can it be done ?

```
void startNTP() {
        int counter = 0;
        while ( !NTP.begin("pool.ntp.org", 2, true) && counter <=2){
          Serial.print("NTP CHECK: #");
          Serial.println(counter);
          counter +=1;
          delay(1000);
        };
        NTP.setInterval(clockUpdateInt); // in seconds
}

```

# Answer
> Having read the NTPClientLib code, I would say that the first sync is not even attempted for 1 second after `NTP.begin()` is called anyway.

You could do this

```
void startNTP() {
    NTP.begin("pool.ntp.org", 2, true);
    delay(2000); // there seems to be a 1 second delay before first sync will be attempted, delay 2 seconds allows request to be made and received
    int counter = 2;
    while ( !NTP.getLastNtpSync() && counter <=2) {
        Serial.print("NTP CHECK: #");
        Serial.println(counter);
        counter +=1;
        delay(1000);
    };
    NTP.setInterval(clockUpdateInt); // in seconds
}

```

or, you could do this

```
void loop() {
    // code that doesn't rely on valid time
    //
    // lets say this bit of code requires sync'd time
    if (NTP.getLastNtpSync()) {
        // this will only run once NTP has been sync'd at least once
    }
    // more code that doesn't require sync'd time
}

```

Now, you may want to check how long time hasn't been sync'd for in your code and *do something* if it's been too long
> 1 votes

---
Tags: esp8266, time
---


# Question
Title: my LM35 temperature sensor gives weird measurements,
Board: esp32

I know my wiring is correct because I get data from the sensor, but the data is a bit weird.

At 22 celcius I get 140, even though if I do the voltage calculation (\* 0.473372) it still doesn't work.

the number 0.473372... comes from taking the voltage 4.7v / 1024 * 1000 / 10

My code:

```
 Serial.print("temp: ");
 float temp = (analogRead(A13) * 0.473372781065088);
 Serial.println(temp);
 delay(2000);

```

Any answers?

# Answer
> 0 votes
ok, the problem is that i used to the wrong voltage conversion, just use:

```
RawValue = analogRead("your analog input pin");
Voltage = (RawValue / 2048.0) * 3300;
Serial.println(Voltage);

```

this should print the tempeture in celcious

# Answer
> -1 votes
try this one i have worked with lm35 using this code and circuit. i have done this thing with arduino uno but you can try it with esp32

---
Tags: temperature, lm35
---


# Question
Title: Mqtt not subscribe on topic that's converted from String to char array
I am still not sure what should be the exact Title for this question, because I don't know where the problem is.

I am using `#include <MQTTClient.h>` mqtt library to subscribe on a topic. This topic is created dynamically depending on the name of the device. Currently I am testing with device name `myDeviceAbc`.

```
String baseTopic  = "arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing";
String espInTopicStr  = baseTopic + "/" + config.machineName + "/espIn"; //config.machineName is a string "myDeviceAbc"

const char* espInTopic  = "";
espInTopic = espInTopicStr.c_str();

const char* hardCodedTopic = "arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn";

int rc = client.subscribe(espInTopic, MQTT::QOS0, messageArrived);
if (rc != 0) {
  Serial.print("rc from MQTT subscribe is ");
  Serial.println(rc);
  return;
}
Serial.println("MQTT subscribed");

Serial.print("size of hardcoded topic: ");
Serial.println(strlen(hardCodedTopic));
Serial.print("size of actual topic: ");
Serial.println(strlen(espInTopic));

Serial.print("hardCodedTopic >>>");
Serial.print(hardCodedTopic);
Serial.print("<<<");
Serial.println(".");

Serial.println("---");

Serial.print("espInTopic topic >>>");
Serial.print(espInTopic);
Serial.print("<<<");
Serial.println(".");

```

I have defined two variables for same topic `arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn` . one is hardcoded `hardCodedTopic` and other is created dynamically `espInTopic`.

when I subscribe on `espInTopic`, I get `MQTT subscribed` message on serial console BUT nothing is received on this topic when I publish from AWS portal. but when I subscribe on `hardCodedTopic` I then receive all published messages. I cannot figure out what is the issue. I checked the mqttClient subscribe method inside the library header file, which is defined like this

```
int subscribe(const char* topicFilter, enum QoS qos, messageHandler mh);

/** MQTT Unsubscribe - send an MQTT unsubscribe packet and wait for the unsuback
 *  @param topicFilter - a topic pattern which can include wildcards
 *  @return success code -
 */
int unsubscribe(const char* topicFilter);

```

It does takes const char\* as topic name. I though maybe due to conversion from String to char array, there might be some unknown characters appended in the char array `espInTopic`, but I also checked the size and content of both topics which is exactly the same.

```
size of hardcoded topic: 52
size of actual topic: 52
hardCodedTopic >>>arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn<<<.
---
espInTopic topic >>>arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn<<<.

```

**Full Code:**

```
#include <Arduino.h>
#include <Stream.h>
#include <EEPROM.h>
#include <ArduinoJson.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266WiFiMulti.h>
#include "helpers.h"
#include "global.h"

//AWS
#include "sha256.h"
#include "Utils.h"

//WEBSockets
#include <Hash.h>
#include <WebSocketsClient.h>

//MQTT PAHO
#include <SPI.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>

//AWS MQTT Websocket
#include "Client.h"
#include "AWSWebSocketClient.h"
#include "CircularByteBuffer.h"

#define ACCESS_POINT_NAME  "VM"
#define ACCESS_POINT_PASSWORD  "12345678"

extern "C" {
  #include "user_interface.h"
}

//AWS IOT config, change these:
char wifi_ssid[]       = "TALKTALKAF521F";
char wifi_password[]   = "xxxxxxxx";
char aws_endpoint[]    = "xxxxxxxxxxxxxxxx.iot.us-east-2.amazonaws.com";
char aws_key[]         = "xxxxxxxxxxxxxxxx";
char aws_secret[]      = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
char aws_region[]      = "us-east-2";

String baseTopic  = "arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing";
//const char* espInTopic  = "";        // was global before, but later I also tried to keep this local on subscribe() method
const char* espOutTopic  = "";
int port = 443;

//MQTT config
const int maxMQTTpackageSize = 512;
const int maxMQTTMessageHandlers = 1;

const char response[] = "{\"response\": {\"request_id\":, \"data\":}}";

String nodeName = ""; // Name needs to be unique
String nodeMac = "";

ESP8266WiFiMulti WiFiMulti;

AWSWebSocketClient awsWSclient(1000);

IPStack ipstack(awsWSclient);
MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> client(ipstack);

//# of connections
long connection = 0;
unsigned long timer = 0;
unsigned long maxTimeOut = 7000;  //7 seconds

//generate random mqtt clientID
char* generateClientID () {
  char* cID = new char[23]();
  for (int i=0; i<22; i+=1)
    cID[i]=(char)random(1, 256);
  return cID;
}

//count messages arrived
int arrivedcount = 0;

//callback to handle mqtt messages
void messageArrived(MQTT::MessageData& md)
{
    MQTT::Message &message = md.message;

    Serial.print("Message ");
    Serial.print(++arrivedcount);
    Serial.print(" arrived: qos ");
    Serial.print(message.qos);
    Serial.print(", retained ");
    Serial.print(message.retained);
    Serial.print(", dup ");
    Serial.print(message.dup);
    Serial.print(", packetid ");
    Serial.println(message.id);
    Serial.print("Payload ");
    char* msg = new char[message.payloadlen+1]();
    memcpy (msg,message.payload,message.payloadlen);

}

//connects to websocket layer and mqtt layer
bool connect () {

    if (client.isConnected ()) {
        client.disconnect ();
    }
    //delay is not necessary... it just help us to get a "trustful" heap space value
    delay (1000);
    Serial.print (millis ());
    Serial.print (" - conn: ");
    Serial.print (++connection);
    Serial.print (" - (");
    Serial.print (ESP.getFreeHeap ());
    Serial.println (")");

   int rc = ipstack.connect(aws_endpoint, port);
    if (rc != 1)
    {
      Serial.println("error connection to the websocket server");
      return false;
    } else {
      Serial.println("websocket layer connected");
    }

    Serial.println("MQTT connecting");
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.MQTTVersion = 4;
    char* clientID = generateClientID ();
    data.clientID.cstring = clientID;
    rc = client.connect(data);
    delete[] clientID;
    if (rc != 0)
    {
      Serial.print("error connection to MQTT server");
      Serial.println(rc);
      return false;
    }
    Serial.println("MQTT connected");
    return true;
}

//subscribe to a mqtt topic
void subscribe () {
   //subscript to a topic
  String espInTopicStr  = baseTopic + "/" + "myDeviceAbc" + "/espIn";
//  String espOutTopicStr = baseTopic + "/" + config.machineName + "/espOut";
  const char* espInTopic  = espInTopicStr.c_str();
//  espOutTopic = espOutTopicStr.c_str();

  const char* hardCodedTopic = "arn:aws:iot:us-east-2:xxxxxxxxxxxxxx:thing/myDeviceAbc/espIn";
  Serial.print("size of hardcoded topic: ");
  Serial.println(strlen(hardCodedTopic));
  Serial.print("size of actual topic: ");
  Serial.println(strlen(espInTopic));

   Serial.print("hardCodedTopic >>>");
   Serial.print(hardCodedTopic);
   Serial.print("<<<");
   Serial.println(".");

   Serial.println("---");

   Serial.print("espInTopic topic >>>");
   Serial.print(espInTopicStr.c_str());
   Serial.print("<<<");
   Serial.println(".");
   int rc = 99;
   while (rc != 0){
      rc = client.subscribe(hardCodedTopic, MQTT::QOS0, messageArrived);
      if (rc != 0) {
        Serial.print("rc from MQTT subscribe is ");
        Serial.println(rc);
        return;
      } else {
        Serial.println("");
        Serial.println("MQTT subscribed");
      }
      Serial.println("rc: " + String(rc));
      delay(500);
   }

}

//send a message to a mqtt topic
void sendmessage (const char* topic, String msg) {
    //send a message
    MQTT::Message message;
    char buf[100];
    strcpy(buf, msg.c_str());
    message.qos = MQTT::QOS0;
    message.retained = false;
    message.dup = false;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf)+1;
    int rc = client.publish(topic, message);
}

void setup() {

    wifi_set_sleep_type(NONE_SLEEP_T);
    EEPROM.begin(1024);
//    for (int i = 0; i < 1024; ++i) { EEPROM.write(i, 0); }
    Serial.begin(115200);
    ardMegaSerial.begin(9600);

    delay (2000);

    //////////////////////////////////////////
  if (!ReadConfig())
  {
    // DEFAULT CONFIG
    config.configMode = true;
    config.ssid = "N.A";
    config.password = "N.A";
    config.machineName = "N.A";
    config.dhcp = true;
    config.IP[0] = 192;config.IP[1] = 168;config.IP[2] = 1;config.IP[3] = 100;
    config.Netmask[0] = 255;config.Netmask[1] = 255;config.Netmask[2] = 255;config.Netmask[3] = 0;
    config.Gateway[0] = 192;config.Gateway[1] = 168;config.Gateway[2] = 1;config.Gateway[3] = 1;
    WriteConfig(true);
    Serial.println("default configs applied");
    //////////starting web config server hotspot
        Serial.println("No configuration stored, starting access point.");
        ESP.eraseConfig();
        WiFi.disconnect();
        WiFi.setAutoConnect(false);
        WiFi.setAutoReconnect(false);
        WiFi.mode(WIFI_AP_STA);
        nodeName = String(ACCESS_POINT_NAME) + String("-") + String(WiFi.softAPmacAddress().c_str());
        WiFi.softAP(nodeName.c_str() , ACCESS_POINT_PASSWORD);
        Serial.print("Connect to ssid " + nodeName + " to configure Node on IP: ");
        Serial.println(WiFi.softAPIP());
        ConfigureWifi();
        server.on ( "/favicon.ico",   []() { Serial.println("favicon.ico"); server.send ( 200, "text/html", "" );   }  );
        server.on ( "/", send_gateway_node_config_html  );
        server.on ( "/admin/values", send_gateway_node_config_values_html );
        server.on ( "/admin/connectionstate", send_connection_state_values_html );
        server.on ( "/style.css", []() { Serial.println("style.css"); server.send ( 200, "text/plain", PAGE_Style_css );  } );
        server.on ( "/microajax.js", []() { Serial.println("microajax.js"); server.send ( 200, "text/plain", PAGE_microajax_js );  } );
        server.onNotFound ( []() { Serial.println("Page Not Found"); server.send ( 400, "text/html", "Page not Found" );   }  );
        server.begin();
        Serial.println( "HTTP server started" );
  } else {
      nodeName = String(ACCESS_POINT_NAME) + String("-") + String(WiFi.softAPmacAddress().c_str());
      Serial.println("Device already configured");
      Serial.println("Wifi SSID: " + config.ssid);
      Serial.println("Wifi password: " + config.password);
      Serial.println("Node name: " + config.machineName);

      setupWifiAndAws();
  }

    //////////////////////////////////////////

}

void setupWifiAndAws() {
    char ssidBfr[500];
    strcpy(ssidBfr, config.ssid.c_str());
    char passBfr[100];
    strcpy(passBfr, config.password.c_str());
    //fill with ssid and wifi password
    WiFiMulti.addAP(ssidBfr, passBfr);
    Serial.println ("connecting to wifi");
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
        Serial.print (".");
    }
    Serial.println("\nconnected");
    ardMegaSerial.println("ESP Started\n");
    //fill AWS parameters
    awsWSclient.setAWSRegion(aws_region);
    awsWSclient.setAWSDomain(aws_endpoint);
    awsWSclient.setAWSKeyID(aws_key);
    awsWSclient.setAWSSecretKey(aws_secret);
    awsWSclient.setUseSSL(true);

    if (connect ()) {
        String espOutTopicStr = baseTopic + "/" + config.machineName + "/espOut";
        espOutTopic = espOutTopicStr.c_str();
        subscribe();
        sendmessage (espOutTopic, "{\"device\":\"connected\"}}");
    }
}

void loop() {

  receiveFromArduino();
  //responseTimeOutCheck();
  //keep the mqtt up and running
  if (awsWSclient.connected ()) {
      client.yield(50);
  } else {
    //handle reconnection
    if (connect ()){
      subscribe ();
    }
  }

}

```

# Answer
> 1 votes
The `c_str()` function of the `String` class returns a pointer to current internal char array. This pointer is valid only until the String exists and is not changed.

Variable `espInTopicStr` is defined in a function and is destroyed at the end of the function. It frees the memory allocated for the internal char array.

You send a pointer to the internal char array of the `espInTopicStr` to `client.subscribe`. The MQTT library doesn't copy that char array, it only stores the pointer. Later the library uses the pointer to call the topic, but the memory on that location already changed and doesnt't contain the name of the topic.

---
Tags: string, mqtt, c-string
---


# Question
Title: "SSD1306 allocation failed" when #include SD.h
I'm using the ssd1306\_128x64\_i2c example file from the 1306's library.

It works perfectly until I add the ***#include SD.h*** line, after which it gives the allocation failed error.

Please advise.

```
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SD.h>

Adafruit_SSD1306 display(128, 64, &Wire, 4);

void setup() {
  Serial.begin(9600);

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
  }

  display.clearDisplay();
  display.display();
  testdrawchar();
}

void loop() {
}

void testdrawchar(void) {
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.cp437(true);

  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }
  display.display();
}

```

# Answer
I was able to make it all fit by using the text-only library for the OLED.

SSD1306Ascii Library

Much thanks to Majenko for explaining the problem and greiman for writing the library!
> 2 votes

# Answer
Both the SD library and the SSD1306 libraries want big buffers. That means lots of memory. You don't have lots of memory.

* The SD wants at least 512 bytes for a sector buffer (which is allocated at compile time).
* The SSD1306 wants at least 1kiB for a display buffer (which is allocated at runtime).
* Serial wants at least 128 bytes for TX and RX buffers (which is allocated at compile time).
* The Wire library needs 32 bytes for a TX buffer.

That's 1696 bytes of a total 2048, and that's not taking into account any of the other variables and things that your program, the various libraries, and the Arduino core itself needs, plus the stack (and its specified minimum size safety zone).

There's nothing much you can do about it, short of upgrading your Arduino to one with more memory, or splitting your design across multiple Arduinos.
> 1 votes

---
Tags: ssd1306, sd.h
---


# Question
Title: Passing arrays, global arrays within functions, pointers, and declaring array sizes
I'm super confused right about now!

I've been working on project involving Xbees in API mode, and I need to send different arrays of bytes to the Xbee depending on which buttons I press. Mostly what I have is working fine, but I'm having a lot of issues with the following questions; I figured I'd summarize all my questions first, then further explain them with code examples.

1. Arduino requires arrays contain to a size. How can I declare `byte data[]` without a size?
2. Arrays sizes must be declared with a number, or a const integer. So how come I can declare `byte packet[arraySize];` when `arraySize` is being passed the integer `ledOn_len` that isn't constant?
3. How can I create a global array within a function?

I've taken the liberty to condense my code for readability purposes. Everything you see is here is mirroring my issues with my Xbee code.

```
byte ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
byte ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

int ledOn_len; // to be used for the array size of ledOn[] NOT a constant
int ledOff_len; // to be used for the array size of ledOff[] NOT a constant

// this doesn't work, because the array length must be a constant
//int arrayLength = 4;
//byte rando[arrayLength];

// this works just fine, since arrayLength is now a constant
//const int arrayLength = 4;
//byte rando[arrayLength];

void setup()
{
  Serial.begin(115200);

  // since using sizeof(data) inside of changeLed() doesn't
  // work (it returns with 2, which is the size of a pointer)
  // set them here, and pass them along.
  ledOn_len = sizeof(ledOn);
  ledOff_len = sizeof(ledOff);
}

void loop()
{
  changeLed(ledOn, ledOn_len);
  delay(1000);
  changeLed(ledOff, ledOff_len);
  delay(1000);
}

void sendToXbee()
{
  //Xbee.write(packet); // packet isn't global, this doesn't work
  // yes I know I didn't include any software serial in this demonstration
}

void changeLed(byte data[], int arraySize)
{
  byte packet[arraySize]; // how does this work???? Pass by value
  memcpy(packet, data, arraySize); // clone data to packet

  // this is all the Serial print code

}

```

**1)** I created the function `void changeLed()` to calculate the checksum (xbee crap). I need to pass it the array `ledOn[]` or `ledOff[]` for the checksum calculations to occur. So I simply added `void changeLed(byte data[])` (and then void loop calls `changeLed(ledOn)` ) which works, but why?! Anywhere else if you declare an array without an array size it says you must provide one. Confusing to me, but it still works. . . kinda. When I serial print `data[i]` byte by byte, it perfectly displays each byte in `ledOn[]`, which is what I'm passing it. But when I call `sizeof(data)` it says it's only 2 bytes. How can it contain the exact data of 4 bytes I give it while only being 2 bytes? Here is the serial monitor of it. The first line is the printout of `data[]`, following the 4 bytes is the length which it claims is 2. The second line is the array of bytes `packet[]`. I set `packet[]` equal to `data[]` with this: `memcpy(packet, data, arraySize);`. Now you'll notice that the array size is correct. Interesting.

**Update #1:** It seems like this all has to do with pointers somehow. I guess `data[]` is just pointing to or referencing the array `ledOn[]`, and using `memcpy(packet, data, arraySize);` is actually copying the array `ledOn[]` to the array `packet[]`?

---

**2)** I try to declare a random array (`byte rando[]`) using `int arrayLength` as the size. This does not work because the array size must be a constant. So I simply add `const int arrayLength` and that works. Great. So how am I able to do `byte packet[arraySize];`!? `ArraySize` is being passed `ledOn_len` which is not a constant, so how come that works?

---

**3)** I need to be able to use the array `packet[]` inside of another function `void sendToXbee()`. `Packet[]` will be my final array of bytes to send to the Xbee containing either the array `ledOn[]` or `ledOff[]` which are different array lengths. As is, I cannot use `packet[]` in `void sendToXbee()` because `packet[]` is local to `void changeLed()`. But here's the catch 22: I cannot declare `packet[]` in the setup making it global, because I don't have a size for that array yet!! The size of that array must be calculated within `void changeLed()`, depending on which array I need to send to the Xbee, `ledOn[]` or `ledOff[]`.

I know this is a lot but I'd appreciate the help! Thanks guys.

# Answer
> 0 votes
> Arduino requires arrays contain to a size. How can I declare byte data\[\] without a size?

You can't. Pure and simple. The compiler can infer a size from a declaration time assignment.

> Arrays sizes must be declared with a number, or a const integer. So how come I can declare byte packet\[arraySize\]; when arraySize is being passed the integer ledOn\_len that isn't constant?

It is a feature of C99 which GCC have also included in C++.

> How can I create a global array within a function?

Simple: you can't.\*

Ok. Now we've to that out of the way, let's look at what you *want* to do and how you should do it.

First off, you have a number of arrays of data:

```
uint8_t ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
uint8_t ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

```

Those arrays have an associated length, which is the size of the array divided by the size of one array entry:

```
const int ledOn_len = sizeof(ledOn) / sizeof(ledOn[0]);
const int ledOff_len = sizeof(ledOff) / sizeof(ledOff[0]);

```

At the moment you're getting away with just using `sizeof(ledOn)` because `sizeof(ledOn[0])` is 1. But if you ever do this with arrays of anything other than `byte` you will come unstuck unless you get into this habit.

Now, those arrays are just blocks of memory with a fixed size, in a fixed location. That means that the arrays, as well as being arrays, are also *pointers*. That is, they are in effect just variables that contain the address where the data for the array is stored.

So you pass the pointer to the array, along with the length of the array, to your function:

```
void changeLed(const uint8_t *data, int len) {
}

changeLed(ledOn, ledOn_len);

```

When you have done is pass the address of the array to the function, not the array.

Now you can do things with that array data using that address. What you can't do is change the data (because I've marked it `const`).

One of the things you can do, though, is just send it. You know where the data is. You know how long it is. You know where you want to send it to.

So you just do:

```
void changeLed(const uint8_t *data, int len) {
    Xbee.write(data, len);
}

```

That is, write `len` bytes starting at the address pointed to by `data`.

There is no need to have variable size arrays. There is no need to have global packet buffers. There is no need to copy any data anywhere with `memcpy()`. Just pass the data and send it.

If you need to send more data than just the content of your array, then just send it. For example you may have to (I don't know the XBee protocol) add a header and footer to the packet.

```
void changeLed(const uint8_t *data, int len) {
    Xbee.write(0x01);
    Xbee.write(0x02);
    Xbee.write(len & 0xFF);
    Xbee.write(data, len);
    uint8_t cs = 0;
    for (int i = 0; i < len; i++) {
        cs += data[i];
    }
    Xbee.write(cs);
}

```

Just because they're not together in the same `write` function doesn't mean that they aren't "together". With serial communication, there is no such thing as "together". It's just one byte after another.

> I need to be able to use the array packet\[\] inside of another function void sendToXbee(). Packet\[\] will be my final array of bytes to send to the Xbee containing either the array ledOn\[\] or ledOff\[\] which are different array lengths. As is, I cannot use packet\[\] in void sendToXbee() because packet\[\] is local to void changeLed(). But here's the catch 22: I cannot declare packet\[\] in the setup making it global, because I don't have a size for that array yet!! The size of that array must be calculated within void changeLed(), depending on which array I need to send to the Xbee, ledOn\[\] or ledOff\[\].

Why do you think you need to copy the data into a separate packet variable? You already have the data in a variable.

If you really want to do that, then just pass `packet` to the next function in the same way as you already pass your other arrays.

---

<sup>* Actually there are ways, using dynamic memory allocation, but I won't condone using that</sup>

---
Tags: array, pointer, bytes, functions
---


# Question
Title: WifiClient and aREST on esp32 - loop until new instructions recieved?
I've created a simple sketch for an esp32 that hosts a REST API that can be accessed via HTTP. Based on the instructions received from the client, the esp32 controls some neopixels with some various animations I've written.

Everything worked as expected until I got to an animation that runs in a while loop. The loop breaks when a new client is detected so that the light can switch functions. However, when the new client is detected, the client seems to be discarded or consumed, and i just end up back in the loop() function until I make a second HTTP request, then the changes to show up.

I'm sure it's something obvious, but what have I done wrong?

**Code:**

```
#include "WiFi.h"
#include "FastLED.h"
#include "aREST.h"
#include "ArduinoJson.h"

#define NUM_LEDS 64
#define DATA_PIN 18

CRGB leds[NUM_LEDS];
int LED_COUNT = 64;
int MAX_BRIGHTNESS = 200;

const char* ssid = "wifi";
const char* password = "password";
aREST rest = aREST();
WiFiServer server(80);
WiFiClient client;

void setup() {
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, LED_COUNT);
  flashAll(CRGB::Black);
  // Bind urls to the handling functions
  rest.function("random-strobe", randomStrobe);
  rest.function("solid-color", solidColor);
  rest.function("reset", reset);

  // Connect to WiFi and wait until we're connected to continue
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    flashAll(CRGB::Cyan);
    delay(500);
    flashAll(CRGB::Black);
    delay(500);
  }
  server.begin();
  flashAll(CRGB::Green);
  delay(2000);
  flashAll(CRGB::Black);
}

void loop() {
  if (checkForTask()) {
    rest.handle(client);
  }
}

boolean checkForTask() {
  // I have tried making this reassignment conditional
  // when the global 'client' is false, but it did not help
  //if (!client) { client = server.available(); }
  client = server.available();
  if (client) {
    return true;
  }
  return false;
}

int randomStrobe(String params){
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:application/json");
  client.println();
  client.stop();
  StaticJsonDocument<200> jsonDoc;
  Serial.println(params);
  Serial.println("params recieved. parsing...");
  auto error = deserializeJson(jsonDoc, params);
  if (!error) {
    // some setup stuff
    while(!checkForTask()){
      // do stuff in here
    }
    return 0;
  }
}

```

# Answer
Okay, I've managed to resolve the issue with some general direction from @juraj.

I now have TWO WifiClient instances:

```
WiFiClient client;
WiFiClient newClient;

```

This allows me to use the newClient instance to check for a new client:

```
boolean checkForTask() {
  newClient = server.available();
  if (newClient) {
    Serial.println("new client detected.");
    return true;
  }
  return false;
}

```

and only reassign the main client instance when a new client is actually detected:

```
void loop() {
  if (!newClient.connected()) {
    checkForTask();
  } else {
    client = newClient;
    runTask();
  }
}

```

This seems to work without any discernible side effects or additional resource usage, but if there is a more efficient way to accomplish this, please share. Thanks!
> 1 votes

# Answer
`server.available()` doesn't return an already 'claimed' connection again. It returns a new connection or an empty WiFiClient object.

The esp8266 and esp32 Arduino core WiFi library close the underlying connection if the last referring WiFiClient instance is freed. The assignment of empty WiFiClient object frees the previous reference to underlying socket and if it was the last referrence, the library closes the socket.

You get a client with `server.available()` in `checkForTask()` and then you call `server.available()` again. It returns an empty WiFiClient object and you assign it to your WiFiClient object. The library closes the referred connection.

The solution is not to check `server.available` until WiFiClient is valid.

```
if (!client) {
  client = server.available();
}

```
> 1 votes

---
Tags: wifi, esp32, led-strip, cpp
---


title: millis() replace delay() question

text:
# Question
Title: millis() replace delay() question
```
// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12=0;
unsigned long previousMillisLED13=0;

unsigned long previousMillisLED3=0;

// different intervals for each LED
int intervalLED12 = 500;
int intervalLED13 = 5000;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);

   pinMode(3, OUTPUT);

}
void loop() {
   // get current time stamp
   // only need one for both if-statements
   unsigned long currentMillis = millis();

   // time to toggle LED on Pin 12?
   if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
      LED12state = !LED12state;
      digitalWrite(12, LED12state);
      // save current time to pin 12's previousMillis
      previousMillisLED12 = currentMillis;
   }

// time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
      LED13state = !LED13state;
      digitalWrite(13, LED13state);
      // save current time to pin 13's previousMillis
      previousMillisLED13 = currentMillis;
  }
}

```

My questions:

1. Didn't see the led12 and led13 have 10 times defferency, almost same intervals, why?
2. How can I use `millis()` as simple as delay?
3. Is that a must to use if?

# Answer
> 0 votes
Your Timing is working, you can test it with the Serial monitor. So your problem is at some other place. Using delay() is from my perspective not a good solution, you did it better the way you already made.

For testing your sketch I included the communication for the Serial Montior (I had to comment out the LED activation since this is working in a different way on my board, and I also made the intervalls Shorter to see better the effect within the test sketch). Here you find the necessary changes and the output of the Serial Monitor.

My recommendation is to look with a simple Sketch if you are able to switch on/off your LEDs sperately without Timing to come closer to your problem. I dont think it is the Timing/use of millis().

```
#include <M5Stack.h> // needed for my board

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12 = 0;
unsigned long previousMillisLED13 = 0;

unsigned long previousMillisLED3 = 0;

// different intervals for each LED
int intervalLED12 = 50;
int intervalLED13 = 500;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
  Serial.begin(9600);
  //  pinMode(13, OUTPUT);
  //  pinMode(12, OUTPUT);
  //  pinMode(3, OUTPUT);
}
void loop() {
  // get current time stamp
  // only need one for both if-statements
  unsigned long currentMillis = millis();

  // time to toggle LED on Pin 12?
  if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
    LED12state = !LED12state;
    // digitalWrite(12, LED12state);
    // save current time to pin 12's previousMillis
    previousMillisLED12 = currentMillis;
  }

  // time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
    LED13state = !LED13state;
    // digitalWrite(13, LED13state);
    // save current time to pin 13's previousMillis
    previousMillisLED13 = currentMillis;
  }
  Serial.print("LED12: ");
  Serial.print(LED12state);
  Serial.print("  LED13: ");
  Serial.println(LED13state);

}

```

---
Tags: sketch, millis
---


# Question
Title: Create New Serial Class Inheriting from Stream
How should I inherit from `Stream`, for creating a new class `MySerial` able to be initialized from a `Stream0` instance?.

The error so far is: `"cannot declare variable 'mySerial' to be of abstract type 'MySerial'"`.

If I make a class `MySerial` not inheriting, but adding a property `Stream`, everything works fine, except the new call mechanism for the `resend()` function, created to accept `Stream` instances.

EDIT: This is the edited code. Current error is: `"expected unqualified-id before '=' token"`.

*MySerial.h*

```
class MySerial:public Stream{
    private:
        int param;
    public:
        MySerial(){}; // OK
        MySerial(Stream &Serial0){MySerial=&Serial0} // Here is the question
        // Stream Implementation
        int available(){return available();}
        int read(){return read();}
        int peek(){return peek();}
        size_t write(uint8_t c){return write(c);}
        using Print::write;
};

```

*MySerial.ino*

```
#include <MySerial.h>
#include <SoftwareSerial.h>

SoftwareSerial swSerial(6,7);
MySerial mySerial(swSerial);

void setup(){}
void loop(){
    if (mySerial.available()){
        c=mySerial.read();
        resend(mySerial,c);
    }
}
// This function should accept any Stream: SoftwareSerial, MySerial, Serial...
void resend(Stream &Stream0, char c){
    Stream0.write(c);
}

```

# Answer
> 7 votes
The `Stream` class has pure virtual methods which must be implemented in derived not abstract class.

The pure virtual method from base class `Print` is:

```
virtual size_t write(uint8_t) = 0;

```

The pure virtual methods from `Stream` are:

```
virtual int available() = 0;
virtual int read() = 0;
virtual int peek() = 0;

```

additionally add in your class the line

```
using Print::write;

```

to pull in overloaded methods write(str) and write(buf, size) from`Print`

Here I have an example of a simple class derived from `Stream`.

---

EDIT: Most of your question seemed to focus on wrapping some Stream implementation. Now I see that you maybe want to enhance the SoftwareSerial class and add a new method in the inherited class. It is simple:

MySerial.h

```
#ifndef _MYSERIAL_H_
#define _MYSERIAL_H_

#include <SoftwareSerial.h>

class MySerial: public SoftwareSerial {
private:
  int param;

public:

  MySerial(uint8_t receivePin, uint8_t transmitPin) :
      SoftwareSerial(receivePin, transmitPin, false) {
    param = 0;
  }

  void resend(char c) {
    write(c);
  }
};
#endif

```

MySerial.ino

```
#include "MySerial.h"

MySerial mySerial(6, 7);

void setup() {
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    int c = mySerial.read();
    mySerial.resend(c);
  }
}

```

---
Tags: serial, softwareserial, class, stream
---


title: Prioritizing one sensor

text:
# Question
Title: Prioritizing one sensor
I want to ask is there a possible code to prioritize a specific part of a code? So I'm doing this project where I want to utilize muscle sensor, servo, and a button on an app over Bluetooth. The problem is since all is running in void() loop, even though I am not using the muscle sensor I can't move the servo with the app, since it reads the muscle sensor first. So is there a possible code to make the muscle sensor stop for a period of time after the button is pressed on the app and the servo is moved?

Here is the code:

```
void loop()
 {
  if(Serial.available()>0)
   {
    char data = Serial.read();

      if (data == 'a')
       {
        myservo.write(15);
       }
  }

int value = analogRead(EMG_PIN);

 if(value > THRESHOLD)
  {
   myservo.write(15);
  }

  else{
       myservo.write(140);
      }

```

So the first code is a bluetooth code where the servo is controlled through a button on an app. The second one is a muscle sensor. As stated above the problem is it will always read the muscle sensor even though the button is pressed from the app.

```
#include <Servo.h>

 int increment = 0;

 Servo myservo;

 void setup() {

   myservo.attach(1);

 }

 void loop()
 {

   Serial.println(increment++);

   if (increment > 9);
    {

     if(Serial.available()>0)
      {
       char data = Serial.read();

       if (data == 'a')
       {
        myservo.write(15);
       }
 }

      else if (increment = 0);

      int value = analogRead(EMG_PIN);

      if(value > THRESHOLD)
       {
        myservo.write(15);
       }

     else{
       myservo.write(140);
      }
  }

```

# Answer
You have to think of your program as having two distinc modes of operation:

* The "fixed servo" mode is entered when you press the button on the app. In this mode the servo is kept at a fixed position. The mode lasts for a predefined delay.
* The normal (not fixed servo) mode is the default mode. In this mode the servo is positioned according to the reading of the sensor.

So you need a boolean variable to remember whether the "fixed servo" mode is active or not, and the code in `loop()` should take care of providing the correct behavior depending on the mode, and updating that variable when needed. For example:

```
void loop()
{
    static bool fixed = false;  // whether we are in "fixed servo" mode
    static uint32_t fixed_started;  // when the mode started
    uint32_t now = millis();

    // On button press, start "fixed servo" mode.
    if (Serial.available() && Serial.read() == 'a') {
        servo.write(SERVO_LEFT);
        fixed = true;
        fixed_started = now;
    }

    // Get out of "fixed" mode after some delay.
    if (fixed && now - fixed_started >= FIXED_DELAY) {
        fixed = false;
    }

    // If not in "fixed" mode, react to the sensor.
    if (!fixed) {
        if (analogRead(EMG_PIN) >= THRESHOLD) {
            servo.write(SERVO_LEFT);
        } else {
            servo.write(SERVO_RIGHT);
        }
    }
}

```
> 0 votes

---
Tags: arduino-uno, arduino-ide, sensors
---


title: Pipe serial dump to SD card file

text:
# Question
Title: Pipe serial dump to SD card file
I am using the RFID module to read mifare NFC chips and the library has only methods to send the data to the serial monitor. I need them to be saved to an SD card file. I have been adding custom methods to the library files to return strings that I then write to the SD card but this is a pain; there must be a quicker way to simply pipe all the data automatically but I do not know how to do this in cpp.

Here is an example of the function to dump to serial, that needs to be piped to the file on the SD card.

```
void MFRC522::PICC_DumpDetailsToSerial(Uid *uid) {
    Serial.print(F("Card UID:"));
    for (byte i = 0; i < uid->size; i++) {
        if(uid->uidByte[i] < 0x10)
            Serial.print(F(" 0"));
        else
            Serial.print(F(" "));
        Serial.print(uid->uidByte[i], HEX);
    }
    Serial.println();

    // SAK
    Serial.print(F("Card SAK: "));
    if(uid->sak < 0x10)
        Serial.print(F("0"));
    Serial.println(uid->sak, HEX);

    // (suggested) PICC type
    PICC_Type piccType = PICC_GetType(uid->sak);
    Serial.print(F("PICC type: "));
    Serial.println(PICC_GetTypeName(piccType));
}

```

Thanks!

# Answer
> 1 votes
Have the MFRC522 objects remember where you want them to send the output by adding a data member to the class like this:

```
private:
    Print &output;

```

This is a reference to a `Print` object, i.e. any object where you can `print()` or `println()` to. This reference should be initialized in the constructor, like this

```
MFRC522:MFRC522(...other arguments..., Print &my_output = Serial)
: ...other initializations..., output(my_output)
{
    ...constructor body...
}

```

Notice that, by default, the `output` is initialiazed as a reference to `Serial`. Thus, unless you explicitly ask for the output to go elsewhere, the class will behave as before.

Last step is to change, in the implementation of the class, *every* reference to `Serial` by `output`. This is just a global find and replace.

At this point, the `MFRC522` class can be used exactly as before, and it will behave identically. This means that *every* user of the library should be able to use your modified version with no issues. I thus encourage you to submit the changes to the original author, so that they have a chance to be incorporated into the canonical version of the library.

Now, if you want this debugging output to be sent elsewhere, just provide the destination as the last argument of the constructor:

```
MFRC522 my_RFID_module(...other arguments..., my_SD_card_file);

```

As long as the destination is an instance of the `Print` virtual class (basically anything you can `print()` to should be OK), it should work as expected.

---
Tags: serial, sd-card
---


# Question
Title: i am getting an error while working with esp8266
i got an error avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 2 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 3 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 4 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 5 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 6 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 7 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 8 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 9 of 10: not in sync: resp=0x00 avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0x00 An error occurred while uploading the sketch

can esp8266anyone rectify this

# Answer
> 0 votes
oh i got the solution for the above question

it might be because i used TX AND RX pins of the arduino. what i observed is as tx and rx pins are for serial communication pin during the process of uploading i have to leave that pins disconnected.arduino

---
Tags: esp8266
---


# Question
Title: I am getting blocks on my lcd screen 16*2
When I have tried interfacing my 16\*2 LCD with Arduino I am getting only the black coloured boxes on my screen. What might be the problem?

Is there any solution to that? Do I need to connect any additional physical device to avoid that situation?

product is here lcd display 16\*2

# Answer
> 3 votes
There are two possible problems, and you haven't stated which it is.

1. A single row of blocks (just the top row)

This is caused by either bad communication (wrong wiring) or incorrect code. Basically, the display isn't being initialized properly by your code for whatever reason.

2. Two rows of blocks (the entire display full of blocks)

The display is being initialized properly, so both your code and wiring are correct. However, the contrast setting of the display is wrong. You need to check the wiring for your contrast potentiometer and adjust as necessary.

---
Tags: lcd
---


# Question
Title: Help with code for pushbutton connected to adafruit motorshield v2
can anybody assist me with a code? I am using arduino uno with adafruit v2 motor shield stacked on top. I am using a pushbutton and one DC motor and I want the state of the push button to change after it has been pushed for a few seconds. That is I want the motor to stop running even though the push button is still pushed down.

Here is the code I'm using:

```
    /*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 4;

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);

}

void loop() {
  uint8_t i;

    // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(0);        // delay in between reads for stability

  if (buttonState==1){
     delay(1000);

  myMotor->run(FORWARD);
    myMotor->setSpeed(150);
    delay(1000);

 }

 else if (buttonState==0){
  myMotor->run(FORWARD);
    myMotor->setSpeed(0);

  }

}

```

# Answer
> 0 votes
You need to do various things:

You need to change your logic not to use delay. Search on "Arduino Blink Without Delay" to find examples of doing timed actions with `millis()` instead of using delay.

Then you need to adjust your logic to start running the motor when the user presses a button, and stop running the motor when either the user releases the button or enough time elapses.

---
Tags: arduino-uno, adafruit, arduino-motor-shield
---


# Question
Title: expected unqualified-id before 'if' if (!client.connected() && lastConnected)
```
#include <PulseSensorPlayground.h>
#include <Timer.h>
#include <SPI.h>
#include <Ethernet.h>

Timer t;
PulseSensorPlayground pulseSensor;

// Local Network Settings
byte mac[] = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "UVGOLIA40B9YHKU8";
const int updateThingSpeakInterval = 16 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
// Variable Setup
const int PulseWire = A0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           //for heart rate sensor
float myTemp;
int myBPM;
String BPM;
String temp;
int error;
int panic;
int raw_myTemp;
float Voltage;
float tempC;

long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
// Initialize Arduino Ethernet Client
EthernetClient client;
void setup()
{
  // Start Serial for debugging on the Serial Monitor
  Serial.begin(9600);
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }

  // Start Ethernet on Arduino
  void startEthernet();
}
void loop()
{
  // Read value from Analog Input Pin 0
  String analogPin0 = String(analogRead(A0), DEC);
  // Print Update Response to Serial Monitor
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
  //temp---
  raw_myTemp = analogRead(A1);
  Voltage = (raw_myTemp / 1023.0) * 5000; // 5000 to get millivots.
  tempC = Voltage * 0.1;
  Serial.println(tempC);

  //Serial.print(temp);
  //Serial.print(" ");

  //-----BMP180-----------
  //
  int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
  // "myBPM" hold this BPM value now.
  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".

    Serial.println(myBPM);
    char buffer1[10];
    char buffer2[10];
    String BPM = dtostrf(myBPM, 4, 1, buffer1);
    String temp = dtostrf(tempC, 4, 1, buffer2);
    // Print the value inside of myBPM.
  }
}
//----------------
void panic_button() {
  panic = digitalRead(8);
  if (panic == HIGH) {
    Serial.println(panic);
  }
}
// Disconnect from ThingSpeak
if (!client.connected() && lastConnected)
{
  Serial.println("...disconnected");
  Serial.println();
  client.stop();
}
// Update ThingSpeak
if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
{
  updateThingSpeak("field1=" + BPM + "&field2=" + temp + "&field3=" + panic);
}
// Check if Arduino Ethernet needs to be restarted
if (failedCounter > 3 ) {
  startEthernet();
}
lastConnected = client.connected();
}
void updateThingSpeak(String tsData)
{
  if (client.connect(thingSpeakAddress, 80))
  {
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + UVGOLIA40B9YHKU8 + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(tsData.length());
    client.print("\n\n");
    client.print(tsData);
    lastConnectionTime = millis();
    if (client.connected())
    {
      Serial.println("Connecting to ThingSpeak...");
      Serial.println();
      failedCounter = 0;
    }
    else
    {
      failedCounter++;
      Serial.println("Connection to ThingSpeak failed (" + String(failedCounter, DEC) + ")");
      Serial.println();
    }
  }
  else
  {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
    Serial.println();
    lastConnectionTime = millis();
  }
}
void startEthernet()
{
  client.stop();
  Serial.println("Connecting Arduino to network...");
  Serial.println();
  delay(1000);
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  }
  else
  {
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
  }
  delay(1000);
}

```

# Answer
If you look at this fragment of your code:

```
void panic_button(){
  panic = digitalRead(8);
    if(panic == HIGH){
    Serial.println(panic);
    }
}
// Disconnect from ThingSpeak
if (!client.connected() && lastConnected)

```

You see that the function panic\_button() stops at the last }, the next is a statement which is not part of a function.

I think the } should be removed, but your code is aligned quite badly, so:

* First align all { and }
* Indent each level with a tab or 2, 3 or 4 spaces
* You will see a misalignment, add/remove a { (like above) or }.
> 5 votes

---
Tags: arduino-uno
---


# Question
Title: Is it possible to connect miband2 and arduino nano (?)
I want to make an IOT project using an Arduino nano and I need heart rate sensors. I I have a miband2. So, is it possible to connect them ?

# Answer
> 1 votes
You need to connect as a central device. I've had good luck with the adafruit nrf52 feather. Also see: https://github.com/Freeyourgadget/Gadgetbridge for the protocol.

# Answer
> 0 votes
To use BLE on Arduino, I tried google and found this Article:

Examples:

* HM-10 (HM-11) BLE Module
* BLE Nano
* BLE Mini
* BLE Shield v2.1
* RFduino
* Bluno series
* BLE WT51822-ABS
* Grove – BLE
* BLEduino

Chose one that fits best, and use it.

---
Tags: arduino-nano, bluetooth, iot
---


# Question
Title: attachInterrupt() corrupting Serial buffer requiring Serial restart
I am working on a proof-of-concept ADC to "explode" what's inside of an ADC chip for teaching purposes.

Currently, I have a sketch that uses a push-button to act as a clock-pulse that counts up (1, 2, 3, 4, ...) for every positive edge using the attachInterrupt() function.

The sketch works great to view the data in the serial monitor.

I am pairing the Arduino (Teensy 3.2) with a Raspberry Pi configured to read data off the Serial line to a text box.

After a good bit of troubleshooting it appears that the `attachInterrupt()` function corrupts the Serial buffer with garbage for every interrupt. For instance, if I use

```
Serial1.flush();
Serial1.begin(115200);

```

immediately after the interrupt and *then* send out my data using `Serial.println()` I get my expected decimal value at my output. However, without these lines I just get unicode garbage at my Serial output. See full "fixed" sketch code below:

My question is: why is this happening? I should not need to restart Serial every iteration of the clock.

```
#define HWSERIAL Serial1

const int numBits = 12;             //Number of bits in ADC (resolution)
const int comparatorPin = 14;       //Pin number of comparator out
const int clockPin = 15;            //Pin number of external clock (square wave) input; expecting clock with 50% duty-cycle
volatile int comparatorState = 0;   //Is comparator high or low?
volatile bool clockState = 0;       //Is clock high or low?
volatile int masterCount = 0;       //Our master count
volatile bool isSameVal = false;    //Is the value of the master count the same value as last cycle?

int outVal = 0;

int masterBinCount[12];     //Array to store binary value of the master count
byte outputPins[12];        //Array to store the numbers associated with the output pin numbers
int maxValue = 0;           //Initialize max counter value to zero

void setup() {
  Serial.begin(115200);       //Begin Serial transmission
  HWSERIAL.begin(115200, SERIAL_8N1);
  HWSERIAL.flush();
  delay(2000);

  defineOutPins(outputPins);  //Assign pin numbers for output pins

  pinMode(14, INPUT);   //Comparator Pin
  pinMode(15, INPUT);   //Clock-in pin

  maxValue = pow(2, numBits);   //Set max counter value to max bit resolution. Ex. for 12 bits --> 4096
}

void loop() {
  attachInterrupt(clockPin, doOnClock, RISING);   //When clock is on a positive-edge execute doOnClock function

  HWSERIAL.flush();
  HWSERIAL.begin(115200);

  if(isSameVal == false) {    //If the master count is NOT the same as the last cycle
    convertDecToBin();        //Convert the master count (dec) to binary
    binaryToPins();           //Send the binary value (via digitalWrite) to output pins
  }
  else {
    //Do nothing
  }
  delay(1000);
}

void defineOutPins(byte pinNos[]) {   //Assign pin numbers to parallel binary out: Teensy 3.2 pin #0 --> #11
  for(byte i = 0; i < numBits; i++) {
    pinNos[i] = {i};      //Assign current pin this value
    pinMode(i, OUTPUT);   //Define pins as outputs
  }
}

void doOnClock() {
  comparatorState = digitalRead(comparatorPin);   //Check comparator state

  if(comparatorState >= 0.5) {            //Check if positive clock pulse
    if(masterCount == (maxValue - 1)) {   //Check if current count value is at "ceiling"
      //Do nothing
    }
    else {            //Else increment count up
      masterCount++;
    }
  }
  else if(comparatorState < 0.5) {    //Check if negative clock pulse
    if(masterCount == 0) {            //Check if current count value is at "floor"
      //Do nothing
    }
    else {
      masterCount--;    //Else decrment count down
    }
  }

  isSameVal = false;    //Set "finished" counting for this clock-pulse
}

void convertDecToBin() {
  for(int j = 0; j < numBits; j++) {
    int tempCnt = bitRead(masterCount, j);
    masterBinCount[numBits - (j+1)] = tempCnt;    //Populate the master binary count array in "reverse" order starting with the LSB at the highest array index
  }
}

void binaryToPins() {
  for(int e = 0; e < numBits; e++) {
    //digitalWrite(outputPins[e], masterBinCount[e]);   //Write our master binary value to output pins
    //Serial.print(masterBinCount[e]);                    //THIS LINE IS FOR TROUBLESHOOTING!!
  }
  isSameVal = true;       //Tell program we wrote the master count to the pins for this clock cycle

  outVal = masterCount;

  Serial.println(outVal);
  HWSERIAL.println(outVal);

  //Serial.print(" decimal: ");   //THIS LINE IS FOR TROUBLESHOOTING!!
  //Serial.print(masterCount);    //THIS LINE IS FOR TROUBLESHOOTING!!
  //Serial.println("");           //THIS LINE IS FOR TROUBLESHOOTING!!
}

```

# Answer
> 1 votes
I believe your issue is with initializing `HWSERIAL.begin(115200);` in `void loop`. I created this simple sketch to verify this. Firstly, I commented out the second initialization of `Serial.begin`, and you can see I was getting a perfect output to the serial monitor. Then I uncommented the line, re-uploaded the code to the Arduino, and you can see it didn't even make it through one print before it sent a bunch of garbled junk and effectively froze my serial port.

Remove `HWSERIAL.begin(115200);` from `void loop` and only set it in `void setup`.

Hope this helps!

```
void setup()
{
  Serial.begin(115200);
}

void loop()
{
  Serial.begin(115200);
  Serial.print("Test");
  Serial.print(" - ");
  Serial.println(millis());
}

```

---
Tags: serial
---


title: Programming Arduino in Pascal?

text:
# Question
Title: Programming Arduino in Pascal?
My question is simple: there is any Pascal or Pascal-class (FPC, Delphi, mikroPascal) programming language for Arduino?

Preferably (I hope I don't ask too much) that language should not be older than 10 years.

---

Update:
Let's not start a flame war about "why the xxx programming language is so much better Pascal" and keep focus on the core of this question. I know that Pascal has it flaws (nothing its perfect, right?). I accept them and I still want to use it :)
Many thanks.

# Answer
Not Pascal, but Ada, which is much less restrictive than Pascal while enjoying the same advantages over low-level programming, and much more actively supported with language revisions as recently as 2012 and the formally provable SPARK language, for when you need your code to work.

Any processor which gcc supports can potentially support Ada, whose Gnat compiler is fully part of gcc.

That's not the whole story because you also need run-time system support for Ada's facilities, but for the Arduino's AVR processor there is a well established environment in the form of the AVR-Ada project.

It generates nice tight little executables, you'll be amazed how much less space simple Gnat executables take compared to Arduino ones - unless you've already made the same comparison between Arduino and C ... which after all uses the same gcc compiler.

For ARM-based Arduinos (Arduino Due at least) the same is possible, though the support is newer and possibly less well established, see the Cortex-GNAT project.

Leaving the Arduino, Ada has also been demonstrated on the MSP430 processor \- my own project, sadly neglected at the moment.
> 4 votes

# Answer
> Is it possible to program Arduino in Pascal?

The answer is yes and no. The answer is yes because it is possible to port the p-code virtual machine to Arduino and compile for that.

The answer is no if extending the question with "is there a supported open-source Arduino/AVR IDE for Pascal available?"

There are a few commercial AVR/Pascal products. You can easily web-search them.

Last, a possible short-cut is to use p2c, a Pascal to C translator, as a pre-processor in the Arduino IDE. There are hooks in the Arduino build for adding additional tools.

Cheers!
> 1 votes

# Answer
A Pascal front-end to the Gnu compiler collection (gcc, on which nearly all the of AVR programming is based) already exists. Therefore, a Pascal compiler for AVR exists in principle if not in fact (and I don't know that it doesn't). I'd start by getting in touch with the folks working on the GPC to find out what has already been done.
> 1 votes

# Answer
There's also pascal p5c at sourceforge --\> https://sourceforge.net/projects/pascal-p5c/

It uses gnu c as intermediate code so should work on any platform where gcc is available.
> 0 votes

---
Tags: arduino-uno, arduino-mega, arduino-due, arduino-nano
---


title: Not able to split string into 2 char

text:
# Question
Title: Not able to split string into 2 char
I am trying to split an incoming string into 2 integer values since I have to control 2 dc motors with it. The processor is node MCU and I get following error:-

Com Port Reading:-

```
WiFi connected
Received: "84+62"
"84+62"

Soft WDT reset

>>>stack>>>

ctx: cont
sp: 3ffffd90 end: 3fffffc0 offset: 01b0
3fffff40:  2b343822 00223236 3ffee70c 40204148
3fffff50:  3ffe85ee 3ffee6d8 3ffee70c 402043c5
3fffff60:  3ffe85dc 3ffee70c 3ffee6d8 402043c5
3fffff70:  3ffe85f0 3ffee69c 00000000 00000001
3fffff80:  00000000 40200038 3ffefca4 0000000f
3fffff90:  00000007 00000000 00000001 402048f9
3fffffa0:  3fffdad0 00000000 3ffee744 40204984
3fffffb0:  feefeffe feefeffe 3ffe851c 401009a5
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld

```

Code:-

```
if (msg.length() > 0) {
        Serial.print("Received: "); Serial.println(msg);
        char charBuf[50];
        msg.toCharArray(charBuf, 50);
        Serial.println(charBuf);

        char left[3] = {};
        char right[3] = {};
        int n = 0;

        while (charBuf != 0) {
          for (int i = 0; i < strlen(charBuf); i ++) {
            if (charBuf[i] != '+') {
              left[n] += charBuf[i];
              n++;
            }
            else {
              n = 0;
              break;
            }
            right[n] += charBuf[i];
            n++;
          }
        }
        Serial.println("Left Motor: "); Serial.print(left);
        Serial.println("Right Motor: "); Serial.print(right);

    }

```

My desired result is following:-

```
Left Motor: 84
Right Motor: 62

```

So what changes I need to make?

# Answer
> 0 votes
Here's an example sketch that uses `strtok()`.

```
char charBuf[] = "\"84+62\"";

// Set array size to maximum number of integers you will receive.
uint16_t myArray[2];

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(charBuf, "\"+");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "\"+");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }
}

void loop(){}

```

`myArray[0]` contains 84 and `myArray[1]` contains 62.

# Answer
> 0 votes
You get this memory leak because you overflow the variable `right`. This does not happen in the for loop itself even though this could be implemented more straight forward. But it's the while loop that doesn't come to an end (`charBuf` doesn't change and will not become 0) and in the second iteration `n` will be 1 initially (due to `n++` at the end of the for loop). That causes the overflow at `right[n] += charBuf[i];`.

So: remove the `while` loop (and use `strtok()`).

# Answer
> 0 votes
> "84+62"

The additional doublequote characters are part of your string and charBuf

```
    Serial.println(charBuf);  // Text with " and  +

    char* cpl = nullptr;
    char* cpr = nullptr;
    for (char* cp = charBuf; *cp != 0; cp++) {
        if (*cp != '"' && ! cpl )  cpl = cp;
        if (*cp == '"') *cp = 0;
        if (*cp == '+' ) {
          *cp = 0; // split
          cpr = cp+1;
        }
    }
    Serial.println("Left Motor: "); Serial.println(atoi(cpl));
    Serial.println("Right Motor: "); Serial.print(atoi(cpr));

```

---
Tags: nodemcu, code-review, error
---


title: Reaction timer using millis

text:
# Question
Title: Reaction timer using millis
I've written this code for a reaction timer game. The reaction time is to be displayed in milliseconds to the serial monitor as accurately as possible. The reaction time is not being displayed correctly. I'm including my timer setup routine and where I increment milliseconds.

```
TCCR1A=0;
TCCR1B=0;
timer1_counter=65536;
TCNT1=timer1_counter;
TCCR1B |=(1<<CS12);

TIMSK1 |=(1<<TOIE1);
interrupts();
}

ISR(TIMER1_OVF_vect)
{
  TCNT1=timer1_counter;
  int_flag=1;
 }

  digitalWrite(LED,LOW);
  randomSeed(analogRead(A1));
  NumSecs=random(1000,7000);
  delay(NumSecs);
  digitalWrite(LED,HIGH);
  while(digitalRead(PUSHBUTTON) == HIGH)
  {
  }
  if (int_flag==1){
  millisecs++;
  int_flag=0;
  }

```

# Answer
> 1 votes
You're over-thinking this:

```
  digitalWrite(LED,LOW);
  randomSeed(analogRead(A1));
  NumSecs=random(1000,7000);
  delay(NumSecs);
  digitalWrite(LED,HIGH);
  unsigned int startTime = millis();
  while(digitalRead(PUSHBUTTON) == HIGH)
  {
  }
  unsigned int elapsed = millis() - startTime;

```

After that code, `elapsed` will contain the number of milliseconds it took the user to press the button. Note, however, that the user could cheat and simply press the button the whole time while waiting for the LED to change states. You could add logic to make sure the button isn't pressed just before you change the LED state, but I'll leave that up to you.

# Answer
> 0 votes
Your ISR is not counting the elapsed milliseconds. Instead, it just sets a flag and lets the main program do the counting when it sees the flag. Here:

```
while(digitalRead(PUSHBUTTON) == HIGH)
{
}

```

you are waiting for the user to press the button. The program does nothing else during the wait. It doesn't event count the time. Here:

```
if (int_flag==1){
    millisecs++;
    int_flag=0;
}

```

you increment *once* the millisecond count *after* the wait.

The obvious solution is to count the milliseconds while waiting for the button press:

```
millisecs = 0;  // don't forget to reset the stopwatch!
while (digitalRead(PUSHBUTTON) == HIGH) {  // button not pressed
    if (int_flag) {
        millisecs++;
        int_flag = false;
    }
}

```

(side note: `int_flag` should be a `bool`).

There are still many issues with this program. First of all, it should check that the user did not press the button before the LED came up.

Then, the interrupt period is not one millisecond, because the interrupt takes some time to be processed by the CPU and to go through its prologue. By the time you do `TCNT1=timer1_counter;` you are at least several tens of cycles late. You should instead configure the timer to keep the correct period by itself, typically using CTC mode.

Also, there is no point in letting the main program count the milliseconds when the ISR could do it. E.g.

```
ISR(TIMER1_OVF_vect)
{
    millisecs++;
}

// Avoid a race condition when reading millisecs.
static inline unsigned int getMillisecs()
{
    noInterrupts();
    int millisecsCopy = millisecs;
    interrupts();
    return millisecsCopy;
}

```

Note that the time keeping variables should be unsigned in order to avoid undefined behaviour on overflows.

Finally, it may be a good learning experience for working with interrupts, but in the end just using `millis()` or `micros()` would be the easiest way to achieve what you want.

---
Tags: millis
---


# Question
Title: Problem with SPI when using rf24 NRF24L01 transceiver with LED matrix MD_MAX72xx
I am currently using Arduino Mega to use a LED matrix and a NRF24L01 transceiver.

for LED matrix, I use MD\_MAX72xx library. While for the transceiver I use the RF24 library.

I am already able to interface Arduino using two different LED matrix, and two matrix board is already using the SPI.

But when I try to add the RF24 library, and radio.begin(); the LED matrix isn't working properly anymore.

Here is my whole code:

```
#include <MD_MAX72xx.h>
#include <SPI.h>
#include <Servo.h>

#include <nRF24L01.h>
#include <RF24.h>

#define PRINT(s, v) { Serial.print(F(s)); Serial.print(v); }

#define BUF_SIZE      75  // text buffer size
#define CHAR_SPACING  3   // pixels between characters
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 4

const int buzzer_pin = 26;
const int servo_pin = 28;

unsigned long buzz_time;
unsigned long sys_time;
String buzz_type = "off";
int buzz_count = 0;
char charr[50];

Servo myservo;

RF24 radio(30, 32); // CE, CSN
const byte address[6] = "GLN71";
//const byte address[5] = {'R','x','A','A','A'};

struct LineDefinition
{
  MD_MAX72XX  mx;
  char    message[BUF_SIZE];
  boolean newMessageAvailable;    // true if new message arrived
};

struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, 51, 52, 53, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, 51, 52,  49, MAX_DEVICES), "MAX", true }
};

#define MAX_LINES   (sizeof(Line)/sizeof(LineDefinition))

void printText(uint8_t lineID, uint8_t modStart, uint8_t modEnd, char *pMsg)
// Print the text string to the LED matrix modules specified.
// Message area is padded with blank columns after printing.
{
  uint8_t   state = 0;
  uint8_t   curLen;
  uint16_t  showLen;
  uint8_t   cBuf[8];
  int16_t   col = ((modEnd + 1) * COL_SIZE) - 1;

  Line[lineID].mx.control(modStart, modEnd, MD_MAX72XX::UPDATE, MD_MAX72XX::OFF);

  do     // finite state machine to print the characters in the space available
  {
    switch(state)
    {
      case 0: // Load the next character from the font table
        // if we reached end of message, reset the message pointer
        if (*pMsg == '\0')
        {
          showLen = col - (modEnd * COL_SIZE);  // padding characters
          state = 2;
          break;
        }

        // retrieve the next character form the font file
        showLen = Line[lineID].mx.getChar(*pMsg++, sizeof(cBuf)/sizeof(cBuf[0]), cBuf);
        curLen = 0;
        state++;
        // !! deliberately fall through to next state to start displaying

      case 1: // display the next part of the character
        Line[lineID].mx.setColumn(col--, cBuf[curLen++]);

        // done with font character, now display the space between chars
        if (curLen == showLen)
        {
          showLen = CHAR_SPACING;
          state = 2;
        }
        break;

      case 2: // initialize state for displaying empty columns
        curLen = 0;
        state++;
        // fall through

      case 3: // display inter-character spacing or end of message padding (blank columns)
        Line[lineID].mx.setColumn(col--, 0);
        curLen++;
        if (curLen == showLen)
          state = 0;
        break;

      default:
        col = -1;   // this definitely ends the do loop
    }
  } while (col >= (modStart * COL_SIZE));

  Line[lineID].mx.control(modStart, modEnd, MD_MAX72XX::UPDATE, MD_MAX72XX::ON);
}

void buzz_start(){
    buzz_count = 5;
    buzz_time = millis();
}

void buzz_call(){
  if(buzz_count > 0){
    if(millis() >= buzz_time){
      if(buzz_type == "off"){
        tone(buzzer_pin, 1000);
        buzz_type = "on";
      }else{
        noTone(buzzer_pin);
        buzz_type = "off";
        buzz_count--;
      }
      buzz_time = millis() + 300;
    }
  }
}

void setup()
{
  Serial.begin(57600);
  pinMode(buzzer_pin, OUTPUT);

  myservo.attach(servo_pin);

  tone(buzzer_pin, 1000);
  Serial.println("BEGIN");

  for (uint8_t i=0; i<MAX_LINES; i++){
    Line[i].mx.begin();
  }

  radio.begin();
  radio.openReadingPipe(20, address);
  radio.setPALevel(RF24_250KBPS);
  radio.startListening();

  String charrr = "STOP";
  charrr.toCharArray(charr, 50);
  printText(1, 0, MAX_DEVICES-1, charr);

  myservo.write(90);
  delay(500);
  myservo.write(180);

  noTone(buzzer_pin);
  sys_time = millis();
}

int counter = 10;
int disp = 0;
void loop()
{
  String charrr = String(counter);
  charrr.toCharArray(charr, 50);
  printText(0, 0, MAX_DEVICES-1, charr);
  if(counter == 0){
    counter = 9;
    if(disp == 0){
     disp = 1;
     String charrr = "  GO";
     charrr.toCharArray(charr, 50);
     printText(1, 0, MAX_DEVICES-1, charr);
     myservo.write(90);
     buzz_start();
    }else{
     disp = 0;
     String charrr = "STOP";
     charrr.toCharArray(charr, 50);
     printText(1, 0, MAX_DEVICES-1, charr);
     buzz_start();
     myservo.write(180);
    }
  }
  if(millis() >= sys_time){
    counter--;
    sys_time = millis() + 1000;
  }

  buzz_call();

}

```

I think the problem here is not connection, but with the initalization of the RF24, and radio.begin();

# Answer
> 0 votes
I looked into the source code of the MD\_MAX72XX library. The constructor with SPI pins starts software SPI.

Use the `MD_MAX72XX::MD_MAX72XX(moduleType_t mod, uint8_t csPin, uint8_t numDevices):` constructor to work with SPI hardware/library with all devices.

```
struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, 53, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, 49, MAX_DEVICES), "MAX", true }
};

```

Or if the MD\_MAX72XX worked for you with software SPI, then use some other pins then hardware SPI pins to make hardware SPI free for the NRF24L01.

```
struct LineDefinition  Line[] =
{
  { MD_MAX72XX(HARDWARE_TYPE, SW_SPI_SI, SW_SPI_CLK, MAX1_CS, MAX_DEVICES), "MAX", true },
  { MD_MAX72XX(HARDWARE_TYPE, SW_SPI_SI, SW_SPI_CLK, MAX2_CS, MAX_DEVICES), "MAX", true }
};

```

---
Tags: arduino-mega, led, library, spi, nrf24l01+
---


title: Problem with a code

text:
# Question
Title: Problem with a code
I have one problem with my code and I'm a beginner and I can't solve it. Can you help me? Thank you so much.

I have this problem:

```
error: expected unqualified-id before '{' token

```

And this is my code:

```
int trigPin = 12;
int echoPin = 11;
long timeperiod, cm;
const int analogOutPin = 9;
int brightness;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){

  if (timeperiod > 50)
  analogWrite(analogOutPin,0);
}
{

  if (timeperiod 10 < 50){
  for(brightness = 0; brightness < 256; brightness++){
    analogWrite(led,brightness);
    delay(10);}
}}
  if (timeperiod < 10)
  analogWrite(analogOutPin,0);

{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(20);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(0);
  digitalWrite(trigPin, LOW);

  timeperiod = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(timeperiod);
  Serial.print("dist=");
  Serial.print(cm);
  Serial.println();

  delay(10);
}
long microsecondsToInches(long microseconds)
{
  return microseconds / 74 /2;
}
  long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29/ 2;
}

```

# Answer
The only problem I can see in your code is that your code modules are starting and ending anywhere. See from where till where you want to run a particular line of code. If you writing this code on arduino IDE you will be able to see which the ending of a particular bracket when you keep the cursor on one.
> 1 votes

# Answer
For example, the first 5 lines:

```
void loop(){

  if (timeperiod > 50)
  analogWrite(analogOutPin,0);
}
{

```

Always align your braces, you can do it like this:

```
 xxx {
    yyy
 }

```

or

```
 xxx
 {
    yyy
 }

```

where xxx and yyy can be one or more statements.

If you align the first 5 lines correctly, you see you should add a {:

```
if (timeperiod > 50)
{ // <- added
    analogWrite(analogOutPin,0);
}

```

Also, if you have an if, for or while statement, ALWAYS add brackets, even if it is only one line. Thus:

```
if (timeperiod > 50)
    analogWrite(analogOutPin,0);

```

should be written as

```
if (timeperiod > 50)
{
    analogWrite(analogOutPin,0);
}

```

This is not a mandatory rule, but if you later misindent something, or add a new line in the body, it is easily forgotten to add the brackets, so you better can do it beforehand.

So (also), it is wise to

* align brackets (like explained above)
* always use brackets in if/while/loop statements.
* always use the same amount of spaces (or a tab) to indent a new level (e.g. after an if, while, loop, or the body of a function).
* use new lines between functions; this makes it much easier to read
* split up big functions with many brackets, in (sub) functions/methods (not in your case, yet)
> 0 votes

# Answer
Your problems start here:

```
void loop(){

  if (timeperiod > 50)
  analogWrite(analogOutPin,0);
}
{

```

You are missing an opening brace for your if statement, and then have an extra opening brace afterwords. Also, any code inside braces should be indented from the code before it:

```
void loop(){

  if (timeperiod > 50) {
    analogWrite(analogOutPin,0);
  }

  if (timeperiod 10 < 50){
    for(brightness = 0; brightness < 256; brightness++) {
      analogWrite(led,brightness);
      delay(10);
    }
  }
  //And the rest of your loop function also needs cleanup...

```

The rest of your loop function needs cleanup as well. You've got bad indentation and mismatched braces all over the place. As @Majenko says in their comment, if you clean up your code formatting then your syntax problems will be obvious.
> 0 votes

---
Tags: programming
---


# Question
Title: Generate a ramp input with an Arduino Uno
Is there anyway to generate a ramp input from an Arduino Uno? A visual depiction of the pulse I am looking for is as follows:

With other microcontrollers, I was able to use their in-built DACs, however I am aware that the Arduino UNO doesn't have any? Is there a way using PWM or analogWrite to output these type of pulses? I'm new to Arduino programming, so I'm a bit unsure. However my next guess would be to use an R-2R ladder to output this type of pulse?

# Answer
A RC filter will create a slow slewrate.

simulate this circuit – Schematic created using CircuitLab

The circuit creates this signal:

A slow rising signal and a fast falling signal can be created with an extra transistor (the signal will be inverted).

simulate this circuit

For a linear rising and falling edge, a resistor network with a few digital pins is a simple solution. I think it can be created with an opamp circuit as well, but there are also special chips called "slew rate limiter".
> 0 votes

# Answer
By "ramp", it seems that you mean a square wave with sloping rather than vertical edges between + and -. Can you clarify the question further: do the sloping parts need to be linear?

Direct synthesis of the waveform could be done using the digital output ports and an R2R ladder, as suggested in the comments. Each PWM timer output of the AVR can control output of 2 digital pins and definitely with a timing precision better than 1 microsecond. If high voltage resolution is needed, this method may not be able to produce the result you want.

Other possible solutions:

* The waveform as plotted in the original post looks like a truncated sine wave. Such a waveform could be made by clipping a sine wave with an operational amplifier. For the sine wave connect the Arduino to a DDS module such as AD9850/1.
* Use an external digital-to-analog converter, e.g. MCP48x2
* Use an Arduino Zero or other 32-bit microcontroller (e.g. ARM STM32). These microcontrollers have a true analog output pin, but it's not bipolar.
> 1 votes

---
Tags: arduino-uno, voltage
---