# Question
Title: Does anyone have a data sheet for MC16-0072
I can't seem to relibly find data sheets for MCM electronics parts.. Searched for hours.. Any help?

# Answer
A quick search gave me the impression that MC16-0072 is actually some sort of rebranding. It seems MCM is not the manufacturer, simply a distributor.

Does the hardware itself have any number or serial printed on it?

In any case, when I dug a bit deeper and found this datasheet. However, without an image of your hardware or its serial number, I cannot confirm the datasheet is for your hardware.
> 2 votes

---
Tags: pwm
---


title: ESP8266 Web Server Crash + Arduino IDE

text:
# Question
Title: ESP8266 Web Server Crash + Arduino IDE
I am working on HTTP GET Request. I have created ESP wifi as web server. It creates a access point with IP address : 192.168.4.1 When my android app is connected to web server, it sends values every 50ms on 192.168.4.1/R"VALUE". Value is integer type (0~1023). Example :- 192.168.4.1/R546

However, it is working fine when I send values every 1s, but esp crashes, when IP is hit every 5ms second. I have captured the crash detail on serial monitor. Attaching the file and code as well. Kindly help.

```
#include <ESP8266WiFi.h>
#include <EEPROM.h>
#include <ESP8266WebServer.h>

#define RED_LED     12

WiFiServer server(80); //Initialize the server on Port 80

char myTestUrl[100];

void setup()
{

  EEPROM.begin(512);
  Serial.begin(9600); //Start communication between the ESP8266-12E and the monitor window

  WiFi.mode(WIFI_AP); //Our ESP8266-12E is an AccessPoint
  WiFi.softAP("LED_Downlight1", "12345678"); // Provide the (SSID, password); .
  server.begin(); // Start the HTTP Server

  IPAddress HTTPS_ServerIP = WiFi.softAPIP(); // Obtain the IP of the Server
  Serial.print("Server IP is: "); // Print the IP to the monitor window
  Serial.println(HTTPS_ServerIP);
}

void loop()
{
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  String request = client.readStringUntil('\r');
  //Serial.print(request);

  request.toCharArray(myTestUrl, 100);

  char *Red = strstr(myTestUrl, "/R");
  if (Red)
  {
    int RedValue  = atoi(Red + 2);
    analogWrite(RED_LED, RedValue);
    Serial.print("Red: ");
    Serial.print(" ");
    Serial.print(RedValue);
    Serial.print("\n");

    int SetRedValue = (RedValue / 4);
    EEPROM.write(0, SetRedValue);

    EEPROM.commit();

    Serial.print("Red Memory Write :");
    Serial.print(" ");
    Serial.print(SetRedValue);
    Serial.print("\n \n");

  }
}

```

# Answer
> 1 votes
I've worked with ESP8266 to create a centralized network over which different devices could communicate. In my first iteration I used an ESP8266 as an AP and let other ESP8266s connect to it. This didn't work for longer than 5 minutes. I suspected the ESP8266 couldn't handle many connections for a long period of time and bought an USB WiFi router. Now, I connected all ESP8266 to the WiFi router, including the ESP8266 that I set up as server. And it worked.

In other words: the ESP8266 isn't *strong* enough to be an AP and communicate a lot of data at the same time. Instead, you'd rather like your ESP connect to an existing wireless network with other devices and let those devices connect to the IP of the ESP.

---
Tags: arduino-ide, esp8266, web-server, http
---


title: If - else statement in Arduino

text:
# Question
Title: If - else statement in Arduino
I'm starting to learn how to use Arduino and I tried to make this code, which is just a simple if else statement; what I want to make is when the input is LOW, LED 1 is HIGH and LEDs 2,3 are LOW, and when the input is HIGH, the LEDs 2,3 are HIGH and LED 1 is LOW. I wrote this code but when I put the switch in LOW, instead having just like what I intended, all the outputs are HIGH.

I try changing the output and I checked all the wiring to the LEDs so my mistake is in the code.

Could you guys tell me what's wrong with the code?

```
int switchstate = 0;
void setup() {
  pinMode (13,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(3,INPUT);
}

void loop() {
  switchstate = digitalRead(3);
  if (switchstate == LOW) {
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
  } else {
    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);
    digitalWrite(13,HIGH);
  }
}

```

# Answer
Your code doesn't seem to be the problem. Contrary to what you are saying I think your problem is most definitely in your hardware setup.

Most likely, your digitalRead doesn't register a HIGH input, so it doesn't get 5V. Instead of digitalRead, go for analogRead(A0). So change your circuit and attach it to pin A0.

Use serial.println(switchstate) to print the results to the serial monitor and then decide what your top value (HIGH) and bottom value (LOW) for detection will be. Perhaps include a pull down resistor as well on the A0 pin.
> 1 votes

# Answer
To debug this, as Len has suggested I would recommend putting in some Serial.println("Debug info") commands into your code. This will confirm that you are programming the Arduino as you expect, and that the Arduino is running.

To do this simply include a `Serial.begin(9600)` command in your setup block, and then a `Serial.println("Some text")` wherever you want to check if you are reaching a certain part of the code. You can then read these messages via the serial monitor (which you can get to from Tools-\>Serial Monitor in the Arduino IDE).

For hardware debugging if you have a multi-meter available I would check that you are getting 0V/5V on digital pin 3 when you expect (i.e. when you are / are not pressing the button). Also, to check your LEDs are working, and connected to the output pins you think they are, write a script which just scrolls through them with a short delay (See the `Blink` example under File-\>Examples-\>01.Basics-\>Blink for an example of how to do that).
> 0 votes

---
Tags: ide
---


title: Storing an array of function pointers

text:
# Question
Title: Storing an array of function pointers
I have some Arduino code that looks like:

```
char packet = ser.read();
switch(packet){
    case 'a':
         someobj.somefunc();
         break;
    case 'b':
         otherobj.otherfunc();
         break;
    ...
}

```

I've added a few large libraries that are now causing my sketch to exceed the Arduino Uno's memory. I've done all the usual tricks to reduce memory usage, like using F(), removing unused variables and functions, but I'm still 5% over the memory limit.

I tried commenting out various parts of my code to see what was taking up so much space, and I found removing this switch statement freed up a whopping 20% of memory.

Since it acts like glorified array index, I was wondering if it could in fact be replaced with an array of function pointers, with the packet variable serving as the array index. e.g.

```
uint packet = ser.read();
func_array[packet]();

```

Although the class instance types are arbitrary, the methods all return the same type and take no arguments.

How would you write an array of pointers to arbitrary class instance methods in Arduino C/C++?

# Answer
> 6 votes
This all gets very much trickier than just an array of function pointers.

Your functions are methods in unknown objects. As such you can't have one single type that stores pointers to the functions in different objects.

The simple reason is that C++ changes the function prototype for you. For instance, it changes:

```
class MyClass {
    public:
        int myFunction(int size) { ... }
};

```

into:

```
int myFunction(MyClass *this, int size) { ... }

```

For another class you end up with something like:

```
int myFunction(MyOtherClass *this, int size) { ... }

```

And that is a problem, because although you started with functions that, to you, look the same, they are actually very different. So you can't have one function pointer array with one type that can store either.

One possible method is to use *polymorphism*, where you have one *interface* class that defines the interface your other classes use:

```
class MyBaseClass {
    public:
        virtual int myFunction(int size) = 0;
};

class MyClass : public MyBaseClass {
    public:
        int myFunction(int size) { ... }
};

class MyOtherClass : public MyBaseClass {
    public:
        int myFunction(int size) { ... }
};

```

You can then access `myFunction()` in either object as if it were in the class `MyBaseClass`. Instead of then storing pointers to the functions within the classes you can then store pointers to the classes themselves:

```
MyBaseClass *classes[2];

classes[0] = (MyBaseClass *)&myClassInstance;
classes[1] = (MyBaseClass *)&myOtherClassInstance;

```

And then access the functions:

```
x = classes[i]->myFunction(z);

```

However, this is all probably very much a moot point. The `switch` statement in your code is most likely not what is using all the memory, but all the classes are. By removing the switch you are most likely then not actually doing anything with the classes you have included, and so the linker is then stripping out all that now unreferenced code. A single `switch`, unless it is an absolutely mammoth bit of code, won't take 20% of the Uno's flash.

# Answer
> 5 votes
This is not a direct answer to your question, as I have no such answer, and I believe the answer you are seeking would be of no use to you.

The problem with your question is that your method of testing memory usage is heavily flawed. By removing the `switch` statement, you most likely have allowed the linker to remove lots of methods referenced by it, leading to huge memory savings. Those savings **do not mean** the culprit is the switch statement itself.

The correct way to test static memory usage is to use either `avr-objdump` or `avr-nm`. You have to find where the IDE puts the compiled elf file, then you can issue the command:

```
avr-nm --size-sort -Crtd my_program.elf

```

This will give you a list of all symbols in your program sorted by size. Symbols of type 't', 'w' and 'd' (upper or lower case) eat flash. Symbols of type 'd', 'b' and 'v' eat RAM.

# Answer
> 4 votes
I'm not sure if it will not blow your memory limit as every pointer takes up 16 bits. But in C you usually do it this way:

```
void func1() {
    puts("Hello");
}

void func2() {
    puts("World!");
}

void func3() {
    puts("Array of Size 4");
}

void func4() {
    puts("with Pointer");
}

void func5() {
    puts("to a Function with no arguments");
}

void func6() {
   puts("with return type void");
}

void (* myFunc[6])() = { func1, func2, func3, func4, func5, func6 };

int main(int argc, const char * argv[]) {
    for (int i = 0; i < 6; i++) {
        myFunc[i]();
    }

    return 0;
}

```

For explanation of

```
void (* myFunc[6])()

```

You read form inside to outside looking first to the right then to the left

The variable is named myFunc.

```
myFunc

```

My func is an array of size 6.

```
myFunc[6]

```

Each of those entries is a Pointer.

```
* myFunc[6]

```

Now we need parentheses to make clear, that we have a Pointer to a function with no arguments.

```
(* myFunc[6])()

```

And its return type is void.

```
void (* myFunc[6])()

```

Hope this helps a bit.

---
Tags: arduino-uno, memory-usage, code-optimization, pointer
---


# Question
Title: Why send my Arduino sometime Hex and sometimes the wrong?
Hi i have an Arduino mega 2560 i send data from the Arduino over USB to PC. That works when i test a simple Serial.print("Hello"); but that is not that what i need. I send a timestamp as a longe Value and the databyte as a short Value. When i send the timestamp as BIN like that:

```
      //Initialisisation

const int RX = 0;
const int TX = 1;
const int RX1 = 19;
const int TX1 = 18;
unsigned long currentMillis;

void setup()
{
  pinMode(RX, INPUT);   //Readpin for USB
  pinMode(TX, OUTPUT);  //Writepin for USB
  pinMode(RX1, INPUT);  //Readpin for bus
  pinMode(TX1, OUTPUT); //Writepin for für bus

  Serial.begin(38400);   //open interface for USB
  Serial1.begin(4800);   //open interface for bus

  while (!Serial & !Serial1 &! Serial2)
  {
    ;//wait for serial port connect.
  }
}

void loop()
{
  //Ask if the timestamp over 8 hours, when yes,
  //send the time to the pc and reset currentMillis.
  currentMillis = millis();
  if (currentMillis >= 28800000)  //milli() 8 hours is a 4 byte  timestamp 28.800.000 millisec.
  {
    unsigned long timestamp = currentMillis;
    sendBinaryTime(timestamp);
    currentMillis = 0;
  }//end if

  //if the businterface available, read a byte
  //and send it with the timestamp to the PC.
  //If the businterface not available send an error.
  //short incomingByte = Serial1.read();
  //sendBinaryValue(incomingByte);
  if(Serial1.available()>0) //if the bus (serial1) available?
    {
      short incomingByte = Serial1.read(); //read the next byte from _rx_buffer
      sendBinaryValue(incomingByte);
      sendBinaryTime(currentMillis);   //sendBinary send a long over the bus
    }//end if
}//end Loop()

//Methods for sending long values

void sendBinaryValue(short incomingByte)
  {
    int temp = (incomingByte & 0xFF00)>>8;
    Serial.println(temp, HEX);
    temp = (incomingByte & 0x00FF);
    Serial.println(temp, HEX);
    return;
  }

void sendBinaryTime(unsigned long currentMillis)//send milliseconds after every byte
{
  int temp = (currentMillis & 0xFF000000)>>24; //send 16 bit of the low value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x00FF0000)>>16;      //send 16 bit of the high value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x0000FF00)>>8;
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x000000FF);
  Serial.print(temp, BIN);
  return;
}

```

All is fine i haven´t any error. But i want the timestamp as DEC so i have changed the code to:

```
       void sendBinaryValue(short incomingByte)
 {
   int temp = (incomingByte & 0xFF00)>>8;
   Serial.println(temp, HEX);
   temp = (incomingByte & 0x00FF);
   Serial.println(temp, HEX);
   return;
 }

void sendBinaryTime(unsigned long currentMillis)
{
 int temp = (currentMillis & 0xFF000000)>>24;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x00FF0000)>>16;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x0000FF00)>>8;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x000000FF);
 Serial.print(temp, DEC);
 return;
}

```

Now when i look on the serial monitor i get an error. Here you can see it:

I send an A as ASCII sign that must be Hex 41 and i receive a Hex 5 but why? When i send the timestamp as BIN i get the 41 and haven´t any problem.

I hope someone can help me with friendly wishes sniffi

# Answer
I have found several problems with your program, although they may not be related with your primary problem:

```
while (!Serial & !Serial1 &! Serial2)

```

You mean `while (!Serial || !Serial1 || !Serial2)`, although this is only useful with virtual serial ports, like on the Leonardo. On the mega, all of these ports are real hardware ports.

```
void sendBinaryValue(short incomingByte)

```

The way you name the parameter is misleading: a `short` is not a byte, it's two bytes.

```
int temp = (incomingByte & 0xFF00)>>8;

```

You are bit-shifting a signed number, which is going to do a sign extension. This is probably not what you want.

```
Serial.print(temp, DEC);

```

You are printing several numbers one after the other with no separator. This is going to cause ambiguities: you cannot know whether "345" means "3 45" or "34 5".

Finally, I don't get the purpose of your functions. Why don't you just print the numbers like this?

```
Serial.println(incomingByte, HEX);
Serial.println(currentMillis);

```
> 1 votes

---
Tags: serial, arduino-mega
---


title: Programming Arduino With Python

text:
# Question
Title: Programming Arduino With Python
Im a beginner working with arduino. Im little familliar with java syn and its not hard for me to do the work with ide ;but i know python better....is there any Lib that let you program Arduino with Python?

# Answer
Here is a page on interfacing Arduino with Python.

Interface Arduino with Python
> 0 votes

---
Tags: arduino-ide, library, python
---


# Question
Title: Arduino + ultrasonic rangefinder behaving unexpectedly
I'm using an HC-SR04 ultrasonic rangefinder to control the frequency at which an Arduino pin turns on and off, with the output going via a 1/4" jack plug into my computer's audio interface. (i.e. it's a simple audio oscillator that responds to gestures). This is the code (based on that given here):

```
#define trigPin 10
#define echoPin 12

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(9, OUTPUT);

}

void loop() {

  float duration, distance;
  digitalWrite(trigPin, LOW); // Sends a 2 µs LOW signal to the trigPin
  delayMicroseconds(30);

  digitalWrite(trigPin, HIGH); // Sends a 10 µs HIGH signal to the trigPin
  delayMicroseconds(30);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); //Defines the duration variable

  digitalWrite(9, HIGH); //square wave oscillator
  delay(0.1+duration*0.01);
  digitalWrite(9, LOW);
  delay(0.1+duration*0.01);
}

```

Pin 9 is the output, and sounds roughly as expected, but what's confusing me is that making any kind of gesture other than very slow ones (i.e. if the distance isn't changing very slowly) causes the output to stop completely for a few seconds, then start again, as if something is overloading and then resetting. What am I doing wrong?

# Answer
> 0 votes
I do not really understand the behaviour of your program, but I would like to point out a couple of points that may be problematic:

1. Your comment says “Sends a 10 µs HIGH signal to the trigPin”, just as the program you based yours on, yet you have a 30 µs delay. If this extra delay makes you miss the rising edge on the echo pin, then `pulseIn()` will believe it is seen the *previous* pulse, and it will wait for the next raising edge before starting its measurement. Since that next rising edge will never happen, `pulseIn()` will eventually time out after one second. This is probably the silence you are hearing.
2. Your sound frequency may not be what you expect, because the time needed to run through the loop is not only the two calls to `delay()`, but also the time taken by `pulseIn()` and the various `delayMicroseconds()`. You should have more consistent timings if you use the `tone()` function instead of trying to bit-bang the sound.

# Answer
> 0 votes
Your comments don't match your timing delay values and the datasheet specifies a 10 µs pulse. You're giving it 30 µs but you might get away with it.

I'd look at how often you're triggering the device.

*Figure 1. Don't trigger the device more frequently than 40 times per second.*

---
Tags: audio
---


# Question
Title: Why do I get negative voltages for a PWM waveform?
I used my Arduino Uno's pin 3 to generate a PWM output. The code is:

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

void loop() {
  analogWrite(3, 180);
}

```

I connected the output directly with a oscilloscope. And the output waveform is shown below:

I found it's weird that the minimum voltage is negative! And with the duty cycle increasing, both the maximum voltage and minimum voltage decrease. Why does it behave in such a way?

# Answer
> 13 votes
At first you had the scope AC (Alternating Current) coupled. Then you switched it to DC (Direct Current) coupled.

AC coupling is used to remove the DC component of a signal. It places a large capacitor between the probe and the internal amplifier. This is used, for instance, if you want to see a small signal with a large DC offset. But it can also attenuate and / or alter signals that are low in frequency.

When a PWM signal is AC coupled to an oscilloscope, an interesting phenomenon occurs. As the duty cycle goes from a minimum (almost always off) to a maximum (almost always on) the DC component of the PWM signal changes. Since the DC component is blocked by the AC coupling, the PWM signal appears to move lower on the screen as the duty cycle increases.

DC coupling is where there is no coupling capacitor between the probe and the internal amplifier. Everything comes through. For digital electronics where the signal travels a small distance from 0 to 5 volts or from 0 to 3.3 volts, this is the best way to use the scope.

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


# Question
Title: RC522 RFID reader doesn't read NTAG216 chip
I have an RFID-RC522 module based on the MFRC522 chip. This chip is described in the datasheet as supporting "ISO/IEC 14443 A/MIFARE and NTAG" protocols. I have wired it up to an Arduino Uno using the recommended wiring in the documentation for the MFRC522 library I'm using. I have a sketch that (among other things) polls for presence of a new card:

```
void setup() {
    lcd.setup ();       // initialise LCD display
    SPI.begin();        // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    lcd.println ("Found new card");
    ...
}

```

This sketch correctly detects the presence of the card that was supplied with the module (I believe this is a Mifare Classic card) but does not detect my NTAG216 implant. Does anyone have any idea why it might be failing to find the implanted chip?

# Answer
> 2 votes
I got my RFID kit (RF522) just this week, but I haven't had a chance to play with it yet - nor do I have an NTAG216 implant. But I remember when I was researching them seeing a couple of posts that had to do with "Authentication errors". The problem for you (maybe) is that they were in Python rather than C:

https://github.com/mxgxw/MFRC522-python/issues/24

and Cotix's link

https://github.com/mj3052/MFRC522-Pi

Give them a lookover and see what they can tell you.

The problem with the `PICC_IsNewCardPresent()` function is that it gives a Yes/No answer, not a "Yes, but there's an error". In that case it would also return `false`. But the other code may give you a clue - you'll have to delve into the library...

---
Tags: arduino-uno, rfid
---


# Question
Title: How to send data from arduino to Temp Controller for setting temp?
I send data from arduino by method following. Configure the value : byte message\[ \];

```
#include <SoftwareSerial.h>
#define RX 2
#define TX 3
int incomingByte = 0;

SoftwareSerial mySerial(RX, TX);

void setup()
{
  pinMode(5, OUTPUT);

  Serial.begin(9600);
  mySerial.begin(9600);
}

void loop()
{
  incomingByte = Serial.read();

  if (incomingByte == 's')
  {
    digitalWrite(5, HIGH);
    byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
    mySerial.write(message1, sizeof(message1));
  }
}

```

It works. But I want to input from "Serial monitor" to set the temperature. It does not work when input from "Serial monitor".

# Answer
> 1 votes
You're not writing any data to incomingByte and you're not detecting if data is sent towards the Arduino over serial.

You should change your `void loop()` into this:

```
void loop(){

  //Detects if something is sent over serial.
  if(Serial.available() > 0){

    //reads the byte and puts it into the incomingByte variable
    incomingByte = Serial.read();

    //below is your old code
    if (incomingByte == 's') {
      digitalWrite(5, HIGH);
      byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
      mySerial.write(message1, sizeof(message1));
    }
  }
}

```

When you're using the serial monitor to send data towards the Arduino, also make sure the baudrate you use is the same as the Arduino's. In this case you set your baudrate to 9600 `Serial.begin(9600)`.

---
Tags: softwareserial
---


# Question
Title: Quadrature Encoder:Interrupts: Reset Count
I'm working on a quadrature encoder(with a 500ppr codewheel) with a Channel A, B and an Index pulse output. Using an Arduino Mega I'm counting the number of pulses on Channel A on the rising edge. The code for counting pulses on channel A using an interrupt is straight forward enough with plenty of sources and examples out there to work with.

I've used the the code below to the count the pulses(in an increasing manner). What I'm trying to figure out is how I can reset the overall count using a second interrupt. The second interrupt is invoked when the Index channel pulses high.So in another words when the index channel pulses to indicate a full rotation on the code wheel the main count will reset to zero

```
#define CHA 2
#define CHB 3
#define CHI 19

