title: Serial source code

text:
# Question
Title: Serial source code
`Serial` is documented on the Reference pages, but seems to receive special treatment (no need to include header), and there does not seem to be any file with the Source code.

`Stream` is the base class for `Serial` and inherits from the Print class.

There is source for `Stream.h`

`LiquidCrystal_I2C` also inherits from the Print class, and I was planning to write code which outputs to either `LiquidCrystal_I2C` or `Serial`; there are many options, but I was looking for `Serial` to explore its inner workings.

# Answer
`Serial` is an *instance* of the `HardwareSerial` class. It is defined in `HardwareSerial0.cpp`:

```
#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

```

`HardwareSerial` is a child of `Stream` as defined in `HardwareSerial.h`:

```
class HardwareSerial : public Stream
{
    ....
};

```

`Stream` is a child of `Print` as defined in `Stream.h`:

```
class Stream : public Print
{
    ....
};

```

`Print` is a top-level class with no inheritance.

`Serial` is *not* a class. It is an *instance* of a class. That is, it's an object that has been *constructed* from the class definition. Anything you access member functions of using a `.` is an *instance* of a class (aka an *object*) not a class itself. Anything you access member functions with `::` is a class using *static* member functions.

Examples:

```
Serial.println(); // Call the println() function in the Serial object
Wire.beginTransmission(0x34); // Call the beginTransmission function in the Wire object
Foo::bar(); // Call the static function bar() in the Foo class.

```
> 4 votes

---
Tags: serial
---


title: Comparing 2 char converted from a array

text:
# Question
Title: Comparing 2 char converted from a array
I wrote this little program to test converting and comparing 2 char with each other. With some help from here i have learned that you have to NULL-terminate c stings. But when i try to compare them i still get that they are not equal to each other. this is my program:

```
char code[4] = {'1','2','3','4'};
char strcode[5];
char pass[4] = {'1','2','3','4'};
char strpass[5];

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

void loop()
{
    memcpy(strcode, code, 5);
    strcode[4] = '\0';
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
    memcpy(strpass, pass, 5);
    strpass[4] = '\0';
    Serial.println(strpass);
    Serial.println("donepass");
    if (strpass == strcode)
    {
        Serial.println("yes");
    }
    else
    {
        Serial.println("no");
    }
}

```

I get this in my serial monitor:

```
1234
done
1234
donepass
no

```

Why is this not equal to each other?

# Answer
You cannot compare char arrays with `==`. A char array, as far as your program is concerned, is just a block of memory. That memory has an address where it starts. It is that address that is stored in your array variable.

C string library functions take that address and read the block of memory starting there. However it doesn't know how big the memory block is, only where it starts. So they operate on the content up until they find the NULL character (which is why it is vitally important to NULL terminate your strings).

Comparing two char array variables with `==` is just comparing the addresses stored in those variables. Instead you need to compare, byte by byte, the contents of the memory starting at the specified memory addresses up until the NULL characters.

There's various functions for doing that depending on how you want to compare.

```
strcmp(a, b)
strncmp(a, b, n)
strcasecmp(a, b)
strncasecmp(a, b, n)

```

All return 0 for `a == b`, a negative number for `a < b` and a positive for `a > b`.

The "n" variants (e.g., `strncmp`) take the extra parameter giving a maximum number of characters to compare. Useful for looking at just the first few characters of a string (also useful for stopping buffer overruns).

The "case" variants are *case insensitive* comparisons - that is "foo" matches with "Foo" and "foO".
> 2 votes

---
Tags: array
---


title: Wierd Issue with PWM pin

text:
# Question
Title: Wierd Issue with PWM pin
I'm trying to run two of my motors through PWM. Here's my code -

```
#include <Servo.h>
int Lm = 11;
int Rm = 10;
int incomingByte = 0;
int pos = 0;
Servo myservo;
void setup() {
  pinMode(Rm, OUTPUT);
  pinMode(Lm, OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(2,OUTPUT);
  myservo.attach(3);
  Serial.begin(9600);

}

void loop() {
  blinkers();
  if (Serial.available() > 0) {
                incomingByte = Serial.read();
  }
  if(incomingByte == 49){
    analogWrite(Rm, 128);
    analogWrite(Lm, 128);
  }
   else if(incomingByte == 48){
    analogWrite(Rm, 0);
    analogWrite(Lm, 0);
    myservo.write(0);
  }
  else if(incomingByte == 50){
    analogWrite(Rm, 0);
    analogWrite(Lm, 128);
    delay(500);
    analogWrite(Lm, 0);
  }
  else if(incomingByte == 51){
    analogWrite(Rm, 128);
    analogWrite(Lm, 0);
    delay(500);
    analogWrite(Rm, 0);
  }
  else if(incomingByte == 52){
    for (pos = 0; pos <= 180; pos += 10) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 10) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);
  }
}
}

void blinkers(){
    digitalWrite(7, HIGH);
    digitalWrite(2, HIGH);
  delay(100);
  digitalWrite(7, LOW);
  digitalWrite(2, LOW);
  delay(100);
}

```

Now in this code... Lm, and Rm are my motors. The motor Lm runs perfectly fine, but Rm doesn't move at all. When I use `digitalWrite` instead, both motors work fine.

I tried running the motor in the exact same setup but this time with only the code for running the motor by PWM. The code was -

```
void setup() {
  pinMode(10,OUTPUT);

}

void loop() {
  analogWrite(10, 128);
  delay(100);
  analogWrite(10, 0);
  delay(100);

}

```

This code worked perfectly fine.

So clearly there is an issue in the earlier code but I can't figure out what. Everything is correct in that as well but the motor refuses to move...

Can anyone tell why is this happening?

# Answer
> 2 votes
It is a timer conflict.

The Servo reference says: "*...use of the library disables analogWrite() (PWM) functionality on pins 9 and 10...*"

This is a picture of the pinmapping of the Arduino Uno: PighiXXX - Uno.
Pin 9 en 10 uses OC1A en OC1B for PWM, that is Timer1. You can't use PWM on them when the Servo is used.
Pin 11 uses OC2A for PWM, which is Timer2.

I suppose it will work if you choose another PWM pin for analogWrite. Timer0 is used for millis and therefor the PWM frequency will be different (pin 5 and 6). That is mentioned in the analogWrite reference. In most cases that is not a problem.
Pin 3 is a normal PWM pin.

This is a common problem. The documentation is not always clear about the use of timers and other parts of the microcontroller. Many times the source code has to be read to see what is used. In the end, you need more experienced Arduino users to spot the conflict.

---
Tags: arduino-uno, programming, motor
---


title: Sim900 error on AT command AT+HTTPINIT

text:
# Question
Title: Sim900 error on AT command AT+HTTPINIT
I want to send data to my php server using sim900 module but I am unable to initialize http service on sim900.

code:

```
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(8, 9);

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

  Serial.println("Con");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // See if the SIM900 is ready
  gprsSerial.println("AT");
  delay(1000);
  toSerial();

  // SIM card inserted and unlocked?
  gprsSerial.println("AT+CPIN?");
  delay(1000);
  toSerial();

  // Is the SIM card registered?
  gprsSerial.println("AT+CREG?");
  delay(1000);
  toSerial();

  // Is GPRS attached?
  gprsSerial.println("AT+CGATT?");
  delay(1000);
  toSerial();

  // Check signal strength
  gprsSerial.println("AT+CSQ ");
  delay(1000);
  toSerial();

  // Set connection type to GPRS
  gprsSerial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(2000);
  toSerial();

  // Set the APN
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"web\"");
  delay(2000);
  toSerial();

  // Enable GPRS
  gprsSerial.println("AT+SAPBR=1,1");
  delay(10000);
  toSerial();

  // Check to see if connection is correct and get your IP address
  gprsSerial.println("AT+SAPBR=2,1");
  delay(2000);
  toSerial();

}

void loop()
{
   // initialize http service
   gprsSerial.println("AT+HTTPINIT");
   delay(2000);
   toSerial();

   // set http param value
   // ToDO : send dynamic value
   gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://www.fohoraayo.000webhostapp.com/?lat=1111&lon=1111\"");
   delay(4000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(1000);
   toSerial();

   //gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}

```

output:

```
Config SIM900...
Done!...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CREG?

+CREG: 0,1

OK
AT+CGATT?

+CGATT: 1

OK
AT+CSQ

+CSQ: 31,0

OK
AT+SAPBR=3,1,"Contype","GPRS"

OK
AT+SAPBR=3,1,"APN","web"

OK
AT+SAPBR=1,1

ERROR
AT+SAPBR=2,1

+SAPBR: 1,1,"xx.xxx.x.x"

OK
AT+HTTPINIT

ERROR
AT+HTTPPARA="URL","http://www.fohoraayo.000webhostapp.com/?lat=AT+HTTPACTION=0

ERROR
AT+HTTPREAD

ERROR
AT+HTTPTERM

ERROR

```

# Answer
For me, your code is working like charm. but change the

```
gprsSerial.begin(9600)

```

to

```
gprsSerial.begin(4800)

```
> 1 votes

---
Tags: gsm
---


# Question
Title: Arduino not recognizing when a timer reaches 0
Alright, so I'm attempting to make a timer that will turn on a light after an hour. Currently I have it set to 5 seconds for testing. What is happening is whenever I start the program it won't recognize when the timer reaches 0. Here is my code

```
/*
Hour Alarm
An hour long alarm that allows breaks
Created by: Jaxon Reid
Last Edited: 19/5/2017

Pins:
Pin 13 = Led
Pin 2 = Button
*/
int secLeft=5;
const int led=13;
const int button=2;
const int buttonIn=4;
int buttonValue=0;
// Declares the button to reset as 2 and the lightbulb on pin 13
//the secLeft means the seconds until the light turns on and button value is for wether or not the button is pushed

void setup() {
  Serial.begin(2400);
  Serial.print("On  ");
  pinMode(13,OUTPUT);
  pinMode(button,OUTPUT);
  pinMode(buttonIn,INPUT);
}
// makes the led pin an input and opens the channel for the debugger
void loop() {
  int buttonValue=digitalRead(button);
  Serial.println("Checking time");
  if (secLeft<=0) {
    Serial.println("No time remaining");
    digitalWrite(13,HIGH);
    Serial.println("Light On");
    // If the time remaining is 0 then turn on the light
  }
  if (secLeft>0) {
    Serial.println("Time Remaining");
    digitalWrite(led,LOW);
    secLeft=(secLeft--);
    Serial.println(secLeft);
  }
  if (buttonValue==1) {
    int secLeft=5;
    Serial.println("Reset Timer");
    Serial.println(secLeft);
  }
  delay(1000);
}

```

