# Question
Title: Crash when datalogging MPU-6050 to SD card
On an Arduino Pro Mini, I'm using Jeff Rowberg's stuff in i2cdevlib to read from the MPU6050, and using SdFat to write data to an SD card. Each part in isolation is fine, but when both DAQ and logging are in use the Arduino locks up after a few minutes, then happily restarts when reset is pressed.

I've tried disabling the interrupt and manually polling `mpu.getIntStatus()` in `loop()`, and I've also dropped the FIFO rate from 100Hz to 10Hz by changing the config in `MPU6050_6Axis_MotionApps20.h` (and confirmed that it has actually dropped) along with changing the SPI speed from SPI\_FULL\_SPEED to SPI\_SIXTEENTH\_SPEED and changing the I2C wire speed from 400kHz to 50kHz. All of these were done progressively and showed no significant change in the run times, which are scattered pretty randomly between \<1 and 20 minutes. I also changed the datalogging to doing a filesystem flush on every cycle from doing it every 100 cycles, which helped performance but might have meant lots of internal buffer allocation/deallocation and memory leak risk.

I've tried putting a watchdog in but have encountered a widely known issue with this board that the watchdog is useless with the stock bootloader. I'm now working on that so I can try and use it to debug where in code the hang is, but I suspect it's going to be deep in one of the two third party libraries and I'm not going to be able to do much with it. I've attached the present iteration of code below. Does anyone have thoughts on where to go from here? Has anyone done similar with this kit?

```
#include "I2Cdev.h"

//#include <helper_3dmath.h>
//#include <MPU6050.h>
#include <MPU6050_6Axis_MotionApps20.h>
//#include <MPU6050_9Axis_MotionApps41.h>

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

//Includes for SdFat

#include <FreeStack.h>
#include <MinimumSerial.h>
#include <SdFat.h>
#include <SdFatConfig.h>
#include <SdFatUtil.h>
#include <SystemInclude.h>

//Includes for watchdog
#include <avr/wdt.h>

// ************* Defines for MPU6050 *****************
#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

// ************* Variables for MPU6050 *****************

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
//Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 gyro;       // [x, y, z]            gyro measurements

//VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
//VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
//VectorFloat gravity;    // [x, y, z]            gravity vector
//float euler[3];         // [psi, theta, phi]    Euler angle container
//float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// ************* Defines for SdFat *******************

// The chip select line for the SD card
#define SD_CHIP_SELECT 4
// Log file base name.  Must be six characters or less.
#define FILE_BASE_NAME "Data"

// ************ Variables for SdFat *******************
//
// Set DISABLE_CHIP_SELECT to disable a second SPI device.
// For example, with the Ethernet shield, set DISABLE_CHIP_SELECT
// to 10 to disable the Ethernet controller.
const int8_t DISABLE_CHIP_SELECT = -1;
//
// Test with reduced SPI speed for breadboards.
// Change spiSpeed to SPI_FULL_SPEED for better performance
// Use SPI_QUARTER_SPEED for even slower SPI bus speed
const uint8_t spiSpeed = SPI_SIXTEENTH_SPEED;
// File system object.
SdFat sd;
// Log file.
SdFile file;

int sd_writes_since_flush = 0;

// Serial streams
ArduinoOutStream cout(Serial);

// input buffer for line
char cinBuf[40];
ArduinoInStream cin(Serial, cinBuf, sizeof(cinBuf));

// ******************************* Misc *******************************
int crash_timer = 0;

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

//******************* Setup ***************************

void setup() {
  // put your setup code here, to run once:

  // Set up serial comms
  Serial.begin(250000);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately
  Serial.println(F("Serial initialised"));

  // initialize device
  Serial.println(F("Initializing MPU.."));

  // Set up comms to the MPU6050
  Wire.begin();
  Wire.setClock(50000); //400000= 400kHz I2C clock. Comment this line if having compilation difficulties

  mpu.initialize();

  pinMode(INTERRUPT_PIN, INPUT);
  Serial.println(F("Initializing DMP.."));

  devStatus = mpu.dmpInitialize();

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

  // verify connection
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  Serial.println(F("Initialising SD card.."));
  if (!sd.begin(SD_CHIP_SELECT, spiSpeed)) {
    if (sd.card()->errorCode()) {
      Serial.println (F(
             "\nSD initialization failed.\n"
             "Do not reformat the card!\n"
             "Is the card correctly inserted?\n"
             "Is chipSelect set to the correct value?\n"
             "Does another SPI device need to be disabled?\n"
             "Is there a wiring/soldering problem?\n"));
      //Serial.println(F("\nerrorCode: ") << hex << showbase);
      //Serial.println(sd.card()->errorCode());
      //Serial.println(F(", errorData: ") << int(sd.card()->errorData());
      //Serial.println(noshowbase);
      sd.initErrorHalt();
    }
    Serial.println(F("\nCard successfully initialized.\n"));
    if (sd.vol()->fatType() == 0) {
      Serial.println(F("Can't find a valid FAT16/FAT32 partition.\n"));
      sd.initErrorHalt();
    }
    if (!sd.vwd()->isOpen()) {
      Serial.println(F("Can't open root directory.\n"));
      sd.initErrorHalt();
    }
    Serial.println(F("Can't determine error type\n"));
    sd.initErrorHalt();
  }
  Serial.println(F("Card successfully initialized."));

  getFile();

  //Serial.println(F("Enabling 2s watchdog"));
  /* Watchdog is set to 2s.
   *  We tick every 10ms so initially it was set to 60ms, however the watchdog stays enabled
   *  after reboot, and since the code takes more than 60ms to come back up we ended up in a boot loop.
   */
  //wdt_enable(WDTO_2S);

}

void getFile()
{
    const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
    char fileName[13] = FILE_BASE_NAME "00.csv";

    // Find an unused file name.
  if (BASE_NAME_SIZE > 6) {
    sd.errorHalt(F("FILE_BASE_NAME too long"));
  }
  while (sd.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      sd.errorHalt(F("Can't create file name. May have used them all."));
    }
  }

  Serial.print(F("Trying to create file "));
  Serial.println(fileName);

  if (!file.open(fileName, O_CREAT | O_WRITE | O_EXCL)) {
      sd.errorHalt(F("file.open failed"));
    }

  file.println(F("Time/ms,acc_x,acc_y,acc_z,gyr_x,gyr_y,gyr_z"));

    // Force data to SD and update the directory entry to avoid data loss.
  if (!file.sync() || file.getWriteError()) {
    sd.errorHalt(F("write error"));
  }
  Serial.print(F("File opened; "));
  Serial.println(fileName);

}

void loop() {
  // put your main code here, to run repeatedly:
 // wdt_reset(); //reset watchdog
  // wait for MPU interrupt or extra packet(s) available

    int loopTO = 0;

    while (!mpuInterrupt && fifoCount < packetSize) {
        if (loopTO++ > 100000)
        {
          Serial.println(F("mpuInterrupt died?"));
          loopTO=0;
        }
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        loopTO=0;
        while (fifoCount < packetSize)
        {
          fifoCount = mpu.getFIFOCount();
          if (loopTO++ > 100000)
          {
            Serial.println(F("fifo no longer getting data?"));
            loopTO=0;
          }
        }

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        mpu.dmpGetAccel(&aa, fifoBuffer);

        //Gyro data is in the packet that comes back. More easily obtained using
        //dmpGetGyro(int32_t *data, const uint8_t* packet)
        //or dmpGetGyro(VectorInt16 *v, const uint8_t* packet)
        //These take the same parameters as the two versions of dmpGetAccel
        mpu.dmpGetGyro(&gyro, fifoBuffer);

        file.print(millis());
        file.print(",");
        file.print(aa.x);
        file.print(",");
        file.print(aa.y);
        file.print(",");
        file.print(aa.z);
        file.print(",");
        file.print(gyro.x);
        file.print(",");
        file.print(gyro.y);
        file.print(",");
        file.println(gyro.z);

        //Either sync here or in the 100th iteration bit.
        if (!file.sync() || file.getWriteError()) {
          sd.errorHalt(F("write error"));
        }

        if (sd_writes_since_flush++ > 10) //was 100 at 100Hz but at 10Hz that gets silly
        {
           // Force data to SD and update the directory entry to avoid data loss.
           sd_writes_since_flush = 0;
          /*
          if (!file.sync() || file.getWriteError()) {
            sd.errorHalt(F("write error"));
          }
          */
          //Also output so we know something's happening
          Serial.print(millis());

        Serial.print("\t");
        Serial.print(aa.x);
        Serial.print("\t");
        Serial.print(aa.y);
        Serial.print("\t");
        Serial.print(aa.z);
        Serial.print("\t");
        Serial.print(gyro.x);
        Serial.print("\t");
        Serial.print(gyro.y);
        Serial.print("\t");
        Serial.println(gyro.z);

        //Force a crash after 10s to test the watchdog
        //if (crash_timer++>10) while(1);

        }
        /*
        Serial.print(millis());

        Serial.print("\t");
        Serial.print(aa.x);
        Serial.print("\t");
        Serial.print(aa.y);
        Serial.print("\t");
        Serial.print(aa.z);
        Serial.print("\t");
        Serial.print(gyro.x);
        Serial.print("\t");
        Serial.print(gyro.y);
        Serial.print("\t");
        Serial.println(gyro.z);
*/
        // blink LED to indicate activity
        //blinkState = !blinkState;
        //digitalWrite(LED_PIN, blinkState);
    }

}

```

# Answer
> 2 votes
This seems to be fixed. I've connected the modules together using short soldered leads rather than the breadboard and it's just run for 18 and a half hours before I decided to stop the test. Previously the maximum run time was less than an hour. So even with SPI at sixteenth speed and I2C at 50kHz instead of 400kHz, it seems a breadboard is too flaky when both comms mechanisms are in use. I note I didn't actually say I was on breadboard- in hindsight maybe that would've prompted immediate comment but I thought at slow data rates I'd be ruling out such things.

# Answer
> 0 votes
It seems that, from my experiments, this has something more to do with the serial buffer. If you print more than 55 characters in Serial.print (); using the MPU6050 and the SDCard, stack overflow errors occur. Try limit the buffer to 55 using the snprintf(); function; instead of Serial.print(); directly. Or make the serial output divided by 55 if your serial output is more than 55 per line.

# Answer
> 0 votes
I had a similar problem with an SD-Card and CAN-BUS Module on an Arduino Mega Pro Mini.

