# Question
Title: millis() function always returns same value
I'm trying to program an Arduino MKR1000 and I am using the `millis()` function to emulate a traditional timer. The problem is that any call to `millis()` inside the `debounceTimer()` function returns the same value. I only added the `Serial.print` to debug.

I left out a decent bit of the code to simplify your reading of it. It works by waiting for an interrupt on pin 4 which then calls the `runTimers()` function and that calls the `debounceTimer()` function and within that the `millis()` function is called. The `debouncetimer()` function keeps getting called until the 10 ms has elapsed and then should end the timer. The problem is that the `millis()` function stops returning a value that goes up.

```
#define doorIntPin 4
unsigned char sysEnabled = 0;
unsigned long debounceTimerPlace =0;
unsigned char debounceTimerOn =0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(doorIntPin, doorOpens, LOW);
  interrupts();
}

void loop() {

}
void runTimers(){
  Serial.print('r');
  while(alarmTimerOn || debounceTimerOn || enablingTimerOn){
     if(alarmTimerOn)
      alarmTimer();
    if(enablingTimerOn)
      enablingTimer();
    if(debounceTimerOn)
      debounceTimer();
  }
}

void debounceTimer(){
  unsigned long time = millis()- debounceTimerPlace;
  Serial.println(millis() & 0xFFFF, DEC);
  if(sysEnabled && time> 10){
    debounceTimerOn=0;
  }
}
void doorOpens() {
  Serial.print('o');
  if(!debounceTimerOn){
      debounceTimerPlace = millis();
      debounceTimerOn=1;
  }
  runTimers();
}

```

I suspect that in the background an interrupt is being called than increments the value `millis()` returns and somehow my external interrupt is disabling that. I don't know why this is happening or how to fix it.

Any ideas?

# Answer
> 3 votes
You never exit the ISR, hence all interrupts are disabled. Do the *minimum* work possible within an ISR, and have the main loop outside.

# Answer
> 0 votes
To answer your question about millis(), it uses interrupts to function, and so you can't call it within an ISR. According to this: https://www.arduino.cc/en/Reference/AttachInterrupt, you should be able to use delayMicrosconds() within an ISR, since it (reportedly) doesn't use interrupts.

# Answer
> 0 votes
> The problem is that the millis() function stops returning a value that goes up.

That's right. The value returned by `millis()` is incremented by an ISR which won't be called inside your other ISR.

You can use `micros()` which *will* increment. However that will only be good up to approximately 1 ms. The main rule of ISRs is that you don't attempt to do delays inside them.

---
Tags: millis, mkr1000
---


# Question
Title: Methods to prevent Accelerometer values changing from current spikes
I've connected an Arduino Uno to a MAX7219 IC, which is connected to only one standard 8x8 LED matrix, and an ADXL355 3-axis accelerometer. I use the matrix initially, and turn on all LEDs, while taking the "rest" values for the accelerometer to base all other calculations on. However, what happens is the current spike the LEDs create messes up the values - they become closer to 300, instead of the 230 they settle on when the spike is over. I've tried preventing this by adding up to a 5-second delay between the LEDs turning on and the rest values being measured. However, the problem still persists, though to a somewhat lesser extent.

Are there any methods to prevent this more effectively?

# Answer
Adding a distinct power supply for the MAX7219, as suggested by @jfpoilpret, solved the issue.
> 0 votes

---
Tags: arduino-uno, accelerometer, current
---


# Question
Title: What is the best type of Arduino board for simple delivery robot?
I'm new to arduino, and I want to design a Simple Delivery Robot for Data Center, which has an arm to move items, and it follows line while moving.

I have no idea if there is a special arduino board for these types of robot or I can buy any arduino board.

# Answer
**ANWSER**

I would suggest you to use the Arduino UNO for all the shields that it has. Most Arduinos are so similar that it wont make a difference but the UNO has many shields to it, including a motor/servo shield which is going to be great for your project.

But at the end of the day, it's your project and you can pretty much use any of the boards listed below. They are just advantages and disadvantages of many popular board. Hope it helped you!

**The summary has been removed for the sake of respecting Stack Exchanges rules.**
> 0 votes

# Answer
Arduino UNO is the best arduino board for simple projects. but if you want to add modules like LCD screen and some wireless sensors like bluetooth and RF and you want to make it with more motors then you should probably use Arduino Mega. It is better to use simple DC geared motors.
> 1 votes

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


# Question
Title: Power Arduino Over 9V automatically after being disconnected from USB 5V
Am wondering if there is some way the Arduino can automatically power itself using through the 9v port in case the USB is disconnected, and afterwards if the USB is connected again it stop feeding from the 9v Input.

# Answer
> 1 votes
The anwser is somewhat.

If you connect a 9V battery to Vin, I'll "take over" the power wheter if the USB is connected or not. Note tought that some problems may occur when both are connected at the same time (personnal opinion). See this link for more info.

**So in conclusion, if you have a USB, remove the 9V for power efficiency. Once you include the 9V though, it will take over control of the power on the ARDUINO.**

# Answer
> 3 votes
there is one way you can make it. you can use a temporary capacitor(with a voltage output near to 9v)(or a lipo battery) connected to arduino's voltage input pin and 9v battery connected to arduino with a transistor. whatever program you are uploading to arduino, you can add a code that reads the serial port, and if serial port is not available then it opens the transistor's gate so as the capacitor gets discharged very quickly the 9v battery takes the job.when it gets the serial port again it closes the transistor's gate and arduino stops feeding upon battery and takes power from USB port.

---
Tags: arduino-uno
---


# Question
Title: getting error while trying to compile code for soil moisture sensor
I think the below logic should work but its throwing error

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

void loop() {
  int soil_moisture = analogRead(A0); // read from analog pin A3
//  int soil_moisture = pinMode(AO);
  Serial.print(“analog value: “);
  if (soil_moisture < 30) {
    Serial.println(“Dry soil”);
  }
  if ((soil_moisture > 300) && (soil_moisture < 700)) {
    Serial.println(“Humid soil”);
  }
  if ((soil_moisture > 700) && (soil_moisture < 950)) {
    Serial.println(“water”);
  }
}

```

error i get is

```
Arduino: 1.6.12 (Mac OS X), Board: "Arduino/Genuino Uno"

analog_soil_moisture_v02.ino:16: error: stray '\342' in program
   Serial.print(“analog value: “);
   ^
analog_soil_moisture_v02.ino:16: error: stray '\200' in program
analog_soil_moisture_v02.ino:16: error: stray '\234' in program
analog_soil_moisture_v02.ino:16: error: stray '\342' in program
analog_soil_moisture_v02.ino:16: error: stray '\200' in program
analog_soil_moisture_v02.ino:16: error: stray '\234' in program
analog_soil_moisture_v02.ino:18: error: stray '\342' in program
     Serial.println(“Dry soil”);
     ^
analog_soil_moisture_v02.ino:18: error: stray '\200' in program
analog_soil_moisture_v02.ino:18: error: stray '\234' in program
analog_soil_moisture_v02.ino:18: error: stray '\342' in program
analog_soil_moisture_v02.ino:18: error: stray '\200' in program
analog_soil_moisture_v02.ino:18: error: stray '\235' in program
analog_soil_moisture_v02.ino:21: error: stray '\342' in program
     Serial.println(“Humid soil”);
     ^
analog_soil_moisture_v02.ino:21: error: stray '\200' in program
analog_soil_moisture_v02.ino:21: error: stray '\234' in program
analog_soil_moisture_v02.ino:21: error: stray '\342' in program
analog_soil_moisture_v02.ino:21: error: stray '\200' in program
analog_soil_moisture_v02.ino:21: error: stray '\235' in program
analog_soil_moisture_v02.ino:24: error: stray '\342' in program
     Serial.println(“water”);
     ^
analog_soil_moisture_v02.ino:24: error: stray '\200' in program
analog_soil_moisture_v02.ino:24: error: stray '\234' in program
analog_soil_moisture_v02.ino:24: error: stray '\342' in program
analog_soil_moisture_v02.ino:24: error: stray '\200' in program
analog_soil_moisture_v02.ino:24: error: stray '\235' in program
/Users/ciastro/Documents/Arduino/analog_soil_moisture_v01/analog_soil_moisture_v02.ino/analog_soil_moisture_v02.ino.ino: In function 'void loop()':
analog_soil_moisture_v02.ino:16: error: 'analog' was not declared in this scope
   Serial.print(“analog value: “);
                   ^
analog_soil_moisture_v02.ino:18: error: 'Dry' was not declared in this scope
     Serial.println(“Dry soil”);
                       ^
analog_soil_moisture_v02.ino:21: error: 'Humid' was not declared in this scope
     Serial.println(“Humid soil”);
                       ^
analog_soil_moisture_v02.ino:24: error: 'water' was not declared in this scope
     Serial.println(“water”);
                       ^
exit status 1
stray '\342' in program

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

```

# Answer
> 0 votes
It is because you declared NONE of your variables (`int`, `float`s) (except `soil_moisture`)

You must declare them. This is not Python where you can simply name a variable without declaring its type. Arduino language is based on C/C++.

# Answer
> 3 votes
The actual error you are seeing is caused by the use of incorrect quotes in your program. You most likely copied and pasted the code from a website which has replaced the proper quotes with typeset-standard quotes:

```
    Serial.println(“Humid soil”);

```

should be:

```
    Serial.println("Humid soil");

```

Note the subtle difference in the quite shape. The first set are typesetter's open- and close-quote characters. The latter are just plain double-quotes (shift-2 on a UK keyboard).

There are other special characters in your program that need replacing with the standard ASCII equivalent, as well.

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


title: Matlab interfacing with arduino ERROR

text:
# Question
Title: Matlab interfacing with arduino ERROR
I installed the MATLAB support package for arduino in my MATLAB r2013a today. Now I plugged on my Arduino in my usb port.

And ran the command:

> > a = arduino()
> >
> > Error: Undefined function or variable 'arduino'.

When I get:

> > a = arduino('COM18')
> >
> > Undefined function 'arduino' for input arguments of type 'char'.

I have checked that this package has been installed.

It is grey.

Any help will be appreciated.

Thanks very much

Anupam.

# Answer
Arduino support within MATLAB came with Matlab-2014a onwards, you are using R2013a

Arduino support within SIMULINK came with Matlab-2012a onwards

for your release you can only interact via a simulink model
> 0 votes

---
Tags: matlab
---


title: Stepper motor with HCSR-04 sensor

text:
# Question
Title: Stepper motor with HCSR-04 sensor
I want to make a stepper motor increase and decrease speed working with a HCSR04 sensor. The idea is that if the sensors detects an object the stepper motor is going to decrease, and stop as close as possile to the object.

I have made some code, and it is sorta working..

**My current code looks like this:**

```
if (distance > 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(500); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(500); // Wait
}

