# Question
Title: The exact time for functions or CPU cycles for any function
I'm trying to read input data from the parallel port of a PC and send it to another device. For this purpose the input data is saved, when it's available and is sent if a flag is set.

The whole procedure should be done in less than 10 ms. I need to know the running time. How can I compute the CPU cycles for `ReadParallel` and `WriteParallel` functions (`digitalRead`, `digitalWrite`, `bitRead`,`bitWrite`) in my code or any other instructions?

Here is the code for the Arduino Uno:

```
#define InterruptInputPin 2 // For checking if the input data is available
#define InterruptSensorPin 3 // For checking when to send data

#define IN0 A0
#define IN1 A1
#define IN2 A2
#define IN3 A3

#define OUT0 5
#define OUT1 6
#define OUT2 7
#define OUT3 8

volatile int ParallelInput; // The input data

//*************************************
void ReadParallel() //Reads input and saves it in parallelInput.
{
  if (digitalRead(IN0) == HIGH)
    bitWrite(ParallelInput,0,1);
    else
      bitWrite(ParallelInput,0,0);

  if (digitalRead(IN1) == HIGH)
    bitWrite(ParallelInput,1,1);
    else
      bitWrite(ParallelInput,1,0);

  if (digitalRead(IN2) == HIGH)
    bitWrite(ParallelInput,2,1);
    else
      bitWrite(ParallelInput,2,0);

  if (digitalRead(IN3) == HIGH)
    bitWrite(ParallelInput,3,1);
    else
      bitWrite(ParallelInput,3,0);

}
//***************************************

void WriteParallel() //Writes ParallelInput to output.
{
  detachInterrupt(digitalPinToInterrupt(InterruptInputPin));
  digitalWrite(OUT0,bitRead(ParallelInput,0));
  digitalWrite(OUT1,bitRead(ParallelInput,1));
  digitalWrite(OUT2,bitRead(ParallelInput,2));
  digitalWrite(OUT3,bitRead(ParallelInput,3));
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

}

void setup() {

  pinMode(IN0,INPUT);
  pinMode(IN1,INPUT);
  pinMode(IN2,INPUT);
  pinMode(IN3,INPUT);

  pinMode(OUT0,OUTPUT);
  pinMode(OUT1,OUTPUT);
  pinMode(OUT2,OUTPUT);
  pinMode(OUT3,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

attachInterrupt(digitalPinToInterrupt(InterruptSensorPin),WriteParallel,RISING);

}

void loop() {

}

```

# Answer
## Method summary

(section added on 2018-01-28)

There are several methods available for timing code. I am adding this preliminary section to my answer in order to provide comparative data on several methods. The methods covered in the table below are those proposed as answers to both this question and a duplicate question of this. As this question has been tagged “arduino-uno”, all this data assumes an AVR-based board clocked at 16 MHz.

Method comparison:

```
| method         | resolution    | max. time       | typ. overhead  |
|----------------|---------------|-----------------|----------------|
| `millis()`     | 1 – 2 ms      | 49.7 days       | 0.69 – 1.3 µs  |
| `micros()`     | 4 µs          | 71.6 min        | 2.8 – 2.9 µs   |
| Timer 1        | 0.0625 µs     | 4.096 ms        | 0.25 – 0.5 µs  |
| pin toggling   | scope-limited | ∞               | 0.125 µs       |
| cycle counting | 0.0625 µs     | boredom-limited | 0              |
| looping        | N.A.          | N.A.            | 0.25 µs        |

```

The methods are characterized by the following criteria:

* **Resolution** is the granularity of the measurement, the smaller the better.
* **Maximum measurable time**: any method that does timing arithmetics on the Arduino is prone to overflows if measuring too long times. Note that a timer rolling over to zero during the measurement is not a problem, as long as the period being measured is less than the rollover period.
* **Typical measurement overhead**: the code used to measure the timings takes itself a finite time to execute, thus one ends up measuring the execution time of the “instrumented” code, which is slightly larger than the time taken by the code one is trying to profile. This overhead should in principle be subtracted from the result, but it is often not known exactly, as it depends on how the compiler optimizes *both* the instrumented and the non-instrumented code.

The methods listed in the table are:

* **`millis()`**, which may be the most obvious choice, as it is so well known. Its low resolution, however, makes it ill-suited for timing code execution. It should be noted that the `millis()` counter is incremented every 1024 µs. Most of the time it is incremented by 1 but, every 43 ms (roughly) it is incremented by 2 in order to avoid creeping drift. This is why its resolution is stated as “1 – 2 ms” in the table.
* **`micros()`**, as proposed in ratchet freak's answer, is usually a good choice, the main caveat being the 4 µs resolution, when one could naively expect 1 µs. It also has a significant overhead.
* **Timer 1**, which is discussed in the second part of this answer, is my favorite: it has single cycle resolution and low overhead. However, it is incompatible with other uses of the timer (PWM, Servo library...). It is also limited to measuring small delays.
* **Pin toggling**, as proposed by 4ilo, and by myself in the third part of this answer, is ideal if you have an oscilloscope handy. Any half-decent scope should provide single-cycle resolution. It is also minimally invasive on the code being measured and has minimal overhead.
* **Cycle counting**, as proposed in Majenko's answer, is arguably the “perfect” method: it is cycle-accurate, does not modify the code and has zero overhead. However, for anything beyond a handful instructions, it quickly becomes tedious. And it requires some understanding of the AVR assembly.
* **Looping**, as proposed in Michel Keijzers' answer, is not a measurement technique *per se*. It is meant to be used in conjunction with another technique in order to improve the resolution and dilute the overhead. However, lopping carries it's own overhead, which is typically 4 CPU cycles *per iteration*, assuming a 16-bit loop counter.

---

## Using Timer 1

(original answer of 2017-10-23)

One technique I often use is to make Timer 1 count at the full CPU speed and use it to time the code I want to profile. For example:

```
volatile uint8_t pin = 2;
volatile uint8_t value = HIGH;

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

    // Set Timer 1 to normal mode at F_CPU.
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    cli();
    uint16_t start = TCNT1;
    digitalWrite(pin, value);
    uint16_t finish = TCNT1;
    sei();
    uint16_t overhead = 8;
    uint16_t cycles = finish - start - overhead;
    Serial.print("digitalWrite() took ");
    Serial.print(cycles);
    Serial.println(" CPU cycles.");
}

void loop(){}

```

Note the `volatile` variables used to prevent the compiler from optimizing them as constants.

Note also that when you profile some code you are inevitably slowing it down, because of the time taken by the profiling operations themselves. This is what the `overhead` variable above accounts for. In order to know the exact overhead, I start with a guess, compile and disassemble, and then count the number of clock cycles spent in profiling that will be counted by the timer. Then I adjust the `overhead` value, compile and disassemble again, and make sure the overhead has not changed. This is also when you have to ask yourself what exactly you want to count. Here I am counting the time needed to execute `call digitalWrite`, but not the time needed to get the arguments in the proper registers, as I am artificially slowing this down by making them `volatile`.

This method is good for anything that takes more than roughly a dozen, and less that 65,536 clock cycles. Less than that, clock counting would be simpler, since you still have to clock-count the overhead. More than that, the count would overflow, and you could instead just use `micros()`, and live with its inherent inaccuracy.

---

## Toggling a pin

(section added on 2017-10-23)

If you have a scope, there is another method that is minimally invasive on your code: toggle a pin just before and just after the thing you want to time. E.g., assuming you have previously `pinMode(13, OUTPUT)`:

```
// Set pin 13 HIGH.
PORTB |= _BV(PB5);

// The thing we want to time.
...

// Set pin 13 LOW.
PORTB &= ~_BV(PB5);

```

This will create a pulse that you can measure on the scope. Note that using direct port access, like here, the overhead is only two CPU cycles, or 125 ns. Also, direct port access won't use any CPU register, so chances are the compiler will not generate less efficient code than when not including the timing part.
> 9 votes

# Answer
There's two methods:

1. Profiling.
2. Clock counting.

The first method involves recording timestamps at different points in your program and calculating the time difference between them. That's the simplest, but not always the most accurate.

The second method is far harder and involves disassembling the program after you have compiled it (or obtaining the assembly language from part way through the compilation sequence) and examining all the assembly instructions, looking them up in the instruction list, and totalling how many clock cycles are used for each instruction. That gets very complex, especially when you have loops. However it will tell you precisely how many clock cycles, and thus how long, a block of code will take to execute (not including interrupts, which always throw a big spanned in the works).
> 2 votes

# Answer
To efficiently measure the time a block of code takes, run it for like 1,000 or 1,000,000 times and divide the time by the amount of iterations.

In some cases initialization/variables can be cached but in principle the times are quite accurate. You can easily check this by doing the test for e.g. 1,000 and 2,000 times and see that the time difference also is a factor 2.

For the time counter, use an unsigned long type to accommodate more than 65,535 (ms/us whatever the unit is used).
> 1 votes

---
Tags: arduino-uno, time
---


# Question
Title: Send HTTP request from Arduino Ethernet to server on PC
I am simply trying to send a simple HTTP request from an Arduino Uno with w5500 Ethernet Shield to a local server running on my PC.

The two are connected via a crossover ethernet cable and I am able to host a server on the Arduino that is accessible from my PC browser. Now I am trying to use the PC as a server and the Arduino as the client.

Using the simple WebClient example, I can send a successful GET request to google.com from the Arduino.

Here is what I am trying that is failing:

1 - Start a local server via running http-server in my command prompt. That successfully starts a server at 192.168.56.1:8080 that I can access via my browser

2 - Change the Web Client example to use

```
IPAddress server(192,168,56,1);

```

and change the port to

```
if (client.connect(server, 8080))

```

3 - Run this Arduino sketch. The connection fails and I don't know why. I have allowed port 8080 full input access through the Windows firewall.

Any ideas?

# Answer
> 1 votes
The answer was simple. Instead of trying to connect to the IP address of the local server (192.168.56.1) I had to use the IP address of the ethernet connection between the Arduino and the PC (found using the ipconfig command on the command prompt).

---
Tags: ethernet, ethernet-shield
---


# Question
Title: Using Multiple 4 Digit displays with the same pins
I currently have a ton of 4 Digit 7 Segmented displays(TOFD-5465GGH-B).

The display is driven by a PT6961 LED Driver. Using a Library that I found here I was able to use the display with no issues. The pin out on the display is as such:

```
1) 5V
2) CS
3) CLK
4) DIN
5) DOUT
6) Common

```