My solution was to add a 470uF capacitor between VCC and GND. Problem solved!

That was the only capacitor I tried, maybe a smaller value would have done the job. My project used about 200mA.

What I found surprising was that I had to add this capacitor when I used the USB from my PC for the power supply. The PC power supply and motherboard are high quality.

When I powered my project with a linear regulator (12V to 5V) and a switching converter all worked fine. But both had already a 470uF capacitor on the 5V side.

It's obvious that this won't be the answer in all scenarios. But it might be one of the possible answers for a system which hangs for no obvious reason.

---
Tags: i2c, spi, arduino-pro-mini, sd-card, mpu6050
---


title: OLED DISPLAY USING SPI

text:
# Question
Title: OLED DISPLAY USING SPI
My display is not responding to this code. Help please

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

#define OLED_MOSI 10
#define OLED_CLK 9
#define OLED_DC 12
#define OLED_CS 13
#define OLED_RESET 11
Adafruit_SSD1306 display(OLED_MOSI,OLED_CLK,OLED_DC,OLED_CS,OLED_RESET);

void setup(){
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();

  display.setTextSize(1);
  display.setCursor(30,30);
  display.print("Hello WOrld");
  display.display();
  }

  void loop(){

    }

```

# Answer
> 1 votes
Pin definitions in your code seem to be mixed up. If Adafruit example works fine with your setup, you should keep the pin definitions Adarfruit uses:

```
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

```

Also, you are using a deprecated constructor. It is recommended to use a constructor which explicitly specifies display size.

---
Tags: arduino-uno, spi
---


# Question
Title: Problems when racing multiple IR controlled Arduino robots
We are attempting to race 3 IR-controlled Arduino robots (Elegoo IR kit), but the IR signal from each remote seems to be picked up by all three receivers. It is possible to create a unique bond between each IR remote and its receiver? Lego Mindstorms IR remote has channels to solve this problem. Anything I can do with Arduino?

# Answer
> 0 votes
Not familiar with Elegoo kit... Question is are they using 1 way or 2 way communication? If they use 1 way communication(which is most likely) there's not much you can do since multiple IR signals interfere with each other, and you would need the toys to send back acknowledge signals to the controller, to do error correction... In that case the most you can do is give them each a unique id, and make them ignore anything else then commands associated with their unique id.

If they do 2 way communication you can also make the controller only send a command when a button is pressed, and when it's released, instead of continuous transmission, while also making sure that the command is understood by the receiver. That minimizes interference for other controllers. And if the command was not understood then wait random milliseconds, and repeat it until the receiver understands it.

# Answer
> 0 votes
IR remote signals are OOK-modulated with different base frequencies (the most common are 36 kHz, 38 kHz and 40 kHz). Elegoo seem to use 38 kHz transmitters/receivers, so if you manage to find 36/40 kHz devices, you'll get 3 channels with somewhat reduced interference.

---
Tags: ir, infrared
---


# Question
Title: Maximum power rating for Arduino UNO revision 2 (SMD)
I have located the 5V voltage regulator chip on my Arduino board which I am hoping to use to power an attached device (which draws up to 500 mA at 5V). The chip is next to the plug for the external voltage supply. It says: `ON RUX 117-5`. It looks like it's in a SOT−223 package (body about 6.1 by 3.4mm).

I used this page to shows 3 different possible voltage regulators from ON Semiconductors: https://www.mouser.co.uk/ON-Semiconductor/Semiconductors/Power-Management-ICs/Voltage-Regulators-Voltage-Controllers/LDO-Voltage-Regulators/\_/N-5cgac?P=1z0wa29Z1z0xwtvZ1z0zlrjZ1ywvc7yZ1yxz1yoZ1ywvc5z

This gives two unique data sheets for NCP1117LP and NCP1117, NCV1117. But this is where I'm stuck. They look pretty similar but not exactly the same data sheets. Also I don't know what RUX stands for, perhaps this is important in figuring out what power rating the Arduino 5V line has. Additionally the mouser.co.uk site says they're in SOT-223-3 packages but then gives dimensions which a) aren't the dimensions of the chip I have and b) are the dimensions of the SOT-223-4 package (6.3mm wide instead of the ~6.1 mm I have).

I don't care about the dimensions but I would like to correctly identify the chip on the Arduino board to be able to know what power I can draw from it before it shuts itself down.

# Answer
> 2 votes
The Arduno UNO SMD R2 uses an MCP33269 not an LM1117. What you have is probably some cheap Chinese clone of the Arduino, and in that case the regulator will be the cheapest Chinese copy of the LM1117 available. It's impossible to tell what the specs of that specific chip are. Suffice it to say, though, that the specs of the chip are pretty much irrelevant since they rely on good heatsinking, which you most certainly don't have on a little Arduino board.

500mA, though, is a lot to push through a linear regulator like that, and when running from batteries the excess power loss imposed by the regulator will be a major factor in longevity.

You are better off investing in a proper switching regulator (such as a UBEC from a model aircraft supplier like Hobbyking).

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


# Question
Title: PUT request: PHP code to Arduino HTTPClient
I'm uploading a file to Azure blob storage using REST API request. The file uploaded successfully using PHP curl request. But when I transfer the code into ESP32 HTTP client I'm getting an Authentication error. I also verify the HMAC key generated by the ESP32 Arduino code in PHP code. I'm thinking that I'm missing something in adding header. Here is my PHP code :

```
       $header = array (
        "x-ms-blob-type: BlockBlob",
        "x-ms-date: " . $date,
        "x-ms-version: " . $version,
        "Authorization: SharedKey account_name:" . $signature_str,
        "Content-Type: text/plain; charset=UTF-8",
        "Content-Length: " . strlen($fdata),
        );

    $url =  "https://acount_name.blob.core.windows.net/container/test.txt";
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fdata);
    curl_setopt ( $ch, CURLOPT_HEADER, True );
    echo($ch);
    curl_exec ( $ch );

```

and here is the corresponding Arduino IDE code:

```
    String sig = get_hmac();
      Serial.println(sig);

      if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
        HTTPClient http;
        http.begin("https://account_name.blob.core.windows.net/container/test.txt");  //Specify destination for HTTP request

        http.addHeader("x-ms-blob-type", "BlockBlob");
        http.addHeader("x-ms-date", Date);
        http.addHeader("x-ms-version", "2018-03-28");
        http.addHeader("Authorization", "SharedKey account_name:"+sig);
        http.addHeader("Content-Type", "text/plain; charset=UTF-8");
        http.addHeader("Content-Length",  "20");

        int httpResponseCode = http.PUT(d);
        if (httpResponseCode > 0) {
          String response = http.getString();
          Serial.println(httpResponseCode);
          Serial.println(response);
        } else {
          Serial.print("Error on sending POST: ");
          Serial.println(httpResponseCode);
        }
        http.end();  //Free resources
      } else {
        Serial.println("Error in WiFi connection");
      }

```

The error I'm getting is :

> The MAC signature found in the HTTP request 'sVrSFpplX+Gkcb4R/iSDf6eqUP4srkZuVD68/pAeYwE=' is not the same as any computed signature.....

Although the HMAC signature created from same String works in PHP here is the reference page of the API: https://docs.microsoft.com/en-us/rest/api/storageservices/put-blob Thanks

# Answer
I got clue from @esoterik answer and manage to send request successfully. The problem were in adding header parameter:

```
 http.addHeader("Content-Length",  "20");

```

This duplicate the header( 2nd one added in PUT method). I just comment it and the code works. Thanks for every one response
> 2 votes

---
Tags: esp32, http
---


# Question
Title: Arduino UNO and TB67H303HG Ic driver: Wiring question
I would like to control the TB67H303HG (a full bridge driver IC for DC motor adopting MOS in output transistor) with my Arduino UNO. This is its datasheet.

I was thinking to connect:

* **PIN 3 INPUT** to Arduino Digital Output 13 and set it to LOW to use the direct PWM mode
* **PIN 5 Vref** to 24VDC
* **PIN 6 Vcc** to 24VDC
* **PIN 7 STBY** to Arduino pin 8
* **PIN 8 IN1** to Arduino Pin 12
* **PIN 9 IN2** to Arduino Pin 11
* **PIN 16 OUT1A** and **12 OUT1B** in parallel to the Motor
* **PIN 14 OUT2A** and **10 OUT2B** in parallel to the Motor
* **PIN 13** and **17** to GND
* **PIN 20 Vcc** to 24VDC
* **PIN 22 PWM** to Arduino PWM 10

I do not know if I'm wrong, but I think I should use IN1 and IN2 to select the motor spin rotation and the Pin 12 PWM to change the velocity by setting the Arduino pin 10 with the PWM output from 0 to 255. Is it correct?

Can you tell me if the wiring is correct? Thank you a lot!

# Answer
> 3 votes
The Vref potential should not be 24V. As mentionned in the datasheet:

Vref = 0.3V to 1.95V depending on what you want.

---
Tags: arduino-uno, motor, wires
---


title: Programming options other than C++

text:
# Question
Title: Programming options other than C++
Can I program my Arduino using any programming language other than C++? If so, which programming languages? What software would I need for compiling and loading my code onto the Arduino?

# Answer
> 5 votes
Some commonly known ones:

In theory you should be able to extend avr-gcc to support other languages, though this is no small undertaking. I should also caveat that support for languages other than C typically comes with some fairly weighty restrictions on language components -- for instance, even with C++ it's discouraged to be instantiating new objects as `malloc` and `free` are extremely expensive in both memory space and cycles.

Besides using Google, the following references are applicable Click Here.

# Answer
> 9 votes
In theory, any compiler which outputs AVR assembly could be used (modulo limitations on code size, ram usage etc).

AVR backends exist for both LLVM and GCC -- so in theory, with some effort, most languages which are supported by LLVM and GCC's front-ends could be compiled to AVR. A big question will be library support, etc.

Never the less, here's a couple of odd choices for the spirit of the question, rather than its letter \[1\].

* AMForth, a forth dialect can be flashed onto an Arduino.
* AVR-Ada: Ada for AVR micro-controllers.
* BASIC: Bring back the Goto!

Oh, and you could write raw AVR Assembly!

\[1\]- I Haven't tried these though!

# Answer
> 2 votes
There are also some people working on **Javascript** node.js based systems. One that is already publicly available is Espruino and another is Tessel which launches in spring 2014.

# Answer
> 2 votes
I'm surprised that nobody has mentioned AVR Assembly!

Assembly is not often thought to be the most interesting, or even an easy method of programming, but it's nonetheless, 100% possible with all AVR based arduino. SAM boards will likely not work with this flavor, but it's still possible to use assembly in their programming.

All Arduino boards (as of posting) support assembly programming via Atmel Studio, The SDK made for Atmel based chips.

Assembly is naitively supported by all Atmel devices, and requires no boot loader in order to work, so all programs are inherently real-time.

# Answer
> 1 votes
Because avr-g++ should support all standard C / C++ constructs it is possible to code inline assembly. More info on this arduino.cc forum thread

---
Tags: programming, software
---


title: Remembering a colour

text:
# Question
Title: Remembering a colour
Hey guys I have a led grid. it's 8 sides that are addressable with the bytes `'1'` through `'8'`. (a Kinect is sending these bytes through processing) I have also creates three buttons in processing that change the colour of the leds. (`'R'`,`'G'`,`'B'`).

I'm stuck in the code, my code now when receiving the bytes: `'R'`, `'G'` or `'B'` changes all leds to that colour. instead of remembering the colour and only lighting up the sides determined by the `'1'`, `'2'`, `'3'`, `'4'`, `'5'`, `'6'`, `'7'`, `'8'` values.

I need it to remember the chosen R,G,B colour until another colour is chosen and only use the bytes `'1'`, `'2'`, `'3'`, `'4'`, `'5'`, `'6'`, `'7'`, `'8'` to select what side of the grid to light up.

Here is my code so far:

```
#include <FastLED.h>

