# Question
Title: Send numbers to arduino via serial port using python
I have a file with numbers called `fginputs.txt`. For example it could be something like this:

```
4958
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4958

```

I want python to send each number to arduino via serial port. After each number is received, arduino should print back an acknowledgment number, indicating that it got a valid number, and then store that number in a dynamic array, because I could create larger files. When there are no more numbers left, send a '-1' to finish transmission.

Here's my arduino code:

```
// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;

void setup()
{
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);

 //free dynamic array memory
 free(inputList);
 //counter for how many numbers I've received starts at 0
 cont = 0;
 //This is true when there are no more numbers to receive, meanwhile false
 inputsReady = false;
 setupInputList();
 }

/* If there's not enough space, resize the array by one unit and store the number
   */
void growAndInsert(int currentSize, int newInt){
    if(currentSize > SIZE)
        inputList = (uint16_t *)realloc(inputList, (currentSize + 1)*sizeof(uint16_t));
    inputList[currentSize] = newInt;
}
/**
  init inputList with 100 blocks
 */
void setupInputList(){
  SIZE = 10;
  inputList = (uint16_t *)malloc(sizeof(uint16_t) * SIZE);
}

void clearBuffer(){
while(Serial.available() > 0)
    Serial.read();
}

/**
Listens in serial port for an integer that represents a new input and returns it.
If it doesn't get anything useful from serial, return 0
*/
  int getNewInputFromSerial(){
   if (Serial.available() > 0) {
    delay(100);
    // look for the next word
    int cmd = Serial.parseInt();
    clearBuffer();

    if(cmd == 4958)
        Serial.write("4");
    else if(cmd == 4154)
        Serial.write("5");
    else
        Serial.write("0");
    return cmd;
   }
  return 0;

}

void loop()
{
     if(!inputsReady){
        int newInput = getNewInputFromSerial();
        if(newInput == 0)
            return;
        if(newInput != -1)
            growAndInsert(cont++, newInput);
        else{
            inputsReady = true;
            //initTimer();
        }
    }

}

```

and the python script:

```
global arduino
PORT = '/dev/ttyACM0'
FILENAME = "fginputs.txt"
#Read file with inputs
with open(FILENAME) as f:
        content = f.readlines()
#init serial port
arduino = serial.Serial(PORT, 9600, timeout=1);
time.sleep(2);

#write
for input in content:
    arduino.flush()
    arduino.write(input)
    time.sleep(.1);
    resp = arduino.read();
    print "i got " + resp

#Finish transmission with -1
arduino.flush()
arduino.write("-1")
#done
arduino.close();

```

The fist time I execute the script I get this:

```
i got 4
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 4

```

Which is great. But if I run it a second time I get this:

```
i got 0
i got 4
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0

```

Which is terribly wrong because the file hasn't changed. I don't know what is going on here. If I unplug and plug back in the USB cable, transmission works flawlessly again.

# Answer
```
// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;

void setup()
{
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);

 //free dynamic array memory
 free(inputList);

```

You are freeing a NULL pointer which is ~~an undefined operation~~ not necessary here, since it was never allocated.

---

```
  if (Serial.available() > 0) {
    delay(100);
    // look for the next word
    int cmd = Serial.parseInt();
    clearBuffer();

```

This is going to just throw data away, I'm not surprised stuff goes missing.

Read this: How to process incoming serial data without blocking \- you need to get rid of the `delay`, and the `clearBuffer()` for a start.

---

Example code for reading from Serial without blocking and without using `delay`:

```
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

```

In `process_data` in my example is where you would call `atoi` to convert the incoming string into an int (or `atol` if it is going to be longer).
> 3 votes

# Answer
You could have a look at this.

It's a python program which does record/playback of key-presses, through an UNO.

It already implements:

* serial communication with error checking
* ACK: each message has its own ID, so you can keep track of what was lost, should anything bad happen
* synchronization, in case your Arduino is powered up after the python program is started
> 1 votes

---
Tags: serial, usb, python
---


# Question
Title: What happens if I don't open the USB serial port of Arduino Pro Micro / Leonardo?
My question is related to this one. My sketch seems to stop responding after some time if I run it with debug enabled and I don't open the serial port/monitor on the computer.

Does the UART buffer fill up and block or something? Or, does it discard the excess data and keep working?

I can't find information about it.

# Answer
As far as I can see from CDC.cpp it attempts to see if the USB is available and if not, do not write anything but set the "write error" flag.

```
size_t Serial_::write(const uint8_t *buffer, size_t size)
{
    /* only try to send bytes if the high-level CDC connection itself
     is open (not just the pipe) - the OS should set lineState when the port
     is opened and clear lineState when the port is closed.
     bytes sent before the user opens the connection or after
     the connection is closed are lost - just like with a UART. */

    // TODO - ZE - check behavior on different OSes and test what happens if an
    // open connection isn't broken cleanly (cable is yanked out, host dies
    // or locks up, or host virtual serial port hangs)
    if (_usbLineInfo.lineState > 0) {
        int r = USB_Send(CDC_TX,buffer,size);
        if (r > 0) {
            return r;
        } else {
            setWriteError();
            return 0;
        }
    }
    setWriteError();
    return 0;
}

```

This is the same test as is done in `operator bool()` without the 10 ms delay.

```
// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

```

Judging by the comments above, this may not be the most reliable thing in the world.
> 1 votes

---
Tags: serial, arduino-leonardo, usb, uart
---


title: Power saving of atmega 2560

text:
# Question
Title: Power saving of atmega 2560
Is arduino code Consume More power other than "Avr Studio" Code?

Please tell some key points for power saving. Processor on $ off Methodology.

# Answer
> 2 votes
There is nothing about the Arduino code that would inherently consume more power than using a different compiler, so no, it doesn't. What the code does you can change in either development environment.

Read Power saving techniques for microprocessors for a considerable number of tips about saving power.

Also see related threads about this question such as What are (or how do I use) the power saving options of the Arduino to extend battery life?

---
Tags: power
---


# Question
Title: What requirements should components have to work with Arduino (UNO in particular)
I am fairly new to the whole concept of Arduino and electronic engineering in general.

Recently I bought myself an Arduino UNO and I'm wondering what "non off the shelf" components will work when I hook them up with the UNO. I have a lot of old electronic stuff laying around containing pushbuttons, sliders, faders, knobs etc. wich if possible, I'd like to take apart to connect them to the UNO for some fun fuzzin' around.

Many thanks in advance!

PS: this is my fist post ever on stackexchange so excuse me if the question is placed incorrectly or the tags are weird. Please DO correct me where I'm wrong.

# Answer
When it comes to electronics, hypothetically anything can be connected to anything else. The only real barriers are time, cost, and practicality.

Two major things to look out for though are voltage and current requirements.

Most Arduinos operate at 5 volts, so it's often easiest to connect it to other electronic devices which also operate at 5 volts. That certainly doesn't mean you *can't* connect an Arduino to something that operates at 3.3 volts (for example). However, it means you may need to add some voltage level conversion circuitry (although it's not always necessary, depending on the context).

Regarding current, a critical issue to look out for is how much current something will draw. For example, a motor will often require more current than an Arduino can safely provide. That means you'd need some kind of external power supply which can be switched by the Arduino.

The most valuable thing to do is to learn to find and read datasheets. These give information about electronic components, specifying things like voltage, current, timing and so on. For situations where there's no datasheet available, you may find it useful to learn how to use a multimeter and an oscilloscope to monitor how equipment behaves.
> 2 votes

---
Tags: arduino-uno, components
---


# Question
Title: What could cause interrupts from MCP23017 suddenly stop working?
I have 4 rotary encoders connected to an MCP23017 which in turn is connected to interrupt port 0 on the arduino (and to I2C of course). Everything works fine: I get interrupts for all 4 rotary encoders, can read the values for them and even store these values in the EEPROM and load them in setup.

Now, I connect a WS2812 LED to the arduino (with a resistor and a capacitator in front of it). I connect the UNO and the led lights up. I attach the serial console (resetting the UNO) and it stops working (LED does not light up). This could just be simple wiring mistake and is not my real problem.

I remove the LED (and the capacitor) from the board and start everything up again. I can see via the serial console that the UNO works, however it does not receive any interrupts anymore. I exchange the MCP23017 thinking I fried it somehow but that doesn't change anything either...

Is there some sort of state the UNO has I could have affected?

Or could I have fried the interrupt "sub-system" on the UNO (again: all the other stuff still works)?

EDIT: The code is here: https://github.com/qollin/Liting/blob/master/src/Liting.cpp

# Answer
I think I figured out whats wrong: you need to reset the interrupt handling of the MCP in setup() (by reading from both INT pins). Otherwise the MCP may start in a state where it does not generate new interrupts, because it waits for the old ones to be handled...
> 0 votes

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


# Question
Title: Can I supply the board's 3.3V directly to the AREF pin?
Short dumb question: can I connect the 3.3V pin and the analog reference pin (AREF) directly?

I've heard mentions of a 32K internal resistor but I'm not willing to risk a short circuit without confirmation. Should I add an external resistor? Won't that create a voltage divider?

# Answer
In Atmel's doc8271 pdf (with specification details for ATmega48A; ATmega48PA; ATmega88A; ATmega88PA; ATmega168A; ATmega168PA; ATmega328; and ATmega328P), table 29-20 on page 117 shows R\_REF (the AREF input resistance) as 32KΩ (typical). Section 24.5.2 on page 248 suggests that AREF is to be treated as a high-impedance input or output:

> ... the reference voltage can be made more immune to noise by connecting a capacitor between the AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that VREF is a high impedance source, and only a capacitive load should be connected in a system.

Also note that there is no reason to connect anything to AREF (pin 21), because on a standard Uno, AVCC (pin 20) is connected to VCC (pin 7), and one can select AVCC as the reference voltage during analog converter setup \[as explained below\]. Quoting again from section 24.5.2:

> VREF can be selected as either AVCC, internal 1.1V reference, or external AREF pin. AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC...

Summary: you can connect the 3.3V pin and the analog reference pin (AREF) directly, but on a 3.3V system there is no reason to do so.

*Selecting AVCC as the reference voltage:* Say analogReference(DEFAULT) to select AVCC as the reference voltage. According to arduino.cc, this will choose “the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)”.
> 1 votes