Since the display has a DOUT does this mean I can run multiple display is series off of the same pins? If so, can someone point me in the right direction to do so. I am currently using a Particle Photon and I am limited as to the number of PWM pins.

# Answer
That is an SPI interface. Using multiples should be easy. Each one has a CS pin. When that pin is pulled low it selects that chip as the one you are talking to. Several displays could all share the CLK, DIN, and DOUT pins on the Arduino and each would have it's own pin on the Arduino for CS. To update any given display, you pull its CS pin low and then transmit your data. If you pull the CS pins on two displays low at the same time you'll send the data to both. Whichever has the CS pin pulled low on it is the one that listens.

Google SPI and do a little investigation on SPI with Arduino. That will help you learn a little about how SPI works and you will certainly get your question fully answered about how to drive multiple chips while sharing pins. Driving multiple things with the same pins is the whole point of SPI.

The connection would look like this for an UNO -

Pin 13 ---- CLK pin on all chips

Pin 12 ---- DOUT on all chips

Pin 11 ---- DIN on all chips

Choose a different pin on Arduino for each chip and connect to the CS pin.

To use SPI, pin 10 MUST be configured as an output. It cannot be an input. So it would be a good idea to use 10 for one of the CS pins just to make sure it is going to stay an output.

EDIT:

I just looked at the page you linked to and it looks like the library you are using isn't using the SPI hardware but is bit-banging SPI from software using other pins. The concept is still the same, all share CK and DIN and the CS pin picks the one you're talking to.

The code would be a lot faster and much more compact if you changed this library to use the SPI hardware instead of software. It just limits which pins you have to use to the ones I listed above.

EDIT AGAIN:

I feel generous and it was really really really easy to do so I switched his code to run on the SPI hardware. It compiles but hasn't been tested. It should work though. Hooking DOUT to pin 12 is optional, but you still can't use pin 12 for anything else so you might as well.

PT6961\_SPI.h

```
/*
  PT6961.h - Library for communicating with PT6961 LED driver.
  Created by Garrett Blanton January, 16, 2013.
  Released into the public domain.
*/

#ifndef PT6961_SPI_H_
#define PT6961_SPI_H_

#include "Arduino.h"
#include <SPI.h>

class PT6961
{
  public:

    PT6961(uint8_t CS);
    void initDisplay();
    void initRAM();
    void sendCmd(char cmd);
    void sendDigit(char digit, char val);
    void sendNum(int num, char colon);
    void sendDigits(char digit1, char digit2, char digit3, char digit4, char colon);

    const static char _DISPLAY_6X12 = 0x02;
    const static char _DISPLAY_7X11 = 0x03;
    const static char _AUTO_INCREMENT = 0x40;
    const static char _FIXED_ADDRESS = 0x44;
    const static char _DISPLAY_OFF = 0x80;
    const static char _DISPLAY_1_16 = 0x88;
    const static char _DISPLAY_2_16 = 0x89;
    const static char _DISPLAY_4_16 = 0x8A;
    const static char _DISPLAY_10_16 = 0x8B;
    const static char _DISPLAY_11_16 = 0x8C;
    const static char _DISPLAY_12_16 = 0x8D;
    const static char _DISPLAY_13_16 = 0x8E;
    const static char _DISPLAY_14_16 = 0x8F;

  private:

    uint8_t _CS;

};

#endif

```

PT6961\_SPI.cpp

```
/*
 PT6961.cpp - Library for communicating with PT6961 LED driver.
 Created by Garrett Blanton January, 16, 2013.
 Released into the public domain.
 */

//0 - A
//1 - B
//2 - C
//3 - D
//4 - E
//5 - F
//6 - G
//7 - Colon
#include "Arduino.h"
#include "PT6961_SPI.h"

PT6961::PT6961(uint8_t CS) {

    pinMode(CS, OUTPUT);
    _CS = CS;

    SPI.begin();
    SPI.setBitOrder(LSBFIRST);

}

void PT6961::initDisplay() {
    sendCmd(_DISPLAY_6X12);
    sendCmd(_AUTO_INCREMENT);
    initRAM();
    sendCmd(_DISPLAY_14_16);
}

// Initializes RAM to all zeros
void PT6961::initRAM() {
    //first clear 8 bytes of the display RAM
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);
    for (int i = 0; i < 8; i++) {
//      shiftOut(_DIN, _CLK, LSBFIRST, 0x00);
        SPI.transfer(0x00);
    }
    digitalWrite(_CS, HIGH);
}

// Use to send command based on enumeration
void PT6961::sendCmd(char cmd) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, cmd);
    SPI.transfer(cmd);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendDigit(char digit, char val) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, digit);
//  shiftOut(_DIN, _CLK, LSBFIRST, val);
    SPI.transfer(digit);
    SPI.transfer(val);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendNum(int num, char colon) {
    int digit1 = num / 1000;
    int digit2 = (num % 1000) / 100;
    int digit3 = (num % 100) / 10;
    int digit4 = (num % 10);

    sendDigits(digit1, digit2, digit3, digit4, colon);
}

void PT6961::sendDigits(char digit1, char digit2, char digit3, char digit4,
        char colon) {

    const char DISP[17] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
            0x7f, 0x6f, 0x77, 0x7c, 0x58, 0x5e, 0x79, 0x71, 0x61 };

    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1] | 0x80);
        SPI.transfer(DISP[digit1] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1]);
        SPI.transfer(DISP[digit1]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC2);
    SPI.transfer(0xC2);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2] | 0x80);
        SPI.transfer(DISP[digit2] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2]);
        SPI.transfer(DISP[digit2]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC4);
    SPI.transfer(0xC4);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit3]);
    SPI.transfer(DISP[digit3]);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC6);
    SPI.transfer(0xC6);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit4]);
    SPI.transfer(DISP[digit4]);
    digitalWrite(_CS, HIGH);
}

```

Example.ino

```
#include "Arduino.h"
#include <SPI.h>
#include "PT6961_SPI.h"

PT6961 LED(10);   /// This is the pin number for CS pin on each chip
// PT6961 LED2(9);  // The next might look like this if it were connected to pin 9
void setup()
{
     LED.initDisplay();
     Serial.begin(9600);
}

void loop()
{
     //count through 0-9,a-f
     for(int i=0; i<16; i++)
     {
          LED.sendDigits(0,0,0,i,0);
          Serial.println(i);
          delay(500);
     }
}

```
> 0 votes

---
Tags: led, display, 7-segment
---


# Question
Title: Error using nRF24L01+ with ATmega328P-PU. Works fine on Uno
I am trying to use a nRF24L01+PA with an ATmega328P minimal breadboard system. I first connected the module to my Uno and verified it with the "scanner" example sketch from the rf24 library, which showed:

```
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x00
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

```

It also shows the readings from each channel after; I just omitted that part.

Removing the chip and reconnecting it to my breadboard ATmega, which has been bootloaded and tested with the blink sketch, I get the following:

```
STATUS       = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1     = 0x0000000000 0x0000000000
RX_ADDR_P2-5     = 0x00 0x00 0x42 0x42
TX_ADDR      = 0x1042082184
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x00
EN_RXADDR    = 0x00
RF_CH        = 0x00
RF_SETUP     = 0x00
CONFIG       = 0x00
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = Disabled
PA Power     = PA_MIN

```

I double-checked all my wires against an ATmega328P pin map and everything checks out.

Furthermore, running the "gettingstarted" sketch on my Uno returns the correct result in the serial monitor where the chip starts in receiving mode and waits for instructions or to receive packets. And because I don't have the other chip set up yet, nothing shows up. However, when I run the exact same program on my breadboard ATmega, I get the following right after it finishes uploading.

```
RF24/examples/GettingStarted
*** PRESS 'T' to begin transmitting to the other node
Sent response 4194829060
Sent response 4194829060
Sent response 4194829060
Sent response 4294967295
Sent response 4294967295
Sent response 4294967295
Sent response 0
Sent response 4294967295
... yada yada yada

```

The fact that it is picking up any signals doesn't make sense as I am not transmitting from anything... yet.

The only MAJOR difference between my breadboard setup and the uno is the uno is running off USB 5V and the antenna is getting power from the 3.3V pin. On my breadboard, I have my usb2serial jumpered to 3.3V right off the bat and it is running the ATmega328P with a 16MHz crystal basically at 3.3V (waiting on my 3.3V regulators to arrive this Friday so I can run the chip at 5 and drop down to 3.3 just for the chip, as it is a potential solution I have in mind but in the meantime I am asking for other possibilities). Yes I know it is low but so far other sketches like the blink work, and I am running the chip in receive mode anyways.

I am lost and would appreciate some guidance.

Thank you.

# Answer
The ATmega328P can't run at 16MHz at a supply voltage of only 3.3V (check the datasheet). Either raise the voltage or lower the frequency.

Also note that 16mHz would be 16 milliherz (16E-3), so you probably mean 16MHz, i.e. 16 megahertz (16E6).

Remember that the nRF24L01+ is a 3.3V device, so don't connect it to the ATmega's Vcc when changing the supply voltage to 5V.
The IO pins are 5V tolerant, so that's not an issue.
> 1 votes

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


# Question
Title: Error compiling code for Arduino/Genuino Uno
> Arduino: 1.8.6 Hourly Build 2017/10/20 02:33 (Windows 10), Board: "Arduino/Genuino Uno"
>
> c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied
>
> exit status 1 Error compiling for board Arduino/Genuino Uno.
>
> This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences.

Please help me fix this problem. This is my code:

```
int redled = 6;
int yellowled = 9;
int greenled = 12;

void setup() {
  pinMode (6, OUTPUT);
  pinMode (9, OUTPUT);
  pinMode (12, OUTPUT);
}

void loop() {
  digitalWrite (redled, 1);
  delay(9000);
  digitalWrite (redled, 0); //stopped
  digitalWrite (yellowled, 1);
  delay (3000); // yellowled lights for 3 sec.
  digitalWrite (yellowled, 0);
  digitalWrite (greenled, 1);
  delay (9000);
  digitalWrite (greenled, 0);// greenled starts flashing
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
}

```

# Answer
The problem is just what the error message says it is.

> c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

When you are compiling your code the compilation process is trying to rename a file called core.a (.a means a library). I'm guessing it is doing this because you have changed the board type and it needs to compile the library for that type of board.

You don't have permission to change this file. This could be because:

1. You don't have Windows security permission.
2. The file is in use already.
3. It's because you have installed it on your desktop.

