# Question
Title: How to get my water pump to turn off and on with the moisture level?
I am trying to built an automatic plant watering system with my arduino. I have an LCD display screen that outputs the moisture level, a moisture sensor and a water pump with a relay. I have been trying to get the water pump to read the moisture data and if it reads lower that 60 to turn on the pump for 10 seconds and then turn the pump off until it reads the moisture again to see if it needs more water. However I am unable to get my water pump to turn off. Is it not reading the moisture sensor?

```
String writeAPIKey = "dCFFuwutXLRoHKQNqbIXrP";  //Put your ThingSpeak Write API key here.
unsigned int interval = 60000;  //Update every Minute
long int now=0, previous=-50000; //Used to hold time variables.
#define DST_IP "maker.ifttt.com"  //Thingspeak Server

//LCD display
//Load libraries
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

 //Define address for the Serial LCD display.
#define I2C_ADDR  0x27  //If 0x3f doesn't work change this to 0x27
#define BACKLIGHT_PIN  3

//Initialise the Serial LCD.
LiquidCrystal_I2C lcd(I2C_ADDR, 2,1,0,4,5,6,7); //These pin numbers are hard coded in on the serial backpack board.

// Moisture sensor
int moistureSensor = A3; // moisture sensor is plugged into A3 on the arduino
int data; // Used to store data from user
int waitTime = 1000;

// water pump
int pumpPin = 8; // water pump
int waterTime = 10; // 10 seconds watering time

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

// LCD display
lcd.begin (16,2);     //Initalize the LCD.
lcd.setBacklightPin(3,POSITIVE);//Setup the backlight.
lcd.setBacklight(HIGH); //Switch on the backlight.
lcd.clear();
lcd.setCursor(0,0);   //go to first column  and first line (0,0)
lcd.print("Hello - Arnold");     //Print at cursor Location
lcd.setCursor(5,1);   //goto first column and second line
delay(1000);

// pump
pinMode(pumpPin, OUTPUT);

 // Wifi
  Serial.begin(9600);  // Open serial Connection to Computer
  Serial1.begin(115200);  // Open serial Connection to ESP8266
  Serial.println("IFTTT Maker");
  Serial1.println("AT+RST");  //Issue Reset Command
  Serial.println("AT+RST");
  delay(1000);

  //DEBUG LOOP- display ESP output to serial Monitor.
  while (Serial1.available()) {
  Serial.println(Serial1.read());
  }
  Serial.println("AT+CWMODE=1");
  Serial1.println("AT+CWMODE=1");  //Set single client mode.
  delay(5000);

  Serial.println("AT+CIFSR");
  Serial1.println("AT+CIFSR"); //Display IP Information

  //DEBUG LOOP- display ESP output to serial Monitor.
  while (Serial1.available()) {
  Serial.println(Serial1.read());
  }
  delay(1000);

  Serial.println("AT+CIPMUX=0");
  Serial1.println("AT+CIPMUX=0");  //Sets up Single connection mode.
  delay(1000);

  //DEBUG LOOP- display ESP output to serial Monitor.
  while (Serial1.available()) {
    Serial.write(Serial1.read());
  }
  delay(1000);

}
void loop() { // put your main code here, to run repeatedly:

    // Moisture
    delay(waitTime);
    data = analogRead(moistureSensor);
    data = map(data, 0, 1023, 0, 100);
    Serial.println(data);

    // LCD
    for(int count = 0; count < 15; count++) {
    lcd.clear();
    lcd.setCursor(7,0);
    lcd.print(data);
    delay(500);
      }

    // pumpPin
    if (moistureSensor <= 60) {
    digitalWrite(pumpPin, HIGH);
    delay(waterTime*1000); // on for 10 seconds
    digitalWrite(pumpPin, LOW);
    delay(waitTime);

    } else if (moistureSensor >=65) {
        digitalWrite(pumpPin, LOW);
        delay(waitTime);

    }

// IFTTT
  now=millis(); //Get the current time.
//Check to see if it's time to run.
if(now - previous >= interval){
  previous = now;
  Serial.println("Running Update");
  updateThingSpeak();
   }
}

void updateThingSpeak(){

  int moisture = analogRead(moistureSensor); //Read the moisture

   //Builds the connection string for the ESP8266
    String cmd = "AT+CIPSTART=\"TCP\",\"";
    cmd += DST_IP;
    cmd += "\",80";
    Serial1.println(cmd);  //Run the command
    Serial.println(cmd);    //Print this to the debug window
    delay(1000);

    //DEBUG LOOP- display ESP output to serial Monitor.
    while (Serial1.available()) {
    Serial.write(Serial1.read());
    }

   //I NEED TO UPDATE THIS IF STATEMENT TO MAKE SURE CONNECTION WORKED
  //if (client.connect(thingSpeakAddress, 80)){
    String httpcmd="GET/trigger/arnold_the_plant/with/key/dCFFuwutXLRoHKQNqbIXrP?";
    httpcmd += "value1=";
    httpcmd += moisture;
    httpcmd += " HTTP/1.1\r\n";
    httpcmd += "Host: maker.ifttt.com\n";
    httpcmd += "Connection: close\r\n\r\n";

    Serial.print("AT+CIPSEND=");
    Serial.println(httpcmd.length());

    Serial1.print("AT+CIPSEND=");
    Serial1.println(httpcmd.length());
    delay(1000);

    Serial.print(">");
    Serial1.println(httpcmd);
    Serial.println(httpcmd);
    delay(3000);

    //DEBUG LOOP- display ESP output to serial Monitor.
     while (Serial1.available()) {
      Serial.write(Serial1.read());
      }

    Serial.println("AT+CIPCLOSE");
    Serial1.println("AT+CIPCLOSE"); //Close the Web Connection

   } // end of void loop

```

# Answer
> 1 votes
Invert logical level on the pin that controls water pump.

```
// pumpPin
if (moistureSensor <= 60)
 { digitalWrite(pumpPin, LOW );
 delay(waterTime*1000);
 // on for 10 seconds
 digitalWrite(pumpPin, HIGH);
 delay(waitTime); }
else if (moistureSensor >=65)
 { digitalWrite(pumpPin, HIGH);
 delay(waitTime); }

```

---
Tags: programming
---


# Question
Title: Arduino IDE compiling for non-arduino AVR boards
Using:

I was able to run my code successfully by modifying the file

`[ardunoIDE]\hardware\arduino\avr\variants\standard\pins_arduino.h`

building and then flashing the MCU with `avrdude`.

Is there any way to have Arduino IDE build system pick its `pins_arduino.h` file from somewhere else ?

# Answer
> 1 votes
Yes, MiniCore is a self-contained hardware package. After installing MiniCore select one of the MiniCore boards in the Arduino IDE's **Tools \> Board** menu and the Arduino IDE will automatically use the pins\_arduino.h file included with MiniCore. There is no need to modify any file in the Arduino IDE folder or any other folder.

---
Tags: arduino-ide, pins, avr, port-mapping
---


# Question
Title: Function is executing when I try to store it in an array
I am trying to store a set of functions with different parameter in an array. When the code enters the function `songlearn` with `tune==1` I want the functions with set parameters to be stored in the array without executing. What am I doing wrong? Here's my code:

```
const int x=100;
int (*SongSeq[x])();
int note[x];
int playNote(int midi, int row, int col, int len, bool short_led = false);
void songlearn(int tune);
int tune;

void songlearn (int tune){
  if (tune==1){
    state=1;
   lcd.clear();
  lcd.setCursor(4,0);
  lcd.print("Learning Song :");// Print a message to the LCD.
  lcd.setCursor(1, 1);
  lcd.print(menuP1);
// if (songpage==1){
// if (BackState==HIGH){//leaving song
//     posP=0;
//     Page=2;
//    Play(posP);
//    }
// }
  //Plays Mary Had a Little Lamb on a loop at 145 BPM
//Bar 1
SongSeq[0]= playNote(0x40, 3, 1, 414); //Quarter note: E
note[0]=0x40;
SongSeq[1]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[1]=0x3e;
SongSeq[2]=playNote(0x3c, 2, 2, 414); //Quarter note: C
note[2]=0x3c;
SongSeq[3]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[3]=0x3e;
//Bar 2
SongSeq[4]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[4]=0x40;
SongSeq[5]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[5]=0x40;
SongSeq[6]=playNote(0x40, 3, 1, 828,1); //Half note: E
note[6]=0x40;
//Bar 3
SongSeq[7]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[7]=0x3e;
SongSeq[8]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[8]=0x3e;
SongSeq[9]=playNote(0x3e, 2, 4, 828,1); //Half note: D
note[9]=0x3e;
//Bar 4
SongSeq[10]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[10]=0x40;
SongSeq[11]=playNote(0x43, 3, 4, 414,1); //Quarter note: G
note[11]=0x43;
SongSeq[12]=playNote(0x43, 3, 4, 828,1); //Half note: G
note[12]=0x43;
//Bar 5
SongSeq[13]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[13]=0x40;
SongSeq[14]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[14]=0x3e;
SongSeq[15]=playNote(0x3c, 2, 2, 414); //Quarter note: C
note[15]=0x3c;
SongSeq[16]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[16]=0x3e;
//Bar 6
SongSeq[17]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[17]=0x40;
SongSeq[18]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[18]=0x40;
SongSeq[19]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[19]=0x40;
SongSeq[20]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[20]=0x40;
//Bar 7
SongSeq[21]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[21]=0x3e;
SongSeq[22]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[22]=0x3e;
SongSeq[23]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[23]=0x40;
SongSeq[24]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[24]=0x3e;
//Bar 8
SongSeq[25]=playNote(0x3c, 2, 2, 1656); //Whole note: C
note[25]=0x3c;

//End song
  }
 }
 int playNote(int midi, int row, int col, int len, bool short_led = false)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOff(0x90, midi, 0);
}

```

# Answer
What you have done will certainly call the function. Since it is always the same function, just store the *arguments* into an array. Something like this:

```
const int COUNT = 100;

struct
  {
  int midi;
  int row;
  int col; int len;
  bool short_led;
  } notes [COUNT] = {
  { 0x40, 3, 1, 414 },  //Quarter note: E
  { 0x3e, 2, 4, 414 },  //Quarter note: D
  { 0x3c, 2, 2, 414 },  //Quarter note: C

  // and so on
  };

int playNote(int midi, int row, int col, int len, bool short_led = false);

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

void loop()
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (notes [i].midi)
      playNote (notes [i].midi, notes [i].row, notes [i].col,
                notes [i].len, notes [i].short_led);
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOff(0x90, midi, 0);
}

```

