title: ColorPal Sensor

text:
# Question
Title: ColorPal Sensor
First off let me preface this my explaining my background. I am a mechanical engineering student and have some programming knowledge but it's limited. I'm trying to make a skittle sorter and I right now I'm working on the color identification part. I bought a ColorPal sensor for the project but I'm having trouble using it. I modified the demo a bit and it sort of works but not as well as I would like. Can someone please help me with my code or perhaps suggest an easier color sensor to use. Also I hope I paste my code correctly.

```
#include <SoftwareSerial.h>

#define sio      6           // ColorPAL connected to pin 6
#define unused   255         // Non-existant pin # for SoftwareSerial
#define sioBaud  4800

// Received RGB values from ColorPAL
int red;
int grn;
int blu;

// Set up two software serials on the same pin.
SoftwareSerial serin(sio, unused);
SoftwareSerial serout(unused, sio);

void setup() {

  delay(2000);

  Serial.begin(9600);
  reset();                    // Send reset to ColorPal
  serout.begin(sioBaud);
  pinMode(sio, OUTPUT);
  serout.print("=(00 $ m)!"); // Loop print values, see ColorPAL documentation
  serout.end();               // Discontinue serial port for transmitting
  pinMode(sio, INPUT);
  serin.begin(sioBaud);       // Set up serial port for receiving
}

void loop() {
  readData();
}

// Reset ColorPAL; see ColorPAL documentation for sequence
void reset() {
  delay(200);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  pinMode(sio, INPUT);
  while (digitalRead(sio) != HIGH);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  delay(80);
  pinMode(sio, INPUT);
  delay(200);
}

void readData() {
  char buffer[32];

  if (serin.available() > 0) {
    // Wait for a $ character, then read three 3 digit hex numbers
    buffer[0] = serin.read();
    if (buffer[0] == '$') {
      for (int i = 0; i < 9; i++) {
        while (serin.available() == 0);     // Wait for next input character
        buffer[i] = serin.read();
        //Serial.print(buffer[i]);
        if (buffer[i] == '$')               // Return early if $ character encountered
          return;
      }
      //Serial.println("");
      parseAndPrint(buffer);
      delay(10);
    }
  }
}

// Parse the hex data into integers
void parseAndPrint(char * data) {
  sscanf (data, "%3x%3x%3x", &red, &grn, &blu);  // Pull the R, G, and B values from the data string

  char buffer[48];                               // create a buffer
  //sprintf(buffer, "r = %4.4d    g = %4.4d    b = %4.4d", red, grn, blu);   //print the values into a buffer as formatted integers
  int sum = red + grn + blu;
  //Serial.println(sum);
  if (sum >= 120 && sum < 126) {
    Serial.println("Purple");
  }
  if (sum >=  238 && sum < 248) {
    Serial.println("Green");
  }
  if (sum >= 230 && sum < 235) {
    Serial.println("Red");
  }
  if (sum >=  330 && sum < 340) {
    Serial.println("Orange");
  }
  if (sum >=  420 && sum < 430) {
    Serial.println("Yellow");
  }
}

```

# Answer
In `parseAndPrint`

You need to check the return value of `sscanf` to see if the function read the data.

The problem you are having is the difference between + and &. The sensor is providing 3, 3 digit hex values (which should be sprintfed with %03x not %4.4d). Adding these together isn't going to give you the write answer. For instance $001001001 should give you a colour of r=1, g=1 and b=1. If you add those together you get 3, but you really want 0x001 0x001 0x001.

You need to recalibrate you system and keep the three values separate and represent each colour by a minimum and max of those three colours and then check the value 3 values you receive are within the 3 ranges you have.

```
// Define a structure (could be a class) to hold the data
struct ColourData
{
    int redMin;
    int redMax;
    int grnMin;
    int grnMax;
    int bluMin;
    int bluMax;
    char Name[30];
    ColourData (int rm, int rx, int gm, int gx, int bm, int bx, char* name)
      : redMin(rm), redMax(rx)
      , grnMin(rm), grnMax(rx)
      , bluMin(bm), bluMax(bx)
    {
        sprint(Name, "%s", name);
    }
};

// Define an array containing the data
ColourData colours[MaxColours] = {ColourData(150, 200, 0, 20, 150, 200, "Purple")
                         , // Add some more

// The code to check the colours
for (int index = 0; index < MaxColours; ++index)
{
    if (  red >= colours[index].redMin && red <= colours[index].redMax
       && grn >= colours[index].grnMin && grn <= colours[index].grnMax
       && blu >= colours[index].bluMin && blu <= colours[index].bluMax)
    {
       Serial.println(colours[index].Name)
    }
}

```
> 1 votes

---
Tags: arduino-uno, sensors, rgb-led, code-review, automatization
---


# Question
Title: Autolock transistor for powering Arduino
I have a portable project where I want to take care about batteries getting discharged.

Usually I just put a switch at the very beginning of my circuit that completely cuts off the electricity when switched off. The problem with this approach is that if you forget to switch it off your batteries will discharge.

So I was thinking about an approach that after some inactivity time cuts off the circuit (I want to completely cut off the electricity to minimize power consumption, so I'm not interested in sleeping modes or similar approaches).

So my approach consist in changing a switch for a regular push button that enables the circuit when pushed, and then one of the arduino pins is used to lock the transistor until a function times out and the pin gets to a low voltage (see image)

In the arduino code I can just test a simple program that keeps the circuit closed for 10 seconds and then switches it off.

```
setup() {
    pinMode(3,OUTPUT);
    digitalWrite(3,HIGH);
    delay(10000);
    digitalWrite(3,LOW);
}

loop() {
}

```

For the transistor part I'm not sure what to use. I was thinking about using an motor driver L298 (which should work and also accepts some load for other electronics that I might have in the project)

However this looks like something that should already exist (either in a shield or maybe integrated in some Arduino variant).

Does anybody have experience with such an approach or a suggestion on any standalone transistor that would also do the job?

Any help is appreciated :)

.

# Answer
Here is a mock-up of what I usually do.

simulate this circuit – Schematic created using CircuitLab

Keep in mind that the resistors are just an example value: you'll have to make some calculations.

Now, M1 is a PMOS, while M2 is an NMOS. Both MOSFETs should be able to turn on and off with the voltages you can supply them (so look at their Vgs curves). Moreover the M1 mos will be the one where all the supply current will run, so you'll have to choose it wisely. The M2 mos will only have to supply a small current, so the smallest one is fine. Beware that if the Vin voltage is greater than the maximum Vgs voltage of M1 you'll have to add a resistor between M1 gate and M2 drain to form a voltage divider with R1.

The R4 and D1 are used if you want to detect a SW1 push (for instance to turn off the device). If you don't need this feature, remove them both.

The circuit works this way: when you push the button, a voltage (for instance 5V - 0.6V of D1) will come to the arduino Vcc. The arduino then should immediately bring up the pin. This will turn on M2, which in turn switches on the M1 transistor, thus bypassing the switch. When you remove it, the arduino stays powered.

When the arduino decides that it should turn off (either because you pressed the button again, or because it timed out, or who knows) it executes two instructions: one to pull down the pin and the other is `while(1)`. This prevents it to continue executing the program. The M2 transistor shuts down, the M1 gate floats to Vin and so it shuts down too.

You can find the transistor as discrete componetns (sometimes also in the same SOIC-8 package. Usually I use big pMOS (e.g. IRF9310 in SOIC8) and smaller nMOS (usually in SOT-23 case). I do this because I can easily solder them also on perfboards (SOIC8 single transistors have a lot of redundancy for pins, while SOT-23 ones can be mounted easily on 3 pads).
> 2 votes

# Answer
If you would like an out-of-the-box solution, the Pololu Pushbutton Power Switch is a lovely piece of hardware that lets the device turn itself off :)

Update: Adafruit also released a "Low Power Timer Breakout" that allows a device to be turned on automatically from 1s-2hr intervals, and then disable the power supply from the device once each run is done.

If you need less often than 2 hr intervals, you could increment a number in EEPROM in `setup()` each run and immediately re-enter sleep if the number doesn't match your desired value.
> 2 votes

---
Tags: arduino-uno, power, transistor
---


# Question
Title: Build error on a phantom file that is not in my sketch, but somehow created in AppData/Local/Temp\build
on attempt to build I get the following error

```
C:\Users\gmyer\AppData\Local\Temp\build5d24776aeb7b2efec3566cec737c36d8.tmp\sketch\trash\bootloader.c:1:1: error: unknown type name 'This'

 This modules tests receiving vacuum data from the

 ^

```

The problem is that I have no file of that name, and no text that exactly matches that any where in my sketch. and my sketch is located in C:\Software

I have tried rebooting, deleting the Temp directory, reverting to known working code. but it keeps regenerating.

# Answer
I found the offending file in a sub directory of the C:\Software sketch directory. I had a subdirectory called trash, and the Arduino build found it from there, and put it in AppData then referenced the error from there.
> 1 votes

---
Tags: arduino-builder
---


# Question
Title: exit status 1 'mcpButtonState' cannot be used as a function
I keep getting this error and I don't know why.

mcpButtonState is an array, and I would like to change one of its values using a line like this:

```
mcpButtonState(thisPin) = 0;

```