The easiest to check is 2, reboot you machine and start only one instance of the IDE and try again. If it works, something (don't ask what) was accessing the file.

If it doesn't work you need to change the security permissions of the parent folder and all sub folders and files. You will need to Google how to do that, and you will need to search for core/core.a.
> 2 votes

---
Tags: arduino-uno, compilation-errors, avr-gcc
---


# Question
Title: Using SPI and 2 shift registers WITHOUT libraries
Arduino Mega 2560 board and SN74HC595 shift register(s). I'm working on a school assignment and having issues getting the shift register(s) working without using Arduino libraries.

I know with the libraries you can use functions such as `digitalWrite(....);` and `shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);`.

For my project, I've set up my individual pins as inputs and outputs, but I am having trouble converting the library code into basic code.

IE:

```
digitalWrite(latchPin, LOW);

```

can be rewritten as

```
DDRB &= ~(1 << DDB1);

```

where `latchPin` is the `SCK` pin.

At this stage in the project, we're just trying to get 8 LEDs lit up using 1 shift register, then 16 using 2 shift registers. Any help in understanding what I need to do or direction in which to look would be appreciated.

Thank you,

Nic

Edit:

This is what I have converted from the void setup from https://www.arduino.cc/en/Tutorial/ShftOut12 :

```
void setup() {
  //Clear the shift registers prev data, Need a low input to reset registers
  //PORTL0 to first SReg SRCLR, PORTL2 to second SReg SRCLR
  //* See data sheet for sn74hc595 shift registers
  DDRL &= ~((1 << PORTL0) | (1 << PORTL2)); //Pg 100 - 21.2.3
  //Use port L0/L2 for SRCLR pin on SReg
  PORTL |= (1 << PORTL0) | (1 << PORTL2); //Pg 100 - 21.2.3

  //Set OE (Enable) to 0 until after last bit is sent
  DDRL &= ~(1 << PORTL4); //Pg 100 - 21.2.3
  //TODO SPI DELAY HERE USING SPDR pg 199

  //Enable SCK as output to drive RCLK and SRCLK on SR
  DDRB &= ~(1 << DDB1); //Pg 96 - 13.4.6
  PORTB |= (1 << PORTB1); //Pg 96 - 13.4.5

  //Enable MOSI as output to drive SER Input on SR
  DDRB &= ~(1 << DDB0); //Pg 96 - 13.4.6
  PORTB |= (1 << PORTB0); //Pg 96 - 13.4.5

  Serial.begin(9600);
  Serial.println("reset");
}

```

# Answer
> 3 votes
The main problem you seem to have is how to implement `shiftOut`. Well, that's actually quite simple once you understand how `shiftOut` actually works.

You already know how to set a pin HIGH or LOW - all you lack from that is the concept of *time*.

All `shiftOut` does is set the clock and data pins HIGH and LOW at the right *time*.

It's simply a case of:

1. Set the DATA pin to HIGH or LOW depending on the bit value to send
2. Set the CLOCK pin HIGH
3. Set the CLOCK pin LOW
4. Go back to 1 for 8 iterations total.

Getting the bit value from a byte can be done with boolean operators `&` and `<<`

The basic `shiftOut` code looks like this:

```
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

```

Since your bit order is fixed you can reduce that down to this:

```
void myShiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(dataPin, !!(val & (1 << (7 - i))));
        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

```

And then you can replace your `digitalWrite` calls with direct register manipulation.

```
void myShiftOut(uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (val & (1 << (7 - i))) {
            PORTB |= (1 << PORTB0);  // Data 1
        } else {
            PORTB &= ~(1 << PORTB0); // Data 0
        }
        PORTB |= (1 << PORTB1);      // Clock HIGH
        PORTB &= ~(1 << PORTB1);     // Clock LOW
    }
}

```

Note that this code will now run considerably faster than the bloaty `digitalWrite` based version - so you may find it's now too fast. You may need to include some short delays around the clock HIGH and clock LOW lines. Depending on how long they need to be you could write a little delay loop to introduce a short delay:

```
void delayLoop(uint32_t iterations) {
    while ((--iterations) > 0) {
        asm volatile("nop");
    }
}

```

That will delay for `iterations` clock cycles plus the time taken to do the loop and call the function. For very short delays it may be better to just insert a few `nop` instructions:

```
PORTB |= (1 << PORTB1);      // Clock HIGH
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");
PORTB &= ~(1 << PORTB1);     // Clock LOW
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");

```

# Answer
> 3 votes
My strategy: Write the sketch using the standard Arduino library. The goal is have the LED lit up, as you need.

Then, change all standard function calls in your sketch (like `digitalWrite`) with your own (called it `digitalWrite2`).

Now implement `digitalWrite2` using register manipulation.

Pros:

* Divide and conquer. You know have two independent smaller problems (LED and registers).
* When is time to implement digitalWrite2 you can learn from your classmate how to do that. I bet that they will start with the hard part (register manipulation).
* It makes for a easier debuging. You can compare your own implementation against the standard implementation just by deleting/adding a single "2" in the call.

Of course, taking a look at the Arduino source code will made things trivial :-) Is that cheating? No, we learn from others, we learn reading other people's code.

**Edit: Step by Step Example**

Let use Blink to show how to do it:

**Original**

```
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

For the new version I will replace `pinMode` and `digitalWrite` for the my own implementation them. How?

Go to the directory where you put your Arduino binaries, which include the source code. There is a subdirectory with the sources (mine is ~/bin/arduino-1.8.3/hardware/arduino/avr/cores/arduino).

There is a file (wiring\_digital.c) where I found the source code for `pinMode` and `digitalWrite`. Without any shame, I copy-paste and rename.

Note: the original includes a call to `turnOffPWM`, which I simply comment out, because we will not use it here and I want to cut it short.

That's all.

**New version**

```
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode2(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite2(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite2(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

void pinMode2(uint8_t pin, uint8_t mode)
{
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg, *out;

  if (port == NOT_A_PIN) return;

  // JWS: can I let the optimizer do this?
  reg = portModeRegister(port);
  out = portOutputRegister(port);

  if (mode == INPUT) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out &= ~bit;
    SREG = oldSREG;
  } else if (mode == INPUT_PULLUP) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out |= bit;
    SREG = oldSREG;
  } else {
    uint8_t oldSREG = SREG;
                cli();
    *reg |= bit;
    SREG = oldSREG;
  }
}

void digitalWrite2(uint8_t pin, uint8_t val)
{
  uint8_t timer = digitalPinToTimer(pin);
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *out;

  if (port == NOT_A_PIN) return;

  // If the pin that support PWM output, we need to turn it off
  // before doing a digital write.
  // if (timer != NOT_ON_TIMER) turnOffPWM(timer); By Look Alterno

  out = portOutputRegister(port);

  uint8_t oldSREG = SREG;
  cli();

  if (val == LOW) {
    *out &= ~bit;
  } else {
    *out |= bit;
  }

  SREG = oldSREG;
}

```

---
Tags: arduino-mega, spi, shift-register
---


title: FIS1100 (IMU)/ I2C/ Arduino

text:
# Question
Title: FIS1100 (IMU)/ I2C/ Arduino
I am a student and currently doing a semester project. The first goal is to get accelerometer and gyroscope data from FIS1100 using the Arduino (Uno). I've got the FIS1100 Evaluation Kit user guide from my supervisor. I've simply separated the sensor PCB from the MCU and connected this sensor to an Arduino Uno as shown on this photo:

The connections are as following:

* SCL (on the header of FIS) - A5 (Arduino)
* SDA (on the header of FIS) - A4 (Arduino)
* GND (on the header of FIS) - GND (Arduino)
* 3V3-to VIOREF (on the header of FIS) - 3V3 (Arduino)

I wrote this simple code, which I uploaded to the Arduino board. Unfortunately as a result, I got zeros as output.

```
#include <Wire.h>
const int I2C_address = 0b1101010;
long a_X, a_Y, a_Z;
float g_X, g_Y, g_Z;

long gyro_X, gyro_Y, gyro_Z;
float rot_X, rot_Y, rot_Z;

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

}

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(800);

}

void setupFIS(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x02);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x08);
  Wire.write(0b10000011);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x04);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x03);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x05);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x06);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x07);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
}

void recordAccelRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x19);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  a_X = Wire.read()<<8|Wire.read();
  a_Y = Wire.read()<<8|Wire.read();
  a_Z = Wire.read()<<8|Wire.read();
  processAccelData();
}

void processAccelData(){
  g_X = a_X/16384.0;
  g_Y = a_Y/16384.0;
  g_Z= a_Z/16384.0;
}

void recordGyroRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x1F);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  gyro_X = Wire.read()<<8|Wire.read();
  gyro_Y = Wire.read()<<8|Wire.read();
  gyro_Z = Wire.read()<<8|Wire.read();
  processGyroData();
}

void processGyroData(){
  rot_X = gyro_X/1024.0;
  rot_Y = gyro_Y/1024.0;
  rot_Z= gyro_Z/1024.0;
}

void printData(){
  Serial.print("Gyro(deg)");
  Serial.print(" X=");
  Serial.print(rot_X);
  Serial.print(" Y=");
  Serial.print(rot_Y);
  Serial.print(" Z=");
  Serial.print(rot_Z);

  Serial.print("   Accel(g)");
  Serial.print(" X=");
  Serial.print(g_X);
  Serial.print(" Y=");
  Serial.print(g_Y);
  Serial.print(" Z=");
  Serial.println(g_Z);
}

```

So, I really need help to get some relevant data.

And also I have doubts concerning the I2C-address of the FIS1100. In the datasheet of the FIS1100 on page 50 it is said:

> the address is 0b1101010 in case when pin SA0 is left unconnected, internally there is a weak pull-down of 200k; the address is 0b1101011 in case when pin SA0 is pulled-up externally.

Now lets go again to user guide and on page 25 (schematic of pull-up/down resistors) we see that SA0 is externally pulled-down.

Question: which I2C-address should I use?

# Answer
> 1 votes
I think you'll find you need to add some pull up resistors to both connections on the I2C (SDA and SCL).

Also I'm not sure what you should be pulling them up to 3.3v or 5v. You should check if you need a level shifter or if the device you are connecting is 5v tolerant.

According to you question you should be using the address 0x6A. 0x6B is when you have an external pull up resistor, which I don't think you do have. So your code is correct.

---
Tags: i2c, accelerometer
---


# Question
Title: Displaying 3 hex bytes sent to serial port on an OLED display
I am new to Arduino and I'm trying my first Pro Mini. I was able to find OLED display code from github that runs perfectly. My problem is trying to show 3 hex bytes sent by a remote control decoder module on the display.

The code will run under serial monitor with `serial.print("I Received");` and `serial.println(incomingByte, HEX);`.

I want to receive this code on the serial port and display it on the OLED screen.

Any help is welcome.

I attached my code any help will be appreciated.

```
int incomingByte = 0
void setup() (
  Serial.begin(9600)
)