volatile int count = 0;
volatile byte INTFLAG1 = 0;

void setup()
{
  pinMode(CHA, INPUT);
  pinMode(CHB, INPUT);
  pinMode(CHI,INPUT);

  Serial.begin(9600);
  Serial.println(count);

  attachInterrupt(0, flag, RISING);

 }

void loop()
   {

       if (INTFLAG1)
             {
               Serial.println(count);
               INTFLAG1 = 0; // clear flag
             }

    }

void flag()
    {
       INTFLAG1 = 1;
       if (digitalRead(CHA) && !digitalRead(CHB))
               {
                count++ ;
               }
     }

```

Is it possible to implement the reset of the main pulse count with a second interrupt as described?

From what I've read interrupts work at the same level of priority- so I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested

Any help is appreciated if anyone has done anything like this using interrupts or can point me in the right direction.

# Answer
> Is it possible to implement the reset of the main pulse count with a second interrupt as described?

Yes, and it's quite straightforward. Your index signal goes to pin 19, which is interrupt 4 on the Mega, so you can simply

```
attachInterrupt(4, reset, RISING);

```

in `setup()`, where `reset()` is a function that resets the counter:

```
void reset()
{
    count = 0;
}

```

> I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested

In general you do not want to nest interrupts. If an interrupt is being serviced when a second interrupt fires, the second one will just wait for the first one to finish. This approach works fine as long as you do not have interrupt handlers that take too long to execute.
> 1 votes

---
Tags: arduino-mega, rotary-encoder
---


# Question
Title: How to use same sketch on two different computers in two different directories
I have the same sketch one that I use at my desk and in the lab, but they are in different directories on the different computers. This means that I have to change the paths to the includes which I have to fixup every time I transfer back and fourth. Is there a way to put in a #ifdef that I can set at the start of the build that would include correct path.

# Answer
> 1 votes
Open `preferences.txt` in `C:\Users\YourUserName\AppData\Roaming\Arduino` and change the path of `sketchbook.path=C:\Users\YourUserName\Documents\Arduino` to `sketchbook.path=YourDesiredPath`.

---
Tags: compile, build
---


# Question
Title: ESP 01 - reset settings to default values
I set up communication between Arduino UNO and ESP 01 module. ESP replied to AT commands, but sometimes I got result from ESP uncompleted or with wrong characters, so I tried to set AT+IPR=9600, I didnt receive any output to this command and after reboot I only can see random characters on every baudrate, blue diode on ESP shines all the time. Is there any way how I can reset ESP 01 to default settings? Tried to set RESET pin to GND, but it didnt help.

I use remote power supply 3,3V/1A

Pins connected:

```
Vcc = external power supply 3,3V
GND = GND (interconnected bot Arduino and power supply GND)
Tx = Arduino Rx(changed pin to 11 by SoftwareSerial)
Rx = Arduino Tx(changed pin to 10 by SoftwareSerial)
CH_PD - 3,3V

```

# Answer
Current ESP-01 firmware versions do not have an `AT+IPR` command. If you're trying to change the ESP's baud rate to use it with SoftwareSerial, the command to do so (in recent versions of the firmware) is: `AT+UART=9600,8,1,0,0` for 9600 baud, 1 stop bit, no parity, no flow control.

The full syntax is:
`AT+UART=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>`
, where \<databits\> is the number of data bits per frame, 5,6,7,or 8; \<stopbits\> is 1, 2, or 3 for 1, 1.5, or 2 stopbits (respectively); \<parity\> is 0, 1, or 2 for None, Odd, Even (respectively); and \<flow control\> is 0, 1, 2, or 3 for None, RTS, CTS, RTS and CTS (respectively). Most serial communication and devices that most of us will ever see will be 8 data bits, no parity, and 1 stop bit, abbreviated as "8N1". Flow control is sometimes used, but often it is contained in the data stream itself, such as sending `Ctl-S` and `Ctl-Q` from the keyboard to manually stop and resume incoming data transmission.
> 1 votes

# Answer
While this technically is not an answer, I can highly suggest the ESP 8266 Arduino library. This way you can program in the Arduino IDE and upload to the ESP module. It's so much faster and efficient than AT commands and because you can see the code in the IDE, you have a better overview of what is happening in the code.

https://github.com/esp8266/Arduino
> 0 votes

---
Tags: arduino-uno, esp8266
---


title: NeoPixel Blink/Glitch

text:
# Question
Title: NeoPixel Blink/Glitch
I'm having this weird effect where my NeoPixel will blink/glitch after every cycle of a fading sketch. I'm not certain whether the issue is hardware or in my code. The blinking only occurs during the if statement portion of the code and not during the else statement which blinks red. I have tried multiple sources of power, 5V 2amp, 9V 1 amp, 12V 1amp and a Mac Usb and the problem persists on each power supply.

Any suggestions or ideas would be greatly appreciated.

```
#include <Adafruit_NeoPixel.h>
#include <DistanceGP2Y0A21YK.h>

#define PIN 6
#define PIXEL 16

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL, PIN, NEO_GRBW + NEO_KHZ800);

DistanceGP2Y0A21YK Dist;
int distance;
int R = 0;
int G = 0;
int B = 0;

void setup() {
  strip.begin();
  strip.show();
  strip.setBrightness(127);

  Serial.begin(9600);
  Dist.begin(A0);
}

void loop() {
  distance = Dist.getDistanceCentimeter();
  Serial.print("\nDistance in centimers: ");
  Serial.print(distance);
  delay(2); //make it readable

  if (distance > 10) {

    for (R && G && B; R < 150 && G < 150 && B < 150; R++ && G++ && B++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(2);
    }

    // fade off
    for (R && G && B; R > -1 && G > -1 && B > -1; R-- && G-- && B--) {
      for (int j = 0; j < strip.numPixels(); j++) {
        strip.setPixelColor(j, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(1);
    }

  } else {

    for (int j = 0; j < 256; j++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(255, 0, 0));
        strip.show();
      }
      delay (1);

      //blink off
      for (int j = 64; j > 0; j--) {
        for (int i = 0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color(j, 0, 0));
          strip.show();
        }
        delay (2);
      }
    }
  }
}