Whenever I start it up it just starts reading

```
On 5
Checking time
Time remaining
5
Checking time
Time remaining
4
Checking time
Time remaining
3
Checking time
Time remaining
2
Checking time
Time remaining
1
Checking time
Time remaining
0
Checking time
Time remaining
-1
Checking time
Time remaining
-2

```

etc... So where did I go wrong is what I'm asking. Thanks!

# Answer
As per comment and Majenko's answer you are current creating local variables called `secLeft` and `secLeft2` inside the `'if` block. These take precedence over the ones you have defined globally. Removing the `in` declarations from inside the `if` block will stop doing that and point you at the globally defined variables.

As to the rest of the code. If you have

```
secLeft=(secLeft2--);
secLeft2=(secLeft);

```

Then that translates to this sequence of instructions

1. Assign `secLeft` with the value of `secLeft2`
2. Decrement `secLeft2`
3. Assign `secLeft2` with the value of `secLeft`

And in the end you do not change anything.

This is because you are using `post-decrement` on `secLeft2` EG `secLeft2--`. This is a feature of C style languages.

I am not sure what you are even trying to do at this point.
> 2 votes

# Answer
```
int secLeft=(secLeft2--);
int secLeft2=(secLeft);

```

You are making 2 new variables there instead of using the existing ones.
> 1 votes

# Answer
Besides problems mentioned in other answers, your use of `button` and `buttonIn` variables is messed up.

With `button` equal to 2, the `pinMode(button,OUTPUT)` statement initializes pin 2 to be an output. Pin 2 is low after reset and `pinMode()` doesn't change it.

When you say `int buttonValue=digitalRead(button);` the low value at pin 2 will be read into `buttonValue`. In the sketch, `buttonValue` will never be anything but low.

To fix this problem, get rid of `buttonIn`, and in `setup()` use `pinMode(button,INPUT)` to set `button` to be an input, not an output.
> 0 votes

---
Tags: timers, timing, prototype
---


title: No Response to AT commands

text:
# Question
Title: No Response to AT commands
I'm unable to communicate with my nodemcu ESP8266 module using the AT commands. The module does not return 'ready' on the serial monitor and entering AT commands has no effect at all. I am able to upload programs onto the module and even receive messages onto the serial monitor. But not for the AT commands. Please help....

# Answer
> 1 votes
AT commands require the installation of firmware that responds to AT commands.

A plain ESP module normally comes with that firmware installed. A nodemcu doesn't. A nodemcu comes with Lua installed instead.

# Answer
> 1 votes
The bare chip knows nothing, just as an Arduino would. The AT+ command set is provided by an interpreter running on the 8266 processor. The AI Thinker modules and others, come with that interpreter already loaded. Your module does not have it installed. And any time you load a program into it, the previous one is over-written.

You can find the AT+ interpreter available for download and upload it to the module, after which it will be able to execute AT+... commands.

# Answer
> -1 votes
**Use the NodeMCU to process your logic, instead of the Arduino**

When using the NodeMCU (or NodeMcLua) you (in a lot of cases) don't really need an Arduino. The ESP8266-12E based "dev boards" with mini-usb connector can be programmed just like an Arduino, using the Arduino IDE.

**Why?**

* The ESP8266-12 is powerfull enough (32-bit 80mhz)
* The ESP8266-12 has (usually) enough I/O pins (and you can use an I/O expander if needed)
* Adding an Arduino to it is only making the system more expensive.
* Adding an Arduino to it is only making the system more complex (and needs additional wiring).

This is especially true for the ESP8266-12 nodemcu boards with mini-USB, since they're "almost" as easy to program as the Arduino.

**Configuring the board file**

You'll need to be able to select the "ESP8266" as your target, the Arduino IDE has a possibility to use board files for other targets than Arduino. This is best explained on tutorials and other sources online:

> * Install Arduino 1.6.8 from the Arduino website.
> * Start Arduino and open Preferences window.
> * Enter http://arduino.esp8266.com/stable/package\_esp8266com\_index.json into Additional Board Manager URLs field. You can add multiple URLs, separating them with commas.
> * Open Boards Manager from Tools \> Board menu and install esp8266 platform (and don't forget to select your ESP8266 board from Tools \> Board menu after installation).

Sources:

https://github.com/esp8266/Arduino

https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon

**Limitations**

When using the ESP8266, you obviously can't use any of the specific hardware features that you could normally use with the Atmega based Arduino's. However, SPI, I2C, UART, analog and digital pins should be ported rather well, and can be used. You are not able to call Atmega328 registers directly (but you may, I believe, call registers of the ESP8266 directly).

---

*Note on the boards.txt not listing your specific ESP8266*

You may find that the boards.txt does not list your specific ESP8266 or that it simply doesn't upload (can cause various errors).

*Note on Chinese boards with CH340G usb-serial chip*

The Chinese boards often come with a CH340G chip, these usb\<-\>uart chips are used to interface the MCU with the PC (over USB, while acting as an USB-COM device). These drivers for these CH340x chips aren't installed in Windows/Mac on default, you'll have to instal the drivers manually. It can be a little frustrating since these drivers usually aren't signed.

# Answer
> -1 votes
Have you tried connecting the ESP8266 to 5 V?

Some Arduino Uno boards have 2 V output for 3.3 V pin and have 3.3 V output for 5 V pin. 5 V pin can provide more current than 3.3 V pin. I have tried 3.3 V pin and it doesn't work due to lack of current. When I connect it to 5 V pin, it works.

---
Tags: arduino-ide, esp8266, nodemcu
---


# Question
Title: Sidestep one second log rate with NeoGPS when another sensor on the board need to log faster
The sample rate of an accelerometer, like an MPU6050, is much faster than the GPS log rate, different technology, different issues. A common GPS Reciver has, approximatly, one second log rate. In my specific case the accelerometer has a 100hz log rate.

With a previous code the gps log rate was slowing down the accelerometer log rate so i thought to introduce two counters:

* one for the gps
* one for the accelerometer

What i tried to do was:

```
  if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
  //Log accelerometer and gps data
  } else ((  if ((lastLog + LOG_RATE) <= micros()) {
  //Log only Accelerometer data
  }

```

---

**1. Is that a speed and memory efficient solution? Or better way exist\*?**

**2. During a 60 seconds test the board return me only the accelerometer value, never the satellites informations, i think there are some dumb errors in my code**

---

Thanks for your help :)

This is the void loop section

```
void loop()
  {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU,14,true);   // request a total of 14 registers
    AcX=Wire.read()<<8;
    AcX|= Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY=Wire.read()<<8;
    AcY|=Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8;
    AcZ|=Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    GyX=Wire.read()<<8;
    GyX|=Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY=Wire.read()<<8 ;
    GyY|=Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ=Wire.read()<<8;
    GyZ|=Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
    while (gps.available( gpsPort )) {
    fix = gps.read();  // get the entire fix structure, once per second

    if (logGPSData()) { // Log the GPS data
    SerialMonitor.println( F("GPS logged.") ); // Print a debug message
    } else {// If we failed to log GPS
    // Print an error, don't update lastLog
    SerialMonitor.println( F("Failed to log new GPS data.") );
      }
    }
   lastLogGPS=micros();
  }
  else{
    if ((lastLog + LOG_RATE) <= micros()) {

      printImuData(dataFile,lastLog, AcX, AcY, AcZ, GyX, GyY, GyZ);
      dataFile.flush();
      }
    lastLog=micros();
    }
  }

```

This the function that print only the accelerometer informations:

```
static void printImuData(Print &printer, unsigned long lastLog,
        int16_t AcX, int16_t AcY, int16_t AcZ,
        int16_t GyX, int16_t GyY, int16_t GyZ)
{//Printing the mpu6050 information

  printer.print("0");   printer.print(",");   //0 longitude
  printer.print("0");   printer.print(",");   //0 latitude
  printer.print("0");   printer.print(",");   //0 altitude
  printer.print("0");   printer.print(",");   //0 speed
  printer.print("0");   printer.print(",");   //0 course
  printer.print("0");   printer.print(",");   //0 date
  printer.print("0");   printer.print(",");   //0 time
  printer.print("0");   printer.print(",");   //0 satellites
  printer.print(lastLog); printer.print(",");
  printer.print(AcX);     printer.print(",");
  printer.print(AcY);     printer.print(",");
  printer.print(AcZ);     printer.print(",");
  printer.print(GyX);     printer.print(",");
  printer.print(GyY);     printer.print(",");
  printer.println(GyZ);

}

```

And this is the part for the GPS informations:

```
byte logGPSData()
{
  if (dataFile.isOpen())
  { // Print longitude, latitude, altitude (in feet), speed (in mph), course
    // in (degrees), date, time, and number of satellites.

    if (fix.valid.location)
      dataFile.print(fix.longitude(), 6);
    dataFile.print(',');
    if (fix.valid.location)
      dataFile.print(fix.latitude(), 6);
    dataFile.print(',');
    if (fix.valid.altitude)
      dataFile.print(fix.altitude() * 3.2808, 1);
    dataFile.print(',');
    if (fix.valid.speed)
      dataFile.print(fix.speed_mph(), 1);
    dataFile.print(',');
    if (fix.valid.heading)
      dataFile.print(fix.heading(), 1);
    dataFile.print(',');

    if (fix.valid.date) {
      dataFile.print( fix.dateTime.full_year() );
      if (fix.dateTime.month < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.month );
      if (fix.dateTime.date < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.date );
    }
    dataFile.print(',');

    if (fix.valid.time) {
      if (fix.dateTime.hours < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.hours );
      if (fix.dateTime.minutes < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.minutes );
      if (fix.dateTime.seconds < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.seconds );
    }
    dataFile.print(',');

    if (fix.valid.satellites)
      dataFile.print(fix.satellites);
  dataFile.print(',');
  dataFile.print(lastLogGPS);
    dataFile.print(',');
    dataFile.print(AcX);
    dataFile.print(',');
    dataFile.print(AcY);
    dataFile.print(',');
    dataFile.print(AcZ);
    dataFile.print(',');
    dataFile.print(GyX);
    dataFile.print(',');
    dataFile.print(GyY);
    dataFile.print(',');
    dataFile.print(GyZ);

    dataFile.println();
    dataFile.flush(); // make sure the file contains at least this much

    return 1; // Return success
  }

  return 0; // If we failed to open the file, return fail
}

