title: Storing integer into character buffer

text:
# Question
Title: Storing integer into character buffer
I have my Arduino code as below.I am trying to send Serial request and get response for it. I can able to send request mentioned in Setup function and also able to switch cases. Problem i am facing Print character buffer after storing the values. can someone suggest me how to store integer value into charcter buffer and print result later.

```
#include "glob.h"
const int BUFFER_SZ = 32;
char sendBuffer[60]={'0'};

void Take_Reading() {

  for (int row = 0; row < 8; row++)
  {
    //   // get rid of me:
    digitalWrite(SO_enable, array[row][0]);
    digitalWrite(S1_enable, array[row][1]);
    digitalWrite(S2_enable, array[row][2]);
    delay(50);
    analog_1_pv[row] = ANALOG_SCALING * analogRead(A0);
    analog_2_pv[row] = ANALOG_SCALING * analogRead(A1);
    analog_3_pv[row] = ANALOG_SCALING * analogRead(A2);
    if ( (analog_1_pv[row] <= MINV_RANGE || (analog_1_pv[row] >= MAXV_RANGE) ))
    {
      Current_Value1[row] =  0.0;
    }
    else
    {
      Current_Value1[row] =  (analog_1_pv[row] * 12.5) - 31.25;

    }

    if (  (analog_2_pv[row] <= MINV_RANGE || (analog_2_pv[row] >= MAXV_RANGE) ))
    {
      Current_Value2[row] =  0.0;
    }
    else
    {
      Current_Value2[row] =  (analog_2_pv[row] * 12.5) - 31.25;

    }

    if (  (analog_3_pv[row] <= MINV_RANGE || (analog_3_pv[row] >= MAXV_RANGE) ))
    {
      Current_Value3[row] =  0.0;
    }
    else
    {
      Current_Value3[row] =  (analog_3_pv[row] * 12.5) - 31.25;

    }

    Mod_current[row] = (uint16_t)(Mul_Factor * Current_Value1[row]);
    Mod_current[row + 8] = (uint16_t)(Mul_Factor * Current_Value2[row]);
    Mod_current[row + 16] = (uint16_t)(Mul_Factor * Current_Value3[row]);

  }

}

int ID_Check() {

  int ID_value;
  for (int row = 0; row < 8; row++)
  {
    digitalWrite(SO_enable, array[row][0]);
    digitalWrite(S1_enable, array[row][1]);
    digitalWrite(S2_enable, array[row][2]);
    Status_Out[row] = digitalRead(Output_Read);

  }

  ID_value = 1 * Status_Out[7] + 2 * Status_Out[6] + 4 * Status_Out[5] + 8 * Status_Out[4] + 16 * Status_Out[3] + 32 * Status_Out[2] + 64 * Status_Out[1] + 128 * Status_Out[0];
  return (ID_value);

}

int  Take_Temp_Reading()
{

  Temp_Total = Temp_Total - Temp_readings[Temp_index];
  Temp_readings[Temp_index] = analogRead(A5);
  Temp_Total = Temp_Total + Temp_readings[Temp_index];
  Temp_index = Temp_index + 1;

  if (Temp_index >= numReadings)
  {
    Temp_index = 0;
    Temp_Average = Temp_Total / numReadings;
  }
  temp = (Temp_Average * 5.0) / 1023.0;

  //  temp = float(analogRead(A5)) * 5.0 / 1024.0;
  temp_int = (int)(temp * 100.0);
  return (temp_int);
  // Serial.print("Temp"); Serial.println(temp);
}

int SPD_Check()
{

  SPD_STATUS = digitalRead(SPD_STATUS_PIN);
  return (SPD_STATUS);
}

int  DC_Status()
{

  DC_STATUS = digitalRead(DC_STATUS_PIN);
  return (DC_STATUS);

}

int   Take_HV_Reading()
{

  //int analog_int= analogRead(A4);

  total = total - readings[index];
  // read from the sensor:
  readings[index] = analogRead(A4);
  // add the reading to the total:
  total = total + readings[index];
  // advance to the next position in the array:
  index = index + 1;

  // if we're at the end of the array...
  if (index >= numReadings1)
  {
    index = 0;
    average = total / numReadings1;

  }
  else
  {

    HV_voltage = (average * 5.0) / 1023.0;
  }
  if (HV_voltage <= 0.25)
  {

    Conv_HV_voltage = 0.0;
  }
  else
  {
    Conv_HV_voltage = 197.837837838 * HV_voltage + 10.8108108108;
  }

  HV_Reading = (uint16_t)(Conv_HV_voltage * 10);

  //  HV_Reading = (uint16_t)(Conv_HV_voltage * 10);

  return(HV_Reading);
}

void  Serial_Command1()

{
   Take_Reading();
  int Temp_read=Take_Temp_Reading();
  int HV_Read=Take_HV_Reading();
  SPD=SPD_Check();
  DISCONNECTOR=DC_Status();
  Serial.println("Command1 executed ");

  sendBuffer[1]=char(Mod_current[1]) ;
  sendBuffer[2]= ',';
  sendBuffer[2]= Mod_current[1];
  sendBuffer[3]= ',';

  sendBuffer[4]= Mod_current[2];
  sendBuffer[5]= ',';
  sendBuffer[6]= Mod_current[3];
  sendBuffer[7]= ',';

  sendBuffer[8]= Mod_current[4];
  sendBuffer[9]= ',';
  sendBuffer[10]= Mod_current[5];
  sendBuffer[11]= ',';

  sendBuffer[12]= Mod_current[6];
  sendBuffer[13]= ',';
  sendBuffer[14]= Mod_current[7];
  sendBuffer[15]= ',';

  sendBuffer[16]= Mod_current[8];
  sendBuffer[17]= ',';
  sendBuffer[18]= Mod_current[9];
  sendBuffer[19]= ',';

  sendBuffer[20]= Mod_current[10];
  sendBuffer[21]= ',';
  sendBuffer[22]= Mod_current[11];
  sendBuffer[23]= ',';

  sendBuffer[24]= Mod_current[12];
  sendBuffer[25]= ',';
  sendBuffer[26]= Mod_current[13];
  sendBuffer[27]= ',';

  sendBuffer[28]= Mod_current[23];
  sendBuffer[29]= ',';
  sendBuffer[30]= Mod_current[22];
  sendBuffer[31]= ',';

  sendBuffer[32]= Mod_current[21];
  sendBuffer[33]= ',';
  sendBuffer[34]= Mod_current[20];
  sendBuffer[35]= ',';

  sendBuffer[36]= Mod_current[19];
  sendBuffer[37]= ',';
  sendBuffer[38]= Mod_current[18];
  sendBuffer[39]= ',';

  sendBuffer[40]= Mod_current[17];
  sendBuffer[41]= ',';
  sendBuffer[42]= Mod_current[16];
  sendBuffer[43]= ',';

  sendBuffer[44]= Mod_current[15];
  sendBuffer[45]= ',';
  sendBuffer[46]= Mod_current[14];
  sendBuffer[47]= ',';
  sendBuffer[48]= Temp_read;
  sendBuffer[49]= ',';
  sendBuffer[50]= HV_Read;
  sendBuffer[51]= ',';
  sendBuffer[52]= SPD;
  sendBuffer[53]= ',';
  sendBuffer[54]= DISCONNECTOR;

  Serial.println(sendBuffer[1]);

}

void Serial_Command2(int a)
{

  Serial.print("Command2 executed: ");
  Serial.println(a);
}

void setup()
{
  Serial.begin(57600);
  Serial.println("Format 1: <SMCB1,1>");
  Serial.println("Format 2: <SMCB1,1,Length>");

}

// Parse the request, WITHOUT the '<' and '>' delimiters.
void parseRequest(char *request)
{
  // Check the request starts with the prefix "SMCB1,1".
  if (strncmp(request, "SMCB1,1", 7) != 0) {
    Serial.println(F("Error: bad request prefix"));
    return;
  }

  // Remove that known prefix.
  // Now we have either "", ",Length" or ",Timer,On_OFF"
  request += 7;

  // Format 1: ""
  if (request[0] == '\0') {
    //Serial.println(F("Received format 1"));
    Serial_Command1();
    return;
  }

  // Remove the leading comma.
  // Now we have either "Length" or "Timer,On_OFF"
  if (request[0] != ',') {
    Serial.println(F("Error: ',' expected"));
    return;
  }
  request++;

  // Format 2: "Length", no comma.
  char * comma = strchr(request, ',');
  if (!comma) {

    int length = atoi(request);
    Serial_Command2(length);
    //Serial.print(F("Received format 2, length = "));
    // Serial.println(length);
    return;
  }

}

void loop()
{
  static char buffer[BUFFER_SZ];  // received chars
  static size_t pos;              // current position in buffer
  static bool insideRequest;      // are we between '<' and '>'?

  if (Serial.available()) {
    char c = Serial.read();
    if (insideRequest) {
      if (c == '>') {  // end of request received
        buffer[pos] = '\0';  // terminate the string
        parseRequest(buffer);
        pos = 0;             // get ready for the next request
        insideRequest = false;
      }
      else if (pos < BUFFER_SZ-1) {  // add char to buffer
        buffer[pos++] = c;
      }
    }
    else if (c == '<') {  // start of request
      insideRequest = true;
    }
  }
}

```

Golb.h header file contains

```
#ifndef GLOB_H
#define GLOB_H
int counter=0;
int Mod_current[24];
const int numReadings = 10;
const int numReadings1 = 10;
int Temp_Total = 0;
int Temp_readings[numReadings];
int Temp_index = 0;
int Temp_Average = 0;
float  reading[10];
float Total = 0.0;
static int i;

int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;

// These PinS are use to enable and disable analog MUX
int SO_enable = 5;
int S1_enable = 4;
int S2_enable = 3;

// temprature sensor permeter
int TempPin = 5;
float temp;
static int temp_int;

// digital mux setting
int Output_Read = 2;

float Vref = 2.5;
// Used for sensor conversion
float ANALOG_SCALING = 0.004887585532746823;
//tempfloat ANALOG_SCALING=0.0049560117;

int Sensor_Value0 = 0;
int Sensor_Value1 = 0;
int Sensor_Value2 = 0;
float analog_1_pv[8];
float analog_2_pv[8];
float analog_3_pv[8];
int Status_Out[8];

//SPD & DC STATUS PIN
static int SPD_STATUS_PIN = 6;
static int DC_STATUS_PIN = 7;

int row;

int Mul_Factor = 10;

float Current_Value1[8] = {
  0.0
};
float Current_Value2[8] = {
  0.0
};
float Current_Value3[8] = {
  0.0
};

//HV perameter setting are defined here
int HV_SensorValue;
int HV_Reading;
float HV_voltage;
float Conv_HV_voltage;
unsigned  int DC_STATUS = 0;
unsigned int SPD_STATUS = 0;
float MINV_RANGE = 2.52;
//float MIDV_RANGE1=1.875;
float MAXV_RANGE = 4.5;

int SPD;
int DISCONNECTOR;

int Serial_Status=0;

int array[8][3] = {
  {
    0, 0, 0
  }
  , {
    0, 0, 1
  }
  , {
    0, 1, 0
  }
  , {
    0, 1, 1
  }
  , {
    1, 0, 0
  }
  , {
    1, 0, 1
  }
  , {
    1, 1, 0
  }
  , {
    1, 1, 1
  }
};

#endif

```