(it's inside of a for loop looping trough all my pins). This is my complete code:

```
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h
#include <Wire.h>
#include "Adafruit_MCP23017.h"
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);
Adafruit_MCP23017 mcp;

int mcpButtonPins[] = {0,1,2,3,4};
int mcpButtonCount = 5;
int mcpButtonState[5];

int analogButtonPins[] = {0};
int analogButtonCount = 1;
int analogButtonState[1];

int potiPin = A2;
int soundVolume = 15;

void setup() {
  mySoftwareSerial.begin(9600);
  //Serial.begin(115200);
  mcp.begin();
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
    mcp.pinMode(thisPin, INPUT);
    mcp.pullUp(thisPin, HIGH);
    mcpButtonState(thisPin) = 0;
  }
  //ANALOG BUTTON SETUP
}

void loop() {
  int potiValue = analogRead(potiPin);
  int newVolume = (potiValue / 1023 * 30);
  if(newVolume != soundVolume)
  {
    soundVolume = newVolume;
    myDFPlayer.volume(soundVolume);
  }
  for (int thisPin = 0; thisPin < mcpButtonCount; thisPin++)
  {
     if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 0)
     {
      mcpButtonState(thisPin) = 1;
      myDFPlayer.play((thisPin + 1));
     }
     else if(mcp.digitalRead(thisPin) == 0 and int mcpButtonState(thisPin) == 1){}
     else {
      mcpButtonState(thisPin) = 0;
      }
  }
  //ANALOG BUTTON PLAYING
}

```

# Answer
> 0 votes
Use `[]` not `()`:

```
 if((mcp.digitalRead(thisPin) == 0) && (mcpButtonState[thisPin] == 0))

```

Note the use of `&&` instead of the word `and`.

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


title: 3D printer Arduino sketch

text:
# Question
Title: 3D printer Arduino sketch
I'm building an automatic warehouse system using 3 nema17 stepper motor. My problem is to move the motors with precision, since I do not have any kind of encoder on the motor and so I cannot know the position of the axes. I tought that the system could be similar to a 3d printer, since neither 3d printers have encoder on the motor. Where can I find a sketch for Arduino of a 3d printer, to understand how they work? How do they move with such precision without any kind of sensor?

# Answer
With stepper motors you don't need any form of encoder. Only a limit switch.

A stepper moves in steps - you tell it how many steps to move. As long as you know where you started from (which is what the limit switch is for) then you can always know exactly where you are.

If you told the stepper to move 10 steps clockwise you know the stepper has moved 10 steps clockwise. If you then move 10 steps anti-clockwise, you will be back where you were.

All you need to do is count.
> 1 votes

---
Tags: arduino-uno, sketch
---


# Question
Title: Arduino receives no external UART comms after Serial.begin(9600)
I face the following issue. I connected my RasPi (3b) with an Arduino Uno via RX/TX and a logic level converter. UART comms from the RasPi to the Arduino and vice-versa work fine on minicom and serial monitor. It also works fine from my qt program to the serial monitor, but as soon as I start a Serial.begin(9600,8N1) or Serial.begin(9600) function on the Arduino there seems to be no communication anymore at all between the two. Neither the expected result (toggle an LED, works from serial monitor), nor any blinking of the tx/ex LEDs onboard anymore. Issue occurs no matter if I provide power to the Arduino via USB or the 9v powercable. Any suggestions?

# Answer
Solved. I double crossed the rx/tx connection which made it wrong again... stupidity attacks
> 1 votes

---
Tags: arduino-uno, serial, uart, raspberrypi
---


# Question
Title: Using Air Quality Sensors like MQ135 to sense dust particles
**Using MQ135 (or similar) to sense dust particles in PM**

I was building a Air-purifier system. So, I need to monitor dust particles present in the air. Is it possible to use a gas sensor like the MQ135 to sense dust particles? Since, It can sense very small gas particles. Would it be possible to sense dust particles with it(MQ135 {Cheaper to buy}) or I need to buy a special optical dust sensor {Costly!}

# Answer
> 2 votes
The MQ sensors can not be used to sense dust particles. They are Electrochemical gas sensors which are sensitive for certain gasses. They are not sensitive for dust particles. Dust is not a gas, but tiny solid particles.

---
Tags: sensors
---


# Question
Title: DS18B20 - Thermometer and Sensor discrepancy (varying)
This is a follow-up question from this other question

I followed of the user Jot (get the sensor away from the sun and use a delay in arduino program)

But the results are still varying.

I recorded the temperature measured in the sensor, the temperature measured using a mercury thermometer and calculated the difference. The data was collected within 8 days

Here's the data (sorted):

```
SENSOR  THERM   DIFF
32.69   31.25   1.44
32.00   30.25   1.75
31.94   30.50   1.44
31.87   30.50   1.37
31.44   29.50   1.94
31.00   29.00   2.00
30.75   29.00   1.75
30.50   29.00   1.50
30.44   28.80   1.64
30.31   28.90   1.41
30.25   28.75   1.50
29.87   28.00   1.87
29.81   28.00   1.81
29.81   28.00   1.81
29.81   28.25   1.56
29.75   28.20   1.55
29.69   28.00   1.69
29.56   27.00   2.56
28.75   27.25   1.50
28.69   27.00   1.69
28.56   27.00   1.56
28.44   27.00   1.44
28.25   26.80   1.45
28.00   26.50   1.50
28.00   25.50   2.50
28.00   25.00   3.00
27.75   25.50   2.25

```

The average difference is around **+1.76°C** but that's not linear, and as you can see there are fluctuation in the same sensor value, 28.00 has three associated temperatures(25.0, 25.5, 26.5).

I'm not sure what to do, if the difference was regular I could simply subtract that from the sensor readings, but it seems that it varies a lot(Min: 1.37°C, Max: 3.00°C)

Any ideas?

# Answer
> 1 votes
This isn't so much an Arduino question, but you are asking how to do better than a simple offset. The next level of complexity is to do an offset and scale.

If this is the best data you can get from your setup, a better calibration than just an offset would be finding the best **offset** and **scale**. You can do this with your data in R with:

```
> x<- read.table(header=TRUE,text="SENSOR  THERM   DIFF
 32.69   31.25   1.44
 32.00   30.25   1.75
 31.94   30.50   1.44
 31.87   30.50   1.37
 31.44   29.50   1.94
 31.00   29.00   2.00
 30.75   29.00   1.75
 30.50   29.00   1.50
 30.44   28.80   1.64
 30.31   28.90   1.41
 30.25   28.75   1.50
 29.87   28.00   1.87
 29.81   28.00   1.81
 29.81   28.00   1.81
 29.81   28.25   1.56
 29.75   28.20   1.55
 29.69   28.00   1.69
 29.56   27.00   2.56
 28.75   27.25   1.50
 28.69   27.00   1.69
 28.56   27.00   1.56
 28.44   27.00   1.44
 28.25   26.80   1.45
 28.00   26.50   1.50
 28.00   25.50   2.50
 28.00   25.00   3.00
 27.75   25.50   2.25
 ")

summary(lm(THERM ~ SENSOR,x))

```

... to get:

```
Call:
lm(formula = THERM ~ SENSOR, data = x)

Residuals:
     Min       1Q   Median       3Q      Max
-1.05217 -0.16263  0.08482  0.21809  0.47224

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -4.81422    1.60425  -3.001  0.00602 **
SENSOR       1.10237    0.05369  20.533  < 2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3816 on 25 degrees of freedom
Multiple R-squared:  0.944, Adjusted R-squared:  0.9418
F-statistic: 421.6 on 1 and 25 DF,  p-value: < 2.2e-16

```

... from which you can use the intercept and SENSOR parameters as an intercept and scale like:

```
therm_estimate = -4.81422 + 1.10237 * sensor;

```

You could plot the data in R like:

```
library(ggplot2)
ggplot(x,aes(x=SENSOR,y=THERM))+geom_point() +geom_smooth(method='lm')

```

Looking at the graph and data, your mercury thermometer is reading sometimes to the nearest 0.1th, and sometime to the 0.25th, and that is causing patterns in your data. Maybe use a better, high-accuracy, calibrated lab thermometer if you want to be sure you aren't calibrating against something unreliable.

# Answer
> 0 votes
Can you buy a few more from other (more reliable) sellers ? Perhaps it is damaged. Did you accidently connect it wrong and it got very hot ?

There has been counterfeit DS18B20 sensors, but they were transistors that were re-labeled as DS18B20. Those didn't work at all.

You have not convinced me that you are only measuring the air temperature. Maybe there is still something nearby that causes it to get warmer. The 3 degrees difference is a lot. There must be a good reason for that, or else the DS18B20 is broken. How accurate is that mercury thermometer ?

I wrote before: "*To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water)*". That is what I did, out of curiosity. It turned out to be accurate.

---
Tags: temperature-sensor, ds18b20
---


title: Serial Monitor (user input)

text:
# Question
Title: Serial Monitor (user input)
I'm trying figure out how to make the serial monitor printing specific content based on the user input. For instance if the user has typed '1' it should constantly print ("Hello") and when user has typed '2' it should print ("Bye") and vice versa. I'm new to programming, so I would be grateful if any can help me with this.

```
  String readString;

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

       void loop()
       {

         if(Serial.available()>0)

         {
            char c = Serial.read();
            readString +=c;
            delay(2);

                   if (c == '1')
                    {
                     delay(1000);
                     Serial.println("Hello");
                     c = "";
                    }

                                 if (c == '2')
                                  {
                                    delay(1000);
                                    Serial.println("Bye");
                                    c = "";
                                  }
             else
            {
             readString= "";
            }
          }
        }

```

# Answer
You have most of what is needed but you have it structured incorrectly.

Because you want to print continuously, you need to split your program into 2 sections. One section deals with the serial input and the other with the printing.

The serial handling part checks if there are any characters to be read. If so, it simply stores the character that you read into a global variable.

The printing part executes every time through the loop and prints the value you want based on the global variable, which may, from time to time, change if something new arrives on the serial port.

This code is untested:

```
char cMode;

void loop()
{
  if(Serial.available())
  {
    char c = Serial.read();

    if (c == '1' || c == '2')
      cMode = c;
  }

  if (cMode == '1')
    Serial.println("Hello");
  else if (cMode == '2')
    Serial.println("Bye");

  delay(1000); // to slow down the loop?
}

```
> 3 votes

# Answer
Try out this code. It will helpful for you.

```
char serialData;

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

void loop()
{
  if(Serial.available())
  {
    serialData = Serial.read();

    if(serialData == '1')
    {
      Serial.println("Hello");
    }
    else if(serialData == '2')
    {
      Serial.println("Bye");
    }
  }
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Deprecated Conversion error

text:
# Question
Title: Deprecated Conversion error
I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming How to remove it?

C:\Users\Mahe\Documents\Arduino\sketch\_mar09b\sketch\_mar09b.ino: In function 'void updateState(byte)':

C:\Users\Mahe\Documents\Arduino\sketch\_mar09b\sketch\_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char\*' \[-Wwrite-strings\]

```
   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

```

# Answer
> 1 votes
> I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming How to remove it?

```
C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

```

To give a detailed answer the full prototype for DisplayInfo() is needed. The issue is that the literal strings are `const char*` and the function parameters are declared as `char*`.

The correct way to fix this would be to update DisplayInfo() so that the parameter types are `const char*`. The dirty fix is to cast the parameters in the call.

```
   DisplayInfo((char*) "RFID Scanner", (char*) "Starting up", HIGH, HIGH);

```

But I would not recommend that.

Cheers!

---
Tags: arduino-uno
---


# Question
Title: How i can have one code for multi sensors
am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

# Answer
> 6 votes
You have to keep some points in your mind:

(1) You have to ensure that pins must be not conflicting with each other. If you merge all sensor codes in one code then pins must be conflict. So you have to change pin number.

(2) If all sensors have separate working then make the function for all that sensors. It will very helpful for understanding and debugging the entire code.

(3) Don't try to merge all codes same time. Add one by one and also change pin number during that.

# Answer
> 1 votes
> am doing multi sensor project concerning PIR,vibration,tilt angle,temp&humidity,gas sensors with LCD in Arduiono mega ...i have each sensor code,need help on programming in one program

This could be considered a general question: Is it possible to merge several sketches and if so how?

The first step is to check pin conflicts: Are any of the sketches using the same pins (or resources)? If that is the case this needs to be resolved.

The next step is to check timing. Is is sufficient to run each loop() after each other or does the timing behavior also require changes.

The idea is then to simply "merge" the different setup() and loop() functions to a single setup() and loop().

In most cases, the timing behavior will leave no other choice than to rewrite the code.

There are a few tools (such as a Scheduler) that can be used but they require additional understanding of programming and nothing for the novice.

---
Tags: bootloader
---


# Question
Title: Problems powering standalone arduino with USB powerbank
I've successfully migrated and ATMEL328P-UP microcontroller from the Arduino Uno Board to a breaboard, following these instructions: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard. Everything is OK, the bootloader worked and code is already uploaded an running.

The ATMEL is connected to a pair of sensors, and all the system works using 3.3V. And here comes the problem: I'm using a 5V USB power bank to power up everything. When I make this connection:

*USB Power Bank @ 5V -\> Arduino Uno board (without the microcontroller) -\> 3.3 V Output from the board -\> ATMEL/Sensors on the breadboard*

everything works just fine! Now I decided to replace the Arduino uno board with an LM317 voltage regulator which gives me the 3.3V needed. The connection is this:

*USB Power Bank @ 5V -\> LM317 with 3.3 V output -\> ATMEL/Sensors on the breadboard*

and nothing happens! Is as if there wasn't enough current to feed the ATMEL nor the sensors. I've checked the Vcc/GND pins of the sensors and the ATMEL and they're all getting the required 3.3 V, but for some reason the system seems to be OFF.

What could be happening? I'm sure the USB power bank is at full charge, so it should be able to supply enough current. Any suggestions?

Thanks guys!

# Answer
> 4 votes
According to the datasheet, the LM317 needs an input voltage 3v higher than the output. Since 6.3\<5, there's not enough margin for the LM317.

You can use an AMS117 LDO @3.3, which only needs an input of 3.9v to operate. I find these modules very handy. If the MCU has some tolerances, you can likely get away with using a diode or two in series with the 5v rail to drop it down; the actual forward voltage fluctuates slightly on load, but it will likely stay in the acceptable range for your MCU.

you can also use a switch-mode regulator, commonly sold as "buck converters" on ebay, to more efficiently reduce the voltage. This is the way to go over linear regulator like the 317 if you power your project from batteries or have concerns about heat. I go through a lot of these style converters, and they seem to work very well.

---
Tags: arduino-uno, power, atmel
---


# Question
Title: Arduino UNO WiFi "wifi shield not present"
I currently use the Arduino UNO WiFi, but when I try to use the WifiChatServer example, I keep getting the same error: `wifi shield not present`.

What am I doing wrong?

# Answer
That example, and the library it comes with, are for the Arduino WiFi Shield. Not the Arduino Uno WiFi, which is an Arduino Uno with an ESP8266 strapped on the side through an I2C-\>UART converter chip.

You can't use that library, nor the examples that come with it. Instead you need to use the Uno WiFi library as stated in the FAQ for the board:

> If you are using the Arduino 1.7.x then you need to use the ArduinoWiFi.h library that it is already included in the IDE. Instead you are using the Arduino 1.8.x then you need to download the UNOWiFiDev.Edition library from Library Manager.
> 1 votes

---
Tags: arduino-uno, wifi, shields
---


# Question
Title: Blink 2 LEDs one at a time every x seconds
Newbie here - literally opened my Arduino about 3 hours ago. I have been able to code 2 LEDs to blink randomly, but what I want to do is have one of the two blink every 10 seconds.

My current code:

```
void setup() {
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop() {
  // set 2 random on/off values
  byte on4 = random(2); //returns a random choice of 0 or 1
  byte on5 = random(2);

  //Write the value of each variable to the pins.
  digitalWrite(4,on4);
  digitalWrite(5,on5);
  delay(500);
}

```

I know I have to do something to the loops, I just can't figure out what.

# Answer
> 4 votes
Try out this code. It will helpful.

```
const int kPinLed = 4;      // LED at pin 4

void setup()
{
  pinMode(kPinLed, OUTPUT); // LED as OUTPUT
}

void loop()
{
  digitalWrite(kPinLed, HIGH); // LED ON
  delay(10000);                // 10 Sec delay
  digitalWrite(kPinLed, LOW);  // LED OFF
  delay(10000);                // 10 Sec delay
}

```

# Answer
> 0 votes
Choose if you want to keep pin 4 or 5. Remove every reference to the other.

Move the declaration of the remaining pin outside of the loop, before the setup function. Ex: byte on4;

inside setup, assign a value (1 or 0) to the surviving pin. Ex: on4 = 0;

inside the loop, change the value of the pin. EX: on4 = !on4;

digitalWrite changes the state of the pins driving the LEDs. Remove the one you do not want.

delay expresses how long the system waits, in milliseconds. Change accordingly.

```
byte on4;

void setup() {
  on4 = 0;
  pinMode(4, OUTPUT);
}

void loop() {;
  on4 = !on4;
  digitalWrite(4,on4);
  delay(10000);
}

```

This should work, but I have not tested it.

# Answer
> 0 votes
You need to split the logic into 2 parts. One part will select the pin that you want to blink and the other will blink the pin. I'll show how you do this using delay() but, clearly, it would be better to use the BlinkWithoutDelay methods of counting time so the processor can do something else. This code is untested and is set up so that you can just add pins to the ledPin array with no other changes and it will always work properly.

```
uint8_t ledPin[] = { 4, 5 };  // Arduino pins with the LEDs

#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

void BlinkOne(uint8_t pin)
{
  digitalWrite(pin, HIGH);
  delay(5000);
  digitalWrite(pin, LOW);
  delay(5000);
}

void setup(void)
{
  for (uint8_t i=0; i<ARRAY_SIZE(ledPin); i++)
    setMode(ledPin[i], OUTPUT);
}

void loop(void)
{
  uint8_t thisPin = ledPin[random(ARRAY_SIZE(ledPin))];  // select which pin

  BlinkOne(thisPin);  // blink that pin
}

```

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


# Question
Title: Char transmission using Virtualwire RF signal
This is a really basic problem, but I haven't been able to resolve it myself and would really appreciate the help. So I've been struggling for a few weeks now to set up RF communication between two arduino uno chips. I have the transmitter and receiver hooked up to 5V supply, with the data pins connected to digital pin 4. My code looks like this:

Transmitter code:

```
#define rfTransmitPin 4  //RF Transmitter pin = digital pin 4
#define ledPin 13        //Onboard LED = digital pin 13

unsigned int data = 0;  // variable used to store transmission data

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

void loop(){
  digitalWrite (rfTransmitPin, HIGH);
  data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
  Serial.println(data);
  digitalWrite (ledPin, HIGH);
  delay(2000);

  digitalWrite (rfTransmitPin, LOW);
  data = digitalRead (rfTransmitPin); // Read the digital transmitter pin
  Serial.println(data);
  digitalWrite (ledPin, LOW);
  delay(2000);
  }

```

Receiver code:

```
#define rfReceivePin 4  //RF Receiver pin = digital pin 4
#define ledPin 13        //Onboard LED = digital pin 13

unsigned int data = 0;   // variable used to store received data

void setup(){
  pinMode(ledPin, OUTPUT);
  pinMode(rfReceivePin, INPUT);
  Serial.begin(9600);
}

void loop(){
  data=digitalRead(rfReceivePin);    //listen for data on Digital Pin 4

   if(data = HIGH){
    digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
    Serial.println(data);
  }

  if(data = LOW){
    digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
    Serial.println(data);
  }
}

```

This should be really simple, but for some reason I'm reading a continual HIGH signal from the receiver module. I'm trying to sort out the basic functionality of the RF tx-rx pair before developing code to send a char using the Virtual Wire library, but I can't even get it to function at this level. Since my code is so basic I'm convinced it must be a hardware issue and I'm not sure what I'm doing wrong. Any suggestions?

# Answer
VIf you using Virutalwire try exemple in the library. You can't send simple digitata data with Rf. Best Regards Mikael

link Virutalwire
> 1 votes

---
Tags: arduino-uno, rf, remote-control
---


title: Run exe or apk on Arduino

text:
# Question
Title: Run exe or apk on Arduino
how to run exe file or apk file on Arduino UNO?

Please suggest me any way to execute both file. Thank you.

# Answer
You cannot. An APK is an Android package, and an EXE is a Windows executable. Neither can run on an Arduino,
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How to execute three functions at the same time?
How to implement **three functions**, which can **execute in the same time** (function of input random variables)?

# Answer
No single processor can do more than one thing at a time. The best you can hope for is that each function runs for a short time only and gives the processor to the next one, giving the illusion that there is more than one thing happening at once. This is called **multi-tasking** or **multi-threading**.

There are some libraries that will do this for the Arduino (search "RTOS Arduino" or "Arduino multitasking"), or you can write each functions using the principles of **Finite State Machine** programming to achieve the same effect.
> 4 votes

# Answer
You can implement three functions but you can't able to execute them same time.
> 5 votes

# Answer
> How to implement three functions, which can execute in the same time (function of input random variables)?

Micro-controllers such as the AVR used on Arduino boards have only one processing core but there are many hardware modules (ADC, UART, SPI, TWI, Timers, etc). Using these it is possible to achieve several "functions" at the same time, i.e. pure concurrency.

Some examples, while waiting for ...

1. ADC (analogRead) there are over 100 cycles
2. SPI (spi.transfer) there are 16 cycles
3. UART (Serial) is actually already concurrent with buffering and ISR's.
4. The same goes for I2C (twi).

These cycles can be used to interleave different functions or improve performance (e.g. pre-fetching, pipe-lining).

Another example; using direct port read it is possible to read the state of several pins at the same time.

With simple collaborative multi-tasking it is possible to context switch between several functions (tasks) on delay or yield. This can be done with a scheduler.
> 4 votes

# Answer
> How to implement three functions, which can execute in the same time (function of input random variables)?

have three executors / arduinos, one for each function.
> 2 votes

# Answer
If the result of each function can be expressed as a single byte (i.e. an integer between 0 and 255) then you could:

* Connect 3 shift registers (e.g. 74595 ic) to 3 pins on your Arduino
* Assign one pin to each function
* Use the shiftOut function to output the result of each function one bit at a time on its relevant pin
* Use a 4th pin connected to all 3 shift registers as a common latch - when this pin is set HIGH the outputs from the 3 shift registers will all change at the same time.
> 2 votes

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


title: How accurate is arduino time keeping?

text:
# Question
Title: How accurate is arduino time keeping?
I want to use my arduino to turn a light off for 16 hours and on for 8 hours. I know the general code, just using delays and the relay shield code as well. I want to know how accurate this will be? ( I tagged uno and leonardo, as I have access to both)

# Answer
> 1 votes
There are multiple versions and "clones" of the Arduino, and each one will probably use different components. The time you refer, in this case "millis()" I believe, is maintained from a timer interrupt, which is derived from the main clock (normally 16Mhz).

The main clock on your board might be generated by a ceramic resonator, which is not very accurate: around 0.5%-1% error. It also might be from good quartz crystal, with up to 0.001% accuracy. Those variations on the frequency source will produce some drift over time... Like your watch needs to be readjusted from time to time.

Another factor that affects accuracy, including for RTCs using a 32.768KHz crystal, is the temperature. Here an Application Note on this: http://www.st.com/content/ccc/resource/technical/document/application\_note/55/e2/3d/2a/87/ab/4d/e1/CD00232494.pdf/files/CD00232494.pdf/jcr:content/translations/en.CD00232494.pdf

Your application might not require too much precision, and you could simply write a sketch to print the time every second on the serial... let it run from one hour, one day, and check how much drift you're getting. After that will be easy to estimate how much drift you'll have a after a month.

# Answer
> 1 votes
By definition, the Arduino is as accurate as it's crystal clock/resonator.

This clock runs at approximately 16mhz for an Uno.

The Arduino's internal time is just a count of how many times this crystal has vibrated.

**READ THIS!** \- these next two paragraph are apparently **incorrect**. See Nick Gammon's comment below.

> The crystal in question is approximately like this one: https://www.sparkfun.com/products/536 \- this one from SparkFun is accurate to 50 ppm - that's parts per million. So, if your Arduino has that EXACT crystal, it may lose or gain 50 parts per million - in a million seconds, it would count somewhere between 999,950 and 1,000,050 seconds. This would mean you gain/lose less than 4.3 seconds per day, or 2 minutes per month. If you find the crystal on your board, google the code (probably something like 16.000N, for the Sparkfun one), which should tell you exactly what the accuracy is for that chip. Note that, if you can find the datasheet, it should tell you the accuracy, at particular temperatures - as the temperature goes up and down, the error will change too.

Remember also that an Arduino's clock is in volatile memory - that is, if you power down the Arduino, and power it back up, it has no idea what time it is - you would need to set the clock again, either by connecting it to a PC, network, or via buttons/display on your project.

There are a number of alternatives, depending on your need, to work around this: you can get the data from LAN or WIFI, if your project has that, or you can use a RTC module - you need to set this to the correct time once, then it will remember after that.

Alternatively, you can use a light-dependent resistor (aka photoresistor), and trigger automatically when it gets dark. This may trigger when it gets dark for some other reason, e.g. a storm, which may or may not be an advantage.

# Answer
> 1 votes
I made a temperature and humidity sensor in August 2013. It uses a RTC chip (DS1307) which you can buy on eBay for $1 if not less. It has a battery backup (lithium cell).

I don't recall ever resetting the clock on it. It is now about 3 years later, and it is running about 11 minutes slow. This would be an acceptable error for something like turning garden lights on and off. Even for taking the temperature, a few minutes out when logging a reading is probably not going to matter.

Using the internal clock probably won't be as accurate, but could be OK in this case. I suggest you follow Chris Stratton's suggestion and code so that errors are not cumulative. For example, if you delay for an hour, and then do something, make sure that the "do something" isn't added to the next delay time.

If you want super accuracy (sounds like you don't) then connecting up a GPS module lets you query the exact time from the satellite, which could cut the error down to negligible amounts. Those GPS modules however aren't cheap.

---

Something to consider if you try to make do with the internal clock is: what happens if the power goes off? Then it loses track of when to turn the lights on and off. A clock chip however (usually) has a battery backup, and will "know the time" once the power comes back on.

# Answer
> 1 votes
I think that RTC modules and real time clock chips have some sort of "mistake" said that, it CAN max. delay for fast forward for max. 6 seconds per month. Something as this, I've read year or so ago, when I was dealing with some sort of doors locking mechanism.

But for app. 8 hours, there's an arduino RTC module more than enough, I'd say. I assume, that seconds doesn't matter.

# Answer
> 1 votes
Just because it's always an option... I'm usually connecting my Arduinos to the Internet one way or another, so I just get the time from NTP servers once every day or so using UDP to keep the clock accurate, or accurate enough.

The advantage is that, even if power is lost, it's relatively easy to ask Arduino to get the time while booting up. Then it always knows, and is always on time.

Happy to share fave code, but I found mine in UDP library examples and have adapted it to my own needs.

# Answer
> 0 votes
Not very.

For that kind of period of timing you are far better off using a Real Time Clock (RTC) module.

# Answer
> 0 votes
> I want to know how accurate this will be?

accuracy is a function of coding and hardware. with good coding, you can make it as accurate as your hardware is capable of.

I experimented with a tco-919 high accuracy oscillator (19.2Mhz), in an unairconditioned environment, no meaningful timing drift after a month.

So if you really want accuracy, go with a good oscillator.

if you just care about reasonable accuracy (1%?), the internal oscillator will do.

---
Tags: arduino-uno, sensors, arduino-leonardo, timers
---


# Question
Title: Why is my circuit working only when I touch it?
I have connected digital pin 2 of arduino to the circuit as shown:  The problem is that the LED is not turning on normally its only turning on when I touch anything on collector side of circuit. What seems to be the reason? Seems like grounding problem as its turning off when I don't touch my legs to ground.

Thank you in advance.

# Answer
Sounds like you have guessed it: although it's very hard to say from those photos, it doesn't look like you have the circuit grounded.

Connect a ground from the Arduino to the black wire from the battery.
> 4 votes

---
Tags: led, arduino-pro-micro, transistor
---


title: SSD1306Ascii Library

text:
# Question
Title: SSD1306Ascii Library
Is there any way to add Inverse Text color function into SSD1306Ascii library like which is available in ssd1306 adafruit library ?

# Answer
Yes, you can edit the library yourself, or copy its functions to your sketch and modify them.

You can also use another library, like u8g2.
> 2 votes

---
Tags: arduino-pro-mini, adafruit
---


# Question
Title: Is there any way to use a JTAG programmer with the Arduino IDE?
I am doing a lot of work with custom boards I've designed with the ATSAMD21G. I'd like to get away from using USB to program my boards since the USB port takes up space on the PCB and consumes extra pins. Is there any recommended way to configure the Arduino IDE to simply dump out the compiled program into a JLink debugger, much like the Atmel Studio IDE can?

# Answer
> 1 votes
For a one-click upload, you can make a custom hardware definition that calls any executable of your choosing.

# Answer
> 0 votes
The IDE makes a .hex file which you can then program onto your chip with a suitable programmer.

---
Tags: arduino-zero
---


title: How to convert macros for Arduino code?

text:
# Question
Title: How to convert macros for Arduino code?
I have a piece of code I'd like to make Arduino editor friendly. The code is written in C and contains macros the Arduino IDE can't deal with. Is it a good idea to turn those macros into functions?

```
#define AN221_EXECUTE_Low   cbi(PORTA, PIN0)        //drive EXECUTE low
#define AN221_PORb_High     sbi(PORTA, PIN1)        //drive PORb high
#define AN221_ACTIVATE      bit_is_set(PINA, PIN2)      //sense ACTIVATE high
#define AN221_NO_ERROR      bit_is_set(PINA, PIN3)      //sense ERRb high i.e. no rror
#define AN221_ERRb_Input    outp(0xEB, DDRA)        //make uP drive ERRb
#define AN221_ERRb_Output   outp(0xE3, DDRA)        //make uP sense ERRb

```

# Answer
> 2 votes
> Is it a good idea to turn those macros into functions?

it depends.

macros are fast, but lack type checking.

functions offer type checking but incur overhead.

whether one is better than the other depends on your priorities.

---
Tags: c
---


# Question
Title: My HM-10 Bluetooth module only returns OK after any AT command
I bought an HM-10 Bluetooth module (BLE 4.0) to use in my school project. Every command that I send to it, it always returns "OK". Can you guys help me?

Here's the code that I am using in my Arduino Uno.

```
#include <SoftwareSerial.h>

SoftwareSerial BT(10, 11); // RX, TX
String command = ""; // Stores response of bluetooth device

void setup() {
  BT.begin(9600); // HC-06's usual default baud-rate
  Serial.begin(9600);
  Serial.println("Type AT commands!");
}

void loop() {
  if (BT.available()) {
    // Read device output if available.
    while(BT.available()) {
      // While there is more to be read, keep reading.
      delay(10); //Delay added to make thing stable
      char c = BT.read(); //Conduct a serial read
      command += c; //build the string.
    }
    Serial.println(command);
    command = ""; // No repeats
  }
  if (Serial.available()) {
    delay(10);
    BT.write(Serial.read());
  }
}

```

# Answer
On the command write you read only one character to send to bluetooth.

Make same than for bluetooth to serial part above:

```
void loop()
{
if (BT.available()) // Read device output if available.
{
  while(BT.available()) // While there is more to be read, keep reading.
 {
   delay(10); //Delay added to make thing stable
   char c = BT.read(); //Conduct a serial read
   command += c; //build the string.
  }
  Serial.println(command);
  command = ""; // No repeats
}

if (Serial.available())
{
  while(Serial.available())
  {
     delay(10);
     char d = Serial.read(); //Conduct a serial read
     command += d; //build the string.
  }
  BT.write(command);
  command = "";
 }
}

```
> 1 votes

---
Tags: arduino-uno, communication
---


title: Bredboard board in new release

text:
# Question
Title: Bredboard board in new release
I had installed the old release (1.0.5) but for some reasons arduino stops working and I upgraded to new version 1.8.2, all works fine but I would like to use the **bredboard 8Mhz** version in the new release, but the **boards** system is not compatible with new version. The **boards.txt** is this:

```
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=stk500
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.path=arduino:atmega
atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

```

How to build it to be compatible with news version? Thank you

# Answer
> 1 votes
I found a solution in this video:

https://www.youtube.com/watch?v=cebMSJrNntI

Adding:

```
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.board=AVR_ATMEGA328BB
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

```

to **/hardware/arduino/avr/boards.txt**

---
Tags: atmega328
---


title: How do I use a photodiode for arduino?

text:
# Question
Title: How do I use a photodiode for arduino?
I am doing a project that requires me to program an arduino to sense changes of a steady stream of light due to the scattering of that light. If the phootodiode does change its resistance to the current, then a flap will turn a certain number of degrees. I'm not sure how to operate a photodiode, but know the basics of how it works.

The apparatus is designed to increase the operating life of a solar panel on Mars. When dust from a dust storm collects on its surface, a photodiode will detect the change in light and change its resistance to a current running through it. Then a flap connected to the solar panel will close to cover the solar panel. I'm using Hitec HS-311 Standard servo to rotate the flap, but I've had some problems operating it.

# Answer
> -1 votes
try to use an opamp to create a voltage output from the diode. you can then adc that voltage output from the mcu.

---
Tags: arduino-uno, programming, sensors, servo
---


title: (Beginner) Blinking led call function

text:
# Question
Title: (Beginner) Blinking led call function
I'm completely new to this world, so probably my question would sound noobish, but here it is:

I'm trying to make a led blinking just for 5 times by calling a "for" cycle inside void loop(). The confirmation of the successful cycle would come from the Serial Monitor which will print "let's star over", and at the end of each blinking cycle, it will print the text "cycle done".

The point is that my code doesn't work, the led remain switched ON and the serial monitor blank. What is wrong with it?

```
int ledred = 3;
int count = 5;

void setup() {
  digitalWrite(ledred, LOW);
  pinMode(ledred, OUTPUT);

}

void loop() {

    blinkingred(ledred, count);
    Serial.println("let's start over")

}

void blinkingred(int ledred, int count)
{
  for(byte i=0; i == count; i++)
  {
        digitalWrite(ledred, HIGH);
        delay(1000);
        digitalWrite(ledred, LOW);
        delay(1000);
        Serial.println("Cycle done !");
  }
}

```

# Answer
There's two things wrong with your sketch - one fatal and one that is more confusing for humans.

First the fatal problem:

```
for(byte i=0; i == count; i++)

```

That `for` loop is never going to do anything. The way it is written it will loop only while `i` is equal to `count` (`0 == 5`) which it never will. Instead you need to loop while `i` is *less* than `count`:

```
for(byte i=0; i < count; i++)

```

The second issue is that you have named your function parameter variables the same as your global variables. While this is syntactically valid (the local variables will override the global ones) it is incredibly confusing for people to follow what is what and should be avoided at all costs.
> 1 votes

# Answer
the simplest would be to unroll your loop and repeat the code 5 times.

```
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);
  digitalWrite(ledred, HIGH); delay(1000); digitalWrite(ledred, LOW); delay(1000);

```

hard to get that wrong.
> -1 votes

---
Tags: arduino-uno
---


title: I think I have a bad batch of TPIC6B595

text:
# Question
Title: I think I have a bad batch of TPIC6B595
I want drive a large number of LEDS from an Arduino Pro Mini using a number of TPIC6B595. I purchased these on ebay, perhaps a mistake.

Initially I connected two TPIC6B595 as I would connect 74HC595 (with the exception of taking account of how the open drain outputs work) to the SPI pins of an Arduino Mega (my test bench system) and tried sending an alternating bit pattern to the LEDs. No alternating LEDs. I checked SRCLR was Vcc and OE (G) was Gnd. I poked about with my scope (Rigol DS1102D) and SRCK, RCK and SERIN looked as expected. Suspiciously SEROUT (pin 18) of the first chip was permanently LOW. Note that this is all on a breadboard.

I have used the 74HC595 now many times and from time to time I have made stupid mistakes in wiring/software. These usually stand out on the scope like a sore toe. Not this time.

So I decided to simplify it all and clock some data into a single TPIC6B595 using a simple non-SPI sketch and see if anything comes out of the SEROUT.

Here are the connections to the TPIC6B595 and to the Mega:

```
1 Not connected,  20  Not connected,
2 Vcc             19  Ground,
3 Arduino pin 12  18  Not connected (except to scope when tested),
4 Not connected   17  Not connected,
5 Not connected   16  Not connected,
6 Not connected   15  Not connected,
7 Not connected   14  Not connected,
8 Vcc             13  Arduino pin 11,
9 Ground          12 Ground (See note 1),
10 Ground         11  Ground.

```

The chip is bypassed by a 1uF electro across pins 2 and 10. Not ideal but the clock rates are low and it isn't unreliable, it just doesn't work at all. Note 1: I am not trying to test the transfer between the Shift Register and the output D flip-flops so RCK should be irrelevant. I just want to see data going in to SER IN , coming out on SER OUT.

Here's the Arduino code. It generates a slow clock and an alternating data bit every few clock cycles:

```
const int ser_clk = 11; // blue
const int ser_in  = 12; // white
byte data, count;

void setup()
{
  pinMode(ser_clk, OUTPUT);
  pinMode(ser_in,OUTPUT);

  digitalWrite(ser_clk, LOW);
  digitalWrite(ser_in, LOW);

  count = data = 0;
}

void loop()
{
  digitalWrite(ser_clk, HIGH);
  delay(1);
  digitalWrite(ser_clk, LOW);
  delay(1);

  count++;
  if (count >= 3)
     {
       count = 0;
       if (data == 0)
          {
            data = 1;
            digitalWrite(ser_in, HIGH);
          }
       else
          {
            data = 0;
            digitalWrite(ser_in, LOW);
          }
     }
}

```

Here's a screenshot of the wave-forms (photo of scope - sorry can't make UltraScope work):

The cyan trace is the "clock" from pin 11 of the Arduino feeding pin 13 (SRCLK) of the TPIC6B595. The yellow trace is the data from pin 12 of the Arduino feeding pin3 (SER IN) of the TPIC6B595. I am only looking to get the same data pattern out of SEROUT, pin 18 of the TPIC6B595 and this should do it. The clock is as slow as a wet week (see cursor) and even if I have bad set up and hold times and the wrong transitions the data is held for enough cycles for something to make it through surely?? Pin 18 is persistently and forever low. No screenshot - seems to be no point.

I bought several of these TPIC6B595. Tried 3 so far. All the same. Now I might have killed them with static. I am not using wrist straps, but I also don't believe I could have killed 3 of them.

As improbable as that is I think they are dead or duds, or is there something else wrong that is so obvious I cannot see it?

Regards, Fred.

# Answer
Thanks to all those who responded. I have a double embarrassment here as I have the answer. Firstly if you can answer your own question there is an argument it should never have been posted, more thought needed first. Sorry everyone. Secondly when the cause is ignoring well known good practice then it is even worse.

So when tying a pin to Vcc (in this case SRCLR) it is known bad practice to hard couple it to Vcc. A pull-up resistor is a much better method. In this case suitable pull-ups were in the next room and I could not be bothered so I just jumpered SRCLR to Vcc. After I had written the post I was staring at the breadboard and thought - I should not have really done that replaced the jumper with a 10K pullup to Vcc. Instantly the SEROUT pin of the TPIC6B595 came to life as it should have. Now I have taken this short-cut before and gotten away with it. But it seems not this time.

Subsequently I have a one chip version of the alternating LEDS running with the SPI interface.

As to the suggestion by dannyf about the datasheet, there is no doubt the datasheet is a good place place to go. **Prior** to developing my test sketch as per my original post I consulted the datasheet and if you look in Section 8, page 11 of the TI datasheet revised June 2015 there is a Functional Block Diagram. This block diagram clearly shows that the RCK signal is concerned only with the C2 column of D flip-flops which take the output from the shift register and latch it to the output FET through the output enable logic. RCK is independent of the process to clock data through the shift register, controlled by SRCLK. You will note my test did not exercise the transfer function it was just interested in getting data into the shift register and out again.

I stand by my assertion that for the serial shift register function and checking SEROUT, RCK is not relevant. Once you want to start data transfers from the shift register to the output register then it is different matter. No disagreement there. Having that timing wrong will lead to a mess of corrupted data.

Thanks again to all. This is solved and is a lesson to abide by good practice always.

Regards, Fred.
> 1 votes

---
Tags: shift-register
---


# Question
Title: Unable to type in Arduino IDE running on OS X
I'm trying to use the Arduino IDE (1.6.8 downloaded from arduino.cc) on a MacBook running OS X (10.11.5 beta).

The IDE seems to run and I can open and upload the examples and they run. But…

I can't type in the editor window of the IDE – either with the examples or with the new sketch that opens when you launch the IDE.

I have a similar problem with the version of the IDE distributed with mBlock (1.6.5) if I use the Edit in Arduino IDE button. I also tried the 1.6.9 hourly version. All to no avail. So I'm thinking that this is a OS X problem, or maybe an issue with version of Java (1.8.0).

Any ideas or troubleshooting suggestions?

# Answer
Make sure that in `preferences` the option `Use external editor` is **not** checked.
> 3 votes

# Answer
I find solution on this forum \[http://forum.arduino.cc/index.php?topic=93338.\] File | Preferences | Use External Editor (Don't use)
> 0 votes

# Answer
you may also consider Sublime Text -\> with the STino plug-in, it is a full-fledged editor that does everything your arduino IDE does, in a much more stylish way.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: Not showing output when using pins other than 10 and 11 with SoftwareSerial library on Arduino Mega
I am trying to run below code on Arduino Mega using GPS module(skg13 bl). It is working fine with pins 10, 11 as rx, tx in the SoftwareSerial but it is not showing output when other pins such as 4, 5 are used.

I further have to send this data through RF module using virtual wire library.

Code is as follows:

```
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
TinyGPSPlus gps;

SoftwareSerial mySerial(10, 11);

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  Serial.println("GPS start");
}

