# Question
Title: How to fix: Invalid conversion from 'const char*' to 'char*' [-fpermissive]
I'm trying to upload the code from here to work with an ESP8266. So I copy/pasted the code to the Arduino IDE and I get this error:

> C:\Program Files (x86)\Arduino\libraries\WiFi\src/WiFi.h:79:9: error: initializing argument 1 of 'int WiFiClass::begin(char\*, const char\*)' \[-fpermissive\]
>
> int begin(char\* ssid, const char \*passphrase); ^
>
> exit status 1 invalid conversion from 'const char\*' to 'char\*' \[-fpermissive\]

Can anyone help me with this?

# Answer
> 4 votes
This `begin()` method expects a modifiable character array as its first argument. That's what you should provide:

```
char ssid[]           = "YOUR_SSID";      // this is changed
const char* password  = "YOUR_PASSWORD";  // this is fine
[...]
WiFi.begin(ssid, password);

```

# Answer
> 2 votes
The location where you are calling the function begin, has as first parameter a parameter of type const char\* instead of char\* ... remove the const from this argument type.

Probably you have something like

```
const char* s = ....

...

...begin(s, ...)

```

Change class s to

```
char* s = ...

```

---
Tags: arduino-ide, esp8266
---


# Question
Title: Conflict between UART serial transmission and timer interrupt Arduino MEGA
I have a small problem with collision between handling serial transmission and executing things in timer interrupt.

I'm doing program which communicates with PC. It transmits and receives as well and received values are computed in timer interrupt and then transmitted to PC. I have also a LCD for simple debugging state of variables.

My question is generally about influancing uart transmision and timer interrupts each other, but I paste part of my code to better discribing my issue:

```
float Kr;
float Tp=0.05;
float Ti;
float Td;
float yref;

void setup() {
lcd.begin(16,2);
 Serial.begin(115200);
lcd.clear();

 analogReference(DEFAULT);

   Timer1.initialize(50000);
   Timer1.attachInterrupt(Myfunction);

 }

  void loop() {

  while(1)
  {

if(Serial.available() > 0)
{
 received = (char)Serial.read();
  if(received== 'a')
  {
    Serial.print(y);  // Here uC transmits to PC
    Serial.print('b');
  }
  if(received == 'w')
  {
    yref_str = Serial.readStringUntil(';');  //uC receives datas from PC
   // yref = yref_str.toFloat();
  }
  if(received == 'x')
  {
    Kr_str = Serial.readStringUntil(';');  //uC receives datas from PC
    //Kr = Kr_str.toFloat();
  }
  if(received == 'y')
  {
    Ti_str = Serial.readStringUntil(';');  //uC receives datas from PC
    //Ti = Ti_str.toFloat();
  }
  if(received == 'z')
  {
    Td_str = Serial.readStringUntil(';');  //uC receives datas from PC
    //Td = Td_str.toFloat();
  }

}

 //Conversion string to float
 yref = yref_str.toFloat();
 Kr = Kr_str.toFloat();
 Ti = Ti_str.toFloat();
 Td = Td_str.toFloat();

//Simple displaying some of  variables values
  lcd.home();
  lcd.print("Process ");
 lcd.setCursor(0,1);
 lcd.print("yref=");
 lcd.print(yref);
 lcd.setCursor(9,1);
 lcd.print(" ");
 lcd.setCursor(10,1);
 lcd.print("Kr=");
 lcd.print("    ");
 lcd.setCursor(12,1);
 lcd.print(Kr);
 }
 }

  void Myfunction()
  {
     //here the datas are computed
  }

```

Transmition bases on kind of frame. When it gets from PC proper char sign it sends datas or receives datas. The frame has ';' sign at the end.

The main thing is that when I set values of variables: float Kr, Ti, Td at the beginning of program, in declaration section (not by serial port) it works perfectly. problem appears when I don't set value at the beginning (just declare likes above) and try to set it via serial port the situation is following: I can see correct values of those variables on LCD (exactly what I send from PC to arduino) but they don't get to Myfunction (function which is executed within timer interrupt) so actually they are 0 continually.

I don't give whole code for "Myfunction" because this function works properly, for sure. I don't change anything since good working program version. Change is only adding serial transmission.

I tried to declare variables as volatile but it didn't solve the problem.

Anyone did have any experience with such problems??

***Update:***

I paste code of whole program, as you asked me for: It looks like below

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

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

#define Max 127
#define Min -128

/*float Kr;
float Tp=0.05;
float Ti;
float Td; */
/*float Kr = 0.19;
float Tp=0.05;
float Ti = 0.91;
float Td = 0.19;*/
volatile float Kr;
volatile float Tp=0.05;
volatile float Ti;
volatile float Td;
float yref= -50;
float y;
float ep_p, ep_i, ep_d, u_b;
float U_pr, U_int, U_intp, U_ip;
float U_d, Ui_d, Ui_d_pop, U_d_pop;
int Upwm;
float u_b_OGR;
float b=1;
float c=0;
float Tdf;

float ep_a;
float Tt;
float U_a;
int out=11;
int inp=A7;
int x;
boolean state;

 String Kr_str, Ti_str, Td_str, yref_str;
 char received;

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

analogReference(DEFAULT);
Timer1.initialize(50000);
Timer1.attachInterrupt(Myfunction);

U_int=0;
U_intp=0;
Ui_d_pop=0;
U_d_pop=0;
y=0;
U_a=0;

 state=0;

}

void loop() {

if(Serial.available() > 0)
{
  received = (char)Serial.read();
  if(received == 'a')
  {
    Serial.print(y);
    Serial.print('b');
  }
  if(received == 'w')
  {
    yref_str = Serial.readStringUntil(';');
   // yref = yref_str.toFloat();
  }
  if(received == 'x')
  {
    Kr_str = Serial.readStringUntil(';');
    //Kr = Kr_str.toFloat();
  }
  if(received == 'y')
  {
    Ti_str = Serial.readStringUntil(';');
    //Ti = Ti_str.toFloat();
  }
  if(received == 'z')
  {
    Td_str = Serial.readStringUntil(';');
    //Td = Td_str.toFloat();
  }

}
yref = yref_str.toFloat();
Kr = Kr_str.toFloat();
Ti = Ti_str.toFloat();
Td = Td_str.toFloat();

lcd.home();
lcd.print("Process");
lcd.setCursor(0,1);
lcd.print("yref=");
lcd.print(yref);
lcd.setCursor(9,1);
lcd.print(" ");
lcd.setCursor(10,1);
lcd.print("y=");
lcd.print("    ");
lcd.setCursor(12,1);
lcd.print(y);

}

void Myfunction()
{

Tt=0.3*Ti;
Tdf=Td/10;

y=analogRead(inp);
y=y/4;
y=y-128;

ep_p=b*yref-y;
ep_i=yref-y;
ep_d=c*yref-y;
U_pr=Kr*ep_p;
U_int=U_ip*Tp+U_intp;
U_ip=ep_i*(Kr/Ti)+U_a;
U_intp=U_int;
Ui_d=ep_d*Kr;
U_d=(Td/Tdf)*Ui_d-(Td/Tdf)*Ui_d_pop-U_d_pop*exp(-Td/Tdf);
Ui_d_pop=Ui_d;
U_d_pop=U_d;
u_b=U_pr+U_int+U_d;

if (u_b > Max)
 {
 u_b_OGR=Max;
}
else if (u_b < Min)
{
  u_b_OGR=Min;
}
else if (u_b>=Min && u_b<=Max)
{
u_b_OGR=u_b;
}

ep_a=u_b-u_b_OGR;
U_a=ep_a*(1/Tt);

Upwm=(int)u_b_OGR+128;
analogWrite(out,Upwm);

}

```

# Answer
> 1 votes
When you say that something is working for sure, then there is a big chance that the problem is in that part. If the problem was somewhere else, then perhaps you could find the problem yourself.

Interrupts are executed one after another (with a few exceptions). Things run smooth when all interrupt routines are as short and as fast as possible. You have no control over the interrupt routine of the serial communication in the Serial library, but at least your own interrupt function should be as short as possible.

Please show us a sketch that has the problem. You have removed the most important part.
If for example your interrupt function calls a Serial function, then it can go wrong because the Serial library uses interrupts itself. If your interrupt function takes longer than the interrupts from receiving data at 115200 baud, then characters could be missed. The keyword 'volatile' should be used in a proper way. The Arduino Mega has a 8-bit microcontroller, that means that when handling an 16-bit or 32-bit variable an interrupt could occur while that variable is read or writting only halfway. And so on, and so on.

**Update**
You have shown the complete sketch, and the interrupt function 'myFunction' takes a very long time to do all those calculations.

The 'Kr', 'Ti' and 'Td' are written in the loop, and used in 'Myfunction' which is an interrupt routine. They are float variables that are 4 bytes long. That means that 'Myfunction' could be executed when one of those variables are written only halfway. It is better to disable interrupts when writing those variables. To keep disabling the interrupts short, don't disable interrupts when calling .toFloat(). Use temperary variables.

```
float yref_temporary = yref_str.toFloat();
float Kr_temporary = Kr_str.toFloat();
float Ti_temporary = Ti_str.toFloat();
float Td_temporary = Td_str.toFloat();

noInterrupts();
yref = yref_temporary;
Kr = Kr_temporary;
Ti = Ti_temporary;
Td = Td_temporary;
interrupts();

```

I think you have to make 'yref' volatile as well.

The Serial input is 115200 baud, that can be an interrupt every 87µs.
The Timer1 Myfunction runs every 50ms.
The Myfunction takes more than 600µs.

I did not measure the timing of 'Myfunction'. I calculated it for a rough number. 5 float divisions = 5\*70µs. 11 float multiply = 11\*7µs. 10 float substractions or additions = 10\*7µs. Plus analogRead of 112µs. Plus a few more, that adds up to at least 600µs. It could be about 1ms.

There might be more conflicts.
The baudrate is high, and the Serial.readStringUntil is slow because it uses a String object.
There is no error checking for the received values.
The four .toFloat are always called, even when there was no serial data received.
Printing to the lcd display is also done every time the loop runs. There is no need to update the slow LCD display hundreds of times per second. That could be slowed down with millis.

Conclusion: Your 'Myfunction' is a real interrupt routine. When that is busy, the other interrupts have to wait. Since it takes more than 600µs, the Serial interrupts could be missed.
Perhaps a software timer with millis is accurate enough for the calculations. To be able to use millis, the Serial.readStringUntil can no longer be used.

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


title: Listen for specific frequency

text:
# Question
Title: Listen for specific frequency
I’m trying to build a custom baby monitor for my wife who is deaf. It needs to detect loud noises and listen for a specific series of tones from a feeding pump our daughter uses. It will then send a radio signal to the other room to trigger a bed shaker.

I do have a loop which samples the **MAX4466** microphone and uses a “peakToPeak” calculation to determine volume, which I can use to trigger for loud noises (pasted below). However, **I cannot figure out how to determine the frequency of a noise sample.** I’ve tried searching for other sketches and tutorials that would work, but haven’t found anything. The feeding pump, when it has an error puts out a series of tones which alternates between 4.1 kHz and 2.1 kHz. What I wanted to do is see if the first tone is sounding, and then if the second tone shows up within a couple seconds afterwards, then it would trigger sending the signal to the other device.

I’ve tried for two days now to find a way to determine the frequency, but haven’t figured it out. Any help would be *greatly* appreciated. The closest I was able to get was this: Instructables - Arduino Frequency Detection, but when I use this script, the Arduino can no longer do `analogRead()` to get the status of various setting knobs and such I have on the device.

The script I use to get the sound level / loudness is:

```
  #define micPin 0                      // Microphone
  const int sampleWindow = 96;          // Sample window width in mS (50 mS = 20Hz)
  unsigned int sample;
    while (millis() - startMillis < sampleWindow) {
      sample = analogRead(micPin);
      // Check peakToPeak mins and maxs
        if (sample < 1024) {
          // toss out spurious readings
           if (sample > signalMax) { signalMax = sample; }          // save just the max levels
           else if (sample < signalMin) { signalMin = sample; }     // save just the min levels
        }
    }
    peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude

```

# Answer
As stated in previous answers, frequency measurement is unlikely to be reliable because the microphone is going to pick up ambient noise, which is a combination of many individual frequencies. You want instead to see how much sound amplitude you have at the specific frequency of the feeding pump. Fourier analysis seems like the natural tool for the job.

However, a Fourier transform is heavy math, and overkill for your application. You are only interested in the Fourier amplitude at one specific frequency. Computing that single amplitude is way easier and faster than doing a full-fledged Fourier transform.

My preferred method for doing that is called homodyne detection. It is fast enough to be done *in real time* by an Arduino Uno sampling at 9.6 kHz. Basically you multiply the input signal by both a sine and a cosine at the target frequency, then you low-pass filter both products. The two resulting signals are the real and the imaginary part of the complex amplitude you are looking for.

Here is a small program of mine that does *almost* exactly what you are looking for: homodyne.ino. It is set for one specific frequency (1 kHz, but it's trivial to change), and you will have to adapt it to be able to change the target frequency between 4.1 and 2.1 kHz.
> 3 votes

# Answer
You can use a DFT(Discrete Fourier transform) that just checks the component frequency magnitude at 4.1kHz and 2.1kHz. Below is some code that works for my Arduino UNO. When I put a signal generator on A0 with a 2.3V(peak to peak) sine wave, the result goes above 0.5 at the respective frequencies.

```
float Single_Point_DFT(int16_t inputArray[], int startingIndex, int endingIndex, float sampleFreq, float freqToSampleFor){
  float N = endingIndex - startingIndex + 1; //N=number of samples
  float k = freqToSampleFor * N / sampleFreq;
  float radiansPerSample = 2.0 * 3.14159 * k / N;

  float RealSum = 0;
  float ImaginarySum = 0;
  for (int n = 0; n <= endingIndex - startingIndex; n++){
    float angle = n * radiansPerSample;
    float voltage = inputArray[startingIndex + n] * (5.0 / 1023.0);

    RealSum += voltage * cos(angle);
    ImaginarySum -= voltage * sin(angle);
  }

  return sqrt(RealSum*RealSum + ImaginarySum*ImaginarySum) / N;
}

const int analogInPin = A0;
uint32_t startTime_uS;
uint32_t endTime_uS;

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

void loop() {
  int16_t values[128];

  while(1)
  {
    startTime_uS = micros();
    for(uint8_t n = 0; n<128; n++)
    {
      values[n] = analogRead(analogInPin);
    }
    endTime_uS = micros();

    float sampleFreq = 128.0*1000000.0/(endTime_uS - startTime_uS);
    float result = Single_Point_DFT(values, 0, 127, sampleFreq, 2100);
    Serial.print(result);
    Serial.print(", ");
    result = Single_Point_DFT(values, 0, 127, sampleFreq, 4100);
    Serial.println(result);
  }
}

```

This calculation is pretty slow due to the float arithmetic and the sine/cosine calculations, But is is fast enough if the beeps last longer than a quarter of a second.
> 1 votes

# Answer
With a microphone listening for one frequency in ambient audio you have to do far more than just count cycles or measure time between crossings.

You have to sample a burst of audio into a buffer at a minimum of double the rate of the highest frequency you are interested in. Then you need to analyse that audio sample to determine the amplitudes of the different frequencies within it. FFT (Fast Fourier Transform) is the most popular method of doing that, and there are integer maths based libraries and examples around on the internet suitable for running on an Arduino.
> 0 votes

# Answer
A few ways, fft, 1057, or sin multification. Fft is quite calculation and space intensive, even in interfere form. For the detection of a known frequency, 1057 can be very efficient.

Multification is iterative so space and mips efficient. But you will need to filter and it detects with a delay.

A more efficient way is hardware filtering followed by rectification .
> 0 votes

---
Tags: arduino-uno, audio, frequency
---


# Question
Title: How can I find and specify the address of my adafruit MMA8451 accelerometer in arduino code?
I am trying to use four of the same accelerometer on the same bus and acquire data from each of them using an SD card. Because I am using four of the same accelerometer I need to be able to differentiate between them and I dont know how to find their specific address. I need the specific address so I can tell my arduino which accelerometer to pull data from. essentially it would pull data from 1 then 2 then 3 then 4 and loop back to 1.

# Answer
> 1 votes
You can't have 4 of those on one bus. The maximum is 2.

The pin `SA0` defines the least significant bit of the I2C address. From the datasheet:

> 7 | SA0 | I2C least significant bit of the device I2C address, I2C 7-bit address = 0x1C (SA0 = 0), 0x1D (SA0 = 1).

In fact, as it states on the Adafruit website (if you'd care to read it sometime):

> A is the I2C Address select pin. By default this is pulled down to ground with a 10K resistor, for an I2C address of 0x1C. You can also connect it to the 3Vo pin for an address of 0x1D

If you want more than 2 you will either have to have multiple I2C busses or use an I2C multiplexer (such as this one) to select different branches on the same bus.

# Answer
> 0 votes
Power them on one at a time. They don't take much current to run so a GPIO pin would be more than sufficient.

---
Tags: sensors, sd-card, accelerometer
---


# Question
Title: Can't get constant reading with load cells
I'm really a newcomer to arduino and I'm trying to build a scale with four SEN-10245 load cells and a HX711. My issue is that I can't get constant readings in the serial monitor and I'm not sure if my coding is right or if I did the right setup. I made the following setup, based on some examples I found online:

The code I'm using is as follows:

```
    #include <hx711.h>
    Hx711 scale(A1, A0);
    void setup() {
    Serial.begin(9600);
    }
     void loop() {
     Serial.println(scale.averageValue());
     delay(200);
    }

```

link for the library github: https://github.com/aguegu/ardulibs/tree/master/hx711

Please help me, i'm a total beginner.

# Answer
> 2 votes
Assuming everything is hooked up correctly, your issue is likely related to electromagnetic noise (aka electromagnetic interference, EMI). Load cells output very small voltages, which is why you need the HX711 amplifier. Your long wires are essentially acting as antennas, picking up the electromagnetic noise in the room. One easy way to reduce the noise is to twist the wires together. You can also shield the wires by wrapping them with aluminum foil and attaching the foil to ground.

Making the wires much shorter would likely also help. That would be a good test to see if it helps.

The power supply could also be creating noise. I have found that the 5v line coming from a computer is often quite noisy. This is harder to fix, but an easy way to test if this is the issue is to power the Arduino with a 9V battery. Just make sure you plug it into the Vin pin, not the 5V pin, because the 9V needs to be regulated down to 5V.

---
Tags: programming, software, calibration
---


# Question
Title: How can I get Serial.print to print a variable thats a char?
I'm trying to write a function as part of my code, and the function basically has to write the name of a parameter, but I can't get it to print properly to the screen. Here is what I've got:

```
void dataprint(char parameterName, float dataNum, char unitName);
{
 Serial.print(",");
 Serial.print(parameterName);
 Serial.print(",");
 Serial.print(dataNum);
 Serial.print(",");
 Serial.print(unitName);
}

```

In the actual program part I have something like this:

```
char temp = "temperature";
float t = tempsensor.readTempC(); // just some number that comes from sensor
char unit = "C";
dataprint(temp,t,unit);

```

Right now in the serial monitor I get a question mark or something like that instead of the name I have saved in parameterName or unitName. I want this function to print the same way something like this would show up:

```
Serial.print(",");
Serial.print("temperature");
Serial.print(",");
Serial.print(c);
Serial.print(",");
Serial.print("C");

```

Thanks in advance for any help.

# Answer
To make your code work, you must use character array pointers. A "char" holds only one character, while "char\*" can point to a string.

```
char foo = 'a';
char *bar = "string with lots of stuff.";

```

So the full code to implement your example is:

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

void dataprint(char *parameterName, float dataNum, char *unitName)
{
  Serial.print(parameterName);
  Serial.print(",");
  Serial.print(dataNum);
  Serial.print(",");
  Serial.println(unitName);
}

void loop() {
  char *temp = "temperature";
  float t = 123.4;
  char *unit = "C";
  dataprint(temp,t,unit);

  while(1)
  {
    //do nothing
  }
}

```

Which prints the following to the serial port:

```
temperature,123.40,C

```
> 3 votes

---
Tags: serial, print
---


title: Certain String Characters To Int

text:
# Question
Title: Certain String Characters To Int
I have a char\* array which looks like this "T 20" and I'd like to extract the "20" and convert it in to an integer. I was thinking of using atoi() but it seems that function will operate on the entire string, not just the bits I want. Memory is a bit tight so is there a function similar to atoi() which allows you to specify which charters to operate on?

# Answer
How about

```
char array[5] = "T 20";
int num = atoi(array+2);

```

This obviously assumes that all your strings are of the same format `"A NN"`. If not, you can try parsing it using `strtok()`. See this excellent answer.
> 4 votes

---
Tags: arduino-uno, programming, esp8266, ide
---


title: Compatibility between shields

text:
# Question
Title: Compatibility between shields
Despite that I am new to Arduino, I am tasked to invent a serious alarm system and I chose Arduino. I study electronics, but virtually I am a software programmer and C is my area of expertise.

I ordered the parts I think I will need and the time is immensely pushing me. The delivery goes slow and it needs to happen before our planned vacation, because we've been robbed several times so far. I need to know if I will need another gadgets to deal with a problem I've discovered suddenly.

> \>

I plan to stack up these 3 shields

1. Arducam-F Shield V2 Camera module shield /w OV2640
2. 3.5" TFT LCD Display Touch Screen Module
3. SIM900 Quad-band GSM/GPRS Shield

From what I've learned the shields 1 and 3 are compatible, as the arducam uses CS/SD, ICSP, VCC, GND, SDA and SCL or according to standard pin out table: I2C\_SCL, I2C\_SDA, SPI\_SCLK, SPI\_MISO, SPI\_MOSI, 9, 10, Reset, 5V, GND and the GPRS shield uses D7 and D0/D1(or D2/D3), 3 I/O ports. For D7.