```

Here a pic of some data returned by Arduino

\*I need to load easily the \*.csv whith the recorded data on matlab so i have some constraints.

# Answer
Ok, I won't recreate your whole code, but here is a logic snippet that you can use.

Let's suppose that you have 2 sensors, `sensor1` and `sensor2`.

`sensor1` is read every 10 milliseconds and `sensor2` is read every 16 milliseconds.

Here is what you would do:

Make 2 global variables for your timers :

```
unsigned long timer1 = 0;
unsigned long timer2 = 0;

```

Then make 2 constants for the frequency, this example will set the frequency in milliseconds.

```
const int frequency1 = 10;
cosnt int frequency2 = 16;

```

Then in your void loop, you would do something like this:

```
void loop () {
    if (timer1 + frequency1 >= millis()
        read(sensor1);
        timer1 = millis();
    }

    if (timer2 + frequency2 >= millis()
        read(sensor2);
        timer2 = millis();
    }
}

```

This method makes sure that your code isn't going to get *stuck* anywhere. I would also suggest to remove any `while` loops because of that danger that it might *freeze&* your code.
> 1 votes

---
Tags: gps, mpu6050, matlab
---


title: Java + JSSC + Arduino + Windows

text:
# Question
Title: Java + JSSC + Arduino + Windows
I want to know the basics of Arduino serial communications and connection with a Java application in Windows.

Can anybody provide me with a sample Java program that upon running just makes an Arduino pin high as well as the corresponding Arduino sketch, and some explanation on how the Arduino communicates with the Java app?

I am now starting with Arduino, and I have some experience with Java

I found this code on the net - will this work?

**Java code**

```
package arduino;

import jssc.SerialPort;
import jssc.SerialPortException;

public class Arduino {

public static void main(String[] args) throws InterruptedException {

    SerialPort serialPort = new SerialPort("COM3");
    try {
        System.out.println("Port opened: " + serialPort.openPort());
        System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("o".getBytes()));
        Thread.sleep(1000);
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("f".getBytes()));
        System.out.println("Port closed: " + serialPort.closePort());
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
  }
}

```

**Arduino**

```
  void setup()   {
  Serial.begin(9600);
  pinMode(8, OUTPUT);
  digitalWrite(8,HIGH);
  delay(500);
  digitalWrite(8,LOW);
  }

  int incomingByte = 0;

  void loop()
  {
 // send data only when you receive data:
    if (Serial.available() > 0) {
           int text = Serial.read();
           Serial.println(text);
           if (text == 'o') {

            digitalWrite(8,HIGH);

           }

           if (text = 'f') {

            digitalWrite(8,LOW);

           }
     }

  }

```

# Answer
> 0 votes
I managed to finish my project and here is the code

Useful information:

To prevent reset on serial port open and close

https://tushev.org/articles/arduino/22 /\* Add a 10-100 μF capacitor between reset and GND

```
 JAVA

 /* FIRST IMPORT JSSC LIBRARY */

package arduino;

import java.util.Scanner;
import jssc.SerialPort;
import jssc.SerialPortException;

public class Arduino {

public static void main(String[] args) throws InterruptedException,     SerialPortException {

    Scanner scan = new Scanner(System.in);
    int nummer = 0;
 SerialPort serialPort = new SerialPort("COM4");

        while (true) {
            menu();
             if (scan.hasNextInt()) {
            nummer = scan.nextInt();
        } else {
            System.out.println("verkeerde ingave");
        }
        switch (nummer) {
            case 0:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("a".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
            case 1:
                 serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
         serialPort.writeBytes("b".getBytes());//Write data to port
         serialPort.writeBytes("c".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;

                 case 2:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("d".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
                 case 3:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("e".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
        }

}
}

public static void menu() {
    final String ANSI_CLS = "\u001b[2J";
    final String ANSI_HOME = "\u001b[H";
    System.out.print(ANSI_CLS + ANSI_HOME);
    System.out.flush();
    System.out.println("");
    System.out.println("    ************************************************************************************");
    System.out.println("    *      ***       ********   *******   **    **  *****  **      **      ******      *");
    System.out.println("    *     ** **      **    **   **    **  **    **   ***   ****    **    ***    ***    *");
    System.out.println("    *    **   **     *** ****   **     ** **    **   ***   ** **   **  **          **  *");
    System.out.println("    *   *********    **   **    **     ** **    **   ***   **  **  **  **          **  *");
    System.out.println("    *  **       **   **    **   **    **  **    **   ***   **   ** **    ***    ***    *");
    System.out.println("    * **         **  **     **  *******     ****    *****  **    ****      ******      *");
    System.out.println("    ************************************************************************************");
    System.out.println("");
    System.out.println("    By Emmanouil Perselis");
    System.out.println("");
    System.out.println("What would you like to do?");
    System.out.println("0.---");
    System.out.println("1.Toggle lights");
    System.out.println("2.Toggle air");
    System.out.println("3.---");
    System.out.println("4.---");

}
 }

```

ARDUINO SCETCH

```
 int led = 13;
 int led1 = 2;
 int led2 = 4;
 int led3 = 7;
 int led4 = 8;
 void setup() {
   Serial.begin(9600);
   pinMode(led, OUTPUT);
   pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led4, OUTPUT);
 }

 void loop() {
   char i= Serial.read();

   if(i=='a'){////////////////
     if(digitalRead(led)){////////////
   digitalWrite(led, LOW);  ////////////
  }else if(!digitalRead(led))//////////
   digitalWrite(led, HIGH);  //////////
 }

  if(i=='b'){////////////////
     if(digitalRead(led1)){////////////
   digitalWrite(led1, LOW);  ////////////
  }else if(!digitalRead(led1))//////////
   digitalWrite(led1, HIGH);  //////////
 }

 if(i=='c'){////////////////
     if(digitalRead(led2)){////////////
   digitalWrite(led2, LOW);  ////////////
  }else if(!digitalRead(led2))//////////
   digitalWrite(led2, HIGH);  //////////
 }

 if(i=='d'){////////////////
if(digitalRead(led3)){////////////
   digitalWrite(led3, LOW);  ////////////
  }else if(!digitalRead(led3))//////////
   digitalWrite(led3, HIGH);  //////////
 }

 if(i=='e'){////////////////
if(digitalRead(led4)){////////////
   digitalWrite(led4, LOW);  ////////////
  }else if(!digitalRead(led4))//////////
   digitalWrite(led4, HIGH);  //////////
 }
}

```

# Answer
> 1 votes
I had this problem with communication with Arduino Uno (I think that the Arduino Uno, and other boards, with this type of scheme, suffer this problem).

The DTR line on Arduino Uno is connected with RESET, including when you use the Arduino IDE Serial Monitor port, such that the parameter of DTR is false. Yeah, you can fix this with capacitor or catch place RESET EN on board. But when you set setting you can just write:

```
comport3.setParams(9600, 8, 1, SerialPort.PARITY_NONE, false, false);

```

The last parameter is DTR and its default is `true`, the second to last parameter is RTS (it defaults to `true` too). I set both of these parameters to `false` and my board reads commands from the computer without resetting.

I write this for other people who had this problem.

---
Tags: serial, java, windows
---


title: Wi-Fi module 5 GHz

text:
# Question
Title: Wi-Fi module 5 GHz
What is a Wi-Fi module for an Arduino that works on 5 GHz? The ESP8266 - doesn't support 5 GHz according to:

# Answer
I asked Microchip a while back if they planned to release a 5GHz WiFi module at any point in the near future. The answer was basically "No, there would be no benefit to it." For embedded systems there is no point in 5GHz since 2.4GHz is more than adequate and there are better long range solutions than WiFi (LoRa for instance).
> 2 votes

---
Tags: esp8266, wifi, wireless
---


title: Extracting char array out of function

text:
# Question
Title: Extracting char array out of function
I have a array called Table1 witch contains '1','2','3','4' I do not want to work with global variables I want to change the content of Table1 with a function called 'Change' that gives a return char array back in to Table1

This is the program i wrote:

```
void setup()

{
  Serial.begin(9600);
}

void loop()
{
  char tabel1[4] = {'1','2','3','4'};
  int i;
  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }

  tabel1 = Change(tabel1);

  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }
}

char Change(char tabel2)

{
  tabel2[0] = 'n';
  tabel2[1] = 'b';
  return tabel2;

}

```

This is the error i'm getting:

```
In function 'void loop()':
testArray:17: error: incompatible types in assignment of 'char' to 'char [4]'
tabel1=Change(tabel1);
^
In function 'char Change(char*)':
30:12: warning: invalid conversion from 'char*' to 'char' [-fpermissive]
return tabel2;
^
exit status 1

[Error] Exit with code=1

```

# Answer
> 1 votes
You should read something about C arrays and how they work.

Anyway, if you use:

```
  Change(tabel1);

// ...

void Change(char * tabel)
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

```

It'll change passed array because it's passed as pointer to the first element of `tabel1`.

# Answer
> 1 votes
In c an array's name is effectively a pointer to the start of the memory location where the array is stored. You have to be careful, if you pass an array to a function that function will have no knowledge of the array size. If there is a risk of the size being unknown you normally pass a second parameter, the size of the array. In this case we will assume the array passed to change is always at least 2 chars long and risk a crash if it isn't.

At the most simple level your change function becomes:

```
void Change(char tabel[])
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

```

and the line to call it is: `Change(tabel1);`

Notice how there is no return type or return value. We were passed a pointer to where the array is in memory. When we make changes to the values we are changing the original array directly. The old values are lost.

The function:

```
void Change(char *tabel)
{
  *tabel = 'n';
  *(tabel+1) = 'b';
}

```

Is functionally identical to the one above only it is explicitly using a pointer rather than an array.

One thing you need to get used to in c is that an array is not a type of variable, it's a collection of variables. As such normal variable operations don't work on them.

e.g. `array1 = array2` does not set the contents of array 1 to being the same as array2. It sets the memory address where array1 is stored to being the same as the memory address that is used for array2. The original memory used to store array1 is no longer accessible by the program and is now unusable. This is a bad thing.
Similarly `if (array1 == array2)` doesn't compare the contents of the two arrays, it compares their memory addresses.

---
Tags: array
---


title: if-else statement not working

text:
# Question
Title: if-else statement not working
So I'm facing this problem a lot in my code where the program is not getting into the `if` `else` loop properly and just returning the same answer again and again.

```
void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));
if (temp == 0.00) {
temp2 = 0.00;
} else {
  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

```

The answer keeps on coming 0 even when temp is non zero.

If anyone knows the reason please help...

# Answer
I'm assuming that temp2 must be defined as a global or you'd be getting compiler errors.
You are re-defining temp2 within the else statement, that redefined value is then only local to that else and is lost as soon as you exit it.

```
void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));