#define LED_PIN     6
#define NUM_LEDS    360

CRGB leds[NUM_LEDS];
CRGB saved_color;

void setup()
{
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(50);

  Serial.begin(9600);

  FastLED.clear();
  FastLED.show();

}

void loop()
{

  if (Serial.available() > 1)
  {
    int incomingByte = Serial.read();

    if (incomingByte > '0' && incomingByte < '9')
    {
      FastLED.clear();
    }

    if (incomingByte == 'R') {
      saved_color = CRGB(255, 0, 0);
    }
    else if (incomingByte == 'G') {
      saved_color = CRGB(0, 255, 0);
    }
    else if (incomingByte == 'B') {
      saved_color = CRGB(0, 0, 255);

    }

    if (incomingByte == '1')
      for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '2')
      for (int i = 44; i <= 89; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '3')
      for (int i = 90; i <= 134; i++) {
        leds[i] = saved_color;
      }

    else if (incomingByte == '4')
      for (int i = 135; i <= 179; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '5')
      for (int i = 180; i <= 224; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '6')
      for (int i = 225; i <= 269; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '7')
      for (int i = 270; i <= 314; i++) {
        leds[i] = saved_color;
      }
    else if (incomingByte == '8')
      for (int i = 315; i <= 359; i++) {
        leds[i] = saved_color;

      }

    FastLED.show();
  }
}

```

I'll describe the project a bit more to elaborate. It's a lamp (octagon shape) with 45 leds on the 8 sides. each side is triggered by movement and sends a byte (`'1'`, `'2'`, `'3'`, `'4'`, `'5'`, `'6'`, `'7'`, `'8'`) to turn on one side of the lamp.

I want to be able to select the colour before sending the bytes. so I need arduino to remember the `'R'`, `'G'`, `'B'` bytes and only change when I send the other byte.

# Answer
The array `CRGB leds[NUM_LEDS]` only holds the current state of the LEDs. It is used to push the data out to the LEDs. If you want the code to save one color to use later, you need an extra variable, that can hold the color.

Add a variable at global scope:

```
CRGB saved_color;

```

In the `if` statements for R, G and B you can set this variable to the corresponding value, for example:

```
if(incomingByte == 'R'){
    saved_color = CRGB(255,0,0);
}

```

And in the `if` statements of 1 to 8 you can use this value, for example:

```
if (incomingByte == '1'){
    for (int i = 0; i <= 44; i++) {
        leds[i] = saved_color;
    }
}

```

Note: The above code does not change any LEDs on R, G or B. They just set the color for future operation 1 to 8.
> 1 votes

---
Tags: serial
---


# Question
Title: How does use an arduino like a A/D converter for convert 3 analogue signal from 3 poteciometer to a raspberry?
I am developing a control system in my raspberry, but i have the problem that it doesn't have any analogue port, so if i use an arduino to convert de signal from analogue to digital and after send this signal into a I/o digital port from anduino to raspberry, thas is posible?

my plan was receive the analog signal in arduino and transforms here in a digital signal and after send it by Digital port to rasberry

# Answer
> 1 votes
It is not clear what you mean by “digital port”. The simplest mean to communicate from the Arduino to the Raspberry is to use the Arduino's serial port, which gets into the Raspberry Pi through USB. Just like you would do if you had a PC instead of the Raspberry:

```
/*
 * Continuously report the analog readings on pins A0 through A2.
 */

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

void loop() {
    Serial.print("0 "); Serial.println(analogRead(A0));
    Serial.print("1 "); Serial.println(analogRead(A1));
    Serial.print("2 "); Serial.println(analogRead(A2));
}

```

This program will continuously output a text stream like this:

```
0 145
1 220
2 865
0 142
1 223
...

```

where the first column is the analog channel number and the second column is the ADC value. How you handle this stream on the Raspberry side is up to you.

---
Tags: adc, raspberrypi
---


title: How to make an electronic suction cup?

text:
# Question
Title: How to make an electronic suction cup?
The uArm is a robot arm with a suction cup (or gripper). I'd like to try to make **just the suction part** of it, and I'm wondering what components I'd need?

By the looks of it, I'd need a hobby vacuum pump, but these seem few and far between on UK components sites.

How would I power it? It looks like they're all 12v, and I believe Arduino gives you 5v?

Exact what components would I need? Do I need any shields?

Here's a short video of the suction cup I'd like to copy:

# Answer
> 4 votes
Just a note for those who wonder the same and are in need of a vacuum: In theory, you can use Venturi effect (or Bernoulli's Principle; it's basically the same) to create a vacuum. Or go buy an Aspirator pump. Since English is not my native language it's difficult for me to explain it in my own terms, but I'll try to give you a rough idea anyway. (Google it or feel free to answer with a better explanation).

First you need some flow of a fluid or gas (air from a compressor or water from a household outlet are fine). You pass that flow through left-to-right in a T-pipe (I'll call that the "flow pipe"). This will result in a weak vacuum in the orthogonal pipe (I'll call this the "vacuum pipe"), which you can connect to your suction cup.

The strength of the vacuum depends on the pressure in the "flow pipe". That means a higher velocity of your matter in the "flow pipe" is good (either a stronger compressor or smaller diameter of your flow pipe).

If I understand my physics book correctly, a higher density of the matter in your flow pipe will also produce a stronger vacuum. If you need a really strong vacuum, you could even use a water compressor, i.e. high pressure cleaner; but I suppose even a small air compressor will outperform a household water outlet (and you could toggle it from an Arduino with a relay board).

Since the air in the vacuum pipe expands more than many other materials, you could try to replace it with i.e. oil (be aware you'll pull out some of the air/replacement material at the intersection in aspirator!). This optimization is dangerous with a normal vacuum pump, since these usually break when sucking up fluids into their internals.

Also using an aspirator has the upside of not needing to buy a vacuum pump if you already own a compressor. On the other hand, that setup might be even louder (and possibly less efficient) than a dedicated vacuum pump.

# Answer
> 1 votes
There are two approaches I can think of that would work decently. Either a.) suck air out of a "cup," turning off the pump when done. OR b.) have a valve where the arm pushes one part of the bag against the table to squeeze all the air out of it, and shutting a valve attached to the "cup." Then, to release, the valve could be opened. For the suction cup, I'd personally try making it out of a suction cup hanger like this:

*Source: http://www.amazon.com/Set-Large-Suction-Hanger-Hook/dp/B00439SCZO*

The availability of these might vary by area, so I'm not sure how common these are in the UK. If you find one, make sure that it's pretty thick, with not that large of diameter so it's not too big to work with. I'd then remove the metal hook with pliers and drill a hole in the center. After that, you would need to superglue a tube through the center of the hole and seal it with some caulk.

Like I mentioned earlier, the two options are to a.) suck to grab and turn off pump to release or b.) have arm apply pressure to a flat surface and then shut a valve attached to the tube, creating negative pressure in the suction cup. Then, you could open the valve to balance the pressure and let the item go. I'd personally do the suction approach because, although it is louder and might use a little more electricity, it's a bit easier to build and execute and can grab in the air. I'm going to focus on that.

For the pump approach, build the suction cup (like I said above), attach the tube to one end of the motor with a hose clamp, leave the other hose terminal unconnected, and connect the pump (through a relay) to a 12V 1A+ power supply. You can do this by connecting the + pin of the pump to the "out" (or similar) pin of a relay breakout board, the "in" (or similar) of the relay to the power supply +, and the - of the pump to the power supply's - wire. This will make a circuit similar identical to a switch (the switch being the relay). To connect the relay to the Arduino you will have to connect the relay's logic signal to a pin on the Arduino and then you can just write `HIGH` or `LOW` to turn the pump on and off.

**EDIT:** Forgot to mention, you can use a transistor, too. Also, I illustrated the second method (hopefully it makes this clear).

# Answer
> 0 votes
You can't power things like pumps and motors with the power supply from an Arduino. It doesn't provide nearly enough current. It's meant for providing regulated 5V for low powered logic circuits, and nothing else.

What you can do is use a transistor as a switch to turn on and off the power from a suitable external power supply.

If you find a vacuum pump that runs on 12V, get a 12V power supply with enough current to drive the pump, and then use a **MOSFET transistor** (example link) that will can handle enough current at 12V and can be controlled by a 5V signal to it's gate, and use that to switch the power on and off. Then you'd need a diode to protect the transistor against the reverse current you get from inductors like motors.

---
Tags: robotics
---


# Question
Title: Sending sine wave from MATLAB and reading on Arduino Uno
I am working on timing issues associated with sampling data at high rates and storing it on an SD card (ADC delays, clock drifts and file I/O time). For this experiment, I thought of sending a sinusoidal wave to an analog pin on the Arduino Uno, and have the board read the samples. Can I eliminate the need for a function generator and instead use the Matlab Support Package for Arduino to send the sinusoid to the Arduino? (I guess this would mean two programs simultaneously, a Matlab program for generation of a sinusoid and an Arduino sketch for reading and writing.) I'm new to Matlab, so any help would be greatly appreciated.

# Answer
No, you can't. The Arduino Uno has no analog outputs to start with and, as you guessed, it cannot run two programs at the same time.

Maybe you should search for a solution of the *initial* problem instead. You should be aware that you cannot get consistent timings with `analogRead()`. You will have to read the datasheet of the ATmega328p, especially the section dedicated to the ADC. Then you will configure the ADC yourself, at the register level. It has a feature called “auto-trigger” which is intended to provide perfectly consistent timings. This is what you are looking for.
> 0 votes

---
Tags: arduino-uno, matlab
---


# Question
Title: How to send sensor data from Arduino through NRF24L01 to Raspberry Pi
> I am able to send text from the Arduino wirelessly to RPi. I am now trying to send the sensor data I'm measuring to the Pi. This is what I have below:

```
int moisture = A0;
int temp = 3;

