# Question
Title: How to toggle LED and motor on button press?
we want to have a LED turn on with the press of a button, and become brigther and brighter as times go by (whithin a defined time frame), and when it reaches maximum brightness to turn off for a couple of seconds and then start again. in addition to that, we are trying to add a motor that will start spinning 720 degrees when the button has been pressed. Our main problem is the fact that when we let go of the button the led turns off. How do we set the button so that when it is pressed once it turns everything on, and the led runs in a loop, but the motor doesn't; and when we press it again the whole led turns off completely and the motor runs 720 degrees in the opposite spinning direction than the previous.

Here is what we have managed so far (we didn't get to introduce the motor yet as we got stuck along the way):

```
const int switchPin = 11;
const int motorPin = 6;
int led = 9;
int switchState = LOW;
int previous = LOW;
int i = 0;
int fadeAmount = 5;

void setup()
{
  pinMode(led, OUTPUT);
  pinMode(motorPin, OUTPUT);
  pinMode(switchPin, INPUT);
}

void loop()
{
  int switchState = digitalRead(switchPin);

  for (int i = 0; i <= 255; i++)
  {
    analogWrite(led, i);
  }

  if (switchState == HIGH && previous == LOW)
  {
    if (i == 0)
    {
      digitalWrite (led, HIGH);
      i = i + fadeAmount;
      delay(1000);
    }

    analogWrite(led, i);

    for (int i = 255; i <= 255; i--)
    {
      digitalWrite (led, LOW);
      i = 0;
    }
  }
  else
  {
    //toggle off
    digitalWrite(led, LOW);
    i = 0;
  }
}

```

PS. WE are beginers. Thanks for the help and understanding!

# Answer
Here is a program that should fade the LED as you specified. Initially the LED is off. If you press the button the LED starts fading within the time frame to its maximum. Then it switches to zero waits a couple of seconds and starts fading from new. If you press the button a second time the LED stops fading and is set to darkness. ;-) This happens emediately, but of cause, you can only see it if the LED is in the fading phase.

I used interrupts in order to have a well defined state transition I can work with.

Aquiring the button pin in the loop, would be more complex to handle. That would require a state variable and some state transition rules. And I was too lazy to work that out. If interupts can't be used for any reason, I would change the answer. (No Mum I don't want to ...)

I removed the motor pin as it makes no sense for the answer. I also think that one pin would not be enough if your motor (stepper, dc with feedback or a servo) should spin a certain amount of degrees.

I tested the program on a Arduino UNO. The button I used is of low quality so I had to debounce it.

If there is something not clear to you, please ask within a comment.

```
// Attache the LED to a PWM pin UNO -> 3,5,6,9,10,11
const byte ledPin       = 9;

// UNO -> only pin 2 or pin 3 are interrupt pins
// as we use pullups the button should be connected to GND
const byte interruptPin = 2;

// in milli seconds - The time the LED needs to fully light up
const int timeFrame  = 5000;

// in milli seconds
const int aCoupleOfSeconds = 2000;

const int fadeAmount =    5;

volatile boolean fadeOn = false;
volatile long debounceTime = 800;
volatile long actTime = 0;

int brightness =   0;

int stepCount = 256       / fadeAmount;
int stepDelay = timeFrame /  stepCount;

void setup()
{
  pinMode( ledPin,       OUTPUT       );
  pinMode( interruptPin, INPUT_PULLUP );

  attachInterrupt( digitalPinToInterrupt( interruptPin ), pressed, CHANGE );
}

void loop()
{
  if ( fadeOn )
  {
    delay( stepDelay );
    brightness += fadeAmount;
    if ( brightness >= 255 )
    {
       brightness = 0;
       analogWrite( ledPin, brightness );
       delay( aCoupleOfSeconds );
    }
    analogWrite( ledPin, brightness );
  }
  else
  {
    brightness = 0;
    analogWrite( ledPin, brightness );
  }
}

void pressed()
{
  // the debouncing does not work perfectly

  if ( digitalRead( interruptPin ) == LOW )
  {
    if ( millis() - actTime > debounceTime )
    {
      fadeOn = !fadeOn;
    }
  }
  else
  {
    actTime = millis();
  }
}

```
> 1 votes

# Answer
Have a look at some code inside the forum from marcello.romani. He posted it on jan 1st, 2013. The topic on subject is called : "button pressed more than 2 seconds do somethingelse" Marcello's code is so KISS (Keep It Simple Stupid) and efficient that it deserves a Nobel prize. The goals is to handle the different signals that come from a button or switch action : keyPress, keyRelease, longKeyPress etc.. as you can find in the original sketch.
> 0 votes

---
Tags: c++, led, motor, switch
---


title: ESP32-CAM not reading BME680

text:
# Question
Title: ESP32-CAM not reading BME680
I am trying to read BME680 on ESP32-CAM with following code :

(Before trying BME680, I have suscessfully connected BME280 to ESP32-CAM over S/W SPI)

```
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"

#define SEALEVELPRESSURE_HPA (1013.25)

#define BME_SCK 12 //Connected SCL to IO12
#define BME_MISO 15 //Connected SDO to IO15
#define BME_MOSI 13 //Connected SDA to IO13
#define BME_CS 14 //Connected CS to IO14

//Adafruit_BME280 bme; // I2C
Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
//float temperature = 0;
//float humidity = 0;
//float pressure = 0;

void setup() {
  Serial.begin(115200);
  while (!Serial);
  Serial.println(F("BME680 test"));

  if (!bme.begin(0x76))
  {
    Serial.println("Could not find a valid BME680 sensor, check wiring!");
    while (1);
  }

  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void loop()
{
  if (! bme.performReading())
  {
    Serial.println("Failed to perform reading :(");
    return;
  }
  Serial.print("Temperature = ");
  Serial.print(bme.temperature);
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.pressure / 100.0);
  Serial.println(" hPa");

  Serial.print("Humidity = ");
  Serial.print(bme.humidity);
  Serial.println(" %");

  Serial.print("Gas = ");
  Serial.print(bme.gas_resistance / 1000.0);
  Serial.println(" KOhms");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.println();
  delay(2000);
}

```

When I try to upload the code to ESP32-CAM while BME680 is connected I get following error

```
esptool.py v2.6
Serial port /dev/ttyUSB0
Connecting....
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: a4:cf:12:99:b5:70
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Warning: Could not auto-detect Flash size (FlashID=0xffffff, SizeID=0xff), defaulting to 4MB
Compressed 8192 bytes to 47...

A fatal error occurred: Timed out waiting for packet content
A fatal error occurred: Timed out waiting for packet content

```

Then I tried to disconnect BME680 and uploaded the code to ESP32-CAM which worked, then connected BME680 back to ESP32-CAM.

But now I see following error in Serial Monitor :

```
ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jn  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot0x33 SPI_FAST_FLASH_BOT)
lash read err, 1000
et_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

```

Any idea what is wrong here ?

Update :

I switched `#define BME_SCK 12` to `#define BME_SCK 16`, now getting following message

```
ts Jun  8 2016 00:2:57

rst:0x1 (POWEON_REST),boot:0x13 (PI_FAT_FLASH_BOOT)
cnfigsi: 0, SPIWP:0xee
clk_dv:0x00,q_drv:0x0,d_drv0x00,cs0_drv:0x00,d_drv0x00,wp_drv:0x0
mod:DIO, clock div:
loa:0x3fff0018,len:4
load0x3fff001c,len:1216
ho 0 tail 12 room 4
lod:0x40078000,len:9720
h 0 tail 12 room 4
load0x40080400,len:6352
etry 0x400806b8
[D][esp32-hal-psram.c:47] psramInit(): PSRAM enabled

```

# Answer
GPIO12 must not be pulled high during boot. It's possible there's a pull-up resistor on the BME680 breakout board you're using that's pulling SCK high and interfering with the boot process. I would avoid using GPIO12 here.

If you're out of pins on the ESP32 you can connect the BME680 via I2C rather than SPI. I2C only needs SDA and SCK (and power and ground, of course). The Adafruit library for the BME680 has an example of how to call the constructor for an I2C connection.
> 2 votes

# Answer
You use pins

```
#define BME_SCK 12 //Connected SCL to IO12
#define BME_MISO 15 //Connected SDO to IO15
#define BME_MOSI 13 //Connected SDA to IO13
#define BME_CS 14 //Connected CS to IO14

```

for software SPI, but the esp32 can use any set of pins for hardware SPI.

And your set of pins are even the dedicated mux pins for SPI2 (they have the direct connection without mux). But they are in different mapping then your software SPI.

```
SPI2:
SCLK    14
MISO    12
MOSI    13
SS      15

```

Source: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/spi\_master.html

SPI2 is the default SPI used by the ESP32 Arduino SPI library, so the Adafruit library should have no problem to use hardware SPI with the SPI library.

```
Adafruit_BME680 bme(BME_CS); // use hardware SPI

```

and wire the sensor to SPI2 pins according to their function
> 0 votes

---
Tags: esp8266, sensors, spi, esp32
---


# Question
Title: How do I segment Arduino program when line count is so large that code maintenance is difficult?
I'm looking for the Arduino/C++ equivalent of COBOL's 'copy' statement.

I'm working on a program that is approaching 600 lines of code in the TopLevel.cpp source file. This is hard to manage because I feel like I spend all my time scrolling up and down the source file. The code in question does not easily lend itself to conversion to a class because it is sections of loop/main. I've tried using xxx.h (for storage definitions) and yyy.cpp (for code sections). Those approaches yield error messages, which I think are due to the different timings of the Arduino pre-processor and the compiler code that resolve the #include statements.

Thanks for the help. --CVTBrakeman

p.s. I wrote my first program in 1967; the language was GOTRAN on an IBM 1620. For almost 50 years, I made my living designing/writing COBOL and SAS code on IBM mainframes. Yes, Y2K was real and I survived it.

# Answer
This is more like a general programming question than an Arduino question but, anyway...

You don't need to write classes to sort your code into files. You just need to think in term of independent pieces of functionality. Each of those pieces would be implemented in a .cpp file, with the interface declared in a .h file.

As an example, let's say your Arduino is controlling an hyperdrive. Managing the dilithium plasma generator is one of those functionalities that can be separated in its own files. The .h files declares everything that is needed for *using* that functionality:

**plasma\_generator.h**:

```
// Read the state of the plasma.
float plasma_density();
float plasma_temperature();

// Control the plasma.
void set_plasma_target_temperature(float target_temperature);
void ignite_plasma();
void turn_off_plasma();
void add_dilithium(float amount);

```

Then the .cpp file contains the implementation:

**plasma\_generator.cpp**:

```
#include "plasma_generator.h"

// A "static" function is a function private to this module.
static float get_gauge_reading(int gauge_number)
{
    ...
}

// Implementation of a public function, described in the .h file.
float plasma_density()
{
    float raw_reading = get_gauge_reading(42);
    ...
}

...

```

