title: MIDIUSB - Why is the command put twice?

text:
# Question
Title: MIDIUSB - Why is the command put twice?
Consider this function:

```
void noteOn(uint8_t pitch) {
  midiEventPacket_t noteOn = {0x09, 0x90 | 9, pitch, 127};
  MidiUSB.sendMIDI(noteOn);
}

```

`midiEventPacket_t` is defined as:

```
typedef struct
{
    uint8_t header;
    uint8_t byte1;
    uint8_t byte2;
    uint8_t byte3;
}midiEventPacket_t;

```

The first nibble of the first byte of a MIDI message is the command: `0x90` \["note on"\] and the second nibble is the MIDI channel: `9`, so what's sent over the wire should be `0x99` meaning "Note On, channel 9", with the two more bytes representing the pitch and the velocity.

My question is, why do all of the examples start with: `{0x09, 0x90 | 9,`? I'm not understanding the use of the struct here. Intuitively, I thought I would need: `{0x90 | 9, pitch, 127, 0}`. Why do all of the examples have that seemingly strange syntax?

# EDIT

After getting a great explanation below, here's my new function!

`void noteOn(uint8_t pitch) {
 midiEventPacket_t noteOnPacket;
 noteOnPacket.header = USB_CABLE_NUMBER | (MIDI_NOTE_ON >> 4);
 noteOnPacket.byte1 = MIDI_NOTE_ON | CHANNEL;
 noteOnPacket.byte2 = pitch;
 noteOnPacket.byte3 = MIDI_BUTTON_ON_VELOCITY;
 MidiUSB.sendMIDI(noteOnPacket);
}`

# Answer
> 2 votes
From the specs:

> The first byte in each 32-bit USB-MIDI Event Packet is a Packet Header contains a Cable Number (4 bits) followed by a Code Index Number (4 bits). \[...\]
>
> \[...\]
>
> The Cable Number (CN) is a value ranging from 0x0 to 0xF indicating the number assignment of the Embedded MIDI Jack associated with the endpoint that is transferring the data. The Code Index Number (CIN) indicates the classification of the bytes in the MIDI\_x fields. The following table summarizes these classifications.
>
> CIN | MIDI\_x Size | Description
>
> \[...\]
>
> 0x9 | 3 | Note-on
>
> \[...\]

No rationale is given *why* the CIN is required if the full message is also included, but it could be used for quicker routing of the event to the routine that will process it.

---
Tags: programming, c, midi, struct
---


# Question
Title: Can I use an ESP8266 as a replacement for an original Arduino?
I want to learn Arduino, but I'd like to use the ESP8266 as it has built in wifi. I understand that I can use the Arduino IDE for this board.

However, what about books and resources out there? Are these two boards so similar that I can follow original Arduino examples? I'm primarily thinking in terms of connectivity to, say, sensors.

I'm a beginner at this and will not be able to figure out how to bridge compatibility gaps.

# Answer
> 0 votes
Yes, No and Maybe is the best answer :)

Assuming that you want to replace a Arduino Uno board with an ESP8266 **based** board. Your best choice at the moment would be a Wemos D1. It has the same form factor as the UNO, but it has less pins, 9 digital and 1 analog.

If you are not bothered about the form factor, you could also try a Node-LUA, or a Wemos D1 Mini. If you have steady hands you could try just using the heart of these three boards directly, which is usually called an ESP8266-12E, but it has 1mm pitch and no voltage regulation.

There are a lot of sites around that have tutorials on using ESPs. They are mostly interchangeable with Arduino boards from a software perspective, they have more memory and a faster clock speed.

The biggest difference between an Arduino based board and an ESP board is **most** Arduino use 5v and **most** ESP based boards use 3.3v. Make sure you read the datasheet before you hook up you sensors.

There is an ESP-32 as well. This is not interchangeable with an Arduino Uno at the moment.

# Answer
> 0 votes
> Are these two boards so similar that I can follow original Arduino examples?

for most applications, an mcu is useful not because of its core - which is almost fully transparent to a high level language programmer - but because of its peripherals: timers, serial comms, interrupts, adc/dac, ...

sure, there are applications that don't require those functionalities; or those functionalities could be emulated. but you will find it much easier if the mcu does have those functionalities.

so all it takes is to take a look at the datasheet of your esp and ask yourself if you see those peripherals. after that, the answer is clear.

---
Tags: esp8266
---


# Question
Title: SD card fails to write every 5 or 6 minutes
My SD card initializes fine in the beginning. It finds the right file and opens it. However, after 5 or 6 minutes of data logging, the error "file not found" appears on my LCD. Why would this be the case? I need this to work consistently for at least an hour, this 5 to 6 minutes will not do.

Also, in my code the "sv" and "cpm" data is not yet initialized, due to another problem incorporating a sensor. I left these in there, and the data is just logged as 0 for those variables.

```
#include <SPI.h>
#include <MPL115A1Lib.h>  // Pressure Sensor MPL115A1
#include <DHT.h>  // Temperature and Humidity Sensor RTH03
#include <U8glib.h>  // LCD Display 128x64
#include <floatToString.h>  // Converts floats to strings
#include <GPS610F.h>  // GPS-610F Module
#include <RFZuluArduino.h>  // Zulu 2km RF Module
#include <SD.h> //SD data logger

//----- Defining Modules and Variables ------//
// Pressure Sensor
MPL115A1Lib PressSens;  // Defines Pressure Sensor for library
#define FT_TO_M(x) ((long)((x)*(0.3048)))
#define KPA_TO_INHG(x) ((x)*(0.295333727))
#define KPA_TO_MMHG(x) ((x)*(7.50061683))
#define KPA_TO_PSIA(x) ((x)*(0.145037738))
#define KPA_TO_KGCM2(x) ((x)*(0.0102))
#define INHG_TO_PSIA(x) ((x)*(0.49109778))
#define DEGC_TO_DEGF(x) ((x)*(9.0/5.0)+32.0)

float press_pKa = 0;
float temp_c = 0;
long alt_ft = 0;
char charPress[7];  // Stores pressure
char charTemp[6];  // Stores temperature in C
char charAlt[5];  // Stores altitude
// Temperature & Humidity Sensor
#define DHTPIN 48     // Defines signal pin connection
#define DHTTYPE DHT22   // Defines Sensor model # DHT22 (RTH03)
DHT dht(DHTPIN, DHTTYPE);  // Defines the Temp/Humd Sensor
float t = 0;  // temp
float h = 0;  // rel. humd.
float f = 0;  // temp in f
float hi = 0;  // heat index
char rh[6];  // Stores Relative Humidity
char tempC[6];  // Stores Temperature in °C
char tempF[7];  // Stores Temp in F
char heatIndex[7];  // Stores heat index
char degree[3] = {176, 67};  // Stores °C symbol
char degreeF[3] = {176, 70};  // Stores °F symbol
// LCD Display
U8GLIB_ST7920_128X64_4X u8g(41, 42, 43);  // Defines LCD pins (SPI: EN = 41, RW = 42, RS = 43)
// GPS Module
GPS610F gps(17, 16, 28, 26, 44, 27, 9600);  // Defines GPS pins (SDI, SDO1, SDO2, PIO, PPS, RST, baudRate)
String gpsData;
char charGPS[82] = "";
String strnmeaProto;
String strutcTime;
String strgpsStatus;
String strlatitude;
String strnsIndicator;
String strlongitude;
String strewIndicator;
String strspeedOverGnd;
String strcourseOverGnd;
String strutcDate;
String strmagVarDegrees;
String strmagVarDirection;
String strmodeIndicator;
String strcheckSum;
char nmeaProto[6] = "";
char utcTime[11] = "";
char gpsStatus[2] = "";
char latitude[11] = "";
char nsIndicator[2] = "";
char longitude[11] = "";
char ewIndicator[2] = "";
char speedOverGnd[6] = "";
char courseOverGnd[6] = "";
char utcDate[7] = "";
char magVarDegrees[6] = "";
char magVarDirection[2] = "";
char modeIndicator[2] = "";
char checkSum[3] = "";
char tempTime[9] = "";
char tempDate[9] = "";
char tempLat[12] = "";
char tempLong[13] = "";
// RF Module
RFZuluArduino rf(15, 14, 2, 3, 4, 5, 4800);  // Defines the RF module's pins (rx1, tx1, RTS, CTS, RST, PD, baudRate)
//Data Logger
const int chipsSelect = 10;
File Data;
String Header = "DATE(utc)  TIME(utc)  STATUS  MODE  LATITUDE(deg)  LONGITUDE(deg)  SPEED(km)  COURSE(deg)  Temperature(C)  Temperature(F)  Humidity(%RH)  Heat Index(F)  Pressure(kPA)  Altitude(m"; //CPM  uSV/hr";
int dcounter = 0;
//Geiger Counter
unsigned int gcount = 0;
unsigned int countStartTime = 0;
int countsPerMinute;
float coefficientOfConversion = 140.0 / 60000.0;
float sV = 0;
String str;  // temporary string
int draw_state = 0;
int tracker = 0;

void setup() {
  pinMode(53, OUTPUT);
  dht.begin();
  if (!SD.begin(10, 11, 12, 13)) {
    // see if the card is present and can be initialized:
    u8g.firstPage();
    do {
      drawCardError();
    }
    while (u8g.nextPage());
    while (1);  // don't do anything more:
  }
  Serial1.begin(9600);
  // start serial port for geiger counter
}

void loop() {
  delay(1000);
  //----- Get Sensor Data -----//
  // Temp/Humid
  h = dht.readHumidity();
  t = dht.readTemperature();
  f = dht.readTemperature(true);
  /*if (isnan(h) || isnan(t) || isnan(f)) {  // check for failed reading from sensor
    return;
    }*/
  hi = dht.computeHeatIndex(f, h);
  // Pressure Sensor
  press_pKa = PressSens.calculatePressurekPa();
  alt_ft = PressSens.calculateAltitudeFt(press_pKa);
  // GPS
  gpsData = gps.getData();
  strnmeaProto = gps.dataFields(0);
  strutcTime = gps.dataFields(1);
  strgpsStatus = gps.dataFields(2);
  strlatitude = gps.dataFields(3);
  strnsIndicator = gps.dataFields(4);
  strlongitude = gps.dataFields(5);
  strewIndicator = gps.dataFields(6);
  strspeedOverGnd = gps.dataFields(7);
  strcourseOverGnd = gps.dataFields(8);
  strutcDate = gps.dataFields(9);
  strmagVarDegrees = gps.dataFields(10);
  strmagVarDirection = gps.dataFields(11);
  strmodeIndicator = gps.dataFields(12);
  strcheckSum = gps.dataFields(13);

  //----- Convert to Transmit -----//
  // Temp/Humid
  floatToString(rh, h, 1);  // relative humidity
  floatToString(tempC, t, 1);  // temperature in C
  floatToString(tempF, f, 1);  // temp in F
  floatToString(heatIndex, hi, 1);  // heat index
  // Pressure Sensor
  str = String(FT_TO_M(alt_ft));  // convert altitude in ft to m
  str.toCharArray(charAlt, 5);  // covert string to char array
  floatToString(charPress, press_pKa, 2);
  // GPS Module
  gpsData.toCharArray(charGPS, 80);  // convert string to char array
  strnmeaProto.toCharArray(nmeaProto, 6);
  // time
  strutcTime.toCharArray(utcTime, 11);
  tempTime[0] = utcTime[0];
  tempTime[1] = utcTime[1];
  tempTime[2] = ':';
  tempTime[3] = utcTime[2];
  tempTime[4] = utcTime[3];
  tempTime[5] = ':';
  tempTime[6] = utcTime[4];
  tempTime[7] = utcTime[5];
  strgpsStatus.toCharArray(gpsStatus, 2);
  // latitude
  strlatitude.toCharArray(latitude, 11);
  strnsIndicator.toCharArray(nsIndicator, 2);
  tempLat[0] = latitude[0];
  tempLat[1] = latitude[1];
  tempLat[2] = 176;   // °
  tempLat[3] = latitude[2];
  tempLat[4] = latitude[3];
  tempLat[5] = latitude[4];
  tempLat[6] = latitude[5];
  tempLat[7] = latitude[6];
  tempLat[8] = 39;  // '
  tempLat[9] = ' ';
  tempLat[10] = nsIndicator[0];
  // longitude
  strlongitude.toCharArray(longitude, 11);
  strewIndicator.toCharArray(ewIndicator, 2);
  tempLong[0] = longitude[0];
  tempLong[1] = longitude[1];
  tempLong[2] = longitude[2];
  tempLong[3] = 176;   // °
  tempLong[4] = longitude[3];
  tempLong[5] = longitude[4];
  tempLong[6] = longitude[5];
  tempLong[7] = longitude[6];
  tempLong[8] = longitude[7];
  tempLong[9] = 39;  // '
  tempLong[10] = ' ';
  tempLong[11] = ewIndicator[0];
  strspeedOverGnd.toCharArray(speedOverGnd, 6);
  strcourseOverGnd.toCharArray(courseOverGnd, 6);
  // date
  strutcDate.toCharArray(utcDate, 7);
  tempDate[0] = utcDate[0];
  tempDate[1] = utcDate[1];
  tempDate[2] = '/';
  tempDate[3] = utcDate[2];
  tempDate[4] = utcDate[3];
  tempDate[5] = '/';
  tempDate[6] = utcDate[4];
  tempDate[7] = utcDate[5];
  strmagVarDegrees.toCharArray(magVarDegrees, 6);
  strmagVarDirection.toCharArray(magVarDirection, 2);
  strmodeIndicator.toCharArray(modeIndicator, 2);
  strcheckSum.toCharArray(checkSum, 3);
  // transmit the data
  rf.transmit(gpsData, tempC, rh, charPress);
  //-----Writes Data to SD Card-----//
  Data = SD.open("DATA", FILE_WRITE);
  if (!Data) {
    u8g.firstPage();
    do {
      drawFileError();
    }
    while (u8g.nextPage());
    while (1);  // don't do anything more:
  }
  dcounter++;
  if (dcounter == 1) {
    Data.println(Header);
  }
  Data.print(strutcDate + "     " + strutcTime + "   " + strgpsStatus + "      " + strmodeIndicator + "     " + strlatitude + "     " + strlongitude + "     " + strspeedOverGnd + "        " + strcourseOverGnd + "          ");
  Data.print(t);
  Data.print("          ");
  Data.print(f);
  Data.print("            ");
  Data.print(h);
  Data.print("         ");
  Data.print(hi);
  Data.print("            ");
  Data.print(press_pKa);
  Data.print("         " + str + "  ");
  Data.flush();
  Data.print(countsPerMinute);
  Data.print("  ");
  Data.println(sV, 5);
  Data.flush();
  //----- Output to LCD Display -----//
  u8g.firstPage();
  do {
    draw();
  }
  while (u8g.nextPage());
  tracker++;
  if (tracker <= 2) {
    draw_state = 0;
  } else if (tracker <= 5) {
    draw_state = 1;
  } else if (tracker <= 8) {
    draw_state = 2;
  } else {
    tracker = 3;
  }
}

//----- LCD Display Drawings -----//
void drawCardError() {
  u8g.setColorIndex(1);
  u8g.setFont(u8g_font_baby);
  u8g.drawStr(12, 32, "Card Failed, or not present");
}

void drawFileError() {
  u8g.setColorIndex(1);
  u8g.setFont(u8g_font_baby);
  u8g.drawStr(5, 32, "Error opening DATA");
}

void draw(void) {
  LCDprepare();
  switch (draw_state) {
    case 0:
      AECLlogo();
      break;
    case 1:
      SensorInfo();
      break;
    case 2:
      GpsInfo();
      break;
  }
}

```