void loop() {
  while (mySerial.available()) {
    gps.encode(mySerial.read());
  }

  if (gps.location.isUpdated()) {
    double a = gps.location.lat();
    Serial.println(a);
    Serial.println(gps.location.lat(), 6);
    double b = gps.location.lng();
    Serial.println(gps.location.lng(), 6);
  }
}

```

Thanks in advance!!

# Answer
> 2 votes
From https://www.arduino.cc/en/Reference/softwareSerial:

> Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

So you will need to use one of the pins from that list for RX, pin 4 or 5 will not work.

---
Tags: gps, tinygps
---


title: I2C MCP4725 DAC connection speed

text:
# Question
Title: I2C MCP4725 DAC connection speed
I'm trying to use the MCP4725 DAC from Adafruit (https://www.adafruit.com/product/935) to output some waveforms over a frequency range up to about 50kHz. At the moment, I'm simply sending values to the DAC via the Wire library and through the DAC's onboard library. It appears that the values are only being sent at 7kHz. Is this due to the added weight of the libraries I'm using? Is there some way I can increase the transmission speed?

# Answer
> 1 votes
You cannot get 50kYz from a DAC running on I2C on an Arduino.

The maximum rate for I2C (if you select fast mode) is 400kbps. Setting the DAC takes three bytes plus start/stop/ack bits (total 29 bits).

At 400kbps that equates to (400000/29) 13793 settings per second.

Add to that the time taken to actually create and process the data, running the instructions to do everything, you can expect about half that - which is the 7kHz you're getting.

To get 50kHz from a DAC you really need a CODEC and run something like I2S, which you are never going to do on an Arduino.

---
Tags: i2c, wire-library
---


# Question
Title: "stray '/302' in program error" when compiling
For some weird reason, the following code doesn't compile. I get a "stray '\302' in program" error around `volatile unsigned int encoderPos = 0;`, and I have no idea what the issue is. I've been trying to figure this out for over 40min, and nothing works. It doesn't make any sense

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

//Pin definitions:

const int control_PWM = A3; //PWM output for the delay

const int btn_1 = 1; //Button for mode 1
const int btn_2 = 4; //Button for mode 2
const int btn_3 = 5; //Button for mode 3

const int r_A = 2; //Rotary encoder A's data
const int r_B = 3; //Rotary encoder A's data
const int r_SW = 0; //Rotary encoder's button data

const int oled_CLK = 9; //SPI cloack
const int oled_MOSI = 8; //MOSI pin
const int oled_CS = 7; //Chip Select pin
const int oled_DC = 6; //OLED's D/C pin
U8G2_SH1106_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8);

int mode = 1; //1: RGB, 2: HSL, 3: Distance control
int value_selection = 1; //Actual value selectrion
int value1 = 0; //red in mode 1; tint in mode 2
int value2 = 0; ////green in mode 1; saturation in mode 2
int value3 = 0; //blue in mode 1; luminosity in mode 2

volatile unsigned int encoderPos = 0;  // rotary encoder's current position
unsigned int lastReportedPos = 1;   // rotary encoder's previous position
static boolean rotating=false;      // is the encoder activity status

// interrupter variables
boolean A_set = false;
boolean B_set = false;
boolean A_change = false;
boolean B_change= false;
void setup() {

}

void loop() {
}

```