# Answer
I don't see any big objection to connecting the 3.3 V pin to AREF, providing you take precautions in your code.

The default for AREF is so-called DEFAULT (heh) as here:

```
uint8_t analog_reference = DEFAULT;

```

Once you do an `analogRead` the analogRead code connects up the desired analog reference:

```
ADMUX = (analog_reference << 6) | (pin & 0x07);

```

Then it starts the ADC conversion.

If you **change** the analog reference voltage then this needs to be done **before** doing the analogRead. eg.

```
  analogReference (EXTERNAL);
  analogRead (A0);  // use external reference

```

The reason they do it this way is so that it is safe to physically connect up the 3.3V pin to the AREF pin, because the initial state of the processor is to **read** the AREF pin.

Once you do your first analogRead, and with the DEFAULT reference voltage used, you will find 5V at the AREF pin. If you had then connected that to something else like the 3.3V pin, it will short out and damage the board.

Example code:

```
void setup ()
  {
  pinMode (13, OUTPUT);
  delay (5000);
  digitalWrite (13, HIGH);
  int foo = analogRead (0);
  }  // end of setup

void loop ()
  {
  }  // end of loop

```

Put your meter on AREF and you will see it jump to 5V after 5 seconds.
> 1 votes

---
Tags: arduino-uno, analogread, resistor
---


title: What's Wrong with this DHT22?

text:
# Question
Title: What's Wrong with this DHT22?
I made a circuit that takes humidity and temperature from DHT22 sensor and displays it on Lcd Screen. Simple enough but i get this error "Failed to read from DHT". That happens because i have this code

```
 if (isnan(t) || isnan(h)) {
  delay(100);
    Serial.println("Failed to read from DHT");
  } else {
    delay(100);
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
    //lcd.print("Temp: ") ;
    //lcd.print(t);
    //lcd.setCursor(0, 1);
    //lcd.print("Hum: ") ;
    //lcd.print(h);
  }

```

So the values are **NaN** . But 1 minute before it worked fine, and now again it doesnt. Everything is soldered the right way and nothing is false. Lcd is wired ok and it works but i dont get values from DHT22.

Here are some pics to help you out.

In the third Image we see its working. And now its not! is the DHT sensor broken?

```
  #include "DHT.h"
#include <LiquidCrystal.h>`

#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHT22 test!");
  lcd.begin(16, 2)
  dht.begin();
}

void loop() {

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(t) || isnan(h)) {
    Serial.println("Failed to read from DHT");
  } else {

    lcd.print("Hum: ");
    lcd.print(h);
    lcd.setCursor(0, 1);

    lcd.print("Temp: ");
    lcd.print(t);

  }
}

```

Thats my code by the way

# Answer
> 2 votes
Two things:

1. You need to put a delay in between your read requests. Currently you're reading way too fast, every few milliseconds you're hitting the DHT. Max interval should be every two seconds or so.
2. Add a 10k resistor between pin 1 and 2 of the DHT.

I'd bet adding a delay, or using the simpleTimer library to control how frequently you read from the DHT will clear this up.

---
Tags: c++, temperature-sensor
---


# Question
Title: I would like to control 16 motors with a servo shield
Ok so I've used nicks code and have the code running once ok.... I the noticed however I had a fast 180 sweep and then it returned under control of code. I then noticed the comments wrt pulselen of 1000 being zero degrees and using 1500 as 90 degrees.... Wow so I get a single movement which holds but it doesn't go 90 degrees...

I'm using an Adafruit servo shield.

I can make my servo move. However, I want to stop it at 90 degrees *without* it returning to 0 degrees each time.

What am I missing?

The code I've used is as follows:

```
void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop()
{
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }
  delay(500);
}

```

# Answer
The code in `loop` is called repeatedly. Thus it does this:

* Go from SERVOMIN to SERVOMAX very rapidly (I measured 72 ms)
* Pause half a second
* Repeat the above

To make it pause at SERVOMAX you need to either not repeat the loop, or put it all in `setup`, eg.

```
#include <Adafruit_PWMServoDriver.h>
#include <Wire.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)
void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }

}

void loop()
{
}

```
> 1 votes

# Answer
The variable `pulselen` in your code corresponds to the angle you want the servo to turn to. For most servos the `pulselen` is supposed to be a number from 1000 to 2000, where 1000 corresponds to 0 degrees and 2000 corresponds to 180 degrees, but some servos may be different. It's probably safe to assume that you want a value close to 1500.

Of course the servo takes a while to get to its position, so the best approach usually involves changing `pulselen` gradually until you get to the desired position.

Once you get to 90 degrees stop changing `pulselen`. At that point you should still be sending the PWM but keep it at 1500. You'll want to keep sending the PWM signal, or the servo will have no resistance to external forces.
> 0 votes

---
Tags: arduino-uno, motor, servo, adafruit
---


# Question
Title: Simple Arduino - 74hc595 shift register construction [tmli5]
I'm quite new to Arduino world and I'm trying to understand how shift registers work. I built this construction :

In fact, it is an Arduino Duemilanove with AtMega on it, but afaik it doesn't matter.

The tutorial I try to follow use SPI library so I try to do it too. I kind of understood that data input, latch and clock had to be pins 7, 4 and 11.

Basically, all I try to do is sending a byte to light the LEDs. As for me now, the sequence should light all LED, then no one, then one after another. I know there is one more input ont the right side of the SR but I didn't plan this model so I ran out of LEDs...

This is the code I use :

```
#include <SPI.h>
#include <StandardCplusplus.h>
#include <vector>
#include <iterator>
#include <size_type>

using namespace std;

//pin du shift register
#define DATA_PIN 13
#define LATCH_PIN 4
#define CLOCK_PIN 11
//à utiliser plus tard
#define INPUT_PIN 2

void setup() {
  pinMode(DATA_PIN, OUTPUT);
  pinMode(LATCH_PIN, OUTPUT);
  pinMode(CLOCK_PIN, OUTPUT);
  //pinMode(INPUT_PIN, INPUT);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.begin();

  //SPI.transfer(getBit(3));
  //digitalWrite(LATCH_PIN, HIGH);
  //digitalWrite(LATCH_PIN, LOW);

  Serial.begin(9600);
  Serial.println("start !");
}

void loop() {
  shift(B11111111);
  shift(B00000000);
  shift(B10000000);
  shift(B01000000);
  shift(B00100000);
  shift(B00010000);
  shift(B00001000);
  shift(B00000100);
  shift(B00000010);
  shift(B00000001);
}

void shift(int n){
  SPI.transfer(n);
  digitalWrite(LATCH_PIN, HIGH);
  digitalWrite(LATCH_PIN, LOW);
  Serial.print("shift : ");
  Serial.println(n);
  delay(1000);
}

```

When I upload this code, LEDs sequence has no sense, but serial output was totally OK.

What I see (without the output 0 of course) is : 1111111, 0111111, 1011111, 1110111, 1111101 and then 1111111 without further changes, whereas serial output is 255, 0, 128, 64, 32, 16, 8, 4, 2, 1, 255, 0, 128 and so on.

I assume I didn't understand something important, and it prevent me from finding answers in google.

Thanks for helping, it's really disturbing for me.

EDITS :

changed the title, it is a 74HC595.

Strangest behavior too (not gonna create another topic for that now), I dont have to connect both the gnd and VCC from my arduino for this to light LEDs. It changes a little the brighness of LEDs, but surprisingly VCC\< GND\< both

This is the tutorial I use to understand shift registers : https://youtu.be/6fVbJbNPrEU?t=195, and the one that uses SPI is nXl4fb\_LbcI

I am now aware that I should get one resistor for each LED but I don't have that much resistors and as far as I can see this don't harm my LEDs nor underpower them.

# Answer
> 1 votes
You have a number of problems here. The first is the wiring.

My wiring diagram above is for the Uno / Duemilanove. Since that is what you have, you should follow that.

The pins are fixed in hardware, except for the slave select pin. Thus D13 on the Duemilanove should go to pin 11 on the 595. D11 on the Duemilanove should go to pin 14 on the 595. And your slave select (which may as well be pin 10 on the Duemilanove) should go to pin 12 on the 595.

---

Your code looks more complex than it needs to be. This code will exercise the 8 LEDs:

```
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

```

---

As other responders have said, you should have a current-limiting resistor for **each** LED. You can't share it like that.

Also the 595 ground (pin 8) should be wired to the Duemilanove ground, not via a resistor.

---

## Reference

Using a 74HC595 output shift register as a port-expander

---
Tags: shift-register
---


# Question
Title: Arduino Ethernet Shield Response Process, Time, and Synchronization
I have a ethenet shield. I want to update my server page. Server page have to show current time. The code is given in this link. Code works but there is two problem

1- When i press the stop button in the browser, Arduino stops. After this i press refresh button and there is no response.

2- How can i synchronize the arduino time. From where? without setup another server. Is there any time stamp server that compatible with arduino?

# Answer
### Question 1.

Your code looks odd:

```
void checkForClient(){

  EthernetClient client = server.available();

  if (client) {
    boolean sentHeader = false;
    while (client.connected()) {
      if (client.available()) {
        if(!sentHeader){
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          sentHeader = true;
        }
        durumBildir(client,50,ID);
      }
    }
  }
  delay(1); // give the web browser time to receive the data

}

void durumBildir(EthernetClient client, int deger,String ID){
  client.print(ID);
  client.print("-");
  client.print(deger);
  client.print("-");
  if (timeStatus()!= timeNotSet) {
    digitalClockDisplay( client);
  }

  client.print("<br>");
}