---

> yeah but i want to be able to store the function in an array with the set parameters

Do you? I wonder why.

Anyway, you can do that by making an array of lambda functions like this:

```
const int COUNT = 100;

int playNote(int midi, int row, int col, int len, bool short_led = false);

void (*SongSeq[COUNT])() =
 {
 [] { playNote(0x40, 3, 1, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,
 [] { playNote(0x3c, 2, 2, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,

 // ... and so on

 };

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

void loop()
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (SongSeq [i])
      SongSeq [i] ();
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
  Serial.print ("Playing note ");
  Serial.println (midi);
  delay (100);
}

```
> 2 votes

# Answer
Calling or entering a function *means* executing it -- that is just how the language is defined. A 'function' is not a construct you can manage, i.e., store or otherwise mess-with (technical term!) in the ways you might do with other kinds of data. But:

You *can* store a function's address (i.e., a pointer to the function) and use the pointer to call the function, and you can store its parameters just as you would store any data. So, if I understand correctly what you want to do, try something like this crude outline based on my quick read of your code. It uses stored function pointers and song-numbers and shows how to call one of those functions with the associated, stored song number as a parameter:

```
// Ptr to a function and a song number
typedef struct {
   void (*pfunc)(int tune);
   int tuneNum;
} SONG_T;

#define COUNT 12

void songlearn(int);
void othersongfunc(int);
// void moresongfunctions(int);
// void moresongfunctions(int);

// Table of songs & functions:
SONG_T Songs[COUNT] = {
   {songlearn, 2},
   {othersongfunc, 1},
   {songlearn, 7},
   {othersongfunc, 3},
   // etc
};

void songlearn(int)
{
    ;   // does whatever it does
}

void othersongfunc(int)
{
    ;   // does whatever it does
}

void somefunc(uint8_t whichSong)
{
   if( whichSong < COUNT )
      (*Songs[whichSong].pfunc)(Songs[whichSong].tuneNum);
}

void setup(void)
{
   somefunc(3);
}

void loop(void)
{
   ;
}

```
> 1 votes

---
Tags: arduino-mega, programming, array
---


# Question
Title: Multiple 3-wire SPI sensor interfacing with Arduino
I want to connect 4 MAX6675 thermocouple to Arduino. MAX 6675 description.

It comes with its own Arduino library. library link.

I tested the example code for one sensor and it works perfectly. Now I want to connect all the four sensors to Arduino using minimum GPIO pins possible.

I connected - (for 2 sensors only for initial testing):

```
D7 -> clk (slave 1) ->clk (slave 2)
D3 -> so (slave 1) ->so (slave 2)
D4 -> cs (slave 1)
D5 -> cs (slave 2)

```

My code (I modified the original example code a bit):

```
// this example is public domain. enjoy!
// www.ladyada.net/learn/sensors/thermocouple

#include "max6675.h"

int thermoCLK = 7;
int thermoDO = 3;
int thermoCS = 4;
int thermoCS2 = 5;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
MAX6675 thermocouple2(thermoCLK, thermoCS2, thermoDO);

void setup() {
  Serial.begin(9600);
  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
  Serial.print("C = ");
  Serial.println(thermocouple.readCelsius());
  Serial.print("F = ");
  Serial.println(thermocouple.readFahrenheit());
  Serial.print("C 2= ");
  Serial.println(thermocouple2.readCelsius());
  Serial.print("F 2= ");
  Serial.println(thermocouple2.readFahrenheit());
  delay(1000);
}

```

I am able to read only one sensor information correctly. The other output is *nan*. Am I wiring the circuit wrong or is my code incorrect or both?

# Answer
First off ditch that library. It's completely pointless and actually makes things harder.

Secondly connect your sensors to the SPI pins, selecting a new CS pin for each sensor.

* Arduino SCK (pin 13) to all the SCK pins.
* Arduino MISO (pin 12) to all the SO pins.
* Individual GPIO pins to individual CS pins (use pin 10 for one of them).

Then just use a simple function to read the data using the SPI library (adapted from the library you link to). For instance with CS on 10 an 9:

```
#include <SPI.h>

double readCelsius(uint8_t cs) {
    uint16_t v;

    digitalWrite(cs, LOW);
    v = SPI.transfer(0x00);
    v <<= 8;
    v |= SPI.transfer(0x00);
    digitalWrite(cs, HIGH);

    if (v & 0x4) {
        // uh oh, no thermocouple attached!
        return NAN;
    }

    v >>= 3;

    return v*0.25;
}

void setup() {
    SPI.begin();
    pinMode(10, OUTPUT);
    pinMode(9, OUTPUT);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);

    Serial.begin(115200);
}

void loop() {
    Serial.print(readCelsius(10));
    Serial.print(" ");
    Serial.println(readCelsius(9));
    delay(1000);
}

```
> 2 votes

---
Tags: sensors, spi
---


title: Char Array Buffers String UINT8

text:
# Question
Title: Char Array Buffers String UINT8
So, I have an ATTiny85 sending data, awesome. I would like to have it send a message that consists of a few concatenated parts.

I have been reading about strings, buffers, chars, toCharArray and more for about 6 hours now and am completely puzzled by this.

Below, the variable `deze` will no transmit, but `msg` will. So I tried to do something like `char *deze = "hello" + "world";` but that also fails.

What would be the best way to construct a piece of data that will be send by my 433MHz transmitter. I need to combine INT, String and float before sending it as uint8\_t (bytes?).

```
#include <RH_ASK.h>

#define R_PIN PB4
#define T_PIN PB1
#define L_PIN PB3

RH_ASK driver(2000, R_PIN, T_PIN);

void setup()
{
  if (!driver.init()){
    pinMode(L_PIN, OUTPUT);
    digitalWrite(L_PIN, HIGH);
    delay(500);
    digitalWrite(L_PIN, LOW);
    delay(500);
  }
}

void loop()
{
  char deze[5];
  char *msg = "gewonechar";

  String thijs = "thijs";
  thijs.toCharArray(deze, sizeof(deze)-1);

  driver.send((uint8_t *)deze, strlen(msg));
  driver.waitPacketSent();
  delay(200);
}

```

**\[edit\]**
This is the working code on the receiver side.

```
struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) {

      memcpy(&myData, buf, buflen);

      Serial.print("ID: ");
      Serial.println(myData.id);

      Serial.print("Pin: ");
      Serial.println(myData.pin);

      Serial.print("Value1: ");
      Serial.println(myData.value1);

      Serial.print("Value2: ");
      Serial.println(myData.value2);

      Serial.println("");
    }
    server.handleClient();
    yield;
}

```

And the transmitter

```
#include <RH_ASK.h>

#define BAUD 2000
#define RX 11
#define TX 12

RH_ASK driver(BAUD, RX, TX);

struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

void setup() {
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    struct data myData;

    myData.id = 1001;
    myData.pin = 4;
    myData.value1 = analogRead(4);
    myData.value2 = analogRead(5);

    driver.send((uint8_t *)&myData, sizeof(myData));
    driver.waitPacketSent();
    delay(2000);
}

```

Library used: http://www.airspayce.com/mikem/arduino/RadioHead/

# Answer
> 2 votes
First off you never want to use `String` \- especially on a chip with a mere 512 bytes of SRAM.

You should really be learning about `struct` for sending of data in the most efficient way. A `struct` is a complex data type that combines multiple bits of data into one single variable - a bit like a record in a database.

You should avoid sending text as it is generally wasteful. The odd character, yes, but not whole strings of text.

For instance, you might want to send temperature, humidity and pressure:

```
struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
};

void sendData() {
    struct data myPacket;

    myPacket.temperature = 23;
    myPacket.humidity = 72;
    myPacket.pressure = 1016;

    driver.send((uint8_t *)&myPacket, sizeof(myPacket));
    driver.waitPacketSent();
}

```

With a `struct`, if you want to send text, you need to allocate enough space in the struct for your text. For instance, enough room for 9 characters plus NULL:

```
struct data {
    int8_t temperature;
    uint8_t humidity;
    uint16_t pressure;
    char weather[10];
};

```

Then, to get data into it, you (for example):

```
strcpy_P(myData.weather, (PGM_P)F("fog"));

```

---
Tags: string
---


# Question
Title: How to read CPU temperature into Arduino?
I'm not sure about this and if it is possible. I need to read CPU (normal computer) into an Arduino. This could be possible (at least I think) by connecting some kind of sensor that can be placed between the heatsink and the CPU, where the thermal paste is placed. Or, the second option is to read values from the system somehow, or from the motherboard. I hope I'm not talking about stupid things. I need some advice about this.

# Answer
> 1 votes
Here is a simple way to send CPU temperature reading data via serial port, under Windows.

As answered in the question Batch-file get CPU temperature in °C and set as variable, it is possible to build batch file (\*.BAT) to get the readings and output to console. I took following option and built the BAT file.

```
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature

```

Now, to redirect the console to serial port, use `>` symbol. Try following and receive it in your Arduino or use serial port monitor to check (in my case it works):

```
mybatfile.bat > COM1

```

Alternatively, you can use

```
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

```

inside your BAT file.

Next, we have to specify the serial configuration, make it EXE file so it can run under Administrative account. I used Advanced BAT to EXE converter. In the tool, specify the commands:

```
@echo off
mode COM1 BAUD=38400 PARITY=n DATA=8
wmic /namespace:\\root\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature > COM1

```

Convert it to EXE using File-\>Build EXE...

And finally, you can create Scheduled Task to run your newly built EXE application periodically.

BTW, WMI is a powerful interface, it is possible to retrieve many other metrics and configuration data.

---
Tags: arduino-uno, temperature-sensor
---


# Question
Title: Need to set an output pin without it going LOW during initalization
For a control system I am using a relay module that controls a larger relay for high-current electrical stuff, as part of a battery protection circuit for my solar plant. This module switches 120 VAC for the larger one. The larger one is set up to latch the power off until a button is pressed manually.

I have several Adafruit relays, (single, dual, quad) and they all seem to be active-LOW. I am using one of them for this project.