# Answer
> 7 votes
0302 is 0xc2. ~~Somewhere in your source you have one or more non-breaking spaces (0xa0) encoded in UTF-8 (0xc2 0xa0). Use `od` or a similar tool to find them, and then replace them with normal spaces.~~ Since you have non-ASCII Latin-1 characters in your source, those characters are encoded as two bytes with the first being 0xc2 or 0xc3. Remove all non-ASCII characters before proceeding.

# Answer
> 4 votes
One cause of the /(302) error is copy and paste code from a word processor. You have ASCII codes copied that add spaces, etc to your code. Go through each identified line and remove any extra spaces at the beginning and end of any identified line. Then, (Arduino IDE) go to TOOLS, Auto Format. At least, this cleared up the problem for me.

---
Tags: programming, arduino-ide, sketch, compilation-errors
---


# Question
Title: how can i fix the error ? stk500v2_getsync(): timeout communicating with programmer
I bought this Chinese Arduino Mega 2560 16AU.

This was the first time to deal with Arduino boards. When I try to upload a sketch I always get this error:

`stk500v2_getsync(): timeout communicating with programmer`

I successfully burnt a bootloader to it using an Arduino uno,
but the same error is there.

Finally I discovered the the loop test is not working, and only the LX LED flashes once when I enter a letter in the serial monitor.