# Answer
Might be a flaky SD card, you get that sometimes. Try changing to another card and see if it helps.

SD card formatter tool might also be useful: https://www.sdcard.org/downloads/formatter\_4/
> 1 votes

# Answer
Answered by OP in the comments

"fixed, I have remvoed some of the ending code thought. They were just functions for the lcd"
> 0 votes

# Answer
Are you sure there are no rollovers / overflows? Keep in mind the limitations of FAT16, max volume size is 2GB, and only with the max sector size of 512B.

At minimum `dcounter` will overflow in 9 hours if you log every second.
> 0 votes

# Answer
OK, it looks like this question is going to be floating with not accepted answer for all of eternity since the poster clearly isn't responding to comments.

But if it works for a few minutes and then dies it's probably something silly like opening the same file every second and never closing that's the cause of the issues rather than a bad SD card or a counter that will overflow after 9 hours.
> 0 votes

---
Tags: arduino-mega
---


title: is there a timeout for Ethernet.begin?

text:
# Question
Title: is there a timeout for Ethernet.begin?
I'm working on a project, but just for testing, I haven't connected it to the internet yet, even though the code SHOULD be ready to roll out.

When trying to test some of my code with the serial console, I realized my program was locking up and I traced it down to here. Now my arduino uno and ethernet shield isn't currently connected to the internet, so my question is, how could I timeout this function so that I can keep my program running when there's no internet to connect it too.

Here's my code in the setup function

```
if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

```

If anyone has any thoughts or suggestions, I'd definitely appreciate it.

# Answer
The default timeout is 1 minute for DHCP. There is also a response timeout, and in the library millis is used for timeouts. I don't know if there is a timeout for everything, but I suppose there is.

If it stops working when no ethernet cable is connected, that would be a bug. If something like that is in the library, then you have no way to bypass the Ethernet.begin when it took too long. How long did you wait ?

This is the source code for Ethernet.begin: Ethernet.cpp
> 3 votes

---
Tags: arduino-uno, ethernet
---


title: 15x15x15 LED cube with thermal sensors

text:
# Question
Title: 15x15x15 LED cube with thermal sensors
I'm trying to wrap my head around a public art project that I've recently received funding for, and I'm hoping that someone here can help me with a bit of guidance.

The concept I'm working on is a kind of 'digital campfire' that builds and falls in intensity as people approach and depart.

The way I imagine it working is with a 15x15x15 RGB LED cube that plays fire-like animations of varying intensities in response to the presence of nearby people - detected by a 360 degree array of thermal sensors (probably something like Omron D6T sensors, rather than IR movement sensors).

Full disclosure: I'm an Arduino noob. I've tinkered with LEDs and soldering, but even the thought of building a non-responsive 4x4x4 LED cube hurts my brain. That said, I have a couple of months up my sleeve, a bit of cash, and a willingness to forge new neural pathways to get this done.

My main questions at this point are:

* Can an Arduino even handle the processing power required to run a thermal activated 15x15x15 LED cube, even with multiplexing?
* I'm considering 15-cubed because I want the object to have a fairly large physical presence, and have a relatively high definition. Is there any game-changing reason I should seriously consider something smaller? I anticipate being able to connect to a 240v power outlet (I'm in Australia), but running off battery would be ideal.
* How difficult would it be to build a 360 degree thermal sensor array consisting of, say, 8 separate thermal sensors? The programming is clearly beyond me, and I expect to out-source this...

Any help or suggestions would be hugely appreciated. And don't be gentle – if my expectations need to be 're-aligned' to something closer to reality, I'd rather that happen sooner than later.

Cheers,

Adam

# Answer
> 1 votes
The answer to "Can an Arduino even handle the processing power" is probably No, but no one can really answer because you have not specified the problem.

Just for starters you have \>3k LEDS, if you want to control RGB that means ~10k devices.

To operate at moderate brightness (10mA per LED) you will need at least a 35A power supply. This will require external high power circuitry to switch/control.

Do you need to individually control each LED? To control 10k devices you will need serious external circuitry.

Do you need to control brightness or just switch individual devices on/off?

You could probably achieve a solution, but 15 modules each controlling 15\*15 LEDS may be achievable, 32 or 64 is probably more realistic.

Either way soldering by hand would be impractical, you need to design a board for each module.

You could use an Arduino on each module, but a ATMega chip would achieve the same end, without the unnecessary peripheral circuitry.

# Answer
> 0 votes
firstly we need a bit more detail, I'm assuming by saying a 15x15x15 cube you actually mean a cube with a 15x15 array of LEDs on each face, so you would have a total of 1350 LEDs. we also need to know if you intend to have just single colour LEDs of whether you want multi colour or even RGB with full control (like a monitor) assuming you only want single colour with on/off control then look into the MAX7219 or MAX7221 IC's, these can be bought with LED matrix's already fitted, and each IC can drive an 8x8 matrix of LEDs, so you would need 4 ICs to do each side (these can be daisy chained) and so a total of 24 ICs for the whole cube. but note that that would allow for 16x16 on each side.

the arduino can easily drive this many, what you need to consider is how often you want the LEDs to "update" i.e. the frame rate. the more you try and drive the slower you can drive it, however from experience i believe the arduino could easily drive that many LEDs in this arrangement.

on the subject of current the MAX72xx ICs work by multiplexing the output for you, so at most only 8 out of each 64 LEDs are on at any one time, so if you drive each at 10mA your maximum current would be 1.7A, probably a bit much for batteries (unless you use something big, AA's or a 9V won't cut it.) but still reasonable.

if you wanted individual brightness control things get more complicated, and the rate at which you could update the outputs would sharply drop off. I still think it would be feasibly for this many LEDs but you may find your update rate is only 10-20 times a second so any motion may not appear very smooth. but this way will require a lot more wiring, and will be a lot more complex to program.

if you want full RGB control then the amount of connections and components required would grow to ridiculous proportions, you would need 3 connections plus power to each LED so about 4000 connections between your control circuitry and your LEDs, and your current requirements would go through the roof due to so many LEDs being on at the same time.