//Skipping the setup and reading of the values

radio.write(&moisture);
radio.write(&temp);

//the above couple lines is where I start having trouble.  The RPi will spit output a seemingly random selection of numbers

```

# Answer
As you haven't said or shown which NRF24L01 library you are using, one can't say for sure what the problem is, but in some NRF24 implementations, the `write()` method accepts (or requires) a second parameter, `len`, giving the number of bytes to be sent. If the library you're using doesn't require that parameter, it could be defaulting it to some value, or could be treating the buffer as a string, to be terminated with a null byte.

Either of those cases could produce erratic results.

Instead of leaving off the second parameter, specify it. For example:

```
radio.write(&moisture, 2);
radio.write(&temp, 2);

```
> 1 votes

# Answer
I recommend you to choose a platform for communication. You don't need to deal with the low level communication. I suggest you to try https://www.mysensors.org/ It helps to wire your sensors, gives you example codes for the chosen sensors for data transfer in the direction to your Pi. There is a well documented API you can build your application on. On the Pi you can use a serial gateway or/and a controller installed. These controllers are written to communicate with your sensors and other nodes. They give graphical web interface to visualize your data and their history. For a controller I recommend to start with https://www.domoticz.com/ or Openhab I think Domoticz is the better choice to start with on Pi.
> 0 votes

# Answer
most likely is that your nrf24l01 library only allow text or string communcaiton, not nuermical data. when you send your measured data, nrf24l01 treats it as text. so what you read is text (text's unicode numbers). I encountered the same problem.
> 0 votes

# Answer
I will suggest you to provide valid size of data with write function for eg radio.write(&moisture,sizeof(moisture)). hope this will work for further explanation of this method www.robofever.in
> 0 votes

---
Tags: arduino-uno, nrf24l01+, wireless, raspberrypi
---


# Question
Title: Having an issue accessing values from a pointer
# Context

This may be more of a C++ question than an arduino specific question, but it's dealing with arduino c++ so I thought I'd start here.

I'm building a class to abstract some simple melody playing that I want for a project. I got everything working in a procedural way, so I started moving everything out to a header and cpp file (still new-ish territory for me).

The general concept is that I want to call a public method on my class to allow my code to play a specific melody. I defined an enum for each melody available and in my `playMelody()` method I'm using a couple of pointers and a switch statement to get the specific frequencies and durations I need to play the specific melody. These frequency and duration values are stored in private arrays in the class.

Here's the header:

```
// MelodyPlayer.h

enum MELODY
{
    SHAVE_AND_A_HAIRCUT = 0,
    IDLE,
    READY,
    PROCESSING,
    COMPLETE,
};

class MelodyPlayer
{
    uint8_t speakerPin;

    int melody_shaveAndAHairCut[9];
    int durations_shaveAndAHairCut[9];
    int *activeMelody;
    int *activeDurations;

    void _playMelody();

public:
    MelodyPlayer(uint8_t speakerPin);
    void playMelody(MELODY name);
};

MelodyPlayer::MelodyPlayer(uint8_t pin)
{
    speakerPin = pin;

    int melody_shaveAndAHairCut[] = {
        NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4, 0};

    int durations_shaveAndAHairCut[] = {
        4, 8, 8, 4, 4, 4, 4, 4, 4};
}

void MelodyPlayer::playMelody(MELODY name)
{
    switch (name)
    {
    case SHAVE_AND_A_HAIRCUT:
        Serial.println("Shave and a hair cut");
        activeMelody = melody_shaveAndAHairCut;
        activeDurations = durations_shaveAndAHairCut;
        break;
    }

    _playMelody();
}

```

And here's the implementation:

```
// MelodyPlayer.cpp