```

# Answer
```
for (int j = 0; j < 256; j++) {

  ...

  //blink off
  for (int j = 64; j > 0; j--) {
    ...

```

Notice that you are re-declaring the variable `j`.
> 1 votes

---
Tags: arduino-uno, neopixel
---


title: Programming addressable LED

text:
# Question
Title: Programming addressable LED
I have `TM1812` addressable `LED` strip (1meter long 96 LED). I am looking a way to `program` it and i found this http://www.deskontrol.net/blog/arduino-based-artnet-node-for-led-pixels/ and its mentioned in article that it doens't work with `current version` of Arduino `IDE`.

Is there some other lib/api available to program it or another method?

**UPDATE** As mentioned by @dlu FastLED support wide variety of `LEDs`. I contacted developers of `FastLED` on google + and they have updated there documentation for support of `TM1812` its similar to `TM1809`

# Answer
> 1 votes
There is a very nice library called FastLED, it is also on GitHub as FastLED/FastLED. It is quite flexible and supports a huge range of addressable LEDs. I'm currently using it with 1.6.6.

The code that you linked to was developed with an older version of the Arduino IDE, so you might want to see if you can find an older version and try building with that.

# Answer
> -1 votes
All TM chip Family is supported by Fastled Libs if you use a TM1811 just put TM1809.

It should work, I have tried and it succeeded.

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


title: Arduino yun is not creating it's wifi?

text:
# Question
Title: Arduino yun is not creating it's wifi?
I have installed Arduino software into my PC and copied the bin files into the memory card that has to be fixed into Arduino yun.

After switching on the yun board it is not creating any Arduino yun wifi connection.

Can you help me to overcome this problem? Thanks.

# Answer
> 1 votes
If there is no code that enables the WiFi, it won't be enabled.

Here's the link: https://www.arduino.cc/en/Guide/ArduinoYun#toc14

# Answer
> 1 votes
Perhaps you need to reset wiffi. Press for 3 seconds. After this you must await for a while. Some leds will open and close. This process takes about 2 or 3 minutes. After this. Your white led will be flashing. That is all. Have in mind some points: First time you have to connect your yun by usb. Then you have to openIDE and choose IP PORT which will be showed(192.168....). Then go to your browser and type Ip and configurate your yun for wifi.

---
Tags: wifi, arduino-yun
---


# Question
Title: Which Protocol to use to control WiFi (ESP8266) enabled Led Light
I am developing a Wifi based Led light (Got Inspired from Philips hue, Lifx). I have little knowledge about web server, clients, Web protocols. I will be using ESP8266 as Controller cum WiFi module.

There are two ways to control Led light over WiFi.

1. Locally
2. Remotely

Android/iOS app will be handling all the control part.

Which protocols can I use to control Led light, locally? HTTP or Websockets?

> Note :- The speed is critical, android/iOS app can send around 50-60 values per second.

Also, which protocol should I go with if Led light is controlled Remotely.? So far, MQTT seems reliable. Any suggestion?

Kindly help!

# Answer
UDP :D

Seriously though, ESP8266 is limited in resources, AND you want to send 50-60 updates a second, just UDP will be the most lightweight, and you won't run out of connections (5 I think on ESP), because UDP has no connection state.

This is what was used here to control a RGB strip: https://github.com/cnlohr/esp8266ws2812i2s , it just listens for UDP packets on port 7777, and each packet contains rgb values, one byte for R,G,B, etc.

MQTT is nice, but it doesn't work well for 60hz updates, *I Tried* :D It resulted in un-smooth animation, and frames out of order.
> 1 votes

---
Tags: arduino-ide, esp8266, wifi, rgb-led, http
---


# Question
Title: ATMEGA328 SPI MCP2515 - SPI communication freezes at certain point
I got 2 boards with an ATMEGA328 microcontroller and MCP2515 CAN Controller and I'm trying to get them communicate with each other.

To shortcut the programming a little bit I'm using the Sparkfun CAN BUS Library, but I am not using ther CanbusClass(), I'm directly using the included mcp2515.c/h

The MCP2515 drives a MCP2551. CAN\_H and CAN\_L of both boards are connected with each other, the line has a 120Ohm termination resistor.

Both Microcontrollers share the same code:

```
#include <mcp2515.h>
#include <global.h>
#include <mcp2515_defs.h>
#include <defaults.h>
#define CANSPEED_125    7
const uint8_t PIN_LED_RED = 6;
const uint8_t PIN_LED_GREEN = 7;

void setup()
{
  Serial.begin(9600);
  pinMode(PIN_LED_GREEN, OUTPUT);
  pinMode(PIN_LED_RED, OUTPUT);
  unsigned long now=micros();
  unsigned long init = 0;
  if(mcp2515_init(CANSPEED_125)) {
    init=micros();
    Serial.println("CAN Init ok");
    digitalWrite(PIN_LED_GREEN, HIGH);
    delay(500);
    digitalWrite(PIN_LED_GREEN, LOW);
  } else {
    init = micros();
    Serial.println("Can't init CAN");
    digitalWrite(PIN_LED_RED, HIGH);
    delay(1000);
    digitalWrite(PIN_LED_RED, LOW);
  }
  Serial.print("Time for init: ");
  Serial.println (init-now);
  delay(1000);
  mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
  Serial.println("-------------------------");
  Serial.println("1. CAN - MSG1");
  Serial.println("-------------------------");
}

void loop()
{
  tCAN CANmessage;
  unsigned long tnow;
  unsigned long tsend;
  if (Serial.available() > 0) {
    char incomingByte = Serial.read();
    switch (incomingByte) {
        case '1':
            Serial.println("1. CAN - MSG1");
            tsend=micros();
            CANmessage.id = 0x01;
            CANmessage.header.rtr = 0;
            CANmessage.header.length = 8;
            CANmessage.data[0] = B01010101;
            CANmessage.data[1] = B11001100;
            CANmessage.data[2] = B11100011;
            mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);
            mcp2515_send_message(&CANmessage);
            tnow=micros();
            Serial.print("Message send in time: ");
            Serial.println(tnow-tsend);
            break;
    }
  }
  checkCANBus();
}

void checkCANBus() {
  if (mcp2515_check_message()) {
    tCAN CANmessage;
    PORTD ^= _BV(7);
    Serial.println("Has message");
    if (mcp2515_get_message(&CANmessage))
    {
        Serial.print("Message receivced: ");
        Serial.print(CANmessage.id);
        Serial.print(", ");
        Serial.print(CANmessage.data[0], BIN);
        Serial.print(", ");
        Serial.print(CANmessage.data[1], BIN);
        Serial.print(", ");
        Serial.print(CANmessage.data[2], BIN);
        Serial.print("end ");
        if (CANmessage.id==0x01) {
            Serial.println("MSG ID1 received");
            PORTD ^= _BV(6);
        }
    }
  }
}

```

On Serial port of both boards I get on startup:

> CAN Init ok
> Time for init: 250
> 1. CAN - MSG1

When I send a byte on the Serial port of one baord ('1') I get on the Serial:

> Message send in time: 212

On the receiver side I only get

> Has message

and the green LED on PIN7 is turned on (means mcp2515\_check\_message() returns that the MCP2515 has set the receive interrupt signal).

After that the program crashes in the routine mcp2515\_get\_message().

By toggling the LED's I figured out that the program crashes directly at the beginning of mcp2515\_get\_message() in the line mcp2515\_read\_status(SPI\_RX\_STATUS); So the problem lies in mcp2515\_read\_status().

```
int8_t mcp2515_get_message(tCAN *message)
{
  // read status
  uint8_t status = mcp2515_read_status(SPI_RX_STATUS);
  ...
  ...
}

uint8_t mcp2515_read_status(uint8_t type)
{
    uint8_t data;
    RESET(MCP2515_CS);
    spi_putc(type);
    data = spi_putc(0xff);
    SET(MCP2515_CS);
    return data;
}

uint8_t spi_putc( uint8_t data )
{
  SPDR = data;
  while( !( SPSR & (1<<SPIF) ) )
    ;
  return SPDR;
}

```

By further toggling I figured that the last line correctly executed is spi\_putc(type);

The line data = spi\_putc(0xff); freezes the microcontoller! Which means the while loop in spi\_putc() is endless running as the SPIF bit is not cleared.

Here is what I think I figured out so far:

* The SPI bus connection is clearly working as the initialization is working!
* As the mcp2515\_check\_message() returns on the receiver board that MCP2515\_INT is set so I assume the CAN communication is working (otherwise, why would controller set the MCP2515\_INT).

SPI\_RX\_STATUS is defined as 0xB0(original as in library). The Datasheet of the MCP2515 controller states on page 66

> The RX STATUS instruction (Figure 12-9) is used to quickly determine which filter matched the message and message type (standard, extended, remote). After the command byte is sent, the controller will return 8 bits of data that contain the status data. If more clocks are sent after the eight bits are transmitted, the controller will continue to output the same status bits as long as the CS pin stays low and clocks are provided.

Which it clearly doesn't! But what I cant figure out is why :)

# Answer
> 3 votes
There is one huge pitfall in Master Mode in this ATMega - Select Slave pin (/SS - active low). If it's configured as input, SPI is switched to Slave Mode by low level on this pin. And /SS is on pin PB2 (used as CAN\_INT).

In the library defaults I can see: `#define MCP2515_INT D,2`. PD2 is also INT0 external interrupt pin, so it does make sense to be here and it can be used with attachInterrupt. PB2 is used as an output for selecting slave device, so it's ok too.
Schematics corresponds with that defaults:

In OPs schematics there are slight changes. Interrupt request CAN\_INT is located on /SS pin (PB2, arduino pin 10). CAN\_CS was moved from PB2 to PB1 (arduino pin 10 -\> pin 9)

And in Mega328 datasheet is section: 19.2 SS Pin Functionality:

> **19.3.2 Master Mode**
> When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the /SS pin.
> If /SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI Slave.
> **If /SS is configured as an input, it must be held high to ensure Master SPI operation. If the /SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the /SS pin defined as an input, the SPI system interprets this as another master selecting the SPI as a slave and starting to send data to it.**
> To avoid bus contention, the SPI system takes the following actions:
> 1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs.
> 2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt routine will be executed.
> Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by a slave select, it must be set by the user to re-enable SPI Master mode.

**Conclusion**: If you are using HW SPI in master mode, you can't just use pin 10 (PB2) as general input.

---
Tags: spi
---


# Question
Title: Sparkfun Can-Bus Shield example not working
I recently bought a Sparkfun Can-Bus Shield, and tried the SparkFun\_CAN\_Demo from here but the program only prints "CAN-Bus Demo" and then does nothing, even when I have it connected into my vehicle's OBD-II port and the key is turned to ON (I can't run the engine because I am in my garage). Any help will be appreciated.

# Answer
SPI pins are located on different pins in Arduino Mega. You have to wire it correctly with your shield. Some shields uses ICSP (6-pin header) for better compatibility but this one doesn't.

See Arduino SPI Reference for more details (section: Connections)
> 2 votes

---
Tags: serial, arduino-mega, spi, can-bus
---


title: problem with bitwise OR

text:
# Question
Title: problem with bitwise OR
I have this code, in which I try to "glue" four bytes in order to construct an unsigned int. I shift left the bytes and "add" them using the OR operator.

```
unsigned long number1;
unsigned long number2;
unsigned long number3=0;

byte byte0 = 1;
byte byte1 = 40;
byte byte2 = 107;
byte byte3 = 238;

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

void loop(){
  number1 = byte1 <<8 | byte0 ;  //(=10.241 O.K.)

  //(should be 4.000.000.001, it produces 10.241)
  number2 = byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0;

  //(should be 4.000.000.001, it produces 4.016.777.217)
  number3 = number3 | byte3;
  number3 = number3<<8;
  number3 = number3 | byte2;
  number3 = number3<<8;
  number3 = number3 | byte1;
  number3 = number3<<8;
  number3 = number3 | byte0;

  Serial.print("number1 = ");Serial.println(number1);
  Serial.print("number2 = ");Serial.println(number2);
  Serial.print("number3 = ");Serial.println(number3);
  Serial.println(" ");
}

```

The problem is that the OR operator applies only to `byte1 <<8 | byte0` and ignores the rest. That is number1 and number2 appear to have the same value *(10241)*.

I also tried "adding" them up separately, as shown with number3, but it also produces a wrong result as well.

I tried the same code in python, and it works fine.

```
byte3, byte2, byte1, byte0 = 238, 107, 40, 1
print byte1 <<8 | byte0
print byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0

number3 = 0;
number3 = number3 | byte3;
number3 = number3<<8;
number3 = number3 | byte2;
number3 = number3<<8;
number3 = number3 | byte1;
number3 = number3<<8;
number3 = number3 | byte0;
print number3

```

So, the question is:

Why both number2 and number3 produce a false result?

# Answer
Correction from another answer for number2:

```
number2 = (unsigned long)byte3 <<24 | (unsigned long)byte2 <<16 | byte1 <<8 | byte0; // = 4.000.000.001

```

And in the first round of loop number3 is correct, all others are wrong as number3 holds a result from previous loop.

```
  number3 = byte3; // all magic lays here
  number3 <<= 8;
  number3 |= byte2;
  number3 <<= 8;
  number3 |= byte1;
  number3 <<= 8;
  number3 |= byte0;

```
> 1 votes

---
Tags: programming
---


# Question
Title: Accelerometer Z Value off a significant amount, all other values reasonable
I'm using the MPU9255 Accelerometer to measure acceleration in the X,Y, and Z directions. As per the datasheet, I've applied a scaling to the raw digital values based off of whether I specified +- 2G, +- 4G, +- 8G etc. This scaling works fantastically, but there is consistent noise on the Z axis, far greater than that of gravity's 1G of force. Here is a sample output

```
ACCELEROMETER-X
0.7226562500
ACCELEROMETER-Y
0.1523437500
ACCELEROMETER-Z
7.9707031250

ACCELEROMETER-X
0.7460937500
ACCELEROMETER-Y
0.1875000000
ACCELEROMETER-Z
8.0468750000

```

As you can see, there is about 7G of noise on the Z axis. I calculated the scaling with this code:

```
//Get accelerometer scaling based off of how many G's per of variation the system was tuned to handle
int16_t getAccScalar(int16_t system_scale){
  int16_t acc_scalar = 16384;
  short scalar = 1;
  if(system_scale == ACC_FULL_SCALE_4_G){
    scalar = 2;
  }
  else if(system_scale == ACC_FULL_SCALE_8_G){
    scalar = 4;
  }
  else{
    scalar = 8;
  }
  acc_scalar /= scalar;
  return acc_scalar;
}

```

And then in configuration I use a register writing function with this header:

```
void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)

```

and call it with these values

```
I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_2_G);

```

Anyone know why this is happening? Thanks and have a squanchy day.

# Answer
> 0 votes
Accelerometer static errors are usually not anywhere near that large, so I suspect your scaling code is not behaving correctly. You could verify this by turning the accelerometer on its side and see if the Z axis retains a +7G value, or if the X/Y axis instead becomes too large.

---
Tags: i2c, accelerometer
---


# Question
Title: Is it possible to reprogram an atMega328 chip inside of a pcb?
I have already soldered the atMega chip with instructions onto the perfboard, and I may need to make changes to it. Is it possible to reprogram it without taking it out of the PCB?

# Answer
> 1 votes
I'm assuming you're trying to program using an AVR programmer.