if (temp == 0.00) {
  temp2 = 0.00;
} else {

/* Bug here.                                                             */
/* this temp2 is local to these {} and is lost as soon as we reach the } */
/* at the end of the else.                                               */
/* Remove the word double and it should work                             */

  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

```

Personally I'd replace the entire if ... else with:

```
double temp = abs(tan(theta_rad)); // removed redundant casts to double

double temp2;
if (temp > 1.0) // 1/temp will be smaller if temp > 1
  temp2 = 1.0/temp;
else
  temp2 = temp;

```

It'll have exactly the same effect but avoids unnecessary floating point calculations
> 1 votes

---
Tags: arduino-uno
---


title: Measuring distance based on time

text:
# Question
Title: Measuring distance based on time
I have written a arduino sketch which is used to measure the distance travelled. Since `distance = speed * time` , I have initiated speed = 6. I have initiated `time = millis()` variable and it calculates the time in millis().

So, `distance` is calculated as `(speed*time) /1000` and we get distance for every second.

Now, as soon as the `distance==20`, I want to print `distance` and then delay for 5 seconds. So, as soon as `distance==20` implies `time = 4000` . If I delay for 5 seconds, time becomes 9000. But I want time to start from 4000 itself. So I have initiated another variable called `curTime = time - prevTime`.At the start, `prevTime = 0`. Code:

```
int prevTime = 0;
void loop(){
  unsigned long time = millis();
  unsigned long curTime = time - prevTime;
  int speed = 6;
  unsigned long distance = (speed * curTime)/1000;
  Serial.println(distance); // displays values of distance
  if(distance == 20){
    Serial.println(distance);
    delay(5000);
    prevTime = time;
  }
}

```

So `prevTime = 4000` if distance == 20. After this, time will be equal to 9000 and curTime will be 9000-4000 which equal 5000. So the distance will be 30 skipping all the values between 20 and 30. I don't want the distance to skip the values between 20 and 30. I have tried a lot but couldn't achieve it. Please help me fix this.

Thanks.

Link for code:

https://circuits.io/circuits/5260912-the-unnamed-circuit/edit

# Answer
> 0 votes
When `distance == 20` you pause for 5 secs. So all calculations after that will be off by 5 secs. So, `prevTime` should equal 5000.

```
unsigned long time = millis();
unsigned long curTime = time - prevTime;    // 0 or 5000
int speed = 6;
unsigned long distance = (speed * curTime) / 1000; // calculating distance in meters for every milli second
Serial.println(distance);
// Only pause once
if (distance == 20 && prevTime == 0) {
  delay(5000);
  prevTime = 5000;  // Adjust for the delay
}

```

---
Tags: arduino-uno, programming, arduino-ide, time, millis
---


# Question
Title: Some questions about a RGB LED Strip project that Im planning to do
Good day all

So Im in the planning and research phase of a new project that I want to start for my car. I want to control a bunch of RGB LED strips independently from each other via a micro controller, preferably Arduino of courese, with a breakout board or something. I am going to run this system off the car battery so the current shouldn't be an issue, I hope, but prolonged usage will most likely drain the battery quite quickly. The strips I want to control are of the following lengths:

* 6 x 30cm Pieces
* 3 x 2m Pieces

So I want to be able to control all of them individually as well as the colour and brightness individually. So here are my questions:

Is there a board that the arduino can talk to that has 27 PWM outputs? Can one maybe use normal outputs and just HIGH Low them quickly in sequence and use an arduino MEGA? What would the current draw be if all the colours are on full on all strips? Would it rather be better to blink them in sequence,rather than full on, and lose some brightness to reduce current draw? Could multiplexing here be an alternative to controlling them individually? Maybe get it so I switch all the Positive outs of the LEDs, and the connect the 3 colours together. So in that case I would have 3 + 9 outputs? Would addressable LEDs actually work better?

If you could refer to me to similar projects so I can sniff around there that would be greatly appreciated. So far Im just trying to wrap my head around all the aspects of the project. And yes I know that I wil not be able to use this while Im on public roads, its just for show.... So not sure what the legal aspects there are... :P

# Answer
> 1 votes
You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLed library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".

---
Tags: led, pwm
---


# Question
Title: Global variables with C++ in multiple files
I'm not a C++ programmer (but I have used regular C code for implementing low-level machine language equivalent SW for some time), and after trying to modify an existing cC+ program to do what I need (and failing), I've decided to rewrite parts of the code in plain C code.

But to be able to use the data, I need to create some variables that have to be accessible to parts of the existing C++ code.

When I declare a global variable (`extern int variable name;`) outside the main program, the compile fails because the references to the global variable aren't within the scope of the cpp parts of the program.

I don't program with multiple files myself, so I was wondering if I need to globally declare the same variables as part of each cpp program that needs to have access to the variables? Is there a another/better way?

# Answer
When using multiple source files you need to use header files to share things between them.

myproject.h:

```
#ifndef __myproject_h__
#define __myproject_h__
extern int aGlobalVariable;
#endif

```

myNewCode.c

```
#include "myproject.h"
int aGlobalVariable;

```

modifiedOldCode.cpp

```
#include "myproject.h"

```

This way the header file defines the variable as an extern in all of your c / cpp files so that it is visible to all of them but the variable is only actually declared and memory allocated for it in one place, in the .c file.
Similarly any functions that you want to be visible in both files should be declared in the headerfile (e.g. `void myfunction(int x);`) but the actual definitions should be somewhere in the .c or .cpp files.
The #ifndef and #define lines in the header as there so that if the header somehow gets included twice you don't get lots of redefinition errors.

There is nothing strange about c++ and globals, a global defined this way is global to everything, it doesn't matter what object you're in or how things are scoped. This can however have some strange effects since there is only ever one copy of a global while you can possibly have multiple instances of the c++ class that uses it. This can cause some consistency related issues if you aren't careful. Whether you need to worry about this or not depends very much on the nature of the code.
> 5 votes

---
Tags: arduino-uno, programming, c
---


# Question
Title: How can I use the NRF24L01 modules without a library?
The datasheet is too intimidating for me, and I dont want to use the libraries available. Hence, I am looking for some clarity on this matter.

# Answer
You can use the NRF24L01 by writing the functionality that is currently within a library yourself (and strip of parts you do not use).

However, for this, you need to understand the library, and therefore high likely the datasheet too.

You also can start without looking at a library, but your only documentation source is the datasheet itself.

A NRF24L01 has a lot of possibilities (that is why the datasheet is so extensive), so writing the functionality yourself might be causing more time.
> 2 votes

---
Tags: spi, nrf24l01+
---


title: Rounding up and Down

text:
# Question
Title: Rounding up and Down
My arduino is meisuring the tempature and gives values like: 28.58 Degrees Celcius. I would like to round this up to one decimal. I could make the variable one shorter by cutting the "8" off which would desplay 28.5. Yet this feels a bit like cheating as it mathimatical not correct. Does anyone know how to round up/down. Which would show my tempature as 28.6.

Extra advice needed. I am sending the tempature by Serial to my RPi which has a python code running. Would you suggest doing the rounding in the Arduino code or in The Python code.

Thanks in Advance!

# Answer
> 4 votes
As far as I know, the Serial.print (or println) does rounding up and down. All you have to do is take a float variable and do `Serial.print( value, 1);`

Without extra parameter, the default is choosen, which is 2 decimal digits: `Serial.print( value, 2);`

Why do you want to shorten the bytes over the Serial ? You can just as well send two decimal digits and process the value in Python.

# Answer
> 4 votes
You can round in C by multiplying for the significance, adding +0.5, round down (equals as casting to an integer) and divide.

```
float f_rounded = ((int) (f * 10.0 + 0.5) / 10.0);

```

28.6 will be:

```
float f_rounded = ((int) (28.6 * 10.0 + 0.5) / 10.0)
                = ((int) 286.5) / 10.0 = 286 / 10.0 = 28.6

```

In Python it is equal (except the cast operator is int(...)

Update: for negative numbers +0.5 should be -0.5

Credits for Edgar Bonet: using round works for both positive and negative numbers:

```
float f_rounded = round(f * 10) / 10.0;

```

---
Tags: arduino-uno, raspberrypi, mathematics
---


title: send sketch to arduino via wifi

text:
# Question
Title: send sketch to arduino via wifi
I'm pretty new to arduino and need some help.

My task is to connect my UNO R3 to wifi AND then send data (sketch for blinking led) to it. I successfully connected my arduino with my wifi, but how do I send the sketch?

I didn't find a tutorial for this. Do you know a good one or can you help me, please?

# Answer
> 1 votes
There is a difference between communicating via WIFI while a sketch is running or to send the sketch itself ... for the latter, I don't think there is an easy solution; you probably have to write your own AVR programmer, receiving the sketch via WIFI and store it on the Flash memory.

# Answer
> 1 votes
You can't with a normal Arduino and WiFi shield.

However it is possible (if you are cunning) to do it with the ESP8266.

The basic idea is that you program an ESP8266 module to act like a transparent TCP/IP to UART bridge. Connect it to the TX and RX pins of the Arduino, listen on a port number of your choice, then when you connect to it (with telnet, netcat, socat, etc) all data is forwarded directly back and forth to the UART interface. If you monitor the connection state as well and use that to drive an equivalent of the DTR pin you can reset the Arduino automatically when you connect.

There is an example in the ESP8266 core that does it all apart from the connection monitoring, which is easy enough to add.

Then it's just a case of getting your computer to connect a virtual serial port with the remote socket on the ESP8266 and you have OTA programming for your choice of target board.

On Linux you can use `socat` for that:

```
root@foo:~# while `true`; do echo "ready"; socat pty,link=/dev/ttyACM99,raw,wait-slave,user=youruser,group=dialout tcp:192.168.0.16:24; done

```

(yes, you have to run it as root).

Quite how you'd go about that on other operating systems I don't know. I think socat is available on OS X. Windows is anyone's guess though.

---
Tags: wifi, sketch
---


# Question
Title: Sending JSON message to web api via post. Why does HTTP 1.0 versus 1.1 make a difference?
I am sending a message to a web api call every xx seconds. I could not get it to work at all until I changed the header from HTTP 1.1 which is what I was using to HTTP 1.0. Then, it started working. Why would this affect things where I could not post and now I can?

This is what it was when it wasn't working:

```
client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.1");

```

And the change that fixed it:

```
client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.0");

```

Thanks!

# Answer
HTTP/1.1 requires you to provide the host name of the server. And it will keep the connection open for some time unless you explicitly opt out of this. Thus, the equivalent of the basic HTTP/1.0 request in HTTP/1.1 language is

```
POST /the_uri HTTP/1.1
Host: foo.example.com
Connection: close

```
> 1 votes

---
Tags: programming, tcpip, web-service, json
---


# Question
Title: Problem on multiple interrupts operation on Arduino Uno
I experimenting with the interrupt ISR using Arduino Uno. In my circuit, I am taking two switches which are connected with Uno's interrupt pins, pins 2 and 3, and also taking multiple LEDs which are connected with other pins.

My logic is when I press switch1 (which is connected to pin 3) LEDs should be turned on by the interrupt service routine and when I press switch2 (which is connected to pin 2) LEDs should be turned off by the interrupt service routine.

My problem is that when I pressed switch1 LEDs are turned on but when I pressed switch2 LEDs are not turned off.

Here's my code:

```
int switch1 = 3;
int switch2 = 2;
int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
int led6 = 8;
int led7 = 7;
volatile bool flag1 = false;
volatile bool flag2 = false;
//volatile byte state = LOW;

void setup()
{
  pinMode(switch1, INPUT_PULLUP);
  pinMode(switch2, INPUT_PULLUP);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(switch1), &setFlag1, CHANGE);
  attachInterrupt(digitalPinToInterrupt(switch2), &setFlag2, CHANGE);
}