My problem is that I can't seem to prevent my Arduino Nano code from briefly setting the output pin LOW in setup, setting in motion the cascade involving latching the power off.

If at all possible with this hardware, I would like to prevent the need to manually reset the latch when uploading code changes.

Here is how I am initializing that pin in my setup code:

```
pinMode(12,OUTPUT); digitalWrite(12,HIGH);

```

All in one line. The LOW pulse is just long enough to trigger the other relay.

I know I can probably find parts like an inverter chip or maybe a different relay, but really want this working yesterday.

So my question is: Is there any way to prevent it from pulling it LOW during initialization? Or, is there a different approach I should take in relation to this relay output?

Thanks in advance

# Answer
> 3 votes
Arduino sketches are actually (somewhat constrained) C programs. As such, what is true for C is usually true for sketches. In C, a segment of code usually ends with a ";". It matters not if there are two (or more) of these on a single line. The computer will execute the segment before the first ";" first and the segment after the first ";" second.

In this case you are setting a register inside the Atmel processor on the Nano to the "out" direction. So it will force the associated pin to what ever the data in already set up in that pin's data register. Then you are setting that pin's data register to high or 1.

Instead, try setting the data register to 1 before setting the direction register to "out". Do this by switching the order of the code segments.

In case this does not work. Or in case you find the relays acting randomly on power up, consider the relay driver inputs to be high impedance and susceptible to any noise prior to the Nano taking control of the relay driver control pins. In such a case, consider adding pull up resistors small enough to ensure the inputs of the relay drivers are held at a known voltage but high enough such that the Atmel processor in the Nano can easily over power the pull up resistor when necessary.

---
Tags: sensors, pins, relay
---


title: No message got sent

text:
# Question
Title: No message got sent
I used this code:

```
void setup() {
  Serial.begin(4800); //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+918281537478\"\r");
  //Number to which you want to send the SMS
  delay(1000);
  Serial.print("Test SMS -Jay\r");
  //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void loop() { }

```

In the serial monitor AT commands were printed but no message was sent. Someone please help.

# Answer
> 1 votes
I have the same code and it's working fine. But in my code, I set my baud rate `9600` means you have to change

```
Serial.begin(4800);

```

to

```
Serial.begin(9600);

```

And few question... which GSM Model you used? GMS SIM 300 or someone else. Becuase mine is GSM SIM 300. If you have someone else then maybe you have received some document with it, in that specific baud rate is defined. Just set it.

And then fist of all, check your GSM board is really working or not? Becuase I have this problem but that time my GSM module is not working. So, I replace and then everything working fine.

Put your SIM CARD on GSM and then make a call. If the buzzer is ringing that mean your GSM board working fine. Be sure about your arduino connection with GSM shield.

I hope this will help you.

# Answer
> 0 votes
Serial.print is designed to print out to the serial (programming) port.

If you are seeing these commands there then that means they are not being sent to the GSM module.

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


title: Switch Statement Alternative

text:
# Question
Title: Switch Statement Alternative
I am working on a project where I've mapped an IR remote control to certain functions. I am currently using a massive switch statement to control the program based on the IR remote button pressed.

Is there a an alternative to using a switch statement, or is a switch the best way to go?

```
decode_results results; // Initialize the results

IRrecv irrecv(irPin); // Initialize the IR sensor

int buttonPressed;

void setup()
{
  Serial.begin(115200);
  Serial.println("Tile Controller");
  analogReference(DEFAULT);
  irrecv.enableIRIn(); // Start the receiver

  Wire.begin(); // Join the I2C network
}

void loop()
{
  if (irrecv.decode(&results))
  {
    if(results.value != buttonHeld)
    {
      buttonPressed = results.value;
      Serial.println(buttonPressed,HEX);
    }

    switch(buttonPressed)
    {
      case 0x3AC5: // 11 - Brightness Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Brightness Up Held");
          brightnessUpHeld();
        }
        else
        {
          Serial.println("Brightness Up Pressed");
          brightnessUpPressed();
        }
        break;
      }

      case 0xFFFFBA45: // 12 - Brightness Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Brightness Down Held");
          brightnessDownHeld();
        }
        else
        {
          Serial.println("Brightness Down Pressed");
          brightnessDownPressed();
        }
        break;
      }

      case 0xFFFF827D: // 13 - Pause
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Pause Held");
          pauseHeld();
        }
        else
        {
          Serial.println("Pause Pressed");
          pausePressed();
        }
        break;
      }

      case 0x2FD: // 14 - Power
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Power Held");
          powerHeld();
        }
        else
        {
          Serial.println("Pause Pressed");
          powerPressed();
        }
        break;
      }

      case 0x1AE5: // 21 - Red
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red Held");
          redHeld();
        }
        else
        {
          Serial.println("Red Pressed");
          redPressed();
        }
        break;
      }

      case 0xFFFF9A65: // 22 - Green
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green Held");
          greenHeld();
        }
        else
        {
          Serial.println("Green Pressed");
          greenPressed();
        }
        break;
      }

      case 0xFFFFA25D: // 23 - Blue
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue Held");
          blueHeld();
        }
        else
        {
          Serial.println("Blue Pressed");
          bluePressed();
        }
        break;
      }

      case 0x22DD: // 24 - White
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White Held");
          whiteHeld();
        }
        else
        {
          Serial.println("White Pressed");
          whitePressed();
        }
        break;
      }

      case 0x2AD5: // 31 - Red 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red One Held");
          redOneHeld();
        }
        else
        {
          Serial.println("Red One Pressed");
          redOnePressed();
        }
        break;
      }

      case 0xFFFFAA55: // 32 - Green 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green One Held");
          greenOneHeld();
        }
        else
        {
          Serial.println("Green One Pressed");
          greenOnePressed();
        }
        break;
      }

      case 0xFFFF926D: // 33 - Blue 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue One Held");
          blueOneHeld();
        }
        else
        {
          Serial.println("Blue One Pressed");
          blueOnePressed();
        }
        break;
      }

      case 0x12ED: // 34 - White 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White One Held");
          whiteOneHeld();
        }
        else
        {
          Serial.println("White One Pressed");
          whiteOnePressed();
        }
      }

      case 0xAF5: // 41 - Red 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 2 Held");
          redTwoHeld();
        }
        else
        {
          Serial.println("Red 2 Pressed");
          redTwoPressed();
        }
        break;
      }

      case 0xFFFF8A75: // 42 - Green 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 2 Held");
          greenTwoHeld();
        }
        else
        {
          Serial.println("Green 2 Pressed");
          greenTwoPressed();
        }
        break;
      }

      case 0xFFFFB24D: // 43 - Blue 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 2 Held");
          blueTwoHeld();
        }
        else
        {
          Serial.println("Blue 2 Pressed");
          blueTwoPressed();
        }
        break;
      }

      case 0x32CD: // 44 - White 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 2 Held");
          whiteTwoHeld();
        }
        else
        {
          Serial.println("White 2 Pressed");
          whiteTwoPressed();
        }
        break;
      }

      case 0x38C7: // 51 - Red 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 3 Held");
          redThreeHeld();
        }
        else
        {
          Serial.println("Red 3 Pressed");
          redThreePressed();
        }
        break;
      }

      case 0xFFFFB847: // 52 -  Green 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 3 Held");
          greenThreeHeld();
        }
        else
        {
          Serial.println("Green 3 Pressed");
          greenThreePressed();
        }
        break;
      }

      case 0x7887: // 53 - Blue 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 3 Held");
          blueThreeHeld();
        }
        else
        {
          Serial.println("Blue 3 Pressed");
          blueThreePressed();
        }
        break;
      }

      case 0xFFFFF807: // 54 - White 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 3 Held");
          whiteThreeHeld();
        }
        else
        {
          Serial.println("White 3 Pressed");
          whiteThreePressed();
        }
        break;
      }

      case 0x18E7: // 61 - Red 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red 4 Held");
          redFourHeld();
        }
        else
        {
          Serial.println("Red 4 Pressed");
          redFourPressed();
        }
        break;
      }

      case 0xFFFF9867: // 62 - Green 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green 4 Held");
          greenFourHeld();
        }
        else
        {
          Serial.println("Green 4 Pressed");
          greenFourPressed();
        }
        break;
      }

      case 0x58A7: // 63 - Blue 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue 4 Held");
          blueFourHeld();
        }
        else
        {
          Serial.println("Blue 4 Pressed");
          blueFourPressed();
        }
        break;
      }

      case 0xFFFFD827: // 64 - White 4
      {
        if(results.value == buttonHeld)
        {
          Serial.println("White 4 Held");
          whiteFourHeld();
        }
        else
        {
          Serial.println("White 4 Pressed");
          whiteFourPressed();
        }
        break;
      }

      case 0x28D7: // 71 - Red DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red DIY Up Held");
          redDIYUpHeld();
        }
        else
        {
          Serial.println("Red DIY Up Pressed");
          redDIYUpPressed();
        }
        break;
      }

      case 0xFFFFA857: // 72 - Green DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green DIY Up Held");
          greenDIYUpHeld();
        }
        else
        {
          Serial.println("Green DIY Up Pressed");
          greenDIYUpPressed();
        }
        break;
      }

      case 0x6897: // 73 - Blue DIY Up
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue DIY Up Held");
          blueDIYUpHeld();
        }
        else
        {
          Serial.println("Blue DIY Up Pressed");
          blueDIYUpPressed();
        }
        break;
      }

      case 0xFFFFE817: // 74 - Quick
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Quick Held");
          quickHeld();
        }
        else
        {
          Serial.println("Quick Pressed");
          quickPressed();
        }
        break;
      }

      case 0x8F7: // 81 - Red DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Red DIY Down Held");
          redDIYDownHeld();
        }
        else
        {
          Serial.println("Red DIY Down Pressed");
          redDIYDownPressed();
        }
        break;
      }

      case 0xFFFF8877: // 72 - Green DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Green DIY Down Held");
          greenDIYDownHeld();
        }
        else
        {
          Serial.println("Green DIY Down Pressed");
          greenDIYDownPressed();
        }
        break;
      }

      case 0x48B7: // 73 - Blue DIY Down
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Blue DIY Down Held");
          blueDIYDownHeld();
        }
        else
        {
          Serial.println("Blue DIY Down Pressed");
          blueDIYDownPressed();
        }
        break;
      }

      case 0xFFFFC837: // 84 - Slow
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Slow Held");
          slowHeld();
        }
        else
        {
          Serial.println("Slow Pressed");
          slowPressed();
        }
        break;
      }

      case 0x30CF: // 84 - DIY 1
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 1 Held");
          diyOneHeld();
        }
        else
        {
          Serial.println("DIY 1 Pressed");
          diyOnePressed();
        }
        break;
      }

      case 0xFFFFB04F: // 84 - DIY 2
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 2 Held");
          diyTwoHeld();
        }
        else
        {
          Serial.println("DIY 2 Pressed");
          diyTwoPressed();
        }
        break;
      }

      case 0x708F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 3 Held");
          diyThreeHeld();
        }
        else
        {
          Serial.println("DIY 3 Pressed");
          diyThreePressed();
        }
        break;
      }

      case 0x708F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("DIY 3 Held");
          diyThreeHeld();
        }
        else
        {
          Serial.println("DIY 3 Pressed");
          diyThreePressed();
        }
        break;
      }

      case 0xFFFFF00F: // 84 - DIY 3
      {
        if(results.value == buttonHeld)
        {
          Serial.println("Auto Held");
          autoHeld();
        }
        else
        {
          Serial.println("Auto Pressed");
          autoPressed();
        }
        break;
      }

    }
    irrecv.resume(); // Receive the next IR value
  }
}

```