void MelodyPlayer::_playMelody()
{
    Serial.println("Playing Melody");
    // * pulled from the toneMelody arduino example
    for (int thisNote = 0; thisNote < 8; thisNote++)
    {

        int activeDuration = activeDurations[thisNote];
        int noteDuration = 1000 / activeDurations[thisNote];
        int noteFrequency = activeMelody[thisNote];

        Serial.println(thisNote);
        Serial.println(activeDuration);
        Serial.println(noteDuration);
        Serial.println(noteFrequency);

        tone(speakerPin, noteFrequency, noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        noTone(speakerPin);
    }
}

```

And I call it in my `.ino` file like this:

```
MelodyPlayer player = MelodyPlayer(SPEAKER);
player.playMelody(SHAVE_AND_A_HAIR_CUT);

```

# The problem

I'll upload the sketch and everything fires. The problem I'm running into is that when I get to the private `_playMelody()` method the values I get for `activeDuration`, `noteDuration` and `noteFrequency` are all ultra wrong:

I imagine I'm doing something wrong with the setting and getting of the values via the pointer variable I set in the switch statement, but I'm not sure where I'm going wrong.

You can see/pull down the actual code from the abstracting-to-class branch of my repo if you want to dig in.

I've done a similar dynamic-selection-via-pointer in a proof of concept before, but it was procedurally written, not classed. I can't seem to figure out where the difference is :|

Any ideas?

# Answer
> 3 votes
As Majenko mentioned in the comment, you created new local arrays in the constructor, but never put anything in the member arrays of the classes. They have the same name, but are not the same variable. Responsible for creating the new variable is the keyword int. However, you cannot simply assign array values by just omitting the int. Therer are multiple possibilities:

* You can fill the array for each index: `durations_shaveAndAHairCut[0] = 1;`
* You can copy your local array to the member variable with memcpy: `memcpy((void*)this->durations_shaveAndAHairCut, (void*)durations_shaveAndAHairCut, 9*sizeof(int));`
* You can declare the arrays static in the class declaration and initialize it outside of the constructor in MelodyPlayer.cpp:

```
int MelodyPlayer::durations_shaveAndAHairCut[] = {
    4, 8, 8, 4, 4, 4, 4, 4, 4};

```

I prefer the last option.

---
Tags: class, sound, pointer
---


title: Compiled sketch vs text file size

text:
# Question
Title: Compiled sketch vs text file size
OK,so this is my first program written via the Tinkercad utility. I have saved the program as a text file, and it equates to about 22K.

My simple question is, when uploaded / compiled to the actual board, is the size increased or decreased? I plan to use the Nano (32K) If it shrinks or stays roughly the same, I should be OK. However,if it 'bloats' due to extra C code ...

\** As someone used to working with sub routines, arrays and variables, found it a bit of a hassle that everything has to be in one loop, only conditional statement breaking the flow - leastin TinkerCAD. And when you want to control 8 LED outputs, having to switch each one on and off via a digital write line. For example, the four output lines below:

```
11001100
01100110
00110011
10011001

```

... needs 32 digital write commands !! (And whilst the above is 4 lines, there are nearer 150 similar lines in final code, hence it's size)

The way I wrote it using ths above utility was something like:

```
for(counter=0; counter<4; counter){
if (counter==0){
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }
if (counter==1){
    digitalWrite(2, LOW);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(9, LOW);
  }
//etc
}

```

# Answer
> 3 votes
The size of the text file and the size of your compiled code are impossible to relate. The compiled size purely depends on *what* your code consists of, not the size.

To find out how much room your code will take on the chip you need to compile it. The IDE will then tell you how much flash and RAM it takes.

For example:

```
Sketch uses 3730 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 157 bytes (6%) of dynamic memory, leaving 2403 bytes for local variables. Maximum is 2560 bytes.

```

# Answer
> 0 votes
Does counter increase somewhere? As written, it would always be 0, yes?

I would use

```
for(counter=0; counter<4; counter = counter +1){ // or counter++

```

You could store your 8 bits in an array

```
byte ledArray[] = {
0b11001100, // or hex format, 0xCC
0b01100110, // 0x66
0b00110011, // 0x33
0b10011001, // 0x99
};

```

Then use a function call (subroutine by another name) to manipulate the outputs.

---
Tags: arduino-uno, arduino-nano
---


# Question
Title: How is better to store html / java script / in code or in flash on esp32
I have an esp32 which is running a web page together with a java script and using socket I update some values on the web page. I am doing this very fast (like each 50ms). Now I am serving all the html/java script code stored in a string variable but I am wondering which is the best? To store this html in spiff or in code ? and why? Thank you very much

# Answer
Best is to store static files in SPIFFS and serve them with Expires header set, to let the browser cache the html, css, js files and pictures files.

How to build the Expires header:

```
unsigned long expires = now() + SECS_PER_YEAR;
bp.printf(F("Expires: %s, "), dayShortStr(weekday(expires))); // two printfs because ShortStr functions share the buffer
bp.printf(F("%d %s %d 00:00:00 GMT"), day(expires), monthShortStr(month(expires)), year(expires));

```

And use AJAX method to show data on the page. Make the request with `XMLHttpRequest` object:

```
function getData(cmd) {
  var xhr = new XMLHttpRequest();
  xhr.onerror = function(e) {
    alert(xhr.status + " " + xhr.statusText);
  }
  xhr.onload = function(e) {
    showValues(xhr.responseText);
  };
  xhr.open("GET", "http://" + host + ":" + restPort + "/" + cmd, true);
  xhr.send();
}

```

`showValues` would be your function to fill the data into page

In ESP32 build the response as JSON for simple handling of the data in JavaScript.

Here is the WebServer in my project. It uses the basic Arduino Server class, not the esp WebServer. It has `#ifdefs` for SD or SPIFFS. The static files of my project including the js file are here.
> 1 votes

# Answer
It depends on your definition of "better".

Directly inlined in your code will probably be faster - it will be subject to the caching mechanisms of the execution pipeline, whereas SPIFFS will have to make specific SPI calls to read the data from the flash chip at the time it's required. However SPIFFS will be easier to maintain since you are just working with files.

I would probably choose SPIFFS for larger files like graphics or big chunks of Javascript. Things that the client can download once and then cache (as long as your web server supports that kind of functionality - not sure what facilities the default ESP32 web server code has). The rest, the more dynamic things that change often, have as inline string literals.
> 0 votes

---
Tags: esp32
---


title: Arduino simple resistors in series

text:
# Question
Title: Arduino simple resistors in series
Silly question but how would a circuit be set up with Arduino where two different resistors are in series but one has an unknown value (i.e. is just a piece of metal for example) and so how would we be able to find the current through each, collage through each and thus find the value of the resistance of the unknown wire.

# Answer
> 2 votes
Just a math exercise really.

Say you had a 5V source, two Resistors R1 and R2, and an Arduino. 5V - R1 - R2 - Gnd, with R1/R2 junction feeding the Arduino. R1 is unknown.

Vout is what the Arduino sees. Vout = 5VxR2/(R1+R2) Vout (R1+R2) = 5VxR2 R1+R2 = 5VxR2/Vout R1 = 5VxR2/Vout - R2

Vout = ~ 0.00488mV x Analog In reading. (5V/1024) If you select R2 of say 5K ohm, and you determine Vout to be 3V (analogRead returns 615), then you can calculate R1: (5V x 5000)/3V- 5000 = 3333 ohm.

Checking with Vout = 5VxR2/(R1+R2), 5V x 5000/(3333 + 5000) = 3.000V

# Answer
> 1 votes
While CrossRoads' answer got the math sorted out that is likely not the kind of measurement you are aiming for if the unknown resistor has a rather low resistance (*i.e. is just a piece of metal*). Assume the same circuit: 5V - R1 - R2 - GND.

Consider R1 to be a strand of copper wire of ribbon cable, AWG 26, i.e. with a diameter of 0.4 mm (0.016 inch) and a cross section of 0.13 mm², and a length of 3 inches (7.62 mm), being that "piece of metal". Its resistance will be 0.001 Ohms. To have any meaningful readings you'd want to have the other resistor (R2) in the same range otherwise the output voltage of the voltage divider will just be close to VCC (or GND if R1 and R2 are reversed). So assuming R2 to be 0.001 Ohms too, the total resistance of both resistors in series is therefore 0.002 Ohms. Connecting these to a 5V power supply (i.e. a voltage source) we find using Ohm's Law a current of 2500 A - which of course an ordinary Arduino wall plug will not provide. The power supply will either limit the current or its output voltage will be reduced or both - either way not a desirable situation in a measurement setup. Another approach of direct measurement is to apply a known current to the unknown resistor and measure the voltage across it. For any reasonable current that voltage will be rather small (i.e. 1 mV at 1 A) and would need to be amplified before being measured with an Arduino's ADC.

In short, measuring low resistances is difficult and might require a dedicated setup such as a Wheatstone bridge. Best answers are likely to be found at Electrical Engineering but need additional input on measurement range and required accuracy.

---
Tags: arduino-uno
---


# Question
Title: Send serial data at custom voltage using PWM
The Raspberry Pi has 3.3 V logic level and the Arduino has a 5V logic level. It is warned against connecting the Arduino TX to the Pi RX:

> Pi is 3.3v and the Arduino is 5v. Connect the two and you might conjure up some magic blue smoke

I was wondering if without a logic level converter chip like the CD4050, you could use the PWM functionality of the Arduino plus a low-pass-filter to effectively produce 3.3 V TX signals that would be safe for the Pi RX to receive?

I have an Arduino Uno with an ATMega8 according to the schematic. It seems it is possible to change the frequency of the PWM pins to up to 32 kHz. I assume it's possible to use the PWM with a low-pass-filter to effect a 3.3 V and as it runs at 32 kHz this frequency would then be more than enough to support 9600 baud rate. Is this correct? I'm finding it hard to search for "Arduino send serial using PWM". The SoftwareSerial library requires any Digital IO pins so this sounds like it might not allow for using the PWM pins? I've also read SoftwareSerial library can use the Analog Input pins for output i.e. TX?

# Answer
> 0 votes
A simple voltage divider between the Arduino TX and the Pi RX should work to protect the Pi.

And thanks to Juraj's comment, it appears that the Pi's 3.3V high will be enough to trigger the Arduino and it won't need to be boosted up to nearer 5 V.

# Answer
> 0 votes
> I assume it's possible to the change the value of the **voltage** the PWM is producing

This is not possible. PWM cannot output an analog voltage. Instead, it rapidly switches between 5 V and 0 V.

---
Tags: pwm, softwareserial
---


# Question
Title: Using Serial.write() to send a uint32_t send one byte x4 or send 4 bytes x1
In the IRremote library, IR signals are decoded and held in **results.value**. My project uses the NEC protocol which is 32 bits, so the IR code will always be 4 bytes.

```
uint32_t dCodedIR;
//
//  code exists here that we can ignore
//
dCodedIR = results.value

```

This decoded signal is then sent out the serial port to a second MCU which will be waiting for incoming data:

```
while (!Serial.available())  {
}

```

After this, there will ideally be a complete code of 4 bytes waiting in the FIFO. I will allow for times when \< 4 bytes are ready (check for more, timed out? NO:loop YES:reset), but this should rarely happen. So I want to optimize the sending code so that the receiver has the best chance of avoiding split groups. In theory, is it better to write as single bytes and repeat 4 times, or make a 4-byte array to send once?

```
Serial.write(dCodedIR & 255);
Serial.write((dCodedIR >> 8) & 255);
Serial.write((dCodedIR >> 16) & 255);
Serial.write((dCodedIR >> 24) & 255);

```

or

```
byte sendBuf[4];
//
//
sendBuf[3] = (byte) dCodedIR & 255;
sendBuf[2] = (byte) (dCodedIR >> 8) & 255;
sendBuf[1] = (byte) (dCodedIR >> 16) & 255;
sendBuf[0] = (byte) (dCodedIR >> 24) & 255;
Serial.write(sendBuf, 4);

```

(Since there will be plenty of storage space for the code, with performance being the priority, I decided against using **for** loops because updating an index, testing it, and looping would seem to add overhead.)

# Answer
> 2 votes
Unless you are using very high baud rates, (at least higher than 115.2 kb/s), it should make no difference.

The reason is that either version of your code should run faster than the UART. `Serial.write()` doesn't wait for the bytes to be sent out the wire. Instead, it just stores those bytes in a ring buffer that belongs to the HardwareSerial library. When the UART is ready to accept an outbound byte, it triggers an interrupt. The corresponding ISR takes one byte from the ring buffer and handles it to the UART. Since the UART itself is double-buffered, all this happens while the previous byte is being sent.

The end result is that, with either version of your code, you end up with a continuous byte stream. The start bit of the second byte comes *right after* the stop bit of the first byte, and so on. The stream doesn't pause until the full message is sent. That is, unless you have somewhere in your program overly long critical sections that can impose excessive latency to the whole process.

**Side note**: if your MCU is little endian (most Arduinos are), you could also avoid one copy and just do

```
Serial.write((byte *) &dCodedIR, 4);

```

---

**Addendum**: The details may depend on the MCU you are using. On an Uno, or similar AVR-based boards, the UART has no knowledge of the software ring buffer. It rises the `UDRE0` (data register empty) flag whenever it is ready to accept an outbound byte in its sender data register. When there is data in the buffer, the software enables the data register empty interrupt, which is tied to the `UDRE0` flag.

---
Tags: serial, ir, code-optimization
---


# Question
Title: Esp8266 server unreachable. Port doesn't open
I have followed all the instructions provided on http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.

But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...

# Answer
> 1 votes
The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.

My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).

This link can provide some good information about this subject:

http://bbs.espressif.com/viewtopic.php?t=133

# Answer
> -1 votes
I had the same problem and it worked when I disconnected my phone from 3g/4G.

---
Tags: arduino-uno, wifi, esp8266, android
---


# Question
Title: How to use while loop in arduino for infinte loop
I am doing code of esp while switching hotspot for connecting esp i am getting some problem . I am using this line of code:

```
while ((!esp.find("WIFI ")) || (!esp.find("+CWJAP:3")));

```

but it is not working. Anybody please give me alternate how to use this type of looping.

# Answer
The `find` method reads the characters until the searched string is found or a timeout interval is passed.

In your case if the connection is not successful, **the first `find`** will not find "WIFI" and **will read all the input** including the "+CWJAP:3", then on timeout it returns false. The second `find` will wait until timeout and then return false.
> 2 votes

---
Tags: arduino-uno, esp8266
---


# Question
Title: OLED shield for wemos d1 mini pro not staying on
I recently bought a wemos d1 mini pro to toy with wifi and bought a oled shield with it. I've been looking on youtube and github for software and I finally found the software and got it to load onto the board. however, the shield is only on for a fraction of a second and I don't know why.

here is the code

```
#include "SPI.h"
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"

#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 display(OLED_RESET);

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

display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
// init done

display.display();
delay(2000);

// Clear the buffer.
display.clearDisplay();

// text display tests
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,10);
display.println("Hello");
display.println("World");

display.display();
delay(10000);
display.clearDisplay();
}

void loop() {

}

```

here is what it says when uploading

```
Build options changed, rebuilding all
Sketch uses 278084 bytes (26%) of program storage space. Maximum is 1044464
bytes.
Global variables use 27432 bytes (33%) of dynamic memory, leaving 54488
bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.6
2.6
esptool.py v2.6
Serial port COM5
Connecting....
Chip is ESP8266EX
Features: WiFi
MAC: b4:e6:2d:53:19:6b
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 16MB
Flash params set to 0x0290
Compressed 282240 bytes to 204639...

Writing at 0x00000000... (7 %)
Writing at 0x00004000... (15 %)
Writing at 0x00008000... (23 %)
Writing at 0x0000c000... (30 %)
Writing at 0x00010000... (38 %)
Writing at 0x00014000... (46 %)
Writing at 0x00018000... (53 %)
Writing at 0x0001c000... (61 %)
Writing at 0x00020000... (69 %)
Writing at 0x00024000... (76 %)
Writing at 0x00028000... (84 %)
Writing at 0x0002c000... (92 %)
Writing at 0x00030000... (100 %)
Wrote 282240 bytes (204639 compressed) at 0x00000000 in 4.8 seconds
(effective 467.5 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

```

and this is the monitor

```
0⸮~?⸮4⸮!⸮⸮⸮⸮OCAG⸮⸮

```

thank you for your time

# Answer
> -1 votes
I fixed the problem. I was the one who did the soldering so i decided to make the soldering better and now it works. thank you juraj for your time

---
Tags: arduino-uno, esp8266
---


# Question
Title: Dot Matrix Display with Arduino UNO (PROBLEM)
I faced a problem in my graduation project and I hope you can help me to solve it :)