The arducam however seems to be not stackable and as far as I can not see it is impossible to make it stackable (Maybe even if I drill holes and solder stackable shield headers) So it must be the topmost shield.

What about the LCD shield? I also learned that such shields use a lot of pins, so it is possible that there will be no free pins. I also ordered lots of jumper wires of any kind, if that can help. Maybe I don't need to wire each of the pins in order to make it work or do some extra coding to get it work? I also don't necessarily need the other shields to work while I operate with the screen, so maybe there is a way I can connect/disconnect shields separately with a program or something else I can buy. I have a feeling that this LCD shield will leave no pins for the other shields and I should connect the arducam on another way since it is not stackable.

# Answer
> 4 votes
Its not just a question of the stackability of the shields and the clash of pins you also need to consider what the shields do.

Stacking the GSM shield under the LCD is going to restrict is tx/rx power unless you have an external aerial.

The LCD will require a large amount of memory and processing power, a 3.5" inch display is really going to push an Uno to the edge, you aren't going to get much time for servicing the GSM and camera.

The camera is also going to require a large amount of RAM and processing time to handle still images. If you are processing video then I really doubt you will be able use the other shields.

You don't say if you are experienced in Embedded development. Its different to Linux or Windows dev where resources are almost limitless. If you don't have experience then you might find the transition quite hard.