```

You never **read** from client, so it will **always** be available (and thus you never leave your loop). I just tested it. Why are you sending the time out indefinitely? Even when you disconnect the poor Arduino is still sending the date and time out forever. No wonder you can't connect again.
> 1 votes

# Answer
I don't have an answer for question 1.

For question 2:

You can add a function to implement an NTP (network time protocol) client. For example, see the UdpNtpClient article on arduino.cc. In your `setup()` or `loop()` code call the function initially or perhaps hourly or daily to set system time via an NTP time server. The server's IP address can be hardcoded or otherwise as you like.

For lists of public time servers, see www.ntp.org and pool.ntp.org.

Alternately, you could add a DS1302 or similar clock chip board to your hardware.
> 1 votes

---
Tags: ethernet, time
---


title: Arduino Mega as a USB device

text:
# Question
Title: Arduino Mega as a USB device
My need is to connect an Arduino board (any board that has around 3 UARTs support) to a host PC via USB and expose the 3 UART connections as 3 USB devices (say /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2) in the host PC. From my search, I found Arduino Mega 2560 supports upto 3 UARTs. My question is can we expose these UARTs into individual USB ports to the host system?

Thanks, Alexander

# Answer
> 2 votes
Not directly, no. You have basically have 4 UARTs on the Mega2560 - one of them (USART0, pins 0&1) is connected to the USB interface chip, and the others are left unassigned for you to use as you like. It's the USB interface chip that is being seen in your computer as /dev/ttyUSB0, not the UARTs in the Mega2560 chip.

That's not to say that what you are after is not possible - it is perfectly possible, but it will require some clever programming on your part. You will need to:

1. Define a protocol that will multiplex 3 streams of serial data through the one USB serial connection
2. Write a sketch that works with that protocol to direct the incoming data to the right UART ports and multiplex the UART traffic into the protocol stream you have defined
3. Write software on your computer to perform a similar task - read in data and multiplex it, and read the multiplexed data stream and split it out to three separate destinations.

What the destinations on the PC end can be is a bit of a wooly area. If you want to make it look like serial ports in /dev then you can use a *pty pair*, which is a master/slave pair of pseudo TTY devices that you can use to pass data through. On most Linux systems they are numbered devices in /dev/pts, so /dev/pts/1 would be an example.

The function `openpty(...)` creates and opens a pty pair for you to use in your program. You would do that 3 times to make three pairs and each one would be the endpoint to a sub-stream in your multiplexed data.

For instance, here is a bit of code I use to open a pty pair:

```
struct termios options;
openpty(&_masterfd, &_slavefd, _dev, NULL, NULL);
fcntl(_masterfd, F_SETFL, 0);
tcgetattr(_masterfd, &_savedOptions);
tcgetattr(_masterfd, &options);
cfmakeraw(&options);
options.c_cflag |= (CLOCAL | CREAD);
if (tcsetattr(_masterfd, TCSANOW, &options) != 0) {
    fprintf(stderr, "Can't set up PTY\n");
}

```

That makes it appear to almost be a serial connection in style. Of course you don't have the concept of a baud rate over a pty connection, so it will be down to your software to define how you control the baud rate (probably easiest to have it hard coded to the baud rates you need).

In that snippet you talk internally to the `_masterfd` with normal `read()` and `write()` functions as you would any other device or file. Some other piece of software would open the other end of the pty pair (the `_slavefd`), the name of which is placed in `_dev` when the pty pair are opened. You could use that `_dev` name to then create a symbolic link to a better named device instead of using the `/dev/pts/x` name that could change without warning from one run to the next.

---
Tags: arduino-mega, usb, uart
---


title: RDM630 RFID Reader on Beaglebone Black?

text:
# Question
Title: RDM630 RFID Reader on Beaglebone Black?
I have an RFID reader RDM-630 with these specifications: http://www.seeedstudio.com/depot/datasheet/RDM630-Spec..pdf

Could I connect this to a Beaglebone Black?

# Answer
Found what I was looking for and the answer is yes.
> 0 votes

---
Tags: rfid
---


title: MCP23017: 16x2 LCD showing black boxes

text:
# Question
Title: MCP23017: 16x2 LCD showing black boxes
I've researched a lot but I couldn't find a solution to my problem, which is that after properly following all steps from this Website: http://www.danielealberti.it/2014/02/collegamento-diplay-lcd-ad-arduino-via.html

and after using the Library LIQUIDTWI2:

(https://drive.google.com/file/d/0BwSP1-P3E2UJY1loYWtWQVRWNlU/edit?usp=sharing)

for I2C connections, the LCD keeps displaying black boxes on the top row.

I'm pretty sure that I have wired (as shown in the tutorial linked above) and programmed everything correctly but I'm still getting the black boxes. Is the problem related with the MCP23017 pin expander or with something else?

I'm using an Arduino UNO

# Answer
> 0 votes
Quite often such situation occurs when the display does not reset properly (the reset from the IDE does not necessarily reset the display!).

So, once the sktech has been uploaded to the board, I would first try to do a reset on the Uno board (using the RESET button). If that doesn't do the trick, I would recommend to make the contrast adjustable (all my LDC displays showed "black boxes in the upper row" on delivery and I had to ajust the contrast).

If that also has not the desired effect, there is no alternative to debugging your code. Without the code itself, we cannot guess what might be wrong.

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


title: Using arduino Due for camera control

text:
# Question
Title: Using arduino Due for camera control
Could the arduino Due take and send image data from 5MP camera module to PC in the following condition?

* frame rate = 1fps
* resolution = 2592 x 1944
* format = 10 bit bayer raw RGB
* interface : parallel ports (DVP) between camera and Due spi between Due and PC(or SD card)
* FIFO(frame buffer): would not be used
* SDRAM: would not be used (But if it is needed, I would SDRAM via spi. Also I can use a frame buffer like AL422B. But if it is possible I would avoid using them.)

The camera would send 50Mbit image data per second and they will be transferred via 8 parallel lines(D0~D7) to the Due. And then they would go to PC directly or after passing SDRAM. But how can one evaluate if the 84Mhz is enough to do this job by calculation?

Arduino Due specs https://www.arduino.cc/en/Main/arduinoBoardDue

camera module example (OV5642) http://www.uctronics.com/cmos-camera-adapter-board-for-omnivision-image-sensor-p-248l.html But this is not what I want to use. In my project I need to build a camera module and it would not include FIFO unless it's highly recommended.

# Answer
So a quick feasability assessment:

2592 W * 1944 H * 10 bit = 50388480 bits

50388480 bits / 8 bit data bus = 6298560 packets

84000000 clocks per second / 6298560 packets = ~13 clock cycles per packet

I think that by itself, from a purely data perspective, without looking too deep into datasheets, you could feasibly read data from a port and push it out the USB port, and clock the data in less than 13 cycles. But what this means is you'd have to get into the nitty gritty of the processor and figure out how to do that as low level as possible because `DigitalRead()` and `Serial.print()` aren't going to cut it as they won't be fast enough.

The real challenge is that the above totally depends on being able to clock the data from the sensor yourself, which if I recall correctly, these sensors can actually be pretty picky about their clock.

I would highly recommend a FIFO, that way the sensor data can be clocked to it as fast as it wants to be clocked, and then you could read from the FIFO at your own pace as it will clock data out at exactly the rate you want it. Also 1 FPS is a pretty lofty goal if you are only a beginner. Like I said, it is probably possible, but it requires a lot of optimizations and planning that are not very straightforward to implement, especially if you are just starting out.
> 0 votes

---
Tags: arduino-due
---


# Question
Title: i2c of Atmega 328 on arduino uno not working
I am using Arduino uno board with Atmega 328 for i2c. The ic is not showing any clock signal on its SCL line on oscilloscope, The same code when used with different new atmega 328, and same code. It is showing a good clock signal on oscilloscope.

The ic whose i2c is not working can be still programmed and can be used for other purposes like serial communication , adc etc.

So, is there any way by which i can confirm and surely say that i2c of my atmega 328 is fried up. And what can be the possible methods by which it can be fried up.

# Answer
> 1 votes
I2C (SDA-SCL) line needs to be pull up (place resistor on both to 5v input from master- the uno), it works with the arduino code for master-slave I2C (uno on master-severino on slave) using the code from arduino website (just be sure you set the address for the slave on the slave sketch (any number 1-126), it works for me that way, my pull up resistor is 10kohm, the same goes for my breadboard, if this is not doing the trick, maybe there's something wrong (I wouldn't know the answer to, just tried the i2c yesterday) update : on august5th (today) I just finished reading i2c's on atmel site, it is a complex one, there are several factors on why something is doing something on your twi comm, post your code, and maybe I have an answer

---
Tags: i2c
---


title: Model Rocket Sensors

text:
# Question
Title: Model Rocket Sensors
My idea is to record the acceleration/altitude of a small model rocket launch using these sensors and record all the data onto a microSD card which I'll retrieve afterwards. I'd like to be able to plot all of the data to analyze the performance of the rocket. This data will also help compare the experimental results to the theoretical ones.

Accelerometer

OpenLog/SD Card

(Was only allowed two links so couldn't include barometer)

I have a few questions to make sure that my logic is sound when trying to design this circuit;

1.) Since the OpenLog contains the ATmega328 microcontroller I was going to use the Arduino to write the instructions to this which will initialize the two sensors and start logging data. Is this the correct way to do this? From what I could tell the other sensors did not contain any EEPROM/Flash so there was no way to store any code on there.

2.) If I have multiple sensors running at the same time is this going to cause a data conflict when writing to the SD card? Would it be possible to save two different .txt files, one for each sensor?

Thanks

# Answer
> 1 votes
The OpenLogger was designed to be paired with and Arduino Pro or Arduino Pro Mini and just log the serial output from one of those. You could theoretically use the OpenLogger itself to do the sensor reading and writing, however, the I2C pins that your sensor needs haven't been broken out on the OpenLogger.

This means if you really wanted to make this happen, you would have to hand solder those pins and break them out yourself. After that the process is pretty straightforward. SparkFun provides both the source code and directions on programming it.

If trying to break those out is a little too tricky, you can either pair it with one of those Arduino models and use it to read the data, or find another similar logger device that has more pins broken out.

Two answer the second part of your question, reading multiple sensors isn't a problem. Usually the way these sensors work is you send a request for data to them and they return the reading, so you would just request from the first sensor, request from the second sensor, write out to the file.

You can write to two different files no problem eiteher. I would not however, recommend writing to two different files. Switching from one file to another, back and forth introduces a little extra overhead which will slow down your loop. In rocketry, things happen very fast, and you'll probably want keep your loop running as fast as possible. I would recommend just writing to a single file and include data from both sensors probably something along the lines of `time,accelX,accelY,accelZ,bar`.

---
Tags: sensors
---


# Question
Title: 2,5m cable too long for LCD connected to Arduino UNO?
So i got that 2,5m cable wired with the LCD and the arduino, but i keep getting those weird characters showing up on the LCD. Clearly there is a signal loss between the components but there has to be a solution to the problem. Perhaps by connecting capacitors/resistors to the wires will help? Is there any solution other than not using this long cable?

# Answer
If the interface you're using is I2C(only two cables from arduino to lcd, vice versa)you have a problem,you need to pull up the sda-scl channel with appropriate resistors, you could (maybe) boost the I2C signal using ti-p82b715 bus extender, I just assume you use I2C (2,5m length?), what interface do you use? SPI? I2C?
> 1 votes

# Answer
I'm presuming this is I2C or SPI, because a Serial cable of 2.5 m should still work.

You can slow both I2C and SPI down.

---

In the case of SPI you can call something like this:

```
SPI.setClockDivider(divider);