and if I read wrong and you actually want 3375 LEDs on each face, for a total of 20250 LEDs then this becomes extremely impractical, even with output multiplexing (mentioned above in the MAX72xx bit) the current requirements would be insane. not to mention the time taken to update all those LEDs would drastically slow down how quickly you could update them. even at a max data rate of 30MHz (SPI) you will probably only be able to update your LEDs at around 1-2 times a second, and there would not be enough RAM in the arduino to remember the previous output states when you are calculating your next ones.

a raspberry pi may be more suitable from that point of view, but the current and the update rate would still be a problem.

---
Tags: arduino-mega, programming, sensors, led
---


# Question
Title: How to create a String with Temperature Value From An int Value
The following code is for a temperature controlled relay which turns a DC fan on and off when the temp threshold is breached. I'm using a DS1820 Temperature sensor and the code for this has several variables including WholeDegrees & FractDegrees Which are the whole number of degrees and the fractional number of degrees. I'm wanting to be able to set the threshold to lets say 23.25 Degrees so that when the temp rises above that then the fan comes on.

I'm trying to do this by using a two condition if statement howeveer, the FractDegrees are causing me a problem because if condition 1 is true and and the WholeDegrees is greater than 22 but the second condition the FractDegrees is lower than 25 then the relay turns the fan off again. So I get the fan turning on for a split second and then off, then on & off again which isn't a problem when the temperature sensor is at roughly the temp I want to set the threshold at but when it's at say 40 Degrees The fan cuts in and out whilst cooling until the sensor is roughly at the threshold value again.

I have kinda had a go already but failed which you might see in the //'d out code but is there a way that I can put these two values WholeDegrees & FractDegrees into a string so that I could have a string with the temp value and then use a single condition if statement to turn the fan on and off by checking the strings value instead?? I'd want the string to be "WholeDegrees.FractDegrees" So that I could just use the if statement to ask if the temp was greater than 23.25 degrees. The code I tried returned a value of "0.0" which obviously wasn't the temperature value but I couldn't understand why......

```
#include <OneWire.h>
int inPin = 10; // define D10 as input pin connecting to DS18S20 S pin
OneWire ds(inPin);
int relay1 = 8; // define relay Signal Pin to Digital Output 8
//String stringOne, stringTwo, stringThree;

void setup(void) {
  Serial.begin(115200);
  pinMode(relay1, OUTPUT);

}

void loop(void) {
  int HighByte, LowByte, TReading, SignBit, Tc_100, WholeDegrees, FractDegrees;
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];
  //stringOne = String(WholeDegrees);
  //stringTwo = String(".");
  //stringThree = String(FractDegrees);

  if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);

  delay(250);

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);

  for ( i = 0; i < 9; i++) {
    data[i] = ds.read();
  }
  Serial.print("Temperature: ");
  LowByte = data[0];
  HighByte = data[1];
  TReading = (HighByte << 8) + LowByte;
  SignBit = TReading & 0x8000;
  if (SignBit)
  {
    TReading = (TReading ^ 0xffff) + 1;
  }
  Tc_100 = (6 * TReading) + TReading / 4;
  WholeDegrees = Tc_100 / 100;
  FractDegrees = Tc_100 % 100;
  if (SignBit)
  {
    Serial.print("-");
  }
  Serial.print(WholeDegrees);
  Serial.print(".");
  if (FractDegrees < 10)
  {
    Serial.print("0");
  }
  Serial.print(FractDegrees);
  Serial.print(" C\n");
  //int tempthresh;
  //tempthresh = (stringOne&&stringTwo&&stringThree);
  //stringOne += stringTwo;
  //stringOne += stringThree;
  //Serial.println(stringOne); // RETURNS VALUE OF 0.0 When I want Temperature Value to be returned
  //Change The Figure "22" To Adjust The Temperature Threshold To Turn Fan On.
  //Currently Set to Keep Temperature At Or Below 23.25 Degrees
  if ((WholeDegrees > 22)&&(FractDegrees >= 25)) digitalWrite(relay1, HIGH);
  else digitalWrite (relay1, LOW);
  delay(250);

}

```

# Answer
> 1 votes
In the Arduino IDE, in the Library Manager, are the OneWire library (by a lot of people including Paul Stoffregen) and the DallasTemperature library (by Miles Burton and others). You need both.

The DallasTemperature makes using the DS18B20 easier. Especially when there is more than one DS18B20 sensor connected. It can get the temperature by index or with the unique ID number that each DS18B20 has.
Start with the examples of the DallasTemperature that appear in the Arduino IDE menu, for example the "simple" example.

Then you have the temperature as a float, and you can compare it with 23.25.

Even the OneWire library comes with the DS18x20\_Temperature example that shows how to calculate the temperature as a float.

# Answer
> 1 votes
As has been pointed out looking for a temperature to that level of accuracy on a sensor that is only accurate to 1 degrees in an application which only needs accuracies of a few degrees is just adding extra complications for no real world benefit. In this situation just looking at the whole number part is good enough.

But ignoring the final application this is still a programming question which should be answered.

Using strings to compare numerical values is a very very bad idea. Even ignoring the wasted memory and CPU time involved converting things to a string performing a string to string comparison to evaluate the value is often problematic at best. Normally you'd do it by converting the string to a float.

Which brings us to the easiest solution, as Jot indicated, use a float:

```
float temp = WholeDegrees + FractDegrees/100.0;
if (temp >= 23.25) { ... }

```

That's by far the clearest and easiest way to perform the calculation but floats are CPU intensive. There are other, faster ways to do it.

You could do everything in 100ths of a degree, this is a better because ints are a lot quicker to work with and take up less memory than floats. But unless you add comments it's not quite as clear as the float version.

```
int temp = WholeDegrees*100 + FractDegrees;
if (temp >= 2325) { ... }

```

Or finally you could do something like your original attempt but fixing the logic. This would probably be the fastest and lowest memory of the lot since it only involved 8 bit calculations which on an 8 bit processor is a big benefit. But of the 3 it's also the least obvious what is happening.

```
if ( (WholeDegrees > 23) || ( (WholeDegrees == 23) && (FractDegrees >= 25)) ) { ... }

```

# Answer
> 0 votes
This code goes to some lengths to separate the temperature into whole- and fractional-degrees, and to do it in floating point. Unless there is more to the job that isn't shown in this code and requires either of those representations, you can do the whole job with integers, much more simply.

The DS18x20 series return temperatures as fixed-point integers. The "DS1820" that you referred to has only 1/2 degC resolution so testing to 0.25 degrees won't be useful. It delivers the result with 1 fraction-bit (binary point to the left of bit-0). This is equivalent to the number of 1/2-degreesC:

```
DS1820
+---------------+---------------+---------------+---------------+
|   |   |   |   |   |   |   |   |   |etc|16 | 8 | 4 | 2 | 1 |.5 |
+---------------+---------------+---------------+-----------^---+

                                                 binary point

```

If you're using the DS18b20 or DS18s20, the result is delivered with 4 fraction bits, binary point to the left of bit-3, or the number of 1/16-degreesC:

```
DS18x20
+---------------+---------------+---------------+---------------+
|   |   |   |   |   |   |etc|16 | 8 | 4 | 2 | 1 |.5 |.25|   |   |
+---------------+---------------+---------------^---------------+
                                     binary point       .125 .0625

```

To detect a temperature threshold you only need to compare that single 16 bit number to the equivalent 16-bit representation of the threshold value.

Using your threshold of 22.25 degC, you'd compare to "44" for a DS1820: (2 * 22.25). The remaining fraction, .5, gets truncated off. Or compare to "356" for one of the DS18x20 types: (22.25 * 16).

This function to converts a 4-place fixed point number to an ASCII decimal string for printing:

```
/*
 * Name:          q12p4toa
 *
 * Function:      Converts a q12p4 binary number to ASCII decimal
 *
 * Description:   Convert a 4 binary-places signed fixed point number (Q12.4) to
 *                an ASCII string as: sdddd.dddd
 *                Up to 3 left zeroes are replaced with spaces; 4 decimal places
 *        are always generated.
 *
 * Parameters:    pbuf            - -> array of at least 10+1 bytes
 *            q12p4         - A fixed-point number to 4 binary places
 *
 * Returns:       pbuf
 *
 */

char *q12p4toa(char *pbuf, int16_t fixp)
{
   // If neg, write the sign and negate the number
   *pbuf++ = ' ';      // don't use this leading space if sending to Blynk
   if( fixp < 0 ){
      *pbuf++ = '-';
      fixp = -fixp;
   }
   // Handle the rest as an unsigned int
   (void)snprintf(pbuf, 9+1, "%d.%04d",
          fixp >> 4, (uint16_t)(10000L/16 * (fixp & 0xF)));
   return(pbuf);
}

```

---
Tags: arduino-uno, c++, relay, temperature-sensor
---


title: Burn smell from arduino uno

text:
# Question
Title: Burn smell from arduino uno
I have did something stupid.. I connected 10K Ohm potentiometer at its maximum value PARALLEL with a LED. The positive long leg of the led to arduino 5v and the negative leg to the GND. After giving arduino 5v from USB Mobile Charger ( Output: 5V , 1A ) I smelt a burn and quickly removed the charger from the outlet. I waited a few hours and connected the arduino ( without any components ) to the charger again. and the arduino worked. I then connected it to the PC and uploaded the blink sketch of the on-board led and it worked ! Then I uploaded a sktech for blinking led on other pins and it worked also !

My question is: 1) What is damaged on the board ? The smell is near the regulator but I'm not sure if it's from the regulator itself or just a component near it.

2) Can it be safe to still using the arduino board on USB Power or Battery Power without any problems ?

# Answer
That burn is likely the smell of the potentiometer, not the arduino. I would check the arduino with a multimeter set to resistance to make sure that the Vin trace resistance is nominal.
> 1 votes

---
Tags: arduino-uno
---


title: Feasability question

text:
# Question
Title: Feasability question
I have some experience with Arduino, but not (yet) with other AVRs or Raspberry/Orange.

I want to make a project with some slave devices (mostly Arduino Unos, one Arduino Mega). These all need to communicate with a controller.

This controller has about the following requirements: - It need to respond every 5 ms to some messages from the devices, within the next 5 ms. - It needs about 128 KB RAM space, but more would be more comfortable (although 1 GB is enough). - I need quite some 'programming' space (like FLASH) - The program that needs to run on it will be reasonable complex, so using a nice programming language would be convenient (Python/Java/C++) - SD or other nonvolatile storage is mandatory - nRF24LR01+ 2.4 GHz RF Transceiver - Like upto 8 LEDs for status showing - WIFI would be nice - Using an adapter (12V/2A?) would be good, no intention to run it on batteries

I think I can do it with a Teensy or Due, but those are reasonable expensive. Another option is an STM32 kind of AVR.