Your question was are they compatible, I don't have the evidence but I would say no because of the resources they consume. Sorry I can't see this project going anywhere fast. :(

---
Tags: arduino-uno, lcd, shields, gsm
---


title: Linear acceleration from MPU 6050

text:
# Question
Title: Linear acceleration from MPU 6050
When reading the MPU 6050 has accelerometer and gyro, I assumed it was linear acceleration, but now I second guess that. From this video https://www.youtube.com/watch?v=qmd6CVrlHOM it seems like they are using acceleration and gyro to make one rotation direction. I need to know what direction the mpu is moving, not just a rotational value. Is there a way to extract this information?

# Answer
> 1 votes
The MPU6050 has an accelerometer and a rate gyro (which tells you how fast it is rotating). The accelerometer will tell you which direction is down and in a motionless situation, that is all the information you have.

You'll probably want something like the MPU9150, it has a compass, which will give you the directional information you're asking for.

# Answer
> 0 votes
The MPU6050 has accelerometers in the x, y, and z axis. When placed on flat surface with no acceleration, you should get 0g (or whatever unit it uses, I cannot remember off the top of my head) in the x and Y directions, and 1g in the z axis. By continuously polling these values, you can find out the linear acceleration of each axis at a given moment in time.

What you saw is probably because the chip also has three Gyroscopes, for measuring rotational acceleration and speed. The chip can do both.

---
Tags: accelerometer, mpu6050, gyroscope
---


# Question
Title: Do AVR delay functions (_delay_us() and _delay_ms()) use timers?
I'm trying to determine if the AVR delay functions `_delay_us()` and `_delay_ms()` use timers in such a way that I can't use those timers for other functionality in my code. If so, what timer does it use?

For reference I'm using an Arduino Uno with ATmega328, but I imagine if it's an AVR function it must work similarly on other devices.

# Answer
> 3 votes
No, these macros expand to calls to `__builtin_avr_delay_cycles()`, which are compiled into delay loops. It should be noted that:

* the arguments to these macros should be compile-time constants, they can be floating point
* the macros are cycle-accurate, e.g. `_delay_us(0.125)` will take exactly two CPU cycles on an Uno
* whereas the *CPU time* used by the call is exactly what you ask for, the *physical time* will be larger if the call gets interrupted.

# Answer
> 0 votes
No.

The long answer is that you can delay via timers, a little bit more painfully within the Arduino framework, or much more efficiently if you are willing to move outside of the arduino framework.

I wrote a set of systick clones for many of the popular 8bit mcus precisely for that.

---
Tags: atmega328, timers, avr
---


# Question
Title: Code flow execution between loop() and timer interrupts
My platform is the Arduino DUE. I know that the timer counts up to a certain value, then generates an interrupt. In the Arduino DUE, you can specify the timer value. In other words, you can specify the frequency of the intterupts. You can do this via the `TC_SetRC(tc, channel, rc)` function.

My question is how code flows in general. Obvisouly the arduino runs the setup function first. After that it jumps to loop. But when does tghe timer starts counting down? When you first jump to loop? Can you figure out how many instructions will be executed in the loop function, before a call to a timer interrupt is performed, for the given frequency you have specified?

After the interrupt is fired, all the code in the interrupt is run. Then code flow jumps back to loop()? And when the timer starts counting again? At the same time the code jumps to loop?

If you set up the timer interrupt frequnecy too high, do you run the risk of having code in you loop functin not run at all? (If, for example, you have lots of code inside the loop()).

In that case, would it be wise to put code that you would generally put inside the loop(), inside a timer interrupt?

# Answer
> 2 votes
The timers starts when it is enabled. Either explicitly or via one of The calls to timer functionality.

Once the interrupt fires, current execution is preserved and the isr execution starts. Once you exit the isr, the loop execution resumes from where it pauses

Yes, if your use fires too frequently or takes too long to execute your loop may never gets executed.

---
Tags: arduino-due, interrupt, timers
---


# Question
Title: High Precision Temperature Sensor LMT70 connection to arduino mega
How can I connect an LMT70 temperature sensor (4Pins) to Arduino Mega board for atmospheric temperature measurement. LM35 sensor has got only 3 pins and connections are known. But LMT70 high precision sensor got 4 pins. How to connect it to arduino mega board Please help. Thank you.

# Answer
> 2 votes
Every electronics component has a document that describes it. It is called a "datasheet".

This is the page for the LMT70: ti.com LMT70
The red text is for the datasheet as pdf document, or else you can use the tab "Online datasheet", and the datasheet can also be found under the tab "Technical documents".

According to the datasheet it works with 5V, you can use it with the Arduino Mega (which is a 5V Arduino board). Connect the analog output of the sensor to an analog input of the Arduino Mega.

If you don't use the T\_ON, then the datasheets says: "Tie this pin to VDD if not used". That means you can connect T\_ON to 5V.

Do you have the chip (the sensor) only, or do you have a module with the sensor on it ?

Since the sensor has an anlog output, the accuracy depends not only on the sensor but also on the Arduino and the Arduino voltage reference. If you need a highly accurate temperature measurement, then you better buy a digital temperature sensor. For example the Si7051.

I suggest to use the 2.56V Internal Analog Voltage Reference.
The sensor has 1375.2mV output at -55°C and 302.8mV at 150°C.

```
const float aref = 2.56;  // adjust it to the actual AREF voltage
int adc_value = analogRead(A0);
float voltage = float(adc_value) * aref / 1024.0;

float t1 = voltage - 302.8;  // get rid of voltage offset
float t2 = t1 * (150.0 + 55.0) / (1375.2 - 302.8); // match range
float temperature = 150 - t2;  // negate and offset.

```

When you measure the AREF pin with a good multimeter and fill in the correct voltage in the calculation in the sketch, then you can get 1°C accuracy for the temperature. Perhaps you can get near 0.5°C accuracy, but no more. The sensor is more accurate than the Arduino Mega.

# Answer
> 0 votes
In situations like this, you always start with reading the device datasheet, understand how it works, how to communicate with the device, and then write your code to implement that communications protocol.

That strategy always works, regardless of the specifics of a given device.

---
Tags: sensors, temperature
---


# Question
Title: Convert my if loop code into a switch/case statement
I have made a project where in photosensors constantly read value and if laser is cut by external object, then it beeps the buzzer.

A switch case would make it easy, as suggested by some people. I have written my short code below, can you kindly help me change it?

Converting all `if` loops into a switch/`case` statement.

```
 int sensorPin = A0;
 int sensorPin1 = A1;
 int sensorPin2 = A2;
 int sensorPin3 =  A3;
 int sensorValue0 = 0;
 int sensorValue1 = 0;
 int sensorValue2 = 0;
 int sensorValue3 = 0;
 const int BUZZER = 9;
 const int BUZZER1 = 7;
 const int BUZZER2 = 8;
 const int BUZZER3 = 5;

void setup() {
 Serial.begin(9600);
 pinMode(BUZZER, OUTPUT);
 pinMode(BUZZER1, OUTPUT);
 pinMode(BUZZER2, OUTPUT);
 pinMode(BUZZER3, OUTPUT);
 // put your setup code here, to run once:
}

void loop() {
  sensorValue0 = analogRead(sensorPin);
  sensorValue1 = analogRead(sensorPin1);
  sensorValue2 = analogRead(sensorPin2);
  sensorValue3 = analogRead(sensorPin3);
  Serial.println(sensorValue0);
  delay(100);

  if (sensorValue0>920)
   noTone(BUZZER);
  else
   tone(BUZZER, 500);

  if (sensorValue1>850)
   noTone(BUZZER1);
  else
   tone(BUZZER1, 300);

  if (sensorValue2>850)
   noTone(BUZZER2);
  else
   tone(BUZZER2, 700);
}

```

# Answer
> 4 votes
A switch can only select different discrete values from a single variable. Since you have multiple variables and aren't looking for discrete values you have to use if not switch.

# Answer
> 2 votes
A switch statement wouldn't be appropriate in this case.

You could optimise the code by adding a function that did the work for you and made the main loop look nicer.

```
void readValue (const int& sensorPin, const int& limit, const int& buzzerPin, const int& frequency)
{
  const int value = sensorValue0 = analogRead(sensorPin);
  if (value > limit)
  {
    noTone(buzzerPin);
  }
  else
  {
    tone(buzzerPin, frequency);
  }
}

```

That way you could add as many buzzer and sensors as pins allowed.

# Answer
> 1 votes
Actually, you cannot really rewrite this, due to the `>` operator instead of the `==` operator.

Also you are checking three different variables, and only one variable can be used to check in a switch statement.

However, what you can do is to create a function with parameters like:

```
void set(int sensorValue, int value, int buzzer, int frequency)
{
  if (sensorValue > value)
  {
       noTone(buzzer);
  }
  else
  {
       tone(buzzer, frequency);
  }
}

```

and call:

```
 set(sensorValue0, 920, BUZZER, 500);
 set(sensorValue1, 850, BUZZER1, 300);
 set(sensorValue2, 850, BUZZER2, 700);
 set(sensorValue3, ...); // I think you miss this one

```

# Answer
> 1 votes
Since your conditions looks like :

```
bool condition = variable > someValue;

```

The value of your variable (i.e. *sensorValue*) should therefore be continuous.

However, the *switch* statement is used when the value of our variable is discrete.

You can't consequently use *switch* statements in your code.

# Answer
> 1 votes
" Switch case would make it easy, as suggested by some people."

That's a great example of why free advice can be quite expensive, :)

Unless you are doing something unique, you are better off with your current approach.

edit: with that said, I can see cases where a switch / case structure can be helpful. For example if you need to compare multiple variables through a consistent set of thresholds, one way to do it without making the code too difficult to read would be something like this:

```
THRESHOLD_TypeDef threshold(uint16_t val) {
  if (val < VAL1) return THRESHOLD1;
  if (val < VAL2) return THRESHOLD2;
  ...
  if (val < VALn) return THRESHOLDn;
}

```

where THRESHOLD\_TypeDef is an enumerated type.

and in your code you can write something like this:

```
   switch (threshold(myval)) {
   case THRESHOLD1: do_something1(); break;
   case THRESHOLD2: do_something2(); break;
   ...

```

Its advantage is obviously better readability and consistency: you can apply the same function on different variables to generate a consistent set of "classification".

Its disadvantage is also obvious: for each threshold(), you can only test one set of classification. But you can always create multiple functions to be applied to different variables.

# Answer
> 1 votes
Just for fun, here yet another way to handle the issue: Create a C++ class. This code might seem a bit longer than your original code, but the advantage is if you want to add more functionality, you only have to modify the class.

```
class Sensor {
public:
    Sensor(uint8_t analog_pin, uint8_t buzzer_pin, uint16_t threshold, uint16_t tone_duration)
        : analog_pin(analog_pin), buzzer_pin(buzzer_pin), threshold(threshold), tone_duration(tone_duration)
    {
    }
    void setup() {
        pinMode(buzzer_pin, OUTPUT);
    }
    void loop() {
        sensor_value= analogRead(analog_pin);
        delay(100);
        if (sensor_value> threshold)
            noTone(buzzer_pin);
       else
           tone(buzzer_pin, tone_duration);
    }
protected:
    uint8_t analog_pin, buzzer_pin;
    uint16_t threshold, sensor_value, tone_duration;
};

```

Then, just create an array of `Sensor` objects:

```
Sensor sensors[] = {
    Sensor(A0, BUZZER1, 920, 500),
    Sensor(A1, BUZZER2, 850, 300),
    Sensor(A2, BUZZER3, 850, 700)
};
const uint8_t num_sensors = sizeof(sensors) / sizeof(sensors[0]);

void setup() {
    for (int i = 0; i < num_sensors; i++) {
        sensors[i].setup();
    }
}
void loop() {
    for (int i = 0; i < num_sensors; i++) {
        sensors[i].loop();
    }
}

```

---
Tags: arduino-uno, arduino-ide, project-critique
---


# Question
Title: Is there any good working MODBUS TCP master library available for Arduino?
I would like to connect with Fronius solar inverter through MODBUS TCP with Arduino to READ and WRITE register values only. I want to set the Arduino as master and the Inverter as slave. I want to use only two functions "Read Holding Registers" and "Write Single Holding Register" function code '3' and function code '6' respectively. Is there any good and working library available for these? And also an example.

# Answer
> 4 votes
Check out the library Modbus-TCP on Github. It has the facility for all the function codes as asked. It has provision for Wiznet W5100 and ENC28J60 Ethernet IC. All tested with Arduino Mega. See the well documented example code for the Wiznet module in the library.

For detailed knowledge about the library, read the index.html inside the doc folder of the library.

Here is an example code explaining a few function codes for the Arduino Mega and a W5100 module.

```
/*
  This is Modbus test code to demonstrate all the Modbus functions with
  with Ethernet IC WIZNET W5100

  ModbusTCP is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  ModbusTCP is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with ModbusTCP.  If not, see <http://www.gnu.org/licenses/>.

  Adopted from ModbusMaster for RTU over RS-485 by Doc Walker
  Modified by Narendra Dehury for TCP.
  copyright @ phoenixrobotix.com

*/
#define WIZNET_W5100 1

unsigned int param_value_int[7];
#include <Ethernet.h>

IPAddress ModbusDeviceIP(10, 10, 108, 211);  // Put IP Address of PLC here
IPAddress moduleIPAddress(10, 10, 108, 23);  // Assign Anything other than the PLC IP Address

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE1 };

#include <ModbusTCP.h>

ModbusTCP node(1);                            // Unit Identifier.

void setup()
{

  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);                      // To disable slave select for SD card; depricated.

  Serial.begin(9600);
  delay(1000);
  Ethernet.begin(mac, moduleIPAddress);
  node.setServerIPAddress(ModbusDeviceIP);
  delay(6000);                                // To provide sufficient time to initialize.

}

void loop()
{
  uint8_t result;

  node.setTransactionID(random(100));           // Not necessary; but good to distinguish each frame individually.
  result = node.readHoldingRegisters(1, 12);    // Read Holding Registers

  Serial.println(result, HEX);
  if(result != 0)
  {
    Serial.println("TimeOut");

    delay(6000);
  }

  int len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));// See the length of data packet received.
  for (byte j = 0; j < len; j++)
  {
    Serial.print(node.getResponseBuffer(j));       // Inspect the data.
    Serial.print(" ");
  }
  Serial.println();
  node.clearResponseBuffer();
  delay(100);

  node.writeSingleRegister(5, 3);                  // Write single register
  Serial.println(result, HEX);
  delay(500);

  for (byte i = 0; i < 5; i++)
  {
    node.setTransmitBuffer(i, (i+100));
  }
  node.writeMultipleRegisters(2, 5);               // Write multiple register
  Serial.println(result, HEX);
  delay(500);

  node.writeSingleCoil(20, 1);                     // Write Single coil
  delay(500);

  node.setTransmitBuffer(0, 0b1010101001010101);

  node.writeMultipleCoils(20, 16);                 // Write multiple coils
  delay(500);
  result = node.readCoils(20, 18);
  len = node.getResponseBufferLength();
  Serial.println("Response Length: " + String(len));
  Serial.println(node.getResponseBuffer(0), BIN);

  node.clearResponseBuffer();
  delay(5000);
}

```

---
Tags: tcpip, modbus
---


# Question
Title: Cannot find solution to "variable out of scope"
First C program. Spent a lot of time looking for a solution. KeyPad produces 'char' instead on 'int'. Plus I want to display 'End', thus I wrote the 'main' to to support 'char' and thus had to adapt a 'char' to 'int' conversion work around, line 89 Certainly there are other errors.

```
extern "C"
// Microwave ccp

  #include <Arduino.h>
  #include <stdlib.h>
  #include <string.h>
  #include <inttypes.h>
  #include <Keypad.h>
  #include "TM1637.h"
  #include <TimerOne.h>
class TimingISR
{
public:
    TimingISR();
    bool Enable_interrupts, Disable_interrupts;

  char lead_char, unit_sec, tens_sec, num_min;
  int int_unit_sec, int_tens_sec, int_num_min;
  int Count_Seconds, Remainder, brightness = 4, PowerLevel;   //BRIGHT_TYPICAL = 4, BRIGHT_DARKEST = 0, BRIGHTEST = 7
  bool Colon, PointFlag, Points_enable;
  char data_char;
};

// these are all Clobal Variables
  int pin_Clk = 2; //  or 3 for IC2
  int pin_DIO = 3; //  or 2 for IC2
  int PIN_RELAY = 4;  // controls power on/off to 'cook'
  int PIN_Beeper = 5; // PWM beeps when finished

  int  pos, Remainder, num;
    // Timer variables
  char tempchar;

  // Read Key Pad, continuously
const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
char lastkey;
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'} };// Define the Keymap
byte rowPins[ROWS] = { 9, 8, 7, 6 };  // Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte colPins[COLS] = { 12, 11, 10 };  // Connect keypad COL0, COL1 and COL2 to these Arduino pins.
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );  // Create the Keypad
#define ledpin 13
void setup()
//        Colon = OFF;   PointFlag, Points_enable   ***************************not coded yet
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);
}
void loop()
{    // run repeatedly

   char key = kpd.getKey();
   // if ((key = NO_KEY) || (lastkey = key)); delay(100); exit(0);    }

 {  if (key)  // Check for a valid key.
      switch (key) {

      case ('0'): case ('1' - '0'): case ('2' - '0'): case ('3'-'0'): case ('4' - '0'):  case ('5' - '0'): case ('6' - '0'): case ('7' - '0'): case ('8' - '0'): case ('9' - '0'): //all key integers
 { if ( Count_Seconds > 0 ) // Cooking in progress, thus SHUT DOWN, any numeric key shuts down the power
  {  lead_char = 'C';
     num_min=    'n';
     tens_sec=   'C';
     unit_sec=   'l';
goto CancelPower;
  } //  Short Delay, then Display “A000”
    else
  {     num_min = tens_sec;  // integers: update the 'time' 'stack' as integers
        tens_sec = unit_sec;
        unit_sec =  (key-'0');  // '0' = 30 base 10 etc
        lastkey = key;
        Colon = ON;
goto DisplayAll;   // accumulate time value  // any old num_min_segment fall off
  } }     //
  break;  //---------------------------------------

      case ('#'-'0'):  // Start Heating
      if (lead_char != 'A')
goto OOPS ;
       else  // convert time parts to Count_Seconds
        (  Count_Seconds = int(unit_sec) + int(tens_sec) * 10 + int(num_min) * 60  );
  {       if  (  Count_Seconds > 0 )
TimingISR(  ) ;
          lead_char = 'c'; //  ’c’ooking
          Colon = ON;
          pinMode(PIN_RELAY, OUTPUT);
          digitalWrite(PIN_RELAY, HIGH);  // turn on the heat
          PowerLevel = 10;
  }
   break;  //---------------------------------------

      case  ('*'-'0'):  // Set Power level or default DEFROST Power level
     //unit_sec_segment = a number as a 'segment' value    // a power level manually inserted
{   if ( lead_char ==  'A'  &&   num_min == '0' &&  tens_sec == '0' )
{    if ( unit_sec =  !('0') )         // &&  unit_sec > '0' && unit_sec <= '9' )
 {      int PowerLevel = aoti(unit_sec);
        lead_char = 'P';    //Display "P=n0", n = percent power via duty cycle
        num_min =   '=';
        tens_sec = unit_sec;  //display 'char' as 10's 'percent' value, move number left one place
        unit_sec =  '0';  // insert a zero
 }   else  // power not manually set
 {      PowerLevel = 2;     // 'defrost' = 20 %
        lead_char = 'd';
        num_min =   'E';
        tens_sec =  'F';
        unit_sec =  '_';
 }
goto DisplayAll;
}
   else
//    if ( lead_char != 'A'  ||  num_min != '0' ||  tens_sec != '0' || unit_sec !=  '0' )
goto OOPS ;
}     //end if, of Case “*"
      break;  //---------------------------------------

   lastkey = key;
delay(100);  //100 millisec
}   // End Of Switch Key
}  //  End of If (Key)
//return

// Beginning of GOTO's--------------------------------------
{
OOPS:
     lead_char = 'o';   //Display "ooPS"
     num_min =   'o';
     tens_sec=   'P';
     unit_sec =  'S';   // then Short Delay, then Display “A000”
CancelPower:
      pinMode(PIN_RELAY,OUTPUT);
      digitalWrite(PIN_RELAY, LOW);  // turn off the heat
goto DisplayAll;  //ready to accumulate 'heating' time input
    delay (3000);     //let it display for 3 Count_Seconds, then clear the display
    lead_char = 'A';        //ready to accumulate 'heating' time input
    num_min =   '0';
    tens_sec =  '0';
    unit_sec =  '0';
    Disable_interrupts;
    int Count_Seconds = 0 ;
DisplayAll:

// DisplayAll:  //Would like to put this into the 7 segment display
 // Address each 7 segent unit, one after the other; left to right
{    for ( pos = 0 ; 3 < 4; pos++);
      if ( pos = 0 )
        char_data = lead_char
      if ( pos = 1 )
        char_data = num_min
      if ( pos = 2 )
        char_data = tens_sec
      if ( pos = 3 )
        char_data = unit_sec

if ( char_data='0') ; num = 1; // the 7 segment display 'h' only allows for integers 0 through 15, i.e. HEX characters
if ( char_data='1') ; num = 2;
if ( char_data='2') ; num = 3;
if ( char_data='3') ; num = 4;
if ( char_data='4') ; num = 5;
if ( char_data='5') ; num = 6;
if ( char_data='6') ; num = 7;
if ( char_data='7') ; num = 8;
if ( char_data='8') ; num = 9;
if ( char_data='9') ; num = 10;
if ( char_data='A') ; num = 11;
if ( char_data='B') ; num = 12;
if ( char_data='C') ; num = 13;
if ( char_data='d') ; num = 14;
if ( char_data='E') ; num = 15;
if ( char_data='F') ; num = 16;
if ( char_data='c') ; num = 17;
if ( char_data='H') ; num = 18;
if ( char_data='h') ; num = 19;
if ( char_data='I') ; num = 20; //left vertical 2 segments
if ( char_data='i') ; num = 21;
if ( char_data='L') ; num = 22;
if ( char_data='l') ; num = 23; /right /vertical 2 segments
if ( char_data='n') ; num = 24;
if ( char_data='O') ; num = 25;
if ( char_data='o') ; num = 26;
if ( char_data='P') ; num = 27;
if ( char_data='r') ; num = 28;
if ( char_data='S') ; num = 29; //same as a five
if ( char_data='U') ; num = 30;
if ( char_data='u') ; num = 31;
if ( char_data=' ') ; num = 32;
if ( char_data='=') ; num = 33;
if ( char_data='-') ; num = 34; //dash / minus
if ( char_data='_') ; num = 35; //under score
if ( char_data='[') ; num = 36; /left /bracket
if ( char_data=']') ; num = 37; //right bracket
// there are other usefull, such as "top score", "middle score... "top minus", "bottom Minus",
// which yoou could assign some other othervise unprintable character as a proxy, e.g  the ampersant to display a "top position minus sign"

}
Disable_Interrupts;
  TM1637DisplayAll(uint8_t num, uint8_t pos);
Enable_Interrupts;
}
return(0)
}
}  //  End of void LOOP()

//--------------------------------------

// ----------------------------------------------------

```

# Answer
1. The first line says `extern "C"` but you haven't scoped it, I'm really not sure what you are trying to achieve or if it will work. Personally I would remove that line.
2. "Microwave ccp" come compilers complain if the filename is not right. As far as I know it should be either .cc or .cpp, but its proably just a typo in the comment, because I doubt you would get this far if it was wrong.
3. Pins 2 and 3 for I2C, its normally A4 and A5.
4. Line 58 The reason your commented out code didn't work is `(lastkey = delay)` you should have used equivalence (==) rather than assignment (=).
5. Use function calls rather than goto statements, it isn't the 1970s anymore! :)
6. `int(variable)` is not casting it is creating an integer from variable and then its disposed of when it goes out of scope. `(int)variable` is casting.
7. `for (pos = 0; 3 < 4; pos++);` This will cause you problems, because its an empty loop, does nothing, which means `pos` doesn't have the value you think it does.

Please don't take any of this the wrong way, I'm not a teacher but I need to explain what has gone wrong with you code and how you can fix it. It is not personal criticism, I bet my first program was ten times worse.

You seem to have a misunderstanding of "variable scopes". Put simply a variable can only be 'seen' after the point you declare it and within the immediate curly braces {} and all child braces. e.g.:

```
int GlobalVariable = 1; // Visible through-out the code
void loop ()
{
    int LoopVariable = 2;
    for (int ForVariable = 0 ForVariable < LoopVariable; ++ForVariable)
    {
       ++GlobalVariable;
    }
    Serial.println (ForVariable);  // ERROR
}
void AFunction()
{
    Serial.println(LoopVariable);//ERROR
}

```

You immediate error is you have defined the variable `unit_sec` inside class TimingISR and you are accessing it like a local variable.

Now The way you have defined `class TimingISR` is like designing a car, its fine on paper but you can't drive it until you build one. As far as I can see you haven't instantiated an instance of TimingISR. It sounds complex but you have been doing it for int and char (They aren't classes, but its very similar)

```
int pin_clk = 2;
TimingISR aTimingISR;

```

If a value should change define it as const.

```
const int pin_clk = 2;

```

If it does change you will get a compilation error rather than suddenly sending the I2C clock signal to the on board LED.

goto is evil.

```
case ('0'): case ('1' - '0'): case ('2' - '0'): case ('3' - '0'): case ('4' - '0'):  case ('5' - '0'): case ('6' - '0'): case ('7' - '0'): case ('8' - '0'): case ('9' - '0'): //all key integers
        { if (Count_Seconds > 0) // Cooking in progress, thus SHUT DOWN, any numeric key shuts down the power
        {
            lead_char = 'C';
            num_min = 'n';
            tens_sec = 'C';
            unit_sec = 'l';
            goto CancelPower;

CancelPower:
        pinMode(PIN_RELAY, OUTPUT);
        digitalWrite(PIN_RELAY, LOW);  // turn off the heat
        goto DisplayAll;  //ready to accumulate 'heating' time input
        delay(3000);         /// NEVER EXECUTED
        lead_char = 'A';     /// NEVER EXECUTED
        num_min = '0';       /// NEVER EXECUTED
        tens_sec = '0';      /// NEVER EXECUTED
        unit_sec = '0';      /// NEVER EXECUTED
        Disable_interrupts;  /// NEVER EXECUTED
        int Count_Seconds = 0;/// NEVER EXECUTED
    DisplayAll:

        // DisplayAll:  //Would like to put this into the 7 segment display
        // Address each 7 segent unit, one after the other; left to right
// Code cut (but it should be == not =)
        Disable_Interrupts;
        TM1637DisplayAll(uint8_t num, uint8_t pos);
        Enable_Interrupts;

```

Code isn't being executed because gotos never return to the call, they just carry on from the label. Try this instead:

```
// TimingISR& theISR means you can change the values in theISR
// TimingISR  theISR means you copy theISR and all changes are lost when the function exits.
// TimingISR const& theISR means you can't change the values in theISR
void CancelPower (TimingISR& theISR)
{
  pinMode(PIN_RELAY, OUTPUT);
  digitalWrite(PIN_RELAY, LOW);  // turn off the heat
  DisplayAll(theISR);  //ready to accumulate 'heating' time input
  delay(3000);     //let it display for 3 Count_Seconds,
  ClearDisplay();
  theISR.lead_char = 'A';        //ready to accumulate 'heating' time input
  theISR.num_min = '0';
  theISR.tens_sec = '0';
  theISR.unit_sec = '0';
  theISR.Disable_interrupts(); // This should be a function that does something, not a bool
  theISR.Count_Seconds = 0;
}

```

I'm afraid that's just some of the things you need to change, ***BUT*** that's one hell of a program for a first attempts and that's the only reason I raised so many issues. Try again and post it again, I'd love to see the differences.
> 2 votes

---
Tags: arduino-nano
---


title: Function pointer or abstract class?

text:
# Question
Title: Function pointer or abstract class?
I need to implement callback in my C++ library. The "proper" C++ way of doing it would be to create an interface (or pure abstract class) and pass it to interested party. I'm wondering though, would that be optimal?

My analysis:

* Function pointer - occupies 2 bytes in memory (+code of function)
* Class derived from abstract one - occupies 2 bytes in memory PLUS 2 bytes for VMT (since we have derived method) PLUS size of VMT table (if any) (+code of method).

Is optimizer smart enough to compile abstract class with single method as method pointer? Which solution is more optimal in regard of memory and speed? Is my analysis correct?

# Answer
> 3 votes
Sometimes you want your callback to be fed some data that you provide when you register that callback. Here is a very common callback pattern in plain C that does that:

```
// The API:

typedef void (*callback_t)(void *data);
void register_callback(callback_t callback, void* data);

// Usage:

typedef struct {
    // stuff only the user of the API knows about.
} my_data_t;

void my_callback(void *in_data)
{
    my_data_t *data = (my_data_t *) in_data;
    // do something with data->foo, data->bar...
}

// ...somewhere else:
my_data_t my_data = { stuff... };
register_callback(my_callback, (void *)&my_data);

```

The problem is: it's clumsy. C++ classes allow you to pack together the code (the callback function) and the data it needs. Thus, if in your use case you need to pass data to the callback, by all means use a C++ class. It will make your life easier and you are unlikely to even notice the memory overhead.

However, if you only need to pass a function, with no attached data, then a plain function pointer would be both easier for the API user and optimal memory-wise.

# Answer
> 2 votes
The best way is to find out yourself, there are memory 'debug' functions to show the amount of free memory, so if you do some tests you know for sure what the compiler optimizes.

See e.g. AvailableMemory library.

It might be quite hard to exactly calculate and predict the optimizer. However, is it really needed to optimize? Mostly it is best to not optimize before knowing it is really necessary.

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


# Question
Title: Strange behaviour on splitting char array and converting the chunks to int
I have this function:

```
void changeColor(char control[16])
{
  char _red[3], _green[3], _blue[3], _brightness[3], _white[3];
  int red, green, blue, brightness, white, offset;

  offset = 1;
  for (int i = 0; i < 3; i++) {
    _red[i] = control[i + offset];
  }
  offset = 4;
  for (int i = 0; i < sizeof(green); i++) {
    _green[i] = control[i + offset];
  }
  // strncpy(_green,control+offset,3); // same result
  offset = 7;
  for (int i = 0; i < sizeof(_blue); i++) {
    _blue[i] = control[i + offset];
  }
  offset = 10;
  for (int i = 0; i < sizeof(_white); i++) {
    _white[i] = control[i + offset];
  }
  offset = 13;
  for (int i = 0; i < sizeof(_brightness); i++) {
    _brightness[i] = control[i + offset];
  }

  red = atoi(_red);
  green = atoi(_green);
  //sscanf(_green, "%d", &green); //same result
  blue = atoi(_blue);
  white = atoi(_white);
  brightness = atoi(_brightness);

  Serial.print(" control ");
  Serial.println(control);
  Serial.print(" _red ");
  Serial.println(_red);
  Serial.print(" _green ");
  Serial.println(_green);
  Serial.print(" _blue ");
  Serial.println(_blue);
  Serial.print(" _white ");
  Serial.println(_white);
  Serial.print(" _brightness ");
  Serial.println(_brightness);
  Serial.print(" red ");
  Serial.println(red);
  Serial.print(" green ");
  Serial.println(green);
  Serial.print(" blue ");
  Serial.println(blue);
  Serial.print(" white ");
  Serial.println(white);
  Serial.print(" brightness ");
  Serial.println(brightness);
  //... do something with ints
}

```

And by calling from the setup:

```
 char _control[16]={'6','2','5','5','0','0','0','0','0','0','0','0','0','0','5','0'};
 //6255000000000050

 void setup() {
   Serial.begin(9600);
   // ... do something
   while (!Serial) {
     ; // wait for serial port to connect. Needed for native USB
   }
  changeColor(_control);
}

```

I get from console this output:

```
   control 6255000000000050
   _red 255ÿ
   _green 000255ÿ
   _blue 000000255ÿ
   _white 000050000000255ÿ
   _brightness 050000000255ÿ
   red 255
   green 255
   blue 255
   white 29951
   brightness 29951

```

Basically, the char array are filled with more elements than the actual dimension (3), but I don't get error or warnings from the compiler

I also tried with `strncpy`, `strcpy`, `strncat`, and by using the pointer in the for loops

```
for(int i=0;i<sizeof(_green);i++){
  _green[i]=control+i*sizeof(char)+offset*sizeof(char);
} // also without the sizeof()

```

And I got the same result in the console (with nl&cr), any hints?

EDIT:

Added NULL char

```
  ...
  char _red[4], _green[4], _blue[4], _brightness[4], _white[4];
  int red, green, blue, brightness, white, offset;
  _red[4]='\0';
  _green[4]='\0';
  _blue[4]='\0';
  _white[4]='\0';
  _brightness[4]='\0';
  offset=1;
  for(int i=0;i<3;i++){
    _red[i]=control[i+ offset];
  }
  // same as above

```

Output:

```
control 6255000000000050
_red 255
_green 100255
_blue 000100255
_white 0000050
_brightness 050
red 255
green 100
blue 0
white 50
brightness 50

```

# Answer
In this piece of code you have a strange mix of upper bounds:

```
  for(int i=0;i<3;i++){
    _red[i]=control[i+offset];
  }
  offset=4;
  for(int i=0;i<sizeof(green);i++){
    _green[i]=control[i+offset];
  }
 // strncpy(_green,control+offset,3); // same result
 offset=7;
 for(int i=0;i<sizeof(_blue);i++){
   _blue[i]=control[i+offset];
 }
 offset=10;
 for(int i=0;i<sizeof(_white);i++){
   _white[i]=control[i+offset];
 }
 offset=13;
 for(int i=0;i<sizeof(_brightness);i++){
   _brightness[i]=control[i+offset];
 }

```

The first looks correct at 3. The second loop has an upper bound of `sizeof(int)` which is 2. The third loop seems to be `sizeof(char)` which is 1.

Unfortunately non of those values match up with the results you are getting. What I would try is refactoring whats inside you function to this.

```
int Convert (char* buffer, char const* control, const int& offset, char const* name)
{
    int value = 0;
    for (index = offset; index < offset; ++index)
    {
        buffer[index-offset] = control[index];
    }
    buffer[4] = '\0';
    atoi(buffer);
    Serial.print(name);
    Serial.print(" = ");
    Serial.print(buffer);
    Serial.print("  Value = ");
    Serial.println(value);
    return value;
}

```

And then call it to populate your values:

```
void changeColor(char control[16])
{
    char buffer[4]; // You can reuse this buffer, unless you wanted to have separate ones.
    const int red    = Convert (buffer, control, 1, "red");
    const int green  = Convert (buffer, control, 4, "green");
    const int blue   = Convert (buffer, control, 7, "blue");
    const int white  = Convert (buffer, control, 4, "white");
    const int bright = Convert (buffer, control, 4, "bright");
}

```
> 0 votes

---
Tags: array
---


# Question
Title: Delay in displaying data received from UART when used with PCINT on PIN0
I have been trying to find a solution for `UART receive interrupt` for my `UNO` board and I came across a possible solution in : PCInt

I did a small editing in the following portion of the code to make it work for `UART`.(code works like a loop-back test)

```
void RXint(void) {
char k;
if(Serial.available()>0)
{
k=Serial.read();
Serial.print(k);
}}
void setup()
{
Serial.begin(9600);
PCattachInterrupt(0, RXint, FALLING);
}
void loop()
{}

```

The code works pretty well with one big drawback. The character displayed is having one char delay, what i mean is that for the following input

> qwerty

output is

> qwert

That means if I enter the 5th char,the output will be 4th one. When the first input is given, it doesn't show output till the second input is entered.

Can someone help me out with this

(This is only a test code, the interrupt part is to be used in a larger code where the `loop()` carries out different tasks and interrupt is to be raised when data is received via `UART`) .

# Answer
> 1 votes
Your interrupt is happening at the same time the START bit of the *next* frame is arriving in the hardware. As a result you don't have that data yet, because it's still to arrive. All you have is what has gone before. You won't get the new character until the frame has finished arriving and the UART RX interrupt fires and the byte gets copied out of the RX FIFO and placed into the Arduino receive buffer.

The way you are doing it is completely wrong. The data is already being captured using an interrupt and placed in a buffer for you to deal with as you see fit at a time that suits you (as long as it is before the buffer overflows).

If you can't read it fast enough using your main loop (or variations thereon) then you need to rethink how you are doing your main loop.

# Answer
> 0 votes
As other have emphasized, make sure your `loop` runs freely, without delays or blocking while loops. It would be very unusual to have a `loop` that *really* takes \> 64ms (the input buffer overflow time @ 9600).

However, there is one case where a frequently-used library is blocked for 150ms or more: SDfat. If you are logging data, the library may have to wait for the SD card to accept more data. It is an indeterminate length of time, and it is specific to the individual card. In this case, you have two choices:

* process the RX characters as they arrive, during the RX character interrupt; or
* add a `yield` call to the offending SDFat method.

For the former solution, I have posted modified versions of the most commonly-used Arduino serial port libraries. They all have a new `attachInterrupt` method that allows your function to be called for each RX character. See NeoHWSerial (a modified `HardwareSerial`), NeoICSerial (a modified `AltSoftSerial`) and NeoSWSerial (a more-efficient alternative to `SoftwareSeriall`).

---
Tags: arduino-uno, interrupt, uart
---


title: Taking pictures with a small Arduino

text:
# Question
Title: Taking pictures with a small Arduino
I'm trying to make a time lapse video of a crystal patch in a small space. I need some way of taking a picture every hour or so within an area no greater than 35mm, the smaller the better. Something like the Arduino-Leonardo-Beetle would be the ideal dimensions. What sort of camera and Arduino board do people recommend? Thanks!

# Answer
Check out Arducam. I have used it and the library is maintained.
> 1 votes

---
Tags: arduino-leonardo
---


# Question
Title: Splitting a string read from Serial into parts
Is there any method with which I can split a string given by `Serial.read()` into an array of 3 items: \[command, address, message\], to write it to EEPROM?

Thanks.

# Answer
> 2 votes
The first thing you should do is to collect your serial input into a string.

If your incoming data use a separator, then you can take advantage of the useful function "readStringUntil".

For example, if your separator is comma (,):

```
while (Serial.available() > 0) {
  var1 = Serial.readStringUntil(','); // writes in the string all the inputs till a comma
  Serial.read();
  var2 = Serial.readStringUntil(',');
  Serial.read();
  var3 = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
}

```

At this point you have your data in 3 different variables and you can use the standard eeprom library to store. Don't forget you will need to declare the variables and to initialize the Serial.

A faster way is to save the whole input in string and process it when ready.

Much better it will be if you use interrupts attached on the Serial input, so you can keep free your loop from waiting data. This can't be done with the standard Serial library but you can use this library:

https://github.com/SlashDevin/NeoHWSerial

It works really well, we use it to collect data from GPS receivers at very high speed and it's fast.

N.B. eeprom is limited in the numbers of reads and writes it can support before risk a failure. Even 100,000 reads/writes sounds a big numnber, if you write the data once every second your eeprom will die in just 27 hours, a day of life. Try to write data only when it's strictly necessary and read data as well only when you start the procedure that uses those data, once.

# Answer
> 2 votes
That's the code I used to fix this issue.

```
#include <EEPROM.h>

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

void loop() {
    while (Serial.available() > 0) {
      String command = Serial.readStringUntil(' '); // writes in the string all the inputs till a comma
      Serial.read();
      String addressStr = Serial.readStringUntil(' ');
      Serial.read();
      String messageStr = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
      int address = addressStr.toInt();
      int message = messageStr.toInt();
      if (command == "Read"){
        Serial.print("Reading from EEPROM->Address: ");
        Serial.print(address);
        Serial.print("\n");
        Serial.print("Content of ");
        Serial.print(address);
        Serial.print("is: ");
        Serial.println(EEPROM.read(address));
      }else if(command == "Write"){
        Serial.print("Writing to EEPROM in Address: ");
        Serial.print(address);
        Serial.println();
        EEPROM.write(address, message);
      }
  }
}

```

---
Tags: eeprom
---


title: Output 12-25V from Arduino Mega

text:
# Question
Title: Output 12-25V from Arduino Mega
I am currently building my first Arduino project : a car that you can control from your computer. I have my Arduino Mega that outputs 3.3 or 5V and my stepper that receives 12-25V, how can I make my Arduino digitally write something to that stepper?

# Answer
Use an H-bridge motor driver. They can use arduino signals to control higher voltages without damaging the arduino. Check out the L298N from gearbest. It's cheap but will probably do the trick if you're not using too much current.

It can supply about 1A through each gate at 5-30V.

this video should help explain it. (I haven't watched the video but it seems like it got good feedback).
> 1 votes

---
Tags: arduino-mega, stepper
---


title: Undervoltage from solar panels

text:
# Question
Title: Undervoltage from solar panels
So i'be been toying with the idea in my head of creating a solar powered weather station with an arduino, two 6V 2W solar panels in parallel, two 5V USB battery packs, and an adafruit module which converts voltages from 3-12V to 5V (to charge my batteries). I'm also working on using some small relays or MOSFETs for the arduino switch between batteries.

The problem: If my solar panel voltage drops below 3V, the adafruit board will supply the batteries with a n unstable voltage below 4.8V. I need some sort of circuit or sensor that is capable of detecting when the voltage from the solar panels drops below 3.3V and which will open the circuit to protect the batteries from unstable voltages.

# Answer
> 3 votes
You have selected a number of things that don't go well together. It is possible to use relays or mosfets to switch between batteries, and the Arduino could be used to measure a voltage. Or you can make a circuit with a few electronic components (e.g. a comparator). However, no one does it like that. It would be unreliable.

Every solar power charging module can handle darkness as well. Some modules will also create 5V.

This Adafruit module has no 5V output, it only contains the charging part: Adafruit:USB / DC / Solar Lithium Ion/Polymer charger - v2
It is out of stock at the moment, and you need solar cells, battery, a cable, and a DC-DC converter to make 5V.
When it is dark and the battery is empty, I assume the output drops and the Arduino stops working. Adafruit made a tutorial for it that shows the DC-DC converter and also Collin shows a DC-DC converter: Youtube, Collin's Lab: Solar

There are other modules like that. For example the Sparkfun Sunny Buddy.

Take care that the batteries don't get too hot.
It is possible to run some Arduino boards directly from a battery (3.1 to 4.2V). Then you would not need the DC-DC converter.
Buy solar cells that are the best in low light conditions. With enough sunlight, the power is no problem. It is the dark winter days that could be a problem.

---
Tags: power, adafruit, battery, solar
---


# Question
Title: delay() runs super fast unless I remove a while loop that never runs
I'm working on a small game on arduino but I'm facing some really odd behavior. When I run this code all of my leds flash on and off in less than a second even though `delay(10000);` should stop them for 10 seconds. However if I remove the while(game\_running) block they go back to flashing every 10 seconds even though that block of code never actually runs.

```
int yellow = 12;
int green = 10;
int red = 9;
int blue = 11;

int debug = 13;

int sequence[1000];
int level = 0;

int game_running = false;

void setup() {
  pinMode(yellow, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(red, OUTPUT);

  pinMode(debug, OUTPUT);
}

void loop() {

  // Pre Game light flash
  digitalWrite(yellow, HIGH);
  digitalWrite(green, HIGH);
  digitalWrite(red, HIGH);
  digitalWrite(blue, HIGH);
  digitalWrite(debug,HIGH);
  delay(10000);
  digitalWrite(debug,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, LOW);
  digitalWrite(red, LOW);
  digitalWrite(blue, LOW);
  delay(10000);

  game_running = false;
  level = 0;

  while(game_running) {

    sequence[level] = random(4); // Select next color

    // Blink LEDs
    for (int i=0; i < level; i++) {

       if(sequence[i] == 0) {
         digitalWrite(yellow, HIGH);
         delay(1000);
         digitalWrite(yellow, LOW);
         delay(1000);
       } else if(sequence[i] == 1) {
         digitalWrite(green, HIGH);
         delay(1000);
         digitalWrite(green, LOW);
         delay(1000);
       } else if(sequence[i] == 2) {
         digitalWrite(red, HIGH);
         delay(1000);
         digitalWrite(red, LOW);
         delay(1000);
       } else {
         digitalWrite(blue, HIGH);
         delay(1000);
         digitalWrite(blue, LOW);
         delay(1000);
       }
    }
    level += 1;
  }
}

```

# Answer
> 2 votes
I will add an official answer just so that others can see it if they run into similar problems.

The issue is with the `int sequence[1000]` array, which eats up 2,000 bytes of data memory. The Uno only has 2,048 bytes of data memory so the instability is due to this memory hog of an array. Use a smaller number of array entries or switch to `char` (if you can) to use half the bytes of an `int`.

# Answer
> 0 votes
offtopic (but cannot put it in a comment):

I do not see any problem with your code (maybe it's in the circuit?)

You can rewrite the 10 s pregame flash as:

```
// Pre Game light flash
setAllLights(HIGH);
setAllLights(LOW);

void setAllLight(int state)
{
  digitalWrite(yellow, state);
  digitalWrite(green, state);
  digitalWrite(red, state);
  digitalWrite(blue, state);
  digitalWrite(debug, state);
  delay(10000);
}

```

You can even optimize this further by creating an array:

```
int[] lights = { yellow, green, red, blue, debug}

void SetAllLights(int state)
{
   for (int color = 0; color < sizeof(lights) / sizeof(int); color++)
   {
       digitalWrite(lights[color], state);
   }
}

```

You can rewrite the inside of the loop like:

```
switch (sequence[i]):
   case 0:
      flash(yellow);
      break;

   case 1:
      flash(green);
      break;

   case 2:
      flash(red);
      break;

   default:
      flash(blue);
      break;
}

void flash(int colorPin)
{
   digitalWrite(colorPin, HIGH);
   delay(1000);
   digitalWrite(colorPin, LOW);
   delay(1000);
}

```

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


# Question
Title: Error while boot loading Atmega 2560 using Arduino Mega 2560
I have developed custom board using Atmega 2560. I am doing boot loading process using the process of migrate from an Arduino board to a standalone microcontroller.

I have followed this steps...

1) Upload the ArduinoISP sketch onto your Arduino board.

2) Wire up the Arduino board and microcontroller as connections mentioned on Arduino Site.

3) Select "Arduino/Genuino Mega/ Mega 2560" from the Tools \> Board menu.

4) Select "Arduino as ISP" from Tools \> Programmer