```

Where "divider" is one of:

* SPI\_CLOCK\_DIV2
* SPI\_CLOCK\_DIV4
* SPI\_CLOCK\_DIV8
* SPI\_CLOCK\_DIV16
* SPI\_CLOCK\_DIV32
* SPI\_CLOCK\_DIV64
* SPI\_CLOCK\_DIV128

The default is SPI\_CLOCK\_DIV4, so try a larger divider.

---

In the case of I2C you can change the clock speed and the prescaler. The default frequency is 100 kHz, but you could make it slower.

```
TWBR   prescaler   Frequency

  12       1       400   kHz  (the maximum supported frequency)
  32       1       200   kHz
  72       1       100   kHz  (the default)
 152       1        50   kHz
  78       4        25   kHz
 158       4        12.5 kHz

```

For example, to run at half the frequency (50 kHz) use:

```
  Wire.begin ();
  TWBR = 152;

```

To run at 25 kHz you also need to change the prescaler, eg.

```
  Wire.begin ();
  TWBR = 78;
  TWSR |= bit (TWPS0);

```

In the case of I2C make sure you have pull-up resistors on SDA and SCL in order to get a clean signal. 4.7 k is a reasonable value to try (for both of them) with the other ends connected to +5 V.
> 1 votes

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


# Question
Title: Existence of a non blocking and task yield framework for Arduino programming
I've been playing around with Arduino and understand that the standard runtime provides a single thread essentially.

I was wondering if it is possible to write a thin layer (library) that allows one to write code that is non blocking and one where each task yields control manually which allows the master loop to implement some form of timesharing.

I'd appreciate any:

1. Comments on existing frameworks that can allow me to write my programs this way
2. Any comments on how hard implementing anything of this order of magnitude would be.

# Answer
I would recommend NilRTOS. I like the fact that it's really minimal. However, you might find that some libraries (which you would like to use) work in blocking mode and cannot be used with this RTOS, because they might do bad things (polling) or worse things (polling in interrupt context with other interrupts disabled). But that will be the case regardless of the thread framework you choose.

You might want to try also femtoos. I think that the code could be organized far better, which is one of the reasons I preferred NilRTOS.
> 2 votes

# Answer
My recommendation would be to simply code without needing blocking. I have examples here.

Petri Häkkinen coded a game - Toorum's Quest \- without using any real-time library. That game (on a Uno) has multiple sprites, TV output and sound effects, all interleaved.

The basic technique is to know that you have multiple things you need to have done, from time to time, and check in the main loop if it is time to do one of them.

One issue with any sort of real-time library is, you only have limited resources. You need to be really aware, for example, of which bits of hardware are doing what (eg. timers, SPI, I2C, interrupt handlers, serial comms).

Even existing libraries suffer from the problem that one library may require (say) pin-change interrupts, and "requisition" the interrupt handlers needed for that, and another library also uses pin-change interrupts, and they cannot be linked together.
> 2 votes

---
Tags: programming, library, sketch, threads
---


# Question
Title: Float arithmetic vs. int arithmetic - is there any power penalty?
It is widely known that float arithmetic takes longer (that is, eats more cycles) than fixed-point (or integer, or bitwise arithmetic), and that surely is something to consider for speed- and time-critical applications.

My question is: supposing I don't have any time-critical need (and I have enough program and RAM memory), should I be worried by any other disadvantage of using `float`?

Specifically, I wonder if the processor would be more power-hungry because of those extra CPU cycles.

---

UPDATE: What will my application do meanwhile?

The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using `float` to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger. So the loop in pseudo-code would be:

1. Read all inputs (digitalRead or direct port access);
2. Filter the readings and decide if a button action has been detected;
3. Set some control flags that determine which part of the cycle the lights are in;
4. Check for elapsed time to actually turn blinkers on and off.

So, since I plan to react to button input as realtime as possible, most time would be spent filtering (that is, performing floating point operations), since direct port access and flag-setting are supposed to be nearly instantaneous, right?

# Answer
It depends on what your processor is doing while it has no real work to do:

* If you put it to sleep, then yes, using floats will keep the CPU awake for a longer time and burn more energy.
* If you are instead doing busy-waits (e.g. with `delay()`) it should make no difference, since the CPU is busy 100% of the time anyway.

**Update**: According to your update, it seems your program never sleeps. Then I would expect no substantial difference in power consumption between using floats or ints. As Majenko said, there can theoretically be some small difference depending on the number of transistor transitions involved in each instruction (and, I would add, the capacitive loading of the involved transistors), but I do not expect this to be very significant.

If you are really concerned about the consumption of your Arduino, I would suggest you use it only for prototyping, then move your code to a bare ATmega (or maybe even an ATtiny) chip. Also, add at least one call to `sleep_mode()` inside your main loop. Each such call will put your CPU to sleep until the next timer interrupt, which typically happens every 1024 µs. There is a lot more to say about power savings, see for example this excellent writeup by Nick Gammon.

**Edit**: When trying to minimize power consumption, one of the very first things to do is figure out how much work has to be done, and make sure your program never does more work than required. In your case, this means you have to know how often your main loop should execute, and prevent it from running more often than needed. For example:

```
#include <avr/sleep.h>

const unsigned long loop_period = 5;  // run the loop every 5 ms.

void loop() {

    /* Sleep while waiting for the next time slot. */
    static unsigned long last_time;
    while (millis() - last_time < loop_period)
        sleep_mode();
    last_time += loop_period;

    /* Actual work goes here... */
}

```

If the actual loop work takes significantly less time than the loop period, your CPU will sleep most of the time, leading to significant power savings. Then you can start digging into more advanced power-saving techniques like those mentioned in the article linked above.
> 4 votes

# Answer
> The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger.

Using floats is **way** overkill here. To debounce all you need to do is note when the switch changed state, and ignore further state changes during a certain interval, say 10 ms. It is even quite feasible to sleep during that debounce period. One of the watchdog timer intervals is 16 ms which would be about right for that.

In any case, an application that turns lights on is hardly going to be one where you are worried about how much power floating point operations take. I would be 1000 times more worried about how much power the lights use.
> 2 votes

# Answer
Yes, more power will (theoretically) be consumed. That is, compared to doing nothing.

Float operations will require more mathematical operations to perform compared with integer or fixed point. That will mean more gates are being activated and deactivated etc, compared to doing nothing.

Would that increase in power be noticeable? Probably not. It'll be so tiny as to be negligible. As Edgar Bonet has mentioned, if you are making use of sleep modes then the extra time taken to perform the float operations will impact the ratio of running to sleep time, but if all you are doing is a set of mathematical operations a few times a second and using the `millis()` or `delay()` functions to control the timing then the difference will be so minimal you'll never notice it.

The effect is more noticeable on a PC when you perform very complex operations (like 3D rendering) and the CPU gets hotter and the fan speeds up. In this situation the CPU is entering an *idle* state (like sleep, but less so) when it's not needing to perform any tasks which reduces both power consumption and heat dissipation. When performing heavy tasks it has less time to be idle and so generates more heat. The more complex the operations the more transistors need to switch and so the more heat is dissipated.

Unfortunately the power dissipation per op-code is not documented, but it should be possible to write some assembly code to execute a single instruction in a tight loop (start with NOP) and measure the current, then change that instruction for a different one and compare the current. Using NOP as a baseline you should then be able to calculate the increase in current for each op-code. Of course, the actual data the op-codes are operating on will also have a bearing on the power consumption.

But that would be pretty pointless unless you are budgeting for every single femtowatt of power.
> 1 votes

# Answer
If you are interested in power saving, I think it would be more important to check that the standard Arduino library doesn't turn on HW blocks that you do not need.

From an engineering perspective, though, the filter you are pursuing seems a bit overkill, if you only worry about bounces. Waiting for a reasonable amount of time after the first transition should be sufficient and would keep the code simpler to write, test and debug.

The mechanical switch is already a dampened system with its own intrinsic time constant.
> 0 votes

---
Tags: power, avr, float
---


title: Powering Arduino from a shield

text:
# Question
Title: Powering Arduino from a shield
I'm designing a shield for Arduino which drives two stepper motors. They are small and require 5V but their max combined current is around 1A, way too much for the USB supply. Therefore I will have external 5V power supply connected to my shield.

The entire device will usually operate being connected to a PC through USB, but still I'd like to have a possibility to run it separately.

The question is: how to power Arduino itself?

1. From my external PSU through the pins: Sounds as the simplest solution but I'm bit worried about the onboard regulator of Arduino while reverse powered.
2. Separate power circuits for electronics and motor: My L293D chips allow for separate power and even different voltage for the motors. It could even be an advantage for my shield, as I could use other motors and different power for them in the future. I will, however, lose the possibility of running the device without USB connection.
3. Same as above with additional barrel jack power connection to supply Arduino when USB is disconnected. This, however, could fail with 5V supply, because of the voltage drop of the regulator which handles power coming from barrel jack.

# Answer
> 2 votes
Option 1 is by far the simplest. Just have one 5V power supply for everything. Make sure you have enough capacitance on there to absorb the noise of the motors - maybe separate the digital side from the drive side with an inductor.

You can add a diode connected backwards between the 5V and VIN pins to bypass the regulator when reverse powered. That is, anode to 5V and cathode to VIN.

# Answer
> 0 votes
What I am doing for similar is powering 7.2v to motorshield EXT\_PWR and same to RAW pin of Arduino mini pro, where taking 5v out from vcc and input to motor shield 5v. It works for my car well.

---
Tags: power, shields, hardware
---


title: Arrays and Functions

text:
# Question
Title: Arrays and Functions
How can I return a char array from a function?

```
char c[] = getFloat(val, valid);