However, I an noticed Orange Pi Zero, which are very cheap. But I wonder if I get myself in trouble? I know Linux commands, never installed it on a computer though. Someone made a remark in another related question to go for a stronger AVR, but afaik an Orange should be suited very well for this (seeing the limited electronics involved).

Or would it be better to go for a Teensy or STM32?

# Answer
A Pi gives you lots of CPU power but I'm not sure how good it would to on the tight timing requirements.

It doesn't have everything you ask for but something like the NUCLEO-F746ZG may be an option. That gives you a 200+ MHz Arm M7 with floating point, 2 MB of flash and 512 kB of RAM. It has USB and Ethernet built in and has arduino compatible headers for connecting shields to give you things like an SD socket or a radio link.
Plus you get 8 UARTs, (no more software serial :-)) and 6 SPI busses (obviously not all on the arduino headers)
You can program it either natively or in c++ using the mBed framework & online compiler.
It is around $20. There are cheaper variants with less processing power / memory available for a little less.
> 1 votes

---
Tags: teensy
---


title: Simulate 9-pin joystick output

text:
# Question
Title: Simulate 9-pin joystick output
I have built this little setup, which is supposed to record and replay input from a classic 9-pin Joystick. I connected the 9 pin connectors to the Arduino, read the input on the left side from the Joystick, and then passed it to the right side by setting the corresponding pins to HIGH.

It does work, and I can play games on the Commodore 64, however, I noticed that with this setup current is passed to the Commodore 64, which is very likely harming the machine a lot (I stopped immediately after noticing).

So my question is: how do I need to modify this setup so that no current is going from the Arduino to the Commodore 64 anymore?

Picture of the setup:

# Answer
I would isolate the two devices using opto-isolators.

simulate this circuit – Schematic created using CircuitLab

Turning the output ON will illuminate the infra-red LED in the opto-isolator which turns on the photo-transistor connecting the input to GND. Both devices are then completely galvanically isolated (unless of course you take power from the C64 for the Arduino).

Another option, if you don't care about galvanic isolation, is to just use a simple transistor (small signal NPN or logic level N-channel MOSFET) to make an Open Drain output:

simulate this circuit

Again, set the output HIGH and the transistor will turn on connecting the C64 input to ground.
> 2 votes

---
Tags: joystick
---


# Question
Title: How to get data from a sensor's FIRST IN FIRST OUT FIFO register (from two's complement)
I want to get acceleration data from a ADXL355 sensor.

My code:

```
void readFIFO (){
long data[3];
byte data2 [9];

digitalWrite(chipSelectPin, LOW);
SPI.transfer( (FIFO<<1) | 1);
for (int i = 0 ; i < 9; i++){
    data2[i] = SPI.transfer(0x00);
}
digitalWrite(chipSelectPin, HIGH);

Serial.println("Byte data in hex and binary");
 for (int j = 0 ; j < 9 ; j++){
    Serial.print("element "+String(j) +": ");
     Serial.print(data2[j],HEX);
     Serial.print(" ");
     Serial.println(data2[j],BIN);
 }
 for (int z = 0 ; z < 3; z++){
    data[z] = ((data2[z*3]<<12) | (data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
 }
 Serial.println("concatenated values: ");
 for (int i = 0 ; i < 3 ; i++){
    Serial.println(data[i]);
 }
}

```

Sample output:

```
Byte data in hex and binary
element 0: F9 11111001
element 1: 1B 11011
element 2: 51 1010001
element 3: 0 0
element 4: FD 11111101
element 5: 90 10010000
element 6: C3 11000011
element 7: 2A 101010
element 8: 20 100000
concatenated values:
-28235
4057
12962

```

The values are two's complement. Are these the correct values? If not what am I doing wrong?

# Answer
> 0 votes
You need to sign extend the results.

e.g. If the value is -1 your 3 byte values will be: 0xff ff f0
Combining these in to a single 32 bit value as you do gives you: 0x00 0f ff ff

Which is not -1.

What you need to do is check the most significant bit of the value and if it is set then set the top 12 bits.

```
for (int z = 0 ; z < 3; z++){
  data[z] = (((long)data2[z*3]<<12) | ((long)data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
  if (data2[z*3] & 0x80)
    data[z] |= 0xfff00000;
}

```

# Answer
> 0 votes
Since you've had no response to this I'll add my experiences with this chip. I'm not sure why you are reading the FIFO buffer. The chip provides three registers for each of the three axes. I simply read those in a loop. You can find my (still very crude) Python to read these at https://github.com/markrad/ADXL355. I hope it's some help to you.

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