5) Run Tools \> Burn Bootloader

While doing this process I am getting this Error...

> avrdude: Yikes! Invalid device signature. Double check connections and try again, or use -F to override this check. Error while burning bootloader.

I have done connection like this...

```
MISO  -  D50
MOSI  -  D51
SCK   -  D52
Reset -  D53/Reset
+5V   -  Vcc
GND   -  GND

```

What wrong I am doing? Or any step I have missed?

# Answer
Same connections worked for me. Just one connection have to change.

```
Reset - D10

```
> 0 votes

# Answer
You wired the whole thing backwards. The proper wiring is

```
Your board - Arduino
     MISO  -  D50
     MOSI  -  D51
     SCK   -  D52
     Reset -  D53
     Vcc   -  5V
     GND   -  GND

```

This is kind of obvious from the picture: you would normally use the ISP connector of the *target* board.
> 2 votes

---
Tags: arduino-mega, bootloader, atmega2560
---


# Question
Title: Read from analog then cast not showing the correct value
I'm trying to read the analog value of the light sensor and print its percentage but for unknown reasons I'm getting negative values when I'm printing the value.

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

void loop() {

  // Let's say 1002 is the analogValue
  int analogValue = (int) analogRead(0);

  // get the percentage
  int value = 100 * analogValue / 1023;

  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
  Serial.println(analogValue); // print the analog value 0...1023
  Serial.println(100 * analogValue); // just for test
  Serial.println(value); // The percentage
  Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");

  delay(500);
}