# Answer
It's our old friend the CH340G again, isn't it?

You've been sold a dud, I'm afraid. The USB chip used there is dead. It happens a lot with those cheap Chinese boards. You should still be able to use the board with an external FTDI adapter by wiring it in to TX-\>RX, RX-\>TX and DTR-\>RESET (via a 100nF capacitor) with power and ground connected of course.

There is also a slim chance that the CH340G may interfere with the TX/RX pins, in which case you may need to remove it. Simply cutting the pins on it with an xacto knife then removing the stumps with a soldering iron and tweezers would do the job.
> 1 votes

# Answer
If You Downloaded the driver it should be fine!

https://github.com/jimaobian/CH34x\_Install\_V1.3
> 0 votes

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


title: MIDI and DMX together

text:
# Question
Title: MIDI and DMX together
I am fully new to Arduino (even don't have one ... yet), however, I'm looking into possibilities to use both MIDI in/out and DMX together. If I understand correctly the MIDI library (re)uses the UART/COM while the DMX does the same.

I am wondering if it can be used together (e.g. use MIDI in to control MIDI out and/or DMX out).

(Also still checking if I would need some simple MIDI/DMX components or 'full' MIDI or DMX shields/boards.)

# Answer
> 1 votes
Yes you can use multiple UART/Serial devices with a single Arduino.

However, there are some things to consider:

The Arduino Uno supports a single hardware serial connection (which is used for programming and debugging with the Serial Monitor). The Arduino Mega supports 4 hardware serial connections.

The arduino environment has a software Serial library that allows for additional Serial connections. However it is worth noting that software serial is slower than its hardware counterpart.

Also, if you want to use software serial, be sure to verify that any shields you want to use will support using a software serial connection.

# Answer
> 1 votes
The DmxSimple/DmxMaster library does not use serial and will work simultaneously with the MIDI library by 47 Effects. I have used the Sparkfun MIDI shield with the Tinkerkit DMX shield. The trick to stacking them is using tall headers on the MIDI shield and not soldering the XLR connectors on the DMX shield.

Or you can use a Teensy which has multiple hardware serials and more RAM at a good price but requires building a couple basic circuits.

---
Tags: midi
---


title: Generating random pattern on startup

text:
# Question
Title: Generating random pattern on startup
I'm trying to get an arduino to generate a random pattern in a neopixel grid every time you restart it. But I only get the same number sequence generated each time. What I'm doing wrong?

Here's the sequence that keeps happening: 1110 0000 1101 0011

Here's the code I have so far:

```
/* ========================== INCLUDES ================================= */
#include "RGB.h"

#include <Adafruit_NeoPixel.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_GFX.h>
#ifndef PSTR
 #define PSTR // Make Arduino Due happy
#endif

/* ========================== NEOPIXELS SETTINGS ================================= */
#define NEOPIN 6
#define MATRIX_W 4
#define MATRIX_H 4

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(MATRIX_W, MATRIX_H, NEOPIN,
  NEO_MATRIX_BOTTOM + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
  NEO_GRB + NEO_KHZ800);

/* ========================== BOARD / GRID STUFF ================================= */

/* coordinates for a 4 x 4 grid
00,10,20,30
01,11,21,31
02,12,22,32
03,13,23,33,
04,14,24,34
*/

int land[4][4] = {};

/* ========================== SETUP AND LOOP ================================= */

void setup(){

  Serial.begin(9600);

  matrix.begin();
  matrix.setBrightness(60);
  matrix.fillScreen(matrix.Color(off.r,off.g,off.b));
  crossFade(off, white, 50, 5);
  drawLand();
}

void loop(){
  matrix.show();
}

/* ========================== FUNCTIONS ================================= */

  void drawLand() {
  for(int row = 0; row < MATRIX_W; row++) {
    for(int column = 0; column < MATRIX_H; column++) {

     land[row][column] = random(0,2);

     Serial.println(land[row][column]);
     if(land[row][column] == 1) {
       matrix.drawPixel(column, row, matrix.Color(red.r,red.g,red.b));
     }
   }
  }
}

```

# Answer
> 0 votes
It's because an machine running the same program on the same data will calculate the same result. rand() is a *pseudo*-random generator for that reason. With the same starting value it will create the same sequence of numbers. The only way to get different outputs is to provide different inputs: You have to start rand with a different value each run. You can set initialize rand() by supplying an unsigned int to randomSeed(). But it still needs to be different from run to run for you get different outputs from those runs.

Some devices do this by reading a real-time clock on startup and hashing the result in some way. Another method is to ask the user to press a button or a key and using the response time (and possibly the key, if it's a keyboard) to generate the seed. Counting non-repeating events, like electrical noise or background radiation is another way.

But bottom line: you need different inputs to get different outputs.

# Answer
> 1 votes
Re: previous comments. You can use a product, sum, and modulus/LSB of analogRead's to make it unpredictable and give somewhat equally probable outcomes. The timing of multiple analogRead's could potentially affect the randomness.

# Answer
> 0 votes
> randomSeed(analogRead(A0)); does the trick well

Better yet, use the lsb of analogreads to seed the random number generator. No repeat patterns any more.

---
Tags: neopixel, arduino-setup
---


# Question
Title: 47Effects MIDI Library and serial debugging
I noticed that since I use the MIDI library from 47effects, I cannot use the print(ln) for the serial port for debugging purposes, neither I can find it in the documentation.

It states that the MIDI library uses the serial port, but I really miss the serial port now for debugging.

Update: so my question: The MIDI library uses the RX (pin 0) and TX (pin 1) on my Arduino One. However, I think the internal Serial.print/println also uses these same pins, so I was wondering how I can use Serial.print and Serial.println statements being visible on the Arduino IDE Terminal (emulator) while using the MIDI library.

# Answer
I assume you have one or more Arduinos, are trying to do MIDI control, and want to know how to debug with the MIDI library having commandeered the hardware serial port.

One approach is to use I2C or SPI to communicate with a second Arduino, which uses its serial port to deliver debugging data to a host system. See Nick Gammon's excellent page Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329), which illustrates communication between two Arduinos, using one of them as a slave to forward information sent by I2C or SPI from a system being debugged.

Another approach might be to use a *serial bridge*. I don't know the ins and outs of this or exactly what it does but have read that, for example, the Hairless bridge (which is an open-sourced software package) can display both sides of MIDI communication, possibly depending on use of `Serial.write` vs `Serial.print`. You could designate certain note sequences as standing for various debugging cases.

A third approach is use of Arduino software serial to send debugging data to a serial port on your host system. This would use some Arduino pins other than the hardware Rx, Tx pins.

*Edit 1: Pin Usage –*

For approach 1, using I2C ties up two specific pins, SDA and SCK. These are shared with other I2C devices, if any. SPI typically shares three signals – SCLK, MOSI, and MISO – among all SPI devices, and generates one SS signal per device. For pinout and protocol details, see Nick Gammon's well-organized and clearly-illustrated I2C and SPI pages.

Approach 2 would use no extra pins.

Approach 3 would use one or two extra pins: one for half-duplex or output-only communication (which may be adequate for debugging), two for separate Rx, Tx lines. Compared to hardware serial, software serial is CPU-intensive, does not support as-high data rates, and has a higher error rate. It should work ok for light-weight debugging output, such as occasional text to show what tests succeeded or failed or what branch was taken, or values of a few variables.
> 1 votes

---
Tags: serial, debugging, midi
---


# Question
Title: HELP with, I think, are wrongly placed Interrupts
I am still struggling to get this sketch functional. The problem seems to lie with the interrupts, and relying on them to turn on and off the PIRtrigger when needed. Everything else seems to be OK. This is a slightly modified sketch from what I had uploaded earlier, with some changes that I thought would fix the problem. In general, a "correct" PIN disables the alarm from firing as it sets the "away" flag to "false", which works. An "incorrect" PIN sets "away" to "true" which, when a trigger is activated via an Interrupt, sounds the alarm. The program should then go to readKeypad for further function, which it appears to do. The following shows the result after an incorrect PIN:

```
Key_input[0] = #
@ checkPIN
@ incorrect PIN
away=1 PIRtrigger=0
at Alarm
after alarm

```

The trigger then doesn't seem to get activated. Can anyone HELP!? Thanks.

```
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;

//To change pins for Software Serial, use the two lines in GSM.cpp.
int PIR_SensorPin = 2;
int LED_OutPin = 11; //green
int Alarm_OutPin = 12; //red
int alarm_count;
volatile boolean PIRtrigger = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;
int timeout = 10000;
unsigned long time = millis();

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (LED_OutPin, HIGH);
  }
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
  Serial.println ("System Ready");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop()
{
  interrupts();
  readKeypad(); Serial.println ("at keypad");
  alarm();
}

////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  PIRtrigger = true;
  // alarm();
}

///////////////////////////// void alarm ///////////////////////////////////
void alarm() {
//  PIRtrigger = false;
  time = millis(); // reset time.
  interrupts();
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
  Serial.println ("at Alarm");
  if (away == true && PIRtrigger == true) {
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW); delay (500);
      digitalWrite (LED_OutPin, HIGH); // delay (1000);
      Serial.println (alarm_count);
    }
  }
  PIRtrigger = false;
  //  away = false;
  Serial.println ("after alarm");
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
  noInterrupts(); /////////////////////////////////
  readKeypad();
}

///////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    tone(10, 900, 100);
    Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          //        Serial.print(key_input[i]);
        }
        //      Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

///////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    //   Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();// go to correct PIN instructions
  }
  else {
    incorrectPIN(); // go to incorrect PIN instructions
  }
}

///////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  // digitalWrite (LED_OutPin, HIGH);
  digitalWrite (LED_OutPin, LOW); // on-board LED to show the status of alarm
  PIRtrigger = false; // turn the PIR state to off
  away = false; // turn the away state to off
  noInterrupts();
  readKeypad();
}

///////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
 //  noInterrupts(); // Serial.println ("interrupt off 1");
  Serial.println ("@ incorrect PIN ");
  away = true;
  digitalWrite (LED_OutPin, HIGH); // tied to Alarm output level
  //Has time passed? delay(timeout) - allow time to leave premises
  PIRtrigger = false;
    alarm();
  }

```

# Answer
First, as AH L said, there is no HIGH interrupt on a Uno. Looking at Arduino.h we see:

```
#define HIGH 0x1
#define LOW  0x0

...

#define CHANGE 1
#define FALLING 2
#define RISING 3

```

Thus your HIGH interrupt (which doesn't exist) is really a CHANGE interrupt.

Next, you seem to be recursively calling stuff.

* `loop` calls `readKeypad`.
* `readKeypad` calls `checkPIN`
* `checkPIN` calls `correctPIN`
* `correctPIN` calls `readKeypad`

So this code is digging itself deeper and deeper into function calls. It will eventually run out of stack.

i.e.

```
readKeypad -> checkPIN -> correctPIN -> readKeypad -> checkPIN ...

```

You need to restructure.

See my page about interrupts.

Also see my page about state machines.
> 1 votes

# Answer
Most Arduinos don't support interrupting when a pin is HIGH. Try changing `attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH)` to `attachInterrupt (digitalPinToInterrupt (2), trigger, RISING)`.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Errors when compiling the GSM SMS receive example from the Arduino IDE
I want to receive SMS and check whether the character is 'y' or 'n'. If it is 'y', set a pin to high so that a light glows. I thought I could use the example code given in the Arduino IDE for receiving SMS, but when I compile (without connecting the board, using ctrl+r) it shows the following errors:

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

In file included from F:\Arduino\libraries\GSM\src/GSM.h:46:0,
                 from F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:21:
F:\Arduino\libraries\GSM\src/GSM3ShieldV1BandManagement.h:49:125: warning: 'typedef' was ignored in this declaration
 typedef enum GSM3GSMBand {UNDEFINED, EGSM_MODE, DCS_MODE, PCS_MODE, EGSM_DCS_MODE, GSM850_PCS_MODE, GSM850_EGSM_DCS_PCS_MODE};
                                                                                ^
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino: In function 'void setup()':
F:\Arduino\libraries\GSM\examples\ReceiveSMS\ReceiveSMS.ino:47:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
     if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
                                  ^
Sketch uses 13322 bytes (41%) of program storage space. Maximum is 32256 bytes.
Global variables use 996 bytes (48%) of dynamic memory, leaving 1052 bytes for local variables. Maximum is 2048 bytes.
An error occurred while uploading the sketch
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

Please help me rectify the error.

I use a SIM900 GSM board. I connect the tx and rx of the GSM board to the Arduino's tx and rx.

# Answer
Those are warnings, not errors. The code should have compiled and be able to flash.
> 2 votes

# Answer
Yes they are just warning, but don't assume all warnings should be ignored. In this case they can be ignored, but you may as well fix them to stop them cluttering the output.

The first one can be fixed by removing the word `typedef`.

The second one needs you to add `.c_str()` on the end of the `string` variable. Sometimes 'string' classes don't store the data in the same way as a char array.
> 1 votes

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


# Question
Title: 74HC595 with 4 digit 7 segment display. Any way to get rid of leading zeros?
I am working on an Arduino based temperature reader using a DS18B20 temperature IC. The display is a 4 digit 7 segment LED common anode display driven by a single 74HC595 shift register. Currently, it is setup to read a variable assigned with a number to test the display portion. It displays to the tenths decimal place I am having troubles trying to get rid of the leading zeros. When the variable 'tempF' is assigned a number such as 12.3, the display yields 012.3 and if the variable is assigned a number such as 1.2, the display will yield 001.2. At the same time, I was wanting to have it place a minus (-) sign when the number is less than zero. So far, the examples I'm finding on the web don't seem to match into the code I'm currently working with or don't work at all. I haven't been able to locate a sketch that seems to work for this type of setup. I have posted below, the code I am working with. The original code was obtained from the link provided in the sketch.

The sketch there does not provide the means of reading negative temps or suppress leading zeros.

---

```
   /*
 * www.pial.net/arduino-controlling-a-4-digit-seven-segment-display/
 */

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

//#define ONE_WIRE_BUS 2

//OneWire oneWire(ONE_WIRE_BUS);
//DallasTemperature sensors(&oneWire);
//DeviceAddress insideThermometer;

const int ledPin =  13;// LED connected to digital pin 13
const int latchPin = 8;//Pin connected to ST_CP of 74HC595
const int clockPin = 9;//Pin connected to SH_CP of 74HC595
const int dataPin = 10;//Pin connected to DS of 74HC595

const int digitPins[4] = {
  3,4,5,6}; //pins to control the 4 common anode pins of the display

const byte digit[10] = //seven segment digit bits
{
  B00111111, //0
  B00000110, //1
  B01011011, //2
  B01001111, //3
  B01100110, //4
  B01101101, //5
  B01111101, //6
  B00000111, //7
  B01111111, //8
  B01101111, //9
//  B00000000, //all segments off
//  B01000000 //-
};

int digitBuffer[4] = {
  1};
int digitScan = 0;
int soft_scaler = 0;
float tempC, tempF;
int tmp;

void setup()   {
  TCCR2A = 0;
  TCCR2B = (1<<CS21);
  TIMSK2 = (1<<TOIE2);
  TCNT2 = 0;
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
  }
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

//  sensors.begin();
//  sensors.getAddress(insideThermometer, 0);
}

ISR(TIMER2_OVF_vect) {
  soft_scaler++;
  if(soft_scaler==15)
  {
    refreshDisplay();
    soft_scaler = 0;
  }
};

void refreshDisplay()
{
  for(byte k=0;k<4;k++)
  {
    digitalWrite(digitPins[k], LOW);
  }
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
  digitalWrite(latchPin, HIGH);
  delayMicroseconds(50);
  digitalWrite(digitPins[digitScan], HIGH);

  digitalWrite(latchPin, LOW);
//  if (digitScan==3)
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000)); //inserting the blank
//    }
//    else
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
//  }

  if(digitScan==1)
  {
    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B10000000)); //inserting the dot
  }
  else
  {
    shiftOut(dataPin, clockPin, MSBFIRST, ~digit[digitBuffer[digitScan]]);
  }
  digitalWrite(latchPin, HIGH);
  digitScan++;
  if(digitScan>3) digitScan=0;
}

void loop()
{
  digitalWrite(ledPin, HIGH);
  boolean sign = false;
  //sensors.requestTemperatures();
  //tempC = sensors.getTempC(insideThermometer);
  //tempF = DallasTemperature::toFahrenheit(tempC);
  //tmp = int(tempF*100);
  tempF = 0.2;
  tmp = int(tempF*10);

//   if (digitScan == 4 ){
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitScan] | B00000000)); //inserting the blank
//    }
//    else
//  {
//    shiftOut(dataPin, clockPin, MSBFIRST, digit[digitBuffer[digitScan]]);
//  }

//if (tmp < 0){
//sign = true;
//tmp = abs(tmp);
//}

//if (digitScan == 3) {
//  if (tmp < 0){
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B01000000)); // outputs minus sign
//  }
//  else {
//    shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
//   }

//  tmp = abs(tmp);
// }
//  else if (digitScan == 3 && digit[digitScan-1] == 0) { // writing on the second display (tens; if there are none, outputs nothing)
//     shiftOut(dataPin, clockPin, MSBFIRST, ~(digit[digitBuffer[digitScan]] | B00000000));
//   }
//   else if (i == 2) { // writing on the third display, where decimal point is needed
//     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
//   }
//   else { // writing on "other" displays (in fact fourth display AND seecond display only if there are some tens)
//     shiftOut(data_pin, clk_pin, MSBFIRST, digit[digitBuffer[i-1]]);
//   }

  digitBuffer[3] = int(tmp)/1000;
  digitBuffer[2] = (int(tmp)%1000)/100;
  digitBuffer[1] = (int(tmp)%100)/10;
  digitBuffer[0] = (int(tmp)%100)%10;
  Serial.print("number assigned to the variable 'tmp' = ");
  Serial.println(tmp);
  Serial.print("number assigned to the variable 'tempF' = ");
  Serial.println(tempF);
  digitalWrite(ledPin, LOW);
  delay(500);
}

```

---

The commented out commands in the sketch were attempts to remove leading zeros and add a minus sign when needed but failed. I have also posted a schematic of the project as well. A 74HC595 was used in this manner to free up pins to be used later in a deep freezer project.

I am by no means an expert programmer but if anyone could help me out or provide some insight on how to solve this problem, it would be most appreciated.

# Answer
> Any way to get rid of leading zeros?

Sure but two conditions have to be true:

1) you have the font information for "blank"; you need to un-comment it in your code for that.

2) you need to get rid of leading zeros, after having calculated the display buffer.

```
  displayBuffer[0]=(displayBuffer[0]==0)?FONT_BUFFER:displayBuffer[0]; //eliminate leading zero for displayBuffer[0]
  displayBuffer[1]=((displayBuffer[1]==0) && (displayBuffer[0]==FONT_BUFFER))?FONT_BUFFER:displayBuffer[1];
  ...

```

edit:

here is an example implementation of the concept from above, on a PIC12F675 driving two HC595. The number to be displayed is "12" on a 4-digit display. Blanking done on the first three digits -\> you can confirm that by looking at the value of the display buffer lRAM\[4\]. 0x11 is my blank designator.

The partial display of '1' is due to multiplexing. Code largely based on what I wrote here: https://dannyelectronics.wordpress.com/2017/03/03/driving-7-segment-leds/, modified to drive over HC595s.

it should work on any mcu with minimum changes.

edit 2: here is your code driving a CC display directly. the number to be displayed is 1.23, with the leading zeros in the most significant 2 digits taken out.
> 1 votes

---
Tags: arduino-nano, ds18b20, 7-segment
---


title: Virtual analog inputs? Possible?

text:
# Question
Title: Virtual analog inputs? Possible?
Just wondering whether it is possible to create 'virtual analog' signals, I am designign a system that uses a tank level sensor (pressure transducer); the component has not yet arrived and I am expecting it in a few weeks.

Is there any way to simulate the signals it would spit out, using some sort of GUI where I can physically control the 'virtual' tank level?

I'm thinking something along the lines of Wonderware's Intouch?

Would appreciate the help! Thanks

# Answer
> 3 votes
You don't specify the sensor you're trying to emulate, so we can't tell you exactly how to do it.

The obvious hardware approach would be a potentiometer.

You could also do it in software by writing a function to get the value, and temporarily replacing its implementation with one which generates random values, or reads values from a serial port, or reads them in order from a hard-coded array, or calculates them according to the time, or whatever you want.

# Answer
> 1 votes
If you just want different values on an analog port then you could use a potentiometer, or a second Arduino the reads a value from its serial port and sets the value of its analog port connected to your first Arduino. Just remember to have a common ground if you do this.

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


# Question
Title: Easy way to upload sketches using MIDI (without RX pin removed)
I noticed when I use sketches with MIDI (using RX/TX), before uploading I have to remove every time the RX wire ... is there an easy way to prevent this?

(I'm thinking about making a push button/toogle for this to prevent it, but maybe there is an easier way).

Update: I use an Arduino Uno

# Answer
> 1 votes
To allow the bootloader on the Arduino MCU to communicate with the USB chip, the TXD/RXD pins are connected:

These connections have 1 kΩ resistors so that the signals of the USB chip do not interfere with your own hardware too much. However, this means that your own hardware can easily override those signals.

In this case, your MIDI hardware actively drives the RXD line to a high level.

You is no way to work around this in software. You could try to replace the optocoupler's pull-up resistor (270 Ω) with a 10 kΩ resistor, which would make the USB controller's signals ten times stronger than the MIDI ones, but this might make the signal edges too slow. To reliably prevent conflicts, you have to add a disable function to the MIDI receiver, or power it down, or disconnect it.

---
Tags: midi, rx-pin
---


# Question
Title: Using Youtube API with ESP8266 = redirection problems
I am using ESP8266 programmed from Arduino to get data from the Google Youtube API. API, of course, works great in a browser using URL:

```
https://www.googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

```

The problem is that "gooogleapis.com" is not the location where from I would receive the answer to my HTTPS request, it comes from a different location. When above URL is entered, it is being redirected and request answer comes from another location.

So what happens on ESP8266 when I try to open that address(of course, with added proper channel ID and google key) is following:

```
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
Content-Length: 1580
Date: Sun, 12 Mar 2017 14:40:18 GMT
Alt-Svc: quic=":443"; ma=2592000; v="36,35,34"
Connection: close

<!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>404.</b> <ins>That’s an error.</ins>
  <p>The requested URL <code>/youtube/v3/channels</code> was not found on this server.  <ins>That���s all we know.</ins>
Done.

```

Which is the Google error page(you seen it!). This is my Arduino code:

```
#include "ESP8266WiFi.h"
#include <WiFiClientSecure.h>

const char* ssid     = "SSID";  // WiFi network name
const char* password = "pass"; // WiFi pass

const char* host = "googleapis.com"; // page I am trying to load
const char* fingerprint = "22 37 4D 58 43 F4 A1 24 12 71 2B 74 7A FC 36 FC 24 A0 F0 9D";

String ch_id = "CHANNEL ID";
String api_key = "API KEY";

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

  WiFi.begin(ssid, password);

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

  Serial.println("Connected to WiFi! Local IP address is: ");
  Serial.println(WiFi.localIP());

  WiFiClientSecure client;
  if (!client.connect(host, 443))
  {
    Serial.println("I am unable to connect to that page.");
    return;
  }

  if (client.verify(fingerprint, host)) {
    Serial.println("certificate OK");
  } else {
    Serial.println("certificate NOT OK");
  }

  String url = "/youtube/v3/channels?part=statistics&id=" + ch_id + "&key=" + api_key;

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  while (client.available()) {
    String linija = client.readStringUntil('\r');
    Serial.print(linija);
  }

  Serial.println("Done.");
}

void loop() {
}

```
* How to find out to which site I am redirected?
* How to read that from ESP8266 and redirect the same data to new site?

# Answer
> 1 votes
In your browser you used `www.googleapis.com`, but in your code you used `googleapis.com`.

```
https://googleapis.com/youtube/v3/channels?part=statistics&id=CHANNEL-ID&key=GOOGLE-API-KEY

```

returns a 404 page.

Add `www.` to your host in code.

---
Tags: esp8266
---


# Question
Title: toInt error when converting character of string to interger
with the following code:

```
int foo = bar[1].toInt;

```

or

```
int foo = bar[1].toInt();

```

I get this error

```
request for member 'toInt' in '*(bar + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'

```

the context for this is bar is the response from a HTTP client over web sockets

# Answer
> 2 votes
The Arduino function `toInt` requires a `String` object. You're passing it a single character, not a `String`.

```
int foo = String(bar[1]).toInt();

```

# Answer
> 1 votes
I'm not quite clean on what you are trying to do. So lets assume the String has "abc123" in and you want the numeric part.

```
const String input = "abc123";
const int foo = input.toInt();  // This will not work!

const String input = "abc123";
const String tmp = input.substring(3); // Take the end of the string
const int foo = input.toInt();  // foo == 123

const String input = "abc123";
const String tmp = input.substring(3,4); // Take the end of the string
const int foo = input.toInt();  // foo == 1 or 12 (can't quite tell from the docs)

```

Is one of those what you want to do?

You can't take a character and then apply a function from the string class to it without making it a String first.

```
int foo = String(bar[1]).toInt();  // This should work

```

---
Tags: programming, esp8266
---