---

My project is connecting Arduino Uno to 16x32 Dot Matrix Display(DMD) and display messages on it from VB.net program. I wrote my VB.net program to convert the input text into 2D binary array. The number of columns depend on the text width. as we know Arduino Uno SRAM is too small just 2 KBytes, so can't receive all the columns and display it.

I tried to receive 100 columns in the Arduino code and display it, then send star `*` to computer to receive the second 100 columns and display it and so on but it didn't work. I see the RX and TX of Arduino LEDs flicker but then nothing gets displayed on the DMD.

Can anyone tell me where is the error part in the code, or if you have another idea to solve this problem :)

**VB.net Code for sending the 2D array `ar(,)`**

```
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        SerialPort2.Open()
        Dim la As String
        If CheckBox1.Checked Then
            la = "arabic"
        Else
            la = "english"
        End If
        SerialPort2.Write("#" + cols.ToString + "#" + "*" + la + "*")
        Dim INDEX As Integer = 0

        While INDEX <= cols
            Dim see As String = SerialPort2.ReadLine().ToString()
            If see = "*" Then
                Dim BUFFER(16) As Byte
                For I = INDEX To INDEX + 100
                    If I < cols Then
                        For J = 0 To rows - 1
                            BUFFER(J) = ar(I, J)
                        Next
                        SerialPort2.Write(BUFFER, 0, 16)
                    End If
                Next
                INDEX += 100
            End If
        End While
        SerialPort2.Close()
End Sub

```

**C++ Code for receiving 100 columns and display them:**

```
#include <SPI.h>
#include <DMD2.h>

SoftDMD dmd(1,1);
void setup() {
  Serial.begin(9600);
  dmd.setBrightness(255);
  dmd.begin();
}
long Wid;
void loop() {
  if(Serial.available()){
    String st = String(Serial.readString());
    Wid = (st.substring(st.indexOf('#')+1, st.lastIndexOf('#'))).toInt();
    //String Language = st.substring(st.indexOf('*')+1, st.lastIndexOf('*'));
  }
  long ind = Wid ;
  while(ind >= 0 ){
    Serial.println("*");
    if(Serial.available()>1 ){
      boolean pixls[16][100];
      getArray(pixls);
      displayArray(pixls);
      ind-=100;
    }
    if(ind >=Wid){
      ind = wid ;
    }
  }
}

void getArray(boolean arr[16][100]){
  byte serialData[16];
  for(int k = 0 ; k < 100 ; k++){
    Serial.readBytes(serialData,16);
    for(int i = 0 ; i < 16 ; i++){
      arr[i][k]= serialData[i];
    }
  }
}

void displayArray(boolean arr[16][100]){
  for(int h = 0 ; h <= 100-33 ; h++){
    for (int i = 0 ,g=h; i < 32 ,g<h+32; i++ ,g++){
      for (int j = 0 ; j < 16 ; j++){
        dmd.setPixel(i,j,(arr[j][g] == 1) ? GRAPHICS_ON : GRAPHICS_OFF);
      }
    }
    delay(100);
  }
}

```

**This VB code works for me when sending just 100 columns of the array:**

```
SerialPort2.Open()

        Dim BUFFER(16) As Byte
        For J = 0 To 100
            For I = 0 To rows - 1
                BUFFER(I) = ar(J, I)
            Next
            SerialPort2.Write(BUFFER, 0, 16)
        Next
        SerialPort2.Close()

```

**C++ code:**

```
#include <SPI.h>
#include <DMD2.h>
SoftDMD dmd(1,1);

void setup() {
  Serial.begin(9600);
  dmd.setBrightness(255);
  dmd.begin();
}
void loop() {
    boolean pixls[16][100];
    for(int i=0 ;i<100 ; i++){
      for(int j=0 ;j<16 ; j++){
        pixls[j][i]=0;
      }
    }
    if(Serial.available()>0){
      getArray(pixls);
      for(int i=0 ; i<100 ; i++)
      {
        displayArray(pixls);
      }
    }
}
void getArray(boolean arr[16][100]){
  byte serialData[16];
  for(int k = 0 ; k < 100 ; k++){
    Serial.readBytes(serialData,16);
    for(int i = 0 ; i < 16 ; i++){
      arr[i][k]= serialData[i];
    }
  }
}

void displayArray(boolean arr[16][100]){
  for(int h = 0 ; h <= 100-33 ; h++){
    for (int i = 0 ,g=h; i < 32 ,g<h+32; i++ ,g++){
      for (int j = 0 ; j < 16 ; j++){
        dmd.setPixel(i,j,(arr[j][g] == 1) ? GRAPHICS_ON : GRAPHICS_OFF);
      }
    }
    delay(100);
  }
}

```

# Answer
```
  boolean pixls[16][100];

```

You are running out of RAM, amongst other possible problems.

That array alone takes 1600 bytes out of 2048 on the Uno. Since you are using Serial that also takes:

* 34 bytes for the HardwareSerial instance (Serial)
* 64 bytes for the Serial transmit buffer
* 64 bytes for the Serial receive buffer
* 4 bytes for the Serial transmit buffer head and tail pointers
* 4 bytes for the Serial receive buffer head and tail pointers

That's another 170 bytes.

```
SoftDMD dmd(1,1);

```

I presume that also uses RAM.

You need to rework. You don't need to store 100 bytes before displaying. How about reading each byte and displaying it? That saves almost 1600 bytes.
> 3 votes

# Answer
You have likely run out of RAM.

The following use up large chunks of your SRAM:

* `pixls` array = 1600 bytes
* Serial = 170 bytes
* DMD \> 64 bytes

This is in addition to all your other variables and function calls.

The problem is that the compiler promotes boolean variables to bytes. So where you need 1600 pixels it takes 1600 bytes. Alternatively, you could pack 8 pixels into that byte. This method would only consume 200 bytes instead of 1600.

Also, I don't understand why you have a 16 by 100 array. From the code I can see that you are using a single DMD which has 32 pixels wide by 16 pixels high. Why send/buffer more pixels than needed? A single DMD would only need an array of 64 bytes.

The Arduino Uno only has 2KB of SRAM.

**Solutions:**

1. **I suggest sending the ASCII text to the Arduino and then letting the font library within SoftDMD convert it to pixels. That is why you are using the DMD2 library.**

However if you want to stick to the approach you have taken:

2. Pack 8 pixels into every byte in the array. This will save 1400 bytes of precious SRAM.
3. Only send one DMD word of data at a time. This will save 1536 bytes of precious SRAM.
4. You could use an Arduino with a greater amount of SRAM.

* Arduino Mega - 8KB SRAM
    * Arduino ZERO - 32KB SRAM
    * Arduino Due - 96KB SRAM
    * Arduino MKR 1000/1010/1400/ZERO - 32KB SRAM
> 2 votes

---
Tags: arduino-uno, serial, c++, array
---


title: Measure position of gear with arduino

text:
# Question
Title: Measure position of gear with arduino
So, my plan is to be able to turn a motor, with a gear on the end, for a certain amount of gear teeth then stop it. I can’t find a data sheet for the motor but it is very fast, brushed and DC. I was thinking putting something like this below the gear so when a tooth goes past, it turns on and off. Like I said before the motor is very fast (faster then being able to see the teeth as it spins) and I don’t think the arduino will be able to read that kind of speed with digital read, I may be wrong. Any suggestions would be appreciated. Thanks.

EDIT: The motor runs off 2 cell or three cell lipo which is 7.4-11.1v, it’s maximum current is 20 amps.

Edit: For anyone wondering how to use the sensor, the datasheet is here and it shows the positions of the collector, emitter, anode and cathode.

# Answer
> 2 votes
If memory serves, the clock speed of an arduino Uno is 16Mhz. Some are faster, some much faster and a few are slower.

Most assembler instructions take around 1-3 clock cycles. A few take more. Assuming an average of 3 ticks per instruction, that translates to executing over 5 million instructions per second.

So, unless your motor is approaching supersonic speeds, the arduino should be able to "keep up" with polling your motor's sensor in your `loop()` function.

If you are doing a few other things in your loop, you might consider using an interrupt to trigger some code when the motor "activates" the sensor. In this case you will unlikely need to worry about the speed of the CPU at all. When using an interrupt, you do not need to worry about polling the state of your sensor inside the `loop()` function.

Always remember to keep the code in your interrupt service routine as short and fast as possible. In this case, probably you would just turn off the motor and return when the interrupt is triggered.

Having said all of that, you will still need to do some work to get the most appropriate implementation as only you know what other things you need to take into account at this time.

One other thing to note is that a single high level instruction will normally equate to more than one assembler instruction. Even a simple statement like `int x = 1000;` will be more than one assembler instruction and thus take more than 1 clock tick. However, if memory serves, the individual instructions generate to execute `x = 1000` will all take just one clock tick.

Others will vary the amount of instructions that are generated to execute them. For example `float x = 1.0;
x = x + 2.0;`