# Answer
> 2 votes
Your switch statement isn't that big - I've seen bigger.

However, as @MarkSmith says, using an array of structs with key codes and function pointers would be a way to go. For instance, you may have the struct:

```
struct button {
    uint32_t keycode;
    void (*press)();
    void (*hold)();
};

```

Populated with data it would look like:

```
const struct button buttons[] = {
    { 0x3AC5, brightnessUpPressed, brightnessUpHeld },
    { 0xFFFFBA45, brightnessDownPressed, brightnessDownHeld },
    ... etc ...
    { 0xFFFFF00F, autoPressed, autoHeld },
    { 0, 0, 0 }
};

```

Note the last entry of `{ 0, 0, 0 }` \- this is being used as an "end of list" marker. An alternative is to keep track of how many entries are in the list, but this makes adding / removing entries easier.

Then you can iterate through the list until you find a keycode that matches or the special keycode `0`:

```
for (int i = 0; buttons[i].keycode != 0; i++) {
    if (buttons[i].keycode == buttonPressed) {
        if (results.value == buttonHeld) {
            buttons[i].held();
        } else {
            buttons[i].press();
        }
        break; // We found the button, no need to continue
    }
}

```

This method decreases the amount of code you have, but has the adverse effect of increasing the amount of RAM you use. It's a tradeoff between making the code simpler and using more RAM. If you can afford the RAM usage it can make things so much easier to read, since you have a simple table for the commands and a simple loop for finding the right entry in the table.

---
Tags: programming, arduino-ide, code-optimization
---


title: Multiple independent LED patterns

text:
# Question
Title: Multiple independent LED patterns
I have an problem, which at first thoughts (and being new to Arduino) I though was a perfect application for an Arduino. However, after trying and failing to implement it I am doubting myself!

Simply - I need to control many LEDs independently, many of which will have their own individual patterns - for example "5 seconds on - 5 seconds off". "continuous flashes" - or sequences such as "2 flashes, pause, 1 flash". Obviously without the luxury of threads I am becoming a little unstuck. Be great to hear if a) Arduino is the best choice and b) if it is - how can I go about this!

Thanks in advance :)

# Answer
Handling multiple patterns at the same time is certainly possible with a platform like Arduino, and there are a number of ways you could go about it.

One method I would consider is writing functions which effectively represent each pattern mathematically. You'd just pass it the total time that's elapsed in your program so far, and it will do the appropriate action for that specific moment in time. It will return immediately afterwards (no delays or anything).

To do that, you'll first need to know how long a single cycle of the pattern lasts. You can then use the modulo operator to figure out how far through the current cycle you are. From there, all you need to do is have some `if` conditions to determine what to do at any given time.

Here's what it might look like for your "5 seconds on, 5 seconds off" pattern:

```
function pattern5on5off(unsigned long totalTime)
{
  // Calculate how far through the current cycle we are
  const unsigned long cycleTime = totalTime % 10000;

  // If we're in the first 5 seconds of the cycle then turn the light on.
  // Otherwise, turn it off.
  if (cycleTime < 5000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}

```

Admittedly, constantly calling `digitalWrite()` when you don't technically need to isn't very efficient. It shouldn't cause any harm though, and is fairly easy to optimise if necessary.

To use the above example in a sketch, you'd just need to call it in `loop()`, and pass the number you get from `millis()`; e.g.:

```
void loop()
{
  const unsigned long totalTime = millis();

  pattern5on5off(totalTime);

  // call other patterns here...
}

```

Other patterns will be more complex, but follow the same principle. You'd just to use appropriate `if` statements to express your logic.

The vital thing to remember is that the function represents a specific moment in time. It should never pause or delay the program, otherwise it will prevent the other patterns from running.

**Edit: Timing on the first cycle**
As jfpoilpret noted in the comments, the very first cycle will start at a random point. This is because the first time you call `millis()` in `loop()`, it won't start at 0 (the device will already have been running for a short time before `loop()` gets called). It's easy to resolve though, if necessary.

You would do it by offsetting the `totalTime` value by the whatever value you got on the very first time around `loop()`. For example:

```
unsigned long g_startTime = 0;

void loop()
{
  unsigned long totalTime = 0;

  if (g_startTime == 0) {
    // This is the first cycle.
    // Store the start time so we can compensate later.
    g_startTime = millis();

  } else {
    // This is not the first cycle.
    // Compensate for the start time.
    totalTime = millis() - g_startTime;
  }

  pattern5on5off(totalTime);
  // etc..
}

```
> 9 votes

# Answer
Arduino is a fine choice for the task - easy to get started with. The key is to write non-blocking code. You could take a look at the BlinkWithoutDelay example.

I made a suggestion for your task:

```
// Timing suquences for the LED's in milliseconds
// First value is on time, second value is off time,
// third value on time and so on (up to 10 values)
// One row for each LED
unsigned int led_timing[][10] = {
  {5000, 5000},
  {100, 1000},
  {100, 100, 100, 1500, 100, 1500}
};

// The pins the LED's are connected to
byte led_pins[] = {11, 12, 13};

// Keep track of timing sequence
// Array size taken from led_pins
unsigned long last_change[sizeof(led_pins)/sizeof(led_pins[0])];
byte timing_i[sizeof(led_pins)/sizeof(led_pins[0])];

void setup()
{
  // Initialize LED's as output
  for (byte i = 0; i < sizeof(led_pins)/sizeof(led_pins[0]); i++)
  {
    pinMode(led_pins[i], OUTPUT);
    digitalWrite(led_pins[i], HIGH);
  }
}

void loop()
{
  // Current timestamp
  unsigned long now = millis();

  // Keep track of sequence for each LED
  for (byte i = 0; i < sizeof(led_pins)/sizeof(led_pins[0]); i++)
  {
    if (now - last_change[i] >= led_timing[i][timing_i[i]])
    {
      digitalWrite(led_pins[i], !digitalRead(led_pins[i]));
      timing_i[i]++;

      // Start over at the end of timing sequence
      timing_i[i] %= sizeof(led_timing[i])/sizeof(led_timing[i][0]);

      last_change[i] = now;
    }
  }
}

```
> 4 votes

# Answer
I know the post is old, but I checked the example with the array based approach and in my opinion:

```
sizeof(led_timing[i])/sizeof(led_timing[i][0])

```

will always yield the allocated size (number of elements) of the array - in this case 10. So the timing won't restart until you reached the "end" of the array, using undefined elements. For LED "0":

```
int led_timing[0][10]:
5000,5000, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>

```

Greetings Tommy
> 1 votes

---
Tags: led, interrupt, threads
---


# Question
Title: How to use analogWrite() on multiple pins at the same time?
I would like to do,

`analogWrite(100,3);
 analogWrite(200,6);`

at the same time. But the problem is that only the led on pin 3 lights up. I want both to light up at the same time. I've heard about direct port manipulation, but I can only find an alternate for `digitalWrite()` but I couldn't find one for `analogWrite()`. Can someone please help me with just a simple example on just how to do the above operation?

I'm using arduino uno.

# Answer
You have your parameters the wrong way round:

```
analogWrite(2, 100);
analogWrite(6, 200);

```

**However**: pin 2 on the Uno cannot do PWM, so you will have to pick a different pin. Look for the pins marked with `~` \- they are the PWM pins. On the Uno that is pins 3, 5, 6, 9, 10 and 11.
> 11 votes

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


# Question
Title: TWI Wire.setClock() on non arduino AVR MCU issue
Using an Atmega168P - programmed by means of `avrdude` with the `.hex` file generated by Arduino IDE.

The following code sets the 8 MHz Atmega's TWI interface to just 15.625 kHz:

```
  Wire.begin(); // Initiate the Wire library
  Wire.setClock(100* 1000);
  delay(10);

```

While this one doubles it to 31.25 kHz:

```
  Wire.begin(); // Initiate the Wire library
  TWBR = (F_CPU/(100*1000) - 16)/2;
  TWSR &= 0b11111100;
  delay(10);

```

Looking to get 100 kHz clock. What am I missing ?

# Answer
> Looking to get 100 kHz clock. What am I missing?

Calculations are int (16-bits) by default in AVR GCC. Try 100\*1000L. Or even better:

```
#define F_TWI 100000L

```

and use:

```
TWBR = ((F_CPU/F_TWI)-16)/2;

```

or:

```
Wire.setClock(F_TWI);

```

Cheers!
> 3 votes

---
Tags: i2c, avr, avrdude, wire-library
---


title: HC-06 RX pin usefulness

text:
# Question
Title: HC-06 RX pin usefulness
I have a HC-06 bluetooth module. The module has an RX and TX pin (the RX pin receives data and TX transmits data) which connect to the TX and RX pin of an Arduino respectively (in my case an Arduino pro mini).

My question is in what scenario would someone use the RX pin of the module(basically for what purpose would the bluetooth module receive a signal from the Arduino)?