In your main program (or even in other modules, if needed) you `#include` the .h file and use the functionality defined therein.
> 1 votes

# Answer
There are two ways of doing this:

1. Multiple INO files

The Arduino IDE combines multiple INO files into one single CPP file before compilation. You can split your program across multiple INO files at will. It makes it easier to manage, since you can split your program into logical chunks at will, but you don't have to think much beyond "which file shall I stick this function in?"

2. Create libraries

Some functionality of your program could be placed into a library or multiple libraries. This is kind of like option 1, but you have to think more about C++ syntax and suchlike that with INO files (function ordering, externs, etc). It does have the benefit that you could easily re-use code between programs, though

Personally I usually use option 2 before option 1. If a code is genericisable ("able to be made generic") then it can be made into a library - after all, I may want it later for some other program. However, if all you want to do is split your program into different chunks with each chunk a different topic or area of your program then option 1 is definitely for you.

Alternatively you might consider a different IDE, such as UECIDE which gives you such things as *function bookmarks&* to make navigation of your code easier.
> 1 votes

---
Tags: arduino-mega, programming, library
---


# Question
Title: How to get air speed, which sensor to use?
I want to measure the airspeed on a flying vehicle and get the data with arduino. Note that, there will not be any control mechanism on the flying object, it will be flying mechanicaly/passively, I mean no flight controller or something like that will be present.

However, I could not understand whether there is a sensor to measure the airspeed directly or is airspeed something you analyze by using other datas(temperature, pressure etc.)

I saw there are sensors which are sold as "airspeed sensor" however it is not so common that I cannot find examples in which the incoming data is shown.

Anybody ever experienced with this issue may lighten me.

Thanks in advance.

# Answer
> 1 votes
Typically you want to use Pitot tube sensor

---
Tags: sensors
---


# Question
Title: Connecting to Alexa with FAUXMOESP library not detecting the device
I am using NodeMCU (ESP8266 12E) module from some days. I am trying to connect to Alexa for voice controlling. I have Amazon Alexa Echo 2 from which I am trying to discover my nodemcu as a smart home device.

Here is my sketch I am trying to use to detect.

```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <fauxmoESP.h>

fauxmoESP fauxmo;

const char* ssid = "myssid";
const char* password = "mypassword";

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

  fauxmo.enable(true);

  fauxmo.addDevice("light one");
  fauxmo.addDevice("light two");

// this is not able to detect .onSetState function I am not sure about the reason.

//  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
//        Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);
//    });
}

void loop() {
    fauxmo.handle();

}

void wifisetup() {
  pinMode(2, OUTPUT);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  IPAddress ip(192, 168, 1, 243); // this 3 lines for a fix IP-address
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress dns(192, 168, 1, 1);
  WiFi.config(ip, dns, gateway, subnet);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(10000);
    digitalWrite(2, HIGH);
    ESP.restart();
  }
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(2, LOW);
    Serial.println("");
    Serial.println("Your ESP is connected!");
    Serial.println("Your IP address is: ");
    Serial.println(WiFi.localIP());

    delay(100);
  }

}

```

I am using https://bitbucket.org/xoseperez/fauxmoesp library to do the setup. Alexa is not able to detect my device. Not sure whats the issue with this, but in the Serial Monitor I can see the logs which is showing that I am getting ping from Alexa to my ESP8266.

Taking an output pin is compulsory? I have tried that too although but no output found.

Thank you!

# Answer
If you are using fauxmoESP library version 3.0 and above your device will not be detected by alexa, i dont know why this is. You may degrade fauxmoESp version to 2.4.0 so that your issue ie. .onSetState will be resolved.

Are you able to connect wifi?
> 1 votes

---
Tags: esp8266, nodemcu
---


# Question
Title: Compile code error: 'Serial' does not name a type
```
int LDR_deger = 0;

int Ledpin1 = 12;
int Ledpin2 = 11;
int Ledpin3 = 10;
int Ledpin4 = 9;
int Ledpin5 = 8;

int LDR_pin = 0;

void setup()
{

  Serial.begin(9600);
  pinMode(Ledpin1, OUTPUT);
  pinMode(Ledpin2, OUTPUT);
  pinMode(Ledpin3, OUTPUT);
  pinMode(Ledpin4, OUTPUT);
  pinMode(Ledpin5, OUTPUT);
}
void loop()

{
  LDR_deger = analogRead(LDR_pin);
digitalWrite(Ledpin1,HIGH);
digitalWrite(Ledpin2,HIGH);
digitalWrite(Ledpin3,HIGH);
digitalWrite(Ledpin4,HIGH);
digitalWrite(Ledpin5,HIGH);

if (LDR_deger <= 80 && LDR_deger> 30) {
  digitalWrite(Ledpin1, LOW);
} else{
  digitalWrite(Ledpin1, HIGH);
  if (LDR_deger<= 150 && LDR_deger > 80){
  digitalWrite(Ledpin2, LOW);
  digitalWrite(Ledpin1, LOW);
  }else{
    digitalWrite(Ledpin1, HIGH);
    digitalWrite(Ledpin2, HIGH);
    if (LDR_deger  <= 200 && LDR_deger> 150){
      digitalWrite(Ledpin2, LOW);
      digitalWrite(Ledpin1, LOW);
      digitalWrite(Ledpin3, LOW);
     }else{
      digitalWrite(Ledpin1, HIGH);
      digitalWrite(Ledpin2, HIGH);
      digitalWrite(Ledpin3, HIGH);
      if (LDR_deger <= 1000 && LDR_deger> 300){
      digitalWrite(Ledpin2, LOW);
      digitalWrite(Ledpin1, LOW);
      digitalWrite(Ledpin3, LOW);
      digitalWrite(Ledpin4, LOW);
      digitalWrite(Ledpin5, LOW);
     }else{
      digitalWrite(Ledpin1, HIGH);
      digitalWrite(Ledpin2, HIGH);
      digitalWrite(Ledpin3, HIGH);
      digitalWrite(Ledpin4, HIGH);
      digitalWrite(Ledpin5, HIGH);
     }
       }
     }
   }
  }
Serial.print("LDR Deger: ");
Serial.print(LDR_deger);
Serial.println(" ");
delay(500);
}

```

# Answer
One reason you are receiving the compile error, is due to the code outside of a function. When you write nice, neat, properly formatted code, these errors are easy to spot. The Arduino IDE has a built in feature that will "highlight" a matching curly bracket (or curly brace?).
> 1 votes

# Answer
VE7JRO already has answered your question. Below is not an answer to the question but a better way to program something like you have.

In your case, you need to set 5 pins according. I assume the following lines are just for initialization (and not needed when you set them afterwards to FALSE), as I do not see any delay.

```
digitalWrite(Ledpin1,HIGH);
digitalWrite(Ledpin2,HIGH);
digitalWrite(Ledpin3,HIGH);
digitalWrite(Ledpin4,HIGH);
digitalWrite(Ledpin5,HIGH);

```

It is much easier for each pin to set the conditions direction; this will reduce all the `if` statements and make it very clear for each pin what the value should be.

First we make some variables to prevent duplication. Actually I normally like using bool but it is not a predefined type. Also I like to have the low range on the left and the high range on the right, and using parenthesis. I added the range 200-300, and lower/upper range:

```
int LDR_deger_min_inf_30 =  (LDR_deger <= 30);
int LDR_deger_30_80      = ((LDR_deger >  30) && (LDR_deger <=   80));
int LDR_deger_80_150     = ((LDR_deger >  80) && (LDR_deger <=  150));
int LDR_deger_150_200    = ((LDR_deger > 150) && (LDR_deger <=  200));
int LDR_deger_200_300    = ((LDR_deger > 200) && (LDR_deger <=  300));
int LDR_deger_300_1000   = ((LDR_deger > 300) && (LDR_deger <= 1000));
int LDR_deger_1000_inf   =  (LDR_deger > 1000);

```

Now you can create a table for each pin (which makes great documentation and a clear overview); I would add it in a comment (if you have no other documentation way):

```
// pin min_inf_30 30_80 80_150 150_200 200_300 300_1000 1000_inf
//  1     HIGH     LOW    LOW     LOW   HIGH      LOW     HIGH
//  2     .. (fill in yourself)
//  3     .. (fill in yourself)
//  4     .. (fill in yourself)
//  5     .. (fill in yourself)

```

Now you can write the pins one by one (I only did the first as example):

```
digitalWrite(Ledpin1, LDR_deger_min_inf || LDR_deger_200_300 || LDR_deger_1000_inf ? HIGH : LOW);
digitalWrite(Ledpin2, …);

```
> 0 votes

---
Tags: serial, compilation-errors
---


# Question
Title: converting character to strings in transmitter and receiver Arduino
I am using transmitter and receiver but I want to change the data type from character to int

receiver code

```
#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray

 RH_ASK rf_driver; // create ASK object
int ledon = 13;
String userid;
String password;
 //RH_ASK ID1; // create ASK object
//RH_ASK pass1; // create ASK object

void setup() {

  rf_driver.init(); //initialize ASK object

  Serial.begin(9600); //setup serial monitor to 9600

  //if(!rf_driver.init())
       //Serial.print("init failed");
}

void loop() {

  // set buffer to size of expected message
  uint8_t buf[9];
  uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  if (rf_driver.recv(buf,&buflen))
  {
    int i;
    // message received with valid checksum
    Serial.print("id: ");
    Serial.println((char*)buf);
      userid =(char*)buf;
        Serial.println(userid);

  }

delay(5000);

   uint8_t buf2[8];
  uint8_t buflen2 = sizeof(buf2);

   if (rf_driver.recv(buf,&buflen))

  {

    int i;
    // message received with valid checksum
    Serial.print("password: ");
    Serial.println((char*)buf);
      password = (char*)buf;
      Serial.println(password);

  }
  delay(5000);

```

transmitter code

```
//Include RadioHead Amplitidue shift keying library
#include <RH_ASK.h>
// Include dependatnt ISP library
#include <SPI.h>

//create Ampitude shift keying object
RH_ASK rf_driver;

void setup() {
 // intialize ASK objct
rf_driver.init();

Serial.begin(9600);

  //if(!rf_driver.init())
      //Serial.print("init failed");

}

void loop()
{

  const char *pass= "123456789";
rf_driver.send((uint8_t *)pass, strlen(pass));
rf_driver.waitPacketSent();
delay(5000);

const char *ID= "A00034732";

rf_driver.send((uint8_t *)ID, strlen(ID));
rf_driver.waitPacketSent();
delay(5000);

```

# Answer
> 0 votes
You have to properly understand what you are trying to do. (It looks like) you have a decimal representation of a number, encoded as a string of characters. "12345" is not a number but a series of characters. <sub>(Technically each character is a number with a certain ASCII value, the digit "1" has ASCII value 49 for instance.)</sub>