char getFloat(float val, bool valid){
      if(valid){
        char stringFloat[16];
        dtostrf(val, 10, 8, stringFloat);
        return stringFloat;
      } else Serial.print("No Float");
    }

```

# Answer
> 1 votes
Allocate it in the heap. Don't forget to free it after.

```
#include <stdlib.h>
#include <string.h>

 ...

char *c = getFloat(val, valid);
use(c);
free(c);

 ...

char *getFloat(float val, bool valid){
  if(valid){
    char stringFloat[16], *ret;
    dtostrf(val, 10, 8, stringFloat);
    ret = strdup(stringFloat);
    return ret;
  } else {
    Serial.print("No Float");
    return NULL;
  }
}

```

# Answer
> 1 votes
An alternative method would be to allocate the string **statically** inside the function, like this:

```
const char * getFloat(float val, bool valid){
      if (valid)
        {
        static char stringFloat[16];
        dtostrf(val, 10, 8, stringFloat);
        return stringFloat;
        }
      else
        return "No Float";
    }

```

Now we can use that string:

```
const char * c = getFloat(24.5678, true);

```

However note that this is only good for one use **at a time**!

This would not work properly, for example:

```
const char * c1 = getFloat(24.5678, true);
const char * c2 = getFloat(42.7654, true);

```

Now c1 and c2 both point to the same piece of memory, so only the last one would be correct. However this restriction may not matter to you. And it saves you having to free memory afterwards, and possibly saves you from heap fragmentation.

---
Tags: arduino-ide, c
---


# Question
Title: Generating a PWM frequency greater than 125 kHz using Arduino Uno
I need to obtain a PWM frequency of at least 125 kHz. I plan to drive a pair of MOSFETs using this PWM as the driver signal. The below code gives a 1 kHz frequency. Can I just change the delay values to obtain a lower time period, and thereby a higher frequency?

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

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);  // Can I change the delay to 1 and 9 for a totaL T=10 µsec and hence f = 100 kHz?
  delayMicroseconds(900);
}

```

---

**Update**

On looking up the answers provided, I stumbled across a few tutorials. I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation). But the code was supposed to provide 250 kHz and 8 MHz.

My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.

Second sketch:

```
// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output (but cro measures only 125 kHz)
   TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
   TCCR2B = _BV(WGM22) | _BV(CS20);
   OCR2A = 63;
   OCR2B = 0;

  // Set up the 8 MHz output
   TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
   TCCR0B = _BV(WGM02) | _BV(CS00);
   OCR0A = 1;
   OCR0B = 0;

  // Make the 250 kHz rolling
  while (1) {
    _delay_us(5);
    if (OCR2B < 63)
      OCR2B += 5;
    else
      OCR2B = 0;
  }
}

```

# Answer
It's a bit beyond the normal Arduino capabilites so you need to delve into setting some of the registers for your ATMEGA chip directly. See the "Using the ATmega PWM registers directly" http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
> 4 votes

# Answer
> My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.

According to my measurements, it is. Using this slightly modified version of your code:

```
// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5 µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output
  TCCR2A = bit(COM2A1) | bit(COM2B1) | bit(WGM21) | bit(WGM20);
  TCCR2B = bit(WGM22) | bit(CS20);
  OCR2A = 63;
  OCR2B = 31;

  // Set up the 8 MHz output
  TCCR0A = bit(COM0A1) | bit(COM0B1) | bit(WGM01) | bit(WGM00);
  TCCR0B = bit(WGM02) | bit(CS00);
  OCR0A = 1;
  OCR0B = 0;
}

```

I get the predicted 8 MHz output on pin 5:

And the 250 kHz output on pin 3:
> 2 votes

# Answer
To your original question: You can reduce the delay, but there's a limit to how small the delay can be.

Two reasons: Firstly, the loop() function does have some overhead, and secondly the code that you write takes time to execute. This is why the hardware PWM timer is valuable - it generates the pulses without much software intervention.

> I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation).

This is really just to add to Nick's answer... (To understand what's going on, you need to refer to the datasheet. Based on your questions, I'm assuming you haven't stared at it long enough.)

### In the first case: 125 kHz.

I am not sure if you're aware, but you're using a special mode of "Fast PWM" which is slightly different from the analogWrite() provided in Arduino.

In this mode, your PWM period is determined by the time it takes your timer counter to match the value in OCR2A register. This means that with a 16 MHz clock, and your output is toggled at a rate of 16 MHz/63 = 250 kHz (roughly).

So far so good, but what does the CRO see? The CRO considers a period to be made up of both high and low signal. It takes TWO 250 kHz cycles to toggle the signal up and down. Hence, the reading shows 125 kHz.

As to why the rolling would make your reading difficult: Think what kind of wave will appear when OCR0B = 0. ;-)

### Case 2: 8 MHz

The same applies in the seccond case, and you should expect a 16 MHz cycle that toggles the signal up and down (which gives a 8 MHz reading on the CRO). As to why you are getting 1.6 MHz - that's an odd case. Can you post your CRO reading?
> 2 votes

# Answer
Yes, you can reduce the delay.

From the documentation:

> This function works very accurately in the range 3 microseconds and up. We cannot assure that `delayMicroseconds` will perform precisely for smaller delay-times.

Note that, there are a few cycles between the delays, so as you get shorter timeperiods, you will get less and less accuracy.

You could hand-code the delay. I would imagine you could get up to 1 MHz, but with little control over the duty cycle (at that frequency).You would need to disable interrupts, and you could do nothing else at all.

If you want still more, you could set a fuse on the ATmega, and get your native clock speed out on of pin 14 CKO (this shows up as digital pin 8 on the Arduino board) - I would expect a 50% duty cycle; you will have NO control over - you can't switch it on or off, or affect the duty cycle. It can be used to run multiple chips off the same clock.
> 0 votes

---
Tags: arduino-uno, pwm
---


# Question
Title: is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together?
I am lakshman a mechanical engineer,i have a question that is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together???

so that i can take the output value from Accelerometer so that to make a call to a preprogrammed number???

Plz help me.

Thank you.

# Answer
> 1 votes
Yes, that is perfectly possible. Typically:

* Accelerometer is either an analog, SPI or I2C interface.
* GSM is usually a UART interface
* The Arduino UNO has all four interfaces (analog, SPI, I2C and UART) available on separate pins.

The rest is just a SMOP.

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


title: Are static variables in a function bad?

text:
# Question
Title: Are static variables in a function bad?
For my code I use a couple of static variables. But when I search the internet, they seem "evil".

For example: I have a function which will be executed every loop (5ms looptime). to increase the speed I added some static variables to it. Is the way I am doing this bad? Are there simple solutions for it?

Code:

```
int ProgFormula() {
  static int StartPosition;
  static int DeltaPosition;
  static int LoopTime = 5;
  static int AccelerationLoops;
  static int TotalLoops;
  static int EndOne;

  static float VelocityLoop;
  static float VelocityFactor;

  int Setpoint;

  if (Iteration == -1) {
    StartPosition = PID.ActualPosition;
    DeltaPosition = abs(SetPosition - StartPosition);
    VelocityLoop = Velocity / (1000 / LoopTime);
    TotalLoops = DeltaPosition / VelocityLoop;
    if (TotalLoops <= (AccelerationLoops * 2)) {
      AccelerationLoops = (TotalLoops / 2);
      VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
    }
    else {
      AccelerationLoops = 70;

      VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
    }
    TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
    EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
  }
  else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
    else {
      Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
  }
  else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
    }
    else {
      Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
    }
  }
  else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
    }
    else {
      Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
    }
  }
  else {
    Setpoint = Setpoint;
  }
  return(Setpoint);
}

```

Is it better to avoid statics? If so why?

Thanks in advance, Koen

# Answer
I made up a test by adding enough to the posted code to get it to compile:

```
float ActualPosition, SetPosition, Velocity;

int Iteration;

int ProgFormula() {

  static int StartPosition;
  static int DeltaPosition;
  static int LoopTime = 5;
  static int AccelerationLoops;
  static int TotalLoops;
  static int EndOne;

  static float VelocityLoop;
  static float VelocityFactor;

  int Setpoint;

  if (Iteration == -1) {
    StartPosition = ActualPosition;
    DeltaPosition = abs(SetPosition - StartPosition);
    VelocityLoop = Velocity / (1000 / LoopTime);
    TotalLoops = DeltaPosition / VelocityLoop;
    if (TotalLoops <= (AccelerationLoops * 2)) {
      AccelerationLoops = (TotalLoops / 2);
      VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
    }
    else {
      AccelerationLoops = 70;

      VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
    }
    TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
    EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
  }
  else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
    else {
      Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
    }
  }
  else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
    if (StartPosition < SetPosition) {
      Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
    }
    else {
      Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
    }
  }
  else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
    if (StartPosition < SetPosition) {
      Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
    }
    else {
      Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
    }
  }
  else {
    Setpoint = Setpoint;
  }
  return(Setpoint);
}

void setup ()
  {
   ProgFormula ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

```

Disassembling this I got the following assembler:

```
000000a8 <_Z11ProgFormulav>:
  a8:   6f 92           push    r6
  aa:   7f 92           push    r7
  ac:   8f 92           push    r8
  ae:   9f 92           push    r9
  b0:   af 92           push    r10
  b2:   bf 92           push    r11
  b4:   cf 92           push    r12
  b6:   df 92           push    r13
  b8:   ef 92           push    r14
  ba:   ff 92           push    r15
  bc:   0f 93           push    r16
  be:   1f 93           push    r17
  c0:   cf 93           push    r28
  c2:   df 93           push    r29
  c4:   00 91 0c 01     lds r16, 0x010C
  c8:   10 91 0d 01     lds r17, 0x010D
  cc:   8f ef           ldi r24, 0xFF   ; 255
  ce:   0f 3f           cpi r16, 0xFF   ; 255
  d0:   18 07           cpc r17, r24
...
 4ec:   cb 01           movw    r24, r22
 4ee:   df 91           pop r29
 4f0:   cf 91           pop r28
 4f2:   1f 91           pop r17
 4f4:   0f 91           pop r16
 4f6:   ff 90           pop r15
 4f8:   ef 90           pop r14
 4fa:   df 90           pop r13
 4fc:   cf 90           pop r12
 4fe:   bf 90           pop r11
 500:   af 90           pop r10
 502:   9f 90           pop r9
 504:   8f 90           pop r8
 506:   7f 90           pop r7
 508:   6f 90           pop r6
 50a:   08 95           ret

0000050c <setup>:

```