void loop()
{
  if (flag1)
  {
    off();
  }
  if (flag2)
  {
    blink1();
  }

}

void blink1()
{
  attachInterrupt(digitalPinToInterrupt(switch2), setFlag2, CHANGE);
  digitalWrite(led1, HIGH);
  blink2();
}

void blink2()
{
  digitalWrite(led2, HIGH);
  blink3();
}

void blink3()
{
  digitalWrite(led3, HIGH);
  blink4();
}

void blink4()
{
  digitalWrite(led4, HIGH);
  blink5();
}

void blink5()
{
  while (1)
  {
    digitalWrite(led5, HIGH);
    delay(10);
    digitalWrite(led5, LOW);
    delay(10);
  }
}

void off()
{
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  attachInterrupt(digitalPinToInterrupt(switch1), setFlag1, CHANGE);
}

void setFlag1()
{
  detachInterrupt(digitalPinToInterrupt(switch1));
  flag1 = true;
}

void setFlag2()
{
  detachInterrupt(digitalPinToInterrupt(switch2));
  flag2 = true;
}

```

# Answer
> 2 votes
You are being way way too convoluted with this. You're overthinking it.

The code should be as simple as (LED stuff omitted):

```
volatile bool running = false;
const uint8_t switch1 =3;
const uint8_t switch2 =2;

void setup() {
    pinMode(switch1, INPUT_PULLUP);
    pinMode(switch2, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(switch1), turnOn, FALLING);
    attachInterrupt(digitalPinToInterrupt(switch2), turnOff, FALLING);
}

void loop() {
    if (running) {
        // Do something
    } else {
        // Do something else
    }
}

void turnOn() {
    running = true;
}

void turnOff() {
    running = false;
}

```

Note that what goes in `loop()` should be *non-blocking*, or at least have a reasonably short duration, so that it is able to pick up the changed `running` variable.

However, for something like this, interrupts are pretty pointless.

---
Tags: arduino-uno, interrupt, isr
---


# Question
Title: What is the meaning of the preceding character on several library defines?
I have been reviewing the code for several libraries,mostly by SparkFun, and looking at the defines for for instance the chip select pins for their hardware.

In the defines, rather than being a simple number or string, they have the following syntax:

```
#define P_MOSI  B,3

```

with others being preceded by a `D` instead.

I am surmising this may be a data type definition, but I don't recognise the syntax and am wondering

1. What does the syntax mean?
2. What is the effect of nominating the data type of a define?
3. Is this Arduino specific syntax or general to C/C++?
4. If I want to modify a value, is it as simple as changing the value after the comma?

# Answer
I looked into one of these libraries, namely the SparkFun CAN-Bus Arduino Library. The macro appears to be used inside other macros that require two arguments, for example `RESET(P_MOSI);`. Given the following definitions from the library:

```
#define RESET(x) _XRS(x)
#define _XRS(x,y) PORT(x) &= ~(1<<y)
#define PORT(x) _port2(x)
#define _port2(x) PORT ## x
#define P_MOSI B,3

```

the call `RESET(P_MOSI);` expands to

```
PORTB &= ~(1<<3);

```

`PORTB` is the name of an IO port of the MCU which controls the outputs of the pins. It is actually a macro from avr-libc that expands to something like:

```
(*(volatile uint8_t *)(0x05 + 0x20))

```

where `0x05` is the IO port number of the register (the number depends on the particular AVR chip) and `0x20` is an offset needed to get the memory-mapped address from the IO port number. When the compiler does constant folding, `RESET(P_MOSI);` resolves to

```
*(volatile uint8_t *)0x25 = 8;

```

which is then compiled into

```
cbi 0x05, 3

```

a single assembly instruction (Clear Bit in Io port) that executes in two CPU cycles and sets to zero the bit 3 of IO port 0x05.

The same end result could be achieved in a much simpler way:

```
#define P_MOSI 11  // assuming digital 11 = PB3, as in the Uno
#define RESET(x) digitalWrite(x, LOW)

```

However, the function `digitalWrite()` is very slow, mostly because it has to map an Arduino pin number to a port address and a bit number, and it does it at *run time*. The SparkFun approach, though somewhat convoluted, is *way* more efficient, because the mappings are performed at *compile time*.
> 2 votes

# Answer
```
#define P_MOSI  B,3

```

This is a C style macro definition. During the pre-processor phase of compilation where ever the text `P_MOSI` is encountered it will be replaced with the text `B,3`.

This is a purely textual replacement with no understanding of the semantic meaning of what is being replaced. So the validity of the macro will depend on where it is being used.

I am not familiar with how this macro is being used in the library code you are looking at, but from what I have seen from a quick google this macro is used to define things on a per-chip architecture basis. EG for an ATmega16 it is

```
#define P_MOSI  B,5

```

But for a AT90USB82 it is

```
#define P_MOSI  B,2

```

So if you are trying to adapt a library to your processor you will need to change the macro to suit your architecture.

In general such defines are used to adapt the same code across multiple architectures. For instance here is a snippet of something I found when googling

```
#if (BUILD_FOR_MCP2515 == 1)
    #if defined(__AVR_ATmega16__) || defined(__AVR_ATmega32__) || defined(__AVR_ATmega644__)
        #define P_MOSI  B,5
        #define P_MISO  B,6
        #define P_SCK   B,7
        #define SUPPORT_FOR_MCP2515__
    #elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__)
        #define P_MOSI  B,2
        #define P_MISO  B,3
        #define P_SCK   B,1
        #define SUPPORT_FOR_MCP2515__

```
> 1 votes

# Answer
While we can't see how the macro is being used, it may be worth noting that, on Uno's built-in SPI interface, the MOSI signal is on port-B, bit 3.

Update:

> the architecture is broken down into ports and pins.

The AVR processors use memory-mapped, byte-wide I/O ports, where each bit mapped to a physical pin (actually to a multi-function pin-driver/receiver). The Arduino programming environment defines symbols such as `PORTB` to be the addresses of those ports. It further defines single-pin I/O functions (`digitalRead()`, `digitalWrite()` ) that "know" the mapping of pin numbers to ports and bits as implemented in each processor. Most people rely on the single-pin functions but the ability read and write the ports directly is there if you need it. And note that the Arduino pin numbers *do not match* the physical pin numbers of the pins at the exterior of the chip, but it does match the numbers silk-screened on the PCB. While this relieves you from having to deal with that mapping, it makes those low level details somewhat less visible.
> 1 votes

---
Tags: library
---


title: Partially clean a LCDScreen

text:
# Question
Title: Partially clean a LCDScreen
I have connected an 16x2 LCD to my Arduino. It shows my Room Temperature and Behind that variable is the string "Celcius". Everytime the temp is diffrent than shown on the screen it updates the screen by clearing the screen. Is there a way I could clear just a part of the screen? or is this technically impossible. Or is it a waste of code? :D

Thanks in Advance!

Anton

# Answer
> 2 votes
The easiest is to clear the entire screen (I'm sure there is a function for that).

What you also can do:

* Create lines which are 16 characters wide and print them, so the old text is overwritten
* More complicated: store the text that is written in two strings (one per line) and check where are not spaces, to overwrite it with spaces to clear.

You would have to do a performance/time check to see what works best.

If performance is not an issue (which I doubt), keep it simple and just overwrite the two lines (without a clear, assuming you call the clear function yourself).

Another solution is to keep the word Celcius always on the same location... this means you might have to change formatting:

* \_28.6 Celcius
* \__3.8 Celcius
* \_-12.3 Celcius

Where _ are spaces (so the word Celcius is always on the same location)

# Answer
> 1 votes
There is only a function to clear the entire LCD display, and that is in most cases visible.

Clearing only a few characters is done by writing spaces to it. After that you can write the new temperature to that part of the display.

You could also create a fixed length format of the temperature and use spaces to fill the unused characters. Then you can use just one write to the display.

It begins by designing the layout of the text on the display. Then you know where everything will be and how many characters are needed for each value.

@MichelKeijzers, I'm aware that my answer is almost the same as yours, but your answer seems to be for clearing an entire line. I would write the word "Celsius" or "°C" to the screen just once, and only update the value of the temperature.

---
Tags: arduino-uno, lcd, adafruit
---


# Question
Title: Is there any way to use the serial port as an interruption source?
I have an sketch made for reading a temp/hum sensor once every ten seconds aprox. However, I want to introduce an interruption source to send from my keyboard a magic word to make the sensor be read exactly at that instant.

By checking out the reference on attachInterrupt(), I found only the ways to declare interruption pins, but nothing related to serial. What you can say about it?

Thanks in advance.

# Answer
> 3 votes
Use `millis()` for the timing of the temperature reading, then you can read from the serial in between time and won't need to use any interrupts.

```
unsigned long last_measure = 0;