void loop() (
  if (serial.available() > 0) (
    incomingByte = Serial.read();
    u8g.drawStr(10, 37" I Received"); //glcd text position
    u8g.setPrintPos(10,42);
    u8g.print(incomingByte, HEX);
  )
)

```

# Answer
I'm going to assume you know the difference and significance between {} and () and the fact that the code you pasted in had a few syntax issues.

Below is a copy which should compile (I haven't tried it) I added a check to see if `Serial.read()` returned data, but otherwise its what you had.

```
int incomingByte = 0;
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    if (Serial.available() > 0)
    {
        incomingByte = Serial.read();
        if (incommingByte != -1)
        {
            u8g.drawStr(10, 37, " I Received"); //glcd text position
            u8g.setPrintPos(10, 42);
            u8g.print(incomingByte, HEX);
        }
    }
}

```

You've not actually said if the code works or not. Please can you try this version and report the results.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino emits signal A (infrared) but another Arduino receives everything but A (IR-LED problem)
Situation: I was trying to make a simple Arduino program that mimics my TV-Remote ON-OFF button.

Diagnosis: It just won't work. So just to check I grabbed another Arduino (2) and added my IR-Sensor to that one and let it look for the signals sent by Arduino (1).

Conclusion: Even though I ran exactly the same program in a loop sending IR signals, Arduino (2) noticed each time another IR signal. The received signals didn't even look like the IR signal I sent.

The program I use to mimic my remote: Link to the Github. It is an example of a Lib

It could be the LED. Just a LED I picked up without being specific. Link to the Documentation of the LED

# Answer
Sorry not enough rep to comment. Had to answer instead.

So if your schematic is correct then you just fried your LED. You need a series resistor between vcc and the LED.

If it's not accurate and you have the resistor in place, I'd check the LED anyway, it could be a dud. Apply voltage with a resistor and look at it with your cell/mobile phone digital camera, you should see it through the camera glow dimly.

If all is good then it might be the wavelength of the LED, which is 850nm. Most IR LED's I've used are 950nm, actually they all were.

Now I don't know what the specs of your receiver are but it might be out of its sensing (is that a word?) range, also it only has a 20° viewing angle, so check the alignment of transmitter and receiver.

I'm also confused by your statement that your getting signals that don't look like IR. This makes me wonder if your sensor is hooked up properly. It could be background IR or from another source. Look around the room or test elsewhere.
> 1 votes

---
Tags: arduino-uno, ir, infrared
---


# Question
Title: AT command to put the A6 GSM/GPRS into sleep / power down
The general AT command for sleep mode (for the SIMCOM GSM modules) is AT+CSCLK=1 (or AT+CSCLK=2). I have given both a shot but they don't work with the A6 module. Does anyone know of any other command that does the same? The manufacturers claim that it can function at very low current levels when in sleep. But sadly they don't mention the sleep AT command.

# Answer
A6 module uses a hardware pin (INT/GPIO\_1) or (EN) enable on some modules. There is no AT command as in the SIM900.
> 1 votes

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


# Question
Title: Programming Arduino Pro mini 328 with Arduino Uno SMD
I apologize in advance, because there is a lot of tutorials out there about programming arduinos with another arduino, however I can't find really simple one I could understand.

I have Arduino Uno SMD version and Arduino Pro mini 328. I want to upload sketch to Arduino Pro mini using Arduino Uno in ISP mode (I guess).

I want to know EXACTLY which pins need to be connected and if all I need is Arduino IDE to upload my sketch to Pro mini ?

Thank you for your help.

# Answer
check this tutorial:

> http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/

Works fine for me (I have a redboard, also with SMD microcontroller). In short this is the pinMap:

```
UNO BOARD (SMD)    Pro Mini 5V
       GND             GND
       5V              VCC
       RX              RX1
       TX              TX1
       Reset           GRN

```
> 1 votes

# Answer
Please check this tutorial if you want to upload sketches to Pro mini with Arduino UNO with SDM chip http://www.instructables.com/id/Uploading-sketches-to-Pro-Mini-using-Arduino-UNO-b
> 1 votes

# Answer
Following the tutorial on http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/ I was able to upload the blink sketch to the Pro Mini 5V version with an Arduino Nano. After I tried uploading the sketch that I really wanted to use but got many errors in the IDE I tried a couple more with no luck. I had stumble on another article earlier about using the Arduino Nano to program the Pro Mini http://www.electronicsmayhem.com/?p=31. I had tried that method but with no luck but using the first tutorial & only changing one thing from it with info from the article i mentioned I was able to upload the sketch without any errors. The only thing I changed was I didn't connect the TX from the Nano to the TXI of the Mini.

```
   Arduino Nano     Pro Mini 5V
       GND-------------GND
       5V--------------VCC
       RX--------------RX1
       Reset-----------GRN(DTR)

```
> 0 votes

---
Tags: arduino-pro-mini, isp, arduino-uno-smd
---


# Question
Title: Unable to receive and print SMS on the serial monitor with Arduino Uno and SIM900A
I'm trying to receive an SMS and show it on the serial monitor.

My code is as following:

```
void setup()
{

  Serial.begin(2400);
  Serial.write("AT+CMGF=1\r");           //set GSM to text mode
  delay(1500);

  Serial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
  delay(1000);

  Serial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
  while(1)
  {
    if(Serial.available())
    {
      Serial.write(Serial.read());
    }
  }
}

void loop()
{
}

```

The circuit diagram is as shown below.

The output that I am getting is as following:

```
AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR
AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR

ERROR
AT+CMGR=1
AT+CMGF=1

```

I am not able to use `AT+CPMS` or `AT+CMGL` commands.

# Answer
> 0 votes
As others have stated, you **cannot** use the hardware serial port for communication with the device **and** communication over the USB cable.

**OPTION 1**
Switch to a different microcontroller, such as the arduino mega with multiple hardware serial ports on board.

**OPTION 2**
Implement the Software Serial library for communication with the sim card device and use the hardware serial for communication with your computer.

*Note: Software Serial implementations are more computationally intensive than the use of hardware serial. Do not expect the same performance from a software serial implementation and do not expect to be able to smoothly run multiple instances of it on a single 8 bit mcu.*

Example Code (Untested):

```
  #include <SoftwareSerial.h>

  void setup()
  {
  Serial.begin(9600);
  SoftwareSerial mySerial(10,11); //RX,TX pins
  mySerial.begin(2400);
  mySerial.write("AT+CMGF=1\r");           //set GSM to text mode
  delay(1500);

  mySerial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
  delay(1000);

  mySerial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
  while(1)
  {
    if(mySerial.available())
    {
      Serial.write(mySerial.read());
    }
  }
}

void loop(){}

```

Disconnect from pin 0 and pin 1 and connect to pins 10 and 11 respectively.

# Answer
> 1 votes
The `Arduino UNO` that you are using only supports one Serial connection (over the `TX` and `RX` pins). Since you are using these pins to talk to the device, you cannot also send data over Serial.

Read this article to see more about `Serial` and how it works on different boards.

# Answer
> 0 votes
The RX/TX pins are on Uno connected to the USB chip. If you connect a device to RX/TX, you should not use Serial Monitor. It sometimes works, but the device receives the data send to Serial Monitor too and can't process them.

Use SoftwareSerial library for connecting the serial device, if you want to have Serial free for printing to Serial Monitor over USB.

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


# Question
Title: Access I2C sensor from Arduino Uno as slave
I connected Raspberry Pi 3 to an Arduino Uno through I2C. The Arduino Uno uses the I2C as slave.

When I connect AM2320 sensor (temperature and humidity) to the Arduino Uno, I am getting the response that the sensor is offline.

I tested the sensor on Raspberry Pi 3 and it is working fine. On the Raspberry Pi the address is 0x5c. On most libraries, the address is 0xb8. I have the same result when I tried these 2 addresses.

Do I have problem because Arduino Uno is working as slave?

# Answer
You can do it. A single device like the Arduino can be both a slave and a master.

It's explained in great detail by Nick Gammon in http://www.gammon.com.au/i2c in the paragraph *Communicating with other devices*
> 1 votes

# Answer
Indeed, I2C slaves cannot communicate with one another.

There are some obscure capabilities for devices to switch role, but that is likely to introduce lots of complications.

You might look at using bit-banged (or "soft") I2C on other digital pins and move the peripheral's I2C lines there instead o the hardware I2C pins connected to the pi. For example, a web search quickly found something that claims to do this at:

https://github.com/felias-fogg/SoftI2CMaster

No idea if that particular one will work for you, but there are others as well.

Or you can re-design your scheme so that the pi reads the sensor, and if necessary writes the values of interest to the Arduino.
> 0 votes

# Answer
I had may be a bad connection but I can read the sensor AM2320 on Arduino- Uno and send the value back to Raspberry Pi.

Arduino side:

```
#include am2320
#define SLAVE_ADDRESS 0x04
Wire.begin(SLAVE_ADDRESS);
AM2320 th;
Wire.write( (int)(th.t * 10)); // th.t is for temperature which I send
integer

```

Raspberry side:

```
import smbus
bus = smbus.SMBus(1)
address = 0x04
number = bus.read_byte(address)

```

Raspberry Pi and Arduino Uno seems to work good together with and I2C sensor on Arduino side. Thanks for you time to help me and I will go to the link you propose.
> 0 votes

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


title: add 0x to a byte

text:
# Question
Title: add 0x to a byte
I have a **byte** variable CardNumberByte with a value of E8 if i print out as HEX:

```
Serial.println(CardNumberByte, HEX)

```

which returns E8.

What I would like to do is to "append 0x as prefix" so that it is equivalent to

```
Char CardNumberByte=0xE8;

```

how should i concatenate 0x to CardNumberByte?

here is the reason i need to do so.

Thanks

# Answer
I've looked at you question and the question you linked two and I've tried to join the dots to give you an answer, so I might be well off the mark, but...

I think you might have misunderstood what `0x28` means.

0x?? means that the ?? represent a hexadecimal number rather than a decimal number.

So 10 (Ten) in decimal is the same as 0x0A in hex or B00001010 or in binary or even 012 in octal. (See https://www.arduino.cc/en/Reference/IntegerConstants for more details)

So you want to have some code that says:

```
char Address = 0x28;

```

This is assigning the hexadecimal value 28 to the variable `Address`. You could also write:

```
char Address = 40;