# Answer
> 3 votes
The simple answer is: don't.

At the moment you are trying to assign integers to chars, and that just won't fit. It's like a round peg in a square hole. Or more like trying to force a bowling pin through a hose pipe. It just isn't going to fit.

So you either need to "print" the values into your final string (say with `sprintf()`) or just don't build up a string at all and print the values directly. And while you're at it, use some loops to make your code simpler:

```
for (int i = 0; i < 14; i++) {
    Serial.print(Mod_current[i]);
    Serial.print(",");
}

for (int i = 23; i > 13; i--) {
    Serial.print(Mod_current[i]);
    Serial.print(",");
}

Serial.print(Temp_read);
Serial.print(",");
Serial.print(HV_Read);
Serial.print(",");
Serial.print(SPD);
Serial.print(",");
Serial.println(DISCONNECTOR);

```

If you really need to create a string the easiest way is probably with `sprintf` (or `snprintf` to prevent buffer overflows):

```
char sendBuffer[200]; // Enough room for 28 integers of 1-5 characters, plus commas.

snprintf(sendBuffer, 200, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
    Mod_current[0], Mod_current[1], Mod_current[2], Mod_current[3],
    Mod_current[4], Mod_current[5], Mod_current[6], Mod_current[7],
    Mod_current[8], Mod_current[9], Mod_current[10], Mod_current[11],
    Mod_current[12], Mod_current[13], Mod_current[14], Mod_current[23],
    Mod_current[22], Mod_current[21], Mod_current[20], Mod_current[19],
    Mod_current[18], Mod_current[17], Mod_current[16], Mod_current[15],
    Mod_current[14], Temp_read, HV_Read, SPD, DISCONNECTOR);

int len = strlen(sendBuffer);
Serial.println(sendBuffer);
Serial.print(len);
Serial.println(" bytes");

```

(note: I think I got the right number of parameters there)

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


title: Button Relay Control

text:
# Question
Title: Button Relay Control
How can I fix this sketch to make it so that once the button is pressed, it performs some action for a certain amount of time and then returns back to a low state until it is pressed again. For example, I need to run a pump for 5 seconds when the button is pressed and then turn off automatically. And then, when I press the button again it will repeat, etc. I am not trying to use a relay module if it is not necessary. Here is my current sketch and a Lab View of the components:

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

int switchPin = 8;
int ledPin = 13;
int buttonPresses = 0;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
}

boolean debounce(boolean last) //just a debounce function
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop()
{
  {currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledOn = !ledOn;

    buttonPresses++;
    lcd.clear();
    lcd.print("Number of Button ");
    lcd.setCursor(0,1);
    lcd.print("Presses = ");
    lcd.print(buttonPresses);
  }
   lastButton = currentButton;
   digitalWrite(ledPin, ledOn);
  }
}

```

THANK YOU!

# Answer
This code should work. You will need to declare the following variables:

* lastPress // The last time the button was pressed
* outputState // The state of the timed output
* outputPin // The pin number for the timed output
* PERIOD // The amount of time that the outptu remains on

The code:

```
void loop()
{
    currentButton = debounce(lastButton);
    if (lastButton == LOW && currentButton == HIGH)
    {
        ledOn = !ledOn;

        buttonPresses++;
        lcd.clear();
        lcd.print("Number of Button ");
        lcd.setCursor(0,1);
        lcd.print("Presses = ");
        lcd.print(buttonPresses);

        outputState = HIGH;
        lastPress = millis();
    }

    if (outputState && ((millis() - lastPress) > PERIOD))
    {
        outputState = LOW;
    }

    digitalWrite(outputPin, outputState);

    lastButton = currentButton;
    digitalWrite(ledPin, ledOn);
}

```

A relay should be used to drive a pump etc.. The Arduino Uno can only drive 5V at maximum 20mA.
> 0 votes

---
Tags: arduino-uno, lcd, timers, button, code-review
---


# Question
Title: Can an ATtiny print results to a console?
I'm trying to port some Arduino code that I wrote for the Arduino Mega to an ATtiny and I'm having trouble figuring out how to do output. Here is what I have:

```
char foo;
#include <SoftwareSerial.h>
const int rx=3;
const int tx=4;

SoftwareSerial mySerial(rx,tx);

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

void loop() {
 if (mySerial.available()) {
   char data = mySerial.read();
   mySerial.write(data);
 }

 mySerial.println("hello");
}

```

To my understanding this should print "hello" to the console over and over again but for some reason it uploads successfully but then it doesn't do anything.

Here is the programmer that I am using to connect my ATtiny to my computer: https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/programming-in-arduino

# Answer
You don't have any output because you don't have a serial adapter connected to the device. The programmer you have is only for programming and does not support a UART serial connection.
> 3 votes

# Answer
This is writing serial data to digital pin 4. If you have a serial to USB converter attached to pins 3,4 and you have a terminal attached to said serial to USB converter, it will print to that terminal.

Also, on an ATtiny, you have to check which pins are pins 3,4. They are probably not the physical pins 3,4, and it is dependent on which pin mappings you are using (dependent on ATtiny libraries).
> 0 votes

---
Tags: attiny
---


title: Arduino wire question

text:
# Question
Title: Arduino wire question
I am a complete newbie to Arduino and I just received an ARDX arduino starter kit (the one that comes in the transparent green case) I have been following the instructions for Circ-01 for the blinking led light but I am curious about the wires. In the breadboard instructional picture it shows a purple wire that is supposed to connect to pin 13 on the arduino. But the kit did not come with a purple wire, it only came with black, red, white, yellow, and green wires.

I also tried following a tutorial on YouTube and the guy in the video used a purple wire that he said was the led "cathode"

Can i substitute another wire for the purple and? Or did I receive an incomplete kit? I am very confused and the breadboard instruction picture is not very clear.

Thanks for any help!

# Answer
> 2 votes
Personally I like to try to use red wires for +5V, black or blue for ground, and yellow for data. However as Majenko said in a comment, the colour is irrelevant to the operation.

The usefulness of colour is just that if you stick to a system (like red for +5V and black for ground) then there is a visual check you make when connecting up a circuit, so you don't accidentally put things in backwards, like you might if every wire is yellow.

Also, if you run half-a-dozen wires from one place to another, using different colours is another way of making it easier to see you have connected the correct things together.

Having said all that, the colour does not otherwise affect things.

---
Tags: arduino-uno, led, wires
---


title: Change timeout of `Serial.parseInt()`?

text:
# Question
Title: Change timeout of `Serial.parseInt()`?
`Serial.parseInt()` reads from the serial buffer until it sees a non-numeric character or it's timeout is reached. When I use it, I put a space after the last number to make it return faster. Can I change the timeout so if I forget the number it doesn't take as long?

# Answer
> 3 votes
You can, just call

```
Serial.setTimeout(millisecondValue);

```

https://www.arduino.cc/en/Serial/SetTimeout

It defaults to one second, and controls the timeouts for readBytes, readBytesUntil, parseInt and parseFloat.

# Answer
> 2 votes
Don't use `Serial.parseInt()`. It is very very wrong. The whole idea behind how it operates is completely wrong and teaches bad practices and methods.

Part of your way of speeding it up is half-way to doing it properly.

You require a delimiter to say "this is the end of the number". Relying on time in a system that is inherently asynchronous is just plain daft. You have chosen to add a space. A better choice is to use a proper line ending "\n".

Then you should either read the serial character-by-character and parse it as it arrives until you find the EOL character, or read it character by character into a string (NOT a String, a "string" - a C string - a character array terminated by a NULL character), and then use `atoi()` etc to convert it to the numerical format you want.

Many of the methods that Arduino provide are not suitable for professional use and should be avoided at all cost lest they teach you the completely wrong way of doing things.

---
Tags: serial
---


# Question
Title: Converting an array of uint8_t to a char array
I'm trying to convert this array `uint8_t data[]` in the code below to a character array to be printed in the serial monitor. However, when I run this code I see a blank screen. What am I doing wrong?

```
Serial.begin(115200);
uint8_t data[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x01,0x02,0x03,0x04,0x05};
Serial.println((char*)data);

```

# Answer
When you cast as `char *`, `println` thinks you are passing it a string. It will try to print it as a string and stop on the first `0x00`.

You can use `Serial.write` to send the array as integers (no conversion):

```
Serial.write(data, sizeof(data));

```

If you want to send the ASCII representation of these numbers, use a loop. `Serial.print` will convert:

```
int count = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < count; i++) {
    Serial.print(data[i]);
}
Serial.println();

```
> 0 votes

# Answer
To print numbers, integers have to be converted to ASCII code. To accomplish this add 0x30 to each value. Note, this (only) works for numbers between 0 and 9 as the ASCII value for zero is 0x30. Good code will check to make sure only the values 0 through 9 are being processed.

When creating a character string you need to identify the end using the NULL character. Before using an array of characters, set the array position after the last desired character equal to NULL or 0x00. Terminating the string is explained further in this article.
> 0 votes

---
Tags: c, arduino-yun
---


# Question
Title: Linking Arduino Nano with ESP8266 Wifi module
I recently started playing around with Arduinos to connect a few sensors up. I used an Arduino Nano to measure temperature, humidity, air pressure and light level.

To store the data in a database, I used another Arduino that I connected to a Raspberry Pi, and let the two Arduinos talk wirelessly to each other via 433 MHz.

That all works pretty well, but the 433 MHz communication is not exactly the most reliable (I often miss a transmission). When I stumbled upon the ESP8266 module, it seemed like the optimal solution for communication. How cool would it be if I could just pull out the information via an HTTP call from the Raspberry Pi?

After toying around for many hours, uploading many different firmwares, getting more and more frustrated because I could not get it to do anything, I finally have it working through an FTDI module connected up like this:

I use an MB102 power module to provide the 3.3v required by the ESP8266. I turns out you need to connect the ground from the MB102 to the ground of the FTDI module to get any proper response. After doing that I was able to send AT commands and get the proper responses. I could even connect it to my home Wifi.

The next thing I want to do is connect it to the Arduino. I found a very simple schema for that (http://blog.huntgang.com/2015/01/20/arduino-esp8266-tutorial-web-server-monitor-example/), where you connect RX to TX and TX to RX. Using the MB102 I connected it like this:

Apparently I should now be able to upload a blank sketch to the Arduino, and then use the serial monitor again to sens AT command, exactly the same way I did it when using the FTDI module.

The problem is that I get nothing at all this way. I don't even see my own AT commands in the console. I do see the ESP8266 flashing every time I send a command (I even see it it still connected to my router, probably it remembered the info I send through the FTDI...?)

The question is, what am I going wrong? I read some posts about the TX from the Arduino also being 5v and that you need to do something to bring it back to 3.3v, but there are also many tutorials that say it's not required.

# Answer
> 3 votes
The easiest way to work with these devuces is to connect them to a spare pair of Arduino pins and use SoftwareSerial for communicating (unless you're using one of the Arduinos with more than one UART). SoftwareSerial work up to 9600 baud on 16MHz devices, 4800 on 8MHz devices, so you'll need to set the ESP8266 to accommodate that. They currently ship at 115200 baud. You can use the hardware UART on pins (0, 1) but then re-programming the Arduino means disconnecting & reconnecting the ESP temporarily each time, and gets old pretty quickly.

Here's what I do with new ESPs (If you've re-flashed your ESP, you'll need to download the AT instruction-set emulator and re-flash it with that, first):

```
# To configure a new ESP module:
# Connect the ESP and the FTDI as in your top diagram, set your
# terminal-emulator to 115200 baud, and enter the following:

AT                             # ESP should respond "OK"
AT+RST                         # Resets the ESP
AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

# Now change the terminal emulator baud rate to 9600

AT+CWMODE=1                    # Set ESP to station mode (client)
ATE0                           # Set ESP's echo off
AT+CWLAP                       # List access points - after a short pause
                               # the ESP returns a list of WiFi access points

```

For future reference, here is a link to the ESP8266 AT Instruction Set.

Update June 2020: The above link was broken, now fixed. You can also find documentation at Espressif's github account (online readable, but not pdf, as of this date).

# Answer
> 0 votes
There might be an issue with the baudrate from the Nano FTDI chip to the RX/TX and the ESP8266. Did you disconnect when uploading the sketch?

How about trying this instead?

Cheers!

# Answer
> 0 votes
Stumbled on good tutorial here, tried and it does the job: https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/

# Answer
> 0 votes
Yes, if you are using different power sources the grounds always have to be connected, otherwise the boards don't know what zero volts is.

The TX of the Arduino is 5v, you need a level shifter to convert 5v to 3.3v, something like this (https://shop.pimoroni.com/products/adafruit-4-channel-i2c-safe-bi-directional-logic-level-converter?utm\_medium=cpc&utm\_source=googlepla&variant=302017581&gclid=CPqujsPxlc0CFcYcGwodb8YIoA)

The TX of the ESP8266 is 3.3v and the RX of the Arduino is 5V and you will need a level shifter to handle this. You can use the same one as listed above, because it can convert 4 high (5v) signals into 4 low (3.3v) signals.

People say you can so it with resistors, but I have also read that they don't perform well enough to handle fast switching digital signals (so 300 Baud on your serial might be OK, but not 115000 :) )

People also say you don't need level convertors. That's true things *might* work for a while without them, but sooner or later something will go pop. Increasing the voltage will speed up the process so you can imagine what will happen if you connected a 230v supply directly to a USB device.

One final point, do you know the ESP8266 is a 80/160MHz processor with 256KB of RAM, when you compare that to you Arduino its like programming you PC via your phone. What you could try is connecting the ESP8266 via a FTDI module and program it via the Arduino IDE in Arduino C. Its a lot easier than all this connection stuff.

---
Tags: esp8266
---


# Question
Title: Deploy data online from SD Card on Arduino
I intend to design an air pollution monitoring station which will measure these data (CO, NO2, O3, Temperature, Humidity and Pressure). I want to store the data on the SD card during the whole day and deploy it online in CSV format. I will have five stations in fixed locations and gather their daily data.

1. Any suggestions about specific types of sensors (references)?
2. How to store the data as CSV format?
3. How to send the data online at certain time on Arduino?
4. Is it better to use GSM or WiFi?

# Answer
> 0 votes
> How to store the data as CSV format?

Write the values to the card with commas between them.

```
myFile.print(noxValue);
myFile.print(",");
myFile.print(coValue);
myFile.print(",");
myFile.println(ozValue);
... etc ...

```

> How to send the data online at certain time on Arduino?

You need to make a suitable network request to whatever unknown thing it is you are sending it to. That may be a HTTP POST request, or it could be some completely different mechanism. Until you have decided where you are sending it we can't help you with the how of sending it.

As to the *when*, you really could do with a Real Time Clock module so you know what the time is. Then at a certain time you can run your code. Some RTC modules have an alarm that can alert you when it's time to send your code. Great for if your MCU has been placed in a sleep mode and needs waking up at the right time.

> Is it better to use GSM or WiFi?

That depends if you have access to WiFi where the sensor is. If you do, then WiFi is (more often than not) cheaper. If you don't, then WiFi is impossible and GSM is the only option.

---
Tags: sensors, wireless, datalogging
---


# Question
Title: Can I connect a camera without a shield?
I have an Arduino Uno and an ArduCAM-mini 2MP camera:

http://www.arducam.com/tag/arducam-mini/

Is it possible to connect this camera, or similar cameras, to the arduino without a shield? The only tutorials I've found use a shield.

edit - here is what my cam looks like:

# Answer
Judging by the photo (below) it is specifically designed to plug into the SPI ports on a Uno or similar (that is, pins 10 to 13). The other two wires are going to the ICSP header, presumably to pick up +5V and ground.

So yes, most certainly you can use it like that. With the pins done like that it even points horizontally.

> It wasn't clear to me that I should bend the camera pins as such (mine has 8 pins pointing downward).

You can buy pins with a 90° angle. If yours are not already soldered on, I would use the bent connector. If the pins are already soldered on, then the camera would lie flat, so just rotate the Arduino itself to point to where you want it to.

However you would need to do something with the +5V and Gnd pins, so that they can be rerouted to the correct place.

---

Looking at another photo on that site.

The pins would match most of the pins on a Uno, like this:

The only one that is wrong is AREF - you need +5V into that pin, not AREF, which is why they bent those two pins outwards (+5V and Gnd) and ran wires to the ICSP header.

---

If you mean all your pins are at right-angles already, then you really only need to fix the +5V one (you can probably bend it up). This is the pin-out for the ICSP header (view from above):

As you can see, you can pick up +5V from pin 2 (Vcc). Alternatively, run the +5 wire over to where +5 is marked on the Uno on the other side.

---

Another possible approach would be to not bend anything, but solder on a wire to the +5V pin and leave it plugged into AREF. AREF is just an input (analog reference voltage) and it won't hurt to have it left at +5V.
> 3 votes

---
Tags: arduino-uno
---


title: Arduino powering from 9V battery

text:
# Question
Title: Arduino powering from 9V battery
Yesterday afternoon I have left my Arduino running on a fresh Alkaline 9V battery (+ connected to Vin, - connected to GND). Today morning (16 hours later) the LCD display was no longer visible, and when I measured the volatage, I saw the battery was depleted to my surprise - its idle voltage was only 7 V.

My device is Arduino Uno with LCD 2x16 with LCD backlight and 2 DS18B20 sensors. Is it normal for such device to deplete 9V battery this quick?

I have read an answer to What are (or how do I use) the power saving options of the Arduino to extend battery life? question and I think what I see might be related to this, however I am not sure. If it is, is there some common schematics how to connect Arduino to be powered by a battery efficiently?

# Answer
**Power consumption**

The Arduino boards use a fair bit of power compared to other embedded systems with similar functionality.

There are three main factors:

* The NCP1117 (datasheet) 5V linear regulator in the Arduino UNO R3 (schematic) has a quiescent current of around 6mA.
* The ATMega328P (datasheet) draws around 5mA @ 8MHz and 5V, and probably more than double that at 16MHz.
* *user2973:* The ATMega16U2 used for USB communications also draws approximately 13mA.

LEDs and other peripherals also draw some current. In your circuit, the LCD backlight is probably drawing 4mA as well.

When dropping 9V to 5V via a linear regulator, almost half of the power is lost by the regulator due to its 4V drop. *Duncan* comments that this nearly doubles the *quiescent* power draw from 9V as well as the power needed for every mA of 5V, since 4/9ths of the power gets wasted as heat by the voltage regulator. An efficient switching regulator would put out 5V with little wasted energy, effectively reducing the current draw seen by the battery by 4/9ths.

A duracell 9V battery (datasheet) drops from 9V to 7V in around 7.5 hours with a 50mA current draw. Therefore, a rough guess is that your circuit draws around 25mA, which sounds about right based on the description of your circuit.

Note, alkaline battery life is non-linear with respect to current. For very small currents (\<1mA) the life of an Alkaline approaches that of a lithium battery.

**Getting current down**

Here are some tips to get the current consumption down:

* *Regulator:* Replace the regulator with one with a low quiescent current, or better yet, a switching regulator (also with low quiescent current). A switching regulator uses 'pulses' of current and some external inductor and capacitors to give a reasonable steady voltage output. It doesn't waste energy like with the voltage drop of linear regulator and efficiency in the high 90% are possible.

+ There are buck (step down) converters that take the battery as input, then connect directly to 5V and GND, bypassing VIN and the regulator. This one from Pololu both steps up and down, and has 0.1mA quiescent current.
    + Alternatively, you could use some 1.5V alkaline batteries, and a boost (step up) converter to get the voltage up to 5V (e.g. this product from Sparkfun). It seems boost converters are more commonly stocked.
    + Finally, you could buy a rechargeable lithium battery with charging shield. This advantage of this is not having to buy new batteries, and for a tiny bit bigger than a 9V battery the lithium one has much greater capacity. A really cool product is the seeeduino stalker waterproof kit that includes a charging circuit, battery, solar panel and other goodies.
* *ATMega328P:* Rather than using `delay` for timing and spinning in `loop` endlessly waiting for something to happen, re-write your code so that it goes to sleep in between sensor reads, etc. There are a few low power libraries out there that use the watchdog timer for periodic wakeup from sleep which are handy. You can get the current consumption of the ATMega328P below 0.1mA during sleep.
* *LCD:* Turn off the backlight, or even the entire LCD. Add a button to the design that the user can push to activate the LCD and have it turn off after a set amount of inactivity.
* *Peripherals:* Most peripheral chips also have a sleep mode that drastically reduces their power consumption. Remove power LEDs and other indicators that are not necessary.
* *ATMegu16U2:* *user2973* comments It seems this chip is quite power hungry (*user2973*). It could be removed to save power and just use the UART instead, but that seems like overkill. There are Arduino Pro boards that are just the bare bones Arduino without the USB interface that could be used instead of the UNO.
* *Batteries:* Other alkaline cells have much greater capacity. For example, a 1.5V AA has over 2000mAh for low currents. Using AA cells plus a boost converter can increase the time before battery replacement. Use D cells (16000mAh) and it will run for quite a while. :D

**Summary**

With appropriate power supply and coding you can get a reasonable amount of life out of a battery. Using the above principles, I have made an Arduino derivative board that measures a few sensors and stores the readings to an SD card every half a second. It can last for about 4 months on 2 AA batteries, so it is definetly possible to have low power and remain in the Arduino ecosystem.

The chip I used for the low power in my board is the LTC3525-3.3V. It takes an input voltage as low as 0.8V and boosts up to 3.3V and a 5V version is also available. I designed a PCB for this chip as there was no ready-made breakout, and in the datasheet there are reference designs. The main critera for choosing this chip was it still had high efficiency at very low currents. Some other converters need a small minimum current draw.

The biggest consumer of power on the board ended up being the micro SD card. It can vary between 0.1mA and 1.5mA of idle current depending on the manufacturer. I have found Verbatim and Lexar cards to consume the least amount of power. I will this EE.SE question up to date with the results of my micro SD card power consumption tests.
> 21 votes

# Answer
I think an Arduino Uno is not suitable for such projects. Some components on the board draw too many amps, as @geometrikal correctly points out. If you're up to a challenge, I would advise you to take your project to another level and go barebones.

Sparkfun has a good article about how to increase battery life, using an ATmega328 that you also have on your Arduino Uno: https://www.sparkfun.com/tutorials/309

Look for ways to create a circuit with only the components that you really need, and have your microcontroller sleep as much as possible.
> 3 votes

# Answer
Another option is to look for a hardware (Arduino Clone) that has been designed for that, like this board: https://bitbucket.org/talk2/whisper-node-avr/overview

Combining such hardware with power-saving code techniques you should be able to run projects for quite long time on batteries!
> 1 votes

---
Tags: power, battery
---


# Question
Title: The function AnalogWrite is outputting less voltage than digitalWrite on my board
I can't figure out why the output voltage of `analogWrite(255)` is less than the voltage of `digitalWrite(255)`. My code and an image of my setup are below. Some other useful information is that I am using the NodeMCU by HiLetgo, 3.3k ohm resistors with the meters, and that the meters use 1mA of current DC at full scale. Thanks for your help!

```
int pPressure       = D2;
int pPrecipProb     = D1;
int pWindSpeed      = D0;