const byte buffer_size = 16;
char buffer[buffer_size] = "";
byte buffer_i = 0;

// setup() and other stuff

void loop() {
    if (millis() - last_measure > 10000) { // read the temperature like in the "blink without delay" example
        last_measure = millis();
        int value = readSensor();
        Serial.println(value);
    }
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') { // end of line, which means we got the whole string
            if (strcmp(buffer, "magic") == 0) { // compare if it matches the magic word
                int value = readSensor(); // read and print the temperature
                Serial.println(value);
            }
            buffer_i = 0; // reset the index
            buffer[buffer_i] = 0;
        }
        else if (buffer_i < buffer_size-1) { // if the buffer is not full
            buffer[buffer_i++] = c; // add char to buffer
            buffer[buffer_i] = 0; // and null terminate the string
        }
    }
}

```

# Answer
> 1 votes
Thank you all, guys. I considered your ideas, and then I code this solution. It works fine, right now I'm reading my sensor once every 30 minutes (1,800,000 miliseconds) and whenever I send the magic word. I hope it is useful to you:

```
void loop(){
if ((millis() - timer < 1800000) && (Serial.available() > 0)){
    magicInput = Serial.readString();
    magicInput.trim(); //Cleans input from \n at the end, otherwise never equals magicInput
    if (magicInput.equals(magicWord)){     //Elegant form for "=="
      Serial.println();
      Serial.println("  === Your request ==="); //Shows requested measurement
      Serial.println(millis() - timer); //Time since last measurement
      measure(); //
    }
  }

  if (millis() - timer >= 1800000){
    Serial.println();
    Serial.println("===== Normal mode =====");  //Indicates that measurement was not requested by user
    Serial.println(millis() - timer); //Checks that 30 "exact" minutes have run
    mide();
    timer = millis();
  }
}

```

# Answer
> 0 votes
Here is a logic snippet you can use:

```
unsigned long timer = 0;

void loop(){
  readSensors();
  while(millis() - timer < 10000){
    if(stringFromSerial == magicWord){
      readSensors();
    }
  }
}

```

---
Tags: serial, interrupt, arduino-micro
---


title: What does Arduino do in 15ms?

text:
# Question
Title: What does Arduino do in 15ms?
I was wondering why there is a 15 ms delay between each iteration of a the main loop.

**Code**: The following code shows the execution time expressed in microsec between each loop

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

void loop()
{
  Serial.println();
  Serial.print("Start: ");
  Serial.print(micros());
  Serial.print("/////////////////////");
  Serial.print("End:");
  Serial.print(micros());
}

```

**Output**:

```
Start: 789452/////////////////////End:821692
Start: 837292/////////////////////End:869532
Start: 885132/////////////////////End:917372
Start: 932972/////////////////////End:965212

```

Arduino needs 32,240 msec to print the messages to serial and to call the micros() function twice. And this it's fine. Now, considering the difference between the values of the End and the following Start, one question arises:

What does Arduino do between each loop?

# Answer
Your serial connection is set to 9600 baud, which is 9600 *actual data* bits per second. The communication consists *(\*)* of 8 bit characters and every bit is useful data (no parity), so you would be able to achieve at most 9600 / 8 = 1200 characters per second.

You have a message of 46 characters including the line break, which brings you to 1200 / 46 = 26 iterations per second.

1000 milliseconds / 26 iterations = about 39 milliseconds per iterations.

This is the theoretic maximum you would get if you would send the data over serial without any other overhead. Pretty close to the 32 + 15 = 47 milliseconds you measured.

Since you print a part of the message (Enter + 'Start:') between the end of the previous iteration and the start of the next (if you take the call to `micros()` as the start and end), it makes sense that a part of the time is in between there as well.

So the actual overhead you are looking at is about 8ms per iteration. This delay is spread out over the loop and the call overhead of the various functions you use. After all, when you call Serial.print, a *lot* of work needs to be done before the data can actually be sent to the serial port. You would probably gain more speed/less overhead if you would construct one big string, and send it with a single print command.

Arduino itself is slow, but still much faster than this. It should be able to do a big(ger) number of iterations per second, but you basically limited it by initialising the serial connection to such a slow speed. You can partially eliminate this by picking a higher number. I think both your Arduino and any modern serial port should be able to handle 115200 baud. Nevertheless, you will always have a relatively big overhead when you are sending data over serial. Use your bandwidth wisely, and reduce the number of calls to Serial.print as much as you reasonably can.

* *) 8 bit, no parity is the de facto default. See Serial.begin() for more information about initializing the serial connection.*
> 7 votes

# Answer
Just check the sourcecode

```
for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

```

So it does a check if serialEventRun is True, and then a jump back to the beginning of the for-loop. And then a call to `loop`.

Also note that Serial.print is blocking if the TX-buffer is full. So you might want to add a delay somewhere to ensure the buffer is never full.
> 5 votes

# Answer
Your code is slightly off if you want to accurately time this

```
Serial.print("End:");
Serial.print(micros());

```

Will get micros() before printing to serial, and then take the time to print it. You also print some text before taking the time at the top of the loop. Your 15 ms is the time to print these to serial between reading micros. For example, change the loop code to something like this:

```
uint32_t time, endTime;
...
void loop(){
    time = micros();

    Serial.print(endTime);
    Serial.print('\t');
    Serial.print(time);
    Serial.print('\n');

    endTime = micros();
}

```

and you should only see a small difference. It showed a 4 microsecond difference when I ran it. The only other thing that runs outside the loop is the serial event handlers, but if you don't use one it obviously doesn't take long.
> 4 votes

# Answer
**TL;DR**: The delays you measure (32.24 ms between `Start` and `End`, and 15.6 ms between `End` and `Start`) are **exactly** what is expected from the amount of data you send through the serial port. Yes, exactly: there is *zero overhead* from the CPU doing other things.

Let me show how the expected timings can be computed. First, a note about the exact baud rate. A rate of 9600 bps implies that each bit takes about 104.17 µs to send. However, the Arduino being clocked at 16 MHz, it cannot achieve this exact baud rate. Instead, when you request 9600 bps, you get the closest value it can achieve, which is about 9615 bps. Then, each bit takes *exactly* 104 µs. Or at least “exactly” as per the Arduino clock: it really takes 1664 CPU cycles.

Then, as already noted in previous answers, one character is worth 10 *raw* bits. It thus needs 1040 µs to be transmitted.

Now, let's look at your code. It should be noted that

```
Serial.print(micros());

```

is compiled into something equivalent to

```
unsigned long timestamp = micros();
Serial.print(timestamp);

```

i.e. the timestamp is taken and *then* it is transmitted. Your `loop()` is then equivalent to:

```
void loop()
{
    Serial.println();                       //  2 chars: CR and LF
    Serial.print("Start: ");                //  7 chars
    unsigned long time_start = micros();
    Serial.print(time_start);               //  6 chars
    Serial.print("/////////////////////");  // 21 chars
    Serial.print("End:");                   //  4 chars
    unsigned long time_end = micros();
    Serial.print(time_end);                 //  6 chars
}

```

By folding the last `Serial.print()` of one iteration into the beginning of the next one, one gets the pseudo-code:

```
forever {
    print 15 chars;  // 15*1040 = 15600 µs
    read time_start;
    print 31 chars;  // 31*1040 = 32240 µs
    read time_end;
}

```

The computed durations match *exactly* your printout. This shows that, once the `Serial` output buffer is full, the timing of your code execution is completely governed by how fast the UART sends the bits out the line. The time taken by the Arduino to do actual CPU work (calling `micros()`, formatting numbers...) is irrelevant because the CPU works *in parallel* with the UART and, being faster, it ends up waiting for the UART anyway.
> 2 votes

# Answer
At 9600now each data byte needs 10 bits to be transmit. Or 1ms per byte.

20 bytes will take 20me to transmit.

However, the existence of a buffer and the way the transmission is carried out can greatly impact the duration of execution of your code - actual time for transmission is invariant however.

If your transmission is done via the interrupt, the execution can be almost instantaneous.
> 0 votes

---
Tags: arduino-uno, serial, arduino-mega
---


# Question
Title: If any kind of character gets loaded into a string, what do I use for an end-of-line character?
I have an Arduino project that is converting floats to characters and then transferring those characters via the serial to a Python program. This is a portion of the Arduino code:

```
#define MEM_LEN (16 * 4 * 4) + 1
uint8_t dataBuf[MEM_LEN];

typedef union {
  float f;
  uint8_t b[4];
} cvt_t;

cvt_t cvt1;

// set up sensor stuff
MLX90621 sensor;
 .
 .
 .

void loop() {
    sensor.measure(); //get new readings from the sensor
    count = 0;
    for(uint8_t y=0;y<4;y++){ //go through all the rows
      for(uint8_t x=0;x<16;x++){ //go through all the columns
        cvt1.f = sensor.getTemperature(y+x*4); // data at position x/y
        dataBuf[count + 0] = cvt1.b[0];
        dataBuf[count + 1] = cvt1.b[1];
        dataBuf[count + 2] = cvt1.b[2];
        dataBuf[count + 3] = cvt1.b[3];
        count += 4;
      }
    }
    dataBuf[MEM_LEN - 1] = '\n'; // not a good delimeter
    Serial.write(dataBuf, MEM_LEN);
}

```

The problem is that float conversion loads any and all characters into dataBuf, so I don't have a good delimiter or "end-of-line". When the Python program ingests the incoming string, there's nothing to use to know it's received a complete frame. I don't want the Python to just count characters to know when it's received a frame. No good delimiter - what should I do?

# Answer
> 1 votes
Generally the method to ensure binary data is correctly decoded is to have some form of header and then a checksum. While the header may appear in the data the chances of the correct checksum also being randomly in the data at the correct point is fairly slim. The longer the header and checksum the lower the probability of invalid data somehow getting accepted.
The header could be as simple as a 1 or 2 byte fixed pattern or could be a fixed pattern followed by a message ID and a length.
The checksum is normally 16 bits, that means that if the system got out of sync somehow and then header happened to appear in the data before the next real header the invalid data has a 1 in 65,000 chance of being accepted.
Exact probabilities of invalid data being accepted depend upon the packet lengths but assuming random data then for a 16 bit header with a 16 bit checksum and 32 bits of data it's in the region of a 1 in 4 billion chance of allowing incorrect data in. A 32 bit header + 16 bit checksum increases that something like 1 in 100 trillion. At that point you've got more chance of winning every lottery in the world while being simultaneously struck by lightning and a meteor.
Data is rarely truly random, if you can use a header that is less likely to appear in the data then you can improve things further.