```

I don't know what's going in background, but I'm getting negative values when I try to print the percentage:

```
~~~~~~~~~~~~~~~~~~~~~~~~~
1002
-30772
-30
~~~~~~~~~~~~~~~~~~~~~~~~~

```

# Answer
> 2 votes
Max value for `int` is 32,767. But 100 * 1002 = 100,200. You are overflowing the `int`. Use `unsigned long`. Or `float` and cast to `int` when printing.

---
Tags: arduino-uno
---


title: Serial.read() always returns 255

text:
# Question
Title: Serial.read() always returns 255
So I'm trying to learn basic Android app dev. My master plan was to make an app using MIT App Inventor that would turn on an LED over Bluetooth using an Arduino. Once I verified that everything worked, I would write the entire app from scratch using Android Studio. This way, when I inevitably run into bugs with my written-from-scratch app, I could say with 100% certainty that the issue is in my Android code and not hardware/Arduino related.

So I'm having trouble right now. I have two separate LED circuits, a blue LED from port 13 and a green LED from pin 8. I verified that both circuits are working properly by using the Blink code, so I know the issue is definitely not with the LED circuits.

I'm using an HC 06 Bluetooth module. The pins are connected as follows:

HC 06 -\> Arduino

RX -\> TX

TX -\> RX

5V -\> 5V

GND -\> GND

Here is the Arduino code:

```
#include <SoftwareSerial.h>