For example let's say i have a simple LED that i turn off and on. I just sent the signal from my phone to the module and the module sends the signal to the Arduino. So basically i've connected the TX pin of the module (which transmits the data) with the RX pin of the Arduino (which receives the data).

In order to connect the RX pin of the module with the TX pin of the Arduino i have to use a voltage divider as the module only accepts 3.3 volts of signal while the Arduino transmits 5 volts of signal. I want to avoid that because in my project i need the PCB to be quite small.

So if someone only wants to transmit data from the module to the Arduino, is there a reason on why would he connect the other two pins?

# Answer
> 1 votes
If you never want to change the configuration of the module either, then no, you don't need to connect the module's RX pin.

However many people want bi-directional communication. Not only the ability to send a signal to turn the LED on or off, but also the ability to get the current state of the LED - is it on or off?

Or maybe to send an analog reading. Or the data from some sensor.

The HC-06 is a bi-directional module. If you choose to use only one direction then you only need to wire in one direction. However, tie the RX pin to 3.3V with a 10KΩ resistor to stop it floating and consuming extra power or causing random noise to be transmitted to your phone.

In fact, it's just like a phone. You can call someone up and just speak to them without listening to what they are saying. That's fine if all you want to do is call Mom and say "Pick me up in 5 minutes" and hang up. But if you want to ask your Mom "Can you pick me up in 5 minutes?" you have to actually listen for her answer "No, walk home you lazy oik!".

---
Tags: arduino-pro-mini, hc-06, voltage
---


title: Yún vs Uno with Yún Shield

text:
# Question
Title: Yún vs Uno with Yún Shield
What are the **differences** between an Arduino Yún and a Arduino Uno with an added Yún Shield? And is there a way to expand the storage of the Yún / Yún Shield?

# Answer
> 1 votes
As Majenko wrote: the Arduino Yún = Leonardo + Yún shield. You get into a lot of trouble with the Arduino Uno, and the Yún shield has already enough troubles on its own.

Maybe the Arduino Mega 2560 can be used when both the hardware and software is changed to use another hardware serial port for the Yún shield. If you start with the Yún shield, then use the Leonardo. Don't even try the Arduino Uno.

It is possible to upload a sketch via Ethernet or WiFi, but that often fails. Therefor you need the usb-serial connection to the computer to upload a sketch.

Even when you use a Arduino Leonardo, the communication between the Yún shield and the Arduino board (the 'Bridge') can cause troubles. In OpenWRT a Python script is used to read the serial data from the 'Bridge', which causes a lot of CPU usage.

The Yún shield is not fully compatible with the Arduino Yún. I think a few GPIO pins are different and maybe some other things. That means you are stuck to the firmware of the Yún shield, which can have issues and is not fully compatible with the Arduino Yún firmware.

When installing software in OpenWRT, the rootfs is filled quickly. You can type `df` or `df -h` to see the disk usage. I have read about ways to add a SD memory card or a USB flash drive to the rootfs. I have not tried that because I want OpenWRT to run even without a SD memory or USB drive.

An SD memory or USB drive can be used to store a website on it, or scripts, or music files, and so on.

When you need more memory, you might want to try the Raspberry Pi. The Raspberry Pi Zero W is very cheap and has WiFi.

# Answer
> 1 votes
The differences are manifold.

The biggest difference is that the Yun employs an ATMega32U4 as the MCU, whereas the Uno employs the ATMega328P. This has big ramifications with the Yun shield.

* The ATMega32U4 uses a dedicated USB connection to the USB socket, and a dedicated UART connection to the MIPS SoC.
* The ATMega328P has only a UART connection which is shared between the USB interface and the MIPS SoC.

This means that the Yun shield can interfere with the operation of the USB connection. You cannot communicate between the MIPS SoC and the Uno whilst at the same time using the USB connection, like you can with the full blown Yun. Uploading sketches can be an issue - you may want to remove the Yun shield while uploading.

The Yun is closer in operation to an Yun Shield + Arduino Leonardo than an Uno.

---
Tags: arduino-uno, shields, arduino-yun
---


# Question
Title: Interfacing TRRS headphone to Arduino Uno
I have been working in a Arduino project lately which requires human voice input to Arduino with some processing Arduino need to perform specific task. Simple sampling of incoming signal and calculating average amplitude from it nothing complex.

My problem is I have tried using electret microphone to receive human voice input but failed since the Elec Mic is not sensitive to detect the voice even though i hooked up with LM386 amplifier circuit. So that option is out of the picture. Then i intend to use Android mobile headphones (TRRS) to receive the human voice which will provide great sensitivity for our voice.

Starting through simple internet searches i bought a product 3.5mm breakout module from Ebay. But am unsure of how to connect them to Arduino. Different sources in internet giving different information i couldn't figure out how to connect the headphone to arduino and read it's Mic output from headphone.

Seeing the pin out of TRRS headphones  i can't understand how could i possibly power my headphones with only GND pin available. I tried several wiring connections given in the internet to read the Mic output of my headphones through Analog pin A0 of Arduino but no luck so far. So my question is

**1) How do i power the TRRS headphone using Arduino?
2) How can i read the MIC output of my headphone using Arduino? Is it even possible?
3) I have read somewhere the audio out from headphones will be of FSK modulated is it true?**

Any help will be much appreciated. Please do provide if you have any links that might answer my questions.

Thanks in advance.

# Answer
> 1 votes
TRRS relates to the style of the jack plug used: Tip Ring Ring Sleeve. You still need to amplify the signal with a microphone preamp the same as your electret (in fact it will be an electret in there anyway).

And then the Arduino cannot process human speech. You may be able to use a voice recognition module to get it to respond to specific commands, but the Arduino by itself has no hope of even thinking about it.

# Answer
> 1 votes
It sounds to me as if your project is really more about what you do with the audio once you're sampling it into the Arduino and this whole "how do I get a usable signal out of a microphone" thing is not your main interest. In that case, I suggest just going with something like this MEMS microphone breakout board which includes the microphone and all the circuitry necessary to get a proper signal to an analog input on the Arduino.

---
Tags: analogread, audio, analog-sampling
---


# Question
Title: How to connect gyro to Arduino Uno via I2C
**parts**

1. Three-axis rate gyro on breakout board: gyro datasheet, breakout board "datasheet"
2. Arduino Uno: pinout

**goal**: I want to periodically read a single axes' angular rate. As rvbarreto pointed out, Adafruit built an Arduino library for this sensor, so I'm playing around with its example file.

**configuration**:

I have a 5600 Ohm pull-up connected to the SDA and SCL pins each on the Arduino. The internal pull-ups of the Arduino are too weak according to this thread.

**code:** (Adafruit library's sensorapi example)

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_FXAS21002C.h>

/* Assign a unique ID to this sensor at the same time */
Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x0021002C);
//Adafruit_FXAS21002C gyro = Adafruit_FXAS21002C(0x21);