To convert "12345" into the number 12345, the CPU needs to take each character, find its digit value, multiply it by the correct power of 10 and add it to all the others. There are a few built-in ways that do this for you. The easiest is the `atoi()` function, e.g.

```
int x = atoi("150");

```

In your case, try this:

```
int userid = atoi((char *) buf);

Serial.println(userid);

```

---
Tags: arduino-uno
---


# Question
Title: Set and extract individual bytes of a number (lowByte() and highByte())
You can extract

> the low-order (rightmost) byte of a variable

or

> the high-order (leftmost) byte of a word

with the functions `lowByte()` and `highByte()` respectively (the quotes are from the Arduino Reference).

Does Arduino provide a way to extract *any* byte from a number with a similar function?

And does it provide a way to set *any* individual bytes of a number (which would be the counterparts to these functions, if they exist)?

# Answer
> 5 votes
Any more sophisticated byte exchange can be done with binary operators.

## Extracting information

You'll need some constants like

```
MASK         SHIFT
0xFF000000   24       (first byte, most significant)
0x00FF0000   16       (second byte)
0x0000FF00    8       (third byte)
0x000000FF    0       (last byte, least significant)

```

You would binary AND the original value with MASK

```
     0x12345678
AND  0x00FF0000
 =   0x00340000

```

and then bit shift it left, e.g.

```
   0x00340000
>> 16
 = 0x00000034

```

So from the original value 0x12345678 you have gotten 0x34.

## Setting information

The opposite direction is also possible with the same constants but opposite operators and in opposite order:

```
   0x00000034
<< 16
 = 0x00340000

```

and then

```
   0x12005678
OR 0x00340000
 = 0x12345678

```

Note that the OR operation only works reliably if the corresponding positions are 0x00. That's fine with a starting value of 0x00000000.

If you don't know that or you want to process an arbitrary number, you can introduce a step in between

```
    0x12??5678   (?? could be anything)
AND 0xFF00FFFF   (which is the inverse of 0x00FF0000 and can be expressed as ~0x00FF0000)
 =  0x12005678   (whatever ?? was, it'll be cleared out)

```

## Actual Code

Tested on Arduino Uno. The `long` data type is 32 bits or 4 bytes.

The code here may not be the most efficient. Advanced developers would likely not use `MASK` and `SHIFT` as arrays like this. This answer focuses more on the educational point.

```
long MASK[]  = {0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF};
byte SHIFT[] = {24        , 16        , 8         , 0};

// Extracts a byte from a larger data type
// value: larger data type to extract a byte from
// position: 0 based number, 0 = MSB, 3 = LSB
byte getByteAt(long value, byte position)
{
  long result = value & MASK[position];  // binary AND
  result = result >> SHIFT[position];    // Shift right, moving all bits
  byte resultAsByte = (byte) result;     // Convert to an actual byte
  return resultAsByte;
}

// Sets a byte in a larger data type
// value: larger data type where to set the byte
// position: 0 based number, 0 = MSB, 3 = LSB
// newPartialValue: the byte to be inserted
long setByteAt(long value, byte position, byte newPartialValue)
{
  long result = value & ~MASK[position];                       // clear the affected byte so that it is 0x00
  long valueToSet = (long) newPartialValue << SHIFT[position]; // Shift left, moving all bits
  result = result | valueToSet;                                // binary OR
  return result;
}

void setup() {
  Serial.begin(9600);
  Serial.println(getByteAt(0x12345678, 1));       // Prints 52, which is 0x34
  Serial.println(setByteAt(0x87654321, 1, 0xBB)); // Prints -2017770719 which is 0x87BB4321
}

void loop() {

}

```

# Answer
> 1 votes
The header Arduino.h defines the macro `word(high_byte, low_byte)`. The resulting value is an `uint16_t`.

# Answer
> 1 votes
There are two alternative methods, and they can both be easily used "in reverse" as well:

### Unions

```
union byte_extract {
    uint32_t ival;
    struct {
        uint8_t byte_0; // least significant byte
        uint8_t byte_1;
        uint8_t byte_2;
        uint8_t byte_3; // most significant byte
    } bval;
};

... later ...

union byte_extract x;

x.ival = 65536 * 99; // change to whatever you want
Serial.println(x.bval.byte_2); //3rd byte

```

Unions are a way to define multiple possible ways to interpret a piece of memory, usually to save memory when you know something can't be 2 things at once. Strictly speaking it is not recommended to use them in this way but it works.

### Pointer arithmetic

```
uint32_t *xaddr;
uint8_t *xbyteaddr;

uint32_t x = 65536 * 99; // change to whatever you want
xaddr = &x;
xbyteaddr = (uint8_t *) xaddr;

Serial.println(xbyteaddr[2]); //3rd byte

```

Memory addresses (on Arduino as well as on PCs) refer to the first byte of a variable. If you have an (uint32\_t \*) you will read 4 bytes starting at that address. But if you have a (uint8\_t \*) or a (char \*) you will only read 1 byte. You can shift this pointer-to-uint8\_t forwards by as many bytes as you want.

Apologies if this doesn't quite work on Arduino, I have only tested it on PC.

---
Tags: data-type, bytes
---


# Question
Title: unable to read RS232 output on Arduino mega with MAX232 shield
I am trying to read data from an RS232 equipped sensor using a serial monitor connected to an Arduino Mega with RS-232 shield but I do not receive any data.

I am unable to detect the exact cause of the problem, as it only occurs when combining sensor and RS232shield/Arduino, while communication works as expected when testing them separately

What works:

* Connecting the sensor to a computer with a RS232-USB converter cable.
* Passing data from the computer through the USB-RS232 converter cable to RS232 shield and back through Arduino USB output.
* Connecting the RS232-pin 2 to port 10 using {SoftwareSerial} library with inverted logic.

What does not work:

* Passing data from the sensor to the computer via the MAX232 and Arduino.

The setup:

* Arduino Mega 2560
* Seeed RS232 shield (MAX232 based)
* Sensor with RS232 output (57600 8N1)

I have connected the RS232 output of the sensor to the shield using an M-M gender changer. The shield and Arduino are connected with three wires: GND-GND , 5V-5V, 232\_TX-RX1), and the Arduino connects to a Macbook via USB. The serial monitor on the computer is set to 56700 baud.

I use the following sketch to transfer data from the RS232 shield to Serial:

```
void setup()
{
// Open serial communications at 5700 baud
    Serial.begin(57600);
    Serial1.begin(57600);

// Check whether Serial1 is active
if (Serial1.available())
     while (!Serial1) {
        ;
    }
    Serial.println("Serial 1 is active");
}

void loop()
{
    if (Serial1.available()){
    Serial.write(Serial1.read());
    }

}

```

# Answer
I have solved the above and will share the answer as it may be of help to others:

As the Tx indicator LED on the RS232 shield would not light up when connected to the sensor, I checked the voltage difference between pin 2 (Tx) and pin 5 (GND) of the RS232 connector. This turned out to be only 5V, indicating that the protocol used is TTL-RS232 rather than 'true' RS232.

Due to the low voltage, I have connected the RS232 Tx and GND pins directly to the Arduino. With Tx connected to digital port 10, I used the SoftwareSerial library with logic inversion to read the data: `SoftwareSerial mySerial(10, 11, 1)`.

This works!
> 2 votes

---
Tags: serial, arduino-mega, rs232
---


# Question
Title: ESP32-Cam No Response and Unable to Program - Timed out waiting for packet header
I recently purchased an ESP32-CAM but have had no luck in programming the board or getting any response whatsoever. I first tried to program it using the an FTDI programmer and the Arduino IDE (following the steps from this tutorial: https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/).

I used this exact wiring diagram:  but got the Timed out waiting for packet header error message. This was with the jumper on the FTDI on the 3.3V section.

Other things I've tried: -Moving jumper to 5V, powering ESP from 5V pin -Powering ESP from external 5V source (Arduino pin) -Powering ESP from external 3.3V source -Switching computers (Linux and Windows) -Programming board directly from Arduino (bypassing FTDI) -Various combinations of pressing/holding reset button during flash process

The other thing is that there is no LEDs that turn on when the board is powered. I couldn't find a concrete reference online that said an LED turns on when the device is on, but I assume the one LED would at least flash or something. Also monitoring the serial output with putty during boot did not yield any output. I'm all out of ideas and I am just starting to suspect that the board is completely dead. Any ideas would be appreciated, thank you.

# Answer
You're right. There is no LED when you power up your ESP32 cam. So this is normal.

Try to power it with the 5V, so you can power it from your USB instead of the 3.3V regulator of your FTDI. The ESP just need 50mA when in programming mode, so it should not be a problem for your FTDI.

Do you see anything on your serial output? Once you connect it in this way, you should set the baudrate to 115200 on your serial terminal and see some characters.

Then, try to program it. Once you see the output "...\___...", press the reset button! Since you are just connecting RDX and TDX, you have to manually press "RESET" on your ESP32 module.

At this point the ESP will reset and enter in the programming mode.
> 1 votes

---
Tags: arduino-uno, esp32, ftdi
---


title: Sketchy Wemos D1 mini Pro

text:
# Question
Title: Sketchy Wemos D1 mini Pro
Recently, I bought a "ThingPulse ESP2866 Wifi Color Display Kit". I bought the kit before reading the reviews and finally read them the other day. Some of the reviews seem fake but a couple of them say that the Wemos D1 mini pro is being used to "steal credit cards" and other information. The bad reviews claimed that when they plugged the wemos into a power source, a wifi network named "ESP\_xxxxxx" appears and thats how their data is stolen. I plugged the Wemos that came in my kit to a power source and a wifi network starting with "ESP..." appeard. I was wondering if this is a valid concern or if its just conspiracy. I am not very informed on cybersecurity and data security so I thought this would be the best place to ask. Please let me know if you'd like anymore information. Thank you!

# Answer
It's pure conspiracy, paranoia, or people just generally not having the slightest clue what they have bought. By default the ESP8266 is in Access Point mode, and named ESP\_\[last 6 chars of MAC address\]. It will have an IP address in the range 192.168.4.x. And that is all.

It can't do anything else until you actually program it to do something.

Part of the "problem" is probably that the ESP8266 remembers WiFi settings independently of the sketch that is running on it. It's only the WiFi settings it remembers, though - not what to do with any data that travels over WiFi. That is purely down to whatever sketch you install.

**Unless you manually program it so it connects to your WiFi, or add extra hardware for other communications, the device can not, and will never be able to, send any data to anyone, anywhere, ever. Full stop.**
> 1 votes

# Answer
Before you’ve programmed the WEMOS, it will appear like an access point. It’s one if it’s great qualities of this versatile little chip. I wouldn’t worry about it. Don’t you have a secure vault for your personal info? It’s very easy to encrypt. Just search the internet on how to protect your data. You can really go it the safe way and implement a VPN. You might have to pay a 1-2$ a month for the service, which is actually a cloud based service.
> 0 votes

---
Tags: wifi
---


title: Timing taking longer than expected