Since you only have 4 bytes of data I'll assuming you want to keep things simple and don't want to add a dozen bytes of overhead to each value. A header of 0xff is a good bet, if that was the first byte of a float the value will be in the -10E38 region. If you use a two byte header the 0xffc0 is a good choice, that would be NaN, an invalid floating point value. Since this means the first two bytes of your data aren't going to match the header this greatly reduces the chance of the header appearing in the data. Your checksum could then be a simple xor of the next for bytes. So your data packet ends up being:
`0x ff c0 <d1> <d2> <d3> <d4> <d1^d2^d3^d4>`

One other alternative approach is through the use of escape codes/characters. This is a special value that never appears on it's own in the data. For example let's define our escape character as being 0xFF and the header value as being 0xC0 C0.
In that situation 0xC0 C0 is always the start of a data packet.
If 0xC0 happens to appear in the data we insert the escape character in front of it. Similarly if the escape character happens to appear in the data we insert an extra escape character in front of it.
e.g. for a data value of `0x11 0xC0 22 FF` we would send `0xC0 C0 11 FF C0 22 FF FF` or `<header> <d1> <escape> <d2> <d3> <escape> <d4>`
For hopefully obvious reasons whenever possible the header and escape characters should be values that rarely occur in the data.

This approach has the advantage that if designed correctly there is no risk no matter how small of invalid data getting through and (on average) it has a lower overhead in terms of bytes sent, most of the time all you need to add is the 2 byte header. The down side is that inserting and removing the escape characters can get complex and messages are no longer a fixed size, the length depends on the data content. This indeterminacy in message length can potentially cause problems depending upon the application.

To be honest for a single floating point number text may be easier. Binary is more efficient, it's less CPU load and less data to send, but for something as short as a single number the savings aren't normally worth the extra complexity.

# Answer
> 0 votes
Using a version of Pascal strings could work: the first byte of the buffer is the number of characters, the rest of the sequence the bytes.

Or convert the numbers to ASCII strings. Inefficient but you'll have your `'\0'` delimiter.

# Answer
> 0 votes
Framing binary messages is not as simple as choosing a delimiter. Counting the characters could be an option, but you need some way to check that your reception has not gotten out of sync. You could for example send messages that looks like:

```
struct Message {
    uint32_t magic;
    uint8_t data[MEM_LEN];
    uint16_t crc;
};

```

Where `magic` in a magic number, i.e. a random but fixed value that is very unlikely to happen by accident, and you end the message with a CRC. On the Python side, you check that both the magic number and the CRC are OK. If they are not, you have a communication error, but you can re-synchronize by looking for the next occurrence of the magic number.

Another option is to choose both a delimiter (say, ASCII 10 = LF = `'\n'`) and an escape character (say, ASCII 92 = backslash = `'\\'`). On the sending side, you prefix by the escape character every accidental occurrence of either the escape character or the delimiter:

```
void send_byte(uint8_t c)
{
    if (c == '\\' || c == '\n')
        Serial.write('\\');  // prefix by escape character
    Serial.write(c);
}

```

and on the Python side you do the reverse operation. The only issue with this approach is that your messages are not constant size anymore.

---
Tags: serial-data
---


# Question
Title: Sampling/transmission limits for USB and Arduino UNO R3
I'm very new at this and I need some help. This is a college project that I must do and not even the professor knows for certain if it is possible.

I have to sample two signals at a fixed sampling rate so there is no aliasing effect and it must be done at the same time (switching the ADC from one analog input to another)..

The signal would be then transmitted via USB to my computer. I guess that the transmission rate would be too slow to do this in real time. I will have to store this somewhere in the Arduino board so it can be transmitted afterwards.

Requirements:

* It could be done with 8 bit resolution.
* Sampling rate of at least 4.8kHz.
* Record both signals for at least 0.1 second.

Is this even possible to do with my Arduino UNO R3? If it isn't, it would be with a sampling rate of 1.2kHz?

PS: I could try to lower the sampling frequency necessary by changing the aliasing filter that I built. The theoretical limit would be at about 1.2kHz for the best filter possible.

# Answer
> 1 votes
It is not possible to sample two signals at the exact same time with an Arduino Uno. The Arduino has only one ADC, so you have to sample one signal, switch channels, sample the other, switch channels again, etc. If this is acceptable for your project, then yes, it is perfectly feasible with an Arduino Uno. But you will have to dig into the datasheet and program the ATmega328P low-level.

Regarding the sampling rate, you want the ADC to take 9600 samples per second (4.8 kS/s × 2 channels). This means one sample every 104 µs. You are lucky: in the default Arduino configuration, the ADC conversions take exactly 104 µs. frarugi87 and Jot suggest you reconfigure the ADC for faster sampling. *This is useless*: the default sampling speed is already optimal for you application. Leave it as is.

You also require a *fixed sampling rate*. This is *not possible* to do with software. Configuring the ADC in *auto trigger mode* is the only way to get a really steady rate. The ADC can be triggered by a timer, but in your particular case, it is just simpler to have it trigger itself. This is called *free running mode* and it gives a sampling rate of exactly one sample every 104 µs. Perfect for your application.

Jot also suggests disabling interrupts. *Do not do that!* Interrupts are harmless because the ADC manages its own timing. And they are actually useful: I would use the ADC interrupt to retrieve the conversion result, send it through the serial port and switch channels in the multiplexer.

If you are happy with 8-bit resolution, I recommend you enable the *left adjust result* mode. This way you can retrieve the 8-bit result from the ADCH register and you won't need to do bit shifts.

> I guess that the transmission rate would be too slow to do this in real time. I will have to store this somewhere in the Arduino board so it can be transmitted afterwards.

Both options are possible. If you send the data in binary, you will need a baud rate of at least 9600 bytes/s × 10 bits/byte = 96 kb/s. You can opt for 115.2 kb/s, which is standard and widely supported. If you want to store the data, then you will need 9600 bytes/s × 0.1 s = 960 bytes, or about half the Arduino RAM. This is fine, as the program can be quite simple, so it won't need more than half the available RAM.

Just to give you some inspiration, I suggest you take a look at this sound-meter sketch of mine. It configures the ADC in free-running mode at 9.6 kS/s and retrieves the result using the ADC interrupt. I would use the same ADC configuration for your project, only with left-adjust and with channel switching performed by the interrupt handler.

---

**Edit**: I just wrote a “dual channel oscilloscope” program along the lines of this answer: dual-scope.c. It's written in plain C, but it can also be compiled as a regular .ino file. I only tested it with constant voltage inputs though.

The program ended up being tiny: it uses about 1% of the flash, 1.4% of the RAM and 3.4% of the CPU power on an Arduino Uno. Meaning you could add stuff to it if you feel so inclined.

# Answer
> 0 votes
The Arduino Uno uses a slow 8-bit microcontroller ATmega328P. The Due, Zero, M0 boards use a faster processor.

However, the ATmega328P microcontroller has many option for sampling analog data. It can easily do what you want. It's all in the datasheet.

The Arduino functions are often slow. For example the analogRead uses 112µs. For two channels you might get near the 4kHz with some luck.

I suggest to write a sketch that reads two channels and stores the data, and see how fast it will be. Note that the Timer0 interrupt will happen during that time. Arduino uses Timer0 for millis. You could disable the interrupts with noInterrupts.
After that, try the prescaler option as mentioned by @frurigi87. It seems to be an easy way to get a higher sample rate.
The next option is to write your own code and use the registers directly. There is code to make a simple oscilloscope with a high sample rate that you can use as an example. For example at avrfreaks.net, click on "projects" and search for "oscilloscope".

---
Tags: arduino-uno, usb, analog-sampling
---


# Question
Title: Running a function in the background continuously
I have a keypad which is connected to arduino (with one analog pin).In the arduino code, I have created a circular queue which stores the inputs by pressing on keypad. Now when a key is pressed on keypad, it is stored as the first element in the queue. If an another key is pressed, it is stored as second element in the queue until is queue is full.(The keypad pins are connected using a voltage divider for each pin, so each and every key pressed on keypad will be recognized by arduino based on voltage for the key. The keys and voltages are stored in an array, as follows):

```
int keyboardPin = 0;    // analog pin to which keypad is connected
int keyboardValue = 0;  // Initial reading of analog pin 0 (A0) (it is zero as no key is pressed initially)
char keypad[16] = {'1','2','3','4','5','6','7','8','9'};
int treshold[16] = {590,568,548,426,415,404,334,326,320}; // Volatge values corresponding to each pin
int front=0,rear=0,size=6; // implementing circular queue using array
char cQueue[6];
int speed = 6,timer=0;
void setup(){
  cQueue[0] = '1'; // the first element of queue is '1' by default at the start
}
void loop(){
  keyboardValue = analogRead(keyboardPin); // Reading the value from A0 when key is pressed
  while(keyboardValue > 5) {  // Runs when a key is pressed
    for(int i=0;i<8;i++){
      if((treshold[i] - keyboardValue) == 0){
        Serial.println(keypad[i]); // Printing the key pressed
        enQueue(keypad[i]); // Storing the key pressed in the queue
        break;
      }
    break;
    } // end of for
  keyboardValue = 0;
  liftStops(cQueue[front+1]);// function to be run in background (front + 1) because  the key pressed by the user should be the argument of function
  break;
  } // end of while
}        // end of loop
int isFull(){  // to check if queue is full
  if( (f1 == r1 + 1) || (f1 == 0 && r1 == stops1-1)) {
  return 1;
}
  return 0;
}
void enQueue(char element){  // adding key pressed to queue
  if(isFull()){
    Serial.println("Lift full");
  }else{
    r1 = (r1 + 1) % stops1;
    qlift1[r1] = element;
  }
}
int deQueue(){  // removing the front element of queue
  char element;
  element = qlift1[f1];
  f1 = (f1 + 1) % stops1;
  return(element);
}

```

At the start of program, 1st element of queue is loaded with '1' (in setup function). When key is pressed, it is added as 2nd element of the queue.

There is a function which should run in the background as soon as a key is pressed. The function is:

```
void liftStops(char keyPress){  // defined after the loop() function
  while(timer<100){
    distance = (speed*timer);
    motorClockwise();
    Serial.println(distance);
    if(keyPress == '1' && distance == 0){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '2' && distance == 30){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '3' && distance == 60){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '4' && distance == 90){
      motorStop();
      deQueue();
      return;
    }
    timer = timer+0.167;
    delay(200);
  }
}

```