```

In this case you are assigning the value decimal 40 (which is hex 28) to the variable. If you want to write strange code that is misleading you could write:

```
char Address = '(';  // ( is ASCII character 0x28 or 40 - Don't do it like this!

```

One other important thing here is that the `char` type in this case is not being used as type that holds a printable character, its being used as a signed 8 bit number.
> 2 votes

# Answer
The answer to the question you asked is:

```
Serial.print("0x");
Serial.println(CardNumberByte, HEX);

```

But what you want to do according to the comment you posted is *parse* `"E8"` to give you `0xE8`.

```
int parseHex(char* input){
    int result = 0;
    while(input && *input){
        if(*input >= '0' && *input <= '9'){
            result <<= 4;
            result+= *input - '0';
        }
        if(*input >= 'a' && *input <= 'f'){
            result <<= 4;
            result+= *input - 'a'+10;
        }
        if(*input >= 'A' && *input <= 'F'){
            result <<= 4;
            result+= *input - 'A'+10;
        }
        input++;
    }
    return result;
}

```
> 0 votes

# Answer
Here you have:

```
  char buffer[20];
  snprintf(buffer, sizeof(buffer), "0x%X", 1234);
  Serial.println(buffer);

```

You have to study the classic C print functions.
> 0 votes

---
Tags: programming
---


# Question
Title: Low cost IR sensor based finger gesture recognition controlled wheelchair
I am doing a project in which three IR sensors are used for getting three fingers's gesture to control the movements (left, right, forward, backward) of two motors.

The threshold value of IR sensor output is 450 mV for getting signal to be passed.

I am not understanding how to design different conditions for different movements of motors

```
int firstanalogPin = 1;     // Infrared Sensor (Right lead) connected to analog pin 1

int val1 = 0;           // variable to store the value read

int enablePin = 1;
int LeftMotorForward = 10; // Pin 10 has Left Motor connected on Arduino boards.
int LeftMotorReverse = 9; // Pin 9 has Left Motor connected on Arduino boards.

int RightMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
int RightMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards

void setup()
{
    pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
    pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
    pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
    pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
    Serial.begin(9600);          //  setup serial
}

void loop()
{
    val1 = analogRead(firstanalogPin);    // read the input pin
    Serial.println(val1);                           // debug value

    if (val1 >700) // forward
        digitalWrite(LeftMotorForward, HIGH);
    else
        digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor ON
    if (val1 >700)
        digitalWrite(RightMotorForward, HIGH);// turn the Right Motor ON
    else
        digitalWrite(RightMotorForward, LOW);// turn the Right Motor ON
}

```

# Answer
> 0 votes
What is it that you have a problem with? You have made the motors move forward. So if you want just 3 different exclusive motions Forward, Left, Right.

What you could do is have 1 finger control the direction, 1 finger control left and 1 control right.

```
   OFF       ON
F1 Forwards  Backward
F2 Left Off  Left On
F3 Right Off Right On

```

So to go straight forwards F2 & F3 have to be greater than 700.

To turn left F3 \> 700 && F2 \< 700 (Right motor on will make the chair turn left)

To reverse then you need F1 \> 700.

etc.

Ensure that the conditions are if/else ifs otherwise its going to get messy.

---
Tags: arduino-uno
---


# Question
Title: waking up arduino mini with a external signal
I have an arduino mini with an ultrasonic sensor conected to the pins 2 and 3, and a RGB LED connected to the 4,5, and 6, I want to include a wake up and sleep functionality that wakes up when receive a high signal in another pin as 7.

I have seen that normaly the pins for that are 2 and 3, as in the arduino web: Arduino sleep web

But can it be done with another pin?

# Answer
> 1 votes
As well as the normal external interrupts INT0 and INT1 you can also wake the chip through a variety of other interrupts. One of those is the *pin change* interrupt.

In the datasheet is a table of what is available in the different sleep modes, and what can wake you from that sleep mode. I have compressed the table to remove a lot of the stuff you don't care about at the moment and just show the "wake-up sources":

As you can see both INT and PCINT can wake from all modes (along with TWI \[Wire.h\] slave mode address matching).

The note (3) on the table just says that for INT0 and INT1 it must be a LOW level interrupt, not a RISING or FALLING. No mention is made of the type of interrupt for PCINT.

So yes, since pin 7 has PCINT facilities (all pins on the ATMega328P have PCINT) you can configure that as a wake-up source and wake the MCU using pin 7.

# Answer
> 1 votes
Arduino Mini has only two interrupt capable pins: 2 and 3. You have to move your sensor to other pin.

From the AtMega328p datasheet:

> If a level triggered interrupt is used for wake-up from Power-down, the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt will be generated. The start-up time is defined by the SUT and CKSEL Fuses.

---
Tags: arduino-pro-mini, sleep
---


title: Detection of DS18B20, arduino Mega

text:
# Question
Title: Detection of DS18B20, arduino Mega
I just bought a DS18B20 temperature sensor. I can't detect the device when i run this code :

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

// Data wire is plugged into pin 10 on the Arduino
#define ONE_WIRE_BUS 10

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

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

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

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

 void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");

  Serial.print("Temperature for Device 1 is: ");
  Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire

}

```

Here are my connections:  and output on Serial Terminal is:
"Temperature for Device 1 is: -127.00 Requesting temperatures...DONE"
I also tried to detect the address of my device but with no success.
I am using an arduino Mega 2560, i have read in some forms that maybe it has something to do with Clock speed or something like that.
I appreciate your help.

I mainly followed this tutorial : http://www.hobbytronics.co.uk/ds18b20-arduino

# Answer
> 1 votes
In the Tutorial, which you are following, it says,

> So we will use the 2 wire method. Simply connect both the GND and VDD pins to 0V (yes both)

and it shows:

but I think you are missing this step, because i can't see any connection like that here:

# Answer
> 0 votes
I attached VDD to GND and set it up so the 4K7 resistor was connecting the 5V to the data line - at first it didn't work, then I swapped it around as if the VDD and data lines from the sensor were switched - which it turned out they were.

Might be the case with your one.

---
Tags: arduino-mega, temperature-sensor, 1-wire
---


# Question
Title: Interface Processing with Arduino to operate a servo by MouseX
I want to make a servo change its angle using my mouse. When I move mouse horizontally the servo should change its angle correspondingly. This is the sketch I wrote, unfortunately the servo doesn't move one bit. HELP.

Processing Code:

```
import processing.serial.*;
Serial port;
void setup() {
  size(256, 150);
  println("Available serial ports:");
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());
  port = new Serial(this, Serial.list()[1], 9600);
}

void draw() {
  // draw a gradient from black to white
  for (int i = 0; i < 256; i++) {
    stroke(i);
    line(i, 0, i, height);
  }
  // write the current X-position of the mouse to the serial port as
  // a single byte
  port.write(mouseX);
  println(mouseX);
}

```

Arduino Code:

```
#include <Servo.h>
Servo myservo;
void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
  // initialize the servo:
  myservo.attach(10);
}
void loop() {
  byte pos;
  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    pos = Serial.read();
    // set the angle of the servo:
    myservo.write(map(pos, 0, 255, 0, 180));
  }
}

```

# Answer
When you try and solve a problem you want to focus on just one part at a time. If I have understood what you are doing correctly then you are trying to:

1. Get a computer to talk to an Arduino over serial
2. Get an Arduino to position a servo
3. Get an Arduino to decode information sent by the computer
4. Get the computer to code the information
5. Get the computer to draw graphics.

You can try and ice a cake, feed a baby, talk on you mobile and drive a truck all at the same time, it doesn't mean its a good idea. When you crash what was the cause? You haven't got a clue, you were too busy trying to do all that not analyse what is happening at the same time.

So, what I'm trying to say is break it down. Normally with motors the problem is related to power, people assume that the Arduino can provide enough power for a servo, that's not always the case.

I would:

1. Write a program that sets the servo to 10 hard coded positions.
2. Write a program that sets the servo to the position manually entered on the command line.
3. Write a program that draws the gradient, interprets the user entry and writes the command to be sent to the Arduino to the command line.
4. Write a program that runs on the Arduino and echoes what it receives over the serial line to some "other output mechanism" (Connecting the computer via SoftwareSerial might be a good idea).

And once they are all working as you expect connect them all together and it will all magically work :)