void displaySensorDetails(void)
{
  sensor_t sensor;
  gyro.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    0x"); Serial.println(sensor.sensor_id, HEX);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" rad/s");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" rad/s");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" rad/s");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

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

  /* Wait for the Serial Monitor */
  while (!Serial) {
    delay(1);
  }

  Serial.println("Gyroscope Test"); Serial.println("");

  /* Initialise the sensor */
  if(!gyro.begin())
  {
    /* There was a problem detecting the FXAS21002C ... check your connections */
    Serial.println("Ooops, no FXAS21002C detected ... Check your wiring!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  gyro.getEvent(&event);

  /* Display the results (speed is measured in rad/s) */
  Serial.print("X: "); Serial.print(event.gyro.x); Serial.print("  ");
  Serial.print("Y: "); Serial.print(event.gyro.y); Serial.print("  ");
  Serial.print("Z: "); Serial.print(event.gyro.z); Serial.print("  ");
  Serial.println("rad/s ");
  delay(500);
}

```

NOTE: I noticed that Adafruit's Github had removed a line of code (line 67) in their library's main .cpp file. I edited my library code to reflect that change.

**problem**: I keep getting the "Ooops, no FXAS21002C detected ... Check your wiring!" error message.

**questions**:

1. Am I connecting my pull-up resistors correctly?
2. Should I not power VDD and VDD\_IO on the same rail? Can they even be powered by the Uno?

# Answer
I needed to connect the gyro's reset input to V\_DD\_IO. See gyro datasheet, table 1, pin 4. This corresponds to pin 7/RST\_21002 on the breakout board. The gyro works like a charm now!
> 0 votes

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


title: HC-06 pairing to arduino

text:
# Question
Title: HC-06 pairing to arduino
I have a bluetooth module HC-06 and want to pair it to my Arduino UNO. The thing is when I researched how to do so, I got different answers. What pairing should I use? Thank you in advance. I have highlighted the differences.

First version: https://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/

HC-06\>\>\>Arduino

**VCC\>\>\>\>3.3v**

GND\>\>\>\>GND

TXD\>\>\>\>RXD

**RXD\>\>\>\>TXD**

Second version: http://42bots.com/tutorials/hc-06-bluetooth-module-datasheet-and-configuration-with-arduino/

HC-06 \<\<\>\> Arduino

HC-06 Ground GND \<\<\>\> GND

**HC-06 VCC pin \<\<\>\> 5v**

HC-06 TX/TXD pin \<\<\>\> Arduino RX

**HC-06 RX/RXD pin \<\< resistors \>\> Arduino TX**

\[!\[enter image description here\]\[1\]\]\[1\]

\[!\[enter image description here\]\[2\]\]\[2\]

# Answer
> 1 votes
Which you use depends on two factors: the HC-06 carrier board you have, and which Arduino you are using.

If your carrier board has (and most do) a 3.3V regulator then you power the board from 5V.

If your Arduino is a 5V Arduino (such as an Uno) then you need a voltage divider on the (arduino)TX-\>(hc)RX pins otherwise you risk damaging the bluetooth module.

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


# Question
Title: What are the consequences of different clock speeds on different boards?
I am a programming amateur, arduino noob, trying to decide which board will be better for my project. I need a small board. I am trying to decide between the Teensy 3.2 and the RFduino. I want to have blue-tooth capability for over air routine changes to a WS2812B LED strip, which makes the RFduino attractive because of its integrated BLE4.0 antenna. However, I want to be able to have enough speed for imperceptible LED modulation, which makes the 72MHz speed of the Teensy attractive.

What would be the objective difference between the 16MHz processor on the RFduino versus the 72MHz on the Teensy3.2? Is this something I should be concerned with?

# Answer
You have to set your requirements, or atleast elaborate what you want to achieve.

Best would be to program in a set amount of effects on the microcontroller and only send which effect you want to "start" with maybe even a color.

But you have to specify stuff, you should make a list like this:

```
Length of messages
(Max) baudrate of bluetooth device & microcontroller

amount of bits in the total LED strip
speed of sending bits into the LED strip

Maximal time from sending to effect

```

**Sample calculation for NeoPixel (WS2182)**

If you can make a good approximation (or find actual values) you can determine which speed you are going to need. This might even be 1Mhz, try to avoid premature optimization.

60 leds/m for 3M = 180 leds. 24bit data per LED.

180\*24 = 4320 bits of data.

One bit takes around 1,3uS, so 4320\*1,3 = 5616 uS Which is 5,616 milliseconds to update the LED strip. (Processor Mhz won't help you here)

**Sample calculation for DotStar (APA102)**

180 leds, 32bit per LED = 5.760 bits total. +64 bits (32bit start frame, 32bit end frame). 5824 total bits.

You can set the SPI clock divider to 2. So if your board runs at 16Mhz, divided by 2, you get 8Mhz SPI output.

> 8 megahertz = 8 000 000 hertz

(EDIT)

> The fastest rate is "divide by 2" or one SPI clock pulse every 125 nS. - Nick Gammon (http://www.gammon.com.au/spi)

Neopixels take 0.85us + 0.4us = 1,25 us (1250ns). So they would be 10x slower.

(never mind this calculation, it was from before using Nicks' facts)

```
8.000.000  |  5824
 1 sec     |   x

```

(Your x value will be the time in seconds to update the DotStar strip with SPI@8Mhz)

**What was your point?**

After this you can check your baudrate + message length to see how long sending/receiving your message will take.

You can then reliably tell if you need 1, 8, 16 or 72Mhz.

I believe the DotStar led strips should be faster, but I haven't completely calculated it out. You could ask yourself if it's worth trying to omptimize that.

BUT, note that the DotStar/SPI led strip allows you to have "interrupts". Which means you can receive characters over the bluetooth while you're writing to the LED strip.

And, we're probably overthinking the situation. But it's better to overthink it using hard values :)
> 0 votes

# Answer
As was mentioned earlier about the DotStar LED strip/led

There is one thing missing in the calculation above. The End Frame shows as a 32 bit frame of all 1's. That is almost correct. The least obvious is that you need to add 1/2 of a bit for each led in the strip. This is due to the way that the clock is sent down the line. So the 180 led strip would require 90 bits in the End Frame. If you don't do this you will have some of the leds at the end that are not reacting correctly. I know this sounds strange, had me for a while (I use Raspberry Pi).

Also, I have seen where some have tested the SPI mode of sending the data down the line and managed to achieve about 16Mhz clock speeds. Great for POV display.

The DotStar don't require refreshment at all. Each LED has it's own PWM chip built in. They are more expensive than the Neopixel, so it depends on the application as to which is better for you. I loaded my string with colors and then disconnected the data lines (led strip on different power supply) and turned off my Pi. Yup, the DotStars stay as they are.

It has been said they are 'addressable' which is not truly accurate. When sending data, it is the first one, then the second and on. If you wanted, you can change only the first few. Odd hack. Just send the Start Frame (32 or more 0's) and start sending data to the first without affecting the rest of the strip. Note: you might have to account for the 1/2 bit clock loss. eg: 1 bit per 2 leds.

Here is a pretty good description of the DotStar functionality : https://cpldcpu.com/2014/11/30/understanding-the-apa102-superled/

Here is a Youtube tutorial (2 short videos) that helped me quite a bit: https://www.youtube.com/playlist?list=PLhXSL6B3uLd551fEQlQGd3LrhzvudKfJQ
> 1 votes

# Answer
You would think on the face of it that a faster processor will give you "more speed" however that does not necessarily work in a linear way. The faster processors tend to have more sophisticated chips. And "more sophisticated" can be code for "it takes more clock cycles to achieve the same thing".

I have code that drives 300 NeoPixels in a seamless manner, on a 16 MHz Arduino Uno, however during the driving it is pretty processor-intensive (and interrupts have to be off). So certainly you can have some smooth effects at 16 MHz. However controlling them in real time, via Bluetooth, may be a different thing.

NeoPixels will "remember" the last thing that was sent to them, so (when interrupts are active) you could be accepting new instructions, and the pixels will just display what they were last sent. This may be acceptable for you.

The Adafruit page for RGB LED Strip mentions that their library is only for the AVR processors. So that may be a consideration for you.

Even with other display strips, you may find that, during reception of radio signals, the strips cannot alter their patterns at high speed. The 72 MHz you quoted is only 4.5 times as fast as 16 MHz. The NeoPixel timings are in the order of nanoseconds (350 ns for a zero-bit) so timing is tight. Having 4.5 x the clock speed isn't necessarily going to give you enough leeway to do radio communications.

---

> I just want to be able to select and change the program remotely via BLE, rather than send sequential commands over air. Does this change your answer at all?

Your design seems to me to consist of two components:

* Showing some pattern
* Receiving a new pattern (or code for a new pattern)

You can't be doing both at precisely the same time. (Maybe with two processors you might - one doing the radio, and one displaying the pixel pattern). I found I could refresh 1000 pixels in 63 ms, which is roughly 16 FPS. If you have less pixels it will be faster. I don't know exactly how long it takes to determine if a Bluetooth message has arrived, I assume not particularly long.

> Planning on 3M of 60LED/M WS2812B strip as of now

So, 180 pixels. At 63 µs per pixel that would be 11.3 ms to refresh the strip. You can see that this gives you quite a bit of time over in one second to receive new instructions.
> 0 votes

---
Tags: led, teensy, oscillator-clock
---


title: ESP8266 cannot handle struct

text:
# Question
Title: ESP8266 cannot handle struct
The following code works on a range of Arduino's but not on ESP. It returns random data for ID and Pin. The other two fields are always empty.

I use the Arduino IDE for both the ESP and the Arduino's. It looks like the ESP has it's own idea when it comes to struct.

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

#define BAUD 2000
#define RX 2
#define TX 5

RH_ASK driver(BAUD, RX, TX);

struct data {
  int id;
  int pin;
  int value1;
  int value2;
} myData;

void setup()
{
    Serial.begin(9600);
    Serial.println("Starting..");
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);

    if (driver.recv(buf, &buflen)) {

      memcpy(&myData, buf, buflen);

      Serial.print("ID: ");
      Serial.println(myData.id);

      Serial.print("Pin: ");
      Serial.println(myData.pin);

      Serial.print("Value1: ");
      Serial.println(myData.value1);

      Serial.print("Value2: ");
      Serial.println(myData.value2);

      Serial.println("");
    }
    yield;
}

```

**Bad Data**

```
ID: 263145
Pin: 18350364
Value1: 0
Value2: 0

```

**Should be**

```
ID: 1001
Pin: 4
Value1: 267
Value2: 843

```

# Answer
> 2 votes
The issue is that Arduino boards (8 bit ones at least), an `int` is 16 bits, where as the ESP's (8266 and 32) and possibly other non-arduino hardware, an int is 32bits

The safest way to declare structs in any case is to use variable types with known sizes, in your case, for signed 16bit ints

```
struct data {
  int16_t id;
  int16_t pin;
  int16_t value1;
  int16_t value2;
} myData;

```

or for unsigned 16bit ints

```
struct data {
  uint16_t id;
  uint16_t pin;
  uint16_t value1;
  uint16_t value2;
} myData;

```

Note: there's also `short int` which I believe is "guaranteed" to be 16bit (and "long int" is always 32 bit) - but having the bit size in the declaration is a far better (future proof) solution

---
Tags: esp8266
---


# Question
Title: How to learn enough C++ to program Arduino?
I am an experienced web developer, but my C++ skills are very basic. I struggle with the concepts because it is so different from something like Javascript (which I already know). I do not have a lot of time to learn C++, and I only need to know enough to play with Arduinos.

Are there any good resources out there for learning C++ that is specifically geared towards Arduino programming, and is there anything interactive like Codecademy?

# Answer
If I were you I'd take the high road.

I was in your shoes a while ago and I didn't know how to approach Arduino. I was very lucky that I came across a book written by the famous Jack Purdum, "Learn C programming for the Arduino". It is written by a retired Purdue University professor who is well known for his extremely easy to learn teaching method. He has another

I only knew MATLAB and Simulink before starting this book. This book is amazing. It was extremely easy to follow. I now have no difficulty programming Arduino in the correct way. This book trains you to optimize everything which is very crucial with the limited resources on Arduino boards.

I suggest C instead of C++. It is the language of choice for programming embedded system. It is said to be low level, but as a MATLAB user I should tell you that syntaxes are extremely easy and intuitive. I didn't find anything hard about them.

Remember:

1. There isn't any problem to use C in Arduino IDE.
2. You don't need to worry about libraries. You only need to load them in the beginning of the code. You do not need to know how was the code written in the library.
3. Check the comments about the book on Amazon if you are not convinced.

Good Luck
> 3 votes

# Answer
A very good book: Beginning C for Arduino:Learn C Programming for the Arduino, by Ph.D. , Jack Purdum
> 2 votes

# Answer
Beginning C for Arduino:Learn C Programming for the Arduino, by Ph.D. , Jack Purdum
> 1 votes

# Answer
Since you have programming experience and you say you only want to learn enough to play with Arduinos, I think a resource worth mentioning is the built-in example programs. I've seen Arduino itself used as a learning tool for C/C++; their examples are very basic and intended for complete novices. If you keep hacking on progressively more complicated examples and googling specific things you don't understand, you will probably be able to get a good handle on things IMHO.

That isn't to say it's necessarily a good tool for learning C++ in general, since the limited memory resources and 8-bit CPU make some capabilities of the language commonly used on desktops (and the whole standard library) rarely used or unavailable on Arduino.
> 0 votes

# Answer
Another way to approach the problem is to come up with a project that you want to do with an Arduino and look for code samples. Since you already have some programming experience you should be able to pick up what's going on pretty quickly and you will have a vested interest in what the code is doing.

For Example: Read temperature from a sensor and display to an LCD.

Arduinos are really good for reading from a sensor and there's a huge arduino community. So, if you start with just reading from different types of sensors you'll find a lot of examples and learn a lot about Arduinos at the same time.
> 0 votes

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


# Question
Title: Common ground serial communication trouble SIM800L
I have a trouble when i'm using SIM800L module with common ground with combinaison with : FTDI232+ARDUINO PRO and Li-po battery. I use common ground to allow Arduino see the serial of SIM800L.

I use battery (lipo) to power the SIM800L to allow 2A peak current.

Serial work but sometime the module reset(i think) and i see strange character. The SIM800L no work correctly.

I meet the same trouble when i use the FTDI's VCC, every time I use the common ground i have this problem.

Look the gif you can see the problem :

I'm using this wiring

It's strange because when i connect the SIM800L directly with FTDI232 i have no problem all work fine.

I use this code to debug the Serial communication :

```
#include <SoftwareSerial.h>
SoftwareSerial serialSIM800(RX,TX)
[..]
//On Setup
 Serial.begin(115200);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(115200);
  delay(1000);
  serialSIM800.print("AT\r");
  //[..]
void loop(){

 if (serialSIM800.available())
     Serial.write(serialSIM800.read());

 if (Serial.available()) {
    while(Serial.available()){
      Serial.print(">");
      char test=Serial.read();
      Serial.print(test);
      Serial.println();
      serialSIM800.write(test);
 }

```

There are a few things that escape me that's why I need your lights, thanks by advance. Regards

# Answer
> 1 votes
I finally fixed my issue. I disable the auto baud rate of SIM800L trough FTDI232, with these at commands:

```
AT + IPR = 9600
AT & W

```

AT + IPR: Fix the baud rate at 9600 AT & W: Save in SIM800L

Then when i use with SoftwareSerial i have no issue anymore. When i reset the module with short connect RST with GND i have a good reply from SIM800L :

```
RDY

+CFUN: 1

+CPIN: READY

Call Ready

SMS Ready

```

Thanks for your help.

Note : And be sure you are a good power supply and good wire.

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


# Question
Title: ESP8266-01 connected to Arduino Mega - Current output?
I was thinking of powering my arduino with an external 9 V power source, but I am still trying to figure out the best way to get the right amount of current for the Wi-Fi module. Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

If there is an easier way to do this I am all ears. I will be using Arduino Mega, not uno as shown in the picture.

EDIT: Voltage divider will be used on the RX pin and I might go for a logic level converter instead of the voltage regulator

# Answer
> Should I use an external power supply for the ESP8266-01 module that can output about 500mA or amplify the output from the arduino pins using a transistor?

Either way you're going to need a power supply that can supply the current. A transistor doesn't magically create more current, it merely allows a small current to control the flow of a larger current.

So you will need an external power source that can provide enough current.

> I might go for a logic level converter instead of the voltage regulator.

Incorrect. A logic leven converter cannot provide anywhere near enough current to power a device. It can barely provide enough to light an LED.

You are right to want to ditch the voltage regulator though.

As it stands you have a chain of regulators, each one wasting power. At 500mA that's lots of power.

```
9V -> [REG] -> 5V -> [REG] -> 3.3V

```

That's 4V dropped in the first regulator at ~500mA, and 1.7V dropped in the second regulator at ~500mA. Since P=VI, 4×0.5 = 2W, and 1.7×0.5 = 0.85W. Since you are providing 9×0.5 = 4.5W of power from the battery, you have 1-((2+0.85)÷4.5) = 0.366, or 36% efficiency. That's about two thirds of your battery power wasted just in heat.

Instead you want to use a switching voltage regulator. These are far more efficient and convert voltage into current rather than voltage into heat. This means that you draw less current from your battery, meaning you can use a battery with a higher internal resistance.

Ideally you would use two - one to convert the 9V into 5V to power the Arduino, and another to convert the 9V directly into 3.3V to power the ESP8266. That would be the most efficient arrangement.

There are plenty of breadboard friendly modules on eBay that can do that, or other small modules you can wire in to your circuit without a breadboard (I myself sell one on eBay that I designed).
> 1 votes

---
Tags: esp8266, wifi, current
---


# Question
Title: Having problems with I2C - Slave is receiving "b ~ ,,,"
so I'm facing a pretty large problem. I'm experimenting with I2C and using one Arduino that acts as a countdown timer to send the current reading on the timer to another Arduino. I'm pretty new to electronics in general so bear with me.

The way the countdown timer works is it stores the time as a String, and uses substring and toInt() to adjust the timer.

I know that with I2C you can only send some data, Strings not included, so I tried converting the String to an array of characters using toCharArray(). My conversion seems to be working well, as I have tested it with the Serial.println() and it displays the time correctly.

Therefore, I am convinced the problem lies with the Slave code. I'm not sure how to set up the Slave Arduino to receive the actual time. Below, I've pasted links to the code of both the Master and the Slave respectively.

Master: https://pastebin.com/AFjTDZB7

Slave: https://pastebin.com/viNGWn9c

How should I change my slave code so everything works?

Also, when I changed the datatype of "time" in the Slave code from char\* to int, all I got in the Serial Monitor was 48. Weird.

Would really appreciate any help and guidance cause I'm pretty stuck. All the tutorials I find online are pretty complicated.

Thanks!

Master Code:

```
#include < Wire.h >
String time = "10:11";
boolean doubleDigits = false;

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

void loop() {
  Serial.println(time);
  sendTime(time);
  int First2 = time.substring(0, 2).toInt();
  if (First2 > 9) {
    doubleDigits = true;
  }

  int Last2 = time.substring(3).toInt();
  if ((time.substring(3) == "00") && (time != "00:00")) {
    First2 = First2 - 1;
    Last2 = 59;
    if (doubleDigits == false) {
      time = "0" + String(First2) + ":" + String(Last2);
    } else {
      time = String(First2) + ":" + String(Last2);
    }
  } else if (time != "00:00") {
    Last2 = Last2 - 1;
    if (Last2 < 10) {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":0" + String(Last2);
      } else {
        time = String(First2) + ":0" + String(Last2);
      }
    } else {
      if (doubleDigits == false) {
        time = "0" + String(First2) + ":" + String(Last2);
      } else {
        time = String(First2) + ":" + String(Last2);
      }
    }
  }
  if (time.substring(1, 2) == ":") {
    time = "0" + time;
  }
  delay(1000);
}

void sendTime(String time) {
  Wire.beginTransmission(9); //transmit to device 9
  char buffer[32];
  time.toCharArray(buffer, 32);
  Wire.write(buffer);
  Serial.println(buffer);
  Wire.endTransmission(); //stops transmitting
}

//master

```

Slave Code:

```
#include <Wire.h>
char* time;

void setup() {
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
  Serial.begin(9600);
}

void receiveEvent(int bytes) {
  time = Wire.read(); //read one character from the I2C

}

void loop() {
  Serial.println(time);
  delay(1000);
}

//slave

```

Edit: added code

# Answer
> 0 votes
In the slave code. `receiveEvent` takes a number of bytes as a parameter, presumably you are supposed to read this many bytes, can you call read with that number? Even if you did you are reading to a char pointer, which will cause issues unless read is allocating the memory, which you should then be releasing. Basically you have a couple of issues here and you need to look at them.

In the Master code. `sendTime` doesn't look right. I would expect you to have to send a certain number of bytes using the Write function. You are just sending 32 chars, the fact you are sending signed char's rather than unsigned char's shouldn't be an issue (but its technically incorrect).

I don't really understand what you are trying to achieve in the rest of loop, annotation would help :)

---

OK, If you take this as a new version for the slave you should be able to see it working. It might not be 100%, but you should get something. (I haven't even compiled this code, so you might have to sort out a few bugs)

```
#include <Wire.h>

#define MaxTimeBufferSize (33)
#define MaxReadSize  (MaxTimeBufferSize - 1)
char timeBuffer[MaxTimeBufferSize];

void setup()
{
  Serial.begin(9600);  // Init first so you can see any issues during setup.
  Wire.begin(9); //start as slave on address 9
  Wire.onReceive(receiveEvent); //attach a function to trigger when something is received
}

// Assumes the bytes are actually printable ASCII characters.
void receiveEvent(int bytes)
{
  const int bytesToRead = (bytes < MaxReadSize) ? bytes : MaxReadSize;
  for (int index = 0; index < bytesToRead; ++index)
  {
     timeBuffer[index] = Wire.read(); //read one character from the I2C
  }
  timeBuffer[bytesToRead] = 0; // Null terminate the bytes (so they will print as a string)
}

void loop()
{
  if (timeBuffer[0])  // Only print the buffer if there is new data
  {
    Serial.println(timeBuffer); // The buffer is NULL terminated.
    timeBuffer[0] = 0;  // Stop the buffer  printing again.
  }
  delay(1000);
}

```

# Answer
> 0 votes
@A.Lordos, the code by @CodeGorilla shows how to read more than one byte as a Slave. It stores the received data in a buffer, and that buffer is printed to the serial monitor to show it.

May I make a suggestion: start all over and do it right.
Forget the String objects and use a integer (int, or unsigned or unsigned long) as a countdown counter for the seconds. Count the seconds, nothing else.
When you need to display the counter, then you can make it in the format of "10:11". But only to display it, the base of the sketch is still that single variable for the seconds. When you need to transmit the counter to the Slave, send the integer variable as binary data (the integer itself), not a text string.

In the Arduino examples, a text is transferred over the I2C bus. That is however almost never done. In most cases binary data of variables is transferred over I2C.

This is a good tutorial: Nick Gammon's Tutorial about I2C

---
Tags: arduino-uno, i2c, string, data-type
---


title: Why analogue pins affect each other?

text:
# Question
Title: Why analogue pins affect each other?
I have a sensor and it generates an analogue signal.

I am reading all analogue data and sending it to my computer.

```
uint8_t sensors[] = { A0,A1,A2,A3,A4,A5,A6 };
const int len = sizeof(sensors) / sizeof(sensors[0]);
void loop(void)
{
    for (size_t i = 0; i < len; i++)
    {
        auto sensor = sensors[i];
        int sensorValue = analogRead(sensor);
        // Convert the analogue reading (which goes from 0 - 1023) to a voltage (0 - 5V):
        float voltage = sensorValue * (5.0 / 1023.0);
        char t[100];
        sprintf(t, "%d:%d$\n", sensor, sensorValue);
        uint8_t t1[100];
        //PrintSerial.println(t);
        memcpy(t1, t, 100);
        wifi.send(t1, strlen(t));
    }
    delay(300);
}

```

I plotted the analogue reading. Why does the graph look like this?

# Answer
This is to be expected.

The other pins have nothing connected to it, so their voltage is floating.

The Arduino MCU only has a single ADC. To read the different analog pins, it uses a multiplexer to connect the pin you want to read to the single ADC. The ADC inside the MCU have a "sample and hold" capacitor inside it.

To read the voltage at the pin, it will connect the pin, to charge the sample and hold capacitor. It will then disconnect and measure the voltage of the sample and hold capacitor, one bit at a time.

So in your case, by reading the voltage at the connected pin, it will charge the capacitor. It will then read the unconnected pins. But because nothing is connected the sample and hold capacitor will stay at about the same voltage, because the unconnected pin will neither charge, nor discharge it.

Measuring the voltage on the sample and hold capacitor will slightly lower this voltage, so that's why in the graph the lines will be lower than the previous measurement.

PS Also, because all the pins are placed in a breadboard, you'll have some capacitive coupling between the adjacent pins.
> 11 votes

# Answer
The acc is really a little capacitor. As you switch channels, the charges in the acc capacitor get carried from one input channel to the next. If the next input channel is of very high impedance, or very low capacitance, the charges on the acc capacitor dominate and its voltage changes little.

In addition, poor code can cause it too - usually from a lack of sufficient time for the add to complete.
> 0 votes

---
Tags: sensors, arduino-nano, analogread, adc
---


# Question
Title: Can I port a project built on Arduino Uno to a standalone ATmega328 using the exact same code?
I'm building an IoT power usage monitor in which the data is logged using a RTC and an SD card module and a web app hosted on an ESP8266 gives access to this data. My question is can I use the exact same code (with libraries like "ESP8266.h") on a standalone ATmega programmed using Arduino as ISP?

# Answer
> 2 votes
Almost all of my projects are roll-your-own-duinos with Atmega 328p chips, with code generated for an "Arduino/Genuino Uno" board. Many of them use an ESP8266-01 board as a WiFi interface. I either run the entire board at 3.3v or use a daughter-board that interfaces the ESP to a 5v environment.

If you're porting code from an actual Arduino Uno, there is nothing to do except to make sure your pinouts are the same between the Arduino and the RYO-duino. Otherwise, make all your pin definitions constants and group them together in such a way (e.g. with #ifdef / #else / #endif) that you can easily enable one or the other group just before you compile.

Update:

> There's a bit more required, for example, the clock rate needs to match or the timing will be off ...

I did gloss over the power & clock since the question hadn't asked about departures from the Uno's design. But yes, a RYO will need a compatible power supply and a matching clock rate, to be able to assume an arbitrary sketch could be run on it successfully. To make the RYO look like an UNO, it will need 5v power and a 16 MHz crystal, just as the Uno design provides.

If a RYO is designed be other than like an Uno, considering power source, clock rate, fuse options, DIP instead of an SMT, then there is nothing to support the supposition that a port from an Uno could succeed *without* modifying the code for those differences.

# Answer
> -1 votes
You can run any code on an ATMEGA328P that you can run on an Arduino Uno. For maximum compatibility, you would configure the ATMEGA328P with a 16Mhz crystal/resonator. There are instructions for using an Arduino Uno as an ISP for programming other devices, many of which require a Uno with a DIP version of the ATMEGA chip which can be removed. What you cannot do is directly run code for an ESP8266 on an ATMEGA328P.

# Answer
> -1 votes
Yes, it might work. But as a minimum you should check that the following is mapped between the two in a compatible way:

1. Pinout and configuration of pins. ESP8266 allows INPUT\_PULLDOWN in some pins, whereas ATmega328 doesn't.
2. Use of timers and interrupts. ESP8266 accepts "true" interrupts on all I/O pins, whereas ATmega328 only accepts them in 2 pins (although you can use Pin Change Interrupts (PCIx), which are far less powerful than "true" External Interrupts (INTx)). Also, ESP8266 accepts HIGH level interrupts, whereas ATmega328 doesn't (even on INT-capable pins).
3. Use of specific ESP8266 libraries which won't work at all on an ATmega328

The Arduino library ports for ESP8266 may work as expected out of the box, it may require minor tweaks, or it may require a major revamp of key code fragments. It's difficult to say without seeing the code.

---
Tags: arduino-ide, wifi, atmega328, avr, avr-toolchain
---


# Question
Title: Attiny85: Watchdog does not initialize properly when using switch(case)
I have a project in which I am putting my ATtiny85 to sleep. Here is the watchdog configuration (in the setup) that works just fine:

```
void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( LED_PIN, INPUT );
  pinMode( STATUS_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );

  /*** Setup the WDT ***/

  /* Clear the reset flag of watchdog interrupts, so that they are available again. */
  MCUSR &= ~(1<<WDRF);

  /* Enable configuration changes */
  WDTCR |= (1<<WDCE) | (1<<WDE);

/*
WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                         Oscillator Cycles     VCC = 5.0V
  0         0      0        0             2K (2048) cycles       16 ms
  0         0      0        1             4K (4096) cycles       32 ms
  0         0      1        0             8K (8192) cycles       64 ms
  0         0      1        1            16K (16384) cycles    0.125 s
  0         1      0        0            32K (32768) cycles    0.25 s
  0         1      0        1            64K (65536) cycles    0.5 s
  0         1      1        0            128K (131072) cycles 1.0 s
  0         1      1        1            256K (262144) cycles 2.0 s
  1         0      0        0            512K (524288) cycles 4.0 s
  1         0      0        1            1024K (1048576) cycles 8.0 s
*/
  /* set new watchdog timeout prescaler value */
  WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

```

Here is the function that actually puts my microcontroller to sleep:

```
void enterSleep(void)
{
//  /* disable all interrupts */
//  cli();
  lcd.clear();
  lcd.print("Asleep...");

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
  sleep_enable();
  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );
  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);
}

```

Then I decided to do a switch case construction, so that I won't have to change manually `WDTCR` register each time I want to change the sleep time. So here is my new setup code:

```
int sleepTime = 0;

void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( IN_PIN, INPUT );
  pinMode( STATUS_PIN, OUTPUT );
  pinMode( DEBUG_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );
  digitalWrite( DEBUG_PIN, LOW );

  /*** Setup the WDT ***/
//  sleepDevice.watchdogInit();
    /*** Setup the WDT ***/
    /* Clear the reset flag of watchdog interrupts, so that they are available again. */
    MCUSR &= ~(1<<WDRF);

    /* Enable configuration changes*/
    WDTCR |= (1<<WDCE) | (1<<WDE);

  /*
  WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                           Oscillator Cycles     VCC = 5.0V
    0         0      0        0             2K (2048) cycles       16 ms
    0         0      0        1             4K (4096) cycles       32 ms
    0         0      1        0             8K (8192) cycles       64 ms
    0         0      1        1            16K (16384) cycles    0.125 s
    0         1      0        0            32K (32768) cycles    0.25 s
    0         1      0        1            64K (65536) cycles    0.5 s
    0         1      1        0            128K (131072) cycles 1.0 s
    0         1      1        1            256K (262144) cycles 2.0 s
    1         0      0        0            512K (524288) cycles 4.0 s
    1         0      0        1            1024K (1048576) cycles 8.0 s
  */

  switch( sleepTime ){
    case 0:
      WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
    case 1:
      WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
      break;
    default:
      WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
  }

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

```

The `enterSleep` function is not changed. But this time sleeping does not work at all! In fact, ATtiny sort of freezes. Does any one has any idea why it is so? To me it looks like the Arduino IDE is confused with switch case instruction, but maybe there is something wrong with my code...

# Answer
> 1 votes
Alright, thanks to you guys I fixed the issue. The main thing is that any changes in the configuration have to be made within 4 cycles after the CONFIG ENABLE bit is set. It is done with this instruciton:

```
/* Enable configuration
WDTCR |= (1<<WDCE) | (1<<WDE);

```

Now switch works like a charm. So the final code for watchdog setup looks like this:

```
void Sleeper::watchdogInit( void ){
    /*** Setup the WDT ***/
      /* Clear the reset flag of watchdog interrupts, so that they are available again. */
      MCUSR &= ~(1<<WDRF);

    /*
    WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                             Oscillator Cycles     VCC = 5.0V
      0         0      0        0             2K (2048) cycles       16 ms
      0         0      0        1             4K (4096) cycles       32 ms
      0         0      1        0             8K (8192) cycles       64 ms
      0         0      1        1            16K (16384) cycles    0.125 s
      0         1      0        0            32K (32768) cycles    0.25 s
      0         1      0        1            64K (65536) cycles    0.5 s
      0         1      1        0            128K (131072) cycles 1.0 s
      0         1      1        1            256K (262144) cycles 2.0 s
      1         0      0        0            512K (524288) cycles 4.0 s
      1         0      0        1            1024K (1048576) cycles 8.0 s
    */

    switch( sleepTime ){
        case 0:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_500:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 1<<WDP0 ;
            break;
        case MSEC_250:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 1<<WDP2 | 0<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_125:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 1<<WDP0 ;
            break;
        case MSEC_64:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
        case MSEC_32:
            /* Enable configuration changes*/
            WDTCR |= (1<<WDCE) | (1<<WDE);
            WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
            break;
    default:
      /* Enable configuration changes*/
      WDTCR |= (1<<WDCE) | (1<<WDE);
      WDTCR =  0<<WDP3 | 0<<WDP2 | 1<<WDP1 | 0<<WDP0 ;
      break;
    }

```

# Answer
> 0 votes
Try this for your sleep function...

```
void enterSleep(void)
{
  lcd.clear();
  lcd.print("Asleep...");

  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );

  /* disable all interrupts, if we get interrupted we might timeout the WDT */
  cli();

  /* Reset the watchdog counter so we know that we are starting at 0 */
  wdt_reset()

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */

  sleep_enable();
  sei();
  /* Now enter sleep mode. */
  sleep_cpu();
  cli(); // Make sure we have time to disable WDT before we get reset

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  sei();

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

}

```

---
Tags: attiny, code-review, sleep, switch
---