So that function (ProgFormula) has taken up:

```
0x50a - 0xa8 = 1122 bytes

```

Now by removing the "static" declarations, like this:

```
   int StartPosition;
   int DeltaPosition;
   int LoopTime = 5;
   int AccelerationLoops;
   int TotalLoops;
   int EndOne;

   float VelocityLoop;
   float VelocityFactor;

```

It now compiles to:

```
000000a8 <_Z11ProgFormulav>:
  a8:   6f 92           push    r6
  aa:   7f 92           push    r7
  ac:   8f 92           push    r8
  ae:   9f 92           push    r9
  b0:   af 92           push    r10
  b2:   bf 92           push    r11
  b4:   cf 92           push    r12
  b6:   df 92           push    r13
  b8:   ef 92           push    r14
  ba:   ff 92           push    r15
  bc:   0f 93           push    r16
  be:   1f 93           push    r17
  c0:   cf 93           push    r28
  c2:   df 93           push    r29
  c4:   c0 91 04 01     lds r28, 0x0104
  c8:   d0 91 05 01     lds r29, 0x0105
  cc:   8f ef           ldi r24, 0xFF   ; 255
  ce:   cf 3f           cpi r28, 0xFF   ; 255
  d0:   d8 07           cpc r29, r24
...
 27e:   cb 01           movw    r24, r22
 280:   df 91           pop r29
 282:   cf 91           pop r28
 284:   1f 91           pop r17
 286:   0f 91           pop r16
 288:   ff 90           pop r15
 28a:   ef 90           pop r14
 28c:   df 90           pop r13
 28e:   cf 90           pop r12
 290:   bf 90           pop r11
 292:   af 90           pop r10
 294:   9f 90           pop r9
 296:   8f 90           pop r8
 298:   7f 90           pop r7
 29a:   6f 90           pop r6
 29c:   08 95           ret

0000029e <setup>:

```

That is now:

```
0x29e - 0xa8 = 502 bytes

```

---

## Conclusion

Adding "static" has made the function over **twice as long**. Presumably it is also slower. After all, those extra instructions have be doing *something*.

> to increase the speed I added some static variables to it.

Your belief that making variables static increases the speed does not seem to be supported.
> 2 votes

# Answer
> to increase the speed I added some static variables to it. Is the way I am doing this bad? ... Is it better to avoid statics? If so why?

I use this technique too ... IMHO it is neither good nor bad. In a logger, for instance, all the wall clock time stamp information has to be looked up (perhaps time(0)), and formatted at least once in any given second. I use function static variables to prevent duplicating that effort for the 10's to 100's (or even more on a really fast machine) of log entries that happen in the **same** second.

I suspect your saying "to increase speed" is what the other answers focus on, and many contributors in SE jump on the 'premature optimization' concept. I think you unintentionally misled them.

Maybe your audience would respond more positively to the term **'memoize'** ... this technique avoids some work (when it can).

And, just to be complete - Wikipedia agrees with you:

> In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

Note 1. I think memoization implies that there is work that need not be duplicated every time through the function (sometimes only initialization) ... thus there often will be an if-clause to skip over the un-necessary work.

Note 2. static is not the only way to hold onto previous values, but is probably somewhat more appropriate for a function when you do not want a class object (to hold the previous values).

Note 3. 'memoize' has impact because it avoids work, and this speeds up the whole system.
> 1 votes

# Answer
Any style recommendation is going to be a bit subjective and conditional, but the biggest problem I see here is that the function can only be running one set of variables at a time. What if you wanted to do two of the task your `ProgFormula` function is a part of simultaneously? You have no way to switch the state of those variables between calls.

You could make a struct to store the state that your function modifies, that way the calling code could swap out the state between calls. Or you could wrap it in a class so the calling code can make as many instances as it needs and not worry about the data each owns.

As a side note, Premature optimization is the root of all evil. The state you are storing is built with a few subtractions and divisions, but the `pow` function your loop sometimes calls may be the part dominating its running time.
> 0 votes

---
Tags: c++, arduino-ide, code-optimization
---