(Sorry if I'm teaching you to suck eggs, if you have already done all this ignore me)
> 2 votes

---
Tags: serial, arduino-ide, servo, processing-lang
---


title: Slice byte-stream into bit pieces

text:
# Question
Title: Slice byte-stream into bit pieces
I receive byte data from a RS-232 device with `Serial.read();`. Now I need to slice this down in bit-pieces:

* value1: 15bits
* value2: 7bits
* value3: 9bits
* value4: 12bits
* and so on

Data from the stream (switch them around for better understanding):

* Byte 1: 00101100 =\> 00110100 (least significant byte first)
* Byte 2: 10011011 =\> 11011001
* Byte 3: 00110011 =\> 11001100
* Byte 4: 11101000 =\> 00010111
* Byte 5: 01001100 =\> 00110010
* Byte 6: 01100111 =\> 11100110

Now the least significant is first.

* value1: `00110100.1101100[1]` =\> 6956
Need to cut of the last bit of the second byte
* value2: `1.110011[00]` =\> 103
Add the last bit of the second byte and cut off the last two bits of the third byte
* value3: `00.0001011[1]` =\> 416
Add the last two bits of the third byte and cut off the last bit of the fourth byte
* value4: `1.00110010.111[00110]` =\> 3737
Add the last bit of the fourth byte and cut off the last 5 bits of the fifth byte

Now the question: How do I realize this from programming side. I'm lost.

# Answer
**Note: This is an answer that OP originally edited into his question.**

---

I gather the data into an array of bytes `data[125]`.

Then I gather the relevant bytes per value and stack them together:

```
long var = (data[4]<<8) + (data[3]);

```

I shift them so the relevant bytes start first

```
var=var>>3;

```

Afterwards I mask them with the RIGHT mask

```
var=var & 0xFF;

```

For the example in my question:

```
long var = (data[1]<<8) + (data[0]); // I need two bytes
var=var>>1; // shift them to the right one bit
var=var & 0x7FFF; // mask it with "0111 1111 1111 1111"

```
> 3 votes

---
Tags: programming, rs232
---


title: ATmega8L power issue

text:
# Question
Title: ATmega8L power issue
I am doing a prototype using ATmega8L-8PU to detect temperature and control a relay and buzzer, but the schematic seems not work, therefore I do a simple test to verify the AVR's pins are working perfectly or not.

I using the example sketch - Blink to control Digital-13 to let LED blink. It is work.

Then I do a second sketch to test all pins (Due to leak of LED, I test first 8 pins.) It failed. Second Sketch is quite simple and strict forward: blink D0-D7 LED one by one.

```
char i, j, pcnt = 1;

char startDigitalPin = 0;
char maxDigitalPin = 7;

void setup()
{
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    // put your setup code here, to run once:
    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        pinMode(i, OUTPUT);
        digitalWrite(i, LOW);
    }
}

void loop()
{
    // put your main code here, to run repeatedly:
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        for(j=i; j<=maxDigitalPin; j++) {
            digitalWrite(j, HIGH);
            delay(100 * pcnt);
            digitalWrite(j, LOW);
            delay(100 * pcnt);
        }

        digitalWrite(i, HIGH);
        delay(200 * pcnt);
    }

    pcnt++;

    if(pcnt > 10) {
        pcnt = 1;
        delay(8000);
    }
}

```

Question:

1. Why I using Blink example sketch, D13 is work fine, the LED light on with normal bright.
2. Why second sketch, the D13 LED super dark, but it light on.

Check it out these 2 videos in youtube. https://www.youtube.com/watch?v=sknNPxqg5zc https://www.youtube.com/watch?v=KWsdP3egsvY

I have burn a bootloader to ATmega8L-8PU (Summary Datasheet) using Arduino IDE 1.6.5 with MiniCore, Config: ATmega8 External 8MHz.

Parts in my bearboard using:

1. ATmega8L-8PU
2. 2 x 22pf
3. 1 x 100nf
4. 1 x 8MHx crystal
5. 9 x LED with 330Ohm resistor

# Answer
> 2 votes
I tested your sketch after adding `pinMode(13, OUTPUT)` in the setup, and it works as you intended.

But, as you don't post your schematic, I was only able to chech on-board LED blinking.

```
void setup()
{
  pinMode(13, OUTPUT);

  for (int i=0; i < 3; i++) {
      digitalWrite(13, HIGH);
      delay(100);
      digitalWrite(13, LOW);
      delay(100);
  }

    // put your setup code here, to run once:
    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        pinMode(i, OUTPUT);
       digitalWrite(i, LOW);
    }
}

```

I also reduce your code using a `for` loop.

---
Tags: arduino-ide
---


# Question
Title: Powering Arduino Pro Mini with different voltage, fuse setting
Arduino Pro Mini commonly comes in two packages, 5V 16MHz and 3.3V 8MHz.

1. The only difference between those two boards are regulator and clock crystal, right?
2. What happens if I supply 2V to VCC pin of 5V 16MHz board?
3. What happens if I supply 2V to RAW pin of 5V 16MHz board?
4. What happens if I supply 5V to VCC pin of 3.3V 8MHz board?
5. What happens if I supply 5V to RAW pin of 3.3V 8MHz board?

I read from some websites stating that Arduino Pro Mini power consumption can be reduced by removing regulator.

6. Does removing regulator cause VCC pin = RAW pin?

Jean created a custom board for Arduino Pro Mini rated at 1MHz 1.8V.

7. Which pin should I supply voltage after changing fuse setting? (Jean changed the fuse setting but I am not sure where to connect the supply voltage of 1.8V)
8. Related to question 7, is there a need to remove regulator to supply 1.8V?
9. Can I supply higher voltage (3V) on board with 1.8V fuse setting?

Reason for question/ Confusion

I want to power Arduino Pro Mini using 3V coin cell. Battery voltage decreases after usage to around 2V. I am thinking of simply inserting 3V coin cell to Arduino with 1.8V setting. But regulator may hinder the operation. That is why I am confused. Sites I visited states the possibility of using lower voltage after changing fuse setting but did not mention where to connect and whether regulator need to be removed.

Furthermore, ATmega328p datasheet states the VCC range is 1.8V to 5.5V. If that is so, why not just plug those voltage to VCC pin of Arduino Pro Mini instead of specifically 5V or 3.3V. Question 1-5 should clear my confusion on this.

# Answer
Read the datasheet once more. A certain voltage is needed for a certain clock frequency. There is a graph somewhere.

Since the Atmega328p is able to run up to 5.5V for VCC, that 5.5V is for every clock frequency.

Using 2V for VCC is not enough to run it at 16MHz. According to the datasheet even 3.3V is not enough. But 3.3V and 16MHz will work (it is outside the specifications though).

The RAW pin is the voltage before the voltage regulator, right ? Depending on the voltage regulator you can apply a large range of voltage. See the pinout.

When you remove the voltage regulator, the RAW pin is open. Sometimes I remove the voltage regulator and use 3 AA batteries and feed the 4.5V into the VCC (or 5V pin) of a 8MHz ATmega328p board.

1. Yes. The bootloader and sketch have to know the clock frequency. A sketch compiled for 8MHz is for a 8MHz Arduino board and a sketch compiled for 16MHz is for a 16MHz Arduino board.
2. 2V is too low. 3.3V should work.
3. 2V is too low. 3.3V depends on the voltage regulator.
4. No problem. The voltage regulator gets a reverse voltage.
5. No problem.
6. No. See the schematic.
7. To VCC.
8. Not a "must", but it is highly preferred to remove the voltage regulator, so no current is leaking towards the voltage regulator which gets a reverse voltage.
9. Yes. The fuses are to lower/disable the BOD, so a higher voltage is no problem.

This is the best tutorial about the power of the Atmega328p : Nick Gammon about Power

**ADDED**

I forgot to mention to remove the led as well.
This is a Pro Mini with a coin cell.

Lowering the clock speed will make it run at lower voltages, but that will not always reduce the used energy. Doing a calculation at a slow speed takes more time than the same calculation at high speed (and going into sleep mode after that).

**ADDED 2**

When a low voltage is supplied (for example 2V to a 5V 16MHz Arduino board), the voltage regulator will not work. How much current/voltage is still passed on depends on the voltage regulator. With the BOD disabled, and the microcontroller runs below its required voltage, anything weird can happen. Parts of the chip will work and parts will not. That is why the BOD was invented in the first place (to reset the chip and avoid weird things to happen). I think it is very unlikely that the microcontroller will get damaged with a (too) low voltage.
> 0 votes

---
Tags: power, atmega328, arduino-pro-mini
---


title: External Flash Memory for ATtiny85

text:
# Question
Title: External Flash Memory for ATtiny85
I'm designing a lightweight circuit, but the ATtiny85 micro-controller I'm using to power it doesn't have nearly enough flash memory to store the code for the devices I'll have hooked up to it (It has 8kb of flash). I was wondering if it'd be possible to have the ATtiny use compiled code from an external flash memory chip of larger capacity elsewhere on the board like its own internal memory. Thanks in advance.

# Answer
No, it's not possible.

AVR chips can only execute code from their internal flash.
> 2 votes

# Answer
Although you cannot run code from external (S)RAM, you can:

* optimize your code (reducing the number of lines of code by):
    + use parameterized functions instead of copying/paste code
    + reduce the type (storage) variables (like constants) which are kept in memory, e.g. instead of 200 integers of 2/4 bytes use 200 bytes
    + instead of storing const calculated array values, calculate them runtime (causing a performance reduction)
    + remove unused libraries
    + strip down used libraries (not needed to remove unused functions)
> 0 votes

# Answer
You could write a small bootloader and load code segments when needed. The internal flash can be written at least 10,000 times so you cannot swap segments too often.

To do this you need to 1) write a bootloader that can load segments from the external flash, 2) partition your sketch into segments, 3) compile and link them to the same address space in program memory, 4) write the segments to the external flash memory.

Extra is handling segment to segment calls as special care is needed by the loader.

An even more elaborate scheme is to allow multiple modules and swap them depending on the execution path (e.g. module to module calls). Segments would be built up of modules, and modules would be reusable between segments. What modules are in memory would depend on some "statistics". This is basically what the instruction cache does in modern processors.

Typical segments could be application level sub-functions such as printing, uploading measurements, etc. Typically functions that are not used very frequently, and where the "background" application is stopped, e.g. data collect.
> 0 votes

---
Tags: attiny, flash
---


# Question
Title: Can I use the Arduino Uno's 3.3v pin while powered by a 9 volt battery?
I have an Arduino Uno. It has a 3.3v pin that I would like to use to power another module that requires 3.3v, and nothing more. If I power my Arduino Uno with a 9 volt battery, will this pin output 3.3v, or will it give more than that?

# Answer
> 1 votes
The 3.3v is regulated and will always output 3.3v if the device is powered on.

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


# Question
Title: Writing a new function: configMotor(speed, direction)
How can I create a function that can control a DC motor's speed and direction?

```
configMotor(int speed, direction){
   pwmVal = speed;

   //need help with code for picking direction
}

//move FORWARD
void moveForward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, HIGH);
  digitalWrite(inb, LOW);
}

//move BACKWARD
void moveBackward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, LOW);
  digitalWrite(inb, HIGH);
}

```

I don't know what to write in the code for `configMotor` function so that it can choose going forward or backward.

# Answer
> 0 votes
All you need to do is pass a parameter to config that says forward or backwards (was direction). This parameter then sets the values of that the pins INA/B will be set to, because they are opposite.

Does that make sense? If not add a comment with you question and I'll try and clarify.

```
int inaDirection = LOW;
int inbDirection = LOW;

void configMotor( int speed, bool forwards = true)
{
   pwmVal = speed;
   inaDirection = forwards?HIGH:LOW;   // ? and : are the same as an if statement, just more compact.
   inbDirection = forwards?LOW:HIGH;
}

// move no need for forward and reverse anymore
void move()
{
    analogWrite(pwn, pwmVal);
    delay(sDelay);
    digitalWrite(ina, inaDirection);
    digitalWrite(inb, inbDirection);
}

```

---
Tags: motor
---