text:
# Question
Title: Timing taking longer than expected
This is on a custom Arduino PCB (32u4) that I am programming with a Sparkfun Pocket AVR Programmer. A different program that I was writing wasn't working the way I expected it to, so I tried the "BlinkWithoutDelay" example sketch from the Digital section of the examples.

https://media.discordapp.net/attachments/572565310679547946/650075749851856908/unknown.png ^ So you don't have to look it up yourselves. previousMillis is initialized to 0.

However, the LED seems to alternate states every 4 seconds instead of every 200 ms with this code. I increased the interval from 200 to 400, and the IRL time increased from 4 seconds to 8 seconds, so at the very least it's consistent that way. My first instinct is that the crystal is broken somehow, but I don't think I'd be able to flash the MCU in the first place if it was. So, does anyone have any idea what's happening? For the record, I had 5 of these PCB's assembled, and the first one worked perfectly for 2 months before something else broke. I've had this issue with the second and third PCB I've tried.

# Answer
Factor 8 in timing smells like wrong fuses.

Perhaps you don't use an external oscillator, but the internal one?
> 1 votes

# Answer
On all of the new boards I had tested (excluding the first one that I said worked), I had not burned the bootloader. Burning the bootloader made the timing normal! If anyone can tell me why that's the case, I'll accept your answer as the "correct" answer.
> 1 votes

---
Tags: arduino-micro, timing
---


# Question
Title: Using usb port to communicate with standalone atmega328p circuit
noob here

So I managed to get my circuit to be a standalone circuit (as pictured below). I want to use this circuit as an input to a game on my computer. What I want to know is could this micro-usb breakout board https://www.diyelectronics.co.za/store/breakout-boards/2414-micro-usb-power-switch-breakout-module.html be used to communicate with the computer. Where would the data pins (d+/d-) connect to the atmega328?

Any help will be most appreciated

# Answer
The ATmega328 does not have any native USB capability, so there is nowhere appropriate to connect D+/D- to the ATmega328.

Assuming you are emulating an Arduino Uno, then something like this:

https://www.jaycar.com.au/arduino-compatible-usb-to-serial-adaptor-module/p/XC4464

is what will come closest to mimicking the USB function on an Uno (ie a serial connection).

This shows how such a device would be connected:

https://www.jaycar.com.au/usb-serial-converter
> 2 votes

---
Tags: usb, atmega328, communication
---


# Question
Title: How to get keyboard input to Arduino from the computer its plugged in to?
I have an Arduino Uno connected to my laptop and I need to get keypress info from the laptop's keyboard with only the Arduino sketch and without any program running on the laptop. Is there a specific library or some way of doing so?

# Answer
You can't. It's impossible.

Or not as you have requested it, anyway.

The Arduino can only talk over Serial, so you will have to have some software running on the PC that transfers data (however that data is generated) over serial to the Arduino to process.

The only other option will be to have one of the Arduino boards that is capable of acting as a USB Keyboard device, such as a Leonardo, plus either a PS/2 keyboard or a USB keyboard plus a USB Host shield. Your Arduino the receives the keystrokes from the keyboard, processes them, and sends the result on to the PC.
> 1 votes

---
Tags: arduino-uno, keyboard
---


# Question
Title: Arduino UNO R3 + SIM800L / NodeMCU via Hadware Serial. Possible?
I'm using Arduino UNO R3 with NodeMCU and SIM800L module. I have to connect these two devices to UNO and make a serial communication between them: UNO\<\>SIM800L and UNO\<\>NodeMCU.

Can I use GPIO0 and GPIO1 of UNO (RX, TX) to communicate with one of above devices?

Thanks in advance.

# Answer
If all you need to do is communicate between the NodeMCU and the SIM800L, what do you need the Arduino for?

Connect the SIM800L directly to the NodeMCU and program the NodeMCU to do whatever communication is needed for the SIM800L.
> 1 votes

---
Tags: arduino-uno
---


title: reading micro SD card directly from PC

text:
# Question
Title: reading micro SD card directly from PC
Is it possible to read a microSD card (on a breakout) through the USB port on the arduino? or perhaps another USB port I could attach to the breakout? Basically, I would like to read data off the card with my laptop without having to go and remove it each time!

# Answer
It would be very useful, but afaik this is not possible, since the Arduino sketch you write communicates to the PC via the serial interface only.

The IDE/Arduino driver can use the USB to write your sketch and use the USB for communicating, but for sketches the USB (as direct medium) is not possible.

The SD card will not show up as a specific drive/map/folder on your PC.

Since you want to read the SD card, write in your sketch code to transmit the file(s) you want to send to the PC, to transfer them by UART, and on the PC write a program that reads the serial port and processes it.
> 1 votes

# Answer
In general that's possible. But you can't read the sd card through the arduino's usb port. Instead you have to read the sd card via another protocol, e.g. SPI (look for the apropriate library) and send it to the pc via serial. You'll need software on the pc side to write the content that was read from the arduino to a file.

Take a look at the SD card tutorial to see how to read it.
> 1 votes

# Answer
It can't be done with an Arduino, but it can be done with other microcontrollers. You need a microcontroller with a direct USB ("native") connection plus a USB stack that is capable of acting as a USB Mass Storage Device. Something like the Teensy or chipKIT series of boards can do that.

Then you can write software that will, on command, detach the SD card from your normal sketch operation and re-attach it to the MSD device in the USB stack. You can then read and write to the SD card (though your sketch otherwise cannot access it) as much as you like - then "unmount" the MSD device and detach the SD card from it, at which point your sketch is then free to re-attach itself to the card and start using it again.

Note that the important thing here is that only one functionality can work at a time - either you can read and write the files on the card with your sketch, *or* you can export the device through MSD. Never both. That way leads to filesystem corruption and loss of data.
> 0 votes

---
Tags: arduino-uno, sd-card
---


# Question
Title: ESP32-CAM interfacing with CCS811+HDC1080+BMP280
I want to measure Temprature, Pressure, Humidity and CO2 in a room with ESP32-CAM & CCS811+HDC1080+BMP280

Since this module is combination of 3 sensors. Can I integrate it with ESP32-CAM over Software SPI ?

# Answer
> 1 votes
No. Those three devices are I2C devices, not SPI devices.

Using that is no different to using three individual sensors all wired to the same I2C bus.

---
Tags: esp8266, esp32, espressif
---


# Question
Title: how to read arduino board info serial no programmatically
well I am try to make an project with original arduino. but I want to make this project unique. if my codes are copied and loaded another arduino board, my app should not work. how can make unique app, are there any idea? on Arduino IDE Tools\> Get Board İnfo\> SN look unique id. but how can read it programmatically.

# Answer
You can't. The serial number is burned into the ATMega16U2 chip and is only available to the computer over the USB interface. There is no method for you to get it from the UART interface that connects the two MCUs together.

To stop people copying your code there are two things you need to do:

1. Don't allow anyone access to the source code or any compiled code files, and
2. Enable the "code protection" facility of the ATMega328P.

The latter will stop people being able to read the code from the Arduino. It would also be beneficial to remove the bootloader and program the board directly. That way there is no other possible route for getting at your code.

You enable code protection by setting the correct fuse bits.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Uno to NodeMCU Serial Connection Problem
This is my first project with any sort of development board and it has been a blast so far.

I am running into some issues, however, while trying to send serial data from my Uno to a NodeMCU board.

I have the following connections:

Uno Rx to NMcu Tx

Uno Tx to NMcu Rx

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

**EDIT:** after some suggestions, I have also tried the following.

Uno DigitalPin 5 to NMcu D6

Uno DigitalPin 6 to NMcu D5

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

With the following code:

```
// UNO sender Code
#include <SoftwareSerial.h>
SoftwareSerial toESP(0, 1); //Rx, Tx (also tried 5,6)

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

void loop()
{
  Serial.println("sending");
  toESP.println("message from Nano");
  delay(1000);
}

```

---

```
// NodeMCU receiver code
#include <SoftwareSerial.h>
SoftwareSerial fromNano(3, 2); //Rx, Tx (also tried D5, D6)

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

void loop()
{
  if (fromNano.available())
  {
    char inChar = fromNano.read();
    Serial.print(inChar);
  }
  else {
    Serial.println("not available");
  }
  delay(2000);
}

```

I can pull up a serial monitor from both and see the UNO sending data (the TX led also blinks on the uno).

The NodeMCU code never satisfies the `fromNano.available` condition.

Is there anything I am overlooking that is causing this not to work? I've attached a picture of my connections as well.

Any help is much appreciated.

# Answer
> 2 votes
Arduino UNO is using pin 0 and pin 1 to have serial with USB serial Communication. You can not use them to softserial. Change softserial to other pins. /Mikael

# Answer
> 0 votes
@Carlmikael is definitely correct in his answer, I should not have been using hardware pins with softwareserial.

Besides that problem, my issue was resolved ultimately when I noticed that if I powered up the NodeMCU before powering up the Arduino, everything worked as expected.

Maybe someone can elaborate as to why this caused an issue?

---
Tags: arduino-uno, nodemcu, softwareserial
---


title: Convert float to hexadecimal value

text:
# Question
Title: Convert float to hexadecimal value
I am trying to convert a float value to a 4-byte hexadecimal value.

For example my input is: 58.5. My expected output is: 426A0000 or like 0x42 0x6A 0x00 0x00.

My program is:

```
void setup() {
  Serial.begin(9600);
  float z = 128;
  unsigned i;
  unsigned char *chpt;
  chpt = (unsigned char *)&z;
  Serial.print("Float Value             : ");
  Serial.println(z);
  Serial.print("4 Byte hexadecimal Value: ");
  for (i = 0; i < sizeof(z); i++) {
    Serial.print(chpt[i],HEX);
    //Serial.print(" ");
  }
  Serial.println();
}
void loop() {
}

```

My current output is:

`Float Value : 128.00`

`4 Byte hexadecimal Value: 00043`

# Answer
> 1 votes
This value looks pretty correct to me. It is stored in little endian thou.

0x43000000 is the actual value.

`Serial.print(x, HEX)` truncates leading zeros. so `00` gets `0` So your output is `0 0 0 43` which corresponds to the little endian representation of the above.

Make yourself familiar with the floating point representation IEEE-754.

Also try the online FoatConverter.

Try the following:

```
char floatString[9];
sprintf(floatString, "%02X%02X%02x%02x", chpt[3], chpt[2], chpt[1], chpt[0]);
floatString[8] = '\0';
Serial.print(floatString);

```

---
Tags: string, float
---


title: Can you use a 128 pin LCD on an atMega?

text:
# Question
Title: Can you use a 128 pin LCD on an atMega?
I found a couple old calculators and their LCD's have about 130 pins.

I was wondering if I can build an LCD driver to reduce the number of I/O pins, because I don't want to use like 14 I/O extenders; or can I make 1 huge extender?

# Answer
This answer assumes that each LCD segment is controlled by a separate pin (see comment of Juraj).