will likely take more instructions to execute than it's integer counterpart: `int x = 1;
x = x + 2`

I hope this helps and enables you to try controlling your motor via Arduino. If not, you can always ask a more specific question later.

---
Tags: ir
---


# Question
Title: (Advice) Home Automation Project (Domotic mobile home)
I have a project that I hope to accomplish in the near future. I want to transform a mobile home into automation mobile home.

The elements that make up my project are the following:

My idea is to supply the home with a solar installation, disregarding their potential (we can discuss the autonomy of the system later, uses and consumptions).

The idea is to keep an Arduino always running in order to monitorize the home and provide remote administration.(like geolocation, camera and sensors control,power management for hardware ...)

The laptop can be out of the system (when I take it with me). It could be connected to a secondary monitor. The docker provide an easy way to charge the laptop, connect devices and provide a WOL utility.

The Arduino could have differents components like Ethernet, own battery, gps... And It could switch on/off the camera and sensors. The laptop could be powered on/off by WOL and administrate remotely.

The camera could have a microSD to save media and it can be manipulated with Arduino by a remote connection. Arduino could get info about sensors too(as proximity).

I have some doubts:

1. Instead of using WOL , we could use Arduino to wake up the laptop?
2. It's possible to connect the laptop and the arduino by wlan or ethernet interface? or we need to wire it (usb...)?

Thanks for the attention, I await your answer.

# Answer
The Arduino is not built or powerful enough to handle things like cameras and high-speed 4g connections for remote administration. I would suggest using something like a Raspberry PI 3 as it would be much better suited to the job. I would recommend asking this question again on the raspberry pi exchange.
> 2 votes

---
Tags: home-automation
---


title: Controller freezes

text:
# Question
Title: Controller freezes
I am using atmega 2560 as main(master) controller and other 5 salve 2 atmega 8 and 3 atmega 328p, there is two device with analogue output connected to main controller atmega 2560 through ads1115 module ,ads1115 converts analogue signal into 16 bit digital data and give it to atmega 2560 via I2C,

also the main controller has serial communication with pc and I2C comm. with salves. and some motors are also connected with controllers.

Now, My issue is that there is one function which reads the data from ads1115 for fix instances and with fix time interval and prints it. for running code for some time lets say 4-5 hour , controller hangs in between that function. and after that no serial communication work. i have to switch of supply to restart the machine.

# Answer
It's hard to say anything for sure without seeing the code, but for a program that freezes using I2C communication, I would seriously suspect the Wire library. This library has a few loops here and there where it waits for a specific condition on the bus, with *no timeout*. See twi.c. If, for whatever reason, the condition never happens, then the program is stuck in the infinite wait.

You could try finding al alternative I2C library or, if you can tolerate the occasional crashes, enable the watchdog in order to get out of the freezes.
> 0 votes

---
Tags: adc, atmega2560
---


# Question
Title: Python - Arduino communication not reliable
I'm trying to establish basic communication between python and my arduino due. I have managed to get a message sent to the arduino and sent back, but the code that achieves this task does not give consistent results. I'm running python 3.5 with pyserial 3.3.

My Arduino Code:

```
String incoming;

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incoming = Serial.readStringUntil('\n');

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incoming);
        }
}

```

My Python Code

```
import serial

arduinoSerialData = serial.Serial("COM5",9600,timeout=1)

print("Initial in waiting:")
print(arduinoSerialData.in_waiting)
print("Initial out waiting:")
print(arduinoSerialData.out_waiting)

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

nummessages =0

while (nummessages<5):
    if (arduinoSerialData.in_waiting>0):
        myData = arduinoSerialData.readline()
        myData = myData.decode('utf-8')
        myData = myData.strip()
        print("The Arduino says:")
        print(myData)
        nummessages=nummessages+1
    elif(arduinoSerialData.out_waiting>0):
        pass
    else:
        arduinoSerialData.write(b'Hello Arduino!\n')

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

print("In Waiting: ")
print(arduinoSerialData.in_waiting)
print("Out Waiting: ")
print(arduinoSerialData.out_waiting)
arduinoSerialData.close()

```

These print statements are largely my failed attempt to diagnose the problem. The "garbage" loops were my attempt to make sure conditions were as identical as possible when the python code starts up. If I start the arduino program running and then call this python program from my command line I get inconsistent results. Sometimes my first call to the python "works" and then others won't, sometime it works several times in a row, and that first line out output where it says "The Arduino Says: I" will have a varying amounts of the "I Received: Hello Arduino" message the arduino was supposed to send. Any Ideas what could be causing this lack of consistency? If I try starting the python code first, the arduino can't even start up.

# Answer
In case other people run into similar issues, I'll lay out what I've found today.

-The inconsistent output was due to the fact that when you open a serial connection with python, it resets the Arduino and so python can send signals without the arduino having finished its setup() function. If I put in a 1 second delay on the python side, inconsistency stops and I no longer run into byte errors at all. I'm looking into alternative means of preventing this reset since the time delay is a deal-breaker for me.

UPDATE: Replacing

```
arduinoSerialData("COM5",9600,timeout=1)

```

with

```
arduinoSerialData = serial.Serial()
arduinoSerialData.port = "COM5"
arduinoSerialData.baudrate = 9600
arduinoSerialData.timeout = 1
arduinoSerialData.setDTR(False)
#arduinoSerialData.setRTS(False)
arduinoSerialData.open()

```

seems to bypass the reset. I included both the setDTR and SetRTS functions here because although setDTR works for DUE, it seems some other Arduino boards need setRTS instead.

-The decode() function has a keyword argument called errors, which can be set to "ignore" if you want the code to just ignore things that can't be interpreted in your desired format. With just this keyword setup, I never got errors but output was inconsistent due to reset.
> 3 votes

# Answer
### Problem:

Arduino being a **microcontroller** ( not a microprocessor ), is **not efficient enough**. If noticed carefully, messages sent to the Serial monitor gets **overlapped if the time interval between 2 messages is less than half a second** !! Also, there is an equal possibility of overlapping of data from Arduino resulting in **garbage data** !!

---

### Solution:

To overcome these, python modules named **Arduino\_Master** and **Arduino\_Master\_Delta** are available.

These modules also help you to **visualize data** in the form of graphs as well as **filter data and remove garbage values**.

**Arduino\_Master is used for approximation and easier interface** whereas **Arduino\_Master\_Delta is used for accurate data representation**!

---

### Links:

Links to their documentation is given below :

Arduino\_Master

Arduino\_Master\_Delta

---

### Examples:

The code for all these can be found in Arduino\_Master\_Delta 's documentation.
> 0 votes

---
Tags: serial, arduino-due, python
---


# Question
Title: How to start a dendrometry dimension build (Dimensions of Trees) for research?
I am looking to build a device that can measure the dendrometry fluctuations of trees (etc). I essentially want to build this https://publiclab.org/notes/kinasmith/09-09-2016/dendrometers to a t but I don't know where to start. I have admittedly pretty limited knowledge of arduino/microcontrollers and microcontroller kits and sensors.

# Answer
The measuring principle, that is describe in that link, is quite cool and simple.

The string is wrapped around the tree. One end is connected to a fixed point (here the casing of the sensor). The other end is connected to a spring, which in turn is again connected to a fixed point. As the tree get's bigger, it will pull at the string. At the first side of the string nothing happens (because it is a fixed point). But the end with the spring will move according to the force of the tree. Force and displacement have a linear relationship for a spring (as long as you don't overload it): `F = k*x` with the force `F`, the spring constant `k` and the displacement `x`.

The displacement of the springs end can be measured with a linear potentiometer. That is just a simple strip of resistive material with a glider, which can be set to any position at the strip. It will create a voltage divider, giving you an analog voltage depending on the position (most potentiometers are linear, but there are also others). Connect both ends of the potentiometer to Vcc (supply voltage) and ground respectively and the glider to an analog pin of the Arduino. Then you can measure the voltage with `analogRead()`.

As jsotola mentioned in his comment: Be sure to use a string, that will not stretch too much, as this will make your measurement less precise.
> 0 votes

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


title: can't return float value from function

text:
# Question
Title: can't return float value from function
I want to put a 2 seconds delay to temperature reading but the `millis()` delay is not applying.

```
#include <OneWire.h>
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

Time t;
LiquidCrystal_I2C lcd(0x27, 16, 2);
DS3231  rtc(SDA, SCL);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

const int OnHour = 23;
const int OnMin = 42;
const int checkTemp = 2000;
const int checkTempinterval = 0;