The element hold indicated by `front` variable in the queue is passed as a parameter to the `liftStops()` function. There is a motor in the circuit and the `motorClockwise()` rotates motor clockwise,`motorStop()` will stop the motor.

When the program is run for first time , if I press '2', it is stored as second element in the queue. The function `liftStops()` starts with '2' as its argument. Now the `liftStops()` function runs till `distance == 30` and motor stops. Now `deQueue()` function is called and the element indicated by front gets eliminated('1' gets eliminated in the above case). After this,if I press '3', `liftStops()` runs till `distance == 60` and the element indicated by front gets eliminated('2' in this case).

If I press a key when the `liftStops()` execution didn't finish, nothing is added to queue. I want the `liftStops()` function to run in background so that each and every key I press at any point of time gets stored in queue and the `liftStops()` function runs for every element in queue one after another.

Thanks.

# Answer
> 3 votes
I wrote in a comment to your question:

> If you use `millis()` instead of `delay()` \[...\], then you won't need to run anything in the background.

and you answered:

> I have tried a lot using `millis()`, but I couldn't achieve the desired output.

From this, I assume the real problem is that you haven't tried hard enough. The general approach is quite simple:

* Is there any work that has to be performed *right now*?
    + if yes, then just do it
    + if no, then don't do it

It works as long as you do not have any *blocking* code in your program. Especially no calls to `delay()`.

In your particular case, it would seem that `liftStops()` has work only when:

* `timer` is less than 100
* *and* it hasn't done useful work during the past 200 ms (that's the `delay(200)` in your code, and it's not *useful* work).

You may try the following:

```
void liftStops(char keyPress) {

    // Manage the execution timing.
    static uint32_t last_time;
    uint32_t now = millis();
    if (timer >= 100 || now - last_time < 200)
        return;  // nothing to do this time
    last_time = now;

    // Do the actual work.
    distance = (speed*timer);
    motorClockwise();
    Serial.println(distance);
    if(keyPress == '1' && distance == 0){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '2' && distance == 30){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '3' && distance == 60){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '4' && distance == 90){
      motorStop();
      deQueue();
      return;
    }
    timer = timer+0.167;
}

```

Just make sure it is called often. I.e. you call it in `loop()` and you make sure there is no blocking code elsewhere in your program.

# Answer
> 1 votes
Typically this is done via an interrupt.

The use of an analog keyboard makes that more difficult or less convintional as the detection of a press in the analog sense is more difficult. One way to go is likely to scan the keyboard on a constant rate. But then detecting releases needs to be done creatively.

# Answer
> 1 votes
Use loop function already provided for repetitive tasks

```
 void loop() {
 //this itself should be the function which you want keep running
 //check for keystrokes here and handle characters as they are
 //received. For handling characters, you can write a function outside
 //of the main loop which should return control to loop when task is
 //finished
 delay(200);
 }

```

# Answer
> 1 votes
I have solved my problem using `attachInterrupt()` function.The `loop()` runs `liftStops()` continuously and if there is a keyPress, it is recorded by the interrupt.

```
void setup(){
  attachInterrupt(digitalPinToInterrupt(3), floor1, CHANGE);
}
loop(){
  liftStops();
}
void liftStops(){
  if(qlift1[f1+1] != NULL){
    while(timer<100){
      distance = (speed*timer);
      motorClockwise();
      Serial.println(distance);
      if(qlift1[f1+1] == '1' && distance == 0){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '2' && distance == 30){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '3' && distance == 60){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '4' && distance == 90){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '5' && distance == 120){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '6' && distance == 150){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }
      timer = timer+0.167;
      delay(200);
    }
  }
}
void floor1(){
  keyboardValue = analogRead(keyboardPin);
  while(keyboardValue > 5) {  // Runs when a key is pressed
    for(int i=0;i<8;i++){
      if((treshold[i] - keyboardValue) == 0){
        Serial.println(keypad[i]); // Printing the key pressed
        enQueue(keypad[i]); // Storing the key pressed in the queue
        break;
      }
    break;
    } // end of for
  keyboardValue = 0;
  break;
  } // end of while
}

```

If any key is pressed during `delay(5000)` even that gets recorded.

---
Tags: arduino-uno, programming, c++, arduino-ide
---


# Question
Title: Powering relay module with 5v external supply
The relay module consists of two sets of pins:

Set1: GND, VCC, Int1, Int2 Set2: JDVcc, VCC, GND

In set 2, VCC and JDVcc are jumpered together normally, which is removed to power the relay coil with external supply.

However, can I supply 5v directly from external source to the VCC pin of Set 1 and connect the GND pin to common ground, leaving the VCC and JDVcc pin jumpered together as they are? It's because I am running out of pins in my Uno.

Will that work?

# Answer
> 1 votes
> can I supply 5v directly from external source to the VCC pin of Set 1 and connect the GND pin to common ground, leaving the VCC and JDVcc pin jumpered together as they are?

Probably you're using this relay module, which is fairly common:

If that's the case, then the answer is **YES as long as you keep all grounds tied together and the 5V external supply deliveries a voltage reasonably close to the Arduino 5V**.

Why?

1. When IN is high and VCC is close to 5V, there isn't enough voltage difference for forward biasing the diodes. They won't conduct and no current will flow from or into your Arduino data pin.
2. When IN is low, the diodes are forward biased and current will sink into the Arduino data pin. As long as VCC is close to 5V, the current limiting resistor will keep current within specification of what the Arduino data pin can tolerate.

---
Tags: relay
---


# Question
Title: How to connect a 5V submersible motor to Node MCU?
I connected the D1,D2 pins of the the Node MCU to the positive and negative of a 5V submersible motor. I wrote the following code, its getting uploaded without any errors but the motor is not working. I tested the condition of the motor by connecting to a battery,it does work.the code:

```
void setup() {
  // put your setup code here, to run once:
    pinMode(D1,OUTPUT);
pinMode(D2,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(D1,HIGH);
digitalWrite(D2,HIGH);
}

```

# Answer
> 1 votes
I think you have got two issues here.

Firstly, as mentioned in the comments, you are driving the motor off the data pins so it will be getting less than 20mA which is almost certainly not enough to break the stall. You need to use the digital pins to switch a MOSFET, transistor or relay (Electrical switch) and then that will switch on a larger supply directly from a "battery pack". Have a Google for 'transistors' or 'relays' and see how they work, then you should get what I mean.

Secondly you seem to be using the pin names D1 and D2. There are a number of Node MCU boards out there but they all seem to have one thing in common and that is the pins labelled D1 and D2 on the board are generally not D1 and D2 in the code.

https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu\_pins.png?w=924

If this is you board then unless you have a header file that does this for you, you should be using GPIO\_5 and GPIO\_4 for D1 and D2 (respectively).

Oh and the last thing, make sure you sub is leak proof :)

---
Tags: motor, nodemcu
---


# Question
Title: Getting more current through an LED array
I have an Arduino Uno controlling an array of 24 LEDs (datasheet). I understand these LEDs are ultraviolet and have a forward current of 0.5A. My power source (12V 2A) is wired to a switch which is then wired to the LED array and Arduino. I should probably use a 12V 4A power source but was worried if too much current would go to the Arduino. As per my attached diagram, the Arduino and LED array are in parallel. I would like to get more current through my LEDs to increase their brightness. What would be the best way to do this?

Updated: I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD. And then I tried a 1 Ohm resistor instead but the resistor burned out. Unfortunately, I threw out the resistor and don't have a picture of it. I believe the correct value should be ~47 Ohm so I have added that resistance as R11. However, I haven't tested it yet as I want to make sure it's correct. (12V - 6V) = 130mA * R \>\>\> R = 46.15 Ohm. I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V). I measured the current through a multimeter to be 130mA.

# Answer
The current a bipolar transistor configured as a common emitter amplifier will allow from its collector to its emitter is equal to its beta time the base to emitter current.

A beta of 100 is common for many transistors. Assuming this information is close enough to your transistor, we can choose a base series resistance suitable for the collector to emitter current desired.

For example if you were using a 5 volt microprocessor and the voltage drop across the base to emitter was the usual 0.7 volts for silicon semiconductors and you had a base series resistor of 10Kohms:

```
V = I * R
V = 5 - 0.7 = 4.3 volts
R = 10000 ohms
I = 4.3/10000 = 0.43mA
I(ce) = Beta * 0.43mA
I(ce) = 100 * 0.43mA = 43mA

```

You could pass up to 43mA from the collector to the emitter. If that is not enough,you can lowered the base resistor to 1Kohms:

```
R = 1000 ohms
I = 4.3/1000 = 4.3mA
I(ce) = Beta * 4.3mA
I(ce) = 100 * 4.3mA = 430mA

```

And increase the current to 430mA. You still need to verify that the processor can supply the current to control the transistor (4.3mA as calculated above) as well as pick a transistor of sufficient capacity to handle the load.

If a beta of about 100 is not enough, consider using a Darlington transistor arrangement. This type of "2 transistor" device has a gain of the product of each individual transistor's beta. So, it is common for such a device to have a beta of 10000! Using this device, you can use a much larger base resistor and still be able to switch more current.
> 1 votes

# Answer
> I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD.

You should not have a resistor in the Arduino's supply line at all.

> And then I tried a 1 Ohm resistor instead but the resistor burned out.

If you really wanted to have one to share the heat load of the on-board regulator, it would need to be a `power resistor` of appropriate wattage rating.

> I believe the correct value should be ~47 Ohm so I have added that resistance as R11...I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V). I measured the current through a multimeter to be 130mA.

This is incorrect.

The Arduino's regulator needs something like 7 volts input to operate correctly.

The power drawn by the Arduino will not be fixed, it will depend on what it is doing, what I/Os are exerted against what loads, and other things like the LCD you apparently have.

Likely, if you want to use a power resistor you should design it to drop no more than half of the difference between the supply voltage and the regulator dropout voltage, under conditions of *maximum* load. A fixed power resistor cannot be used to *replace* the *variable power resistor* that is a linear regulator; at most it can be used to offset some of the *fixed* part of the resistance and resulting thermal load. But you still have to leave all of the variable part plus a healthy margin for the regulator to handle, or it won't be able to regulate.

It would be simpler to just put a heatsink on the regulator.
> 0 votes

---
Tags: arduino-uno, led, current
---