int mTemperature;
int mHumidity;
int mPressure;
int mPrecipProb;
int mWindSpeed;
int mAlert;

void setup() {
  Serial.begin(9600);
  pinMode(pPrecipProb,   OUTPUT);
  pinMode(pWindSpeed,    OUTPUT);
  pinMode(pPressure,     OUTPUT);
  pinMode(LED_BUILTIN,   OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
    mPressure           = (int) constrain(mPressure + 1, 0, 255);
    mPrecipProb         = (int) constrain(mPrecipProb + 1,     0, 255 );
    mWindSpeed          = (int) constrain(mWindSpeed + 1,     0, 255 );

    if(mPressure == 255)
    {
      mPressure = 0;
      mPrecipProb = 0;
      mWindSpeed = 0;
    }

    digitalWrite(pPressure,      HIGH   );
    analogWrite(pPrecipProb,    255 );
    analogWrite(pWindSpeed,     mWindSpeed  );

    delay(10);

}

```

Left: AnalogWrite(255)

Middle: DigitalWrite(HIGH)

Right: the other one that cycles

# Answer
First, do something simpler, and eliminate possible causes.

1. Are you *certain* the NodeMCU's CPU is an 8bit PWM? If it were 9bits, it would read about 50% full scale, and 10bits would be about 25% of digitalWrite (which is what I think I can see on the photo).
2. Swap the analogue meters around, and see if the difference is consistent with the pin, or consistent with the meters.
3. Use a digital multimeter (DMM) to measure voltage. It should be a small load. So this should eliminate, or identify, the analogue meters as a culprit.

If there is still a difference in voltage, do the NodeMCU equivalent of:

```
void setup() {
  pinMode(10, OUTPUT);  // a pin capable of analogOut and DigitalOut
}

void loop() {
  digitalWrite(10, HIGH);
  analogWrite(9, 255);  // a pin capable of analogOut and DigitalOut

  delay(100);
}

```

Then swap 9 and 10.

If the DMM shows the analogue output is consistently lower, then go back and check that PWM is 8 bits, and the device output range for PWM is the same output voltage as digitalWrite to a GPIO.
> 6 votes

---
Tags: analogwrite, digitalwrite
---


# Question
Title: Safe changes in the Arduino Libraries and use them
I changed 2 Arduino Libraries because i have a 9 bit data protocol, now i want use the amended Libraries on my Arduino mega2560.

At first i have set a 9 bit data mode that can i do when i set the UCSZ12 bit on 1(original code under the following link: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L103 ):

```
void HardwareSerial::begin(unsigned long baud, byte config)
  ...
  sbi(*_ucsrb, RXCIE0);
  sbi(*_ucsrb, UCSZ12);  // chance: set 9-bit data mode on 1
  cbi(*_ucsrb, UDRIE0);
  ...

```

At second i want throw an interrupt when the 9th bit is an 1 that can i do when i change the code like the follow (original code under the following link : https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial\_private.h#L101 ):

```
void HardwareSerial::_rx_complete_irq(void)
  if (bit_is_clear(*_ucsra, UPE0)) {
    bool is_address = UCSR0B & _BV(RXB80);
    unsigned char c = *_udr;
    if (is_address) {
      do_something_with_address(c);
      return;
    }
  rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;
...

```

What must i do with the two file´s?

How can i use the changed Libraries?

# Answer
> 0 votes
I found the path to the files i want change in the github link so i can change the files(C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino).

I enable the uart for 9 bit, i add sbi(\*_ucsrb, UCSZ12); in HardwareSerial::begin

I decided that i only send a Flag to my PC when the 9th bit is set. For that i change the \_rx\_buffer to a 2 byte matrix (short \_rx\_buffer). Now i send the databyte in the low-byte and flags for 9 bit, framing error and overrun error in the high-byte. That i can do that i change the void HardwareSerial::\_rx\_complete\_irq(void) code like the follow:

```
void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0))
  {
    bool is_address = UCSR0B & _BV(RXB80);
    bool is_framError = UCSR0A & _BV(FE0);
    bool is_overError = UCSR0A & _BV(DOR0);
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    if (i != _rx_buffer_tail)
    {
     _rx_buffer[_rx_buffer_head] = c;
     _rx_buffer[_rx_buffer_head] |= is_address << 8;
     _rx_buffer[_rx_buffer_head] |= is_framError << 9;
     _rx_buffer[_rx_buffer_head] |= is_overError << 10;
     _rx_buffer_head = i;
    }
  }
  else {    *_udr;  };
}

```

I hope this will work and i can evaluate the data right at the PC.

Frindly wishes sniffi

---
Tags: library, core-libraries
---


# Question
Title: How can you export data to a file in Arduino?
How can I export the readings that are being sent to my Arduino Mega to a file?

I know there is a write() method but I can't find the documentation on how to use it.

I want the file to be created and stored on my PC not an SD card. Also I want to know if there is a way to do this without using external programs.

# Answer
You can use a terminal program like putty or Minicom to write that data to a log file. Then you can use whatever program or app to process this log file. Both programs can read from the serial interface.
> 1 votes

# Answer
if your arduino is connected to a computer, you can create a small application that will listen to serial port and write on a file whatever arduino sends over the serial.

Alternatively you can write directly on an sdCard. (There are many sdCard shields available on the market.)

As for the write method, you probably are referring to write method of File class of SD library
> 0 votes

# Answer
> I know there is a write() method but I can't find the documentation on how to use it.

You can use: `Serial.write(F("TEXT"));` to send text over the "serial communication". This basically means that your Arduino will send the text to your PC over the USB emulated COM port.

The magnifying glass button at the top-right of your Arduino IDE's screen will open the "Serial Monitor" here you can see the text that's coming from the Arduino, you can even send text back.

> How can I export the readings that are being sent to my Arduino Mega to a file?

You could make your Arduino interface with an SD-card. Or use that serial connection I told you about.

You could create a program (on the PC) that takes the serial input and stores it into a file. A lot of examples from this should be on the internet. Another thing might be, to use a more advanced serial terminal. I believe "terminal.exe" allows "logging" to a file.
> 0 votes

---
Tags: arduino-mega
---


title: Operating two functions simultaneously

text:
# Question
Title: Operating two functions simultaneously
I have connected a bluetooth module(HC-06) and a voice recognition shield(EasyVR) on an arduino UNO.

By using an another HC-06 on the another arduino(so, 2 arduinos and 2 HC-06 totally), I am going to let two arduionos communicate with each other.

Also, simultaneously, one arduino with HC-06 will recogize the voice by using the voice recognition module.

I have successed each operations, but after combining two codes the bluetooth doesn't work... (Voice recognition have successed.)

1. Is it unable to operate two operations simultaneously?
2. Can we use these two sentences in one code?

SoftwareSerial BT(2,3); --\> for bluetooth module SoftwareSerial Port(12,13); --\> for voice recognition module

# Answer
> Is it unable to operate two operations simultaneously?

The only way you can do two operations simultaneously is to have two Arduinos. An Arduino can only do one thing at a time. In order to make it seem like it's doing things at once you have to create your sketch accordingly. The use of `delay()` is right out. As are long loops using things like `while()`. In short: *anything that **blocks** is bad*.

> Can we use these two sentences in one code?

Not reliably, no. They are both resource hungry and, to a large extent, blocking. A general rule is, if you need at least two more UARTs than the board provides then you need a different board. You can only reliably work with one software UART at a time.

I would suggest upgrading to a more capable board with more hardware UARTs. Either that or use a bluetooth system that doesn't use UART, such as an SPI based BLE module.
> 1 votes

# Answer
Physically It is impossible to run 2 things at the same time when you have one microcontroller. "The Arduino is a very simple processor with no operating system and can only run one program at a time". But I am pretty sure that the solution you are trying to find, hides in multitasking or interuption. There are some cones in `delay()` function: "The problem is that delay() is a "busy wait" that monopolizes the processor. " But in multitasking, you share clock of the processor between two different pieces. You can find more about running different things simultanously here. I have used `miles()` in one of my projects where were coin validator which was outputing impulses and screen which was showing chash inside it.
> 0 votes

---
Tags: programming, bluetooth, hc-06
---


title: Motor control using arduino board

text:
# Question
Title: Motor control using arduino board
I want to control 2 dc motors using the arduino board directly. One motor must rotate clockwise and the other counter clockwise. The directions doesn't change only the speed of each motors. Can this be done without any shield? Them motors may need a higher voltage than the arduino can provide. If I link the arduino board to a power source of about 15 V (the board is arduino mega limits between 6 and 20 ) and I use "analog.write()" function can I output more than 5 volts(the internal voltage)?

# Answer
Simplest way to do this is two MOSFETs (one per motor, because you don't need to change direction), and some miscellaneous passives, and a flyback diode for each motor.

See this tutorial for wiring diagrams and details.
> 1 votes

---
Tags: motor, voltage-level
---


title: Debugging with an ATtiny?

text:
# Question
Title: Debugging with an ATtiny?
I have an ATtiny hooked up to two line scan modules. I'm sending digital signals to the line scan modules then receiving the analog output and storing it in an array. I have an if statement that will make the LED on the ATtiny programmer blink when the number are below a certain range (meaning that lens is covered).

Here is my code:

```
#include <SoftwareSerial.h>
const int rx=0;
const int tx=1;

SoftwareSerial mySerial(rx,tx);
int CLK = 2;
int SI = 1;
int Aout = A3;
int Aout1 = A2;

int LED = 0;

int pixelsArray[128];   //Array to hold the values of the individual pixles.
int pixelsArray1[128];

 void outputPixels()
{
  for(int j = 0; j < 128; j++)
  {
    digitalWrite(LED, LOW);

    if(pixelsArray[j] < 100)
    {
      digitalWrite(LED, HIGH);
      delay(500);
      digitalWrite(LED, LOW);
      delay(500);
    }
  }
}

```

The problem that I am having is that when I test my code with one line scan module it works just fine. You will notice that in the `readPixels()` I have the statement `pixelsArray1[i]=analogRead(Aout1);` commented out. However, when I try to use it with two the LED start blinking regardless of how much light is hitting the line scanner.

The strange thing is that EVEN when I comment out the `digitalWrite(LED, HIGH);` statement in the `outputPixels()` method...THE LED STILL BLINKS!!!

Since the ATtiny does not support URT and can't use the console in Arduino I have no idea how to debug this. Does anyone here have any clue what is wrong?

Here is the datasheets

ATtiny: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85\_Datasheet.pdf

ATtiny Programmer: https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/?\_ga=1.59946280.467360091.1464906372

# Answer
> 0 votes
Since you do not have enough RAM for your arrays, something has to give. A few options:

1. Do you really need the 10-bit precision of the ADC? If you can live with 8 bits, then use 8-bit arrays (type `uint8_t`) and store only the 8 most significant bits of each reading (`pixelsArray[i]=analogRead(Aout)>>2`). This will make the arrays half as big.
2. If you really need 10-bit precision, maybe you do not need 128-pixel resolution? Then you could store only every other pixel. This will also halve the array sizes.
3. If you do need both the full precision and the full resolution, then you will have to pack the bits tight. You can pack up to 4 readings in 5 bytes. But this will increase the complexity of your program.

**Addendum**: To declare the arrays as being made of 8-bit integers, just replace

```
int pixelsArray[128];
int pixelsArray1[128];