# Question
Title: Arduino continuously reading ADC value using interrupt
I have a mono jack audio act as analog input for arduino UNO. The microphone outputs voltage that varies in terms of `amplitude` (volume) and `frequency`. In order to get the high sampling rate, I use prescaler 16 and set high baudrate for serial communication to print the value. I save the analog read from that jack audio to `buffer` array with maximum value is 256 (8-bit). This is my code (I modify from the Nick Gammon's blog about ADC here) :

```
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

void setup ()
  {
  Serial.begin (230400);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
//  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

}

// ADC complete ISR
ISR (ADC_vect)
{
    results[resultNumber++] = ADC;
    if(resultNumber == MAX_RESULTS)
    {
      ADCSRA = 0;  // turn off ADC
    }
}

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.println (results [i]);
  }
}

```

With that code, I got a nice result of sinusoidal graph represented audio value up to 4000 Hz like this :

But one thing that didn't work is if I change the volume or frequency (while displaying data) of analog input (jack audio), the graph I print and display via serial plot audio **won't change**. So I had to close it and open again to see the change. The question is how can I achieve the continuous and real time reading of this ? Thank you very much.

# Answer
> 4 votes
reset the `resultNumber` to 0 after you have written it to serial. and turn interrupts back on

```
void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.println (results [i]);
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF)| bit (ADPS2) | bit (ADATE);
   // turn ADC back on
}

```

---
Tags: arduino-uno, interrupt, timers, analogread
---


# Question
Title: Why is this IIR Filter unstable on the Arduino Due?
I am using an Accelerometer (on the MPU6050) and connected it to the **Arduino Due**. In order to filter the signal I am using an IIR Filter with the following transfer function:

H(z) = Y(z)/X(z) = B/A

B = 0.00000376 + 0.00001127\*z^(-1) + 0.00001127\*z^(-2) + 0.00000376\*z^(-3)

A = 1 - 2.9372\*z^(-1) + 2.8763\*z^(-2) - 0.9391\*z^(-3)

which is an IIR 3th Order Butterworth, Cutoff Freq: 0.5Hz, Samling Freq: 100Hz. These numbers can be calculated by any IIR calculator.

Thus, then discrete equation is:

y\[n\] = 0.00000376\*x\[n\] + 0.00001127\*x\[n-1\] + 0.00001127\*x\[n-2\] + 0.00000376\*x\[n-3\] + 2.9372\*y\[n-1\] - 2.8763\*y\[n-2\] + 0.9391\*y\[n-3\]

I first tried it on the Arduino UNO. Then I found out that decimal point **precision** (float & double) on the UNO is **only 6-7 digits**. But the therm "B" in the transfer function has for example (0.00000376) **9 digits**. I thought this is the porblem, so I switched to Arduino Due and now I am using double (instead of float) which should have **enough precision**.

It is still unstable. It is not oscillating but getting bigger. I also tried an IIR 4th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz. This one is oscillating.

However, the only IIR that seems to be stable is an IIR 3th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz.

I have no idea so far what the problem is. Could anyone help please?

# Answer
1. The precision of a float is about 7 **significant** digits. The constant term of B in your transfer function (0.00000376) has only 3 significant digits.
2. Your transfer function has a pole at *z* = 1. It is thus not really stable, but only *marginally* stable. Any parasite DC component in the input will make the output drift without bounds.

It seems to me that your problem is not related to the implementation of the filter on the Arduino, but rather to the filter design. Where did you get that transfer function from?

**Edit**: I looked at the filter you are trying to make. It turns out it is very sensitive to the precision of the coefficients of A(z). If you try to add these coefficients, they *almost* cancel out: their sum is about 3e-5. At zero frequency, both A and B are 3e-5, and the transfer function, which is their ratio, is 1. By rounding the coefficients to four decimal places, you made the cancellation exact, and the transfer function infinite.

Just write the transfer function with more decimal places in the coefficients and it should work:

H(z) = 3.75592×10−6 (1 + 3 z−1 \+ 3 z−2 \+ z−3)
÷ (1 − 2.9371759 z−1 \+ 2.8763097 z−2 − 0.9391038 z−3)
> 2 votes

---
Tags: arduino-due, accelerometer, mathematics
---


# Question
Title: How do I call functions sequentially without using the Delay function?
I've been messing with the Adafruit Neopixel lib, and I'm trying to replace some of the delay functions with mills ( so that I don't block the serial port ). So far I have the following code;

```
void loop() {
  currentMillis = millis();

  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
  colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
}

void colorWipe(uint32_t c, uint8_t wait) {
  if (currentMillis - previousMillis >= 200) {
    for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      //delay(wait);
      Serial.println("Light");
      previousMillis = currentMillis;
    }
   Serial.println("Done");
  }
}

```

The issue I'm running into ( and I do understand this is fundamental concept in Arduino programming ) is how to run sequential functions, like the ones in loop, while still not blocking the main loop. The way this currently functions, it runs through the first colorWhipe loop and then just keeps iterating.

# Answer
I'm assuming you want to run each `colorWipe` for 200 ms, one after another.

You need a state machine to timing each `colorWipe`, like this:

```
void loop()
{
    static int state = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;

        switch(state) {
        case 0 :
            colorWipe(strip.Color(255, 0, 0), 50); // Red
            state++;
            break;

        case 1 :
            colorWipe(strip.Color(0, 255, 0), 50); // Green
            state++;
            break;

        case 2 :
            colorWipe(strip.Color(0, 0, 255), 50); // Blue
            state++;
            break;

        case 3 :
            colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
            Serial.println("Done");
            state = 0;
        }
    }
}

void colorWipe(uint32_t c, uint8_t wait)
{
    for(uint16_t i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
        strip.show();
        //delay(wait);
        Serial.println("Light");
    }
}

```

In each `loop` you will be waiting 200 ms before doing anything. When the times comes, you will enter the `if` with `state==0` and you will execute the first 'colorWipe'. After that, you *advance* the state by adding 1 to `state` variable.

Then you will be entering `loop` and doing nothing for another 200 ms. When that time pass, you will enter the `ìf` with state==1. Now the second `colorWipe` will be executed.

When the last colorWipe is executed, you set `state` to zero and begin again.
> 3 votes

# Answer
Assuming the commented out delay in colorWipe should still happen then you need to nest the state machines:

```
void loop()
{
    static bool waiting=false;
    static int state = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = millis();
    if(waiting){
        if(currentMillis - previousMillis >= 200){
            waiting = false;
        }
    }

    if(!waiting  && currentMillis - previousMillis >= 50) {
        previousMillis = currentMillis;

        switch(state) {
        case 0 :
            if(colorWipe(strip.Color(255, 0, 0))){ // Red
                state++;
                waiting = true;
            }
            break;

        case 1 :
            if(colorWipe(strip.Color(0, 255, 0))){ // Green
                state++;
                waiting = true;
            }
            break;

        case 2 :
            if(colorWipe(strip.Color(0, 0, 255))){ // Blue
                state++;
                waiting = true;
            }
            break;

        case 3 :
            if(colorWipe(strip.Color(0, 0, 0, 255))){ // White RGBW
                state++;
                state = 0;
            }
            break;
        }
    }
}

int wipeState = 0;
bool colorWipe(uint32_t c)
{

    strip.setPixelColor(wipeState , c);
    strip.show();

    Serial.println("Light");
    wipeState++;
    if(wipeState == strip.numPixels()){
        wipeState = 0;
        return true;
    }
    return false;
}

```
> 1 votes

# Answer
Here's an OOP solution. (It seems a lot of Arduino programmers shy away from C++ classes, but I use them all the time).

Since you don't want to block `loop()`, you need to create a function that will set the pixel (if time has expired) and return immediately. I would create a class to encapsulate the pixel strip.

The way this works is the class has a `loop()` function that needs to be called every time in the main program's `loop()` function. The class's `loop()` will either return (almost) immediately or it will update the pixel. Which will also be very quick. This allows you to do other things in the main `loop()`.

Disclaimer: I just whipped this up, there may be bugs.

```
// A class to encapsulate the neo pixel strip.
class color_strip {
    protected:
    Adafruit_NeoPixel pixels;
    uint32_t last_ms;
    uint32_t color;
    uint32_t duration = 0;
    int current_pixel;
    bool first_time;

    public:
    // Constructor
    color_strip(int num_pixels, int pin) {
        strip = Adafruit_NeoPixel(num_pixels, pin, NEO_GRB + NEO_KHZ800);
    }

    // Call this from setup()
    void setup() {
       strip.begin();
    }

    // Call this to start a wipe
    // param duration_ms is how long the entire wipe should take
    void wipe(RGB color, uint32_t duration_ms) {
        // Calculate how long to light each pixel
        duration = duration_ms / strip.numPixels()
        // Initialize this data for loop()
        last_ms = millis();
        first_time = true;
        this->color = strip.Color(color.red, color.green, color.blue);
        current_pixel = 0;
    }

    void loop() {
        // Is there something to do? Only if duration != 0
        if (0 != duration) {
            // Time to change pixel?
            uint32_t current_ms = millis();
            if (current_ms - last_ms >= duration || first_time) {
                first_time = false;
                // Finished the entire wipe?
                if (current_pixel == strip.numPixels()) {
                    duration = 0;
                }
                else {
                    // Set the pixel
                    strip.setPixelColor(current_pixel++, color);
                    strip.show();
                    // Save
                    last_ms = ms;
                }
            }
        }
    }

    // Returns true if doing a wipe, else false
    bool working() {return duration != 0;}
};

```

Usage: you can create an array of colors. You then cycle through all these colors. If you want to add more colors, simply add to the array.

```
// Helper struct to store rgb
struct RGB {
    byte red, green, blue;
};
RGB all_colors[] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255},
    {0, 0, 0}
    // Add more colors here, if needed
};
// Need to keep track of the current color being displayed
byte current_color = 0;
const byte num_colors = sizeof(all_colors) / sizeof(all_colors[0]);

// Here's the actual object
// Change the parameters to whatever they need to be in your setup
color_strip strip(number_of_pixels, pin_number);

void setup()
    // Call the class setup function
    strip.setup();
}

void loop()
{
    // If the strip has completed its wipe, set it to next color
    if (!strip.working()) {
        current_color = (current_color + 1) % num_colors;
        strip.wipe(all_colors[current_color], 1000);
    }
    // Call the class loop(). It will return quickly so won't block
    // the rest of the program
    strip.loop();

    // Do other stuff here...
}

```
> 1 votes

---
Tags: led, timers
---


# Question
Title: Wrong code ouput, when the specific function runs more than once
If I run the following code, I get the correct output, and the path is displayed on the serial monitor. However when I run the code together with the commented out portion (in the code below) I don't get any output; even the output that is printed before this code doesn't print completely. Why is that?

I have figured it out that this happens when the dijkstra functions runs more than once. But it shouldn't happen like this.

```
   int *path1 = NULL;
    int no_of_nodes_1;
    dijkstra(graph, startingNode1, end1_start2, &path1, no_of_nodes_1);

    /*int *path2 = NULL;
    int no_of_nodes_2;
    dijkstra(graph, end1_start2, end2_start3, &path2, no_of_nodes_2);

    int *path3 = NULL;
    int no_of_nodes_3;
    dijkstra(graph, end2_start3, endingNode3, &path3, no_of_nodes_3);
        */
        delete graph;

    Serial.println();

    Serial.println( "PATH 1:");
    for (int k = 0; k < no_of_nodes_1; k++){
        Serial.print(path1[k]);Serial.print("..");
        }

/*
    Serial.println();
        Serial.println( "PATH 2:");
    for (int x = 0; x < no_of_nodes_2; x++){
        Serial.print(path2[x]);Serial.print("..");
    }

    Serial.println();
    Serial.println( "PATH 3:");
    for (int y = 0; y < no_of_nodes_3; y++){
        Serial.print(path3[y]);Serial.print("..");
    }

*/

```

**::UPDATE::**

```
/******************************************************************************/
    void getNextNode(int node, const int& src, const int predecessor[264], int temp_path[], int& i){

        i = 1;

        if (node == src)
        {
            temp_path[i] = src;
        }

        else if (predecessor[node] == -1)
        {
                Serial.println("No path exists");
        }
        else {
            getNextNode(predecessor[node], src, predecessor, temp_path, i);
            temp_path[i] = node;
            i++;
        }

        return;
    }
/********************************************************************************/
    int* savePath(int predecessor[264], const int& src, const int& targetnode, int & numofnodes){

        int temp_path[200];
        temp_path[0] = src;
        int i;

        if (targetnode == src)
        {
            temp_path[1] = src;
        }
        else
        {
            getNextNode(targetnode, src, predecessor, temp_path, i);
        }

        numofnodes = i;
        int *path = new int[i];

        for (int k = 0; k < i; k++){
            path[k] = temp_path[k];
        }

        return path;

    }
 /****************************************************************************/
    void dijkstra(struct Graph* graph, int src, int target, int **path, int& numofnodes)
    {
        // The main function that calulates distances of shortest paths from src to all
        // vertices. It is a O(ELogV) function

        int V = graph->V;// Get the number of vertices in graph
        int* dist = new int[V];      // dist values used to pick minimum weight edge in cut

        int predecessor[264]; //array to save nearest nodes

        // minHeap represents set E
        struct MinHeap* minHeap = createMinHeap(V);

        // Initialize min heap with all vertices. dist value of all vertices
        for (int v = 0; v < V; ++v)
        {
            dist[v] = INT_MAX;
            minHeap->array[v] = newMinHeapNode(v, dist[v]);
            minHeap->pos[v] = v;
            predecessor[v] = -1;
        }

        // Make dist value of src vertex as 0 so that it is extracted first
        minHeap->array[src] = newMinHeapNode(src, dist[src]);
        minHeap->pos[src] = src;
        dist[src] = 0;
        decreaseKey(minHeap, src, dist[src]);

        // Initially size of min heap is equal to V
        minHeap->size = V;

        // In the followin loop, min heap contains all nodes
        // whose shortest distance is not yet finalized.
        while (!isEmpty(minHeap))
        {
            // Extract the vertex with minimum distance value
            struct MinHeapNode* minHeapNode = extractMin(minHeap);
            int u = minHeapNode->v; // Store the extracted vertex number

            // Traverse through all adjacent vertices of u (the extracted
            // vertex) and update their distance values
            struct AdjListNode* pCrawl = graph->array[u].head;
            while (pCrawl != NULL)
            {
                int v = pCrawl->dest;

                // If shortest distance to v is not finalized yet, and distance to v
                // through u is less than its previously calculated distance
                if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
                    /*pCrawl->weight*/1 + dist[u] < dist[v])
                {
                    dist[v] = dist[u] + 1 /*pCrawl->weight*/; // 1 is the weight of the node
                    predecessor[v] = u;
                    // update distance value in min heap also
                    decreaseKey(minHeap, v, dist[v]);
                }
                pCrawl = pCrawl->next;
            }
        }

        delete[] dist;
        delete minHeap;
        *path = savePath(predecessor, src, target, numofnodes);
    }

```

# Answer
> 1 votes
You have likely run out of RAM.

You have 200 integers in the `temp_path` array. That equates to 400 bytes of SRAM. You also have 3 `predecessor` arrays each with 264 integers, which equates to 1584 bytes. These arrays combined use 1984 bytes. This is in addition to all your other variables and function calls.

The Arduino Uno only has 2KB of SRAM.

Solution:
Use an Arduino with a greater amount of SRAM.

* ARDUINO M0/Zero - 32KB of SRAM
* Arduino Mega - 8KB of SRAM
* Arduino Due - 96KB of SRAM

---
Tags: serial, programming, arduino-due, debugging
---


# Question
Title: How do I set a continuous servo to turn on until a switch is flicked?
I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.

Here is the schematic:

Here is my code:

```
#include <Servo.h>
Servo servo1;

int button = 2; //Assigning pin 2 for the momentary button
int buttonval = 0; //Creating a variable for the buttons value
int green = 12;
int red = 13; //Assigning the green and red LED to pin 12 and pin 13
int red = 13;
int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
int Open = 7;
int Closedval = 0; //Creating two blank variables for the states of the switch
int Openval = 0;

void setup() {
  servo1.attach(4); //Assigning the data pin for the servo
  servo1.write(1); // Giving a starting speed to the servo
  pinMode(button, INPUT); // Setting up the input pin for the momentary button
  digitalWrite(button, HIGH); //  turn on pull up resistors
  pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
  pinMode(Open, INPUT);
  pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);
  digitalWrite(Closed, HIGH);
  //Turning on pull up resistors for the two inputs from the toggle switch
  digitalWrite(Open, HIGH);
}

void loop() {
  Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
  Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

  if (Closedval == HIGH) {
    servo1.write(180);
    // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
  }

  if (Openval == HIGH) {
    servo1.write(86);
    // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
  }

  digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
  digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
}

```

Any help would be appreciated.

# Answer
> 1 votes
Your are not debouncing your input buttons, which means that `digitalRead(Closed)` (and Open) will be HIGH in one execution of `loop` and in the next pass, 3 millis later, it will be LOW.

The servo probably need over 50ms to complete the action (you don't said what servo are you using).

You need to wait for the action to be completed before trying to move it in another direction.

You didn't post your schematic, so may be you wired things wrong. How can we know?

Usually the first step when you find a problem is add `Serial.print` to know what is working and what not, and then correct the problem.

# Answer
> -1 votes
I seem to have got this working just by doing the following code:

```
#include <Servo.h>
Servo servo1;

int green = 12;       //Assinging the green and red LED to pin 12 and pin 13
int red = 13;

int Closed = 8;       //Assinging the Inputs of the toggle switch to 8 and 7

void setup()
{
  servo1.attach(4);    //Assigning the data pin for the servo
  servo1.write(86);     // Giving a starting speed to the servo

  pinMode(Closed, INPUT);        //Setting up the inputs for the two states of the toggle switch

  pinMode(green, OUTPUT);        //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);

  digitalWrite(Closed, HIGH);    //Turning on pull up resistors for the two inputs from the toggle switch

  delay(50);
  servo1.write(65); // start the motor opening
}

void loop() {
  if (digitalRead(Closed) == HIGH) { //If the toggle switch is changed then turn the servo in the oppisite direction
    servo1.write(100);
    if (digitalRead(Closed) == LOW) { // If the toggle switch is changed again then turn the servo off
      servo1.write(86);
    }
  }
}

```

Instead of using an external button I have had to use the reset button.

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


# Question
Title: Fast I2C communication between ESP8266 & PCF8591
I need faster communication between the ESP and the ADC, so I found this https://github.com/pasko-zh/brzo\_i2c.

**Original wire Example**

```
#include "Wire.h"
#define PCF8591 0x48
byte a0;

void setup() {
  Wire.begin(13, 14);
  Serial.begin(115200);
}

void loop() {
  Wire.beginTransmission(PCF8591);
  Wire.write(0x04);
  Wire.endTransmission();
  Wire.requestFrom(PCF8591, 5);

  a0 = Wire.read();
  a0 = Wire.read();

  Serial.println(a0);
  delay(1000);
}

```

**Brzo I2C example**

```
#include "brzo_i2c.h"

uint8_t buffer[10];
uint8_t error = 0;
float temp = 0.0;

uint8_t ICACHE_RAM_ATTR get_temp(float *t) {
  uint8_t bcode = 0;
  brzo_i2c_start_transaction(0x48, 400);
  buffer[0] = 0x04;
  brzo_i2c_write(buffer, 1, false);
  brzo_i2c_read(buffer, 2, false);
  bcode = brzo_i2c_end_transaction();
  *t = ((buffer[0] << 8) | buffer[1]);
  return bcode;
}

void setup() {
  delay(500);
  Serial.begin(115200);
  brzo_i2c_setup(13, 14, 2000);
}

void loop() {
  error = get_temp(&temp);
  if (error == 0) {
    Serial.print("Temp = ");
    Serial.println(temp, 8);
  } else {
    Serial.print("Brzo error : ");
    Serial.println(error);
  }
  delay(500);
}

```

But I get always the same error.

> 1 : Bus not free

I rewrote it in different ways, changing the frequency, pins and doing multiple transactions. The main reason I don't get it to work is the difference in the API.

There is no `Wire.requestFrom();` in the brzo\_i2c lib. So I need to read the value with `brzo_i2c_read(buffer,2,false);`.

# Answer
This line

```
brzo_i2c_start_transaction(0x48,400);

```

Sets the SCL frequency to 400kHz.

According to the Datasheet for the PCF8591 the maximum SCL clock frequency is 100kHz.

The other issue *may* be the "repeated\_start" flag on `brzo_i2c_write`.

If you look at the examples, and "apply" that to your code, your would do something like:

```
uint8_t ICACHE_RAM_ATTR get_temp(float *t){
  uint8_t bcode=0;
  brzo_i2c_start_transaction(0x48,100); // changed 400 to 100
  buffer[0]=0x04;
  brzo_i2c_write(buffer,1,true); // changed to true because
  brzo_i2c_read(buffer,2,false);
  bcode=brzo_i2c_end_transaction();
  *t=((buffer[0]<<8)|buffer[1]);
  return bcode;
}

```

My understanding of the code is that you would set `repeated_start` to true in the write if you want to then immediately read - which in your case you want to.
> 2 votes

# Answer
I have no idea about Brzo but this looks wrong:

```
 brzo_i2c_start_transaction(0x48,400);
 buffer[0]=0x04;
 brzo_i2c_write(buffer,1,false);       // Write
 brzo_i2c_read(buffer,2,false);        // Then a read ??
 bcode=brzo_i2c_end_transaction();

```

I think you end and read are the wrong way round, but like I say I've never done anything with this so I'm probably wrong.
> 1 votes

---
Tags: esp8266, i2c
---