void setup() {
  Serial.begin(115200);
  pinMode(3, OUTPUT);
  lcd.begin();
  lcd.backlight();
  rtc.begin();
}
void loop() {
  t = rtc.getTime();
  float testTemp;
  testTemp = temperature();
  lcd.setCursor(0,0);
  lcd.print(testTemp);
  lcd.print("   ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print(rtc.getDOWStr());
  lcd.print("   ");
  lcd.print(rtc.getDateStr());
  if(testTemp >= 28){
    digitalWrite(3,HIGH);
  }else{
    digitalWrite(3,LOW);
  }
//  if(t.hour == OnHour && t.min == OnMin){
//    digitalWrite(3,HIGH);
//  }else{
//    digitalWrite(3,LOW);
//  }
}
float temperature(){
  unsigned long currenttime = millis();
  if(currenttime - checkTempinterval >= checkTemp){
  sensors.requestTemperatures();
  float testTemp = sensors.getTempCByIndex(0);
  currenttime = checkTempinterval;
  return testTemp;
  }
}

```

# Answer
I see 2 problems with your code:

1. **Returning a value from a function:** If you want to return a value from a function, you will have to make sure, that in any case the `return x` statement is executed inside the function in the `temperature()` function you currently have this if statement:

```
if(currenttime - checkTempinterval >= checkTemp){

```

Inside of it is the only `return` statement. That means, if the function is called before the next measurement time, the function will not return anything. Normally the compiler gives you at least a warning about that (maybe you have to turn the warnings on in the settings of the Arduino IDE).

Here you also have to think about, what you want to return, if no measurement was actually executed. Do you want to return an error value (for example `-300`; the error value should not be found inside valid data)? Then do so after the `if` statement. Or do you want it to simply return the last measured value? Then declare a variable (either at global scope, meaning outside of any function, or at local scope, meaning inside the function, but static, which means that the value will be retained between the functions executions). Save the measured temperatures to this variable and return it after the `if` statement.

If you do this, also consider what that means for the rest of your code. For example, if you return an error value, currently it will also be displayed by your code.
2. **Doing the `millis()` code correctly:** What you are doing wrong here, it that you update the wrong variable inside the `if` statement. Currently you write the value of `checkTempinterval` (which is the time of the last measurement) to the variable `currenttime`. The variable `currenttime` was declared locally (meaning inside the function) by using

```
unsigned long currenttime = millis();

```

Local variables are only present during the execution of the function, that they are declared in. When the microcontroller has executed the `return` statement, it will throw all local variables away, making the RAM free for other variables. That means currently you are saving a value inside a variable, that get's thrown away directly after it.

What you actually meant to do, was to do it vice versa:

```
checkTempinterval = currenttime;

```

`checkTempinterval` is a global variable. It will stay in RAM during the whole program execution. Since it holds the last measurement time, you write the currenttime to it, when you measure.

**Very important:** Currently `checkTempinterval` is defined as `const int` meaning constant integer. This variable must not be constant, since we want to change the value (update the time of the last measurement). Also you should not use `int` here, because it's value range goes only up to 32767, which is 32 seconds when used with `millis()`. After that, it will overflow to negative values. Better use the type of `millis()` return value: `unsigned long`. It has 4 byte (instead of `int`s 2 byte) and will only overflow after 49 days. If you only use this variable type for things with `millis()`, even this overflow will not be a problem.
> 3 votes

# Answer
You can use the `millis()` function to create a "timer" that will get the sensor reading every 2 seconds. The sketch `BlinkWithoutDelay.ino`, should come with the Arduino IDE, but if not, you can find it here: BlinkWithoutDelay.

I've used that exact sketch with some modifications to display the results on the Serial Monitor instead of blinking an LED. When you are creating something, using the Serial Monitor can help you to De-bug your sketch.

Please read the code comments in the following sketch. Once you have this working with your code, then you could decide if you need a function or not.

```
// Store the last time you checked the sensor.
unsigned long previousMillis = 0;

// interval at which to checked the sensor (milliseconds)
const long interval = 2000;

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

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // Get the current time.
  unsigned long currentMillis = millis();

  // Check to see if it's time to check the sensor reading.
  if (currentMillis - previousMillis >= interval) {
    // save the last time you checked the sensor.
    previousMillis = currentMillis;

    // This is where you add the code that checks the sensor.

    // Test output.
    Serial.println("Checking Sensor");
  }
}

```
> 1 votes

---
Tags: 1-wire, functions
---


# Question
Title: Error conecting raspberry with my arduino in a serial port
Hi i am trying to make a comunication between theses device but when i am trying to run in my raspberry i have the follow error:

> Traceback (most recent call last): File "serial.py", line 1, in import serial File "/home/pi/Desktop/serial.py", line 2, in ser = serial.Serial('/dev/ttyACM0', 9600) AttributeError: 'module' object has no attribute 'Serial'

i have the next code:

```
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

while 1:

    if(ser.in_waiting >0):
        line = ser.readline()
        print(line)

```

If any can help me, i will be thankfull

# Answer
> 2 votes
What's almost certainly happening here is that you've named your file `serial.py`, so the import is trying to load the library from your file within the current working directory.

To fix this problem, simply rename your `serial.py` script to something else, for example `serial_comms.py` or whatever other useful name you want.

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


# Question
Title: How to create a wired ESP8266 range extender?
Context: I have a NETGEAR router on the first story of my home, the range doesn't extend to the ground floor. I do have a cable duct from my router(on the first story) to the ground floor.

Question:

Is it possible to **wire** a Keyes ESP8266 to my router to act as a WiFi range extender?

Note: The length of the cable would be 10 meters.

# Answer
> 1 votes
There's a project that calls itself a "wifi repeater" at

https://github.com/martin-ger/esp\_wifi\_repeater

It includes support for an ENC28J60 ethernet adapter connected via SPI.

It has some serious limitations.

First, it's really a NAT (Network Address Translation) router, not a Wifi extender, though it can effectively extend wifi. However, devices being extended will not be able to communicate with devices on the original network via broadcast or multicast. This will break some applications and many IoT devices.

Also, devices on the original network will not be able to originate connections to devices on the extended network.

But if you just have some devices that only need to talk to the Internet and are a little too far for your router, this should work for them.

Also, the ESP8266 can only get about 5Mbps through it (I'm actually surprised it's that high). You probably won't be able to reliably stream video - definitely not 4K video. It's not a good choice for connecting a television and probably won't work well with security cameras.

Finally, as @Juraj mentioned, it's not an Arduino project. You'll need to install the NON-OS SDK and toolchain to build it. It does include a pre-built image and instructions on how to flash it.

I haven't used it and can't promise that it will work well, but it's the closest thing I'm aware of to what you're looking for.

---
Tags: esp8266, wifi
---


# Question
Title: Constant ADC sampling rate on ESP8266 or ESP32
I want to sample Sound input with either an ESP8266 (preferred) or ESP32. As I'm using a low pass filter anyway, a sample rate of 1000-2000hz would be totally ok. What is more important, is that it is constant. Can I use DMA for that? If so: how? Or should i go via Timer interrupts? I know about the wifi issue on the ESP8266, but I intend to just turn Wifi off as I don't need it for this project.

# Answer
You have several options for controlling the sampling rate.

## Software only

This is the simplest, and the previous answer got it almost right. Here is my take:

```
const SAMPLE_INTERVAL = 500;  // 500 microseconds

void loop() {
    static unsigned long last_sample_time;
    if (micros() - last_sample_time >= SAMPLE_INTERVAL) {  // note 1
         last_sample_time += SAMPLE_INTERVAL;  // note 2
         // Take your sample here.
    }
}

```

**Note 1**: On the AVR-based boards, `millis()` is *not* accurate to the millisecond. It tends to get late, then compensate for this by jumping by two milliseconds at once. For controlling a process that should happen every 1 ms exactly, `millis()` is very clearly *not* suitable. I do not know how good is the ESP8266's `millis()`. It may well be better than the AVR version. However, even a perfect `millis()` will not be good for anything faster than 1 kHz.

The solution to this problem is pretty trivial: just count the time in microseconds instead of milliseconds. The only drawback of using `micros()` is that you cannot measure durations longer than about 71.6 minutes, which in turn means you cannot use it for sampling at any rate slower than 233 µHz. Obviously this is not something you should be concerned about. Note that the `micros()` rollover is not an issue as long as you are sampling faster than the rollover period.

**Note 2**: It is impossible to have a steady sampling rate if it is controlled by software. The best you can hope for is a tight control on the *average* sampling period. This is accomplished by updating `last_sample_time` as

```
last_sample_time += SAMPLE_INTERVAL;

```

Note that this variable holds the time when the last sample was supposed to be taken, not the time it was actually taken. The sample was probably taken a little bit behind schedule, as anything the CPU does takes time. Updating `last_sample_time` this way means that these timing errors *are not cumulative*. They would be cumulative if you did it in the “Blink without delay” style, namely

```
previousMillis = currentMillis;

```

The drawback of this software method is that it inherently has a significant amount of jitter. The program tests the current time only once per loop iteration, and it may have other things to do within that loop that adds to its execution time.

## Software triggered by interrupts

I have never programmer an ESP timer but, if you can, it should provide you better timings than the software-only version. Have the timer deliver an interrupt at the desired sampling period, and use the ISR for triggering the ADC. You may wait for the result inside the ISR, store it in RAM, and set a flag to tell the main loop that a new sample is available, as in

```
volatile int analog_sample;
volatile bool analog_sample_valid;

ISR(whatever_timer_interrupt)
{
    analog_sample = analogRead(ANALOG_PIN);
    analog_sample_valid = true;
}

void loop()
{
    if (analog_sample_valid) {
        int analog_sample_copy = analog_sample;  // note 1
        analog_sample_valid = false;
        // handle analog_sample_copy here
    }
}

```

**Note 1**: On an 8 bit Arduino, you would have to do this with interrupts disabled. You shouldn't need to disable interrupts on a 32 bit platform.

This method should significantly reduce the jitter compared to the software-only version. Now the sampling doesn't have to wait for the program to run through the loop and reach the point when the time is tested. Instead, whatever the program is doing, it will be immediately interrupted for doing the sampling. Well... almost. From time to time it will happen that the interrupt fires when the program is running with interrupts disabled. This may be the case if it is already servicing another interrupt. When this happens, the sampling will have to wait until interrupts are enabled again. You end up with a jitter that is *most of the time* a small fraction of a microsecond, and then occasionally a sample is late by several microseconds.

## Hardware only

On an AVR, you can configure the ADC to be automatically triggered by a timer, or even to automatically trigger itself in the so called “free running mode”. I do not know the specifics of the ADC in the ESP8266. You may want to read the datasheet and see if it offer similar functionality. If you can enable ADC auto-triggering, then you will have *cycle-accurate* timings. The steadiness of your sampling will be just as good as the quartz crystal clocking your MCU. No software solution can ever come close to this level of perfection. The only drawback of this method is that you will have to study the datasheet of your ESP in order to implement it.
> 5 votes

# Answer
Have you looked "BlinkWithoutDelay" sample on Arduino? The most valuable part of it is the following:

```
void loop() {

    unsigned long currentMillis = millis();   // NOTE: 1

    if (currentMillis - previousMillis >= interval) {  // NOTE: 2
         // save the last time you blinked the LED
         previousMillis = currentMillis;  //NOTE: 3
         .. do your thing here ..
    }
}

```

Take into account the places from **NOTE 1** to **NOTE 3** I have marked in comments:

**NOTE 1:**

First thing in the loop where you mainly go is taking current time in millis. Should not take a lot of effort from Arduino to achieve.

**NOTE 2:**

Second thing is a comparison: is there enough time gone to make your thing ( = to take the sample) or not? If it is false, you make another round. If true, make it! Again, no big effort from computer.

**NOTE 3:**

Here you reset the timer, **BEFORE** doing anything else. So, your "sample interval clock" is quite precise, it consists of three little steps inside the computer and it should work in fractions of seconds accuracy (time estimate = (1 / Arduino clock speed) * some machine commands).

The other commands: taking sample, storing or sending it, should happen inside the one millisecond left from these commands. Do make a note, 1000 samples gives you 1ms time and 2000 samples 0.5ms time. This example fits perfectly to the 1000 samples case, as the accuracy of your clock is 1ms. I would go with that, if possible.

The time left, 1ms is quite long as a machine's executing time, but you have to make sure that some other components like a WiFi connection you mentioned, may be harmful for this approach. The other part of code inside the loop cannot take more than 1ms, otherwise it affects to the constant rate. Anything less than 1ms is ok, this algorithm makes no difference between 0.1ms or 0.9ms hard work inside the `if`, the accuracy of 1-10 machine words always holds.

*(I don't know exactly how long command `if` is, nor how long is function `millis()`. If you want to be very precise, you may take these in account, but IMHO you can omit their importance in calculations: whether they take some time or not, anyways the execution of these may be quite well taking the same on every round - in constant time!)*

**SOURCE:**

https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
> 0 votes

---
Tags: esp8266, interrupt, esp32
---