Yes, it's very likely you'll be able to do that. You need to connect the AVR programmer to the correct MCU pins (Sck, Si, So and Rst), including ground and vcc... as you would do with the chip by itself.

If you have any othe SPI device connected to the same pins, make sure it's not enabled - that might be as simple as having the device's CS pulled high.

The way you'll make the connection is up to you, you might need to use some clips, pogo pins or simply solder some wires to the MCU pins.

If you have other things connected to any of the MCU programming pins, you might need to disconnect, but that will vary case by case.

Cheers

---
Tags: arduino-uno, atmega328
---


# Question
Title: Which pins of an Arduino UNO can be used as Tx and Rx pins for connecting to GSM GPRS SIM 900A
I am using Arduino UNO and SIM 900A. Pins 0 and 1 are used as TX and RX. Is it possible to use any other pins?

# Answer
The best choice for serial communications is obviously the HardwareSerial object, `Serial`, on pins 0 & 1. However, it is really dedicated to the USB connection (via the onboard Serial-to-USB adapter). There are ways to connect other devices to these pins, but it is an advanced topic, and should not be attempted by beginners.

The second best choice would be pins 8 & 9, because AltSoftSerial requires those pins. It is very efficient and reliable.

After that, any other pins can be used with one of these two software serial libraries:

NeoSWSerial is less efficient than AltSoftSerial, but *much* more efficient than SoftwareSerial. It only supports baud rates 9600, 19200 and 38400, but it does support simultaneous TX and RX. I maintain this library.

If you must use a different baud rate, SoftwareSerial is the last choice. It blocks interrupts for long periods of time and can interfere with other libraries. It cannot transmit and receive at the same time.
> 6 votes

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