With a 74HC595 (shift register) you can use SPI to control 8 outputs. You can daisy chain 4 of them to get 32 outputs with just the SPI pins, to get 128 pins. I assume two pins are for GND and VCC. If you need more than 128 GPIO output pins, than use 5 or more sets of daisy chained shift registers.

Now, since these shift registers use SPI, you can use the slave select to use multiple sets of daisy chained shift registers. I never tried this myself though.

The pins (except GND/VCC) you use is:

* 3 SPI pins (MISO, MOSI, CLK)
* 4 SS pins (one for each set of 4 daisy chained shift registers)

The idea is:

1. Set SS pin to the first set of 4 shift registers
2. Write 32 outputs for the first 32 segment output pins (using the 4 shift registers of the first set)
3. Set SS pin to the next set of 4 shift registers
4. Write 32 outputs for the next set
5. Continue with the next 2 sets (so you can use 32 * 4 = 128 pins)
6. In the next cycle, start with step 1 again
> 0 votes

---
Tags: arduino-mega, lcd, pins
---


# Question
Title: Compilation Error - Yellow LED blinking as I have installed & connected Arduino UNO board to Windows XP PC
This is the first time when I have installed Arduino IDE (arduino-1.8.10-windows.exe) in my Win. XP SP-3 OS and it seems that the Arduino IDE software installation is successful without any hitch.

After restarting the PC, connected it with Arduino Uno board through USB-Printer cable provided with the board and then selected Arduino Uno, Selected Port: COM3 (Arduino/Genuino Uno) - as I have verified in the Device Manager that the Arduino Uno installed in COM3 port.

As soon as I have connected Arduino Uno board to my PC, the yellow LED started blinking slowly. As I have tried uploading the sketch - File\>Examples\> 01.Basics\>Blink - there is an Error message that says, "Error compiling for board Arduino Uno" - even though the yellow LED still kept blinking without a reasonable act from my side.

So, where have I gone wrong - either in performance or in understanding? And is there any suggestion for making things right?

I thank you.

```
// the setup function runs once when you press reset or power the board
void setup(){

  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);

}

// the loop function runs over and over again forever
void loop(){

  // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED_BUILTIN, HIGH);

  // wait for a second
  delay(1000);

  // turn the LED off by making the voltage LOW
  digitalWrite(LED_BUILTIN, LOW);

  // wait for a second
  delay(1000);

}

```

# Answer
The yellow LED may be flashing because there may be a "Blink" LED program pre-installed on the Arduino.

To diagnose the "Error compiling for board Arduino Uno", we need to see the sketch you are trying to upload, and detailed error messages. If you go to `Arduino > Preferences`, check the "compilation" and "upload" checkboxes beside `Show verbose output during:`. `Display line numbers` is another checkbox you could enable.
> 0 votes

---
Tags: arduino-uno, compilation-errors, installation
---


# Question
Title: Multiple Loops to control on and off LEDs
I'm new here. I have tried to write a simple code to turn LED's and light them up in specific pattern and being able to switch it off while in loop. So far I've managed to either get them constantly flashing in pattern and not responding to button or when I wrote in seperate void loops each function IDE Arduino throwing me error 'expected 'while' before 'loop1'' and I'm completely stuck and not got a clue what's the problem with code. Anyone could help?

Here's a code:

```
const int ledPin =  2;
const int ledPin1 = 3;
const int ledPin2 = 4;
const int buttonPin = 5;

int programState = 0;

int buttonState;
long buttonMillis = 0;
const long intervalButton = 300;

long ledMillis = 300;
const long intervalLed = 500;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH);
}

void loop()
{
  unsigned long currentMillis = millis();
  buttonState = digitalRead(buttonPin);

 if (buttonState == LOW && programState == 0)
  do{
   programState = 1;
    }
void loop1(){
if {programState = 1 && buttonState == HIGH}
 do  {
   programState = 2;
    ledMillis = currentMillis;
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(200);
    digitalWrite(ledPin,HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(1500);}
 }
 void loop2(){
 if (programState = 2 && buttonState == LOW)

 do {
  programState = 2;
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(200);
    digitalWrite(ledPin,HIGH);
    delay(200);
    digitalWrite(ledPin1,HIGH);
    delay(200);
    digitalWrite(ledPin2,HIGH);
    delay(200);
    digitalWrite(ledPin2,LOW);
    delay(200);
    digitalWrite(ledPin1,LOW);
    delay(200);
    digitalWrite(ledPin,LOW);
    delay(1500);}

 else if  (programState == 2 && buttonState == HIGH)
 do
   {

    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
  }
}
yield();
}

```

# Answer
> 0 votes
You are using the `do` function wrongly:

Like this:

```
do{
  programState = 1;
}

```

It should be something like:

```
do
{
  programState = 1;
} while (`some condition`);

```

Where `some condition` is a condition that repeat the parts in { and } in case `some condition` is true.

However, besides that, it does not make sense normally to assign a variable in a while loop as only statement, since it will be 1 after the first iteration and reassigning it again does not make the value different (`programState` stays at 1).

Also note that in most cases the following form is used (unless you always want the body to be executed at least once):

```
while (`some condition`)
{
  `statements`
}

```

Are you sure you need the `do` or `while` statement at all? Otherwise, try to remove the `do` statements and see if that is closer to what you need (I cannot map the code to your requirements). I have the feeling you want to use loops to prevent a lot of code duplication, for that you need to store the `ledPin`, `ledPin1` and `ledPin2` variables in an array and loop over them.

Another way is instead of e.g. the following code:

```
digitalWrite(ledPin, HIGH);
delay(200);

```

to create a separate function:

```
void setPin(int pin, int value)
{
   digitalWrite(pin, value);
   delay(200);
}

```

and call the function by:

```
setPin(ledPin, HIGH);

```

Now you can change all occurences of 'digitalWrite(`some pin`, `some state`); delay(200)' to the single statement above.

Also, I see there is a function `yield` that is not implemented.

# Answer
> 0 votes
In addition to using the `do` construct incorrectly, you are also using an approach that won't work.

You generally should not use a do-while statement in Arduino. That causes your code to "stick" in the body of the do-while statement while the `while` condition is true, which prevents the rest of your code from executing.

You also should not use the `delay()` function if you need to manage timing different things at the same time. (To make a more general statement, you should not use the `delay()` function **at all**. Forget it exists.) There are rare cases (like doing one-time setup of hardware in your `setup()` method.) where using the `delay()` function is appropriate, or **very** short intervals like timing ultrasonic pulses, but the `delay()` function ALWAYS causes your program to come to a complete halt until the delay interval has passed.