SoftwareSerial bluetooth(0,1);
int ledblue = 13;
int ledgreen = 8;
int tx = 1;
int rx = 0;
int type;

void setup() {
  Serial.begin(9600);
  //bluetooth.begin(9600);
  pinMode(ledblue, OUTPUT);
  pinMode(ledgreen, OUTPUT);
  pinMode(tx, OUTPUT);
  pinMode(rx, INPUT);
  allpinslow();
}

void loop() {
  int i = 0;
  int m = 0;
  delay(500);
  if (Serial.available() > 0) {
    while(Serial.available() > 0){
      type = Serial.read();
      Serial.println(type);
    }
    Check_Protocol(type);
  }
}

void allpinslow()
{
  digitalWrite(ledgreen, LOW);
  digitalWrite(ledblue, LOW);
}

void Check_Protocol(int inStr) {
  int i = 0;
  int m = 0;
  if (inStr == '0') { //Led Off equals("2off")
    allpinslow();
  }
  if (inStr == '1') { //Led on
    digitalWrite(ledblue, HIGH);
  }
  if (inStr == '2'){
    digitalWrite(ledgreen,HIGH);
  }
}

```

Here is the MIT App Inventor block code

If I press the Green or Off button, the Serial Monitor spits out 255. If I press Red, nothing shows up on the serial monitor. I'm a bit dumbfounded on what is broken so I would greatly appreciate any help I can get.

Edit: @Delta\_G here is the modified code

```
#include <SoftwareSerial.h>
int ledblue = 13;
int ledgreen = 8;
SoftwareSerial mySerial(2,4); //RX, TX
int type;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(ledblue, OUTPUT);
  pinMode(ledgreen, OUTPUT);
  allpinslow();
}

void loop() {
  int i = 0;
  int m = 0;
  delay(500);
  if (mySerial.available()) {
    while(mySerial.available()){
      type = mySerial.read();
      Serial.println(type);
    }
    Check_Protocol(type);
    //Serial.println(inSerial);
  }
}

void allpinslow()
{
  digitalWrite(ledblue, HIGH);
  digitalWrite(ledblue, LOW);
}

void Check_Protocol(int inStr) {
  int i = 0;
  int m = 0;
  if (inStr == '0') { //Led Off equals("2off")
    digitalWrite(ledblue, LOW);
    digitalWrite(ledgreen, LOW);
  }
  if (inStr == '1') { //Led on
    digitalWrite(ledblue, HIGH);
  }
  if (inStr == '2'){
    digitalWrite(ledgreen,HIGH);
  }
}

```

# Answer
Update: It was a faulty Bluetooth module that was causing the issues. I bought a new one and everything works perfectly!
> 1 votes

# Answer
If you are using Serial then you can't use pins 0 and 1 for something else as those are the hardware serialpins. Pick different pins for the Bluetooth.
> 0 votes

# Answer
From reading the comments, I assume you are using an Arduino Uno, and you have a PC (or Mac, or any type of computer) connected to its USB port, and an Android device at the other end of the Bluetooth link.

I can't see what is wrong with your sketch. I will then only suggest two methods for checking the low-level communication is working properly. Once you know the communication is good, debugging should be easier.

## Test bypassing the microcontroller

**First**, load an empty sketch in the Arduino, **then** connect the Bluetooth module as follows:

```
HC 06   Arduino
───────────────
 GND ─── GND
  5V ─── 5V
  RX ─── RX
  TX ─── TX

```

It is important to load the empty sketch first: you do not want the Arduino to access its hardware serial port. Now you can open your serial monitor on the PC, set to 9600/8N1.

With this setup, the HC 06 will be using the USB/serial bridge of the Arduino (the ATmega16U2), whereas the main microcontroller (the ATmega328P) is just a bystander. Whatever the HC 06 outputs through its TX should appear on your serial monitor. The data path is as follows:

```
┌─────────┐  Bluetooth  ┌───────┐  Serial  ┌──────┐     ┌──────┐  USB  ┌────┐
│ Android │ ──────────→ │ HC 06 │ ───────┐ │ 328P │ ┌─→ │ 16U2 │ ────→ │ PC │
└─────────┘             └───────┘        │ └──────┘ │   └──────┘       └────┘
                                         └──────────┘