# Question
Title: Stepper motor not working in Arduino 101
I am trying to connect a stepper motor ( this model exactly https://create.arduino.cc/projecthub/trduunze/grove-starter-kit-for-arduino-stepper-motor-driver-66471d ) in an arduino 101 but it does not work for some reason. I have tried connecting everything ast they tell in the website with no results:

And then I tried connecting directly to the board without using the shield, and still getting nothing.

The code I am using is this :

```
#include <Stepper.h>
int t =0;
const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;  // number of steps the motor has taken

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

void loop() {
  // set the motor speed:
  int motorSpeed = 15;
  if (motorSpeed > 0) {
    myStepper.setSpeed(motorSpeed);
    // step 1/100 of a revolution:
    myStepper.step(stepsPerRevolution / 25);
  Serial.println(motorSpeed);//print how fast the motor is going in the serial monitor
  }
}

```

Connecting the stepper motor and the driver, and launching the sketch in an arduino UNO board **works perfectly**, so I am really worried about that maybe the Stepper.h library might be different for the Arduino 101 but I couldn't find anything about that. I just have no idea why the project is not working in the 101 but working perfectly in the UNO. Any help or tips would be highly appreciated.

Cheers!

***EDIT***

After a lot of messing around, I have only been able to light up one led in the controller connecting one of the motor cables to GPIO5. None of the other GPIOS seem to work with the step motor controller.

# Answer
After reading the Stepper library and searching for several, I saw that in an example using an EDISON ( I want to thanks to Guimficus for posting his code here:https://communities.intel.com/thread/99133) they changed the pinMode of the GPIOS they were using in the setup function :

```
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);

```

And after adding that seems to work like it is supposed to work.

Cheers!
> 1 votes

---
Tags: arduino-uno, motor, stepper, arduino-101
---


title: How do i power recycle on SD card

text:
# Question
Title: How do i power recycle on SD card
I am working on my home made project where i am using SD card to log GPS data into it,As well as i have to access that data from the SD card on my computer while all the system is connected to battery power, so i also have a USB to SD chip USB2240 from Microchip, this SD controller suits best to my application, Because USB2240 has a card detect pin connected to one of the pin of Arduino, from which i can control interface of SD card between Arduino for logging and the computer for the USB..

But I have to Recycle power to the SD card whenever SD Card is interfaced with the USB controller USB2240.

So for an Example : when the device is powered 'ON' , The SD card is interfaced with the Arduino - which logs data to the card, But when i connected the system to my computer to get the logged file on my computer, Then it's not working, Here i have to disconnect power to SD card and Reconnect it...

How do i achieve Power recycle all on it's own when i connected to the USB OR to the Arduino.

Thanks

# Answer
I just read the

USB2240 Part listing

and it looks really handy for interfacing a PC to the flash.

However, I believe you are taking the wrong approach by trying to power recycle it yourself.

**To address your question about how to power recycle it: If you are physically moving the connection cable then that should power recycle it automatically.**

If not, then you have some other problem with your software not tolerating the disappearance then reappearance of the SD card. In other works, it is likely a software problem. The SD card should always remain connected so the software does not get confused and require a reset.

It is like how you need to eject USB devices in Linux. If you don't, then you can get file corruption because the buffers may not be fully flushed. Back in the day we used sync; sync; sync to ensure buffers were written out to storage devices, even just to do a normal shutdown. Fortunately, modern Linux takes care of that, with the exception of USB flash memory. With that you need to actually go through the eject process to avoid damage or system confusion.

But a much better approach would be to just leave it on one or the other.
Then use some sort of communications (it doesn't have to be USB) between the two computers for memory access.
> 2 votes

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


title: Delay only some function

text:
# Question
Title: Delay only some function
I have code which control thermometer, OLED and nanoservo via MQTT. I want to refresh temperature every 10s. It works but my servo receive command only when temperature is refreshed. How can I configure my loop so my servo can receive MQTT command anytime I send it?

Here in my code (I combined several example codes...):

```
    #include <ESP8266WiFi.h>
    #include <Servo.h>
    #include <PubSubClient.h>

    #include <OneWire.h>
    #include <DallasTemperature.h>

    #include <Wire.h>
    #include "SH1106.h"
    #include "thermometer.h"

    // Data wire is plugged into pin 2 on the Arduino
    #define ONE_WIRE_BUS 14 // je D5 was 2 (D4)

    // Setup a oneWire instance to communicate with any OneWire devices
    // (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    SH1106 display(0x3c, D1, D2);
    #define DEMO_DURATION 3000
    typedef void (*Demo)(void);

    int demoMode = 0;
    int counter = 1;

    // Update these with values suitable for your network.

    const char* ssid = "******";
    const char* password = "******";
    const char* mqtt_server = "192.168.100.220";     /// MQTT  Broker
    const char* topic_state = "/blinds/state";
    const char* topic_command = "/blinds/command";

    IPAddress my_ip (192, 168, 100, 224);
    IPAddress my_gateway (192,168, 100, 1);
    IPAddress my_subnet (255, 255, 255, 0);

    WiFiClient espClient;
    PubSubClient client(espClient);
    long lastMsg = 0;
    char msg[50];
    int value = 0;

    Servo myservo;
    int state = 0;
    int prevstate = 0;
    int dirc = 0;
    int spintime = 0;
    int servoPin = D4; //CHANGE TO WHATEVETR PIN YOUR USING

    void reconnect();
    void callback(char* topic, byte* payload, unsigned int length);

    void setup() {
      Serial.begin(115200);
      setup_wifi();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);

    // Start up the library
      sensors.begin();

    // Initialising the UI will init the display too.
      display.init();
      display.flipScreenVertically();
      display.setFont(ArialMT_Plain_10);

    }

    void servo_move() {
      Serial.println("State Change. Rotating Servo");
      if ( dirc == 180) {
        client.publish(topic_state,"open");
      }
      else if (dirc == 0) {
        client.publish(topic_state,"close");
    }
      myservo.attach(servoPin);
      myservo.write(dirc);
      delay(spintime);
      myservo.detach();

      Serial.println("Returning to main loop");
      return;
    }

    void setup_wifi() {

      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.setPhyMode(WIFI_PHY_MODE_11N);
      WiFi.config(my_ip, my_gateway, my_subnet);
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

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

    void callback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived [");
      Serial.print(topic);
      Serial.print("] ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();
      char *blindcommand = (char *) payload; // convert mqtt byte array into char array
      blindcommand[length] ='\0';            // Must delimit with 0

      Serial.print(blindcommand);
      if (strcmp(blindcommand,"open") == 0) {
        Serial.println(" 433MHZ OPEN COMMAND RECEIVED");
        dirc = 180; // direction for servo to run
        spintime = 50; // << CHANGE TO WHATEVER TIME YOU NEED TO OPEN YOUR BLINDS
        state = 1; //sets current state
      }
      else if (strcmp(blindcommand,"close") == 0) {
        Serial.println(" 433MHZ CLOSE COMMAND RECEIVED");
        dirc = 0;
        spintime = 150; // << CHANGE TO WHATEVER TIME YOU NEED TO CLOSE YOUR BLINDS
        state = 2; //sets current state
      }
      if (state != prevstate) {
        Serial.println("State change!");
        servo_move();
      }
      prevstate = state;

    }
    char temperatureVonku[15];
    String tempUnit = " °C";

    void temperature(){
      float temperatureFloat;
      sensors.requestTemperatures();
      temperatureFloat = sensors.getTempCByIndex(0);

      dtostrf(temperatureFloat, 7, 1, temperatureVonku);

       client.publish("temp/outside", temperatureVonku);    /// send char
       delay(10000);
    }

    void dispTempVonku() {
        display.drawRect(1, 1, DISPLAY_WIDTH -1, DISPLAY_HEIGHT -1);
        // Font Demo1
        // create more fonts at http://oleddisplay.squix.ch/
        display.setTextAlignment(TEXT_ALIGN_LEFT);
        display.setFont(Roboto_Bold_12);
        display.drawString(5, 5, "Temp: ");

        display.drawXbm(7, 24, Img_width, Img_height, thermometer);
        display.setTextAlignment(TEXT_ALIGN_CENTER);
        display.setFont(Roboto_Bold_28);
        display.drawString(64, 22, temperatureVonku + tempUnit);
    }
    void dispTempVnutri() {
        display.drawRect(1, 1, DISPLAY_WIDTH -1, DISPLAY_HEIGHT -1);
        display.setTextAlignment(TEXT_ALIGN_CENTER);
        display.setFont(ArialMT_Plain_16);
        display.drawString(64, 22, "Hello World");
    }

    Demo demos[] = {dispTempVonku, dispTempVnutri};
    int demoLength = (sizeof(demos) / sizeof(Demo));
    long timeSinceLastModeSwitch = 0;

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (client.connect("ESP8266Client", "******", "******")) {

          Serial.println("connected");
          client.subscribe(topic_command);
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }
    void loop() {

     temperature();

      if (!client.connected()) {
        reconnect();

      }
      client.loop();
      // clear the display
      display.clear();
      // draw the current demo method
      demos[demoMode]();

      display.setTextAlignment(TEXT_ALIGN_RIGHT);
      display.drawString(10, 128, String(millis()));
      // write the buffer to the display
      display.display();

      if (millis() - timeSinceLastModeSwitch > DEMO_DURATION) {
        demoMode = (demoMode + 1)  % demoLength;
        timeSinceLastModeSwitch = millis();
      }
      counter++;

     //delay(10000);

    }

```

Thank you.

# Answer
> 1 votes
I assume your servo only receives data when you keep the delay(10000).

The problem is that with a delay, the Arduino does kind of nothing during that time, so it cannot control your servo.

What you want is to call every 10 s the temperature update, but keep the servo control always running.

So keep a last-time-called variable (type unsigned long) that keeps the time of the last call to update the temperature. When 10 s have passed (you can check somewhere in the loop), you call it, and update the last time to the current time.

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


title: Why are some letters reserved?

text:
# Question
Title: Why are some letters reserved?
I wrote a function that takes characters and noticed that the Arduino Compiler treated some characters like system-reserved, and other like functions, and a few just like characters. Lowercase doesn't seem to be effected. I'm just wondering why.

# Answer
> 2 votes
The Arduino IDE does keyword coloration according to a very crude system. It simply scans for all the keywords.txt files included with:

* Arduino IDE
* Libraries bundled with the Arduino IDE
* Libraries you have installed to the libraries subfolder of your sketchbook
* Libraries bundled with the hardware package of the currently selected board - Hardware package of the currently selected board (recent IDE versions only)

There are several types of keyword identifiers that determine which color is used. The reason those letters are colored in your IDE is because some library you have installed just happens to have added them to its keywords.txt file. The Arduino IDE makes no attempt to determine whether you have included those libraries and so coloration doesn't necessarily mean they are "reserved". If you have not included the library that defines a specific keyword then the coloration of that keyword is meaningless.

For more information on keywords.txt see:
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords

# Answer
> 1 votes
In WString.h is a define:

```
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))

```

In other words, the letter `F` is already a macro.

I don't know what your code:

```
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

```

is supposed to do. I suppose you are just testing the syntax highlighting?

The syntax highlighting is designed to try to "help" you by colouring words in a pre-supplied file in a different way. It doesn't in any way affect how the compilation works. And, judging by what you posted, it can't always be relied upon. Personally, I ignore it.

---
Tags: arduino-ide, compiler
---


# Question
Title: Start I2C communication at an external event
I'm working on a Arduino Uno and a ADC ADS1115. Devices communicate by I2C where Arduino is the master.

I would like to use the ADC to the maximum of his possibility.

So i configure the ADC to set a pin when a conversion finish and use this pin as an external interrupt. But i can't read the data because I2C interrupt can't work in a external interrupt handler. I think to use a timer to have a fixed sampling rate too, but it's the same issue.

There is my code below, and if you have any idea of how i can doing my goal let's share it ;)

```
#include <QueueArray.h>
#include <ADS1115_Vibratec.h>

  Adafruit_ADS1115 ads;

  QueueArray <uint16_t> fifo;

  int i=0;

void setup() {

 Wire.begin();

 Serial.begin(115200);

 ads.Config( ADS1115_REG_CONFIG_OS_NOEFFECT,
          ADS1115_REG_CONFIG_MUX_DIFF_0_1,
          ADS1115_REG_CONFIG_PGA_6_144V,
          ADS1115_REG_CONFIG_MODE_CONTIN,
          ADS1115_REG_CONFIG_DR_860SPS,
          ADS1115_REG_CONFIG_CMODE_TRAD,
          ADS1115_REG_CONFIG_CPOL_ACTVLOW,
          ADS1115_REG_CONFIG_CLAT_NONLAT,
          ADS1115_REG_CONFIG_CQUE_1CONV);

 ads.Set_ConvReady_function();

 attachInterrupt(0,interrupt,RISING); //INT0 -> pin 2, fonction interrupt,    front montant

  }

  void loop() {

   while (!fifo.isEmpty ())
   {
      Serial.write(fifo.dequeue());
      Serial.println();

   }

  }
  void interrupt()
  {
    fifo.enqueue(ads.ReadConvert());
  }

```

# Answer
You could set a 'volatile' flag in the interrupt routine. In the loop() you can check if the flag is set. That is how the i2dev uses the interrupt for the MPU-6050. See the MPU6050\_DMP6.ino example.

First thing to do is set the I2C clock to 400 kHz. Keep the wires short and pullup resistors low.

```
Wire.begin();
Wire.setClock(400000L);   // 400 kHz I2C clock speed

```

You can let the MultiSpeed I2C Scanner run for a while to see if it is stable.

The ADS1115 has also I2C High-Speed Mode up to 3.4MHz. The Arduino can not do that. The Arduino has a fast SPI mode, but the ADS1115 has no SPI bus.

Using an interrupt adds extra overhead. A fixed software timer with millis might be just as fast.

Do you want the maximum of 860 Samples per second? The Arduino Uno or Mega or Leonardo are too slow for that. Do you want to continuously read data or just a burst and store it in ram ?
> 2 votes

---
Tags: i2c, interrupt, adc
---


# Question
Title: Arduino as Slave | SPI | Answers too late
I hope you can help me :)

I am communicating between Raspberry Pi 3 and Arduino Uno with SPI. I am using the Arduino as slave and it works pretty fine. The only problem that i have, is the following:

For receiving data from the Arduino, my Raspi sends a byte. But i always have to send 2 bytes for the correct response. Is it even possible for the Arduino to response on the first byte?

Sorry for my english

# Answer
Because of the way SPI works, the slave cannot *respond* to the first byte in a meaningful way. It can send something (eg. 0x00) but not a response.

See my page about SPI. During an SPI transfer each bit is sent, and a bit received, simultaneously, as in this graphic:

You can see that as the first bit is received by the slave, it also has to send a response. There is no way that this response can react to the 8 bits, 7 of which haven't been received yet, by the time it has to send the first bit of response.

> But i always have to send 2 bytes for the correct response.

You don't have to send 2 bytes all the time. For example, you can send one byte (eg. "send me the temperature") and then send zeroes after that, while you read back a (say) 4-byte temperature. So in this case you send 5 bytes to get a 4-byte response.
> 1 votes

# Answer
The only way you can respond on the first byte is if the Arduino already knows, and is primed, what to send on that byte *before it begins to be clocked into the Arduino*.

It is normal to have to send at least 2 bytes - the first is often used as either a register address, or a "read register" command.
> 1 votes

# Answer
> Is it even possible for the Arduino to response on the first byte?

Yeah. There is nothing preventing your slave to respind on the first byte, so long as your code allows it.
> 0 votes

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


# Question
Title: Updating Array Values Incrementally Overwrites The Existing Values, Why?
I have a global array. I'd like to update the array while the program running. But, I've found that my program below doesn't work as I expected.

**Please checkout the program source:**

```
#define RespLength 10
char* response[] = {"0","0","0","0","0","0","0","0","0","0"};
int idxUpd  = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("Start");
}

void loop() {
  // put your main code here, to run repeatedly:
    char assign[5];
    int wkt = random(10, 99);
    dtostrf(wkt, 4, 1, assign);

    response[idxUpd]  = assign;

    Serial.print("Iteration "+String(idxUpd)+" : ");
    for (int i=0;i<RespLength;i++){
        Serial.print(response[i]);Serial.print(",");
    }
    Serial.println();
    delay(500);

    idxUpd++;
    idxUpd = idxUpd >= 10 ? 0 : idxUpd;
}

```

**Expected output:** please concern to the patern

```
Iteration 0 : 12.2,0,0,0,0,0,0,0,0,0,
Iteration 1 : 12.2,23.7,0,0,0,0,0,0,0,0,
Iteration 2 : 12.2,23.7,65.3,0,0,0,0,0,0,0,
Iteration 3 : 12.2,23.7,65.3,0,0,0,0,0,0,0,
Iteration 4 : 12.2,23.7,65.3,15.9,0,0,0,0,0,0,
Iteration 5 : 12.2,23.7,65.3,15.9,10.1,0,0,0,0,0,
Iteration 6 : 12.2,23.7,65.3,15.9,10.1,11.6,0,0,0,0,
Iteration 7 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,0,0,0,
Iteration 8 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,98.2,0,0,
Iteration 9 : 12.2,23.7,65.3,15.9,10.1,11.6,78.9,98.2,68.6,90.1,

```

**Current output:**

```
Iteration 0 : 85.0,0,0,0,0,0,0,0,0,0,
Iteration 1 : 28.0,28.0,0,0,0,0,0,0,0,0,
Iteration 2 : 36.0,36.0,36.0,0,0,0,0,0,0,0,
Iteration 3 : 70.0,70.0,70.0,70.0,0,0,0,0,0,0,
Iteration 4 : 56.0,56.0,56.0,56.0,56.0,0,0,0,0,0,
Iteration 5 : 74.0,74.0,74.0,74.0,74.0,74.0,0,0,0,0,
Iteration 6 : 94.0,94.0,94.0,94.0,94.0,94.0,94.0,0,0,0,
Iteration 7 : 94.0,94.0,94.0,94.0,94.0,94.0,94.0,94.0,0,0,
Iteration 8 : 26.0,26.0,26.0,26.0,26.0,26.0,26.0,26.0,26.0,0,
Iteration 9 : 71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,71.0,

```

From the result above, I can conclude that if I update the array value incrementally, it just overwrites the other element in the array.
So, How can I have my `expected output`?

# Answer
You are using a char pointer (char\*) instead of a char.

When you say;

```
response[idxUpd]  = assign;

```

you are assigning not the value but a pointer to that value. That points to `assign` for every element in `response[]`. Every `response[]` get the same pointer value, every `response[]` get the same value.

Use this:

```
#define RespLength 10
int response[] = {0,0,0,0,0,0,0,0,0,0};
int idxUpd  = 0;

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("Start");
}

void loop() {
  // put your main code here, to run repeatedly:
    int wkt = random(10, 99);
    response[idxUpd]  = wkt;

    Serial.print("Iteration "); Serial.print(idxUpd); Serial.print(" : ");
    for (int i=0;i<RespLength;i++){
        Serial.print(response[i] );Serial.print(",");
    }
    Serial.println();
    delay(500);

    idxUpd++;
    idxUpd = idxUpd >= 10 ? 0 : idxUpd;
}

```

I don't understand why you are converting a `int` to a `float`. That value doesn't change, so I omitted the `dtostr()` call.
> 3 votes

# Answer
C/C++ Arrays don't work the way you are used from scripting languages. Your

```
char* response[] = {"0","0","0","0","0","0","0","0","0","0"};

```

allocates a consecutive space in memory with the lenght of 20 bytes. So you have 10 pointers that point to static memory.

In your loop you have a array of `char assign[5]` that gets assigned to every single of those pointers with `response[idxUpd] = assign;`. You copy **pointers** and **not values** here. So the only value you really have is that in your `assign` variable. So as you update the pointes of the array, you get the results you see.
> 1 votes

---
Tags: serial, programming, c++, arduino-pro-mini, array
---


# Question
Title: Void value not ignored as it ought to be
im trying to build an rc plane using arduino nano and nrf24l01 as receiver but im having some issues in the code

it has error on the line `done = radio.read(joystick,sizeof(joystick));` which says that void value not ignored as it ought to be

the whole code is below

```
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include<Servo.h>

Servo Throttle,Rudder,Elevator,LeftAileron,RightAileron ;

const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(9,10);
int joystick[5];

void setup()
{
  /*Serial.begin(9600);
  delay(1000);
  Serial.println("Starting Rx");*/ //Enable serial for debugging

  attachMotors();

  calibrateMotors();

  radio.begin();

  detachMotors();

  radio.setPALevel(RF24_PA_MAX);
  radio.setPayloadSize(10);
  radio.setDataRate(RF24_250KBPS);
  radio.setRetries(15,15);

  radio.openReadingPipe(1,pipe);
  radio.startListening();;
}

void loop()
{
  detachMotors();

  if(radio.available())
  {
    bool done=false;
    while(!done)
    {
      done=radio.read(joystick,sizeof(joystick));
    }

  attachMotors();

  int a=joystick[0];
  int b= joystick[1]; //stores values from tx
  int c=joystick[2];
  int d=joystick[3];
  int e=joystick[4];

  //Serial.println(a);
  //Serial.println(b);
  //Serial.println(c);
  //Serial.println(d);
  //Serial.println(e);
 // Serial.println(f);

  delay(20);
  Throttle.writeMicroseconds(a);   //write values to motor
  Rudder.write(b);
  Elevator.write(180-c);

  if(d== LOW)
  {
  LeftAileron.write(180); ////to activate right aileron
  RightAileron.write(180);
  delay(15);
  }

  else if(e == LOW)
  {
    LeftAileron.write(0);  //to activate left aileron
    RightAileron.write(0);
    delay(15);
  }
  else
  {
    LeftAileron.write(100);
    RightAileron.write(110); //Ailerons at neutral pos
    delay(15);
  }
    }
  else
  {
    calibrateMotors();
    delay(15);

  }
  }

void attachMotors()
{
  Throttle.attach(3);
  Rudder.attach(4);
  Elevator.attach(5);
  LeftAileron.attach(6);
  RightAileron.attach(7);
}

void calibrateMotors()
{
  Rudder.write(90);
  Elevator.write(90);
  LeftAileron.write(100);
  RightAileron.write(110); //centering servo shafts
}

void detachMotors()
{
  Throttle.detach();
  Rudder.detach();
  Elevator.detach();
  LeftAileron.detach();
  RightAileron.detach();
}

```

# Answer
> 1 votes
Something changed while you were looking away. This is the updated description of `read()`. As you can see, it not longer returns a `bool`. Use `available` to determine if packets are available:

```
/**
   * Read the available payload
   *
   * The size of data read is the fixed payload size, see getPayloadSize()
   *
   * @note I specifically chose 'void*' as a data type to make it easier
   * for beginners to use.  No casting needed.
   *
   * @note No longer boolean. Use available to determine if packets are
   * available. Interrupt flags are now cleared during reads instead of
   * when calling available().
   *
   * @param buf Pointer to a buffer where the data should be written
   * @param len Maximum number of bytes to read into the buffer
   *
   * @code
   * if(radio.available()){
   *   radio.read(&data,sizeof(data));
   * }
void read( void* buf, uint8_t len );

```

---
Tags: arduino-nano, nrf24l01+
---


title: arduino on battery for long time use

text:
# Question
Title: arduino on battery for long time use
I have a small project with arduino UNO R3 + RTC clock DS3231, that control through a relay a electrovalve (12V).

I would like to use the entire circuit on battery.

The electrovalve (a small motor) has a consumption of 500mA and will be active 4 times a day for 15 second.

I have a 7Ah battery, and I had calculated that my system will work only around 34 hours with it... is there any way to optimize circuit consumption ?

Thanks for any suggestion !

# Answer
You can turn off the entire Arduino and let it wake by your RTC. That way you can conserve a lot of power. (link)

Also you will have losses from the power regulator when powering the Arduino from 12V. You might consider using a Arduino Pro mini with 3.3V powered by two AA batteries. That should last for years.
> 1 votes

---
Tags: battery
---


# Question
Title: Serial1 is not reading the Xbee on a Arduino Due
I am trying to test simple communication between a Xbee on my Arduino Due and a Xbee linked to XTCU. I attached jumper wires from RX and TX to RX1 and TX1 (Serial 1 hardware port) but I cannot send or receive data between the Xbees. I tested the Xbees previously with an Arduino Zero talking to the XTCU and it worked flawlessly.

Extra information: I am using a Xbee Shield on my Arduino Due (as shown in the picture)

```
char c,d;

void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
Serial1.begin(9600);

}

void loop()
{
// put your main code here, to run repeatedly:
if (Serial1.available())
{
 c = Serial1.read();
 Serial.print(c);
}
else if (Serial.available())
{
 d = Serial.read();
 Serial1.print(d);
}

}

```

My wiring is attached. What am I doing wrong?

# Answer
I fixed my problem. I stupidly left the Xbee Shield on DLINE instead of UART. Now there is communication between the radio modules. I have another question. When I type a character into XTCU, it "receives" the exact character from the Arduino Due. I have used this basic code with other Arduinos before and this has never happened.

Extra information: The serial monitor solely prints out received data.

I attached an example.
> 0 votes

# Answer
Has there been any update on this problem? Your post has been incredibly helpful as I've been looking for ways to use a Due and an Xbee (specifically with the Sparkfun Xbee shield).

I haven't been able to solve this entirely, but I've noticed a few things; First of all if you delete the second Serial.available, it does not change the functionality of the code at all, still works the same way. I believe this has to do with the hardware Tx and Rx pins on the Due.

What seems to be happening is that if you use XCTU to send information to the Due, XCTU sends the data out, in which the Due receives it. Then it bounces back and seemingly resends it from the Due to XCTU again, without displaying in the serial monitor. I'm probably wrong in my observations but very curious if there's an answer to this. Hope to hear back from someone soon. Thanks!

*EDIT*

Upon thinking about it, I figured out a work around. As stated in one of the comments earlier, you still have the shield's Rx and Tx pins connected to the Due. This is what's giving you double values on XCTU. The Due receives the input from XCTU and immediately sends it back out to XCTU. A simple fix is bending the Rx and Tx pins out slightly so they are not connected to the Due but all of the other pins remain in place. I hope this ends up being helpful!
> 0 votes

---
Tags: arduino-due, communication, xbee, uart
---


# Question
Title: Is Arduino Ethernet shield compatible with arduino due?
Arduino Due's operating voltage is 3.3 volt and Ethernet shield operates on 5 volt supply. So my question is that this Ethernet shield will work on an Arduino Due and also if it will not harm the Arduino Due board due exceeding the operating voltage?

# Answer
> 2 votes
The Arduino Ethernet shield (or at least V2 of it) is based on a W5500 chip which itself features "3.3V operation with 5V I/O signal tolerance". In other words, the core of it already is a 3.3v device, just one that can *tolerate* connection to a 5v Arduino.

Of course the shield is more than just the chip. A very quick look isn't showing any glaringly obvious uses of 5v levels on the board in a place where a 3.3v Arduino derivative wouldn't expect them.

However, you should review the the full schematics and **make your own determination** that these are applicable to the specific board you plan to use and do not place 5v level on any signal the Due could not accommodate.

It's unfortunate that the shield documentation doesn't seem to say anything about compatibility, but worth noting the the Ethernet Library has some specifics for the SAM family of chips one of which is used on the Due.

---

The Ethernet Shield V1 was based on the W5100 chip. This may not have 5v tolerant inputs, as it appears to use level translation on the input side. But it is also powered from 3.3v, so likely the outputs would be fine for a Due. *An interesting question is if the V1 shield would be damaged if connected to a 5v Arduino with a sketch that erroneously drove MISO high as an output.*

# Answer
> -1 votes
Of course it will harm your due. Now for that problem you could use a 3.3v to 5v and vice versa level converter.

---
Tags: arduino-due, shields, ethernet, ethernet-shield
---


# Question
Title: Arduino UNO only works with Monitor Serial opened
My Arduino Uno will not work without the Serial Monitor opened. I have a PHP script to send data to the board. When I send the data, the `TX` and `L` LEDs light up, but the action is not executed. It is only executed when the Serial Monitor is opened. Can you please help me?

Code in Arduino:

```
int const RED = 2;

int status = 0, temp =0;

void setup() {
  pinMode(RED, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  if(Serial.available() > 0) {
    temp = Serial.read();
    if(temp != -1)
      status = temp - '0';

    Serial.print("status: ");
    Serial.println(status);

    if(status == 1)
      digitalWrite(RED, HIGH);
    else
      digitalWrite(RED, LOW);

    delay(1000);
  }

}

```

PHP script:

```
<!DOCTYPE html>
<html>
    <head>
        <title>Alarme</title>
    </head>
    <body>
        <form action="#" method="post">
            <input type="submit" name="alarme" value="ON">
        </form>

        <form action="#" method="post">
            <input type="submit" name="alarme" value="OFF">
        </form>
    </body>
</html>

<?php

$port = fopen("/dev/ttyUSB0", "w");
fwrite($port, ($_POST['alarme'] == 'ON') ? 1 : 0);
fclose($port);

```

My circuit is simple, it only consists of one LED and a 220 ohm resistor.

# Answer
The problem was the auto-reset of the Arduino, I disabled it.

To disable, I connected a 10uf capacitor on the GND and RES. As in the image below:
> 1 votes

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


# Question
Title: I bought ATmega328p with bootloader and I can't erase it
I bought an online deal which had 10x ATmega328p with bootloader installed. I thought I can erase the bootloader once I got the order (I want to write custom task without a bootloader) but my programmer does not seem to find the ATmega328p. I know it is the problem of the microcontroller because I have another ATmega328p which works fine and I can upload code to it. Is there a flag or switch I am missing when trying to overwrite the bootloader on the microcontroller?

Here are the components I am using:

* ATmega328p with bootloader
* SparkFun Pocket AVR Programmer (usbtiny)

Here are the commands I am using:

* To compile: `avr-gcc -std=c11 -mmcu=atmega328 -O -o main.o main.c`
* To generate hex: `avr-objcopy -O ihex main.o main.hex`
* To upload: `sudo avrdude -c usbtiny -p m328p -U flash:w:main.hex`

Here is the output of the `avrdude` command:

```
avrdude: Using SCK period of 10 usec
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

Anyone encountered similar situation before? How did youu managed to fix it? I appreciate any help :)

Thank you

**Edit #1** I tried setting the `-B` flag to various values but nothing seems to solve the problem.

**Edit #2** Here is the circuit I am using while programming the ATmega328p

* 2x Capacitors 22pf
* 1x Crystal oscillator 16Mhz
* 1x Resistor 10K ohm
* 1x ATmega328p
* 1x SparkFun Pocket AVR Programmer

# Answer
Your connections to the ATmega328p are incomplete.

You are missing the connection of ground to pin 22, and you must supply power to AVCC on pin 20.

You should also place the capacitors much closer to the crystal with a very direct route to ground, and try to place the crystal itself closer to the chip.

Additionally you should use supply bypass capacitors.

Please see the minimum wiring at Arduino on a Breadboard, however this document itself is erroneous as it neglects to show the high frequency 0.1 uF bypass capacitors you should have *directly* across each pair of power pins.

That's not to say that there may not be additional issues as well - but you need to fix the circuit problems first.
> 1 votes

---
Tags: atmega328, avr, avrdude
---


# Question
Title: Arduino Mega, PWM analogWite doesn't work with Timer interrupt
Can anybody explain me, why the PWM doesn't work in such a simple example?

Generally, Timer interrupt is being called once per 100 ms and then in the interrupt function the bool flag (**state** ) is being set. Then in the main loop the flag is checked and when it is 1 (true) several instructions are being executed. Next, PWM is generated and measured via ADC and also displayed on the LCD.

The problem is that the PWM is generated as 0 or sligthly over the 0, even when the value put to the **analogWrite** is 255 (max of 8 bit). Variable **counter** is incremented without problems and this value is being put to the **analogWrite** and despite it the PWM doesn't work.

I don't know, totally, what can be wrong.

Can anybody help me?

```
 #include<LiquidCrystal.h>
 #include<TimerOne.h>

  LiquidCrystal lcd(52, 50, 48, 46, 44, 42, 40);

  int out = 12;
  int in = A7;
  volatile bool state;

  int counter = 0;
  volatile int y;

  void setup()
  {
    lcd.begin(16, 2);
    lcd.clear();
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    analogReference(DEFAULT);
    Timer1.initialize(100000);
    Timer1.attachInterrupt(functionInterrupt);

     state = 0;
      y = 0;
   }

   void loop()
   {
     y = analogRead(in);
     y = y / 4;
     y = y - 128;

    if (state == 1)
    {
      state = 0;

      counter++;
      if (counter > 255)
      //counter = 0;
      counter = 200;

      //state = 0;
     }

      analogWrite(out,counter);

      lcd.home();
      lcd.setCursor(0, 1);
      lcd.print(counter);
      lcd.setCursor(12,1);
      lcd.print(y);
     }

    void functionInterrupt()
    {
      state = 1;

     }

```

# Answer
> 0 votes
When you use a timer to generate an Interrupt Service Routine (as you do with the TimerOne library) you change the configuration of that timer (in your case timer1). The timer is used by the TimerOne library to provide an interrupt, but also by the microcontroller itself to produce a PWM signal on some pins depending on the timer: in your case (Arduino Mega, timer 1) on the 11 and 12. If you use one of these pins as "analog" output while controlling an ISR with the same timer you won't get the expected output, because the timer isn't any more configured as needed by the PWM generation mechanism but as needed by you (you changed the configuration of the timer in the `Timer1.initialize(100000);` function call).

---

So, either you use another PWM pin as output either you use a timer library which uses another timer (or you implement it by yourself).

# Answer
> 0 votes
> ```
> if (state = 1)
>
> ```

This is setting `state` to 1, not testing if it is equal to 1. In other words, it will always be true.

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


# Question
Title: Genuino 101 - Can't upload my sketch - Timeout Error
I'm trying to run a sample sketch on my Genuino 101 but the following error shows up. Here is a verbose version.

```
Starting download script...
Args to shell: [/home/userk/.arduino15/packages/Intel/tools/arduino101load/1.6.9+1.28/x86/bin /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin /dev/ttyACM0 verbose ATP1BLE000-1541C5635 141312]
Serial Port: /dev/ttyACM0
BIN FILE /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Flashing is taking longer than expected
Try pressing MASTER_RESET button
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
ERROR: Timed out waiting for Arduino 101 on /dev/ttyACM0

```

I have installed the Intel Curie package with the Boards Manager and tried to press the Master Reset button, the reset and a combination of both. Nothing.

I have also tried the suggestions provided in this question but they did not work. I am using Ubuntu 16.04. Do you have any advice?

EDIT: Same problem with Windows 10/8/7.

# Answer
> 1 votes
Problem solved with a downgrade of the Arduino 101 core. Try with all available versions.

# Answer
> 1 votes
Is the Genuino 101 board been recognized by the OS? Sounds like your board is not being recognized by the system.

For windows, open up your device manager before plugging into the PC. After plugging in, the device manager should refresh and display the board in the COM Port section.

For Linux (in your case Ubuntu), you can use the *dmesg | tail* cmd to check whether your board is being detected when you plug in the Genuino 101 board.

# Answer
> 1 votes
I have the same problem while uploading sketches , when i uploading the sketch and press `MASTER_RESET` button solved my problem . when it shows `Waiting for device...` just press the `MASTER_RESET` .

or try to update Firmware

```
Select Tools >> Programmer >> Arduino 101 Firmware Updater
Select Tools >> Burn Bootloader

```

---
Tags: genuino, 101
---


# Question
Title: Powering Arduino Uno from 5V pin, what exactly is the voltage range/tolerance?
I want to bypass the onboard regulator and use the 5V pin to feed arduino with external, regulated source.

Everybody just keeps saying regulated 5V, **but how precise does the regulation need to be exactly?** Can you state a voltage range and what makes you think so?

10 ways to destroy arduino, Method #5: Apply \>5V to the 5V Connector Pin mentions "applying more than 6V", can anyone elaborate how it can be calculated?

**Is there a higher spike that arduino can handle for a short period of time?** My concern is that the current draw from arduino might be under 60mA (right after switching power on and before the program initilizes and starts running), which is the lowest draw at which my source guarantees the 5V regulation --- when unloaded it gives out 6.5V. How could I resolve this better than putting a 60mA dummy load between the regulator and arduino itself?

# Answer
Unfortunately there is no one "clear cut" answer for all you ask.

There are some hard limits, though, which you can get from the main chip's datasheet:

> Operating Voltage: 1.8 - 5.5V

But that's not the whole story. The minimum voltage depends on the clock speed of the chip, as shown in this graph:

But wait, there's more. The Arduino also contains a 3.3V regulator which is fed from the 5V supply. That will have a minimum voltage above 3.3V that it needs to maintain a 3.3V output. So if you want to use the 3.3V regulator then, according to the datasheet for the regulator (`LP2985-33DVBR`):

> **3 Description**
> The LP2985-N low noise linear (LDO) regulator delivers up to 150mA output current and only requires 300mV dropout voltage of input to output.

So a minimum of 3.3 + 0.3V, or 3.6V.

That gives you a usable range, clock frequency permitting, of **3.6V to 5.5V**.

As to how to protect the Arduino from a power-on spike like you describe - you could:

* Add your own extra regulation in the form of a 5.1V zener diode.
* Add a dummy load which the Arduino can switch out of the circuit once booted up
* Change your source to something with better regulation
* Ignore it - the regulation with even a light load will be considerably better than open circuit. Add a resistor across your supply that would draw much less than 60mA and measure the voltage. See how bad the regulation at low load is.
> 9 votes

# Answer
The 6.5V is too much. I have had an ATtiny chip which seems to run fine after applying 8V to it. But how can I be sure that it is okay ? There are so many parts in the chip die that can be damaged.

There has been a few broken voltage regulators reported, when applying 5V to the 5V pin of an Arduino Uno. The reverse diode inside the voltage regulator might not keep up with a large current peak. In some of my projects I power an Arduino via the 5V pin. I have added an extra diode 1N4007 from 5V to VIN, to save the voltage regulator, and my 5V power is not very strong.

I also don't apply that 5V while it is on. It is from a DC/DC converter that is part of the project. So when I turn on the power, the 5V raises not too fast, and there is no high current peak.

When applying 5V to the 5V pin, the current can flow into the computer via the usb cable. The polyfuse of 500mA on the Arduino board will prevent most troubles, but it could damage the computer. When I turn off my computer with that project connected, I do indeed see an increase of the current to my project. My computer is luckely not broken (yet).
> 1 votes

# Answer
Most decent 5V supplies (e.g. USB chargers) are within 5% of 5V. I use these all the time to power directly to the 5V pin. There has never been an issue with this. I don't use supplies outside 5% for this. Check with your multimeter first.
> 1 votes

# Answer
You don't say why you want this information, but there are others who are trying to do similar. (Starting with NOT destroying their Arduino)

For instance, at the end of the article

10 Ways to Destroy An Arduino

is a reference (broken link in the article) to

The Ruggeduino

which might be more suitable to your requirements.

Here is an excerpt of its specs:
> 1 votes

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


title: What not to do to an Arduino

text:
# Question
Title: What not to do to an Arduino
I may have been working with my Arduino UNO board improperly, because now it fails to upload sketches (says some programmer is not responding) and when I press the cute little restart button, the green LED doesn't do its blink anymore. I am aware what that means, but what I really wonder is how should I properly care the board. I probably will have no other chances to buy more arduinos so this information follows to be of a great importance.

---

As an example I would give, is touching the arduino board with bare hands risky, how much shock-tolerant it is, what if I mistake some pins, are there pins that cannot be mistaken, what will happen if I declare a pin as an output, but use it for input and the contrary, is loading a PWM program onto TFT touch screen shield unhealthy and so forth and briefly - **how should I properly care the arduino board.**

# Answer
> 2 votes
A lot of things can happen to ruin an Arduino board, although so far I made mistakes and none has broken. However, possible causes can be:

* Electrostatic energy, you can prevent it by buying an ESD mat/wristband, or if you don't want to spend money, touch regularly some 'earth' like the central heating
* There should not be too much current on a pin ... so don't try to run too many leds or even a motor which is too big from a pin.
* Watch out with external power supplies
* Don't forget resistors where needed, because of the previous point
* Shaking should not matter much, unless you shake so hard that breadboard components are touching each other
* Running a program for something else (like PWM on touch screen) might be hard to explain ... it can ruin the device connected, and possibly the Arduino too.

Just some tips:

* Whenever you change some hardware/wiring, remove the power
* Check very carefully that everything is wired correctly
* Keep the Arduino on a solid place (don't let the USB cable let it overthrow/fall on the floor)

# Answer
> 3 votes
it is okay to use for simple experiments directly. But while you choose to opt for a complex tasks read the details about all the components and their wiring techniques. specifically try to check soldering is done correctly or not while connecting the wires to any component or to other wire. wrong soldering may damage your parts and arduino as well. Be careful while using power supply, more when it comes to use multiple sources. read carefully before you do anything. Dont be afraid just be careful.

---
Tags: arduino-uno, programming, pins, electronics, safety
---


title: Possible reason for broken Uno

text:
# Question
Title: Possible reason for broken Uno
Yesterday I wrote in a comment that I didn't break much, except a LED and a LED matrix. However, exactly yesterday I think my Uno gave up, since I cannot upload a sketch anymore (timeouts). For the rest the board seems to work still ok.

I have two possible reasons, and would like to know what I can do to prevent this in future. I connected a 415 MHz RF transmitter and receiver to it, which are working.

1. To get more power I attached an adapter (12V), TOGETHER with the USB ... I thought always adapter power would be used, but it seems it is not a good idea to have both connected. Is this true?
2. The Uno was inside a case (with holes near the output pins). I know this causes some extra heat, but I would guess that adding just an RF receiver/transmitter would not cause the Uno to heat up more than allowed.

Which of these reasons is the possible cause ... or are there any other reasons I didn't think off. Everything worked fine until I plugged in the 12V adapter and it still worked for some time (until I tried to upload a new sketch).

# Answer
> 1 votes
It is a mistaken belief that powering an Arduino from an external power source increases the power available. It doesn't. All it does is increase the amount of heat produced.

Unless you are powering your Arduino from an unpowered hub you will have around 500mA available from the USB power. The 5V regulator, which converts the incoming 12V to 5V, can supply at best between 800mA and 1A on a good day. However with 12V the amount of heat generated will cause thermal shutdown at those kind of currents due to lack of proper heatsinking. So you can't get anywhere near 800mA out of it - instead you are limited to around the same as (or even less than) the USB power source can provide.

All that excess heat (and at 12V you are throwing away about 58% of your power as heat) in an enclosed case will have caused nasty things to happen - at the very least your regulator should have gone into thermal shutdown. Worst case scenario your voltage regulator failed (especially if it's a cheap version) which would end with one of two scenarios:

1. No power getting through to the rest of the board
2. More than 5V getting through to the rest of the board

If it's (1) it'd be obvious - nothing works. No LEDs light, etc. However if it's (2) then more nasty things will ensue. One common one is that the ATMega16U2 chip (the USB interface chip) if it's a genuine Arduino will be fried. You may find it's getting excessively hot itself now. Of course, if it's a clone then the CH340G will no doubt have given up what little ghost it had.

# Answer
> 1 votes
You should be OK as long as you use a 9 to 12 volt supply since there is an FET that disconnects the 5 volt USB power from the rest of the Arduino circuitry if VIN is greater than approximately 6.6 volts.

But... if your external voltage is less than 6.6 volts you may have a problem since both supplies will be powering the Arduino circuitry and they probably will not be providing exactly the same voltage. If you get below the dropout voltage of the voltage regulator then you may have a bigger problem since the USB voltage will be backfeeding the voltage regulator.

There is a diode between the PWRIN connector and VIN so if you feed the Arduino from that connector the voltage will have to be greater than approximately 7.3 volts to activate the FET and anything less than 7.3 volts may cause the problems mentioned above.

---
Tags: arduino-uno, uploading, rf, heat
---


title: How to load Image in Arduino?

text:
# Question
Title: How to load Image in Arduino?
In my recent project, I want to load Image in my Arduino. Is there any library available that can be used for loading Image in Arduino. Give some suggestion. Thank you!

# Answer
Yes there is a library to load the image to Arduino called as "TFTLibrary".

Loads an image file from the SD card into a named instance of `PImage`. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. Images can be smaller or larger than the screen resolution (160x128), but there is no method on the Arduino for image manipulation. The images should be sized before you put them on the SD card. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. It is possible to load 24 bit bmp image only.

Syntax:

```
screen.loadImage(name);

```

Details available on Arduino website:
https://www.arduino.cc/en/Reference/TFTLoadImage
> 2 votes

---
Tags: arduino-uno, library
---


title: Delay a part of the void loop

text:
# Question
Title: Delay a part of the void loop
I have two different programs written for my Arduino. One checks the room temperature every 5 seconds. The other one looks for IR remote signals.

I would love to combine those 2 programs, yet the problem is the delay from the room temperature sketch.

If I would combine them. it means my IR script won't be working for a full 5 seconds (because of the delay of the room temperature script) then it will be able to receive a fraction of a second and then the temperature sketch goes again.

```
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
int led = 12;
const int inPin = 0;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  int value = analogRead(inPin);
  float millivolts = (value / 1024.0 ) * 5000;
  float celsius = millivolts / 10;
  Serial.println(celsius, 1);
  delay(5000);
  if(irrecv.decode(&results)) {
    //this checks to see if a code has been received
    if(results.value == 0xFF6897) {
      //if the button press equals the hex value 0xC284
        digitalWrite(led, HIGH);
        // turn the LED on (HIGH is the voltage level)
        delay(1000); // wait for a second
        digitalWrite(led, LOW);
        // turn the LED off by making the voltage LOW
        delay(1000); // wait for a second//do something useful here
    }
    irrecv.resume(); //receive the next value
  }
}

```

Does anyone know how to keep the IR part active and the temperature measure every 5 seconds, and do this simultaneously?

Or do I need another Arduino?

# Answer
> 2 votes
**EDIT:** Modify the code according @Edgar's comment.

Check this alternative. The idea is executing code every 5 and 1 seconds. The `blink` is true when you need the LED blinking. I don't know how long will you need to keep it blinking, but this keeps it as long as `results.value` keep being equals to 0xFF6897.

```
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
int led = 12;
const int inPin = 0;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  static boolean blink = false;
  static unsigned long startTemp = 0;
  static unsigned long startBlink = 0;
  unsigned long msTime = millis();

  //  Check for room temp every 5 seconds.
  if (msTime - startTemp >= 5000) {
    startTemp = msTime;
    int value = analogRead(inPin);
    float millivolts = (value / 1024.0 ) * 5000;
    float celsius = millivolts / 10;
    Serial.println(celsius, 1);
  }

  //  Blink every 1 second
  if (msTime - startBlink >= 1000 && blink) {
    startBlink = msTime;
    int state = digitalRead(led);
    digitalWrite(led, !state);
    //  Change blink to stop blinking after one pass (HIGH/LOW).
    //  Modify if you need to keep blinking for longer time.
    blink = (state == LOW);
  }

  if(irrecv.decode(&results)) {
    blink = (results.value == 0xFF6897);
    irrecv.resume(); //receive the next value
  }
}