# Question
Title: Using micros() to measure analogRead() time varies based on Serial.print location?
I'm trying to use micros() to measure the time it takes to execute an analogRead() cycle, but am having some issues. Originally, I just printed out the measured time for the analogRead() right after doing the subtraction, but I wanted to change that to printing out all of the time values for the 100 loops at once. When I print the start times, end times, and values both in the if statement (right after calculating them) and at the end, the values printed are the same. I'm not sure if they're accurate because they fluctuate a lot within those 100 tests. For example, some of these measured times consecutively are 216, 97, 153, 34, 89, 145, 27. I put the ADC in freerun mode, so I figured it could be normal for that. However, when I don't print the start times, end times, or values immediately after calculating them and instead try to print them in the else if statement, it gives a stream of values that are all either 407 or 408. If I print "Test" instead of the values right after calculating them, it still gives the (I'm assuming) correct values that vary a lot, not the 407s. If, instead of printing them in the if statement, I print them just in the general loop (currently commented out) and the else if statement, they are still the varying maybe-correct values. I assumed that even if the values aren't being printed, they're still being stored in the array correctly. I don't understand why printing something unrelated right after storing the values would change them. Any ideas?

Thanks

```
    int sensorPin = A1;    // select the input pin for the potentiometer
    int ledPin = 13;      // select the pin for the LED
    int sensorValue[1000];  // variable to store the value coming from the sensor
    int ind = 0;
    int starts[1000];
    int ends[1000];
    int vals[1000];
    int stopprint = 0;
    int i = 0;
    int countto = 100;

    void setup() {
      // declare the ledPin as an OUTPUT:
      Serial.begin(57600);
      analogReadResolution(12);
      pinMode(ledPin, OUTPUT);
      Serial.println("ready to begin");
        analogReadSetup(A1);
      for (i = 0; i < 1000; i++) {
        starts[i] = 0;
        ends[i] = 0;
        vals[i] = 0;
      }
    }

    void loop() {
      // read the value from the sensor:
      if (ind < countto) {
      starts[ind] = micros();
    //  delay(50);
      sensorValue[ind] = analogRead(sensorPin);
      ends[ind] = micros();
      vals[ind] = ends[ind] - starts[ind];
    //  Serial.println("Test");
        Serial.print(ind);
        Serial.print('\t');
        Serial.print(starts[ind]);
        Serial.print('\t');
        Serial.print(ends[ind]);
        Serial.print('\t');
        Serial.print(vals[ind]);
        Serial.print('\t');
        Serial.print('|');
        Serial.print('\t');
      Serial.print('\n');
      Serial.print('\r');
      ind++;
      }
      else if (stopprint == 0) {
        Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
        for (int j = 0; j < countto; j++) {
    //        Serial.println(j);
            Serial.print(starts[j]);
            Serial.print('\t');
            Serial.print(ends[j]);
            Serial.print('\t');
            Serial.print(vals[j]);
            Serial.print('\n');
            Serial.print('\r');
            stopprint = 1;
        }
      }
      else if (stopprint == 1) {
        while(1);
      }
    //  Serial.print(ind-1);
    //  Serial.print('\t');
    //  Serial.print(starts[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(ends[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(vals[ind-1]);
    //  Serial.print('\n');
    //  Serial.print('\r');
   }

```

Also, I'm using the Arduino Zero if it makes a difference.

# Answer
> 1 votes
Not sure if it is related to your problem but... if I were to try such a measurement, I would use local variables, like

```
unsigned int start = micros();
int value = analogRead(sensorPin);
unsigned int end = micros();
sensorValue[ind] = value;
starts[ind] = start;
ends[ind] = end;
vals[ind] = end - start;

```

This way you would be measuring the time it takes to call both `analogRead()` and `micros()`, and very little more. If you do something like

```
sensorValue[ind] = analogRead(sensorPin);

```

then you are also measuring the time taken by the pointer arithmetic and the memory access.

I generally program AVR-based Arduinos. These have a load-store architecture, where saving to a local variable costs essentially nothing, as the variable is typically assigned a CPU register by the compiler. Saving to a global takes more time because of the RAM access.

I have no experience with ARM-based Arduinos, like the Zero, but I believe it's also a load-store architecture, thus the same considerations should probably apply.

**Update**: I tried the following experiment on my Uno:

```
#define PRINT_WHILE_READING

#define READ_COUNT 100

void setup() {
    unsigned int starts[READ_COUNT];
    unsigned int ends[READ_COUNT];
    unsigned int vals[READ_COUNT];

    Serial.begin(57600);
    Serial.println("Ready to begin");

    // Take the readings.
    for (int i = 0; i < READ_COUNT; i++) {
        starts[i] = micros();
        analogRead(A1);
        ends[i] = micros();
        vals[i] = ends[i] - starts[i];
#if defined(PRINT_WHILE_READING)
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
#endif
    }

#if !defined(PRINT_WHILE_READING)
    // Print them now.
    Serial.println("All data taken");
    for (int i = 0; i < READ_COUNT; i++) {
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
    }
#endif
}

void loop() {}

```

If `PRINT_WHILE_READING` is defined as above, I get times that fluctuate between 108 and 116 µs. If I comment out the line `#define PRINT_WHILE_READING`, I get mostly 116 µs and, occasionally, 124 µs. In both cases, the first reading takes longer (208 and 212 µs respectively).

The fact that the first reading takes longer is explained in the datasheet: the ADC does some initializations in that first reading. All measured times are multiples of 4 µs because that is the resolution of `micros()`.

Now, trying to understand the differences between the two cases:

1. With `PRINT_WHILE_READING` the times are shorter on average. This is because the numbers are not stored in RAM, as the compiler figured out the arrays `starts[]`, `ends[]` and `vals[]` are not really needed and optimized them away. When `PRINT_WHILE_READING` is not defined, I can see the “store in RAM” instructions in the generated assembly.
2. With `PRINT_WHILE_READING` the numbers fluctuate more. I guess this is due to the printing through the serial port taking a variable amount of time depending on the numbers being printed, and thus creating timing inconsistencies.

The last point deserves some explanation. The ADC is clocked by a prescaler that divides the frequency of the main clock by 128. This gives a clock period of 8 µs. When an ADC conversion is started, the ADC waits for the next rising edge of its clock, which can take anywhere between 0 and 8 µs, then it does the conversion in 13 cycles of its clock. This means the whole process can take anywhere between 104 and 112 µs depending on the exact time the conversion is started relative to the phase of the prescaler. If the conversions are started at irregular intervals, you expect to see roughly 8 µs of fluctuation in the measured times.

All these observations have been done on an Uno, which is based on an AVR clocked at 16 MHz. I know the Zero is quite different. You will have to look at the datasheet of the ATSAMD21G18 to see whether anything of the above can be extrapolated to the Zero.

# Answer
> 0 votes
If you have access to a digital scope, try bracketing your code with changes to the state of an output pin. print() has a lot of moving parts, some (like buffer size, interrupt implementation) will vary with various Arduinos as others have noted. I am mostly using ARM Cortex M4 on Teensy 3.2. If I want to time something really precisely I will drive an I/O pin (with digitalWrite()) at the beginning and end of what I want to time. This has super fast execution. You could use more than one pin to see two things at once. Then, look at them on an oscilloscope. Trigger on the starting edge of the most important signal. Adjust the time scale to encompass the active pin level time. With a digital scope you can set persistence to infinite and then you can see the variation on the trailing edge of the pulse. You can move the digitalWrite points around in your program until you see what is causing the variation. millis() and micros() are 32-bit values so on an 8-bit AVR that is multiple machine cycles to access. A single digitWrite is usually one machine cycle so it is quick even on a slowly-clocked 8-bit AVR. Once you find the place where most of the variation occurs you at least have a quantified smoking gun to tell you what details to excavate further.

---
Tags: serial, analogread, adc, array
---


# Question
Title: Serving binary file with ESP8266WebServer
I am currently using a Nodemcu ESP8266-12E with the Arduino IDE in order to control my boiler. Everything is working fine, however I haven't figured out yet how to serve binary files, eg. images. (I am hosting them on a server at the moment).

```
ESP8266WebServer server(80);

void setup()
{
  [...]
  server.on("/", handleResponse);
  server.onNotFound(handleResponse);
  server.begin();
}

void handleResponse() {
  if (server.uri() == "/style.css") {
    server.send(200, "text/css", "[css]");
    return;
  }
  if (server.uri() == "/favicon.ico") {
    server.send(404, "text/html", "Not set");
    return;
  }
  [...]
}

unsigned char favicon_ico[] = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};
unsigned int favicon_ico_len = 894;

```

Converting the arary to a string and serving it with `server.send` does not work and `server.stream` expects a file.

# Answer
> 7 votes
It looks like you can use the `send_P` function to send raw PROGMEM data:

void send\_P(int code, PGM\_P content\_type, PGM\_P content, size\_t contentLength);

I.e., (from what I can gather):

```
PGM_P favicon = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};

server.send_P(200, "image/x-icon", favicon, sizeof(favicon));

```

Incidentally, `PGM_P` is just a `typedef` for `const char *`.

---
Tags: esp8266, wifi, web-server
---


# Question
Title: Bit shifting fails with warning: left shift count >= width of type
Given the following minimal working example. I tested this initially with uint16\_t and it worked with no warnings. After that, I adjusted everything to work with uint32\_t.

```
#include <stdint.h> /* needed for the uint16_t type*/
#include <inttypes.h> /* needed for sscanf uint16_t format placeholder  */
#include "printf.h"

#define SET_CMD_ID(ID)    ( (ID) << 27)
#define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
#define SET_CMD_PKT(PKT)  ( (PKT)    )

void setup() {
  Serial.begin(115200);
  printf_begin();
  Serial.print(F("\n\rExample command\n\r: "));

}

void loop() {
  uint32_t payload = 0;

  uint8_t id = 3;   // 00000 - 5
  uint8_t cmd = 2;  // 00    - 2
  uint8_t type = 1; // 000000 - 6
  uint32_t pkt = 0; // 0000000000000000000 - 19

  payload =
        SET_CMD_ID(id)   |
        SET_CMD_CMD(cmd)  |
        SET_CMD_TYPE(type) |
        SET_CMD_PKT(pkt);
  Serial.print(F("Now sending "));
  Serial.println(payload);
  delay(2000);        // Try again soon
}

```

Verifying this sketch outputs:

```
/path/to/ino/Arduino32bitTest.ino: In function 'void loop()':
/path/to/ino/Arduino32bitTest.ino:5:37: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_ID(ID)    ( (ID) << 27)
                                     ^
/path/to/ino/Arduino32bitTest.ino:28:9: note: in expansion of macro 'SET_CMD_ID'
         SET_CMD_ID(id)   |
         ^
/path/to/ino/Arduino32bitTest.ino:6:39: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
                                       ^
/path/to/ino/Arduino32bitTest.ino:29:9: note: in expansion of macro 'SET_CMD_CMD'
         SET_CMD_CMD(cmd)  |
         ^
/path/to/ino/Arduino32bitTest.ino:7:41: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
                                         ^
/path/to/ino/Arduino32bitTest.ino:30:9: note: in expansion of macro 'SET_CMD_TYPE'
         SET_CMD_TYPE(type) |
         ^

Sketch uses 3,174 bytes (9%) of program storage space. Maximum is 32,256 bytes.
Global variables use 216 bytes (10%) of dynamic memory, leaving 1,832 bytes for local variables. Maximum is 2,048 bytes.

```

Executing the sketch on an Arduino Uno results in:

```
Example command

: Now sending 0
Now sending 0
Now sending 0
Now sending 0

```

I googled the message of the warning and found out that it could mean that I'm trying to shift 32bit which is undefined, but I'm not sure on that. So my question is: What am I doing wrong here? How can I get this to work?

# Answer
> 5 votes
It's basically an inability of the compiler to auto-promote the source variables to a size big enough to fit the shifted version.

The default type for all operations, unless otherwise specified, is 16-bit. By shifting more than 16 bits you are overflowing that default type.

To get around it you have to manually tell the compiler that you want to work with 32-bits:

```
#define SET_CMD_ID(ID)      ( ((uint32_t)ID) << 27)
#define SET_CMD_CMD(CMD)    ( ((uint32_t)CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( ((uint32_t)TYPE) << 19)
#define SET_CMD_PKT(PKT)    ( ((uint32_t)PKT)    )

```

# Answer
> 2 votes
Another solution would be to not shift values at all. It seems to be very common in Arduino and other micro-controller projects to use antique ANSI C. But ALL major compiles support "bit fields". The language removes your headache of packing bits into and unpacking bits from a larger type.

It goes like this:

```
struct {
    uint32_t pkt  : 19;
    uint32_t type :  6;
    uint32_t cmd  :  2;
    uint32_t id   :  5;
} payload;

```

As long ans 19 + 6 + 2 + 5 does not exceed 32, the struct will still take up only 32 bits.

Setting values works like this:

```
payload.id = 3;
payload.cmd = 2;
payload.type = 1;
payload.pkt = 0;

```

Reading values works the same way. No need to shift mask or do any other operations by hand. The compiler does everything for you without making any mistakes or without forgetting about to mask when reading...

The only thing you have to remember is that bitfields are packed from least significant bit to the most significant bit. So a struct like this:

```
struct {
    uint8_t r :  2;
    uint8_t g :  3;
    uint8_t b :  2;
    uint8_t a :  1;
} someType;

```

Will result it a byte where the values are layout like this:

```
abbgggrr

```

This also works for signed values. But you have to make sure they fit and be aware of the twos complement representation.

Hopefully more Arduino and micro controller developer will adopt this and take advantage of the compiler.

---
Tags: arduino-uno
---


# Question
Title: Where can i get touch sensitive buttons with RGB-LED like in Ableton Push
I am searching for this component: a touch sensitive button with LEDs like in the Ableton Push or in other Launchpads. Does anyone have an idea about where I can buy something like this? The best would be an RGB LED.

This is what I've found so far. It has no RGB LED though.

Thanks!

# Answer
> 3 votes
Just a little more searching would have led you to this, along with its associated breakout board, bezels, and LEDs.

# Answer
> 3 votes
The specific buttons you link to are custom made. They're not something you can buy off the shelf. In fact they aren't even buttons.

What they are is a translucent moulded silicone rubber sheet with conductive pads behind (typically in a ring shape) with an LED mounted on a PCB behind them. The pad is pressed, which flexes the silicone rubber, to press the conductive portion against exposed tracks on the PCB behind.

There are some similar products around, such as the Sparkfun one Ignacio points to but it is highly unlikely you will find anything off-the-shelf that does exactly what you want. Coupling a pre-moulded translucent rubber keypad membrane (if you can find one somewhere) with your own custom designed PCB to take the RGB LEDs you want (preferably surface mount to keep the size small enough) and provide the exposed tracks is probably the only way you can get exactly what you want.

You may be able to create your own sheet by first making a suitable mould, maybe with wood or modelling clay or something like that, then filling it with silicone (translucent bathroom sealant) and then impress on the back of that a second mould to provide the contact points and indents etc. Then, after a few days when it's all dry, add to the contact points some self-adhesive copper foil, or paint them with conductive paint. Don't quote me on that though, I haven't tried it ;)

---
Tags: button
---


# Question
Title: which is the number of bits in a float variable
Since the maximum value of a float variable is 3.4028235E+38, shouldn't it represented with 128 bits instead of 32? *(2^128=3.4028235E+38)*.

# Answer
> 4 votes
No, it is not integer, so you cannot calculate it that way. It have floating point (not in fixed place).

It is stored as

**1.significand x 2 ^ exponent.**

It takes one bit for sign (+/-), 23 for significand (0 is not stored it is implicit) and 8 more for exponent.

Because of this, you have fixed precision (number of significant digits) for very large numbers and also for numbers which are close to zero.

You have it all explained here: https://en.wikipedia.org/wiki/Single-precision\_floating-point\_format

# Answer
> 3 votes
No, because IEEE 754 floats use a decimative compressed format. 64-bit floats allocate 1 bit to the sign, 11 bits to the exponent, and 52 bits to the mantissa, 32-bit floats allocate 1, 8, and 23, and so on.

You convert from it by adding an offset to the exponent, multiplying the mantissa by the exponent to the power of 2, and then applying the sign.

# Answer
> 3 votes
Just adding a little piece of information to the previous answers: it's worth noting that a float can represent *exactly* all integers from −224 to +224 (i.e. ±16777216).

The next integer, namely 16777217, is not representable as a float. A calculation giving this value would suffer a rounding error.

# Answer
> 1 votes
Another way of looking at it is that a float variable is actually a list of 4294967296 numbers. That's far less than the possible range of numbers and fractions that a float can represent, so only a subset of the numbers are actually represented. Any number you try and use that's not in that list of numbers is rounded to the nearest one.

---
Tags: programming
---


title: Scale Magnometer to Servo

text:
# Question
Title: Scale Magnometer to Servo
I'm trying to determine what is the best way to scale a magnometer to a servo, I am using the BNO055 from Bosch I get a heading say 50 degrees, and I want to be able to input 45 degrees and have the servo motor move accordingly. I am using a 180 degree motor. I would like to be able to input 45 degrees, and then the motor if 50 degrees was 95, would decrease in value step by step until the magnometer read 45; I'm having difficulty creating the logic to do this.

Bosch output is between 0 and 360; so I could end up with servo 0 is 120; and servo 180 is 300. Meaning the values are 300 - 360, 0 - 120 making the full 180, so I am not sure how I could use something like map in arduino to solve this issue.

# Answer
Okay, lets say the output of your BNO055 is called `x` and the value for your servo is `y`. We need to translate `x` to `y` and you are correct to use the `map()` function. But what you are forgetting is that you do not need to map all the values of `x` to all the values of `y`. You can split it up.

In your example the values of the BNO055 relate to the servo as follows:

```
x   | y
0   | 0
120 | 0
300 | 180
360 | 180

```

The servo only rotates from 0 degrees to 180 degrees between the BNO055 sensor values of 120 and 300. So you only need to map those values, while all values below should result in 0 and all values above should result in 180 degrees for the servo.

This translates into the following code:

```
//x is the output of BNO055 sensor
if(x < 120){
  servo.write(0);
}
if(x > 300){
  servo.write(180);
}
if(x > 120 && x < 300){
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

```

Another way of coding this is:

```
if(x < 120){
  servo.write(0);
}
else if(x > 300){
  servo.write(180);
}
else{
  y = map(x, 120, 300, 0, 180);
  servo.write(y);
}

```
> 1 votes

# Answer
You need to remember that you are working with a circle. You have degrees 0 to 360, but only if counting clockwise. If you work anticlockwise you also have degrees 0 to -360.

So your angles of interest are, clockwise from 0, 0-120, and anti-clockwise from 0, 0 to -60

To make things easier on you you need to create a range that is wrapped around so that anything in the "left" half of the circle is counted as anticlockwise from 0 and anything in the "right" half of the circle is counted clockwise from 0.

So values 0-180 are 0-180, but values of 180 to 360 are -128 to 0. Then your entire range spreads from -180 to +180 instead of 0-360 (if that makes sense).

It's simple enough:

```
if (angle > 180) angle = 0 - (360 - angle);

```

So if `angle` is 300 you get:

```
0 - (360 - 300) = 0 - 60 = -60

```

If `angle` is 330 you get:

```
0 - (360 - 330) = 0 - 30 = -30

```

Now you can map the new values using the `map` function @Len has detailed above:

```
servo = map(angle, -60, 120, 0, 180);

```

It is also possible to combine it all into one line should you wish, using the C "inline if" format:

```
servo = map((angle > 180 ? (0 - (360 - angle)) : angle), -60, 120, 0, 180);

```

But that is kind of cryptic :)
> 1 votes

---
Tags: sensors, arduino-nano, servo
---


title: Sampling rate of analog read

text:
# Question
Title: Sampling rate of analog read
I have a simple following analog reading code:

```
void setup()
{
  // initialize serial comms
  Serial.begin(9600);
}

void loop()
{
  // read A0
  int val0 = analogRead(0);
  int val1 = analogRead(1);
  int val2 = analogRead(2);
  // print to serial
  Serial.print(val0);
  Serial.print(" ");
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  // wait
  delay(50);
}

```

How do I determine the sampling rate? I understand for the serial print, it's 3\*4 bytes (for val0,1,2) + 2 bytes for space and 1 bytes for \n, which is 15/9600.

How much time is spent on analogRead?

# Answer
The sample rate will be somewhat inconsistent since the first few samples' print output will go into the print buffer with little delay. Once the buffer fills, subsequent samples' time spent in Serial.print() will vary somewhat depending on how long printing the currently printing character takes to finish, when Serial.print() is called. But the average sample rate will settle to about to *about* 64 Hz (1 sec / (15/960 lines/sec).

The printing time for one line is about 15.6 msec, much longer (140 times) than analogRead() takes, about 0.111 msec, according to this author's measurements.

Update:

> So I could just use 50ms + 15.6 for the sampling rate, ignoring analogRead?

That would get you pretty close to the average sampling interval. If consistency is important to you, you'd need to measure that.

How many samples do you need at a time? Another way is to store the data in an array and print it later. Then the jitter in the sampling interval will be much smaller. You'd be limited to the number of samples you could fit in memory, though. Each 10-bit sample would need 2 bytes of storage.

If the range of your data is less than 256, you could subtract from each sample, the lowest value you expect to see; the difference will fit in 1 byte, doubling your storage capability. Don't forget to add back that lowest value to each one when you print them, though.

It would also be a good idea to test each sample against that lowest number and the lowest + 255, and if any sample is outside those limits, store the low or high limit value instead. Then when you plot your data, you'll see it "clipping" and know that it exceeded your bounds. Otherwise you'll get overflows in the arithmetic and the out-of-bounds numbers will appear to suddenly take on high values when they really are low, and vice versa.
> 1 votes

---
Tags: arduino-uno, analog-sampling
---


# Question
Title: Force compiler to execute instructions sequentially?
Is there a way to force the Arduino compiler to compile individual commands sequentially? Looking at the disassembly, lines of the assembly code for different C/Arduino commands are mixed. I was thinking something like a dmb or dsb command in ARM assembly. I realize it's done the way it is for timing optimization, but I would like to see if changing it fixes some other timing issues I'm having. I'm working on an Arduino Zero. Thanks!

# Answer
> 2 votes
You can use the `optimize` function attribute to change the compiler optimization level for an individual function. That's the closest you'll get.

> **optimize**
>
> The optimize attribute is used to specify that a function is to be compiled with different optimization options than specified on the command line. Arguments can either be numbers or strings. Numbers are assumed to be an optimization level. Strings that begin with O are assumed to be an optimization option, while other options are assumed to be used with a -f prefix. You can also use the `#pragma GCC optimize` pragma to set the optimization options that affect more than one function. See Function Specific Option Pragmas, for details about the `#pragma GCC optimize` pragma.
>
> **This attribute should be used for debugging purposes only. It is not suitable in production code.**

E.g.,:

```
void __attribute__((optimize("O0"))) myFunction() {
    // ...
}

```

---
Tags: compile, timing, assembly, compiler
---


# Question
Title: changing from long to bytes and vice versa
I want to converse data from long to bytes and vice versa. After searching around, I sticked together some code, which seems to work *(the same code works for int and floats as well)*.

The long value `LongVal` changes to a byte array, and the four bytes construct `LongVal2`. Obviously `LongVal = LongVal2`.

```
long LongVal = -4080;
long LongVal2;

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

//byte* my_function(long LongVal){
//  byte *LongVal_byte = (byte *) & LongVal;
//  return & (LongVal_byte[0]);
//}

//long my_function2(byte & LongVal_byte){
//  long LongVal2;
//  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
//  return  LongVal2;
//}

void loop(){

  byte *LongVal_byte = (byte *) & LongVal;
  memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
  Serial.println(LongVal2);
  Serial.println(" ");

//byte LongVal_byte = my_function(long LongVal);
//LongVal2 = my_function2(byte & LongVal_byte);

}

```

But should I try to wrap the two first lines of `loop()` in two individual functions, errors occur. The remarked lines are my attempts to create two functions.

How to wrap them up properly?

**EDIT** This is what appears if I try to use the remarked functions:

```
 In function 'long int my_function2(byte&)':
15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void*' [-fpermissive]
25:0,
1:
117:14: error:   initializing argument 2 of 'void* memcpy(void*, const void*, size_t)' [-fpermissive]

 In function 'void loop()':
26:33: error: expected primary-expression before 'long'
27:30: error: expected primary-expression before '&' token

```

# Answer
> 1 votes
So many problems here:

1) in function call there shouldn't be types, only arguments. `byte LongVal_byte = my_function(LongVal);`

2) & before variable means "get variable address". However in function prototype `long my_function2(byte & LongVal_byte)` it means reference to passed variable (and it must be byte), not a pointer.

3) pointer to local variable is returned from my\_function. It might be working until pointed memory gets rewrited by something else (another function call or so)

And whole code might look like that:

```
long LongVal = -4080;
long LongVal2;

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

byte * my_function(long & LongVal) {
  return (byte*)&LongVal;
}

long my_function2(byte * LongVal_byte) {
  return *((long *)LongVal_byte);
}

void loop(){

  byte * LongVal_byte = my_function(LongVal);
  LongVal2 = my_function2(LongVal_byte);

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

```

But it is basically exactly the same as before without functions (just no need for memcpy)

# Answer
> 1 votes
> 15:51: error: invalid conversion from 'byte {aka unsigned char}' to 'const void\*' \[-fpermissive\]

```
memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));

```

LongVal\_byte is a single byte. It's not a pointer, and `memcpy` expects a pointer.

> 26:33: error: expected primary-expression before 'long'

```
byte LongVal_byte = my_function(long LongVal);

```

You do not specify the variable type when passing a variable to a function. The variable already knows what it is, and the function already knows what it wants.

> 27:30: error: expected primary-expression before '&' token

```
LongVal2 = my_function2(byte & LongVal_byte);

```

Same there.

You are showing a fundamental lack of understanding of some concepts of C. Other errors you are making:

```
long LongVal2;
...
long my_function2(byte & LongVal_byte){
    long LongVal2;

```

You should never ever re-define a global variable inside a function. It's not actually syntactically incorrect, but from a reading perspective it becomes almost impossible to keep track of *which* `LongVal2` variable is being used at any one time.

```
long my_function2(byte & LongVal_byte){

```

You are passing a reference to a *single* byte, not an array of bytes. For that you need a pointer.

You should re-write your functions to be like this:

```
byte* my_function(long LongVal) {
    return (byte *)&LongVal;
}

```

(although that is completely pointless, you just need to cast the value, you don't need a function to do it:

```
byte *byteval = (byte *)&LongVal;

```

)

```
long my_function2(byte *LongVal_byte){
    long LongVal2;
    memcpy(&LongVal2, LongVal_byte, sizeof(LongVal2));
    return LongVal2;
}

```

That is a long winded, but "safe" way of doing it. It is needed only on CPUs where alignment matters. On an 8-bit CPU the alignment is 8-bit, and so a 32-bit word can be at any address. On a 32-bit system a 32-bit word will be at a 4-byte alignment, so that method is needed. On an 8-bit though you can just cast the array into a long:

```
long *LongValue = (long *)&LongVal_byte;

```

A better solution to the whole thing, though, is to use a union:

```
typedef union {
    byte byteval[4];
    long longval;
} LongBytes;

LongBytes myVal;

```

You can then access:

```
myVal.longval = 4893723284;

```

And also:

```
myVal.byteval[i];

```

where `i` is 0-3.

---
Tags: programming
---


# Question
Title: What's on an Arduino board? Can i build one of these boards myself?
My question is: What is on an Arduino board besides the microcontroller?

# Answer
> 2 votes
When I first built my first Arduino clone, I fount very useful the Fritzing examples *(boards and schematics)*. http://fritzing.org/home/

Mind that in order to upload sketches, an FTDI module is very handy *(unless you use ISP via another Arduino board)*.

In any case, I should recommend you to build an Arduino clone on a breadboard, before trying soldering.

Good luck.

Additionally, you may use this picture *(this is how I create an Arduino on breadboard)*:

External power *(battery)* is connected to the screw pins *(bottom left of the breadboard)*.

# Answer
> 0 votes
This list is probably not exhaustive but comes reasonably close:

* A power supply (voltage regulator and filter capacitor);
* A USB connector for powering from a USB port and passing data to/from your PC;
* A second processor (Atmega 16U2) for handling USB \<-\> serial data conversion;
* A barrel-jack for powering it from a 7 - 12v;
* A MOSFET for selecting whichever power source is being used;
* An LED connected to the chip's digital pin 13;
* A pushbutton for manual reset and a capacitor for auto-reset;
* A 16 MHz crystal and load capacitors;
* Several lengths of female headers for connecting plug-wires or shields to the Arduino.

And yes, it's relatively easy to build one - instructive, too! There are how-to project details all over the Internet. I've hand-built any number of them, just soldering up whatever parts I wanted.

Here is an Arduino home brew project, CSEDuino, that was easy and fun to build, with good detailed directions. It is an Arduino clone that does everything the Uno does, except that it isn't physically compatible with Arduino shields.

All of my gadgets are on home-brewDuinos. I usually skip the USB connector and 16U2 processor, and keep one or two FTDI USB to serial cables on my bench to power or program whatever board I'm currently working on. I usually skip the auto-reset capacitor too, and manually reset the board to upload it.

Have fun building!

In service, I just power them from a USB wall charger. Any of them that need to communicate get an radio of some kind, usually Bluetooth or Wifi. Some of them just collect data to non-volatile memory for me read out later.

---
Tags: programming, pins
---


# Question
Title: Can anyone help me spot where my buffer overflow might be occuring?
I'm using dtostrf() to transcribe a float into a string for my touchscreen. I'd leave it as a float, but my screen orientation library function only works with a string.

So I have a char array, then a float value. then dtostrf().

```
char buffer[6]
float X; //changes each loop with incoming sensor data from pixy camera
float thingposition = X * .0064  //float calculations are performed.

void loop(){
Camera.Get_X();   //retrieves X from the camera. waits until X has been recieved via UART serial
dtostrf(buffer, 5, 2, thingposition) // writes float to string with a controled decimal place and all that - dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
Tft.drawString(buffer, 70, 215, 5, WHITE);   //print output to screen
}

```

Note that this is a simplified version. In my code I also have methods for overwriting my last string value on the LCD when the new one has changed. I also have several "if" conditionals that control whether I write the buffer value to the screen or instead send an error message. Those things do not seem to be causing me problems though, except to say that my buffer overflows only occur when I cause the sensors to flip the conditionals at just the right interval.