```

by

```
uint8_t pixelsArray[128];
uint8_t pixelsArray1[128];

```

Here “uint8\_t” means “unsigned 8-bit integer”, whereas “int” is a regular integer, i.e. signed and, on the AVRs, 16-bits long.

# Answer
> 0 votes
According to the Specs of the Attiny, this microcontroller only has 128 bytes of memory (RAM).

In the code you declare two arrays:

```
int pixelsArray[128];   //Array to hold the values of the individual pixles.
int pixelsArray1[128];

```

which will occuppy much more memory than the available on this microcontroller. Try to reduce the size of the array. Each int entry occupies 2 bytes according to the link.

---
Tags: library, attiny
---


# Question
Title: Help with getting Sensor Average using Arrays
First of all, let me be clear: I'm a total noob, I have close to zero programming experience and I know i'm out of my league, but I want to learn and understand. Here's the issue. The following code has been made to control heat pads using 4 relays that turn off/on depending on the temperature that 4 lm35 Temp sensors pick up. Because these sensors can be jumpy sometimes, I want to get the average temperature from, let's say, 50 readings, and make the code check THAT data instead of the raw temp reading. I have the code for the arduino (I wrote some code and guys over other forums took it and modified it to make it shorter (and that kind of lost me, but the code works) and then I searched smoothing data and got a piece of code that does exactly what I want: make an array, calculate the average temp, and keep deleting and adding new data.

I tried to join both codes together and I got all different kind of errors, lol So here I am.

**The Code that works without average data is this one:**

```
const byte tempPin[] = {A1, A2, A3, A4};
const byte relayPin[] = {6, 7, 8, 9};

// hysteresis = upperLimit - lowerLimit
const byte lowerLimit = 24;
const byte upperLimit = 31;

float tempC[4];
word reading[4];

word printInterval = 1000; // 1 second
unsigned long printCheck = 0, lastPrintTime = 0;

void setup()
{
  analogReference(INTERNAL);
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) {
    pinMode(relayPin[i], INPUT_PULLUP);
    pinMode(relayPin[i], OUTPUT); // defaults HIGH, relay OFF
  }
}

void loop()
{
  // readings and control
  for (int i = 0; i < 4; i++) {
    reading[i] = analogRead(tempPin[i]);
    tempC[i] = reading[i] / 9.31;

    if (tempC[i] < lowerLimit) {
      digitalWrite(relayPin[i], LOW);   //relay OFF
    }
    else if (tempC[i] > upperLimit) {
      digitalWrite(relayPin[i], HIGH);  // relay ON
    }
  }
  printCheck = millis() - lastPrintTime;
  if (printCheck >= printInterval) {
    for (int i = 0; i < 4; i++) {
      Serial.print("tempC");
      Serial.print(i + 1);
      Serial.print(" ");
      Serial.println(tempC[i]);
    }
    Serial.println();
    lastPrintTime = millis(); // reset print timer
  }
}

```

**The average code I got from Arduino Learning center is this one:**

```
/*

  Smoothing

  Reads repeatedly from an analog input, calculating a running average
  and printing it to the computer.  Keeps ten readings in an array and
  continually averages them.

  The circuit:
    * Analog sensor (potentiometer will do) attached to analog input 0

  Created 22 April 2007
  By David A. Mellis  <dam@mellis.org>
  modified 9 Apr 2012
  by Tom Igoe
  http://www.arduino.cc/en/Tutorial/Smoothing

  This example code is in the public domain.

*/

// Define the number of samples to keep track of.  The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input.  Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
const int numReadings = 10;

int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

int inputPin = A0;

void setup() {
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = analogRead(inputPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println(average);
  delay(1);        // delay in between reads for stability
}

```

**The monster I created joining both codes is this one:**

```
const byte tempPin[] = {A1, A2, A3, A4};
const byte relayPin[] = {6, 7, 8, 9};

// hysteresis = upperLimit - lowerLimit
const byte lowerLimit = 24;
const byte upperLimit = 31;

float tempC[4];
word reading[4];

const int numReadings = 50;
int readings[numReadings];
int readIndex = 0;
int total = 0;
float average[4];

word printInterval = 1000; // 1 second
unsigned long printCheck = 0, lastPrintTime = 0;

void setup()
{
  analogReference(INTERNAL);
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) {
    pinMode(relayPin[i], INPUT_PULLUP);
    pinMode(relayPin[i], OUTPUT); // defaults HIGH, relay OFF
  }
  for (int thisReading = 0; thisReading < numReadings; thisReading++){
    readings[thisReading] = 0;
  }
}

void loop()
{
  // readings and control
  for (int i = 0; i < 4; i++) {
    reading[i] = analogRead(tempPin[i]);
    tempC[i] = reading[i] / 9.31;
    total[i] = total[i] - readings[readIndex];
    readings[readIndex] = tempC[i]
    total[i] = total[i] + readings[readIndex]
    readIndex[i] = readIndex[i] + 1 ;
    if (readIntex[i] >= numReadings) {
      readIndex = 0;
    }
    average[i] = total[i] / numReadings;

    if (average[i] < lowerLimit) {
      digitalWrite(relayPin[i], LOW);   //relay OFF
    }
    else if (average[i] > upperLimit) {
      digitalWrite(relayPin[i], HIGH);  // relay ON
    }
  }
  printCheck = millis() - lastPrintTime;
  if (printCheck >= printInterval) {
    for (int i = 0; i < 4; i++) {
      Serial.print("tempC");
      Serial.print(i + 1);
      Serial.print(" ");
      Serial.println(tempC[i]);
    }
    Serial.println();
    lastPrintTime = millis(); // reset print timer
  }
}

```

**These are the errors that I got:**

```
Arduino: 1.6.8 (Windows 7), Board: "Arduino/Genuino Uno"

\temprelayfinal2.ino: In function 'void loop()':

temprelayfinal2:40: error: invalid types 'int[int]' for array subscript

     total[i] = total[i] - readings[readIndex];

            ^

temprelayfinal2:40: error: invalid types 'int[int]' for array subscript

     total[i] = total[i] - readings[readIndex];

                       ^

temprelayfinal2:42: error: expected ';' before 'total'

     total[i] = total[i] + readings[readIndex]

     ^

temprelayfinal2:44: error: 'readIntex' was not declared in this scope

     if (readIntex[i] >= numReadings) {

         ^

temprelayfinal2:47: error: invalid types 'int[int]' for array subscript

     average[i] = total[i] / numReadings;

                         ^

exit status 1
invalid types 'int[int]' for array subscript

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

```

# Answer
> 1 votes
```
total[i] = total[i] - readings[readIndex];

```

`total` is of type `int`. That is, it is a scalar integer. You cannot index into it, `total[i]` doesn't make sense. That is why the compiler is complaining.

# Answer
> 1 votes
Using the exponential moving average filter suggested by Gerben, things become quite simpler:

```
const byte tempPin[] = {A1, A2, A3, A4};
const byte relayPin[] = {6, 7, 8, 9};

// hysteresis = upperLimit - lowerLimit
const byte lowerLimit = 24;
const byte upperLimit = 31;

const int numReadings = 64;
const word printInterval = 1000; // 1 second

float tempC[4];
unsigned long lastPrintTime = 0;

void setup()
{
  analogReference(INTERNAL);
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) {
    digitalWrite(relayPin[i], HIGH);
    pinMode(relayPin[i], OUTPUT);
  }
}

void loop()
{
  // readings and control
  for (int i = 0; i < 4; i++) {
    float raw_temp = analogRead(tempPin[i]) / 9.31;
    tempC[i] += (raw_temp - tempC[i]) / numReadings;  // filter
    if (tempC[i] < lowerLimit) {
      digitalWrite(relayPin[i], LOW);   //relay OFF
    }
    else if (tempC[i] > upperLimit) {
      digitalWrite(relayPin[i], HIGH);  // relay ON
    }
  }
  if (millis() - lastPrintTime >= printInterval) {
    for (int i = 0; i < 4; i++) {
      Serial.print("tempC");
      Serial.print(i + 1);
      Serial.print(" ");
      Serial.println(tempC[i]);
    }
    Serial.println();
    lastPrintTime = millis(); // reset print timer
  }
}

```

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


title: Amforth on Arduino UNO

text:
# Question
Title: Amforth on Arduino UNO
I'm having trouble with flashing `amforth` on my Arduino UNO. I'm using an Arduino as ISP to write `amforth`.

Here's what I do:

1. Upload the code on the Arduino programmer and set Baudrate to 19200
2. Wire the Arduinos this way -\> Wiring
3. Run `avrdude -P /dev/ttyUSB* -c avrisp -b 19200 -p m328p -e -U flash:w:uno.hex:i -U eeprom:w:uno.eep.hex:i -U efuse:w:0x05:m -U hfuse:w:0xD9:m -U lfuse:w:0xFF:m`

Sometimes it fails to set efuse, but if I give the command just for it, even if it says `"efuse changed, it was 5, not is 0xfd, do you want to change it back?"` and I say no, I get the message with the correct fuses.

I log onto the `amforth` Arduino with the python shell, but my stack is constantly `??? -13` and different numbers. I found out `-13` is error code for `not found`, but... not found what?

What does it mean? What am I missing?
I have to say that I'm new at this things, I recently studied Forth and discovered that I can use it on my Arduino, and I wanted to try.
By the way, the Arduino is not original.
The chip is ATmega 328p

EDIT: I downloaded `amforth` from here Initially I followed \[first guide\] (different wiring but I've read around it's the same) and then "clarified my doubts" with another one from sparkfun. (no link used because maximum for me is 2 links per post at the moment, I'll write it in the comments)

I tried with versions `6.1` and `6.0`, then I decided to try with `5.9` (the one from the first guide) and now I'm running that (at least it allows me to pop elements from the stack).

# Answer
> 3 votes
I programmed by Uno using your first guide and it seems to work OK.

```
amforth 6.1 ATmega
8P Forthduino

```

For example, using the serial monitor, I entered:

```
6 7 * .

```

It printed:

```
42  ok
>

```

Then entered the ASCII table example:

```
\ print a ascii table
: .ascii
base @
$7f $20 do
    i emit
    decimal  ." , dec: " i .
    hex      ." , hex: " i .
    8 base ! ." , oct: " i .
    2 base ! ." , bin: " i .
    cr
loop
base !
;

```

Then when I invoked it with ".ascii" it printed the table:

```
> .ascii
 , dec: 32 , hex: 20 , oct: 40 , bin: 100000