```

# Answer
> 2 votes
> does anyone know how to keep ...

think about ways to conditionalize execution on time elapsed. I showed a short while ago ways to construct a software timer and you may want to look into that.

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


# Question
Title: Include Adafruit_RGB LCD Shield library in class
I'm trying to make a class to expand on the functionality of the Adafruit-RGB-LCD-Shield-Library I'm creating this based on what I see from this post.

```
class LcdMenu
{
 #include <Adafruit_MCP23017.h>
 #include <Adafruit_RGBLCDShield.h>
 public:
 Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu *LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM->Setup();
  LcdM->lcd.setBacklight(VIOLET);
}

```

However, I'm getting the following error:

> C:\Users\jschere2\AppData\Local\Temp\ccUzvCmX.ltrans0.ltrans.o: In function \`main':
>
> ccUzvCmX.ltrans0.o:(.text.startup+0xf0): undefined reference to \`LcdMenu::Adafruit\_RGBLCDShield::begin(unsigned char, unsigned char, unsigned char)'
>
> ccUzvCmX.ltrans0.o:(.text.startup+0xf8): undefined reference to \`LcdMenu::Adafruit\_RGBLCDShield::setBacklight(unsigned char)'
>
> collect2.exe: error: ld returned 1 exit status
>
> exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

# Answer
Move your `#include` statements outside the class definition.

You declare a pointer, but never allocate space for it with `new`. I see no need for a pointer.

```
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu
{
 public:
     // default ctor will be called here.
     Adafruit_RGBLCDShield lcd;

     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.lcd.setBacklight(VIOLET);
}

```

Also note: you are not extending the `Adafruit_RGBLCDShield` class as in the example you linked. To do that:

```
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu : public Adafruit_RGBLCDShield
{
 public:
     void Setup()
     {
      begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.setBacklight(VIOLET);
}

```
> 1 votes

---
Tags: arduino-mega, class
---