For example, when I place my hand in front of the camera, that triggers the error message. Take my hand away, and then the number "thingposition" is printed to the screen. But if I time my hand just right, the buffer overflows and numbers loop across the screen. Usually this freezes the whole sketch. The best I can figure is that since dtostrf() does not check bounds, and since the calculated float values can be longer than the buffer has room for, that sometimes dtostrf() tries to write too many digits to the buffer. Something timing-related seems to trigger the problem, but what I need is some way to prevent the overflow in the first place.

I've tried rounding "thingposition" to a certain number of sigfigs, but I can't seem to truncate it at the desired decimal point. That shouldn't matter though, since dtostrf has controls for the minimum total length including the decimal point, as well the number of digits after the decimal. I also tried making sure that the last byte in my char array is null by adding this right after dtostrf():

```
stringval[5] = NULL;   //make sure buffer is null-terminated to prevent buffer overflow

```

I've tried doubles, different ways of rounding, and anything I could find, but the problem has persisted for several weeks and a few steady days worth of searching for a solution. I'll be glad to provide further information if anyone has any ideas on what to try. Thanks everyone.

# Answer
> 1 votes
The problem with using "simplified code" is that your 'simplification' may not have captured your problem. But I will take your code as given and assume that it's correct (which I'm afraid it isn't).

```
var
    char buffer[6]  // Won't compile - no semicolon (';')
    float X;        // Uninitialised value - could be 1000000000000
    float thingposition = X * .0064 // No ';', and .0064 of 10000000000 is huge!

void loop(){
    Camera.Get_X(); // Should this be "X = Camera.Get_X();" ?
    dtostrf(buffer, 5, 2, thingposition)  // No ';'. You NEED to recalculate thingposition!

```

If the above code is a good representation of what you've got, you seem to be assuming that you define the formula once (in the `thingposition` line), and it automatically applies that formula, like Excel, when you change its input, `X`. Sorry, programs don't work that way.

Once you calculate `thingposition`, it becomes independent of where it came from. If you change other variables, `thingposition` kees its value until you explicitly change it.

How do you fix it? You recalculate `thingposition` every time:

```
var
    char buffer[6];      // Hopefully big enough - see below
    float X;             // Used by Camera.Get_X()
    float thingposition;

void loop(){
    X = Camera.Get_X();        // Get X from Camera
    thingposition = X * .0064; // Calculate thingposition
    dtostrf(buffer, 5, 2, thingposition);

```

Note that `dtostrf()` will try to obey your size parameters, **BUT**. If the float is larger than your maximum size, it WILL print out the full number anyway. That is, if `thingposition` is `1000`, it will produce 5 characters all right: `"1000."`. But if it's `1000000`, it will produce `"1000000"` which is seven characters. You need to ensure that `buffer` is big enough to handle larger numbers than you expect.

Do the maths. If `X` is guaranteed to be between `0` and `255`, then multiplying it by `0.0064` will result in a maximum value of `1.632`, so the above `dtostrf()` woud produce `" 1.63"`. No problem!

---
Tags: float
---


# Question
Title: Send values to a PHP page using Arduino ESP8266
I still a noob, and I'm learning Arduino. I built a PHP page to send values using GET parameters.

I would like to send a specific value from Arduino to that PHP page. I bought an ESP8266, and I would like to see it working.

I found this code and I made some changes there, but the the code is not working. I don't receive any value on my database. Can you guys help me?

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);
String cmd;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Started");
  // set the data rate for the SoftwareSerial port
  esp8266.begin(115200);
  esp8266.write("AT\r\n");
}

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

void teste(){
  // Connect to the server
  esp8266.write("AT+CIPSTART=\"TCP\",\"http://bubu.esy.es\",80\r\n");
  //make this command: AT+CPISTART="TCP","192.168.88.35",80
  //wait a little while for 'Linked'
  delay(300);

  //This is our HTTP GET Request change to the page and server you want to load.
  cmd = "GET /teste.php?test=5 HTTP/1.0\r\n";
  cmd += "Host: http://bubu.esy.es\r\n\r\n";
  //The ESP8266 needs to know the size of the GET request
  esp8266.write("AT+CIPSEND=");
  esp8266.write(cmd.length());
  esp8266.write("\r\n");
  esp8266.write("GET /teste.php?test=5 HTTP/1.0\r\nHost: http://bubu.esy.es\r\n\r\n");
  esp8266.write("AT+CIPCLOSE\r\n");
}

```

# Answer
`Host: http://bubu.esy.es` needs to be `Host: bubu.esy.es`.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: ATtiny44 millis() not working with 16 MHz external clock
I'm using ATtiny44 with Arduino IDE according to this tutorial: http://highlowtech.org/?p=1695

I have a problem with `millis()`. When I use an internal 1 MHz clock it works correctly but when I use external 16 MHz clock it takes `millis()` much more time than one second to be divisible by 1000.

I tested it with LCD and Hello World sketch, modified to correspond ATtiny's pins. Do `millis()` actually work with Tiny's?

Why does it work properly with 1MHz and not with 16 MHz which is the same as used in Arduino platform.

# Answer
Let me guess: "*much* more time" is about, ohhh, 16 times?

When `millis()` was written, it had to assume what the input clock was. There is no way to detect the speed of the input clock: to do so would require another clock! So the writers of the function defined a starting constant, set it to `1000000`, and required anyone that changed the clock would have to change that constant.

Find the constant, and set it to `16000000`. Voilà!

Here's an article on the source code of the function:

https://ucexperiment.wordpress.com/2012/03/16/examination-of-the-arduino-millis-function/
> 1 votes

---
Tags: attiny, millis, oscillator-clock
---


# Question
Title: motor does not move without Serial.println
having strange behavior with motor shield and steppers. when i'm trying to make `onestep`, motor just makes some high-frequent noise, but when i add `Serial.println` for debugging, it moves as intended.

what is going on here?

here is an example:

```
#include AFMotor.h //dunno how to put angle brackets here

AF_Stepper lrM(48, 1);

void rightStep() {
  lrM.onestep(BACKWARD, INTERLEAVE);
}
void leftStep() {
  lrM.onestep(FORWARD, INTERLEAVE);
}

void setup() {
  Serial.begin(9600);
  Serial.println("ready");
}

void loop() {
  rightStep();
//Serial.println("right");
}

```

# Answer
My guess is `Serial.println` adds additional delay so stepper motor can react. Without it changes are way too fast (= high frequency noise) to do whole step.

Try to add `delay(1);` or more into the main loop.
> 1 votes

# Answer
When you have a Serial print statement running really quickly the output buffer will fill up and the `print` command will have to wait for there to be room; That causes the command to take a substantial amount of time to complete.

When the statement is missing, you loop probably runs a few hundred times faster than without it (depending on how long `onestep` takes), probably fast enough that the physical motor can not keep up.

Try adding a delay of a few milliseconds or some kind of rate limiting to the program and then see how much of a difference `serial.println` makes.
> 0 votes

---
Tags: arduino-motor-shield, stepper
---


title: Arduino Due SRAM

text:
# Question
Title: Arduino Due SRAM
I'm trying to create an array in Arduino Due and when the array exceeds the size of 32768 integer elements the compiler (Atmel Studio) complains.

I read that Arduino Due SRAM size is 96K in 2 banks. 64Kb and 32Kb.

Anyone knows any details?

# Answer
> 2 votes
Size of int in arduino due is 4Bytes. If you're trying to create array of 32768 integers, it means you need **128kB** of free space.

# Answer
> 1 votes
I've read in several places that e.g. PROGMEM const int foo\[\] = { 1, 2, 3, ... } would work, but was unable to do it in my environment ( debian, arduino-mk package ). I had a number of arrays I needed to commit to flash to conserve sram. This worked fine for all variables, but not for arrays. Try that... What say the wizards?

Note to moderators and others: I *know* I am not answering the question definitively, but it is relevant to OP's question.

---
Tags: arduino-due, sram
---


# Question
Title: Change max and min read value of potentiometer
I'd like to know if there is a function or some way to define min and max value to potentiometer, for example: I'm using a mechanical part that only tour the potentiometer a little bit, what means the potentiometer doesn't start in the beginning and doesn't finish in the end. So, how can I make this space the potentiometer tour means 0 to 255 the start to end, respectively?

# Answer
> 1 votes
You cannot declare that the `min` and `max` values of a potentiometer are `x` and `y`. What you can do is `map()` the values of the potentiometer to your own desired scale.

To do this, you'll have to get the following values:

* Minimum value of the potentiometer, `pMin`
* Maximum value of the potentiometer, `pMax`

But these values aren't what you want. For example, what you want is `pmin` to be `0` and `pMax` to be `100`. So, you'll have to scale `pMin` and `pMax` to those values.

For this, you use the `map()` function. What `map()` does is changing the value in a given scale, to that of another scale. Let's get some example code:

```
int pMin = 14;  //the lowest value that comes out of the potentiometer
int pMax = 948; //the highest value that comes out of the potentiometer.

int x = 0;  //we will use this value to store the readings of the potentiometer

void setup(){
  Serial.begin(9600); //Serial monitor can be used to check the values
}

void loop(){

  x = analogRead(A0); //connect the potentiometer to the A0 pin of the Arduino

  Serial.print(x);  //prints the original reading

  x = map(x, pMin, pMax, 0, 100) //take the value of x, compared it to the scale of the potentiometer pMin to pMax, and translate that value to the scale of 0 to 100

  Serial.print("\t"); //a tab to make the reading more easy
  Serial.println(x);  //post mapped value, println is a linebreak as well
  delay(100); //so we don't post to much in the serial and you can read data better.
}

```

With this example you can clearly see how your potentiometer behaves and how you can use the 'weird' values from its readings in a useful way for your projects.

# Answer
> 0 votes
Either use a reference voltage closer to the maximum voltage the potentiometer is capable of, or use `map()` to map the existing limited range to a larger range. Note that using `map()` will not improve precision.

# Answer
> 0 votes
If the values from the pot are 0 - 1023 you can divide the number by 4 which would give you a closer range to what you need. The map() function can be used instead.

---
Tags: arduino-uno, analogread, potentiometer
---


title: 12 V 6 A power supply for Arduino

text:
# Question
Title: 12 V 6 A power supply for Arduino
I have 3 motors which work at 12 V 3 A, I have attached a 12 V 6 A power supply and seems to be working fine. However I was wondering if this can also power the Arduino as well.

# Answer
If you have 3 motors that use 3Amps combined then you have 3Amps spare and that's more than enough for an Arduino.

I don't understand this part very well but depending on the type of motors you might get noise on the power lines and this might affect you Arduino. In which case you will need to add in something to smooth the power, which means adding in a capacitor or two and their value depends on the frequency of the noise. (http://www.valvewizard.co.uk/smoothing.html)

Personally I'd give it a try and see, but there again it wouldn't be the first Arduino I'd fried :)
> -1 votes

---
Tags: arduino-mega, power
---