!, dec: 33 , hex: 21 , oct: 41 , bin: 100001
", dec: 34 , hex: 22 , oct: 42 , bin: 100010
#, dec: 35 , hex: 23 , oct: 43 , bin: 100011
$, dec: 36 , hex: 24 , oct: 44 , bin: 100100
%, dec: 37 , hex: 25 , oct: 45 , bin: 100101
&, dec: 38 , hex: 26 , oct: 46 , bin: 100110
', dec: 39 , hex: 27 , oct: 47 , bin: 100111
(, dec: 40 , hex: 28 , oct: 50 , bin: 101000
), dec: 41 , hex: 29 , oct: 51 , bin: 101001
*, dec: 42 , hex: 2A , oct: 52 , bin: 101010
+, dec: 43 , hex: 2B , oct: 53 , bin: 101011
,, dec: 44 , hex: 2C , oct: 54 , bin: 101100
-, dec: 45 , hex: 2D , oct: 55 , bin: 101101
., dec: 46 , hex: 2E , oct: 56 , bin: 101110
/, dec: 47 , hex: 2F , oct: 57 , bin: 101111
0, dec: 48 , hex: 30 , oct: 60 , bin: 110000
1, dec: 49 , hex: 31 , oct: 61 , bin: 110001
2, dec: 50 , hex: 32 , oct: 62 , bin: 110010
3, dec: 51 , hex: 33 , oct: 63 , bin: 110011
4, dec: 52 , hex: 34 , oct: 64 , bin: 110100
5, dec: 53 , hex: 35 , oct: 65 , bin: 110101
6, dec: 54 , hex: 36 , oct: 66 , bin: 110110
7, dec: 55 , hex: 37 , oct: 67 , bin: 110111
8, dec: 56 , hex: 38 , oct: 70 , bin: 111000
9, dec: 57 , hex: 39 , oct: 71 , bin: 111001
:, dec: 58 , hex: 3A , oct: 72 , bin: 111010
;, dec: 59 , hex: 3B , oct: 73 , bin: 111011
<, dec: 60 , hex: 3C , oct: 74 , bin: 111100
=, dec: 61 , hex: 3D , oct: 75 , bin: 111101
>, dec: 62 , hex: 3E , oct: 76 , bin: 111110
?, dec: 63 , hex: 3F , oct: 77 , bin: 111111
@, dec: 64 , hex: 40 , oct: 100 , bin: 1000000
A, dec: 65 , hex: 41 , oct: 101 , bin: 1000001
B, dec: 66 , hex: 42 , oct: 102 , bin: 1000010
C, dec: 67 , hex: 43 , oct: 103 , bin: 1000011
D, dec: 68 , hex: 44 , oct: 104 , bin: 1000100
E, dec: 69 , hex: 45 , oct: 105 , bin: 1000101
F, dec: 70 , hex: 46 , oct: 106 , bin: 1000110
G, dec: 71 , hex: 47 , oct: 107 , bin: 1000111
H, dec: 72 , hex: 48 , oct: 110 , bin: 1001000
I, dec: 73 , hex: 49 , oct: 111 , bin: 1001001
J, dec: 74 , hex: 4A , oct: 112 , bin: 1001010
K, dec: 75 , hex: 4B , oct: 113 , bin: 1001011
L, dec: 76 , hex: 4C , oct: 114 , bin: 1001100
M, dec: 77 , hex: 4D , oct: 115 , bin: 1001101
N, dec: 78 , hex: 4E , oct: 116 , bin: 1001110
O, dec: 79 , hex: 4F , oct: 117 , bin: 1001111
P, dec: 80 , hex: 50 , oct: 120 , bin: 1010000
Q, dec: 81 , hex: 51 , oct: 121 , bin: 1010001
R, dec: 82 , hex: 52 , oct: 122 , bin: 1010010
S, dec: 83 , hex: 53 , oct: 123 , bin: 1010011
T, dec: 84 , hex: 54 , oct: 124 , bin: 1010100
U, dec: 85 , hex: 55 , oct: 125 , bin: 1010101
V, dec: 86 , hex: 56 , oct: 126 , bin: 1010110
W, dec: 87 , hex: 57 , oct: 127 , bin: 1010111
X, dec: 88 , hex: 58 , oct: 130 , bin: 1011000
Y, dec: 89 , hex: 59 , oct: 131 , bin: 1011001
Z, dec: 90 , hex: 5A , oct: 132 , bin: 1011010
[, dec: 91 , hex: 5B , oct: 133 , bin: 1011011
\, dec: 92 , hex: 5C , oct: 134 , bin: 1011100
], dec: 93 , hex: 5D , oct: 135 , bin: 1011101
^, dec: 94 , hex: 5E , oct: 136 , bin: 1011110
_, dec: 95 , hex: 5F , oct: 137 , bin: 1011111
`, dec: 96 , hex: 60 , oct: 140 , bin: 1100000
a, dec: 97 , hex: 61 , oct: 141 , bin: 1100001
b, dec: 98 , hex: 62 , oct: 142 , bin: 1100010
c, dec: 99 , hex: 63 , oct: 143 , bin: 1100011
d, dec: 100 , hex: 64 , oct: 144 , bin: 1100100
e, dec: 101 , hex: 65 , oct: 145 , bin: 1100101
f, dec: 102 , hex: 66 , oct: 146 , bin: 1100110
g, dec: 103 , hex: 67 , oct: 147 , bin: 1100111
h, dec: 104 , hex: 68 , oct: 150 , bin: 1101000
i, dec: 105 , hex: 69 , oct: 151 , bin: 1101001
j, dec: 106 , hex: 6A , oct: 152 , bin: 1101010
k, dec: 107 , hex: 6B , oct: 153 , bin: 1101011
l, dec: 108 , hex: 6C , oct: 154 , bin: 1101100
m, dec: 109 , hex: 6D , oct: 155 , bin: 1101101
n, dec: 110 , hex: 6E , oct: 156 , bin: 1101110
o, dec: 111 , hex: 6F , oct: 157 , bin: 1101111
p, dec: 112 , hex: 70 , oct: 160 , bin: 1110000
q, dec: 113 , hex: 71 , oct: 161 , bin: 1110001
r, dec: 114 , hex: 72 , oct: 162 , bin: 1110010
s, dec: 115 , hex: 73 , oct: 163 , bin: 1110011
t, dec: 116 , hex: 74 , oct: 164 , bin: 1110100
u, dec: 117 , hex: 75 , oct: 165 , bin: 1110101
v, dec: 118 , hex: 76 , oct: 166 , bin: 1110110
w, dec: 119 , hex: 77 , oct: 167 , bin: 1110111
x, dec: 120 , hex: 78 , oct: 170 , bin: 1111000
y, dec: 121 , hex: 79 , oct: 171 , bin: 1111001
z, dec: 122 , hex: 7A , oct: 172 , bin: 1111010
{, dec: 123 , hex: 7B , oct: 173 , bin: 1111011
|, dec: 124 , hex: 7C , oct: 174 , bin: 1111100
}, dec: 125 , hex: 7D , oct: 175 , bin: 1111101
~, dec: 126 , hex: 7E , oct: 176 , bin: 1111110
 ok
>

```

---

I suspect your issue is you are not using it the way it is supposed to be used. Can you show the exact commands you type which cause the error?

---

*(Edited to add)*

After fairly extensive investigation of the source, I think that `.s` is not necessarily implemented for the Uno .hex file.

I found one suggested implementation here:

```
: .s  ( -- )\ stack picture listing order
depth
begin dup while dup pick . 1- repeat
drop
;

```

Running that it seems to work OK:

```
> 1 2 3 4 .s
1 2 3 4  ok

```