if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(2000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(2000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(10000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(10000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

```

**But I thought it could be easier, So I made a function:**

```
void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}

```

Now my question is: Can I manipulate the delayMicroseconds to change if the distance changes? Is there a formula to do so?

**Entire code:**

```
int trigPin = 11;
int echoPin = 10;

void setup()
{
pinMode(trigPin, OUTPUT); //Sensor
pinMode(echoPin, INPUT); //Sensor
pinMode(6,OUTPUT); // Enable
pinMode(13,OUTPUT); // Step
pinMode(12,OUTPUT); // Dir
digitalWrite(6,LOW); // Set Enable low
digitalWrite(5,LOW); // Set Step low
Serial.begin(9600);
}

void loop()
{
//rotateleft();
//Serial.println("ik draai nu exact een rotatie linksom");
//delay(1000);
//rotateright();
//Serial.println("ik draai nu exact een rotatie rechtsom");
//delay(1000);
//velocity();

 //sensor
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(5);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 Serial.print ("cm ");
 Serial.print (distance);

//eigen creatie

if (distance > 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(500); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(500); // Wait
}

if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(2000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(2000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(10000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(10000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

//Own functions
}

void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}

void rotateleft()
{
 digitalWrite(12,HIGH); // Set Dir high
 for(int x = 0; x < 200; x++) // Loop 200 times
  {
    digitalWrite(13,HIGH); // Output high
    delayMicroseconds(1000); // Wait
    digitalWrite(13,LOW); // Output low
    delayMicroseconds(1000); // Wait
   }
  }
  void rotateright()
  {
   digitalWrite(12,LOW); // Set Dir high
   for(int x = 0; x < 200; x++) // Loop 200 times
   {
     digitalWrite(13,HIGH); // Output high
     delayMicroseconds(1000); // Wait
     digitalWrite(13,LOW); // Output low
     delayMicroseconds(1000); // Wait
   }
 }

```

# Answer
> 1 votes
Assuming you have a distance variable containing the distance measured from your sonar sensor in cm. You can use that value to adjust the delay times in between your steps.

**EDIT** Modified code to increase speed when distance increases

```
int time = 0;
int timeWait = 1000; //interval in milliseconds between each distance reading
int maxDelay = 1000;

void velocity(int speed){
   int trim = 10;
   digitalWrite(13,HIGH); // Output high
   delayMicroseconds(maxDelay - speed*trim); // Wait
   digitalWrite(13,LOW); // Output low
   delayMicroseconds(maxDelay - speed*trim); // Wait
}

int readDistance(){
 //code to read distance
 return distance;
}

void setup(){
time = millis();
}

void loop(){
   if(millis()-time > timeWait){ //only read distance if 1000ms has elapsed since the last reading
     time = millis();
     int distance = readDistance(); //your distance reading code;

   }
   velocity(distance);
}`

```

**EDIT 2**
You'll also need something to handle upper and lower limits for delays (i.e. you don't want delayMicroseconds(0) or any negative numbers and you don't want to include extraneous distance readings)

---
Tags: arduino-uno, stepper
---


# Question
Title: RFID-RC522 Can't access sector after writing to trailer block
I'm currently using an Arduino Uno R3 and an RFID-RC522 with https://github.com/miguelbalboa/rfid .

I wrote the following bytes to the trailer block in order to experiment with it:

```
byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA };

```

I wanted to change the default `MFRC522::MIFARE_Key key.keyByte` so I can read and write to the card using a custom key and leave everything unchanged but I cannot access the sector anymore.

What do I have to do to be able to access the sector again? Code:

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

#define SS_PIN 10
#define RST_PIN 9
/*
 * Pin connections for UNO:
 * 9  - RST
 * 10 - SDA
 * 11 - MOSI
 * 12 - MISO
 * 13 - SCK
 */
MFRC522 mfrc522(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key; // will hold card info

// Every 4th block is a trailer block that contains access and security info, modulo 4.
const int blockSize = 16;

int writeBlockNumber = 2; // The block we want to write the data.
int readBlockNumber = 2;
byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA }; // 16 character max
byte readBlockContent[18] = { 0 };

// Will write the data to the block.
int writeBlock(int block, byte data[]) {
  int status;

  if ( (block + 1) % 4 == 0) {
    Serial.println("Warning: Writing on a trailer block!");
    return 0;
  }

  int trailerBlock = block + (4 - block % 4) - 1;
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  status = mfrc522.MIFARE_Write(block, data, blockSize);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("MIFARE_Write() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }
  return MFRC522::STATUS_OK;
}

// Will try to dump the whole card info.
void dumpCard() {
  for(int i = 0; i < blockSize; ++i) {
      Serial.print("Block ");
      Serial.print(i);
      Serial.print(" ");
      if ( readBlock(i, readBlockContent) == MFRC522::STATUS_OK ) {
        printReadBlock();
      }
  }
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

// Will read the block.
// These functions must be called if you wish to read a new card.
//    mfrc522.PICC_HaltA();
//    mfrc522.PCD_StopCrypto1();
int readBlock(int block, byte data[]) {
  int status;
  byte readSize = blockSize + 2;

  int trailerBlock = block + (4 - block % 4) - 1;
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);

  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  status = mfrc522.MIFARE_Read(block, data, &readSize);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("MIFARE_Read() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  return MFRC522::STATUS_OK;
}

// Will print the contents of the readBlockContent.
void printReadBlock() {
  for (int i = 0; i < blockSize; ++i) {
    Serial.print(readBlockContent[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" -> ");
  for (int i = 0; i < blockSize; ++i) {
    Serial.write(readBlockContent[i]);
  }

  Serial.println();
}

// Will print the card id that is stored in mfrc522.uid.uidByte
void printCardUid() {
  Serial.print("Card ID: ");
  for (int i = 0; i < mfrc522.uid.size; ++i) {
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void setup() {
  Serial.begin(9600);
  while (!Serial); // Wait for serial.
  SPI.begin();

  mfrc522.PCD_Init();
  Serial.println("Initialized...");

  // default access key STANDARD KEY 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
  for (int i = 0; i < 6; ++i) {
    key.keyByte[i] = 0xFF;
  }
}

void loop() {
  if ( ! mfrc522.PICC_IsNewCardPresent() ) {
      return;  // No card present, continue.
  }
  if ( ! mfrc522.PICC_ReadCardSerial() ) {
      // On success this function will return 1 and set the uid struct mfrc522.uid
      return;
  }

  printCardUid();

  // Write data to block.
//  writeBlock(15, writeBlockContent);
//  if ( readBlock(13, readBlockContent) == MFRC522::STATUS_OK )
//    printReadBlock();

  dumpCard();

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

```

# Answer
And I quote:

> With each memory access the internal logic verifies the format of the access conditions. If it detects a format violation the whole sector is irreversibly blocked.

The only thing that can get you locked out of a sector is incorrectly formatted access bits. As long as you didn't touch those, the sector should still be accessible.

It looks like you tried to change key A *and* key B. With the transport config, the contents of the sector trailer can only be altered if you authenticate the sector with Key A. Is that what you did? Lets continue then. Since you left the access bits unchanged (right?), it means only key A has R/W access to all blocks (except the manufacturer's) and key B, since it's still readable, can be used to authenticate but can't be used to access blocks. So, if your key change was successful, then you should be able to access the sector with your new key A i.e. `{0,0,0,0,0,0}`. If it wasn't successful (maybe because authentication failed), then the default key A should still be valid.
> 1 votes

---
Tags: arduino-uno, rfid
---


title: Gradual change of PWM motor control

text:
# Question
Title: Gradual change of PWM motor control
Can someone please tell me what I'm doing wrong?

The motor's not turning at all, never mind changing speed.

# Answer
> 1 votes
It looks like you are attempting to perform hardware PWM on an Analog Input Pin.

Assuming that you are using an Arduino Uno, try changing your first line of code to use one of the digital output pins which support PWM. You can use any of pins 3, 5, 6, 9, 10, or 11. Then connect that pin to your motor. (Note that you will likely have to use a transistor or driver circuit between the pin and the motor since the motor may well require more current to operate than the Arduino output can directly supply.)

If you are using a different Arduino other than the Uno, look at the documentation to find one of the PWM pins and try using that.

# Answer
> 1 votes
You should copy and paste the text of the code into your question, not a screenshot of it. Then we can copy and paste the problem lines into the answer.

You are varying up and down the variable `motorVoltage` in two loops. However you are not then doing an `analogWrite` with the new value. It should be more like this:

```
while (motorVoltage <= 255)
  {
  analogWrite (motorPower, motorVoltage);
  motorVoltage++;
  delay (200);
  }

```

# Answer
> 0 votes
A0 is an analog input. You can't output from it. You can only output on analog input pins by using defining them as 14,15,16...

For the best result, try changing the motor pin to something like pins 9, 10 or 11. They are my favorite PWM pins.

---
Tags: motor
---


title: Arduino Micro Power Questions

text:
# Question
Title: Arduino Micro Power Questions
I have a few questions about the Arduino Micro circuit:

* If I can provide a steady 5 V source (connected to `+5V`), then I don't need to use the voltage regulator module (including the selector) of the circuit. Correct?
* If I can provide a steady 5 V source (connected to `+5V`), then I don't need to connect anything to `VIN`. Correct? If that's right, should I connect it (`VIN`) to `GND`, instead of leaving it floating?
* If I'm not using `+3.3V`, should I connect it to `GND` (instead of leaving it floating)?
* If I'm powering off of *just* USB, then I can connect `+5V` to `VUSB`. Correct?

Schematic below for reference:

# Answer
> 1 votes
> If I'm powering off of just USB, then I can connect +5V to VUSB. Correct?

If you are powering off USB leave everything alone. See the schematic:

The blue line added by me shows what is going on. The VBUS signal from the USB connector goes through a 500 mA resettable fuse (to protect the USB port from overloads). Then it goes to the P-channel MOSFET (FDN340P) which makes a decision about whether to switch on and connect VUSB to +5V signal. It does so if VIN is low, making the MOSFET conduct. If VIN is high (which it would be if you had power into the VIN part of the board) then it disconnects the USB from the +5V line.

---

> If I'm not using +3.3V, should I connect it to GND (instead of leaving it floating)?

Definitely not. The 3.3V line is an output from the 3V3 voltage regulator. To connect it to ground would heat it up and destroy it.

---

> If I can provide a steady 5 V source (connected to +5V), then I don't need to connect anything to VIN. Correct? If that's right, should I connect it (VIN) to GND, instead of leaving it floating?

No, VIN is already connected to ground via a 10k resistor (see schematic above) and thus it is not floating.

---
Tags: power, usb, arduino-micro
---


# Question
Title: How to correctly read a string from Arduino serial port?
I'm trying to communicate with my Arduiono UNO via USB serial port, more precisely I'm trying to read a string like 125,0, I know it's full of article out there about this, but belive me I've tryied more or less everything, now I got a NODEJS server on a Raspberry Pi that looks like:

```
var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM1", { baudrate: 115200 });

server.listen(8080);
app.use(express.static('public'));

var brightness1 = 0;
var brightness2 = 0;
var string;

io.sockets.on('connection', function (socket) {
    socket.on('led', function (data) {
        brightness1 = data.value1;
        brightness2 = data.value2;
        string = brightness1 +","+brightness2;
        var buf = new Buffer(1);
        buf.write(string);
        serialPort.write(buf);
        console.log(buf);
        console.log(string);
        io.sockets.emit('led', {value1: brightness1, value2: brightness2});

    });

```

So based on that, I'm sending a string over the serial and the console log showed above gives me that:

```
<Buffer 32>    //console.log(buf);
23,0           //console.log(string);

```

Wich I think it should be ok because I'm sending what I need a 32 and a 0, also if i don't know what it means the

Arduino side I used the sketch provided here and retouch it a bit based on my needs:

```
void setup()
{
  Serial.begin(115200);
}
void loop()
{
  while(!Serial.available());   //wait until a byte was received
      Serial.println(Serial.read());
      int a = Serial.parseInt();
      int b = Serial.parseInt();
      Serial.println(a);
      Serial.println(b);
      //analogWrite(3, a);
}

```

but the result of my Serial.print() are really incongruents, something like: 5--2224, which is totally nosense, my question so is WHY? Where I'm getting wrong? I read a lot around, am I missing something?

# Answer
> 2 votes
This is a common (and my favorite) approach:

* Choose an “end of message” character. CR or LF can be good choices, especially if you want to test your program with a terminal emulator.
* On the Arduino, buffer all the received bytes until you see the end of message.
* When you see the end of message, handle the buffer to a function that will parse and process it.

I would avoid `parseInt()` for anything but the simplest tests, because it is both blocking and sensitive to the timing of the input.

For an example, you can take a look at this Simple Arduino command line interpreter (look at `loop()`). It's non blocking, so you can add background processing to perform while waiting for input characters.

# Answer
> 0 votes
I fully agree here with edgar Bonet.
I only want to add a link to a library I have written that does a line by line (based on end message CR and/or LF)
SerialStringReader This library contains examples.
Note that for many reasons the library uses null terminated strinsg (also known as char arrays) and not the Arduino String class

# Answer
> 0 votes
> How to correctly read a string from Arduino serial port?

You can use the function `Serial.readString()`. It will return a string that you typed from the serial monitor.

---
Tags: arduino-uno, serial, usb, node.js
---


# Question
Title: Programmatically Upload Arduino Sketch From Android App
I am attempting to build an Android app from which I can can upload a .hex file to my Arduino(Leonardo). I am aware of a few apps in the Google Play store that are capable of this functionality but I can't seem to find any actionable resources on how to go about doing this. I am aware that the desktop Arduino IDE uses AVRDude to perform the upload but I don't believe AVRDude is available on Android so I'm at a complete loss here. Does anyone know how I would go about accomplishing this?

After some more searching I now know that the Leonardo(ATMega32u4) uses the AVR109 Protocol to flash new programs onto the hardware but I'm still at a complete loss as to what that process is and how I'd reproduce it in Java.

# Answer
> 2 votes
If I wanted to do this for a conventional Arduino I'd start by figuring out the operations against a serial API to talk to the bootloader, and perhaps test it against something exposing desktop serial ports to Java, as debugging Android host mode stuff is a pain given you have to use ADB-over-wifi. You might try to figure out how avrdude works, for example. Then I'd try to combine that with existing code that is out there for talking serial-over-USB to Arduino boards with the various device-side chipsets. For a leonardo type board the two pieces may be more tightly coupled.

Copy of Chris Stratton's comment which was acknowledged as an answer.

---
Tags: arduino-leonardo, uploading, android
---


title: Using pointers with Arduino

text:
# Question
Title: Using pointers with Arduino
I am learning about pointers.

I was wondering how the memory address is defined in programming. I get different outputs depending on the format I choose for memory address. So I was wondering if it is correct to assume that the format of the memory address is defined by the programmer. I get different results for memory address when I use `Serial.print( (long) &ptr1, DEC);` and `Serial.print( (long) &ptr1, HEX);`

```
 #include <stdio.h>
 int counter = 0;
   void setup() {
    Serial.begin(9600);
   int test1 = 10;
   float test2 = 3.14159;
   char test3[ ] = "This is a character array";
   int *ptr1;
   float *ptr2;
 char *ptr3;
  ptr1 = &test1;
Serial.print("The integer value is stored at ");
Serial.print( (long) &ptr1, DEC);

 Serial.print("The integer value is stored at ");
  Serial.print( (long) &ptr1, HEX);

  }
 void loop() {

    }

```

My output is:

The integer value is stored in 2296

The integer value is stored in 8f8

# Answer
You're printing the address of the pointer, not the contents of the pointer.

Say you have the memory map of:

```
100 20       test1 low byte
101 0        test1 high byte
102 100      ptr1 low byte
103 0        ptr1 high byte

```

`test` is located at address 100 and takes two bytes. `ptr1` is located at 102 and takes two bytes. `ptr1` contains the address of `test` (100) and `test1` contains the value `20`.

The different possible combinations of prints are:

```
Serial.println(test1);  => 20 (contents of test1)
Serial.println(&test1); => 100 (address of test1)
Serial.println(ptr1);   => 100 (contents of ptr1 = address of test1)
Serial.println(&ptr1);  => 102 (address of ptr1)
Serial.println(*ptr1);  => 20 (contents of address pointed to by ptr1).

```

(note: some of those will require a *cast* in order for the C++ to select the correct `println()` overload function.)
> 3 votes

---
Tags: serial, c, pointer, memory, printf
---


# Question
Title: Problem stopping a stepper motor with an endstop
Basically I have created the following code to control my stepper motor:

```
int pin_enable_motor_x = 38;
int pin_motor_step_x = A0;
int pin_direction_x = A1;
int endstop_x = 3;

void setup() {
  pinMode(pin_enable_motor_x, OUTPUT);
  pinMode(pin_motor_step_x, OUTPUT);
  pinMode(pin_direction_x, OUTPUT);
  pinMode(endstop_x, INPUT);

  digitalWrite(pin_enable_motor_x, LOW);

  for (int i = 0; i < 200000; i++) {
    runMotorSingleStepX(100, false); // runMotorSingleStepX(int delay, boolean direction)
    if (digitalRead(endstop_x) == true) {
      break;
    }
  }
}

void loop() {

}

void runMotorSingleStepX(int wait, boolean value) {
  digitalWrite(pin_direction_x, value);
  digitalWrite(pin_motor_step_x, HIGH);
  delayMicroseconds(wait);
  digitalWrite(pin_motor_step_x, LOW);
  delayMicroseconds(wait);
}

```

The idea is that the stepper motor will give many single steps until it reaches my mechanical endstop. But what really happens is that it detects `true` random pulses even when my endstop isn't pressed. So my motor stops before the point it should stop. I'm not sure if it's a common problem and I should be using some tricks to fix this problem.

Does anyone know what could be happening supposing that my electronics circuit is properly settled?

# Answer
> 0 votes
*Answer based on comments originally under the question*

It sounds like the endstop switch may have floating input. Try making the endstop pins `INPUT_PULLUP` rather than `INPUT`.

> It seems to be a little more stable... But it still stops before the point sometimes.

Try a stronger pull-up, like 10k. Over a long wiring run the inbuilt 50k pull-up may not be strong enough to counter noise in nearby wires.

> Thanks, the extra 10K resistor solved the problem :)

# Answer
> 1 votes
Your `for()` loop is using an `int` type for the iterator. You are asking it to run for up to 200,000 steps but an `int` is a 16 bit signed entity (~+/-32,768) so the `for()` loop will exit well before it reaches your desired count. That may be why you are not reaching the stop while still in the loop.

You may want to use an unsigned long as the type for your loop counter and or use a `while()` construct in which you incorporate the exit condition.

---
Tags: electronics
---


# Question
Title: Are function pointer assignments atomic in Arduino?
The following snippets are from TimerOne library source code:

```
// TimerOne.h:
void (*isrCallback)();

// TimerOne.cpp:
ISR(TIMER1_OVF_vect) // interrupt service routine that wraps a user defined function supplied by attachInterrupt
{
  Timer1.isrCallback();
}

// TimerOne.cpp:
void TimerOne::attachInterrupt(void (*isr)(), long microseconds)
{
  if(microseconds > 0) setPeriod(microseconds);
  isrCallback = isr; // register the user's callback with the real ISR
  TIMSK1 = _BV(TOIE1); // sets the timer overflow interrupt enable bit
  resume();
}

```

The question: if the timer is already running, and the main program calls `attachInterrupt()`, could the timer interrupt occur there *during* the function pointer assignment `isrCallback = isr;`? Then, with lucky timing, `Timer1.isrCallback();` function pointer would consist partly of the old and partly of the new address, causing the ISR jump to a bogus location?

I suppose this might be the case, since function pointers are certainly wider than 1 byte, and accessing \> 1 byte data isn't atomic. Possible workarounds could be:

* Always call `detachInterrupt()` to make sure the timer isn't running, before calling `attachInterrupt()`, i.e. clarify Timer1 docs.
* Or, modify Timer1, disabling timer overflow interrupts temporarily just before `isrCallback = isr;`

Does this make sense, or is there something in `Timer1` sources or function pointer assignments that I've missed?

# Answer
> 7 votes
Have a look at the code for attachInterrupt() and detachInterrupt() in `/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino/WInterrupts.c` (well, that's where they are on a Mac, anyway. Arduino file structure on other OSes' probably looks similar in the lower levels of the path).

It appears that attachInterrupt() assumes that the interrupt in question is not yet enabled because it writes the function pointer without taking any precautions. Note that detachInterrupts() disables the target interrupt before writing a NULL-pointer to its vector. So I'd at least use a `detachInterrupt()` / `attachInterrupt()` pair

I'd want to run any such code in a critical section, myself. It appears your first way (detach, then attach) would work, though I can't be sure it couldn't miss an unfortunately timed interrupt. The datasheet for your MCU might have more to say on that. But neither am I sure at this point, that a global `cli()`/`sei()` wouldn't miss it either. The ATMega2560 datasheet, section 6.8, does say "When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example", seeming to imply that it can buffer an interrupt while the interrupts are off.

# Answer
> 0 votes
It looks like you have a point. The logical thing to do would be to disable interrupts in such a way that you don't re-enable them if they were disabled in the first place. For example:

```
  uint8_t oldSREG = SREG;  // remember if interrupts are on
  cli();                   // make the next line interruptible
  isrCallback = isr;       // register the user's callback with the real ISR
  SREG = oldSREG;          // turn interrupts back on, if they were on before

```

---

> "When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example"

The intention of this is to let you write code like this:

```
  sei ();         // enable interrupts
  sleep_cpu ();   // sleep

```

Without that provision you might get an interrupt between those two lines, and thus sleep indefinitely (because the interrupt which was going to wake you has occurred *before* you slept). The provision in the processor that the next instruction, after interrupts become enabled if they were not enabled before, is always executed, guards against this.

---
Tags: interrupt, timers, isr, pointer
---


# Question
Title: Why is communication between a Python program and Arduino not producing the expected result?
I have written some Arduino code (with help from the post *Serial Input Basics*). On serial I send some data and, based on certain values sent, certain LEDs will be lit. Here is the Arduino code:

```
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars];        // Temporary array for use when parsing

// Variables to hold the parsed data
//char messageFromPC[numChars] = {0};
int cmd = 0;
int pitch = 0;
int velocity = 0;
int integerFromPC = 0;
int int2FromPC = 0;
boolean newData = false;

void setup() {

    // Put your setup code here, to run once:
    Serial.begin(9600);//set baud rate

    //Configure pins 2:5 as OUTPUT
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,OUTPUT);
    pinMode(13,OUTPUT);
}

void loop() {
    recvWithStartEndMarkers();
    if (newData == true) {
        strcpy(tempChars, receivedChars);
        // This temporary copy is necessary to protect the original data
        // because strtok() used in parseData() replaces the commas with \0.

        parseData();
        showParsedData();
        if(cmd==144 && velocity!=0){
            switch(pitch){
                case 30:
                    digitalWrite(2, HIGH);
                    break;

                case 31:
                     digitalWrite(3, HIGH);
                     break;

                case 32:
                    digitalWrite(4, HIGH);
                    break;

                case 33:
                    digitalWrite(5, HIGH);
                    break;

                default:
                    break;
            }
        }
        if(cmd==144 && velocity==0){
            switch(pitch){

                case 30:
                    digitalWrite(2, LOW);
                    break;

                case 31:
                    digitalWrite(3, LOW);
                    break;

                case 32:
                    digitalWrite(4, LOW);
                    break;

                case 33:
                    digitalWrite(5, LOW);
                    break;

                default:
                    break;
            }
        }
        newData = false;
    }
}

void recvWithStartEndMarkers() {

    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // Terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

void parseData() {      // Split the data into its parts

    char * strtokIndx;  // This is used by strtok() as an index

    strtokIndx = strtok(tempChars, " "); // Get the first part - the string
    //strcpy(messageFromPC, strtokIndx); // Copy it to messageFromPC
    cmd = atoi(strtokIndx);

    strtokIndx = strtok(NULL, " ");      // This continues where the previous call left off
    //integerFromPC = atoi(strtokIndx);  // Convert this part to an integer
    pitch = atoi(strtokIndx);

    strtokIndx = strtok(NULL, " ");
    velocity = atoi(strtokIndx);         // Convert this part to a float
}

void showParsedData() {
    Serial.print("Comm ");
    Serial.println(cmd);
    Serial.print("Ptch ");
    Serial.println(pitch);
    Serial.print("Velo ");
    Serial.println(velocity);
    Serial.println("\n");
}

```

Now this works perfectly with sending data from the Arduino's serial monitor, so for example if I type the following on serial monitor:

```
<144 30 45>

```

Then the LED I expect to get lit does, and I can turn it off by:

```
<144 30 0>

```

Now, I want to send this data from a Python (2.7) program which I am reproducing here:

```
#!/usr/bin/env python
import time
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600)
noteOn = 144
veloMid = 75
veloSilent = 0
def sendData(cmd, pitch, velocity):
    global ser
    cmd = bytes(cmd)
    pitch = bytes(pitch)
    velocity = bytes(velocity)
    ser.write("<")
    ser.write(cmd)
    ser.write(pitch)
    ser.write(velocity)
    ser.write(">")

while 1:
    notes = range(30, 34)
    for note in notes:
        sendData(noteOn, note, veloMid)
        time.sleep(2)
        sendData(noteOn, note, veloSilent)

```

The idea was to do the same thing I was doing manually in serial monitor, except using a Python script. But this produces no result. I see the RX and TX pins on the Arduino toggling, so it looks like the program is indeed communicating with the Arduino. In the Python IDE I wrote a few lines as follows to read the data from Arduino:

```
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600, timeout=5)
while True:
    data_raw = ser.read()
    print data_raw

```

With above code I receive the following characters in the Python IDE:

```
C
o
m
m

P
t
c
h

V
e
l
o

```

I have a feeling there is some mismatch between the data types of the data I am sending between the Python script and the Arduino, but I am not sure exactly what this mismatch might be.

* Why am I not seeing the values of cmd, pitch and veocity being printed out from the serial.read() although the other strings "Comm Ptch Velo" are printed?
* What dataype is serial.write passing on that might than be causing mismatch with my Arduino code?

# Answer
In your test with the serial monitor you are putting spaces between each number. Using my logic analyzer I got this being sent from your Python code to the Arduino:

No spaces, right? So the Arduino is receiving:

```
<1443175>

```

And since you are using a space as a numeric delimiter your decoding isn't working.

---

Something like this is probably warranted:

```
    ser.write("<")
    ser.write(cmd)
    ser.write(" ")
    ser.write(pitch)
    ser.write(" ")
    ser.write(velocity)
    ser.write(">")

```
> 2 votes

---
Tags: arduino-uno, serial, python
---


title: Help with 1-Wire to I2C translate

text:
# Question
Title: Help with 1-Wire to I2C translate
Please, someone.

I want to use a temperature sensor (DS18B20) in an I2C only shield (Tentacle Mini), but this sensor is One Wire only. Can I write an I2C code to change the 1-Wire to I2C for this sensor? I think to use the (DS2482-800) bridge, but I don't know how to do...

Thanks!

# Answer
> 2 votes
As you said, the DS18B20 uses One-Wire interface. I2C is a Two-Wire interface. Pratically, you can't use the Arduino to translate that, BUT I found the DS28E17, a module that could translate the the 2 methods of communication. It should work but I havent tested it.

The DS28E17 is a 1-Wire slave to I2C master bridge device that interfaces directly to I2C slaves at standard (100kHz max) or fast (400kHz max). Data transfers serially by means of the 1-Wire® protocol, which requires only a single data lead and a ground return. Every DS28E17 is guaranteed to have a unique 64-bit ROM registration number that serves as a node address in the 1-Wire network. Multiple DS28E17 devices can coexist with other devices in the 1-Wire network and be accessed individually without affecting other devices. The DS28E17 allows using complex I2C devices such as display controllers, ADCs, DACs, I2C sensors, etc. in a 1-Wire environment. Each self-timed DS28E17 provides 1-Wire access for a single I2C interface.

Hope I helped you.

---
Tags: i2c, 1-wire
---


title: BLE Python with GUI on OSX

text:
# Question
Title: BLE Python with GUI on OSX
Has anyone connected BLE devices with Python + GUI on OSX? I've looked into a few libraries (most are old), but one that has the most success if Adafruit's BlueFruit library. However, this library works poorly with GUI's since it requires use of the main event loop (which GUI's usually use). After doing a bunch of Google searches, I couldn't find any good examples of using a GUI with Python + BLE. There seems to be no good BLE libraries for Python either.

Specifically looking for help integrating BLE with Kivy, but other GUI toolkit examples should be fine.

Also trying to gauge interest in this to see if I can do development to solve this (if it really is a problem).

# Answer
> 2 votes
If you are still searching for a lib check out: https://github.com/adafruit/Adafruit\_Python\_BluefruitLE

Its specifically made for BLE communication on OS X or Linux by wrapping the corebluetooth and its Linux equivalent bluez in a python lib. Windows is not supported at this moment.

Unfortunately there is no documentation to it. You will have to read the examples and search for specific functions in the lib manually.

---
Tags: serial, bluetooth, python, wireless
---


# Question
Title: Replacing stock String.cpp with smaller version
Hey all I am wondering if it's possible to modify the WString.cpp file to only include the commands that I need for my project since that file is so large.

I am using a Digispark arduino that is Attiny85 which only has about **6k flash memory after bootloader**.

Needless to say I am almost out of flash memory and I still need to do a few things.

I am reading from a serial port (in this case, using DigiCDC for a virtual serial port).

How can I overwrite the default Strings class that looks like its built in to the IDE with my own modified String class so I can get a smaller footprint?

Thanks!

# Answer
> 1 votes
You can make a copy of WString.cpp, edit it, and add it to your project. Note however that:

1. You will have to define *every method* that you use. Otherwise the linker will pull WString.o from the Arduino core library in order to resolve the missing methods, and then it will complain that some methods have been defined twice.
2. Just pruning WString.cpp from unused methods will not help: the linker is already doing that for you.
3. To know which functions/methods of your program are taking too much flash, you can use the command `avr-nm --size-sort -Crtd program.elf`.
4. I second Majenko in recommending against String objects if possible.

---
Tags: programming, softwareserial, attiny, string, digispark
---


title: Sending Analog Data with and IR LED

text:
# Question
Title: Sending Analog Data with and IR LED
This is the idea. I have 2 Arduinos. One with an IR LED and the other with an IR receiver. I want to read the values of multiple sensors and transmit it to the other Arduino via IR. I know how to send data like a fixed HEX code but I dont know how to send values from a potentiometer.

Just think of how a quadcopter sends and receives data from the joysticks, thats somewhat what I want to do.

**\[EDIT\]**

This is a precision of what I want to do. I'll read the values of let's say 2 potentiometers, map the values from 0-99, and then I want to send it to the other Arduino **with IR and not anything else.**

# Answer
> 0 votes
Seems to me you first need to establish a protocol. Could just be a simple one you make up, with it you will eventually find that repetition and retransmission will need to be explored, and you may want to include things such as a CRC if the application suits it; or not...

As part of the thought process you need to look at your sensors, see how they put out their data, you seem to indicate analog, so that would be read on an a to d converter and that d value might be directly sent as the data part of your chosen protocol.

Or some joysticks packages might have have a I2C or SPI driver built in to which the A to D wouldn't be required.

But using IR you will find timing and validation very important so that the receiver knows where the beginning and end of data is at.

Thinking about it there must some libraries out there already. Or entirely completed projects to study.

Now you didn't ask but if reliable communication is desired you might want to go wired serial or use a managed protocol like an Ethernet peripheral.

---
Tags: arduino-uno, communication, ir, wireless, remote-control
---


# Question
Title: Does 'digitalPinToInterrupt' work with analog pins
I have an interrupt signal attached to the A12 pin of an Arduino Mega 2560.

Would the following source line activate the interrupt processing? I am calling the `digitalPinToInterrupt` function on an Analog pin. It compiles fine.

```
attachInterrupt(digitalPinToInterrupt(A12), MessageFromIOBInt, FALLING);

```

where my interrupt code is

```
void MessageFromIOBInt(void) {
    ++gNumInterrupts;
}

```

# Answer
> 2 votes
Interrupts only work on interrupt pins. Trying to translate a pin number into an interrupt number for a pin that isn't an interrupt pin will never work.

> External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level.

Many pins (including the analog pins) can use the *pin change* interrupt. This requires an external library which has its own way of interfacing with them (see the examples).

# Answer
> 2 votes
> Does 'digitalPinToInterrupt' work with analog pins?

It works in the sense that it compiles. When executed, for a pin that is not one of the interrupt pins it will return the value `NOT_AN_INTERRUPT`.

Thus a sensible test would be to check whether or not you get `NOT_AN_INTERRUPT` returned from `digitalPinToInterrupt(A12)`.

A quick test confirms this:

```
void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.println (digitalPinToInterrupt(A12));
}  // end of setup

void loop () { }

```

Output:

```
-1

```

---

In Arduino.h is this define:

```
#define NOT_AN_INTERRUPT -1

```

I have a page about interrupts. On that page, amongst other things, is a list of external interrupt pins for various Arduinos:

You can see that the pins on the board labelled D2, D3, D18, D19, D20, D21 are the only ones which support these sorts of interrupts (external interrupts). Various other pins support pin-change interrupts.

On the Mega2560 in particular these pins are supported for pin-change interrupts:

> 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69)

---

As Majenko mentioned, you use pin-change interrupts in a different way, possibly using the PinChangeInt library, or just accessing the registers yourself as described on the page I mentioned above.

---
Tags: arduino-mega, interrupt
---


# Question
Title: High errors in transmission (completely eliminated by adding delay): What's the issue?
I am using a two Arduino setup with two XBee radios. One radio is sending data and the other is receiving data. I am sending three sensor readings following a protocol which uses three bytes for each sensor reading. Byte one is sensor information, byte two is data, and byte three is for error checking. When I run the set up for about 5 minutes I get approximately 47% errors in transmission. Once one error occurs, there seems to be an avalanche of errors. However, when I add delay in between sending bytes (100ms between bytes and 1s between sensor) it works perfectly. I've tried expanding the hardware buffer, but this didn't work.

```
        delay(2000);

        // Calcuate weather parameters for serial and web
        calcWeather(); // Go calc all the various sensors

        // send weather out to serial port
        if (prevtemplm34_1 == templm34_1) // 2 in a row must be the same to send
        {
            Serial.write(0);
            Serial.write(templm34_1);
            Serial.write(templm34_1 ^ 0);
        }

        // send weather out to serial port
        if(prevtemplm34_2 == templm34_2) // 2 in a row must be the same to send
        {
            Serial.write(1);
            Serial.write(templm34_2);
            Serial.write(templm34_2 ^ 1);
        }

        // send weather out to serial port
        if(prevtemplm34_3 == templm34_3) // 2 in a row must be the same to send
        {
            Serial.write(2);
            Serial.write(templm34_3);
            Serial.write(templm34_3 ^ 2);
        }
        delay(2000);

```

The code for parsing received data is:

```
int readData ()
{
// There must be at least three available bytes to satisfy the protocol
// Otherwise, wait until three bytes have arrived to read anything
if (Serial.available() >= 3) {

      // Read the next three byte in the serial buffer
      incomingByteOne = Serial.read();
      Serial.write("Byte One: ");
      Serial.write(incomingByteOne);
      Serial.println();
      incomingByteTwo = Serial.read();
      Serial.write("Byte Two: ");
      Serial.write(incomingByteTwo);
      Serial.println();
      incomingByteThree = Serial.read();
      Serial.write("Byte Three: ");
      Serial.write(incomingByteThree);
      Serial.println();

      // XOR the first and second incoming bytes so that the result can be checked against the third error checking byte
      byte xorValue = incomingByteOne ^ incomingByteTwo;
      Serial.write("XOR VALUE: ");
      Serial.write(xorValue);
      Serial.println("Number of Errors: ");
      Serial.println(numberOfErrors);
      Serial.println();
      Serial.println();
      if(xorValue != incomingByteThree) {
        numberOfErrors++; // Add one to the total count of number of errors in transmission
      }
      else {
        // Mask for retrieving the five rightmost bits from incomingByteOne (00011111)
        byte maskForSensorNumber = 0x1f;

        // Shift incomingByteOne right 5 times in order to obtain the three bits representing the unit number
        int unitNumber = incomingByteOne >> 5;

        // AND incomingByteOne with the mask in order to retrieve only the five righmost bits representing the sensor number
        int sensorNumber = incomingByteOne & maskForSensorNumber;

        // Store the data for the correct sensor on the correct unit
        data[unitNumber][sensorNumber] = incomingByteTwo*1;
     }
}
}

```

What could be causing the transmissions to work fine with delay, but not otherwise?

# Answer
You are probably just transmitting too fast.

Your receiver is writing at least 80 bytes of debugging information (if I counted it right) for every 3 bytes of incoming data. Since both input and debug output happen at the same baud rate, this means the receiver can only cope with an input data rate equal to 3/80 = 3.75% of the nominal baud rate.

I would expect no errors at the very beginning of the program run, because the debugging info is written to a RAM buffer. Only when that buffer fills up the receiver is slowed down by every `Serial.write()` and `Serial.println()` it performs.
> 2 votes

---
Tags: serial, arduino-mega, xbee
---


# Question
Title: How to measure free RAM on an Arduino Due in Runtime?
I use this Library to measure my free RAM on a Mega in runtime. But this Library does not work on the Due.

# Answer
> 1 votes
As mentioned by Mikael Patel in a comment, the library from Arduino-MemoryFree should do it. A minimal sketch that seems to work on the Due:

```
extern "C" char* sbrk(int incr);

int freeMemory() {
  char top;
  return &top - reinterpret_cast<char*>(sbrk(0));
}

void setup ()
{
  Serial.begin (115200);
  Serial.println ();
  Serial.print ("Free memory is: ");
  Serial.println (freeMemory ());
}  // end of setup

void loop () { }

```

I'm not totally convinced that this gives the correct figure. The figure returned by the library above for my Uno was too high (2297 bytes).

# Answer
> 0 votes
Try to use this method:

```
int freeRAM() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

---
Tags: arduino-due, library, memory
---


title: Explanantion of Addressing

text:
# Question
Title: Explanantion of Addressing
I'm new Arduino user and I'm trying out a SPI protocol to interface a SRAM, specifically, the 23LCV512.

I have found the instructables steps to interface a SRAM using the SPI bus on an Arduino UNO very helpful (http://www.instructables.com/id/Interface-an-SRAM-bus-to-your-arduino/), but there is one point that i would like some explanation for:

In the mem\_demo.ino and other various SPI.h code, I have seen variations of the following, however I do not understand why you would have to do this? I think here that we are communicating the right shifting of an input address 16 places along with 8 bits of '1'.

```
SPI.transfer((uint8_t)(address >> 16) & 0xff);
SPI.transfer((uint8_t)(address >> 8) & 0xff);
SPI.transfer((uint8_t)address);

```

Commenting these lines out for the write did not effect the writing to the SRAM, but reading caused it to return mostly 0's.

I really appreciate any help iIget, I do not have a lot of experience with memory addresses and electronics, thank you.

# Answer
> 0 votes
It is actually slightly confusing owing to the (actually redundant) `& 0xff` in there.

What is happening is first the address is right-shifted so as to place the byte of interest at that moment in the lowest 8-bits (`address >> 16` for instance to get bits 16-23 moved to bits 0-7) and then the lowest 8 bits are masked off by ANDing them with 0b11111111 (0xFF). This removes any bits that are above the 8 bits we are interested in - however the fact that it's cast to `uint8_t` and also passed to a function that expects `uint8_t` makes that masking redundant. Any bits above the first 8 are discarded anyway.

So to take an example address of, say, 100,000 (which is 0x186A0 in hex) and run those three commands on it, we end up with:

```
SPI.transfer((uint8_t)(address >> 16) & 0xff);

0x186A0 >> 16 = 0x00001
0x00001 & 0xFF = 0x01

SPI.transfer((uint8_t)(address >> 8) & 0xff);

0x186A0 >> 8 = 0x00186
0x00186 & 0xFF = 0x86

SPI.transfer((uint8_t)address);

(uint8_t)0x186A0 = 0xA0

```

The end result as you can see is three SPI transfers each sending a single byte:

```
0x01, 0x86, 0xA0

```

And that corresponds to the protocol for that chip, which is basically:

```
<Command>, <Address H>, <Address M>, <Address L>, <Data>...

```

For instance:

```
0x02, 0x01, 0x86, 0xA0, 0x69

```

You send the "WRITE" command, send the three bytes of the address you want to write to, then follow that with the data to write. Or you send the READ command, send the three bytes of the address you want to read from, then the data is returned to you a byte at a time.

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


# Question
Title: Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode
This is a follow up to my previous question.

I have Timer2 in CTC mode, with TOP=OCR2A set to 150 (with a prescaler of 8, giving a 75us timing interval).

The datasheet states that setting COM2B1 to 1 in TCCR2A will "clear OC2B on compare match" (= Arduino pin D3) when you are in CTC mode.

I would like to use this functionality to get a "pwm" signal with a period of 75us, with duty cycle determined by OCR2B. I realize that this is a very convoluted way of achieving this, but eventually I want to be continually be changing OCR2B to get a (rapidly) varying duty cycle.

In the compare channel A interrupt I would like to turn D3 high, relying on the "clear on compare match" feature of channel B to turn it low a small interval later.

I have the following minimal(-ish) example:

```
#define OCIEA 1
#define CA21 1

void setup() {
  // PD3 as output
  DDRD |= (1 << PD3);

  // Pause the timers so they sync up
  GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC); // Halt all timers

  // Reset timer
  TCNT2 = 0; // set timer2 to 0 (8-bit timer)

  // Enable CTC mode
  TCCR2A = (1 << WGM21); // Timer 2 in CTC (TOP = OCR2A)

  // Clear output pins on compare match
  TCCR2A |= (1 << COM2B1); // Clear OC2B on match

  // Set prescaler
  TCCR2B = (1 << CA21); // set timer 2 divisor to 8

  // Set output compare
  OCR2A = 150; // Determines TOP for Timer2

  // Determines the pulse width
  OCR2B = 75; // Timer 2 output B (controls OC2B = PD3 = D3)

  // Enable interrupts for timer 2
  TIMSK2 = (1 << OCIEA);

  // Set the timers going again
  GTCCR = 0; // release all timers
}

ISR(TIMER2_COMPA_vect)
{
  TCCR2A &= ~((1 << COM2B1) | (1 << COM2B0)); // Disable clear OC2B on match
  DDRD |= (1 << PD3); // Enable output
  PORTD |= (1 << PD3); // Output high
  TCCR2A |= (1 << COM2B1); // Enable clear OC2B on match
}

void loop() {

}

```

Ideally the ISR would just consist of `PORTD |= (1 << PD3);` but this does not give my desired 50% duty cycle, but apparently it's impossible to write to the pin with COM2B1 enabled, so I tried various combinations of disabling it and reconnecting the pin but all I am getting is a very, very short pulse. It looks like as soon as COM2B1 is re-enabled, the pin goes low, even though a compare match on channel B should not have happened yet.

Setting COM2B0 instead of COM2B1 works as expected: the pin toggles state (but this is not what I want).

Why does this not work the way I expect it to, and is there a way to get my desired behavior? Also, if this is not possible, what on earth is the purpose of the clear on compare match feature if you can't turn the pin on at all when using it?

I have discovered I can sort of get the behavior I want by setting COM2B0 instead of COM2B1 (toggle on match rather than clear on match) and forcing a compare match in the interrupt (toggling the pin off) so that later the "real" toggle on match will turn it off. However, this is not ideal (as if the real and forced match overlap, I would lose track of the pin's state), and I'm still wondering what the purpose of the clear on match functionality is if it just forces the pin low.

# Answer
> 2 votes
The PWM modes manage pin at both ends of the cycle.

The point of the CTC modes is that they manage the pin only at one end of the count, but allow you to manage the other end explicitly.

To manage both ends explicitly, you use normal mode.

To set the OC2B bit with FOC2B in the TCCR2B with your interrupt:

```
ISR(TIMER2_COMPA_vect)
{
  TCCR2A |=  (1 << COM2B0); // Set OC2B on Compare Match
  TCCR2B |=  (1 << FOC2B ); // Force Output Compare B OC2B
  TCCR2A &= ~(1 << COM2B0); // Clear OC2B on Compare Match
}

```

---
Tags: atmega328, timers
---


title: Strange binary number representation

text:
# Question
Title: Strange binary number representation
I have a very simple sketch, something like this:

```
int aFour = 4;
softwareSerial.print(4,BIN);
softwareSerial.print(aFour,BIN);

```

Which gives the following output:

```
1001
0011

```

Why don't they print both as `0100`?

EDIT: the output was in one line : `10010011`, I falsely asumed the output should be split into twice 4 bits.

# Answer
* `print` never prints leading zeroes (how many *should* it print anyway?).
* `print` doesn't start a new line - you need `println` for that

So you get your `4` in binary printed twice followed by something else (not sure what - maybe something else in your program that you're not showing us?): `10010011`

That's `100 100 11` when split up.
> 4 votes

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


# Question
Title: Use command line to upload program through hex file to Teensy-LC
I want to make a standalone programmer for Teensy-LC in **windows 8.1**.

So basically I have provided the board to a client of mine and now I want to change the program loaded into the Teensy-LC board.

But the solution available right now is to send the Teensy Loader and send the hex file. But the teensy LC board is packed inside a device. So reset button cannot be pressed.

Also it would be better if this code can be burned in an installer format instead of the Teensy Loader.

Is there any way to make this work?

**EDIT**

My Teensy.exe does not have the option for program or reboot The icons are not accessible

Does that mean my interrupts are disabled or there might be something else I am doing wrong? My program loads on pressing the reset button but I cannot press the program button inside Teensy.exe

If I turn off the Auto Mode, all icons go grey.

# Answer
> 3 votes
Paul Stoffregen (Teensy creator) has released a command line version of the Teensy Loader which can be found on his website. However, this program appears to be Linux only, so unless your client has Linux, that may be a non-starter. The source code for the program is available, so you might be able to work out the logic and port it over to whatever platform you are wanting this to work on (just make sure you comply with the source code license).

All that being said, pressing the reset button is not necessary for programming. The Teensy loader should be able to trigger a reset over USB all on its own. So unless the current program on the device disables interrupts that are necessary for the USB port to function, or it was programmed with the USB port disabled (by selecting "No USB" in the USB Type menu), physically pressing the reset button isn't necessary for programming. For more details you can see this forum post.

**Loading Firmware Without Pressing the Button**

When programming via Arduino, it does a lot of things for you automatically. To replicate that manually, follow these steps:

1. Connect the Teensy to the computer via USB.
2. Run `teensy.exe` (found in `C:\Program Files (x86)\Arduino\hardware\tools`)
3. Click the button on the left to select the hex file to load.
4. Go ahead and leave Auto enabled (this actually doesn't matter).
5. Run `teensy_reboot.exe` (also found in `C:\Program Files (x86)\Arduino\hardware\tools`, this will restart the Teensy, as if you had pressed the button, and automatically start the programming process.)

# Answer
> 1 votes
Sadly the accepted answer is incomplete and requires manual steps.

The reason why your "Auto" button is greyed out is that you did not execute the second executable that is required for that: "Teensy\_Reboot.exe". You find it on your disk if you have installed TeensyDuino.

First kill Teensy.exe if it is running (Important)

Then you write path and file of your Hex file into the registry:

```
HKEY_CURRENT_USER\Software\PJRC\teensy\dir
HKEY_CURRENT_USER\Software\PJRC\teensy\file

```

Then you start Teensy.exe

Then you start Teensy\_Reboot.exe as a hidden process.

That is the solution of your problem!

It is a shame that Paul does not document his stuff.

NOTE: If you have previously loaded a sketch into the Teensy that was compiled with "USB Type: No USB" the reboot will not work and the button on the board must be pressed manually, but Teensy\_Reboot.exe is still usefull because it enables the green "Auto" button in Teensy.exe.

NOTE: Teensy\_Reboot.exe has a severe bug: If the Teensy.exe is not successfull because another program still had the Teensy CDC COM port open while you started Teensy.exe, the Teensy\_Reboot.exe may run eternally consuming 100% CPU under some circumstances. I reported that bug in the forum of Paul but he never answered to my posting.

---

**PLAN B:**

The disadvantage of using teensy\_reboot.exe is that you don't know if the programming was successful or not because sadly teensy\_reboot does not return any usefull exit code.

So the better option (which requires more code) is to instruct Teensy.exe directly from your program. Therefore you need a TCP connection to localhost.

You find more details in this thread: https://forum.pjrc.com/threads/38684-How-does-Teensy-Reboot-exe-communicate?p=120443 where Paul (once again) did not answer my question.

---

**PLAN C:**

You can even replace Teensy.exe with your own code. Have a look at this project: https://github.com/Koromix/ty Sadly this code depends on the huge QT library. Apart from that it may not work with future versions of Teensies.

---
Tags: arduino-ide, uploading, bootloader, teensy
---


title: Arduino shield bluetooth

text:
# Question
Title: Arduino shield bluetooth
I have this arduino motor shield, and I want to connect a Bluetooth module, but don't know how (the tx and rx pins are used by the plate). Tried to sold it but now I don't have the tin to do it. So I want to know if I can use this holes (don't know their names) "the ones encircled in red" to connect the Bluetooth module. Thank you folks.

# Answer
You are looking at the wrong place. Tx and Rx are at the bottom of you picture (new picture at the bottom to help you). What you need to do is to get a jumper, heat up the Rx pin and put the jumper in the molten solder. That is not the ideal choice but because you don't have enough solder, thats the way to go. To the same to the Tx pin, GND, and VCC.

A more permanent and clean way of doing this will require extra solder (which you dont have at the moment) and some "shield headers" (aka stackable headers). This will let you connect the shield to your Arduino while still leaving you with all of your female headers.
> 0 votes

---
Tags: arduino-uno, bluetooth, shields
---


# Question
Title: Arduino: Sending SD CSV file online at specific time of the day
I intend to perform data logging from sensors and store it on SD card as CSV format. The data is related to weather and I would like to send it at the end of the day/ Any available codes how to deploy the SD files from Arduino to the cloud/online at specific time of the day? Thank you in advance.

# Answer
> 1 votes
You should use arduino as an ftp client, then stream the csv file to the site in binary mode. You should find examples on the web.

# Answer
> 1 votes
Well for CSV, you might as well do `dataFile.print(",");`. It will log a comma and thus separating your values with a comma.

For **logging** your data at the end of the day, you have multiple ways.

1- Use a delay (worst idea EVER! Don't do this!). This will require you putting `delay(86400000);`. Yes that is indeed a 24h delay!

2- Use the `millis()` function. This function returns the number of milliseconds since the programmed started running. There is an example code called `blinkWithOutDelay`(or something like that). This method is somewhat "ok" but after 49 days there is a rollover which makes things complicated. To solve that rollover, see here.

3- Use a RTC. RTC stands for Real Time Clock. It is pretty much a module that keeps actual time even if the power to your project is disconnected. There are many popular models out there such as the DS3231. There are many libraries for it. You can do so that each day, at a specific time, it logs the data to your SD card.

Now to **send** the data. You have may options for this too.

1- Use an Arduino Ethernet shield. This will connect your Arduino to the Ethernet via an Ethernet cable. From there, you can either log your data to a Google Sheets file or a custom web server. Many tutorials out there for you.

2- Use an ESP8266. With this Wifi module, you can easily host your own web server with it. Note that This makes it somewhat harder for your code then simply using an Ethernet cable but it makes you project wireless. Note that if you do use an ESP8266, you can put the Arduino aside. The ESP has many GPIOs that can be used to do many things, but I'll still suggest keeping the Arduino for sake of simplicity. Again, many tutorials out there.

Note that there are many cloud services out there. A quick Arduino IOT search will bring out many result and interresting projects ideas for you.

---
Tags: arduino-uno, arduino-ide, sd-card, timers, datalogging
---


# Question
Title: Why the GSM Shield is discontinued? What options are available?
I need to build a device with a single button to make a call over a mobile network (GSM)

I wanted to buy an arduino one and an arduino gsm shield for this, but just noticed that the GSM Shield is retired - discontinued.

I checked all the arduino products but there is no options for integration with GSM.

What options do I've to build my products if the GSM Shields is discontinued?

# Answer
> 0 votes
A retired product is just a product that isn't supported anymore. It doesn't mean that this product is not usable anymore. Because the GSM shield is discontinued by Arduino.cc itself, you could buy Arduino.org (link to the GSM shield 2), or even an other model by Adafruit. Here is a link for many options of GSM shields on Adafruits' website.

A last option would be to buy it from a chinese seller on Amazon or Ebay. Though they are cheap, they are usualy very crappy and there are not many libraries for them.

---
Tags: arduino-uno, gsm
---


# Question
Title: Arduino IDE - Start Serial Monitor once upload is complete
When using the Arduino IDE on Windows (10) is there a way to get it to start the serial monitor automatically when the upload to the board completes?

I know this is a long shot, but pressing those extra 3 keys (CTRL-SHIFT-M) is really bugging me.

# Answer
You could set up a macro triggered by the completion of the upload that automatically sends ctrl+shift+m. This could be done by watching for the exit of the upload application(AVRDUDE for example) or by calling a wrapper batch file from platform.txt's upload.pattern/program.pattern that runs the upload application and then triggers the Serial Monitor keyboard shortcut. There are a variety of Windows software options for doing this. EventGhost is the one I'm most familiar with but AutoHotkey could likely do it also.

To do it with EventGhost you would either:

* Install the **Process Watcher** plugin and use, for example, the `Process.Destroyed.avrdude` event to trigger the Serial Monitor keyboard shortcut using the **Send Keystrokes** action. This will cause false triggers on **Burn Bootloader** but you can get around that issue by identifying uploads by the compilation application events(such as `Process.Destroyed.arduino-builder`) that will not occur with **Burn Bootloader**.
* Run EventGhost.exe from the wrapper batch file with the `-e` command line option to generate the trigger event.

I think the first option is the best because it doesn't require modifying platform.txt, which will need to be redone on every update of any hardware core.

Not exactly what you're asking for, but a much more simple solution is to use Arduino IDE 1.6.5 or newer, which leaves the Serial Monitor open(but disabled) during uploads. This means you only need to load Serial Monitor once. You could have both the Arduino IDE window and the Serial Monitor window tiled on your screen so that you don't need to switch screens to go from editing/uploading your sketch and using Serial Monitor.
> 1 votes

---
Tags: arduino-ide
---


title: Keep References Between Objects

text:
# Question
Title: Keep References Between Objects
I'm trying to recreate a small tween engine so I can interpolate values, leds hue, saturation and brightness in a easy way.

I'm having trouble to reference the value to interpolate into my tween object. If you look at the very last block, you'll see what i'm trying to achieve.

I've poor knowledge in pointers and references and it's driving me mad. Thanks for your help !

---

**Pixel.h**

```
class Pixel {
  public:
    Pixel(float a = 180, float b = 100, float c = 100);

    float hue;
    float saturation;
    float brightness;

    uint16_t toRGB();
}

```

---

**Tween.h**

```
class Tween {
  public:
    Tween(int fps = 60);

    float& target;
    float fps;

    void to(float& target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d));

    void tick();
    float apply();
    bool active = false;

  private:
    float a = 0;
    float b = 1;
    float (* ease)(float t, float b, float c, float d);

    float increment = 1;
    float progress  = 0;
};

```

---

**Tween.cpp**

```
#include <Arduino.h>
#include "Tween.h"

int const ITERATIONS = 1000;

Tween::Tween(int f)
{
  this->fps = f;
  this->active = false;
}

void Tween::to(float& target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d)) {
  if (this->active == true) {
    return;
  }

  this->target = target;
  this->active = true;

  this->a = from;
  this->b = to;

  this->ease = ease;

  int frame = 1000 / this->fps;
  int ms = duration * 1000;

  this->progress = 0;
  this->increment = ITERATIONS / (float)(ms / frame);
}

void Tween::tick() {
  if (this->progress >= ITERATIONS) {
    this->progress = 0;
    this->active = false;
  }

  if (this->active == false) {
    return;
  }

  this->progress += this->increment;
}

float Tween::apply() {
  if (this->active == false) {
    return 0;
  }

  float value = this->ease(this->progress, 0, this->b, ITERATIONS);
  this->target = value;

  return value;
}

```

---

The use of those will be :

```
Pixel pixel = Pixel();
Tween tween = Tween(40);

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

  // reset the values of the pixel
  pixel.hue = 200;
  pixel.saturation = 100;
  pixel.brightness = 0;

  // setup the tween object
  tween.to(pixel.l, 0, 100, 3, Easing::linearTween);
}

void loop() {
  // progress
  tween.tick();

  // set pixel.l = tween value (this is where it's not working)
  tween.apply();

  Serial.println(pixel.brightness);

  // we defined 40fps in the tween so the delay should be 1000/40 => 25ms
  delay(25);
}

```

The easing library is actually Robert Penner's work translated to Arduino (https://github.com/tobiastoft/ArduinoEasing)

# Answer
> 2 votes
The member variable `target` does not need to be passed by reference at all.

```
void Tween::to(float target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d))
{
  if (this->active == true)
    return;

  this->target = target;
  this->active = true;

  // etc...
}

```

And then just call it without any sort of address or reference operator.

```
// setup the tween object
tween.to(pixel.l, 0, 100, 3, Easing::linearTween);

```

(but you still need to sort out what you mean by "pixel.l")

If you wanted to pass a Pixel object to the Tween::to() function, I would use a pointer to the object (although you could use a reference too).

```
void Tween::to(Pixel *pixel, /* ... etc*/))
{
    target = pixel->hue;
    other  = pixel->saturation;
    foo    = pixel->brightness;

    // etc.
}

```

Calling it like:

```
// setup the tween object
tween.to(&pixel, 0, 100, 3, Easing::linearTween);

```

It's not really clear exactly what you're trying to achieve just reading the code sample.

---
Tags: programming, c++, c, pointer
---


# Question
Title: Why do i get additional characters when reading a file through a buffer if buffer size > 15?
This is a follow up question to How to speed up writing a file to a WifiClient?

I modified the old code to read from one `Stream` and write to another which looked like this and worked fine albite being a bit slow

```
while (file.available() > 0)
{
    client.print((char)file.read());
}
client.flush();

```

to use a buffer, like so

```
char buffer[300];
size_t bufferSize = sizeof(buffer);

// ...

while (file.available() > 0)
{
    memset(buffer, 0, bufferSize);
    file.read(buffer, bufferSize);

    client.print(buffer);
}
client.flush();

```

Now, if the buffer size is \> 15 (in the above case, it's 300), two additional characters `Øb` are introduced after the buffer size amount of characters. **If the buffer size is \<= 15, this does not happen.**

If the file to be read contains `abcdefg` repeated several times, I get the following result for a buffer size of 32:

```
|-------- 32 characters -------|Øb|-------- 32 characters -------|Øb|-----
abcdefgabcdefgabcdefgabcdefgabcdØbefgabcdefgabcdefgabcdefgabcdefgaØbbcdefg

```

**What's causing those additional characters to appear?**

The above output is produced in the browser If I do **not** specify a charset. if I do, I get  instead of `Øb`.

# Answer
> 1 votes
Try recording the actual number of bytes read and only write that number of bytes:

```
size_t nr = file.read(buffer, bufferSize);
client.write(buffer, nr);

```

# Answer
> 0 votes
If the buffer is full of data then there is no null terminator on your data to output, the client.print will keep going past the end of the buffer until it hits a 0. Because of the way the compiler is placing things in memory you happen to always get 0b and nothing else (does your code happen to have some other variable with a value of 11?)

There are two solutions: Either only output the number of bytes you read (in which case the memset instruction is no longer needed) or limit the file.read to one less than your buffer size so that there is always a 0 left at the end of the buffer.

```
const int buffersize = 32;
char buffer[buffersize];

while (file.available() > 0)
{
    int bytes = file.read(buffer, bufferSize);
    client.write(buffer,bytes);
}

```

or

```
while (file.available() > 0)
{
    memset(buffer, 0, bufferSize);
    file.read(buffer, bufferSize-1);
    client.print(buffer);
}

```

Also it's more a personal preference than a requirement but I don't like to use `sizeof(<array>)`, it only works within the same scope as the array definition and doesn't work if the array is passed to a function. This site is full of examples of people getting caught out by that and wondering why their array is always giving them a size of 4. So while it works fine in this instance I avoid using it if at all possible.

---
Tags: string
---


# Question
Title: How to speed up writing a file to a WifiClient?
I'm working with a Realtek Ameba IoT RTL8195 board that's compatible to Arduino.

I have a text file on an SD card that I want to send via HTTP over wifi, with the Ameba acting as a server.

I combined the SD card example with the web server example. There's no LED involved here.

Upon request from a client, I want to shove the whole content of the text file into a `text/plain` response as quickly as possible. At the moment i have a 18.7KB dummy file that takes 6.3s to download in the broswer total. That's rather slow.

My code looks essentially like this:

```
while (file.available() > 0)
{
    client.print((char)file.read());
}
client.flush();

```

Where `file` is declared as `SdFatFile file = fs.open(absolute_filename);` and `client` is `WiFiClient client = server.available();`. Which are both classes that come with the Ameba Arduino SDK.

Both of them extend `Stream`. I wonder if reading and writing both streams byte by byte causes a bottleneck. is there a way to simply write "the whole thing" to `client`?

# Answer
> 0 votes
Paul's suggestion from the comment worked. Increasing the buffer reduced the overall time to a couple hundred ms.

---
Tags: web-server, time, http, performance
---


# Question
Title: How to change the variable value on arduino program using java?
I am new to arduino and I want to interface it using java . I want to know is there a way to change the variable or set the variable using the input from java :D Thanks For reading Hope you can answer my question .. Sorry for my english not my first language :D

# Answer
> 2 votes
Although you can't straight-up change variables on the Arduino, you can create your own protocol over a serial connection using processing (https://processing.org) on your computer, and a sketch on Arduino.

Use the function

```
Serial.begin(9600);

```

on the arduino to initialise a serial connection to your computer, and then in processing use the lines:

```
Serial myPort;    // Initialise a serial object (do this at the start of the program)

// Inside the setup() function:
String portName = Serial.list()[0];    // Get the first portname on the list (this may need to be changed to get the right one)
myPort = new Serial(this, portName, 9600);

```

to connect from the computer.

Once you have done this, you can use the functions

```
myPort.write();

```

in processing, and

```
val = Serial.read();

```

To recieve data on the arduino.

Source (see here for more info): https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing/all

---
Tags: java
---


title: Arduino - read multiline serial input

text:
# Question
Title: Arduino - read multiline serial input
I'm trying to get data from a heat counter via the serial, the format of the response is:

```
t1=ХХХ.ХХ   t2=ХХХ.ХХ   t3=ХХХ.ХХ   t4=ХХХ.ХХ
P1=ХХ.ХХ    P2=ХХ.ХХ
VolSpd1=ХХ.ХХХ  VolSpd2=ХХ.ХХХ
MassSpd1=ХХ.ХХХ MassSpd2=ХХ.ХХХ
HeatSpd1=Х.ХХХ  HeatSpd2=Х.ХХХ
SumVolume1=Х.ХХХХХХХ    SumVolume2=Х.ХХХХХХХ
SumMass1=Х.ХХХХХХХ  SumMass2=Х.ХХХХХХХ
SumHeat1=Х.ХХХХХХХ  SumHeat2=Х.ХХХХХХХ
PowTime=Х.ХХХХХХХ   PowOffTime=Х.ХХХХХХХ
MeasTime1=Х.ХХХХХХХ MeasTime2=Х.ХХХХХХХ
UnMeasTime1=Х.ХХХХХХХ   UnMeasTime2=Х.ХХХХХХХ

```

I managed to get the data and parce it on arduino but only from the first line. I do not know how to get all other data.

# Answer
Since the format is just = , I'd parse it this way, instead of relying on newlines.

Just treat them as whitespace. So buffer all data till an `=` sign is found, store the buffer as the variable name, then read until you get something other than a digit or decimal point. Then store this as the value. Then do something with the value based on the variable name. Then read and ignore all following whitespace (spaces, tabs, newlines, carriage-returns). And start back from the top.

That way the parse will never get out of whack when some data get missing or something else goes wrong in the serial stream.
> 3 votes

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


# Question
Title: Serial print message results in gibberish
I'm trying to print messages to the serial monitor, and all I get is some unreadable format.

Looping `Serial.println("Wait...!");` gives me the following results:

```
ö’ö’ƒÕ•¬ƒ´¼Õƒö“ƒ²ƒƒƒ¬‘¼¬Õ”’“ƒ¬•

```

Why is it unreadable, and how do I make it print a readable format?

# Answer
> 3 votes
This "weird" result usualy happens when you select then wrong baud rate or a different one then the one you beginned the serial communication with in the program. Thus by using `Serial.begin(9600);`, you have to make sure that the serial monitor is actually set to a baud rate of 9600.

---
Tags: arduino-uno, serial, programming
---


# Question
Title: How do I code my arduino to return a throttle servo to idle?
I have an Arduino powering a small 180 degree Parallax servo that is used to control the throttle link for a small engine. I have code right now that will allow me to open/close the throttle (in either 1/4 or 1/5 increments) using the keyboard of my computer. This is well and fine but I really want to get it working so that when I press (hold) the hot key "t" the throttle will open but when I release the hot key I want the servo to cycle back to its original position (where the engine idles). If you have suggestions I would really appreciate them.

I am using Putty (Putty.org) to interface with the serial monitor so the arduino knows when 't' is pressed.

My Arduino code is just below this bit of wording (55 deg and 0 deg are the bounds of my throttle link, 55 is closed throttle (idle) and 0 is open throttle):

```
#include <Servo.h>

Servo servo;

int pos = 55;  // Stores the position (angle) of the servo. Range is [0, 180].

void setup()
{
  Serial.begin(9600);
  servo.attach(9);  // Attaches the servo on pin 9 to the servo object.
  servo.write(55);  // Resets the position.
}

void loop()
{
  if (Serial.available())   // Returns true if there is serial input.
{
    char ch = Serial.read();

    if (ch == 't')

      {if (pos <= 55)
        {pos -= 11.25 ;}}

     else

      {if (pos >= 0)
        {pos += 11.25 ;}}

    // Now ask the servo to move to that position.
    servo.write(pos);
    // Mechnical limitation to the frequency of commands given.
    delay(15);
}

}

```

# Answer
If your terminal program uses key-repeat, then let each 't' operate the throttle for just slightly longer than the repeat period (slightly longer than twice the period, if you want to tolerate single dropped characters). After that period without another 't', close the throttle. One implementation would be to (re-)start a countdown timer every time you see a 't', and close the throttle when the timer goes to zero.

No auto-repeat? You'll have to simulate it with your finger (and code for a somewhat longer repeat interval, of course).
> 0 votes

---
Tags: arduino-due, servo
---


# Question
Title: Error on UNOr3--> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device
When I try to upload my program on the Arduino Uno Chinese clone, It says

```
 -> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

```
* My Arduino Programmer: ArduinoISP
* My Arduino Software version: 1.6.8
* My OS: Linux Mint

Can you help me fix this error?

# Answer
This could be any number of different problems. Here are several common causes:

1. You have multiple USB serial port devices connected to your computer. Try using the command `ls -l /dev/ttyUSB*` to check if your computer thinks there are more than one terminal USB device. Disconnect all of them, then only connect the Arduino Uno. Then repeat the check.
2. You do not have permissions. This is tricky to check as Linux offers a flexible but complicated root, group and user permission paradigm. **You should NOT make a habit of this**, but, for a quick check, you can try running the Arduino application as root and check if you can upload a sketch to the Arduino Uno.
3. You have a counterfeit FTDI chip on your Arduino Uno that has been rendered useless by certain versions of the Windows FTDI Driver. The USB IDs can get reset to useless values. I believe the current FTDI Windows Driver no longer does this.
4. You did not install the Linux FTDI driver. A driver is a program to abstract the hardware from the application. In this way, different hardware can be treated the same by the application, simplifying the application. However, the wrong driver/hardware combination may not work as expected.
> 2 votes

# Answer
I had the same problem and solved with the suggestion of ndemou:

```
sudo chown root:YOURUSERNAME /dev/ttyUSB0

```
> 0 votes

---
Tags: arduino-uno, arduino-ide, avrdude, clones
---


title: Vibration sensor for arduino

text:
# Question
Title: Vibration sensor for arduino
I need vibration sensor for my project. I have found many sensors similar to this one. But it seems, that this sensor outputs only zeros for "non-hit" state and ones for "hit state". And I need something that can output levels of vibration, not only presence/abscense.

So is there any high-resolution vibration sensor for arduino?

Thank you!

# Answer
I assume the OP wants the frequency of the vibration, which an accelerometer such as the ADXL345 won't give.

I have two workarounds: if the expected vibration frequency is low, say, under 100Hz, use instead an on/off vibration sensor (adafruit has them for under a dollar) and count the number of transitions. If it's more, how about a microphone and a band-pass filter?
> 0 votes

# Answer
The MPU-6050 is a very low-price 3 axis gyroscope and accelerometer with both SPI and I2C interface options.

I found mine here: https://smile.amazon.com/gp/product/B00KKR9ORI

---

EDIT: Removed statement that it is accurate enough for this, based on comment.
> 0 votes

---
Tags: sensors
---


# Question
Title: 20x4 LCD will write but then won't update
I am controlling a solar tracker, and it needs to be reset every 10 minutes or it loses its mind. My program works fine, controlling power relays, so I have added I2C&Power to be able to see the status remotely. For now it is set up on the workbench with fairly short cables. I also have a RTC and the i2cscanner finds them all..

LCD init code is pretty basic:

```
// 20 x 4  LCD Display
#include LiquidCrystal_I2C.h
// set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

```

then

```
lcd.begin(20,4);
lcd.clear();
lcd.setCursor(2,0);
lcd.print("PV Control 3.9");

```

My LCD (20x4) works fine at first, writing the top line with the name of the program, then the bottom line with a temperature reading, then every 10 minutes I need the second line to show when the power is off for 10 seconds. It shows "power off" just fine, but after the delay(10000) it is supposed to overwrite that line with "power on" but nothing changes...

```
Serial.println("POWER OFF");
lcd.setCursor(4,1);
lcd.print("-Power Off- ");
digitalWrite(power1,HIGH);  // DC HOUSE power off
digitalWrite(power2,HIGH);  // DC HOUSE power off
delay(10000);
Serial.println("POWER ON");
lcd.setCursor(4,1);
lcd.print("-Power On-  ");
digitalWrite(power1,LOW);  // DC HOUSE power on
digitalWrite(power2,LOW);  // DC HOUSE power on

```

The problem is that it continues to say "power off" and doesn't overwrite it.

I can see from the Serial Monitor that the program is running fine, but the LCD doesn't change after the first set of lcd.prints at those character positions.

I haven't heard of anybody having this problem, but perhaps someone out there know about this. Any suggestions would be very welcome.

Question is: How can I make the LCD update lines that have been originally written?

---

UPDATE: Problem solved by simply clearing and rewriting the display when things change. I can't debug libraries but at least it is working now.

# Answer
> -1 votes
Ah ha. I solved it by using lcd.clear() and simply repainting the entire display with every change. I have much simpler LCD programs that don't require doing this, but it worked in this instance.

Same code as above, but with this before each power notification:

```
lcd.clear();
lcd.setCursor(2,0);
lcd.print("PV Control 3.9");

```

etc...

---

UPDATE: Now that I have two 20x4 LCD screens showing readings from two separate Arduinos (PV Controls and Weather station) I have discovered that it is very important to keep the screen writes to a minimum. No time delays in between writing parts of the screen, for instance (like when I had Serial.print statements in there for debugging), doing all the readings and calculations before writing the screen, and timing the screen updates to be infrequent, like on the order of 65 seconds for weather and 10 minutes for the PV. I2C does not have collision detection so it is important to try to prevent the two screens from being updated at the same time. The I2C&Power arrangement is working great. One source of power is all it takes to activate the entire network.

---
Tags: arduino-nano, lcd
---