```

Note the 328P disconnected from the serial link.

## Test with an echo sketch

Load the following sketch:

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

void loop()
{
    if (Serial.available())
        Serial.write(Serial.read());
}

```

then connect the Bluetooth module as follows:

```
HC 06   Arduino
───────────────
 GND ─── GND
  5V ─── 5V
  RX ─── TX
  TX ─── RX

```

With this setup, whatever the HC 06 outputs on its TX should appear on your serial monitor **and** should be sent back through Bluetooth. The data path is:

```
┌─────────┐  Bluetooth  ┌───────┐  Serial  ┌──────┐     ┌──────┐  USB  ┌────┐
│ Android │ ──────────→ │ HC 06 │ ───────→ │ 328P │ ┌─→ │ 16U2 │ ────→ │ PC │
│         │ ←────────── │       │ ←──────┐ └──────┘ │   └──────┘       └────┘
└─────────┘             └───────┘        └─────┴────┘

```

Note that the output of the 328P is received by both the 16U2 and the HC 06. Since the Android device seems to ignore whatever it receives through Bluetooth, the setup should work fine for debugging you app too.
> 0 votes

---
Tags: serial, softwareserial
---


# Question
Title: Arduino GSM shield GSM_READY not ready ever
I am using an Arduino Mega and an Arduino GSM shield. I am using the receive SMS example under GSM in the Arduino IDE. My GSM shield's hardware IP is set correctly.

Here is the sketch:

```
/*
 SMS receiver

 This sketch, for the Arduino GSM shield, waits for a SMS message
 and displays it through the Serial port.

 Circuit:
 * GSM shield attached to and Arduino
 * SIM card that can receive SMS messages

 created 25 Feb 2012
 by Javier Zorzano / TD

 This example is in the public domain.

 http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

*/

// include the GSM library
#include <GSM.h>

// PIN Number for the SIM
#define PINNUMBER ""

// initialize the library instances
GSM gsmAccess;
GSM_SMS sms;

// Array to hold the number a SMS is retreived from
char senderNumber[20];

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("SMS Messages Receiver");

  // connection state
  boolean notConnected = true;

  // Start GSM connection
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop() {
  char c;

  // If there are any SMSs available()
  if (sms.available()) {
    Serial.println("Message received from:");
    // Get remote number
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);
    // An example of message disposal
    // Any messages starting with # should be discarded
    if (sms.peek() == '#') {
      Serial.println("Discarded SMS");
      sms.flush();
    }

    // Read message bytes and print them
    while (c = sms.read())
      Serial.print(c);
    Serial.println("\nEND OF MESSAGE");

    // Delete message from modem memory
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }
  delay(1000);
}

```

The issue is this line:

```
if (gsmAccess.begin(PINNUMBER) == GSM_READY)

```

The serial monitor outputs everything until that line.

It just never gets past it, so I assume it cannot connect? The SIM has no pin code: I have tried it with my phone. The SIM has full signal strength when in my phone. I have tried my other SIM card also but the same thing happens.

This seem to be the same question, yet no answer: http://forum.arduino.cc/index.php?topic=270551.0

# Answer
> 1 votes
You could always try setting a pin code and then retry http://arduino.cc/en/Tutorial/GSMToolsPinManagement

What version of the Arduino IDE are you using ? Also, are you sure you are suppying the board correctly ? "It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use."

# Answer
> 1 votes
I Have The Same Problem. But First Of All you have to set your modem Network Band according to your cellular Network Band.

```
GSMBand band;
String newBand= "GSM_MODE_EGSM_DCS";// Your Band In My case That was
  band.begin();
  Serial.println("Modem restarted.");
  String bandName = band.getBand(); // Get and print band name
  Serial.print("Current band:");
  Serial.println(bandName);

band.setBand(newBand);

```

Band Help:

```
  GSM_MODE_EGSM                ---- E-GSM(900)
  GSM_MODE_DCS                 ---- DCS(1800)
  GSM_MODE_PCS                 ---- PCS(1900)
  GSM_MODE_EGSM_DCS            ---- E-GSM(900)+DCS(1800) ex: Europe
  GSM_MODE_GSM850_PCS          ---- GSM(850)+PCS(1900) Ex: USA, South Am.
  GSM_MODE_GSM850_EGSM_DCS_PCS ---- GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

```

Then You Have To use

```
gsm.access.begin();

```

# Answer
> 1 votes
I had the same problem. Then I used `gsm.shutdown();` before `gsm.begin(PINNUMBER)`. After that it goes past `gsm.begin(PINNUMBER)` but not always. I don't know if this is the right way to do it, but it works for me.

---
Tags: arduino-mega, shields, gsm
---


title: read CID of SD card with SD.h library

text:
# Question
Title: read CID of SD card with SD.h library
I would like to be able to read the serial numbers of SD cards using the SD.h library. Only reading the values is enough, I am not looking to modify the CID. This should be possible but I do not have the programming skills to get it running.

I am using an esp8266 and already have the SD card running and working correctly. Only the chipselect needed to be modified for the SD library to work.

So far I have found this in Sd2Card.h

```
      /**
   * Read a cards CID register. The CID contains card identification
   * information such as Manufacturer ID, Product name, Product serial
   * number and Manufacturing date. */
  uint8_t readCID(cid_t* cid) {
    return readRegister(CMD10, cid);
  }
  /**

```

And in Sd2Card.cpp there is this:

```
/** read CID or CSR register */
uint8_t Sd2Card::readRegister(uint8_t cmd, void* buf) {
  uint8_t* dst = reinterpret_cast<uint8_t*>(buf);
  if (cardCommand(cmd, 0)) {
    error(SD_CARD_ERROR_READ_REG);
    goto fail;
  }
  if (!waitStartBlock()) goto fail;
  // transfer data
  for (uint16_t i = 0; i < 16; i++) dst[i] = spiRec();
  spiRec();  // get first crc byte
  spiRec();  // get second crc byte
  chipSelectHigh();
  return true;

 fail:
  chipSelectHigh();
  return false;
}

```

So it seems that the underlying code has been prepared in the library already, my question is how would I include it into a sketch like CardInfo.ino?

# Answer
> 0 votes
The method is visible from within your sketch. You just need to first create a `cid_t` struct like this in your sketch:

```
cid_t cid;  // at the top with the other globals

```

Then call `readCID()` anywhere in `setup()` after the card has been initialized.

```
card.readCID(&cid);
Serial.print("Serial number: "); Serial.println(cid.psn); // psn is the serial number field of the struct

```

Check out `SdInfo.h` for the other struct members.

---
Tags: esp8266, library, sd
---


title: Arduino Zero D0/D1 set output high

text:
# Question
Title: Arduino Zero D0/D1 set output high
I am trying to use D0/D1 as normal IO pins but DigitalWrite does not work as on an Arduino UNO.

I know the SAMD21G has SERCOM but I can't seem to find an example of not using D0/D1 as an UART port.

EDIT \** **Code I have tried:**

```
#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
  REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
  delay(1000);
  REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
}

void loop() {
}

```

# Answer
You can do this by simply calling the right registers:

Example 1, using a MASK

D0/D1 are mapped to to PA10 & PA11 on the M0

```
/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00

int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)

    while(1){

    }
}

```

Here is another simple example:

```
/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00
#define LED1 PORT_PA10
#define LED2 PORT_PA11
int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = LED1 | LED2; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = LED1 | LED2; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = LED1 | LED2; // set state of pin(s) to FALSE (LOW)
    while(1){

    }
}

```

In the Arduino IDE you can do something like:

```
#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
}

void loop() {
   REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
   delay(1000);
   REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
   delay(1000);
}

```
> 2 votes

---
Tags: samd21g
---


# Question
Title: Use SPI and I2C in the same circuit (ATtiny85/84)
There is a previous question about this same topic here, but it does not answer my question.

I want to use a generic I2C OLED 128x64 px display and an SPI RF24 radio in the same sketch. I know that it's theoretically possible to do so as long as they're not used at the same time - my question concerns the implementation of this circuit. Can I just leave the two devices as-is without needing some kind of external apparatus to switch power to each one of them?

I know that for SPI a chip will just ignore everything when its CS pin is pulled high, and from my tests the SPI communications don't affect the SDA line of the I2C - the problem comes when I try and use the CLK and SCL line with this setup. The pullup resistor in my circuit is stopping the I2C SCL line from working. When I remove the wire (green in the breadboard schematic shown) that connects the CLK to one end of the diode the I2C starts working and the display updates, but the radio doesn't work. If I remove the pullup resistor from the circuit the I2C starts working again, but the radio doesn't work anymore. I tried switching the CLK signal with a transistor, but it doesn't look like the 2n2222 transistor I was using is fast enough to switch the CLK signal. Will I have to go with the tiny84, or is there a way to get this to work on the ATtiny85?

# Answer
> 1 votes
In the setup shown, you have 3 pins free, yes? Although hardware i2c may not be directly possible through software, the use of the other GPIO pins can be used for either a logic circuit to switch around the pull up resistor/green wire/whatever OR you can just use software i2c which is a lot easier to do.

---
Tags: i2c, spi, attiny, nrf24l01+
---


# Question
Title: Stopping Serial on RX/TX pins while running Serial on USB
The Arduino/Genuino Micro has RX/TX pins and can do serial via USB.

But, Arduinos `Serial` ties them both together, so when using `Serial.begin(9600)` to send messages between my PC and the Arduino, I cannot use the RX/TX pins as GPIOs.

From what I can tell reading the Atmega32u4s Datasheet, the USART module on the chip is completely separate from the USB controller, so it should be possible to somehow disable the USART Transceiver and Receiver after executing `Serial.begin(9600)`.

Is there something fundamental preventing me from doing this or can it be done? If it can, how would I do it?

# Answer
The Serial and Serial1 are two seperated ports. They are not connected. The Serial is the USB serial and does not use pin 0 and 1 at all. The Serial1 is the hardware serial port at pin 0 and 1, but if Serial1 is not used then pin 0 and 1 are normal digital pins that you can use.

Don't be confused by the text labels printed on the board. Pin TX (also called TX1) is D1 and pin RX (also called RX1) is D0.
This is the pinmapping for the Micro: PighiXXX - Micro.

The Arduino Zero uses 'SerialUSB' to indicate the serial port via USB. You can do the same for the Leonardo and the Micro and use the alias 'SerialUSB' in your sketch instead of 'Serial'.
I found it more convenient to use 'SerialUSB' in my sketch, but not many people use it.
The Serial port at pin 0 and 1 is still called 'Serial1'.
> 3 votes

# Answer
There is no real reason why it should be tied somehow. And running simple test program seconds that:

```
void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(0, LOW);
  delay(400);
  digitalWrite(0, HIGH);
  digitalWrite(1, LOW);
  delay(1000);
  digitalWrite(1, HIGH);
  Serial.println("something");
}

```

LEDs on TX and RX pins blinks and USB Serial is sending the message (Genuine Arduino Micro, Arduino IDE 1.8.1)
> 2 votes

---
Tags: serial, arduino-micro, uart
---