The `.s` word is implemented in the file `dot-s.asm` where you can see exactly how they did it (it's not the same as the Forth version above).

---
Tags: arduino-uno, arduinoisp
---


# Question
Title: What would be the code for using Arduino UNO to alert by sound or LED when it detects a certain position through GPS?
I am in grade 6. I have a very nice pet dog in my house but it often enters Mom's kitchen to spoil all the foods. So I am thinking of a device to attach with him which can locate its position. But I am totally new to arduino programming. I have found some tutorials of arduino UNO to locate position with GPS. But I don't know how to set up the alarm when my dog reaches the position of our kitchen and what will be the code for it. If I wanna set alarm for different position, like kitchen and two toilets, what would be the code then? I know Java a very little bit. C too. Nothing else. Is there any altruist to help me out, please?

# Answer
> 2 votes
First things first: do you know that a GPS can locate your dog accurately enough in your home?

Basically, even with a good GPS receiver, the best accuracy you can expect (using off-the-shelf receivers, non-military or DGPS) is maybe 3 m. Typical performance is maybe 4 m, and indoors it will be even worse. The point is, your dog could be 5 m away from your intended location, and you will get an alarm. 5 m in a house might be the room over, two rooms over, or outside the house!

However, if you want to go forward with this, get yourself a GPS module, connect it to your Arduino, install the TinyGPS++ library (one of the better Arduino GPS libs IMO), and play with it. It's easy to figure out how to perform an action when the GPS coordinates are in range of a given coordinate set.

You might have better luck using a different form of dog location detection.

# Answer
> 2 votes
A more low-tech solution might be better. For example, a couple of light beams across the doorway to the kitchen. An human would block both of them as they passed, and a dog only the lower one. You could sound an alarm if the lower one is broken, and the upper one is not broken (within a second).

---

Or do something with infra-red transmitters / receivers. There are lots of Arduino projects using those. You could have a transmitter in the kitchen pointing towards the doorway, sending some code (eg. 1234). Mount on the dog an Arduino with an IR decoder sketch. When the dog enters the kitchen it will get the code, and then you could sound a beeper. The beeper alone might make the dog change its mind about going in, especially if you go after it yelling "bad dog!" every time the beeper goes off.

Since the IR beam is just light, it would only go in a straight line, and if properly positioned would flood the kitchen, but not hit anywhere else.

---

## Proof of concept

I made up a test of my idea of the IR transmitter.

*(Please don't report me to the moderators for being off-topic. I know the question was about a GPS, but the **real** question is how to detect that the dog has come into the kitchen).*

You can get IR (infra-red) LEDs cheaply at any electronics supplier (or eBay). They are like normal LEDs except that they transmit in the IR light range. They can also usually handle higher currents, like 80 mA.

---

## Sender

So, to drive that from the Arduino we need a transistor to boost the output from the Arduino pin, like this:

Note that the positive pin of the LED will have a longer lead. The positive pin goes to the 39 ohm resistor, and the negative (shorter) lead goes to the transistor collector. In the schematic the negative pin (cathode) is at the bottom and has a horizontal line (think of the horizontal line as a minus sign).

The 39 ohm resistor limits current through the LED to 74 mA. Assuming a LED forward voltage of 2.1V we have:

```
 (5V - 2.1V) / 39Ω = 74 mA

```

The 470 ohm resistor limits current through the transistor base.

---

## Sender code

Then some simple code to send a IR code (using PWM modulation like TV remotes do). There is a library for that, so the code is very simple:

```
#include <IRLib.h>

IRsend My_Sender;

const unsigned long DOG_ALERT_CODE = 0xBADA;

void setup()
  {
  }

void loop()
  {
  My_Sender.send (NEC, DOG_ALERT_CODE, 20);
  delay (1000);
  }

```

That sends the code 0xBADA (which I just picked at random) every second using the NEC IR protocol.

The objective would be to have this plugged into the power somewhere in the kitchen, and aimed at the doorway. The IR library uses digital pin 3 (on the Uno at least). That happens to be the Timer 2 "B" output to send 38 kHz PWM (pulse-width-modulated) signal, which it interrupts from time to time to encode the code into it.

---

## Receiver

Now we need something on the dog to detect the IR code. The objective is to notice the code above (eg. 0xBADA) and if found, sound a tone on a speaker, otherwise ignore it. That way we can still use remotes in the kitchen, and the speaker won't sound.

The code for the receiver is a bit more complex, but not much:

```
#include <IRLib.h>
#include <TonePlayer.h>

const byte SPEAKER = 9;  // output pin is fixed (OC1A)
const byte IR_READER = 11;
const unsigned long BEEP_WIDTH = 50;
const int BEEP_FREQUENCY = 880;  // Hz
const unsigned long DOG_ALERT_CODE = 0xBADA;

// pin D9 (Uno), D11 (Mega)
TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);

IRrecv My_Receiver(IR_READER);
IRdecode My_Decoder;

void setup()
  {
  My_Receiver.enableIRIn(); // Start the receiver
  pinMode (SPEAKER, OUTPUT);
  }

unsigned long lastTone;

void loop()
  {
  if (My_Receiver.GetResults(&My_Decoder))
    {
    My_Decoder.decode();
    if (My_Decoder.decode_type == NEC)
      {
      if (My_Decoder.value == DOG_ALERT_CODE)
        {
        tone1.tone (BEEP_FREQUENCY);
        lastTone = millis ();
        }  // end of wanted code
      }  // end of NEC type
      My_Receiver.resume();
    }  // end of if we got a result

    // if time up, stop the beep
    if (millis () - lastTone >= BEEP_WIDTH)
      tone1.noTone ();

  } // end of loop

```

This also uses the IR library, this time to detect an incoming code. You wire the "Data" pin of the IR detector to digital pin 11 on the Arduino (Uno or similar). The other two pins of the IR detector go to Ground and +5V as marked.

To play a sound get a small piezo speaker and wire that to digital pin 9 (one side) and Ground (other side).

Because of the way that the IR library uses interrupts, I had to use my own Tone library to generate a tone. You can download that from:

http://www.gammon.com.au/Arduino/TonePlayer.zip

---

## Testing

How well did it work? Certainly at short distances (like three feet or one metre) we got a positive result. There could be variance based on the light conditions in the room, and the exact parts you get.

You might want to read the design notes for TV B Gone where they discuss the technicalities of sending IR beams. In particular for their design they used **four** IR LEDs to give adequate range. You could add more LEDs by duplicating the transistor driver shown above a few times. In other words, duplicate the transistors, LEDs and resistors. They could all be driven from the same output pin.

As mentioned in the TV B Gone article, you can get different IR LEDs. Some have a narrow beam, but go further, others have a wider beam, but go less far.

Also you could arrange them to point in slightly different directions to cover more of the room.

You could also change the length of the beep when the code is detected (BEEP\_WIDTH) in milliseconds. And also the frequency (BEEP\_FREQUENCY) which I had at 880 Hz. A higher frequency might annoy the dog more but be less audible to humans. I suppose it depends if you want the dog to hear it or the people in the house.

---

## Hardware size and power

You probably want a small Arduino (like a Nano) which is physically quite small. Also powering it could be an issue. You could get 3 x AA batteries, which would nominally output around 4.5V, and connect them directly to the +5V pin of the Arduino.

To save battery power you could have the Arduino sleep for (say) a second, wake and eheck for a code, and then sleep again. See my post about power savings for more details about that sort of thing.

---

## Hardware photos

---
Tags: arduino-uno, programming, gps, java, buzzer
---


title: Why was the Due retired?

text:
# Question
Title: Why was the Due retired?
Looking at the Sparkfun comparison, it seems that the Due is by far the fastest of the Arduinos and has I/O capabilities similar to the Mega. So why was it retired with no obvious successor?

# Answer
"Why was the Due retired?" - It is quite interesting that Arduino.CC never explained that. One would think, that a professional company or organisation places a notice in advance with at least a short explanation as to why.

Most of the Arduinos, that have been available on both projects (CC and ORG) have suddenly and without further notice or explanation been retired on CC (the exceptions being Uno and Mega 2560, the cash-cows), but are still alive on ORG. It would seem, that either the "divorce" is proceeding or that the copyright case at the US court is not going as smoothly as Banzi hoped. Well, he could repeatedly "bend the truth" by claiming Arduino being completely his idea and design in front of the press (that never bothered to check the obvious facts), but laying such a claim at court is borderline criminal. (see also: arduinohistory.github.io and make your own opinion) CC has still the biggest chunk of the overall community and also serves as the central nexus for developers. But it seems there is a lot of movement... some people move to Wiring (from which the Arduino IDE was forked), others to 3rd Party sites and yet others try out different and newly emerging products (eg. Adafruits MCUs and Pi or the Renesas GR series). ORG on the other hand seems to become the bigger (Arduino branded) hardware supplier and developer. CC has apparently out-sourced this to Intel and tries to live of royalties and "certification" fees (which is the central point where Banzi and Martino started to heavily and openly disagree).

"Why was the Due retired?" - Unless CC doesn't give an explanation, there is no real answer. A lack of interest is certainly not the reason.
> 3 votes

# Answer
Because, basically (in my opinion, anyway) it was rubbish.

Yes, it has grunt. Yes, it has IO, but the chips themselves are pretty rancid.

There are far better options than the SAM3X from other manufacturers.

Also, since all the in-fighting began between the two Arduino factions (.org / .cc) the majority of actual progress and innovation has been by third parties (Intel mostly).
> 1 votes

---
Tags: arduino-due
---


# Question
Title: How to get data from 9DOF razor IMU directly to arduino mega
My final project goal is to make Brushless gimbal for drones using only Arduino MEGA 2560 and 9DOF IMU for control. On Instructables I found two excellent tutorials. Both are different than mine in selected components.

I use the following components:

Arduino MEGA2560

Motors - Quanum 2208 Precision Brushless Gimbal Motor ( httpx://goo.gl/RDBvJL)

Motor Driver - H bridge L298n (httpx://goo.gl/A4ZQi5)

9DOF Razor IMU (httpx://goo.gl/myg9oj )

I'm stuck with 9DOF Razor IMU. Surfing on the internet I found a great tutorial and github repository (httpx://goo.gl/jh2pfU). This tutorial is excellent and AHRS works great with the FTDI Basic Breakout 3.3V. They gave me a good starting point, but my goal is use only Arduino MEGA2560 and sensors.

I want to connect the Arduino and 9DOF IMU directly and use the accelerometer data (Yaw, Pitch, Roll) for directly control the engines. On the website of the manufacturer Sparkfun (httpx://goo.gl/myg9oj ) I can’t find any datasheet exclusively for 9DOF IMU that could help me to connect Arduino and IMU. There are only datasheet of sensors that are on IMU ( ITG-3200 (MEMS triple-axis gyro), ADXL345 (triple-axis accelerometer), and HMC5883L (triple-axis magnetometer) which are useless for me.

That's why I decided to use code from this site ( httpx://goo.gl/zOnYjN ) and he works great. I connected everything as is in tutorial and Arduino SerialMonitor show me the desired values YPR. Values load very quickly directly from IMU and printed on SerialMonitor.

Values on SerialMonitor looks like this:

# YPR=72.13,1.74,-16.38

# YPR=72.14,1.72,-16.39

# YPR=72.12,1.71,-16.39

# YPR=72.13,1.71,-16.37

# YPR=72.13,1.70,-16.40 …

**HELP ME**

This is my first solo Arduino project and I have a lot of questions about it. How could I parse the data that appears on SerialMonitor to get new variables eg. Yaw = 72.12, Pitch = 1.74, Roll = -16.39?

Is it possible to do that?

Does anyone have any experience with 9DOF razor IMU and maybe know better way to collect information from the accelerometer 9DOF razor IMU?

I want to achieve three separate variables which i will use to control the brushless motor. I think this should be an easier method as it is just comma separated numbers but then again i am new to arduino serial communication so i would appreciate any help with this. Even if it's only how to parse and extract the values.

# Answer
sscanf should be enough. There is also other options, String class for example with substring method.

Take a look at the example:

```
#include <stdio.h>

char myString[] = "#YPR=72.13,1.74,-16.38";

void setup() {
  // put your setup code here, to run once:
  float yaw = 0;
  float pitch = 0;
  float roll = 0;

  sscanf(myString, "#YPR=%f,%f,%f", &yaw, &pitch, &roll);
  Serial.println(yaw);
  Serial.println(pitch);
  Serial.println(roll);
}

void loop() {

}

```
> 2 votes

---
Tags: arduino-mega
---


title: Reading a .csv file element wise

text:
# Question
Title: Reading a .csv file element wise
I'm fairly new to arduino programming and C/C++. I would like to read a .csv file element wise, and send each element via. a nRF24L01 tranceiver to a raspberry pi. Right now I'm able to read the .csv file with `Serial.write(<file>.read())`. I was wondering if there's a way to read each element one at a time, if so how would i do that?

My thoughts (Pseudo code-ish):

```
loop through every element in .csv file {
    save the current element to X.
    send X to raspberry pi (I already have a function for sending)
}

```

I hope someone can help. Thanks in advance.

# Answer
The `read()` method works character-wise, not element-wise. Then you have to rethink your algorithm to loop over characters:

* store each character in a buffer
* send the whole buffer (i.e. a single element) when you see a delimiter

Example:

```
const size_t BUFFER_SZ = ...;
char buffer[BUFFER_SZ];
size_t pos = 0;    // current write position in buffer
int c;

// While we can read a character:
while ((c = <file>.read()) != -1) {

    // If we get a delimiter, then we have a complete element.
    if (c == ',' || c == '\n') {
        buffer[pos] = '\0';         // terminate the string
        raspberry.println(buffer);  // send to the RPi
        pos = 0;                    // ready for next element
    }

    // Otherwise, store the character in the buffer.
    else if (pos < BUFFER_SZ-1) {
        buffer[pos++] = c;
    }
}

```

Here the buffer is sent as a string. If you want to parse it into a number, you can use `sscanf`.

This code assumes Unix text-file conventions, i.e. each line of the file (including the last one) being terminated by an LF character. You may have to adapt if your file is different.
> 3 votes

---
Tags: arduino-uno, c++, c, nrf24l01+
---


# Question
Title: how to implement PWM LED fading into a random case switch?
Ive recently bought my self a arduino Mega 2560 and managed to get a sort of RANDOM function to work with different cases which go of by the number selected. My question is is there a way to also make a PWM sequence in such a case? so that the LED is fully light to dark and then the the next case starts? IS there a more random sequence wich i could then also expand if neccesary?

Mark.

```
int ledcolor = 0;
 int a = 500; //this sets how long the stays one color for
int b = 2000;
int brightness = 255;    // how bright the LED is
int fadeAmount = 25;    // how many points to fade the LED by

 void setup() { //this sets the output pins

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

 void loop() {
 int ledcolor = random(1,16); //this randomly selects a number between 1 and 15

 switch (ledcolor) {

 case 1: //if ledcolor equals 1 then the led on pin 11 will turn on etc.
 analogWrite(11, brightness);
 brightness = brightness - fadeAmount;     break;
 case 2:
 digitalWrite(10, HIGH);
 delay(a);
 digitalWrite(10, LOW);
 break;
 case 3:
 digitalWrite(9, HIGH);
 delay(a);
 digitalWrite(9, LOW);
 break;

```

# Answer
> 1 votes
In order to fade in and fade out LEDs you need to use PWM feature. And, specifically you need to use the analogWrite() function call. Also, you need to make sure all your LEDs are connected to PWM port pins. Port pins which support the PWM feature for various Arduinos are listed in the above link.

In your code you might try replacing your 500ms delay with a count up followed by a count down loop. Each loop should contain the appropriate delay and count up or down to the appropriate value.

For instance, you might try a 1ms delay and a count from 0 to 255 followed by a count from 255 to 0. In both loops just before or just after calling the delay() function, place the call to the analogWrite() function and pass the counter value as the PWM duty cycle (LED brightness setting).

added later...

For example, you might try to see if this code works for the 1st case statement:

```
int brightness_level;

case 1: //if ledcolor equals 1 then the led on pin 11 will turn on etc.
  for(brightness_level = 0 ; brightness_level < 255 ; brightness_level++)
  {
    analogWrite(11, brightness_level);
    delay(1);
  }
  for(brightness_level = 255 ; brightness_level >= 0 ; brightness_level--)
  {
    analogWrite(11, brightness_level);
    delay(1);
  }
break;

```

# Answer
> 0 votes
To make a completely "non blocking" system you need to change your thinking somewhat. Instead of thinking "A need to fade from X to Y" you instead need to start thinking "I am at brightness X at the moment. I want to get to brightness Y. What do I need to do to get there?".

For instance, you might have a `loop()` than contains a structure like:

* My target brightness is Y
* My current brightness is X
* Is X equal to Y?
    + Yes:
        - Select a different target brightness to get to
    + No:
        - If my current brightness is below my target brightness then make it brighter.
        - Otherwise make it dimmer.

You can introduce a small delay to slow the fading down, or use `millis()` to only run that structure at pre-defined intervals (like BlinkWithoutDelay does) to get your desired fade speed.

---
Tags: arduino-mega, led, pwm
---


# Question
Title: Gas Sensors with Arduino + Interfacing Circuit
I am intended to use Gas Sensors (MQ series) on protoboard so I connect it to Arduino and perform analogue read. I would like to request if possible to get the interfacing circuit (resistors, amplification.. etc.) or if there are schematics available.

Also, when I read the data digitized into 10bits ADC value, how can I convert it into units (ppm)?

Thank you so much in advance.

# Answer
I would suggest checking out one of the gas sensors that comes with a breakout board. I've found the pins don't quite match the spacing of a protoboard and make it a little difficult to set up. Seeed Studio sells some of the sensors with a breakout board and has some nice examples of how to convert the values to PPM.

http://www.seeedstudio.com/wiki/Grove\_-\_Gas\_Sensor(MQ5)
> 0 votes

# Answer
You can connect the directly to the Arduino +5, Gnd and Signal.

I don't know of any calibration data for the sensors that I have. I suppose you could take the maximum concentration the sensor can measure and divide this by 1024, but I don't know if the value returned is linear or logarithmic.
The data sheet does have some info on, but this page may be more helpful http://forum.arduino.cc/index.php?topic=230945.0

Oh and don't forget the warm up time on the sensors!
> 0 votes

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


title: I need more memory!

text:
# Question
Title: I need more memory!
I am trying to make a RBB Arduino based project and I only need 3 pins. In the future I may use one to two more. I wanted to use an ATtiny85 however my code is 13,270 bytes and it would not fit. So I decided to use an ATtiny84 but it also would not fit, it will fit on an ATmega328p but I do not want to use one because i want to keep the project relatively small and I for sure do not need that many pins. Does anyone know of a chip that has a lot of memory but not many pins, or some other solution. Thank you, any help is appreciated.

# Answer
> 1 votes
AFAIK, 8 KiB of flash is the most you can have on an AVR in a DIP package with less than 28 pins. If you do not mind soldering surface-mount parts, the 328P is available in TQFP and VQFN packages, significantly smaller than the DIP version.

Otherwise you could try to optimize your program to fit in 8 KiB. The Arduino libraries are often inefficient size-wise, and in many instances you can save quite a lot by rewriting the parts that you need on top of just avr-libc. Note that this libc is always linked to your program by the Arduino IDE.

# Answer
> 0 votes
There are a few ways to optimize your code and reduce the size. Have a look on this document from Atmel. I've used some tips to reduce the size of my bootloader once.

http://www.atmel.com/images/doc8453.pdf

For the AVR family I'm not familiar with any option. You could use a small QFN package for the atmega328p as well... You might find some small ARM with much more memory and small size.

---
Tags: memory-usage
---


# Question
Title: Is it possible to control a 12v led matrix with an arduino?
This is a bit home automation but if I want to control my 12v LEDs and I have 8 free pins would it be possible to drive 16 lights as a matrix. I was looking into running 8 LEDs with an 8 channel relay but the I got to thinking if I wire up 16 LEDs in a matrix I could still control them all with those 8 channels. Problem is I was looking at mechanical relays that would burn out very quickly with that kind of switching. Are there any other solutions?

# Answer
You can use ULN2803 driver IC on sink side (cathode), P channel MOSFET on anode/source side of common anode LED matrix. Since you need only 4 sinks you can pair every 2 i/o of ULN2803 so you can drive/sink 1A max load per row. This IC is cheap and widely available.

MOSFET current and speed should match those of ULN2803. You can use BJT instead of MOSFET, but voltage drop on BJT will be higher.

Similar design is here: 8x8 LED matrix
> 1 votes

# Answer
I think the best solution would be to use WS2812 LEDS. I already implemented this many times also for my home illumination. WS2812 is a RGB LED with an integrated chip (1m strip with 60 LED will cost about 10$). One advantage is that you need only 1 output from your Arduino and the library works very well. Another one is that you don't need power! 5mA is enough to drive 1000 LEDS! So you don't need MOSFETS and you don't need any Relais.
> 0 votes

---
Tags: led
---


# Question
Title: how do I power my motor shield without an arduino uno?
I want to power my motor shield without my UNO. I have connected the `+ve` and `-ve` terminals resulting in lighting up of the LED.

Is there any way to control the motors in this arrangement from the Arduino?

# Answer
> 0 votes
Welcome!

I'm not sure I understand what you are asking because what you are trying to do doesn't make much sense.

The motors connected to the motor shield are controlled by the output pins of the Arduino that the motor shield is plugged in to.

You could run jumper leads from an separate Arduino into your unplugged motor shield, but that's just extending what you already have. You really do need some form of controller, not necessary a microprocessor, otherwise how can you go forwards and backwards?

Is the problem you have put the Arduino into a plastic case and you can't plug the motor shield in any more? If so get a set of long male to female connectors (they look like the Arduino connectors) and use them as extensions.

Is the problem you have a different format of board and can't plug it in? If so use the wires method to form the correct connections.

I hope that answers your question, if not please try and explain what I'm misunderstanding.

---
Tags: arduino-uno, motor, arduino-motor-shield, robotics
---


# Question
Title: Row-column scanning to control an 8x8 LED matrix
https://www.arduino.cc/en/Tutorial/RowColumnScanning

This code really confused me because I don't know if the `pixels[x][y]` is HIGH or LOW in `void refreshScreen()`.

As you look at the code, `pixels[x][y]` is HIGH and then LOW in `void setup()`, and then `pixels[x][y]` is HIGH again in `void loop()`. Could anyone explain this to me, please？

# Answer
The pixels array in initialized to all HIGH in `setup()`. Then one element of the pixel array is set to LOW in `readSensors()` which turns on one LED.

The tricky bit is you have to remember to turn off the previous LED. That is why in `readSensors()` there is the line where an element of pixels is set HIGH while the pixels' array pointers are still pointing at the former (already lit) LED.
> 2 votes

---
Tags: arduino-uno, led-matrix
---


title: How to remove SD card safely

text:
# Question
Title: How to remove SD card safely
I’m constructing an arduino based sytem that uses a SD card and I’m looking for a way to safely remove the card from the system during operation. One way would probably be to turn of the arduino before removal of the SD card, but that is not acceptable in this context.

The library I’m using: https://www.arduino.cc/en/Reference/SD

Is it possible to safely remove the SD card during operation? If no, how can I minimize the risk of damage to the SD card while inserting and removing it?

# Answer
> 2 votes
The physical construction of the card and socket are designed such that power to the card is cycled properly when the card is inserted and removed. The only thing the firmware has to do is to stop writing to the card before it is removed.

Unexpected removal can cause a problem in "larger" systems (e.g. cellphones or PCs) because they may have structures open on the card that are not yet complete, but small embedded systems typically do not have the capability to do so and so once all writes are completed the card can be removed.

Detection of non-presence of a card is another issue though, and the firmware will have to be designed to not fail in such a situation.

# Answer
> 2 votes
In my early days of computing, the computer used to turn on a led when writing to cassette tape or floppy disk. If you wanted to remove the tape or disk, you had to wait for the led to turn off. I think that could be your easiest solution.

# Answer
> 0 votes
An SDCard is very much like a hard disk drive. Both in how it is made and how it is treated by the host. As such there are critical times where interrupting the communication to the SDCard can cause corruption.

To avoid problems it is advisable to finish all transaction before removing the SDCard. In a perfect situation all data will be flushed from the host's buffers (cache) and the files being accessed closed. So research the flush() and the close() function calls in the library you are using.

In order to accomplish the above, it is obvious the host device needs to be told the SDCard is about to be removed. In most cases this is accomplished using a switch (human interface) and some code to flush and close any open files.

All this said, often people pull SDCards with out any obvious problems. This is likely because SDCard transactions are fast and completed in fractions of a second. Also pulling an SDCard when periodically reading a file is far safer then when writing to a file or altering any information on the SDCard (for example the name of a file). If you can suffer the possibility of corruption, it may be that the added effort is not worth it. However if you stand lose a great deal, I would advise you to do some research into the best ways to avoid SDCard corruption.

---
Tags: sd-card, adafruit, safety, memory
---


title: I2C multi sensors reading on Arduino

text:
# Question
Title: I2C multi sensors reading on Arduino
I have several sensors (Grove multichannel gas sensor, Air Pressure Sensor MPX4115A, Temperature and Humidity Sensor DHT11) where most of them uses I2C communication. I wonder if it is possible to read all of them using the I2C communication on a single Arduino board?

# Answer
It is possible to use multiple I²C devices, all is needed is for each one to have a different address and the ability to set up the wiring(the other answer points to wriring info).

Of the sensors you listed only one is an I2C device(Grove sensor).

The DHT11 uses a single digital wire to communicate and the air pressure sensor is an analog device. Although you do mention having several devices, the only thing you need to be sure of is if there are no address conflicts, i.e. there being two devices with the same address on the I²C bus.

If address conflicts are an issue most devices provide a way of changing that address, often there are solder jumpers on the board. This allows you to change a devices address to a unique one.
> 0 votes

# Answer
Should be easy enough. Do you already know how to connect and communicate with one I2C device? If so, connecting multiple should be simply a case of connecting them in parallel.

If you don't know how to communicate with a single I2C device, then...

For the Arduino software you can use Wire to talk to devices over I2C.

For the hardware, connect the I2C clock and data lines from the Arduino to the I2C devices. More on that here.
> 0 votes

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