# Question
Title: Controlling Protoneer CNC shield without PC
I'm building an small CNC using `Protoneer CNC shield`, `GRBL` and `Arduino UNO`.
With this I need to connect the board to PC and send G-Code from there.
My question is, is it possible to use the arduino itself to control the CNC shield?
If yes how?
If not is there any other way to send commands other than USB (as Arduino's USB port is not a host)

Thanks

# Answer
An Arduino can talk directly to a shield, independent of a PC.

This will, however, need a way to tell your Arduino to do it's thing. Depending on what you want it to do, this may require nothing ("send this pre-defined g-code as soon as you are turned on"), a memory card of some sort, one or more pushbuttons, or even a small screen. I have seen several 3d printers with memory cards, buttons (usually up/down/select/back), and a small screen that, once set up, can print anything you can load onto a memory card.

There are other forms of communication, too - ethernet, wifi, etc., which you can use, with appropriate shields.

In the end, of course, you still have to design your object - 3d graphics are well beyond the ability of an Arduino, so there will still be some form of computer involved.
> 1 votes

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


# Question
Title: How is stack memory used for fuctions and local variables?
I wanted to save some values to the EEPROM and also wanted to free up SRAM by avoiding some variable declarations, but EEPROM memory is byte wise.

If I want to store an int value, I have to use some expressions repeatedly. I thought I would make some functions for those. But I am concerned that, if I create a function, it would still occupy SRAM memory, better I declare an int variable instead of using EEPROM.

How are the functions and the local variables stored in SRAM? Does it only store the address of the fuction pointer from the flash memory or all the variables and commands are stored on the stack?

# Answer
> 4 votes
Only the function's data is stored on the stack; its code stays in flash. You can't really reduce SRAM use by using EEPROM instead because, as you have seen, EEPROM isn't addressable in the same way. The code to read and store EEPROM also needs to use some SRAM - probably as much SRAM as you were trying to save! EEPROM is also slow to write, and has a limited lifetime (in number of writes to each byte), both of which make it impractical to use for storing the kind of temporary data we usually put on the stack. It is better suited to saving infrequently changed data, like the unique device configuration for mass-produced devices, or capturing infrequent errors for later analysis.

**Edited:** There is no stack for that function *until* the function has been called, so yes, that is when any of the function's data get's put there. What happens after the function returns is that its stack-frame (its reserved area of SRAM) is no longer reserved. It will eventually be re-used by another function call. Here is a diagram of a C stack in memory. When a stack frame is no longer useful, it is simply released and its memory becomes available to be re-used.

# Answer
> 5 votes
Local variables and function parameters are stored on the stack. However, that is not a reason not to use them. Computers are designed to work that way.

Stack memory is only in use while a function is active. As soon as the function returns, the memory is freed. Stack memory is a GOOD Thing.

You don't want to use recursive functions with lots of levels of recursion, or allocate lots of large structures on the stack. Normal use is fine however.

The 6502 stack is only 256 bytes, but the Apple II works just fine.

# Answer
> 5 votes
The AVR (the microcontroller family traditionally used on Arduino boards) is a Harvard Architecture, meaning that executable code and variables are in two separate memories - in this case flash and SRAM. The executable code never leaves flash memory.

When you call a function the return address is usually pushed to the stack - the exception is when the function call happens at the end of the calling function. In this case the return address of the function that called the calling function will be used instead - it is already on the stack.
Whether any other data is put on the stack depends on the register pressure in the calling function and in the called function. Registers are the working area of the CPU, the AVR has 32 1-byte registers. The registers can be accessed directly by CPU instructions, whereas data in SRAM will first have to be stored in registers. Only if arguments or local variable are too big or too many to fit in registers will they be put on the stack. However, structures are always stored on the stack.

You can read the details of how the stack is used by the GCC compiler on the AVR platform here: https://gcc.gnu.org/wiki/avr-gcc#Frame\_Layout
Read the sections "Frame Layout" and "Calling Convention".

# Answer
> 1 votes
Immediately upon a function call entering the function, the first code that is executed is to decrement the stackpointer by an amount equal to the space required for temporary variables internal to the function. The brilliant thing about this is that all functions therefore become re-entrant and recursive, because their variables are built on the calling program's stack. That means if an interrupt halts execution of one program and transfers execution to another, it too can call the same function without them interfering with eachother.

# Answer
> 1 votes
I've been trying quite hard to make an example bit of code to demonstrate what the excellent answers here are saying, without success so far. The reason is that the compiler aggressively optimizes things. So far my tests have not used the stack at all, even with local variables in a function. The reasons are:

---

* The compiler may **in-line** the function call, thus the return address might not be pushed onto the stack at all. Example:

`void foo (byte a)
 {
 digitalWrite (13, a);
 }
 void loop ()
 {
 foo (5);
 }`

The compiler turns that into:

`void loop ()
 {
 digitalWrite (13, 5);
 }`

No function call, no stack used.

---

* The compiler may pass arguments in **registers**, thus saving it having to push them onto the stack. Example:

`digitalWrite (13, 1);`

Compiles into:

`158: 8d e0 ldi r24, 0x0D ; 13
15a: 61 e0 ldi r22, 0x01 ; 1
15c: 0e 94 05 01 call 0x20a ; 0x20a <digitalWrite>`

The arguments are put into registers and thus no stack is used (apart from the return address for calling digitalWrite).

---

* Local variables may well be put into registers, again saving having to use RAM. This not only saves RAM but is faster.

---

* The compiler optimizes away variables you don't use. Example:

`void foo (byte a)
 {
 unsigned long bar [100];
 bar [1] = a;
 digitalWrite (9, bar [1]);
 }
 void loop ()
 {
 foo (3);
 } // end of loop`

Now that's **got** to allocate 400 bytes for "bar" doesn't it? Nope:

`00000100 <_Z3fooh>:
 100: 68 2f mov r22, r24
 102: 89 e0 ldi r24, 0x09 ; 9
 104: 0e 94 cd 00 call 0x19a ; 0x19a <digitalWrite>
 108: 08 95 ret
 0000010a <loop>:
 10a: 83 e0 ldi r24, 0x03 ; 3
 10c: 0e 94 80 00 call 0x100 ; 0x100 <_Z3fooh>
 110: 08 95 ret`

The compiler optimized away the **entire array**! It can tell that we are really just doing a `digitalWrite (9, 3)` and that is what it generates.

---

Moral of the story: Don't try to out-think the compiler.

---
Tags: sram, eeprom, memory-usage
---


# Question
Title: Is there any way to separate this short code into its own function? (webserver, trying to use client.print outside of main loop)
I have an arduino webserver that uses the following code:

```
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println();
client.println(F("<HTML><HEAD>"));
...
if (fan1Toggle == 0)
    client.print(F("Fan1<font color=\"red\">•</font><a href=\"/?fan1on\">On</a><br>"));
else
    client.print(F("Fan1<font color=\"green\">•</font><a href=\"/?fan1off\">Off</a><br>"));

if (fan2Toggle == 0)
    client.print(F("Fan2<font color=\"red\">•</font><a href=\"/?fan2on\">On</a><br>"));
else
    client.print(F("Fan2<font color=\"green\">•</font><a href=\"/?fan2off\">Off</a><br>"));
...

```

The page is pretty long, allowing the user to toggle over a dozen different switches. Some of the code checks to see the state of a certain switch, and then displays a green or red bullet ("&#8226", like •) on the page if the switch is on or off.

Since the code for the colored bullet is repeating, I wanted to make a function for it. Then I would just call (for example) "`displayBullet(fan1Toggle);`", and it would determine if fan1 was on or off, and display the correct color depending on the state.

I tried to create the following function:

```
void displayBullet(int toggle) {
if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("<font color=\"red\">•</font>"));
else    //switch is on, so display green bullet
    client.print(F("<font color=\"green\">•</font>"));
}

```

But then I got an error saying that "'client' is not declared in this scope".

Is there any way to work around that error, so that I can get the displayBullet() function I want? Or is this something that can't be shortened like this, because the "client" function has to be inside the main loop?

Thanks!

# Answer
> 2 votes
You can pass client to the function by reference, like this:

```
void displayBullet(EthernetClient & client, int toggle)
  {
  if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("<font color=\"red\">•</font>"));
  else    //switch is on, so display green bullet
    client.print(F("<font color=\"green\">•</font>"));
  }

```

Now it knows about `client`. Make sure you pass client when you call it:

```
displayBullet(client, 1);

```

---
Tags: web-server
---


# Question
Title: ATtiny85: Power consumption vs clock speed
Short and simple: What is the power consumption for an ATtiny85 running at 1 MHz and 8 MHz using the internal clock? Not using any sleep modes.

I have googled a lot and can't find any info on this. I ask because I want to know if it is worth using 1 MHz to increase battery life.

# Answer
> 51 votes
The datasheet shows that current decreases at lower frequencies. Around **1 mA** at 1 MHz running at 5 V. More like 5 mA at 8 MHz running at 5 V.

You can save quite a bit by using lower voltages as well, as you can see. For really big savings use a sleep mode. Read about Power saving techniques for microprocessors.

---

*(Edited to add)*

To amplify on my remarks, you should be able to get **200 nA** consumption at 3.5 V in sleep mode with no watchdog timer. That will still respond to interrupts, such as closing a switch.

---

If you need to do things periodically you can enable the watchdog, and then get around **5 µA** consumption at 3.5 V.

---

This is so much less current than the 1 mA mentioned above, that it is well worth exploring running in power-down mode, where possible.

---
Tags: power, attiny
---


# Question
Title: Arduino Uno & Simulink - high frequency pulses
I'm trying to control a large stepper motor with high frequency pulses (eventually around 4kHz), but what I get out of the simulink scope is super different from what the Arduino is putting out. I'm using this variable frequency PWM block: www.mathworks.com/matlabcentral/fileexchange/48563-variable-frequency-pwm-block

(yes, I've tried it on pin 5/6, but if I do that there's no difference)

This is the output from the Simulink scope (period of 0.01s):

and the Arduino is putting out pulses with a period of ~4 seconds. This is on pin 6 of the Uno, by the way. Why won't the Arduino output the same frequency as the Simulink program?

# Answer
> 0 votes
It seems clear from what you have described that this is a Simulink bug.

> Why won't the Arduino output the same frequency as the Simulink program?

The Arduino can output quite a lot of frequencies. I have a page about Arduino timers which describes them in some detail.

However since Simulink is generating the code for the Arduino (which we are not being shown) and since it claims to be generating 0.01 s, and the code it is generating does not do this, that is a bug in Simulink.

I suggest you contact their customer support.

Alternatively you could attempt to program the hardware timers yourself. The page I linked could be a good starting point for such an exercise.

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


# Question
Title: Porting SH1106 Oled Driver - 128 x 64 / 128 x 32 Screen is garbled but partially responsive
I'm porting the SH1106 driver to netmf and have found several libraries that more or less accomplish the same thing. A few were much easier to understand and had less abstraction so I followed those.

I've tried the U8glib with my arduino and it works just fine. The ported display driver yields these results:

inverted:

What you're looking at is the screen right after the initialization and attempting to draw a filled circle. You can see the bottom of the circle at the top of the screen. Somehow the origin or page is shifted, but I don't fully understand what's going on. I can send the invert display command and that works as well and turn the display on and off. My initialization code is this:

```
public void init()
{
    resetPin.Write(true);
    Thread.Sleep(1); // VDD (3.3V) goes high at start,
    resetPin.Write(false); // bring reset low
    Thread.Sleep(10); // wait 10ms
    resetPin.Write(true); // bring out of reset

    dcPin.Write(DisplayCommand);

    SendCommandB(0xAE);    /*display off*/

    SendCommandB(0x02);    /*set lower column address*/
    SendCommandB(0x10);    /*set higher column address*/

    SendCommandB(0x41);//0x40);    /*set display start line*/
    SendCommandB(0xB0);    /*set page address*/
    SendCommandB(0x81);    /*contract control*/
    SendCommandB(0x80);//contrast);    /*128*/
    SendCommandB(0xA1);    /*set segment remap*/
    SendCommandB(0xA6);//invertSetting);    /*normal / reverse*/
    SendCommandB(0xA8);    /*multiplex ratio*/
    SendCommandB(0x3F);    /*duty = 1/32*/
    SendCommandB(0xAD);    /*set charge pump enable*/
    SendCommandB(0x8B);     /*external VCC   */
    SendCommandB(0x30);    // | Vpp);    /*0X30---0X33  set VPP   9V liangdu!!!!*/
    SendCommandB(0xC8);    /*Com scan direction*/
    SendCommandB(0xD3);    /*set display offset*/
    SendCommandB(0x00);   /*   0x20  */
    SendCommandB(0xD5);    /*set osc division*/
    SendCommandB(0x80);
    SendCommandB(0xD9);    /*set pre-charge period*/
    SendCommandB(0x1F);    /*0x22*/
    SendCommandB(0xDA);    /*set COM pins*/
    SendCommandB(0x12);
    SendCommandB(0xDB);    /*set vcomh*/
    SendCommandB(0x40);
    SendCommandB(0xAF);    /*display ON*/

    // Switch to 'data' mode
    dcPin.Write(Data);
    this.ClearScreen();
    this.Refresh();

}

```

I have two methods to "refreshing"

```
public virtual void Refresh()
        {
            Spi.Write(displayBuffer);
        }

    /// <summary>
    /// Send buffer to display
    /// </summary>

public void Display()
        {
            //set column address
            dcPin.Write(DisplayCommand);
            SendCommandB(0x21);
            SendCommandB(0);
            SendCommandB((byte)(Width - 1));

            //set page address
            SendCommandB(0x22);
            SendCommandB(0);
            SendCommandB((byte)(_pages - 1));
            dcPin.Write(Data);

            //Spi.Write(displayBuffer);

            for (ushort i = 0; i < displayBuffer.Length; i = (ushort)(i + 16))
            {
                //Spi.Write(displayBuffer);
                SendArray(displayBuffer, i, (ushort)(i + 16));
            }
        }

```

At this point I'm a little lost. My hunch is something to do with paging and or display RAM. I'm looking for some insight here on how to fix this as I know there's a lot of experience here with these displays. Thanks!

# Answer
> 1 votes
While your initialization routine looks fine to me (comparing to the datasheet and as evidenced by the fact the display turns on), what doesn't look right is your drawing routine:

```
//set column address
dcPin.Write(DisplayCommand);
SendCommandB(0x21);
SendCommandB(0);
SendCommandB((byte)(Width - 1));

//set page address
SendCommandB(0x22);
SendCommandB(0);
SendCommandB((byte)(_pages - 1));

```

The commands 0x21 and 0x22 don't correspond to any commands I can see in the datasheet. They look more like commands more commonly seen with ILIxxxx or SSDxxxx screens to create an "addressable window" from 0,0 to Width-1, \_pages-1.

Instead you should be using the same commands you used in the setup routine to set the current col / page coordinate in RAM to write to.

Commands `(0x00 | (col & 0x0F))` and `(0x10 | (col >> 4))` set the column position, and `(0xB0 | (page & 0x0F))` set the page number.

You then write all 128 bytes for the current page before moving on to the next page. This means you will have to do it a page at a time, something like:

```
for (ushort page = 0; page < 4; page++) {

    // Set the current RAM pointer to the start of the currently
    // selected page.
    dcPin.Write(DisplayCommand);
    sendCommandB(0x00); // Set column number 0 (low nibble)
    sendCommandB(0x10); // Set column number 0 (high nibble)
    sendCommandB(0xB0 | (page & 0x0F)); // Set page number

    // Send a single page (128 bytes) of data.
    // Without knowing the rest of your program I don't know the right
    // data sending routines to use, so I made them up. Change it to
    // do it how your program expects.  Maybe with your SendArray
    // function.

    dcPin.Write(DisplayData);
    for (ushort col = 0; col < 128; col++) {
        sendDataB(displayBuffer[page * 128 + col]);
    }
}

```

Note that this method is very similar to how the KS0108 GLCD drivers work. Each byte of the page represents 8 pixels on the screen so the screen, at 32 pixels high, is split into 4 pages, where each page is 8 pixels, or one byte, high.

The effect you are currently seeing is because you are never changing the current page number (0) so you are always writing your data to the first page. This loops around multiple times, so you end up writing all 4 pages to the same strip of the display ending up with the last page being displayed, which is the last 8 lines of your display data. The rest of the display is never being touched and just contains whatever random data was in the RAM at power-on.

---
Tags: lcd
---


# Question
Title: How to pass a filename to a function? What type of variable is the filename?
In the example below, I have two functions that write numbers to two different files on an SD card. I'm using the SdFat library.

Is there any way I can combine the two functions into one, so that I can call (for example): `writeToFile(int t, FileName "filename1.txt");`?

In the example below, to write a value to the "temperature.txt" file, I would like to be able to call: `writeToFile(7, "temperature.txt");` In my sketch I have about a dozen functions that are writing to a dozen different files, so it would be very handy to be able to combine them into one function.

I think the main part I'm stuck on is I have no idea what the filename variable would be, or how to pass the filename to the function.

```
#include <SdFat.h>
SdFat sd;

void setup() {
  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) {
    sd.initErrorHalt();
  }

  setTemperature(7);
  setFanSpeed(4);
}

void setTemperature(int t) {
  SdFile rdfile("temperature.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

void setFanSpeed(int t) {
  SdFile rdfile("fanspeed.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

```

# Answer
> 5 votes
String literals are of type `const char *`. Ordinary `char *`s can be passed to it though; the `const` means that the compiler will make sure that the function doesn't attempt to change the contents.

```
void setFileParameter(const char *filename, int value)
{
   ...
}

```

---
Tags: sd-card
---


# Question
Title: Interrupt variable not getting called while executing another part
```
volatile byte _incomingFlag = 0;

void onIncoming () {
    _incomingFlag = 1;
    Serial.println(F("You got an interrupt"));
    mySerial.println("ATH0");
}

void setup () {
    /* First Start the module */
    Serial.begin(9600);
    Serial.println(F("Initializing module..."));

    powerOn();

    mySerial.begin(9600);

    sendcommand(F("AT"), F("OK"), 1000);
    sendcommand(F("AT+CLIP=1"), F("OK"), 1000);
    sendcommand(F("AT+CMGF=1"), F("OK"), 1000);

    /* We need to attach ringing Interrupt */
    attachInterrupt(M_RING_INTERRUPT, onIncoming, FALLING);

    delay(100);
}

void loop() {
    if (_incomingFlag == 1) {
        manageIncoming();
        Serial.print(F("_incomingFlag: "));
        Serial.println(_incomingFlag);
    } else  {
        Serial.println(_incomingFlag);
        Serial.println(F("not getting value"));
    }
    get_currentLocation();
    send_Location();
}

```

I am trying to check the value of `incomingFlag` from the `loop()` . When I get a call or an SMS the interrupt function is getting executed and `incomingFlag` is set to 1 but I am not getting that value from the `loop()`. Everytime it's getting 0 if I check the value while the `send_Location` function is executing (data uploading part). How can I access the value of `incomingFlag` from the main `loop()`.

# Answer
```
volatile byte _incomingFlag = 0;
 void onIncoming () {
             _incomingFlag = 1;
            Serial.println(F("You got an interrupt"));
            mySerial.println("ATH0");

        }

```

Regardless of what your purpose is there, you **cannot successfully do serial prints inside an ISR**. All bets are off if you do that.

In fact you are doing two prints - is one SoftwareSerial?

If you must have a debugging "flag" turn on an LED. Doing serial printing requires interrupts to be on, and they are off inside an ISR.

---

**Note**: You may get the display once, and therefore you think it works. As soon as the serial buffer fills up (probably 64 bytes) then it will just block indefinitely. Your message "You got an interrupt" is already 22 bytes if you count the trailing carriage-return/linefeed.

---

### More detailed explanation

In your main loop, every time through it, you are printing either:

```
_incomingFlag: 1

```

or

```
0
not getting value

```

Therefore the serial buffer will be **definitely full** (or almost full). It can't empty the buffer if you are cramming this stuff into it every time through loop.

So now you have an incoming call. You set \_incomingFlag to 1, then try to do this:

```
    Serial.println(F("You got an interrupt"));

```

That blocks, because if can't fit all that into the output buffer, and the program then hangs, because the buffer is not emptied inside an ISR.
> 1 votes

---
Tags: arduino-uno, arduino-ide, c, interrupt
---


# Question
Title: Uploading Marlin Firmware To Melzi-ATmega1284p
I'm trying to flash the Marlin Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. Melzi is a variation of Sanguino, and Sanguino is a variation of the Arduino.

The problem is that the version I'm using of Marlin (this one, development branch) only works with Arduino Mega. I saw that the file `pins_RAMPS_13.h` says the following (line 15-17):

```
#if !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__)
   #error Oops!  Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu.
#endif

```

So I tried to make this part to look like this:

```
#if !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(__AVR_Melzi_ATmega1284p16mhz__)
   #error Oops!  Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu.
#endif

```

Does anybody know if there's another repository made for the Melzi board?
Or if I should use another firmware, like Repetier (I tried, fail)?
Thanks for any help.

# Answer
It looks like the Marlin firmware supports two versions of the Melzi board, although it isn't clear if it specifically includes the 2.0 version. The best thing to do is just try it. In the `Configuration.h` file find the section where it says:

```
#ifndef MOTHERBOARD
  #define MOTHERBOARD BOARD_ULTIMAKER
#endif

```

Now replace `BOARD_ULTIMAKER` with `BOARD_MELZI_1284` and try that. If that doesn't work you can try just `BOARD_MELZI`. If neither of those work, you are out of luck, unless you are willing to dig in and do the pin mappings yourself.
> 1 votes

---
Tags: arduino-mega, c++, firmware
---


# Question
Title: How would I go about scrolling a name across a LoL shield with a potentiometer?
I am fairly new to Arduino programming and I have been set with the task of scrolling my name across a LoL shield with a potentiometer. I really don't have any idea how to do this and when I tried to look it up online there is nothing for such a task. I did look at the library references on the LoL shield website but I couldn't make sense of it.

What I did find was a LoL shield sequencer to allow animation on the LoL shield and I figured that might help but I don't know how to use that code to create a scrolling effect with a potentiometer.

# Answer
You know how wide the display is. You know how wide the text is. You know the position of the potentiometer. With those you can determine where in the text (if the text is wider) or display (if the display is wider) you need to start drawing from and where you need to stop drawing. Subtracting the text width from the display width will give you the range for performing linear interpolation with the pot position.
> 4 votes

# Answer
The LoL shield library now supports exactly1 what you want.

If you choose the `LoLShield_FontTest` example it will scroll "HELLO WORLD!" across your shield. Change your text as required.

```
static const char test[]="HELLO WORLD!   ";

```

Example of the word "WORLD":

And in higher contrast to make it more obvious:

---

(1) Except for the potentiometer. In the example code where it automatically scrolls:

```
  for (int8_t x=DISPLAY_COLS, i=0; ; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
       int8_t w = Font::Draw (test[i2], x2, 0);
       x2 += w, i2 = (i2+1) % strlen(test);
       if (x2 <= 0)  // off the display completely?
         x = x2, i = i2;
       }
       delay(500);
    }

```

You would amend it to do an analogRead to set the position of `x`.

---

## Example of using a potentiometer

Based on the Charliplexing example, the code below uses a pot connected to A0 to control the scroll position:

```
#include "Charliplexing.h"
#include "Myfont.h"

char * test = "full ASCII charset: $ % & ! [ ] { }";
int len; // length of this string

void setup()                    // run once, when the sketch starts
{
  LedSign::Init();
  len = strlen (test);
}

void loop()                     // run over and over again
{
  // start empty
  LedSign::Clear();

  int potReading = analogRead (0);  // read A0
  int i = map (potReading, 0, 1023, 0, len * 6);  // starting pixel

  for (int j = 0; j < 14; j += 6)
    Myfont::Draw(j, test[(i + j) / 6]);

  delay(100);   // hold that image for a moment

}

```
> 2 votes

---
Tags: led, shields, potentiometer
---


# Question
Title: Will it work ? MPU6050 Gyro etc. etc. module
Will this code read the values properly ? Using MPU6050.h.

```
#include <MPU6050.h>
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin();
  MPU6050.initialize();
}

void loop() {
  MPU6050.getWaitForExternalSensorEnabled();
  float X = getRotationX();
  float Y = getRotationY();
  float Z = getRotationZ();
  Serial.print("X:");
  Serial.println(X);
  Serial.print("Y:");
  Serial.println(Y);
  Serial.print("Z:");
  Serial.println(Z);
}

```

Please be patient. I know nothing about gyroscope's working. I'm stupid.

# Answer
> 1 votes
Code would normally look like this

```
#include <MPU6050.h>
#include <Wire.h>

MPU6050 mpu;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  mpu.initialize();
}

void loop() {

  //what is this doing for you?
  mpu.getWaitForExternalSensorEnabled();

  if(mpu.getIntDataReadyStatus() == 1) {
        float X = mpu.getRotationX();
        float Y = mpu.getRotationY();
        float Z = mpu.getRotationZ();
        Serial.print("X:");
        Serial.println(X);
        Serial.print("Y:");
        Serial.println(Y);
        Serial.print("Z:");
        Serial.println(Z);
  } else
  {
        Serial.println("MPU not ready");
  }

}

```

---
Tags: arduino-uno, accelerometer, gyroscope, magnetometer
---


# Question
Title: Unable to upload code to the Arduino Nano
I tried to to upload a hex file I generated for the Arduino Nano using avrdude but I keep getting the error:

```
avrdude: stk500_2_ReceiveMessage(): timeout

```

First the arduino board stops doing whatever it is programmed to do, in this case powering a vibration motor . Then this error keeps showing up in delays of around 10 seconds. That error is then followed by

```
avrdude: ser_recv(): read error: The I/O operation has been aborted because of either a thread exit or an application re
quest.

```

which appears to be caused by me pulling out the USB cable after waiting a while.

Thanks

# Answer
> 2 votes
I suggest you disconnect the motor while you are uploading. The power it is using, or the electrical noise it is generating, may intefere with the uploading process.

---
Tags: arduino-nano, avr, avrdude, flash
---