You should search on "Arduino blink without delay" and study the example project you find. It outlines how to use the `millis()` function to keep track of timing. With that approach you can time multiple things at the same time. (You'd have multiple "fire time" variables that would remember the `millis()` value at which you want a change to occur, and you get that value of `millis()`, your code would trigger the change (toggling an LED, for example) and then update that "fire time" variable.

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


# Question
Title: Dotstar strip goes nuts when connected to MIDI piano
I've got a Dotstar strip, a piano, and an UNO(w a usb host shield). I can get and properly translate data from the piano to the UNO, so I'm definitely getting the right information to the board. When i hardcode input values into my code it reacts appropriately, so I know my code works. However, when I attempt to take data from the USB piano keyboard and light a corresponding LED, the whole strip lights up blue and green and flashes brightly between them. This happens before I even hit a key on the keyboard. When I hit a key, the correct light lights up for roughly a milisecond before returning to flashing green or blue.

I feel like there's some electrical concept that I'm not getting- I've got the MIDI information correctly making it to the board, and it can correctly control the LEDs. I don't know where it could be getting the data that's causing it to do this.

I think I might need a resistor- I tried to set an AND gate from the SS pin and the data pin, but that didn't do anything.

Here's the AND gate setup I attempted.

# Answer
The USB host shield and the LED strip use the same SPI bus. The USB host shield has a cable select line, but the LEDs don't, so they're always listening to the bus, even when the USB shield is using it.
You'll have to add some logic gates on the data and clock lines to the LED strip to turn them on or off, depending on another cable select line for the LEDs.

`LED Clock` = NOT `LED CS` AND `SPI CLK`
`LED Data` = NOT `LED CS` AND `SPI MOSI`

If you're only using two SPI devices, you could do:

`LED Clock` = `USB CS` AND `SPI CLK`
`LED Data` = `USB CS` AND `SPI MOSI`

https://forum.arduino.cc/index.php?topic=644679.msg4363133

**Edit**: Judging from the image, you're asking the exact same question as the one I already replied to on the Arduino forum a month ago. Why do you ask the same question twice if you're not even going to reply?
> 1 votes

---
Tags: arduino-uno, led, usb, midi, led-strip
---


# Question
Title: Trying to measure distance using an ultrasound sensor
I am relatively New to Arduino and need your help. Actually i made a code and the problem is that the ultrasound sensor doesn't work at all. It isn't displaying the distance between the object and and the sensor. Can you help me please! Here is my code:

note: the code has some motor cotrol commands

```
int enableBridgePin = 10;
int forwardPin = 11;
int backWardPin = 9;
int tickPin = 2;
const int trig = 5;
const int echo = 6;

int dt;
int distance;

float rotationSpeed[50];

void setup() {
  pinMode(enableBridgePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(backWardPin, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);

  digitalWrite(forwardPin, LOW);
  digitalWrite(backWardPin, LOW);

  interrupts();
  digitalWrite(enableBridgePin, HIGH);
}

void loop() {
  analogWrite(enableBridgePin,255);

  digitalWrite(forwardPin, HIGH);
  digitalWrite(backWardPin, LOW);

  distancefonction(dt, distance);
  if(distance>5){
   detachInterrupt(digitalPinToInterrupt(tickPin));
   digitalWrite(forwardPin, LOW);
   }

}

int distancefonction(int dt, int distance)
{
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  dt = pulseIn(echo, HIGH);
  distance = 0.034/2*dt;
  Serial.println(distance );}

```

# Answer
> 0 votes
You have declared `int distance` outside of any method. That means it's available from all methods. Some people call it a *global* variable.

However, you have a method `int distancefonction(int dt, int distance)` which receives `int distance` as a parameter. This results in an ambiguity: if you refer to `distance` within the method like

```
distance = 0.034/2*dt;

```

should this now refer to the *parameter `distance`* or the *global variable `distance`*?

The answer is: you can't decide. The C/C++ standard has decided for you and the answer is: the parameter will take precedence and thus hide the global variable. This thing is also called "shadowing".

What does it actually mean?

1. The global variable `distance` has an undefined value at the start of the program. Let's assume the value is 0.
2. `distancefonction()` is called, passing `distance` as a parameter. This will create a copy of the value 0 on the stack.
3. the function will calculate the distance and update the variable on the stack.
4. The `Serial.println()` statement within the function accesses the variable on the stack and will print the correct distance.
5. Once the function is complete, the code in `loop()` will access the global variable `distance`, which still has the old value, because only a copy has been updated.

What is the solution?

Of course there are several solutions.

1. The simplest fix is probably to remove the parameter `int distance` from `distancefonction`. Thus the function will not receive a copy and instead operate on the global variable.
2. Another solution is to let `distancefonction` return the actual distance. The method signature already indicates that you wanted to return a value: the `int`from `int distancefunction(...)` says that. At the moment, the function does not return anything. You could write `return distance;` at the end. This approach could eliminate the global variable completely.

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


# Question
Title: choosing prober controller to measure engin speed changes
In order to monitor engine speed changes in real time, sensor is detecting the motion of few magnets around a disk driven by the motor. 1st approach Hall effect sensor signal is regulated by LM393 comparative IC, resulting digital clean signal, connected as input to a selected pin then measuring the timing changes between of the signals to calculate the speed changes. 2nd approach is to connect hall sensor directly without modeling to a micro controller ADC, then process the digital noisy unclean signal which require much processing power than 1st approach. Better approach are welcome, but the question is how to choose proper controller specs for such task

# Answer
The first option is way better than the second. Measuring a voltage with the ADC takes time and you don't really need the analog values in your code. (Though depending on the actual values you might not need a comparator befor it. The digital input pin acts as Schmitt Trigger. The only requirement for this is, that the signal range is greater than 0.3\*Vcc to 0.7\*Vcc.)

About the needed controller: That greatly depends on the speed, that the motor is running at (e.g. the frequency of pulses), and the way you are measuring it.

* The easiest Arduino way is to attach an interrupt to the pin and increment a counter variable in it. Reading and resetting the variable in regular time ranges (using `millis()` will give you the pulse frequency and thus the speed. For this you don't need much extra functionality in the microcontroller. One with external interrupts or pin change interrupts is sufficient (almost all microcontrollers have those).
* Another way is to utilize a hardware timer as counter. You can configure a timer of a microcontroller to get it's clock source from a pin. If you connect your sensor output to it, the counter will increment on every edge (falling and rising). The first timer of an Arduino is used by the Arduino core as time-keeper. You can use it to get the time component. Configure the second timer as counter, set it's value to zero, then start the timer and track the time passed using `millis()`. When the measurement time has passed, you read the counter value, reset it to zero and start a new measurement. While the hardware timer counts the pulses, you can calculate the speed with the number of pulses and the time passed and do whatever you want with it. This approach of course needs at least 2 timers (which most microcontrollers have, I think).

Of course the general speed of the microcontroller, meaning it's clock frequency, is also a concern. But this only becomes relevant, as you reach high pulse frequencies.

This answer is a general overview on how to go on. For a more specific answer, you should edit your question to also be more specific. For example you could include the expected pulse frequency.
> 0 votes

---
Tags: sensors, speed, hall-effect
---


title: Compiling code via terminal

text:
# Question
Title: Compiling code via terminal
How can I compile my code via terminal? I am working on a Chrome app that allows you to write, compile, and upload code to an Arduino, and I need to know this so I can use the command line compiler on my Linux server. Mac or Linux terminal, it doesn't matter.

# Answer
> 2 votes
Check out platformio.org it's the best solution out there for command line compiling.

# Answer
> 1 votes
Assuming an AVR-based Arduino, you would need the avr-gcc compiler, the avr-libc and the Arduino libraries. Also avrdude if you want to upload. The only issue is that the commands used for the build process are quite long (lots of options). You can see them by enabling verbose compilation in the IDE. Thus you will probably want some way to automate the whole thing.

There are several options for this. The most straightforward seems to be the arduino-builder command-line tool. This is part of the Arduino project and should ensure maximum compatibility. Otherwise you could use a plain old Makefile. I personally use Sudar Muthu' Makefile. It can be installed on a Debian-based Linux distribution by:

```
sudo apt install arduino-mk

```

It is not fully compatible with the classic Arduino build process though: it *does* automatically include `<Arduino.h>` into your sketch, but it does *not* add forward declarations. Some prefer it this way, as the automatic inclusion of forward declarations is somewhat buggy and does not play well with some C++ features.

# Answer
> 1 votes
There is an Arduino CLI (command line interface):

https://github.com/arduino/arduino-cli

You use commands such as to access Arduino IDE functions:

`arduino-cli compile --fqbn arduino:avr:leonardo sketch`

and

`arduino-cli upload -pCOM14 --fqbn arduino:avr:leonardo sketch`

(obviously port will be different under Linux)

---
Tags: compile, avr-gcc
---


# Question
Title: I need some help getting data from a rangefinder
I have wired up my range finder (CJVL53L0XV2) to a breadboard for testing and have run the arduino example code for the rangefinder. The rangefinder works, but I do not know how to take the distance that the range finder shows on the serial monitor, example: distance measured 44mm, and turn that information into a variable that the rest of my program could use.

I am not sure how to "grab" data from the sensor and turn that data into a variable that I can then manipulate. I have tried to dissect the example code, but it seems to be taking data and using functions that do not exist anywhere but in some files in the arduino library that I can't identify or access.

Below is the code that I have been trying to reverse engineer.

```
[code]
Adafruit_VL53L0X lox = Adafruit_VL53L0X();
int pbl = 9;
void setup() {
  pinMode(pbl, OUTPUT);
  digitalWrite(pbl, HIGH);
  delay(1);
  Serial.begin(115200);

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin()) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }

  delay(100);
}
[/code]

```

# Answer
> 1 votes
measure.RangeMilliMeter was the key to it all. After experimenting for several hours, I finally got it.

---
Tags: programming, sensors
---


# Question
Title: How to stop OLED flicker when using SSD1306Ascii.h?
Why does the OLED display flicker when using the SSD1306Ascii.h library? The Adafruit library does not have this issue, but I've been told uses a lot of memory and so I'm trying to use Ascii to conserve memory resources. The problem manifests itself when the void loop() begins. When using similar code with the Adafruit library, the display stays steady as a rock.

Here is my example code. many thanks in advance.

```
// Edit AVRI2C_FASTMODE in SSD1306Ascii.h to change the default I2C frequency.

#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"

#define I2C_ADDRESS 0x3C

// Define proper RST_PIN if required.
#define RST_PIN -1

SSD1306AsciiAvrI2c oled;
//------------------------------------------------------------------------------
void setup() {

#if RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS, RST_PIN);
#else // RST_PIN >= 0
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
#endif // RST_PIN >= 0
  // Call oled.setI2cClock(frequency) to change from the default frequency.

  oled.setFont(System5x7);
  oled.clear();
  oled.print("Hello World!");
  delay(2000);
  oled.clear();

}
//------------------------------------------------------------------------------
void loop() {

  oled.setFont(System5x7);
  oled.print("Hello fuuuzzzzyyyy world!");
  delay(1);
  oled.clear();

}

```

# Answer
> 1 votes
Your loop is repeatedly writing and clearing the display, nearly as fast as possible (minus the 1ms delay at the bottom), which is the reason for the flicker you're seeing. If instead, you only update the display when something changes, it will look much smoother. Even a clear-and-rewrite the entire display when something changes (assuming the changes are infrequent) will be a major improvement. Of course this assumes you'd eventually be writing dynamic data; your test program, of course, writes and re-writes static data.

Update:

> If I run the same code structure with Adafruit library there is no flicker, even with no delay in the loop.

Can you compare the two libraries to see what they do differently?

> The Adafruit library does not have this issue, but I've been told uses a lot of memory

There's a likely clue: Adafruit may be buffering the display contents in memory so it can find out which character positions changed and update only those. That would be a classic time/space trade-off.

# Answer
> 0 votes
Yes, it's due to rewriting the whole display. I generally only rewrite portions that have changed or at worst use the ClearToEOL command to make sure everything's obliterated.

---
Tags: adafruit, display
---


# Question
Title: Reliably reloading the calibration data of IMU BNO055
I am using the BNO055 IMU and the Adafruit Library. I want to store the calibration data and load them after the microcontroller is powered off and repowered on. The Adafruit Library provides an example for storing and restoring but, in actual facts, it does not work. It is always required to recalibrate the magnetometers, but even doing so, the library reperform the whole calibration including the accelerometers.

I would like to simply restore all the calibration data (including the magnetometers) so that no calibration needs to be performed when the IMU starts.

I have read a massive amount of posts on the argument, but I really could not figure out how to reliably load all the calibration data at boot and avoid recalibrating them.

Is there anyone who succeeded and can please share the code?

# Answer
> 1 votes
I found the solution. It is enough to add a function that when reperfoming the calibration of the magnetometer, checks ONLY if the magnetometer is calibrated (while the calibration for the accelerometer and gyroscope is reloaded from the EEPROM).

```
void performMagCal(void) {
  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;

  while (mag != 3) {

    bno.getCalibration(&system, &gyro, &accel, &mag);
    displayCalStatus();
    Serial.println("");
  }

  Serial.println("\nMagnetometer calibrated!");
}

```

---
Tags: bno055
---


# Question
Title: sending specific date's data from data logger shield to serial port
I was wondering if it is possible to save lots of data( exp: one year data) in data logger shield and then read them from serial port without ejecting the SD card... this part of my question is fine... the main subject is that i want to read specific date's data from the logger... To explain this better, lets say you have a humidity sensor and saved it's data for a year. Now you want to send the last 6 month's data to your phone via bluetooth. Is it possible? Also, i wanted to use the circular buffer but that doesn't seem like a good idea because it's costly... any ideas will be such a great help.

# Answer
I see a few questions (reading specific data from an SD) and the circular buffer; I think these are two different 'problems'.

**Reading specific data from an SD**

It depends how you save your data. Do you make one big file, or you create daily a new file for example?

Assuming the last, it's relatively easy, just sent the file contents of the files within a certain date.

In case you have a big file, you need to parse the file, in specific the time stamps you have to include in the file, and send everything within certain dates.

If this takes too long parsing, you could create a second file that contains the starting points (e.g. byte offset) for every day. So e.g. Jan 1 -\> 0 means Jan 1 starts at byte 0, Jan 2 -\> 3633 starts at byte 3633; you can use some kind of `seek` function to start reading the data file starting from date; and continuing also checking the end date's byte offset.

You can get the time stamp of a file:

```
void dateTime(uint16_t* date, uint16_t* time)
{
    DateTime now = rtc.now();
    // return date using FAT_DATE macro to format fields
    *date = FAT_DATE(now.year(), now.month(), now.day());
}

```

You can start reading from a certain position in a file by using the `fseek` function, see https://www.arduino.cc/en/Reference/FileSeek.

**Circular buffer**

This relates to sending bytes (via a peripheral/bluetooth). It is not costly at all. What you do is create a circular buffer (e.g. 50 bytes or whatever). Than you start writing bytes into it (which you copy from the SD file increasing the buffer space. Than you start sending bytes from it, decreasing the buffer space.

I never used Bluetooth, so I don't know how the packet (and size) is sent; if you can just sent packages of a certain or fixed length, you don't need a circular buffer, just keep reading e.g. 50 bytes, put it in a fixed array, send it, and load it again etc until all bytes are sent.
> 0 votes

---
Tags: arduino-uno, datalogging
---


# Question
Title: Trouble trying to turn a stepper while a button is pressed down
So i'm currently coding a little device that rotates a step motor round one 8th of a full revolution every time a button is pushed. the motor is attached to a question reel with 8 questions on it, each one is viewable through a little window covering the reel after each button press. the thing im concerned about is that if even one of the question sections is slightly larger or smaller than the others, it will cause the question to become misaligned with the window after a certain number of run throughs.

in order to combat this I want to have a back up code that simply rotates the stepper while the button is held down. this will allow me to manually reset the reel to its proper positioning should the questions become misaligned. im not achieving this however, and was hoping someone may be able to detect where the issues are in my code?

```
#include <Stepper.h>

#define STEPS 2048

Stepper myStepper(STEPS, 8, 10, 9, 11);

const int  buttonPinBlue = 6;

void setup() {

  myStepper.setSpeed(5);
}

void stepp() {

 myStepper.step(1);

  pinMode(buttonPinBlue, INPUT);
}

void loop() {

 if (buttonPinBlue == HIGH) {

  Serial.print("pin is high");

   stepp();
  }

}

```

also just as a side note, the stepper runs fine using the 'define steps' value and the speed that I've set here, the issue appears to be that the button press is not being detected

# Answer
> 0 votes
You don't set the pin itself:

Change

```
if (buttonPinBlue == HIGH) {

```

to

```
if (digitalRead(buttonPinBlue) == HIGH) {

```

Also you don't have to set the pin every time, only one time is enough: in function `setup` should be the following line (and it can be removed from the function `stepp`:

```
pinMode(buttonPinBlue, INPUT);

```

Note that if you want to use a 'click' to move to the next item, you have to debounce the button; on the Arduino site check for button debouncing: https://www.arduino.cc/en/Tutorial/Debounce

---
Tags: stepper-motor
---


# Question
Title: Attiny85, high output impedance, dim leds
I designed what I thought should be a very simple badge using the Attiny85 SU, schematic below:

The problem is the tiny doesn't seem to be sinking current properly. For testing I switched to a 20 PU on the breadboard and 100 ohm load resistors. At 3v supply this should give approximately 30 mA per pin, well under the rated 40 mA per pin and 200 mA total. However with the loads connected only pin 6 sinks any significant current, and appears to be higher impedance than it should be (1.6v across the resistor for 16 mA). The other pins seem to be very high impedance, they drop to ~7 mV (70 microamps) when the loads are connected. With the load resistors disconnected they function normally (digitalWrite HIGH = supply voltage - junction drop).

I'm using pinMode \[this was a problem\] (OUTPUT, N) \[/this was a problem, should be (N, OUTPUT)\] to set up pin N, and digital writes for on/off. I've been able to drive transistors before using an exactly similar setup, although admittedly these have much lower current requirements.

Anybody know what's going on here?

EDIT: Turns out I had accidentally swapped the order of OUTPUT and N in the pin mode command. Not sure why the compiler had no problems with this, but I am at least getting useful outputs now.

I'm gonna leave this up out of curiosity/etc, because I'm still getting higher impedance than I'd have expected on the outputs. With the 100 ohm load resistor, I'm only getting about 16 mA (expect closer to 25). Supply voltage from the CR2032 is ~2.48v under load.

Based on the graph on the datasheet (figure 22-19, PG 182), at 25 c ambient (currently 20) I should expect a voltage drop from VCC to output somewhere on the lower end between 400 and 600 mV when supplying 15 mA, but my readings at 16 mA above represent a voltage drop of almost 900 mV across the Tiny. Additionally the LEDs drop 2v at 10 mA, for which you'd expect approximately 300 mV drop across the tiny according to the graph, but mine is dropping almost 500 mV. I'm not sure if this is something in my setup or if the characteristic curves on the datasheet simply aren't that accurate for production models.

# Answer
> 3 votes
The answer to the main problem was that I had used pinMode(mode, number) where the actual syntax is pinMode(number, mode). Presumably modes can be selected by number and the compiler though I wanted to set an undefined pin to mode number.

TL;DR the correct syntax is pinMode(4, OUTPUT) to set PB4 (pin 3) to output.

The problem of higher than expected output impedance remains, though the outputs are now quite usable. As detailed in the edit, I'm still experiencing voltage drops across the microcontroller nearly 2x higher than I'd expect from the graph on the datasheet for a given current.

# Answer
> 3 votes
You already found your problem. I am answering only to provide some insight on why you were experiencing the symptoms you had.

`pinMode()` takes two integer arguments (two `uint8_t` to be precise). The names `INPUT`, `OUTPUT` and `INPUT_PULLUP` are just macros for 0, 1 and 2 respectively. This is why the compiler accepts your code with the arguments swapped.

On the AVR microcontrollers, setting a pin's output register to `HIGH` on a pin that is configured as input has the effect of turning on the internal pullup. Thus

```
digitalWrite(pin, HIGH);

```

has the same effect as

```
pinMode(pin, INPUT_PULLUP);

```

on an input pin. When you do this, the pin will source (not sink) a very small current. The pullup resistance is typically of the order of 30 kΩ, and this is why you get such a small current.

---
Tags: attiny85
---


title: Cryptic compiler errors

text:
# Question
Title: Cryptic compiler errors
I'm getting the error:

```
    left_hand:3:20: error: expected ']' before ';' token
     #define HAND_ROWS 5;
                        ^

```

on this code:

```
    #include <Keyboard.h>

    #define HAND_ROWS 5;
    #define HAND_COLS 6;
    #define ROW_PINS {9, 8, 7, 6, 5};
    #define COL_PINS {10, 16, 14, 15, 18, 19};
    #define LOOP_SPEED = 10;

    const char keymap[HAND_ROWS][HAND_COLS] = {{0xB1, '1', '2', '3', '4', '5'},
                                               {0xB3, 0x81, 'q', 'w', 'e', 'r'},
                                               {'6', 0x80, 'a', 's', 'd', 'f'},
                                               {'7', 'z', 'x', 'c', 'v', 'b'},
                                               {'h', 'j', 0x82, ' ', 'k', 'l'}};
    boolean pressedKeys;
    int keymapIndex;

```

help, please? This makes no sense to me... If I try to use Keyboard.LEFT\_SHIFT and equivalent constants for the hex-codes in the keymap, they tell me 'expected unqualified-id before numerical constant' What does this even mean? I'm so lost...

# Answer
You mustn't terminate a `#define` with a `;`. Semicolons are for C and C++ statements. `#define` is a *preprocessor* statement.

`#define` creates a literal string replacement, so when you use it you end up with:

```
const char keymap[5;][6;] = {...

```

which is, of course, wrong.
> 1 votes

---
Tags: arduino-pro-micro
---


# Question
Title: millis and micros always returns 0 (or other constant)
On an Arduino Uno, I have a sketch akin to this:

```
void setup()
{
    // Generate some PWM signal on Pin 5, using Timer 0.
    pinMode(5, OUTPUT);
    TCCR0A = 0b00110011;
    TCCR0B = 0b00001000;
    OCR0A = 0x80;
    OCR0B = 0x20;
    TIMSK0 = 0b00000100;

    Serial.begin(115200);
}
void loop()
{
    // Just write the result of millis to the terminal.
    unsigned long ms = millis();
    char s[100];
    sprintf(s, "%lu\r\n", ms);
    Serial.print(s);
}

```

Setup timer 0 to generate a PWM signal, setup the serial port, constantly print the result of `millis()` to the terminal.

The numbers printed to the console do not increase as expected, but stay "0". Similarly, if I use `micros`, "4" is printed constantly.

How's that?

# Answer
`millis` and `micros` appear to use timer 0 internally. Using that timer to also generate a PWM signal messes with their ability to function properly. The solution is to either use a different timer to generate the PWM signal, or to roll a custom equivalent of those functions.

Why does the official arduino documentation not specify that `millis` and `micros` occupy timer 0?
Why are there no Google results mentioning timer 0 when searching for "arduino millis returns 0", "arduino millis constant", "arduino millis not counting" and the like? (There are results with the same symptoms, but for different reasons.)
Who knows.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Reading Data from Google Sheets using Nodemcu
I want to read and writ data on Google sheets using ESP8266 WIfi Nodemcu and I'm able to do it but the time interval between two writing row is 3 seconds which is too much. I can read data but I am able to read only the first row not any other rows i am not able to read even changing the URL parameters.

Here is My Code -

```
#include "ESP8266WiFi.h"
#include "HTTPSRedirect.h"
#include "DebugMacros.h"

// Fill ssid and password with your network credentials

const char* ssid = "Leobotics";

const char* password = "leobotics123";

int sheetHumid = 1;

int sheetTemp  = 2;

int sheetaqu   = 3;

String readaqu = "";

const char* host = "script.google.com";

// Replace with your own script id to make server side changes

const char *GScriptId = "AKfycbyu_JnX7F29Ea5cZUy7HdsFbv9W5UmedmNbhTwt5tznwRUiQhYS";

const int httpsPort = 443;

// echo | openssl s_client -connect script.google.com:443 |& openssl x509 -fingerprint -noout

const char* fingerprint = "ED:83:75:6B:83:FE:01:DE:BA:72:84:05:71:FA:CE:54:FB:6E:23:CA";

//const uint8_t fingerprint[20] = {};

// Write to Google Spreadsheet

String url = String("/macros/s/") + GScriptId + "/exec?value=Hello";

// Fetch Google Calendar events for 1 week ahead

String url2 = String("/macros/s/") + GScriptId + "/exec?cal";

// Read from Google Spreadsheet

String url3 = String("/macros/s/") + GScriptId + "/exec?read";

String payload_base =  "{\"command\": \"appendRow\", \
                    \"sheet_name\": \"Sheet1\", \
                    \"values\": ";
String payload = "";

HTTPSRedirect* client = nullptr;

// used to store the values of free stack and heap
// before the HTTPSRedirect object is instantiated
// so that they can be written to Google sheets
// upon instantiation

unsigned int free_heap_before = 10;

unsigned int free_stack_before = 20;

void setup() {

  Serial.begin(115200);

  Serial.print("Connecting to wifi: ");

  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  Serial.println("");

  Serial.println("WiFi connected");

//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());

  // Use HTTPSRedirect class to create a new TLS connection

  client = new HTTPSRedirect(httpsPort);

  client->setInsecure();

  client->setPrintResponseBody(true);

  client->setContentTypeHeader("application/json");

  Serial.print("Connecting to ");

  Serial.println(host);

  // Try to connect for a maximum of 5 times
  bool flag = false;

  for (int i=0; iconnect(host, httpsPort);

    if (retval == 1) {

       flag = true;

       break;
    }

    else

      Serial.println("Connection failed. Retrying...");
  }

  if (!flag){

    Serial.print("Could not connect to server: ");

    Serial.println(host);

    Serial.println("Exiting...");

    return;
  }

}

void loop() {

  datasend();

  static int error_count = 0;

  static int connect_count = 0;

  const unsigned int MAX_CONNECT = 20;

  static bool flag = false;

  if (!flag){

    client = new HTTPSRedirect(httpsPort);

    client->setInsecure();

    flag = true;

    client->setPrintResponseBody(true);

    client->setContentTypeHeader("application/json");

  }

  if (client != nullptr){

    if (!client->connected()){

      client->connect(host, httpsPort);

      payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

      client->POST(url2, host, payload, false);

    }
  }

  else{

    DPRINTLN("Error creating client object!");

    error_count = 5;

  }

  if (connect_count > MAX_CONNECT){

    connect_count = 0;

    flag = false;

    delete client;

    return;

  }

  Serial.println("GET Data from cell 'A1':");

  if (client->GET(url3, host)){

    ++connect_count;

    payload = payload_base + "\"" + readaqu + "," + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

    Serial.println("RECIEVED DATA IS GIVEN BELOW   ");

    Serial.println("                              ");

    Serial.println("1");

    Serial.println(readaqu);

    Serial.println("2");

    Serial.println(sheetaqu);

    Serial.println("3");

    Serial.println(sheetTemp);

    Serial.println("4");

    Serial.println(sheetHumid);

    Serial.println("                              ");
    Serial.println("RECEIVE DATA PRINT IS OVER  ");

    sheetaqu ++;

    sheetTemp ++;

    sheetHumid ++;

  }
  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  Serial.println("POST append memory data to spreadsheet:");

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  if(client->POST(url2, host, payload)){

    ;
  }

  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  if (error_count > 3){

    Serial.println("Halting processor...");

    delete client;

    client = nullptr;

  }

  delay(4000);

}

void datasend()

{
   // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  // Note: setup() must finish within approx. 1s, or the the watchdog timer
  // will reset the chip. Hence don't put too many requests in setup()
  // ref: https://github.com/esp8266/Arduino/issues/34

  Serial.println("\nGET: Write into cell 'A1'");

  Serial.println("=========================");

  // fetch spreadsheet data

  client->GET(url, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nGET: Fetch Google Calendar Data:");

  Serial.println("================================");

  // fetch spreadsheet data

  client->GET(url2, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nSeries of GET and POST requests");

  Serial.println("===============================");

  // delete HTTPSRedirect object

  delete client;

  client = nullptr;
}

```

# Answer
> 2 votes
I think you'll need to modify your Google Script for that Sheet so that whatever function you are invoking to GET row data takes in an additional parameter for the row value.

Then just add the Javascript logic within that function for retrieving the data at that passed-in row index to be returned.

Does that make sense?

---
Tags: arduino-uno, esp8266, wifi, esp32, iot
---


title: Reading port register and print

text:
# Question
Title: Reading port register and print
I am playing with port registers directly to improve speed on a Arduino micro. I have no problem **writing** them, like

```
PORTF &= B11101111

```

However, when I try to **read** and print it, things get funny and I hope to know why.

Observation 0:

```
byte dat = PORTF;
Serial.print(dat,BIN);

```

produces a single 0, where I am expecting 8 0's as for a byte. And, even when I check that a digitalRead correctly gets a 1 from PF5 or A2,

Observation 1:

```
byte dat = PORTF;
Serial.print(dat,BIN);
Serial.print(dat,BIN);

```

produces a compiler error like

```
...cores\arduino\Print.cpp: In function 'println.constprop':
...cores\arduino\Print.cpp:143:1: internal compiler error: Segmentation fault
}
^

```

# Answer
The function `Serial.print()` and it's siblings cuts all leading zeros. So `0b00001111` get's displayed as `1111` and `0b00000000` as `0`. So you actually get what you expect. It's just printing different.

Also, when reading `PORTF`, you actually read the output state of the pins, as you have set it before. If you want to read the real input level of the pins, you should read `PINF` instead.

Though I don't know, where that segmentation fault came from.
> 0 votes

---
Tags: arduino-micro, port-mapping, avr-gcc
---


title: ARDUINO flashing lights

text:
# Question
Title: ARDUINO flashing lights
I'm making a circuit with my Arduino so that when it receives a '1' or '2' or 'a' it turns on or off the LEDS. But I wanted the lights to flash and do not know how to do loops in loops or if that's what I need to do at all. Any help would be very much appreciated and the code will be below.

```
//-----------------ELECTRONICS-----------------//

int left = 11;
int stoP = 12;
int right = 8;

//variables
int Received = 0;
int left_state =0;
int stoP_state = 0;
int right_state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(left,OUTPUT);
  pinMode(stoP,OUTPUT);
  pinMode(right,OUTPUT);
}

void loop() {

  if (Serial.available() > 0)
  {
    Received = Serial.read();
  }

////////////////LEFT//////////////////

if (left_state == 0 && Received == '1')

{
  digitalWrite(left,HIGH);
  Received = 0;
  left_state = 1;
}

if (left_state == 1 && Received == '1')

{
  digitalWrite(left,LOW);
  Received = 0;
  left_state = 0;
}
///////////////////////////////////

///////////////stop////////////////

if (stoP_state == 0 && Received == 'a')

{
  digitalWrite(stoP,HIGH);
  Received = 0;
  stoP_state = 1;
}

if (stoP_state == 1 && Received == 'a')

{
  digitalWrite(stoP,LOW);
  Received = 0;
  stoP_state = 0;
}

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

 ///////////right///////////////

if (right_state == 0 && Received == '2')

{
  digitalWrite(right,HIGH);
  Received = 0;
  right_state = 1;
}

if (right_state == 1 && Received == '2')

{
  digitalWrite(right,LOW);
  Received = 0;
  right_state = 0;
}
}

```

# Answer
As chrisl already mentions, you have to use the `millis` function.

Besides setting a pin HIGH, you keep a variable for each state for the start time and set it when the corresponding state is set to 1:

```
unsigned long left_start_time = millis();

```

Than within the loop you check for each state when it is 1 (on or actually flashing) and switch the pin on or off, example:

```
if (left_state == 1)
{
    digitalWrite((millis() - left_startTime % 400) < 400 / 2) ? HIGH : LOW);
}

```

What this does is for the first half of the 400 ms period (time % 400 \< 200) to be HIGH, and the last half (time % 400 \>= 200) to be LOW.

Improvements:

* Do not use 400 but a constant value.
* Do not use separate variables for left/right/stop, but put them in a structure, keeping the state, time, pin, and activation key ('1', '2', 'a') together.
* If you do the above, you can make your program more simpler (and avoid code duplication) by parameterize your code.
> 0 votes

---
Tags: programming, led, loop
---


title: When does the ADC take the reading?

text:
# Question
Title: When does the ADC take the reading?
I'm experimenting with the "2 pin capacitance meter" and trying to make it more accurate. Currently I've made the Arduino read 62.5 ns intervals but this means the time for the ADC to read is taking up a bigger part of the interval. I'm currently using a prescaler value of 8 on the ADC. Unfortunately reading continuously isn't really an option so I am limited to around 8us of read time instead of 6.5us. This isn't that much of a problem since I know that the read will take near 8us from experiments, however I do not know when during that 8us interval the actual reading takes place.

So that is my question, does the adc take the average value during those 8us, does it "lock" the bits at the beginning or when exactly does the reading occur?

Link to capacitance meter, specifically the third one: http://www.circuitbasics.com/how-to-make-an-arduino-capacitance-meter/#comment-363733)

# Answer
The ADC is a "Successive Approximation" type ADC. It works by:

1. Taking a snapshot of the incoming voltage in a small capacitor
2. Generating a reference voltage
3. Comparing the voltage in the capacitor to that reference voltage
4. Refining the reference voltage
5. Go back to 3 until you have the accuracy you desire.

There's lots of "time" involved there:

* The capacitor can only store the voltage accurately for so long before the self-discharge (leakage current) causes the voltage to drop (this defines the maximum amount of time you can take to do a reading)
* Each refining of the reference voltage and comparison thereof takes one ADC clock tick. There are a few "setup" clock ticks as well. This defines the minimum number of ADC clocks that you need to take a reading (13)
* The DAC and comparator take a certain amount of time to operate each clock tick - this limits the maximum clock frequency the ADC can run at.

So you have a "sweet spot" of speed (like the "goldilocks zone" of the solar system). Set the ADC too slow or try and get too high a resolution out of it and you lose accuracy due to voltage droop on the capacitor. Set it too fast and the DAC can't keep up and you lose accuracy due to the comparison voltage not being right.

Well, that's the internals. Then on top of that you have the Arduino API. That adds an entire other layer of complication. `analogRead()` is a *blocking* operation. It:

1. Congfigures the IO pin (if needed)
2. Turns on the ADC (if needed)
3. Configures the ADC MUX to the right channel
4. Starts a conversion
5. Sits there twiddling its thumbs for a while
6. Reads the conversion result
7. Returns it to you

And it does that (except maybe 1 and 2) every time you take a reading. That's fine for reading a potentiometer, or an LDR, etc. But rubbish when you want to do fast, time-based, readings.

Instead you need to push the envelope a little and step away from the Arduino API. Much of what the ADC does is done without intervention of the CPU. Manually configuring the ADC to read continuously and trigger an interrupt when the conversion is done, and then using that interrupt to grab the result of the comparison and start a new one (or use a timer interrupt to read the previous result and trigger a new reading) will give you much more control over the ADC and exactly when things happen.

So, now to answer your main question of "when during that 8us interval the actual reading takes place.", in the context of how the ADC works:

**At the moment the SAH capacitor is detached from the MUX to start the comparison sequence**.

When exactly is, though, is subjective. If you use the Arduino API (`analogRead()`) then it's at some point near the start of the function call, but not *at* the start of it.

If you configure it manually and trigger it from within a timer interrupt, it's *on the second (out of 13) falling edge of the ADC clock after ADSC has been set HIGH*.

There are also "Free Running" and "Auto Trigger" modes whose timing is the same as for a single conversion. Note that the first conversion performed in any mode imposes a "run-in" clock sequence where the ADC MUX and reference voltage DAC are initialised.

All this timing can be found in figures 23-4 and 23-5 on page 209 of the ATMega328P datasheet. On page 210 there is a handy table that gives you how many ADC cycles from the start of a conversion the Sample And Hold occurs and how long the conversion takes in clock cycles.

For best throughput you want to use "Free Running" mode and read and store the ADC result in the interrupt the ADC triggers. For most accurate and controllable timing you want to use Auto Triggered mode with a timer for the trigger source, and again read the result in the ADC interrupt.
> 1 votes

---
Tags: analogread, time, adc, speed
---