# Question
Title: Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible)
I bought this SAMD21 development board which shows up as an "Arduino/Genuino Zero (Native USB Port)" when plugged in. And I've successfully got a blink sketch running on it all good so far:

The reason I picked up this board was to experiment with the built-in capacitive touch sensor on the SAMD21. In the datasheet for this chip it claims to support a *'Peripheral Touch Controller with 256-Channel capacitive touch and proximity sensing'*.

Does anyone know what this exactly means and how I would access this functionality to detect touches in my Arduino code? Obviously there are not 256 IO pins so how would this work? Is there some kind of internal multiplexer?

The **256 channel capacitive touch controller** is also mentioned in a Sparkfun video about their SAMD21 board, so it must be possible to access this functionality.

Can someone direct me towards an Arduino library or method and more information on the wiring and pin connections for this. Thanks.

# Answer
> 6 votes
You have three options for the silicon-based PTC (peripheral touch controlller).

1. LibrePTC \- My own library that targets the SAMD11 but should work with some modifications for other SAMD architectures. The README file has lot of information on how the PTC works and how to specify designs for it.
2. Adafruit FreeTouch \- Works only with the SAMD21. Given the high quality of the register documentation, I suspect they may have had inside help from Atmel but I haven't been able to reach Ladyada, their primary contributor, to learn more.
3. QTouch, which is Atmel's library available in closed source only but is extremely feature-rich. Arduino team decided not to allow closed source stuff in their IDE so its been banned from official distributions. However, it is possible to hack it into the Arduino IDE and I've used it successfully that way. However this requires esoteric modification to boards.txt that are beyond the scope of this answer.

The PTC hardware peripheral on the SAMD chips works on self-capacitance using "Y" lines specified in the data sheet. See the README on LibrePTC for details. Some chip variants have more pins broken out. For instance, the SAMD21G has fewer available Y pins than the SAMD21J, although the J series is not as readily available in breakout boards as of the summer of 2017 and it has limited Arduino IDE support. I personally prefer the SAMD11 because it is cheaper ($1.00) and has way more available Y lines in the QFN package.

As of August 2017, I intend to attempt a merge between the Adafruit and LibrePTC libraries but no guarantees when this will happen. I don't have access to insider documentation so my library was 100% reverse engineered through trial and error.

---
Tags: sensors, arduino-ide, arduino-zero, samd21g
---


title: ATSAMD21 sleep + watchdog?

text:
# Question
Title: ATSAMD21 sleep + watchdog?
Has anyone got sleep/standby + watchdog to work together on their Arduino Zero or Sparkfun SAMD mini?

I am able to get the WDT to reset the device, and am able to put it to sleep - but can't get the WDT to bring it out of sleep. Every time I try, it pops right back out of sleep mode again as if `SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk` was never even called

# Answer
use this:

```
attachInterrupt(wakeUpPin, wakeupFunction, HIGH);
    USBDevice.detach();
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
    __DSB();
    __WFI();

void wakeupFunction(){
  NVIC_SystemReset();
}

```
> 1 votes

---
Tags: timers, sleep
---


# Question
Title: Solution to interrupt Arduino every n seconds
I'm a very beginner with electronics and of course with Arduino. Actually I've been in the software field (.NET) for the past 12 years. I am trying to develop a simple system to run for longer using Arduino Nano. Longer means roughly it could be for years continuously, expecting normal wear and tear.

So what I understood is Arduino loop always executes based on any values from sensors while in the loop. And also Arduino has some interrupt mechanism too.

But since the looping system feels pretty awkward for some situations, I tried to stop the loop using `exit(0);` inside the loop. So loop will stop after the first execution.

I am trying to build an external simple interrupt hardware system (like any timer object in software) which interrupts Arduino in a specified interval, say 20 sec. So when that interrupt on that particular pin occurred we can call some function there to do the job and that's all from Arduino side and it can go back to sleep.

So I believe this will reduce the load on Arduino and of course since no looping it will not get heated at all. How can we make such a system (external timer) to interrupt Arduino in specific intervals? This is just a theory in mine, not an idea how to implement it in electronics.

How can I achieve this above scenario?

# Answer
So, since you're coming from the application domain there are some things you might want to consider:

* Make sure to always stay inside the super loop. With an Arduino or any other Microcontroller (not using a RTOS) you do not have anything defined that's going to happen after the superloop. Everything that happens after this loop is basically undefined (it typically is a reboot or jump to a default interrupt handler but may also be a lockup). Simply telling the processor to "exit" will .. well, exit - but you have no idea where it's going after that. To allow for interrupts and further execution of your main code, you need to have your processor in a defined state (and that basically is the super-loop). as a comparison with your PC, after you exit a thread, the operating system will take over. On your Arduino there is no such concept. The super-loop IS your OS (well, at least it's some minimum implementation of a non-preemptive scheduler).
* If you want to have only interrupt actions active while the processor is using only little power, you will need to use the processors sleep modes. These are modes, where special functionality is disabled but which keeps the processor alive or in some idle mode where it's actually just waiting. Whilst the Arduino may have various sleep modes, none of them are what can be achieved with other architectures, such as the MSP430 platform or some SAMxL platform. Those are dedicated as low power processor and provide the necessary deep sleep modes.
* When using a deep sleep mode, it depends on the actual sleep mode which interrupts can wake the processor. Typically for the deepest sleep modes, only few interrupt sources will actually wake the processor up as all other peripherals are inactive either because their clock was gated or power was turned off for that function block.
* You will always have some power drain for the processor but keep in mind that it's not only the processor which will require power. At some point, you have leakage currents through your capacitors/resistors and other ICs on your board which require power as well. When you're talking about "years", you will also need to account for the battery discharge as well. No battery is perfect.
* Jack Ganssle is probably well known for his insight into anything related embedded, but he explicitly wrote some articles for ultra-low-power systems. You must read those if you want to start somewhere. While having the software side covered using low power techniques you will also need to tackle the hardware side, yet as I said - the Arduino wasn't made for such tasks even if it provides some basic sleep modes.
> 6 votes

# Answer
You can refer below links once for understanding sleep concept on Arduino.

1) http://playground.arduino.cc/Learning/ArduinoSleepCode

2) http://www.gammon.com.au/power
> 0 votes

# Answer
You wrote:

> I'm a very beginner with electronics \[...\] the looping system feels pretty awkward

I think these two statements are highly correlated. It feels awkward to you simply because you are not used to it.

> So what I understood is Arduino loop always executes based on any values from sensors while in the loop.

This sounds like a misunderstanding. The Arduino `loop()` is a function *you* write, and whether its behavior is “based on any values from sensors” or not is up to you. The `main()` function provided by the Arduino core library will just call your `loop()` repeatedly.

> I tried to stop the loop using exit(0);

As explained by Tom L. in his answer, there is nowhere to exit to. In this kind of embedded system, `exit()` essentially means “stop doing any useful work”. On AVR microcontrollers (like in the Nano), `exit()` is implemented as an empty infinite loop running with interrupts disabled.

> I believe \[sleeping\] will reduce the load on Arduino and of course since no looping it will not get heated at all.

Heat? What heat? The CPU core of the Arduino does not generate heat. Not at any significant level. Think about this: it's clocked at 16 MHz. Yes, those are **mega**hertz: snail pace! The MCU *can* get hot if you have it source or sink too much current, but this is completely unrelated to CPU load.

> I am trying to build an external simple interrupt hardware system \[...\] which interrupts Arduino in a specified interval, say 20 sec.

Since you come from the software world, you probably know about “premature optimization”: this is exactly what you are doing here. I recommend you stop right now. Do not build into your system complexity that may not be useful. Instead, start simple: read the Blink without delay\[\] Arduino tutorial, and apply this technique to solve your problem. In a nutshell, you will put, inside your `loop()`, something like:

```
if (millis() - previousMillis >= JOB_PERIOD) {
    do_the_job();
    previousMillis += JOB_PERIOD;
}

```

Note that the tutorial I mentioned would instead do something like `previousMillis = millis();`, which is fine if you want to ensure that `JOB_PERIOD` is the *minimum* time between the jobs. The code above, instead, assumes you want to enforce an *average* period.

Once you have this working, test it, and see whether you do need to optimize it. There are two aspects that could be optimized: current consumption and period accuracy. Either may be useful for your particular application. Or none. Or both. It all depends on your specific requirements.

## Current consumption

There is a low hanging fruit here. You can put the CPU to sleep on every loop iteration, simply by calling `sleep_mode()`:

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

const uint32_t JOB_PERIOD = 20000;  // 20 seconds

void do_the_job()
{
    // The stuff you have to do every 20 seconds.
}

void loop()
{
    static uint32_t previousMillis;
    if (millis() - previousMillis >= JOB_PERIOD) {
        do_the_job();
        previousMillis += JOB_PERIOD;
    }
    sleep_mode();
}

```

The Arduino core library has a timer interrupt triggered every 1024 µs. This is the interrupt responsible of updating the variable that `millis()` returns, and it will wake you up. With the code above, the Arduino will be awake for only a few CPU cycles per iteration (update `millis()`, subtract, compare) and spend most of its time sleeping. In the default sleep mode, only the CPU does sleep. But it is also the only mode in which the timer does *not* sleep, and is thus the appropriate mode here.

The trick above should suppress most of the power consumption of the CPU. If it's still consuming too much for your liking (i.e. if you want your Nano to run for years on a couple of AA cells), you should know there are ways to push the microcontroller into the ultra-low power realm. But it is not so simple, and you will have to tune not only the software, but also the hardware. Your journey into microamp hunting should start by reading Power saving techniques for microprocessors, by Nick Gammon. The link has already been mentioned in Chirag Patel's answer.

## Period accuracy

The Arduino Nano being clocked from a ceramic resonator, you should expect its timing accuracy to be pretty poor. The standard solution for when you need accurate timings is to use an RTC. You could query the RTC periodically to ask for the current time or, better yet, you can choose an RTC with “alarm” capability. This is not unlike an alarm clock: you program it to send you an interrupt signal at a time of your choosing. Read the manual of your RTC for details.
> 0 votes

---
Tags: interrupt
---


# Question
Title: Bluetooth Low Energy dropping data at 115200 baud?
I'm transmitting serial data from a sensor on my Arduino simultaneously to my laptop via USB and to a terminal app on my phone via a genuine HM-10 BLE module (onboard a Linksprite BLE Shield).

At 9600 baud, the BLE module was transmitting all of my data to the phone's terminal app without issue. I just figured out how to increase the HM-10 module's baud rate to 115200 (for reference, by sending it an AT+BAUD4 command at 9600 baud from the Arduino IDE console via USB, and then uploading a new sketch to the Arduino with both the USB serial and BLE serial baud rates set to 115200). The data is being received via USB serial flawlessly, but the data received by the terminal app on my phone via BLE appears to be missing chunks of data - and I have to try to connect to it 30+ times to get it to properly connect.

Is 115200 baud too fast to transmit data via BLE? Is there any way to make sure all of the data is properly sent via BLE without slowing the program down too much? 9600 baud is too slow for my application, unfortunately.

I should add that I am using an Arduino M0 pro and the BLE is connected via hardware serial (Serial1) and not SoftwareSerial as would need to be done on the Uno, if that makes a difference.

# Answer
> 0 votes
Well, I did some tests and was not able to reliably receive data at over 9600 baud, even with hardware flow control activated via the AT+FLOW1 command. And even then, if either the BLE module or the phone was moving, data was consistentlydropped.

I ended up implementing an SD data logger instead.

---
Tags: serial
---


# Question
Title: PushButton as LED Switch (does not work)
```
 #define LED 1//This pin goes to the LED
 #define SWITCH 7//From Switch$

void setup() {
      pinMode(LED,OUTPUT);
      pinMode(SWITCH,INPUT);
}
int state=0;//Initializing values of all three
int val;
int lastval=LOW;

void loop(){
      val=digitalRead(SWITCH);//Reads if switch is on or off
      if(val==HIGH&&lastval==LOW){//Basically activates if the button was just pressed
        state=1-state;//Changes state after button is pressed
        digitalWrite(LED,state);//Enforces changed state to LED on or off
        delay(50);//Just a simplistic debouncing
      }
      lastval=val;//Store last value
}

```

# Answer
> 1 votes
Based on your response to my comment, it sounds like you have a floating input. When the button is NOT pressed, the pin isn't connected to ground or 5V so it is floating and picking up whatever stray electrical signals happen to be bouncing around the room.

The easiest way to handle buttons on an Arduino is to wire them between the pin and ground. Then in the code you use INPUT\_PULLUP instead of INPUT for the pinMode call. Once you've done that then the pin will reliably read HIGH when the button is NOT pushed and will read LOW when the button IS pushed. Note that this is backwards of how newbies tend to think, but is really the more common way to handle a button.

# Answer
> 0 votes
I think the problem is in the lastval assignment and checking. During the bouncing, lastval will probably change several times. Within these changes the if statement is checked. If an even amount of changes are detected, the LED will change 4 times (being OFF again if it was OFF and On when On). Even if the user clicked possibly only one time. When an uneven amount of changes are detected it will be ok. So it's kind of luck when it works.

Use a proper debouncing technique (checking for some time if the switch is high or low and act on that directly).

Also do not use a boolean to flip that way, if you want it use a proper boolean:

```
boolean state;

...

state = !state;

```

However, I suggest using something like:

```
digitalWrite(LED, state ? HIGH : LOW); // HIGH if state is true, else LOW

```

And change the if condition in a proper debouncing check (plenty of examples, e.g. Arduino debouncing switch).

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


# Question
Title: Do we need ARM build for arduino while interfacing R-pi and arduino
I wonder whats ARM build for Linux? Do we really need ARM build when we work with arduino? I need to integrate arduino and raspberry pi over wi-fi, I don't know whether I need ARM in this case. Also any quick learning tutorial for interfacing two of these hardware is appreciable

A newbie to Arduino. I hope fun learning with it

# Answer
The ARM build of the IDE is for running the IDE on ARM systems. If you want to run the IDE on the pi then you need the arm build. However if you want to run the IDE on your PC then you need the IDE build that matches the architecture of your pc.

There are a million and one ways of communicating wirelessly between an Arduino and a pi.
> 3 votes

---
Tags: arduino-uno, raspberrypi
---


# Question
Title: Selling a product using Arduino microcontroller or bootloader
I was wondering if I am legally allowed to sell an Arduino based product. I also want to know if it is easy for people to retrieve code from an Arduino based circuit (reverse engineer it) or upload code from Arduino microcontrollers.

If I'm posting in the wrong please, please let me know. If there is better place to redirect my question, letting me know would be helpful too.

# Answer
The Arduino hardware is released under the creative commons license.

https://www.arduino.cc/en/Main/FAQ#toc3

"which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license"

It's possible for someone to retrieve the instructions from the MCU but they would be looking at assembly rather than the c code you wrote your sketch in.

This is a similar question and answer: https://electronics.stackexchange.com/questions/67030/can-arduino-be-used-in-commercial-products
> 1 votes

---
Tags: arduino-mega, arduino-ide
---


# Question
Title: Using special Arduino "boolean" Data Type instead of standard "bool" data type
There is a special, non-standard Arduino data type called "boolean".

How does it compare with the standard C++ data type "bool", and what are the reasons to use one or the other?

If they are identical in usage, why do both exist, and which one is preferred in Arduino code?

# Answer
> 8 votes
While the other answers give generally useful information, the authors seem to have not read the question very carefully because they are talking about the **bool** type rather than the **boolean** type. In the Arduino API, `boolean` is a type alias for `bool`, as defined in Arduino.h:

https://github.com/arduino/Arduino/blob/1.8.3/hardware/arduino/avr/cores/arduino/Arduino.h#L125

```
typedef bool boolean;

```

So you can use the `boolean` type just as you would `bool` and any standard C++ programming reference will instruct you in the use of `bool`. For this reason the other answers which mistakenly refer to `bool` are still somewhat useful.

Apparently at some point in the past the Arduino folks decided the name `boolean` would be more beginner friendly than `bool`, perhaps to be consistent with the Processing language. However, as discussed here:

https://github.com/arduino/Arduino/issues/4673

the unnecessary use of a non-standard type is now considered by some to be a poor decision as its use makes code less portable and really doesn't provide any clear advantage over `bool`. A proposal is in the works to remove the use of `boolean` from all official Arduino code and document `bool` in the Arduino reference and some even wish to formally deprecate `boolean`. Therefore my advice is to use `bool` instead of `boolean` in your code.

# Answer
> 1 votes
A Boolean variable type is one that has only 2 possible values, `true` or `false`. Internally, it is created as an `int` (16-bit integer) or a `uint8_t` type (8-bit integer).

You can assign the "values" of `true` or `false` using the assignment operator:

```
bool foo;
foo = true;
if (foo) {
  do_something();
}

```

Internally, a `true` is a `1` and a `false` is a `0`, and the number values could be equally substituted.

Boolean types in Arduino and C++ mostly exist for readability, and not for any particular efficiency over `int` type.

# Answer
> 1 votes
The official reference can be found here

It is best to always use true and false, and not use numbers.

Below some examples are given

Assign false resp true to a Boolean:

```
bool a = true;
bool b = false;

```

Check the Boolean value:

```
if (b)
{
   // Executed when b is true
}
else
{
   // Executed when b is false
}

if (a && b)
{
   // Executed when a is true and b is true
}

if (a || b)
{
   // Executed when a is true or b is true
}

```

If b is false, a will be false, otherwise a will stay as it was

```
a &= b;

```

If b is true, a will be true, otherwise a will stay as it was

```
a |= b;

```

// If a is true it will be false and vice versa.

```
a = !a;

```

---
Tags: c++
---


# Question
Title: Using I2C to keep track of position of slaves
I am trying to flesh out my ideas for an electronics project and this question seems to be the main hangup. Is it possible, in the I2C protocol, to figure out the order in which the slaves are chained to the host? For example if I have 5 arduinos strung together by their serial and clock lines I want the master to be able to see that Arduino 1 is in position 1, Arduino 2 is in position 2... And so on. But if I switch Arduino 1 and 2 I want the master to know that Arduino 1 is in position 2 and Arduino 2 is in position 1.

I assume this isn't possible because all of the arduinos are connected to the same data and clock. So does anyone have any other protocols or algorithms in mind where I could do this. I was thinking I could have one Arduino talk to it's neighbors somehow and waterfall data down the line until it gets to it's destination. But I'm curious to see what y'all come up with.

# Answer
> 1 votes
This is indeed not possible. I2C was meant for short on-the-same-board communications and though it's sometimes also extended to near-board communications, it still has no facility for position sensing. Each slave simply listens for an address and then responds to commands sent for that address.

Slaves can "stretch the clock" to slow down things, but cannot otherwise make themselves known so long as they are not mastering the bus. In any case, even if bus mastering is assigned round-robin, only presence can be determined, not the position in any chain.

---
Tags: serial, i2c, communication
---


title: Data logging speed with arduino

text:
# Question
Title: Data logging speed with arduino
I am trying to make some data logging conserining physiological data coming from a bitalino. My problem is that I would like to collect samples at something like 1 kHz, that is the rate that the bitalino can read the sensors, but I think that the time needed to write this data to the SD card can't keep up with the speed, and here is why i think that:

I put in the script some timers to check what was consuming the time causing to low sample rate, resulting:

```
Bitalino: 0, SD: 27
Bitalino: 0, SD: 28
Bitalino: 2, SD: 26
Bitalino: 0, SD: 29

```

Being that the time in miliseconds.

```
void loop() {
    time = millis();
    readBIT();
    time2 = millis();
    printDataSD();
    time3 = millis();
    printData();
}

void printData() //Send the data acquired to the pc through the serial port
{
  Serial.print("Bitalino: ");
  Serial.print(time2-time);
  Serial.print(", SD: ");
  Serial.println(time3-time2);
}

void printDataSD() //Send the data acquired to the SD Card
{
    if (myFile) {
    //Bitalino
    myFile.print(_ECG);
    myFile.print(",");
    myFile.print(_EMG);
    myFile.print(",");
    myFile.print(_EEG);
    myFile.print(",");
    myFile.print(_EDA);
    myFile.print(",");
    //Time
    myFile.println(time);
    myFile.flush();

    } else {
    Serial.print("error opening file, ");
    SD.begin(10);
    delay(1000);
  }
}

```

I would like to know if there is a way to improve my sample rate.

Thank you!

Here is the readBit() like asked:

```
void readBIT() //Read IMU data
 {
  _ECG = analogRead(ECG);
  _ECG = ((_ECG/1024) - 0.5)*Vcc*1000/gECG; //mV

 _EMG = analogRead(EMG);
 _EMG = ((_EMG/1024) - 0.5)*Vcc*1000/gEMG; //mV

 _EEG = analogRead(EEG);
 _EEG = ((_EEG/1024) - 0.5)*Vcc*1000000/gEEG; //uV

 _EDA = analogRead(EDA);
 _EDA = (_EDA/1024*Vcc-0.259388)/gEDA; // revolution
 }

```

# Answer
> 1 votes
The OP has likely solved this problem by now, but I know that others will be in the same position, so I am answering for them.

I routinely record ten channels of biological sensors including one of 16-bit sound at 8 kHz (plus the associated FFT data) to an SD card using arduino-compatible systems, so I doubt very much that the SD card writing per se is the problem.

Throughput to an SD card is a function of several variables.

* To maximize write throughput you need to write full blocks of data at the correct block size, since partial blocks take the same amount of time as full blocks.
* You also need to be ready with more data as soon as the SD card is ready to take more, otherwise precious cycles slip away from you.
* You need to ensure that your writes are non-blocking (don't try to write more than the buffer can receive) so your loop can process and queue up new data while the SD card is doing its thing.
* You need to read any timing-sensitive sensors using interrupt service routines that write their data either to a circular buffer or to one of a group of two or three buffers that are cycled between being filled and being emptied.

Printing debug statements to the serial port can take many tens of milliseconds in a loop that otherwise may take only a few microseconds. If you write more than the serial port buffer can hold, the call will be blocking and you will be at the mercy of the PC that's reading the serial port. This will always be bad enough to mess up the program you're trying to debug... I've encountered situations where this introduced delays of up to 10 seconds (the PC was misbehaving, but still...).

A quick improvement to printing debug statements is to maintain a loop counter and only print a debug statement every N loops.

The program in the original question uses a naive strategy in the sense that it acquires some amount of data and then immediately tries to write it to the SD card, waiting until the write is complete before trying to acquire new data. This will never work at high data rates for the reasons given above. If you use this approach, you are likely wasting 90% of your program cycles in waiting for the SD write and the Serial port write. If either one takes too long, you will miss the next data acquisition window.

My advice: your first step is to research and find or write a circular buffer library.

Then set a timer to call an interrupt service routine that acquires data and puts it into the circular buffer.

Write a loop routine that checks to see whether the SD card is available for writing, and then takes just enough data out of the circular buffer to fit in a single block write for your SD card (look at the documentation for the card adaptor and the card).

At that point you will know whether your system can keep up with your needs.

It's possible that your SD card writing itself is OK but your Arduino is having trouble keeping up either because it's too slow or because you don't have enough room for a sufficiently large circular buffer. I doubt this because I've recorded and played back audio at 8 KHz on the Uno, but then I don't know what else you need to accomplish in your program.

If you do determine that the Arduino itself is too slow or has insufficient memory, take a look at the Teensy series of boards\[https://www.pjrc.com/teensy/index.html\]. They are entirely compatible with Arduino libraries and IDE but they run hundreds of times faster than the Uno at a larger data width, plus they have oodles of RAM and a gazillion pins. They're also much smaller than the Arduino form factor and the community that uses them is very knowledgeable.

If it turns out that SD card write throughput is OK but that it requires more buffering than you have on-board, you can add an SPI ram breakout board for more fast buffering space.

Finally, if the amount of data you need to collect is so large and so continuous that you simply can't buffer it long enough to get it written out to SD, or if the SD card truly can't keep up, or if the data is larger than any available SD card, you may consider sending your data off the board in near-real-time. I send 10 hours of nightly data from a Teensy over a USB virtual serial port to the PC at about 3Mbps, and others have done better. Ethernet output is also available and can be at least an order of magnitude greater.

glhf!

# Answer
> 0 votes
Why not write a simple program and try to write values like 1, 2, 3 ... 100 to the SD card with a 1 second delay between writes. Then read the values back and send them via serial link to your PC screen. This way you can make sure that you are writing and reading values in the correct way.

Once this works, you can reduce the delay and see what is the minimum delay between writes that the SD card will support.

It might be advisable to also write a program to fill the SD card with 100 values = 0 to clear it before the next test.

---
Tags: datalogging, sd
---


# Question
Title: How to run a timer every 12 hours (exceeding the max size of int) without an RTC?
I'm experimenting with a Nano, and trying to trigger an action around twice a day. I'm aware that it's not super accurate, but I don't really mind, as long as it's in the ballpark.

I've tried using the SimpleTimer library but I'm running into an issue because it takes milliseconds as an int, and 12 hours is 43200000 (larger than 32,767 max). Is there another library, or another technique I can use for this?

# Answer
Set the timer for every hour, which is within the limit. In your action, keep a `static int`, initialized to zero, which you increment each time. When it `==12`, do the thing you want to do and reset your `int` back to zero.
> 6 votes

# Answer
> I'm running into an issue because it takes milliseconds as an int ...

No it doesn't. Look at the function prototype:

---

```
int setInterval(long d, timer_callback f);

```

> Call function f every d milliseconds. The callback function must be declared as void f().

---

The interval `d` is a long. The `int` you see is the return value from the function, not the interval.
> 5 votes

# Answer
You have 2 other options to the `setInterval()` function:

* `delay()` (blocking)
* `millis()` (non-blocking)

Both of these functions deal with an `unsigned long` which has 32 bits = (2^32)-1 = 4,294,967,295. Doing the sums (and considering that both are in milliseconds), this will last for 49 days and 17 hours.

1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
12 hours = 12 * 60 * 60 * 1000 = 43,200,000

`delay(x)` will delay for x number of milliseconds. The delay function is blocking, meaning that while it is running/delaying you can't do any other task. The code would be:

```
delay(43200000);

```

`millis()` on the other hand is non-blocking and returns the number of milliseconds since power-up. This can be implemented with the following code:

```
#define TWELVE_HRS 43200000UL
unsigned long startTime;

setup()
{
  startTime = millis();
}

loop()
{
  if (millis() - startTime > TWELVE_HRS)
  {
    // Put your code that runs every 12 hours here

    startTime = millis();
  }
}

```
> 1 votes

---
Tags: arduino-nano, timers, rtc
---


title: How to compare payload value?

text:
# Question
Title: How to compare payload value?
Connecting my ESP8266 device to an IOT cloud service. When I push a button in the dashboard, it sends either 1 or 0. Then my ESP should turn a pin HIGH if signal received was 1 or Low if it was 0. Here is the code of the method in question:

```
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message received[");
  Serial.print(topic);
  Serial.print("] ");
  for (int i=0;i<length;i++) {
     Serial.print((char)payload[i]);
  }
  Serial.println();

  if ( (byte)payload[0] == 0) {
    digitalWrite(13, LOW);
    Serial.println("Setting PIN on to LOW");
  } else {
     digitalWrite(13, HIGH);
     Serial.println("Setting PIN off to HIGH");
  }

}

```

When sending a 1 signal, serial monitor displays:

> Message arrived \[/v1.6/devices/esp8266/relay/lv\] 1 Setting PIN off to HIGH

When sending a 0 signal, serial monitor displays:

> Message arrived \[/v1.6/devices/esp8266/relay/lv\] 0 Setting PIN off to HIGH

So it seems like it always goes into the `else` clause. Similarly, if casting the value as char:

```
if ( (char *)payload[0] == 0)

```

Then it will always go into the first condition `payload[0] == 0` regardless of the value received.

# Answer
You receive the character `0` or `1` but compare it to the value `0` or `1`. The two things are very different.

You are sending ASCII but comparing it to decimal.

Instead you need to compare like for like. Either:

```
if (payload[0] == '0') {

```

Or:

```
if (payload[0] == 48) {

```

You can find an easy reference for the full ASCII table here.
> 1 votes

---
Tags: arduino-ide, esp8266, c++
---


# Question
Title: Dynamic SSID + Password from ESP8266WiFi
I'm using the ESP8266WiFi library on a NodeMCU, running the arduino bootloader in the arduino software (Windows 10 app version).

I'm trying to load the SSID and password from SD-card (this part is successfull).

My problem this far is when i use the Wifi library it looks like this:

```
 Wifi.begin(const char*, const char*);

```

Since it takes 2 const parameters i cannot change it later. Is there anyway i can add SSID and PASSWORD to my sketch without having to recompile it. (I have to send it to people who does not know how to compile and flash an arduino)

I'm not attached to the ESP8266WiFi library, i'm not attached to SD-card, other solutions are welcome.

SD-reader works as planned, WiFi works as planned with a static password and SSID.

# Answer
> 1 votes
The `const` keyword there does not force the data you call it to be constant, it only forbids certain assignments with the parameters inside that function but it's just superfluous in most cases. Meaning you can call it with input you got from serial or some other source (for ex. setup page accessible from hotspot-\>Store in EEPROM-\>Next boot connect to set WiFi AP). There's also a nice StackOverflow thread about this here and why it's not actually a good idea in many cases.

# Answer
> 0 votes
The problem was not const char\*, but bad conversion from string to char\*.

Thing that lead me to believe it was the const char\* was an unclear compiler message, and poor understanding of C++ data types.

but the correct answer was:

```
 ssid.toCharArray(ssidc, ssid.length());

```

---
Tags: esp8266, wifi, nodemcu
---


# Question
Title: Blueduino Rev2 service UUID for web bluetooth
I have a Blueduino Rev2 board that I would like to have communicating with a web app (running the chrome bluetooth software) but I'm having trouble sorting out the service UUIDs that the web bluetooth library requires.

According to the wiki, it uses the service UUID 0xFFF0, write characteristic UUID 0xFFF1 and read characteristic UUID 0xFFF2 (source) but when I scan for the device through the web app filtering for that service UUID it doesn't appear, but does when I remove the service UUID filter.

Code used to scan for the blueduino:

```
navigator.bluetooth.requestDevice({
    filters: [{
        name: 'ZeroBeacon',
        services: [0xFFF0]
    }]
})

```

Does anyone know what the UUIDs are that I should be using? The documentation is quite unclear and lacking.

# Answer
> 1 votes
If the 0xFFF0 Bluetooth Service is not advertised by the Blueduino Rev2 board, you should not include it in the "services" key. It should be in "optionalServices. See https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web#request\_bluetooth\_devices

I think your code should look like:

```
navigator.bluetooth.requestDevice({
  filters: [{ name: 'ZeroBeacon' }],
  optionalServices: [0xFFF0]
});

```

---
Tags: bluetooth
---


title: Serial communication on Arduino Uno

text:
# Question
Title: Serial communication on Arduino Uno
I have a Raspberry Pi 3 connected to the serial of my Arduino Uno (pins 0 and 1), but I also have another device connected to two other serial pins on the Arduino (pins 10 and 11, using the SoftwareSerial library).

What I want to do is send a string from the RPI, then the Arduino gets it and resends that information through the other serial port to my device.

Until now the Arduino can receive the information from the RPI, but I'm not sure how to send that same string through the other serial port, the one going to the device.

Here is the code I'm using:

```
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }
  portOne.listen();
  while(portOne.available() > 0){
      Serial.println("Data from port one:");
      Serial.println(b);
    }
  }

```

I just get the data coming from the RPI, but nothing from portOne.

Any thoughts?

# Answer
> 0 votes
After reading more about the SoftwareSerial, I managed to get the communication I wanted in a simpler way. This is what I ended up using in my void loop:

```
void loop() { // run over and over

  if (Serial.available()>0) {
    HW = Serial.read();
    mySerial.write(HW);

  }

  if (mySerial.available()>0) {
    SW = mySerial.read();
    Serial.write(SW);
  }
}

```

Thank you all for your help, your answers gave me also a better understanding of what I was doing.

# Answer
> 2 votes
Your code is not reading the `SoftwareSerial`. `b` is only populated when the Pi sent data. The loop below sends what it reads from the `SoftwareSerial`, after that is prints a new line `println()` (only because that's what your code is doing)

The `listen()` method of `SoftwareSerial` is only required if you have more than one `SoftwareSerial` connection.

```
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }

 //not required with only one software serial connection
 //portOne.listen();

  if (portOne.available() > 0)
  {
   while(portOne.available() > 0){
      byte byteRead = portOne.read();
      Serial.write(byteRead);
    }
    Serial.println();
   }
  }

```

# Answer
> 1 votes
If you goal is to relay a string from RPI through the Arduino to a device connected via SoftwareSerial then you should be doing something like this:

```
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {

  if (Serial.available() > 0) { // data available on HW Serial
    b = Serial.readString();    // Read it
    portOne.print(b);           // and write it to SW Serial
  }

}

```

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


# Question
Title: ADXL345 becomes 0g when plugin MicroSD Adapter using SPI
Try SD SPI code and ADXL345 SPI code separately and both are fine. When merge the codes, ADXL345 reading okay (not plug in MicroSD Adapter). Pin should bo okay.

Every time MicroSD is plugged (the same pin working with above code), ADXL345 reading suddenly becomes 0g, 0g, 0g. Pull it out then reading is good.

See https://forum.arduino.cc/index.php?topic=360718.0 and not sure if this is due to a hardware defect on MicroSD Adapter.

Already read many post like https://forum.sparkfun.com/viewtopic.php?f=14&t=38072 and the code produce 0g result, too.

Is it purely a hardware problem? Anyone suggest another one? Is there any way to fix in software?

More details: I am using Nodemcu v1. and arduino library. The connected pins for SD and ADXL345 both at HSPI pins. I understand Nodemcu has another SPI (or even for SD card (SD0, SD1, ...etc), but I did not see any example by using those two and integrate with ADXL345 on HSPI.

# Answer
> 1 votes
You may have the same problem as my answer in Multiple SPI device answer ... not all devices supports another SPI device on the same port

That is (one of the) reasons I use STM32 instead of Arduino, since the Arduinos have 'only' one SPI port.

---
Tags: spi, sd-card, accelerometer, nodemcu
---


# Question
Title: PHP/My SQL Database -> to Arduino Serial Monitor
I'm using this domain http://www.decathlon.commonarchitecture.ca/ to host my phpmyadmin database and php code. I would like to read a specific column of the database in the serial monitor, displaying each number one right after the other. I'm unsure of whether to work with a GSM shield, an Ethernet shield or an Arduino wifi shield. Here is my php code (indents are off I know):

```
<?php

 $dbhost = "mysql.commonarchitecture.ca";
 $username = "arduinodb";
 $password = "*******";
 $db = "arduinodb" ;

    mysql_connect("$dbhost" , "$username" , "$password");
     //echo "Connected" ;

    //select db
    mysql_select_db($db);
    //echo "Connected to db" ;

  $sql="SELECT * FROM data";

  $records=mysql_query($sql);

 ?>

 <!DOCTYPE html>
 <html>

 <head>
 <title> Consumption Data </title>
 </head>

 <body>

 <table width="600" border="1" cellpadding="1" cellspacing"1">

 <tr>

 <th>Day</th>
 <th>Date</th>
 <th>Water Consumption (liters per person)</th>

 <tr>

 <?php

    while($data=mysql_fetch_assoc($records)) {

         echo "<tr>";

         echo "<td>".$data['id']."</td>";

         echo "<td>".$data['date']."</td>";

         echo "<td>".$data['value']."</td>";

         echo "</tr>";

     }//end while

     ?>

 </table>

 </body>
 </html>

```

The code works, however I'm unsure of how to go about reading the data on an Arduino (very new to Arduino)

Here's my Arduino code paired with an ethernet shield

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

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

IPAddress ip(192, 168, *, *);

EthernetClient client;

char server[] = "www.decathlon.commonarchitecture.ca";

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

  // attempt a DHCP connection:
  Serial.println("Attempting to get an IP address using DHCP:");
  if (!Ethernet.begin(mac)) {
  // if DHCP fails, start with a hard-coded address:
  Serial.println("failed to get an IP address using DHCP, trying
  manually");
     Ethernet.begin(mac, ip);
  }

  Serial.print("My address:");
  Serial.println(Ethernet.localIP());
}

void loop()
{
    // connect to the server
    if (client.connect(server, 80))
    {
        // print to serial monitor
        Serial.println("connected...");
        Serial.println("ARDUINO: forming HTTP request message");

        // send data the server through GET request
        client.print("GET /index.php?value");
        client.println(" HTTP/1.1");
        client.print("HOST:  ");
        client.println(server);

        Serial.println("ARDUINO: HTTP message sent");

        // give server time to receive request
        delay(1000);

        // get the response from the page and print it to serial port
        // to ascertain that request was received properly
        if(client.available())
        {
            Serial.println("ARDUINO: HTTP message received");
            Serial.println("ARDUINO: printing received headers and
script response...\n");

            while(client.available())
            {
                char c = client.read();
                Serial.print(c);
            }
        }
        else
        {
            Serial.println("ARDUINO: no response received / no response
received in time");
        }

        client.stop();
    }
    // do nothing forever after:
    while(true);
}

```

My issue now is in getting the Arduino to read my php data, can I not use an http GET request to display data in my serial monitor? Am I using this function properly? There's a ton of documentation on posting Arduino sensor data to the web using php/my sql but not as much on retrieval of set data back into the serial monitor. Here's what the monitor reads currently...

```
Attempting to get an IP address using DHCP:
My address:192.168.*.*
connected...
ARDUINO: forming HTTP request message
ARDUINO: HTTP message sent
ARDUINO: no response received / no response received in time

```

# Answer
> 1 votes
Firstly if you really are using an Uno then you cant read the data without putting the uno on a network (obviously). To do this you could get either a Ethernet shield of a Wifi shield. A wifi shield is probably based on an ESP8266 and you talk to it by creating a serial connection (using a software serial port). There are plenty of examples and messages on here to get you started.

Once that's working you need to write a web client (note that this is much easier if you program the ESP8266 rather than the Arduino). Your client needs to request the page from your server and then parse the returned data and extract the field you want.

While you are waiting for you network shield to arrive you could practice doing it on a Windows PC with Visual Studio, it will be easier to debug.

# Answer
> 1 votes
Any one of a GSM shield, an Ethernet shield or an Arduino wifi shield should be able to pull a web page from a web server and feed it into your Arduino.

I highly recommend buying hardware from people that put lots of example program text on their website, rather than trying to save a few nickles buying "equivalent" hardware from people that don't give any examples, leading to hours of frustration.

Some of the places I've found that have lots of example program text (in no particular order):

If I were you, I would test the hardware with *exactly* the example programs given for that hardware, and resist the urge to "improve" them until after I confirm that the example programs actually do work. (Perhaps you already did that? If so, please update your question to say the example code seemed to run OK, and exactly which example code you tried, and what minor changes you made that still seemed to run OK, so we can focus on *what changed* between "partially working" vs. "not even that part working").

(I personally find it easier to parse JSON data sent by a web server set up to send out `"Content-Type: application/json; charset=utf-8"`, or TOML data sent by a web server as `"Content-Type: text/plain; charset=utf-8"`, rather than programmatically parse HTML tables sent by a web server set up to send out `"Content-Type: text/html; charset=utf-8"`, but any of these ways should work).

---
Tags: arduino-uno, ethernet
---


# Question
Title: ESP8266-12 is showing garbage when RST is given
I use ESP8266-12 with an Arduino Uno as a USB-serial adapter.

When I upload any sketch to the ESP8266 it works fine until I reset the ESP8266.

```
uint32_t realSize = ESP.getFlashChipRealSize();
uint32_t ideSize = ESP.getFlashChipSize();
FlashMode_t ideMode = ESP.getFlashChipMode();

Serial.printf("Flash real id:   %08X\n", ESP.getFlashChipId());
Serial.printf("Flash real size: %u\n\n", realSize);

Serial.printf("Flash ide  size: %u\n", ideSize);
Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
Serial.printf("Flash ide mode:  %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));

if(ideSize != realSize) {
    Serial.println("Flash Chip configuration wrong!\n");
} else {
    Serial.println("Flash Chip configuration ok.\n");
}

delay(5000);

```

If I ground reset button, garbage values are being shown.

Connections details:

EN - 3.3V of Uno
VCC - 3.3V of Uno
RST - GND Of Uno(If needed)
TX - TX of Uno
RX - RX of Uno
GPO15 - GND of Uno
GPO01 - GND of Uno
GND - GND of Uno

# Answer
Espressif says it can not be disabled.

Ref.: https://github.com/esp8266/Arduino/issues/3047
> 0 votes

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


title: IEEE 754 for integer

text:
# Question
Title: IEEE 754 for integer
Maybe is to easy to answer but i don't know it. I know IEEE-754 is for float values and double but i don't know if is exclusive for those type.

I use this to convert float and works fine i have another code in javascript to revert it. But when used it with integer values it just gives some values and the revert doesn't work as supposed to.

So, this definitely doesn't work for integer values?, i can parse it to float and pass it to IEE754 but i just want to know.

this is the code i use in arduino.

```
void IEEE754( float val, int pos)
{
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}

```

also, does anyone has the revert code for arduino?..

# Answer
IEEE 754 is the specification for floating point values. Integers aren't floating point values so this function of yours can have nothing to do with integers.

On an Arduino (8-bit):

* A float value is 4 bytes in IEEE-754 format.
* A long value is 4 bytes in little-endian format.
* An int value is 2 bytes in little-endian format.
* A byte is a byte.

To convert 4 bytes into a long you can use:

```
long val = (payload[3] << 24) | (payload[2] << 16) | (payload[1] << 8) | payload[0];

```

An int value is just the lower two bytes of the same kind of conversion:

```
int val = (payload[1] << 8) | payload[0];

```

You can use the same method (albeit backwards) to get the bytes to put in your payload:

```
long val = 12345678L
payload[0] = val & 0xFF;
payload[1] = (val >> 8) & 0xFF;
payload[2] = (val >> 16) & 0xFF;
payload[3] = (val >> 24) & 0xFF;

```

You can also use the same technique as your existing function with different datatypes, since all you care about is the byte content not the format or meaning of the bits within it:

```
void int2payload( int val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 2 ; i++) {
      payload[pos + i] = array[i];
  }
}

void long2payload( long val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}

```
> 2 votes

---
Tags: float
---


title: Menu libaries for a clock

text:
# Question
Title: Menu libaries for a clock
I have a 7 segment clock with 4 digits, and 2 push buttons to control time (hours seconds days month etc). What is the best way to manage the settings of each sub menu when the user wants to change the time? Is coding it myself or using a menu library such as this one better for the task? https://playground.arduino.cc/Code/Menu

Thanks

# Answer
> 3 votes
I would make it myself.

One way to do it:

* Create an enum with all states, like Normal, ChangeMonth, ChangeDay, ChangeHour, ChangeMinute };
* Use one button to increase the item you are changing with 1
* Use the other button go to go the next enum

You can make it fancier by using longer/shorter presses (e.g. to increase faster)

Don't forget to debounce button inputs.

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


# Question
Title: WiFi101 Client HTTP POST fails after 3rd request
I would really appreciate any help, my home project has been put on hold for weeks as I haven't been able to figure this out. In a nutshell, I'm connecting to my wifi network, measuring temperature from a sensor, and sending that temperature data to a server via a HTTP Request. All of that stuff works.

I have it in a loop, and on the 3rd HTTP request I get 'Connection Failed' when it's trying to `client.connect(server, 80)` \- I don't understand why it fails. I've tried adding `client.stop()` and `client.flush()` after each HTTP request, but nothing fixes it. Below is my sketch file with some of the temperature code removed to make it easier to read

```
#include <SPI.h>
#include <WiFi101.h>
#include <string.h>
#include <stdlib.h>
#include <OneWire.h>
#include <DallasTemperature.h>

//WiFi Client Setup
char ssid[] = "HIDDEN";    //  your network SSID (name)
char pass[] = "HIDDEN";       // your network password
int status = WL_IDLE_STATUS;    // the WiFi radio's status
char server[] = "HIDDEN";
WiFiClient client;

// Setup for temperature sensor
#define ONE_WIRE_BUS A5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress insideThermometer;

void setup() {
  Serial.begin(9600);
  WiFi.setPins(8,2,A3,-1);
  while (!Serial) {
    Serial.println("Waiting for serial");
  }

  //Connect to wifi shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    while (true);
  }
  wifiConnect();
  sensors.begin();
}

void loop() {
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
  /*
  Code to get temperature here
  */
  httpRequest(temp);
  delay(10000); // 5min
}

void httpRequest(String temp) {
  String request = "POST /api/webhooks/temp?temperature=" + temp + " HTTP/1.1";

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    client.println(request);
    client.println("Authorization: Token HIDDEN");
    client.println("Host: HIDDEN");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("Connection failed");
  }
}

void wifiConnect() {
  //Attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(1000);
  }

  Serial.println("You're connected to the network");
}

```

# Answer
I tried changing the strings to char's, that didn't work. Verified that it was closing connections with the server, check.

Was reading around and saw someone who tried a soft reset of the wifi client here. I added the following to the end of my `httpRequest()` method

```
client.stop();
WiFi.end();
delay(10);
WiFi.begin(ssid, pass);

```

And now it's working just fine. I'm going to have it run all night and see if there are any issues, but it's definitely an improvement as I can make more than 3 requests :|

This seems like a terrible work around. Clearly something isn't getting reset after each HTTP request on the wifi client, and this (right now) is the only way to solve it. I'd really love any other feedback on a better ways to solve it. Seems like some issues with the WiFi101 Library.
> 2 votes

---
Tags: wifi, arduino-pro-mini, mkr1000
---


# Question
Title: Arduino and ESP8266 Two-way Communication
I've searched the internet quite a bit and all I find is how to make two esp8266 communicate. What I am trying to do is connect a single esp8266 to the arduino and have a two-way communication between them.

I want to send and receive data on both the Arduino and ESP8266. The concept is to send data to the esp8266 over WiFi connection and then send that data to the Arduino. The Arduino will manipulate it and send it back over WiFi.

I feel like this would be a common beginner example to have a two-way communication over a TX/RX connection, but I can't seem to find any. All examples I find are strictly one as sender and other as receiver.

# Answer
See How can I verify that my ESP8266 is working? asked 2 hours before.

use something like https://www.sparkfun.com/products/12009 or https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

Usual way is let the Arduino direct the ESP, but if you are able to program ESP too, then any communication can work the same way as between twou ESPs or two Arduinos (with the level shift in mind)
> 1 votes

# Answer
The best way for connecting ESP8266, Arduinos and devices like displays, RTC, etc., is using the serial protocol I2C.

I2C is a master-slave protocol. In this case, ESP8266 will be your master, and every other device (including Arduino) will be a slave. Every slave had an *address*, for id purposes. You can have up to 127 slaves, in theory, but real limits is determined by space, distance, capacitance, etc.

Only masters can initiate communication, so you have to program your ESP8266 to poll the the Arduino for sending back the processed information.

Connection is simple. For a I2C device (slave or master), you need Vcc and GND, plus two lines for communication: SDA and SCL.

For programming, you have lots of tutorials and examples on how to use I2C.

Both ESP8266 and Arduino (an many others MCU I think) can speak I2C. I strongly recommend you to adopt this protocol for everything. If you want to buy some device (like a display), always looks for the I2C version.
> 0 votes

---
Tags: esp8266, communication
---


title: Servo jitter with two atmegas

text:
# Question
Title: Servo jitter with two atmegas
So i'm building my own quadcopter at this moment and I have designed a flight controller board for it using two atmega328p's. I've programmed it so that the first atmega receives al the data from sensors and the radio transmitter and then calculates the values for the motors, LEDs and servos. To have it run smooth, the motor controller (ESC) gets updated 250 times per second (250Hz). So the first atmega sends all the data via i2c to the second atmega 250 times per second. When the second atmega receives the data it causes an interrupt via Wire.onReceive(event);. This then sets a flag so the main loop starts when there is new data. Here is a really simplified version of my code:

atmega 1:

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

int servo1;
int val, i;

int escLR;
int escRR;
int escLF;
int escRF;

byte send_array[11];
byte error;

unsigned long int loop_timer;

void setup() {

  Wire.begin();                                                    //joins the i2c bus
  TWBR = 12;                                                      //set i2c clock to 400kHz

  GyroAccelInit();

  delay(3000);

  loop_timer = micros();                                     //set the timer for the loop
}

/*************************************************************************************************************************/

void loop() {

  //ReadGyro();                                                              //commented out because not relevant
  //ReadAccel();
  //PPM_get();

  if (error == 1) {
    send_array[10] &= B11111000;
    send_array[10] |= B00000001;                                   //set led bits to red
  }

  SendData();                                                                //send the data

  if (micros() - loop_timer > 4050) {                               //set error if the loop takes too long
    error = 1;
  }

  while (micros() - loop_timer < 4000) {}                          //wait until 4 milliseconds have passed
  loop_timer = micros();
}

/*************************************************************************************************************************/

void SendData() {                                                  //sends the data to second atmega

  send_array[1] = escLR & 0xFF;                                    //isolates the low bits
  send_array[0] = escLR >> 8;                                      //shifts high bits to the right

  send_array[3] = escRR & 0xFF;                                    //isolates the low bits
  send_array[2] = escRR >> 8;                                      //shifts high bits to the right

  send_array[5] = escLF & 0xFF;                                    //isolates the low bits
  send_array[4] = escLF >> 8;                                      //shifts high bits to the right

  send_array[7] = escRF & 0xFF;                                    //isolates the low bits
  send_array[6] = escRF >> 8;                                      //shifts high bits to the right

  send_array[9] = servo1 & 0xFF;                                   //isolates the low bits
  send_array[8] = servo1 >> 8;                                     //shifts high bits to the right

  Wire.beginTransmission(42);                                      //begins the transmission to device 42

  for (int n = 0; n < 11; n++) {
    Wire.write(send_array[n]);
  }

  Wire.endTransmission();                                          //sends the buffer to the slave
}

```

atmega 2:

```
include <ServoTimer2.h>
include <Wire.h>

int count;
int servo1_val;

int escLR_val;
int escRR_val;
int escLF_val;
int escRF_val;

byte state;
byte new_data;

byte buff[11];

unsigned long int loop_count;

ServoTimer2 escLR, escRR, escLF, escRF, servo1, servo2;           //initialize ESCs
WS2812 LED(1);                                                    //one LED
cRGB value;

/*************************************************************************************************************************/

void setup() {

  Wire.begin(42);                                                 //joins the i2c bus as a slave with an adress of 42
  Wire.onReceive(event);                                          //sets up the handler that gets activated when there is data coming in

  Serial.begin(57600);

  escLR.attach(8);                                                //set ESC output to pin 8
  escRR.attach(7);                                                //set ESC output to pin 7
  escLF.attach(6);                                                //set ESC output to pin 6
  escRF.attach(5);                                                //set ESC output to pin 5
}

/*************************************************************************************************************************/

void loop() {

  if (new_data == 1) {                                            //start loop if there is new data

    escLR_val = buff[0] << 8 | buff[1];                           //get the two bytes to make a 16 bit integer
    escRR_val = buff[2] << 8 | buff[3];                           //get the two bytes to make a 16 bit integer
    escLF_val = buff[4] << 8 | buff[5];                           //get the two bytes to make a 16 bit integer
    escRF_val = buff[6] << 8 | buff[7];                           //get the two bytes to make a 16 bit integer
    servo1_val = buff[8] << 8 | buff[9];                          //get the two bytes to make a 16 bit integer
    state = buff[10];                                             //get the state byte

    escLR.write(escLR_val);                                       //write to all the ESCs
    escRR.write(escRR_val);
    escLF.write(escLF_val);
    escRF.write(escRF_val);

    new_data = 0;
    loop_count++;
  }
}

/*************************************************************************************************************************/

void event(int howMany) {                                         //handler that gets activated when there is data coming in
  byte count = 0;

  while (Wire.available()) {                                      //wait until all bytes are in

    buff[count] = Wire.read();
    count++;
  }

  new_data = 1;
}

```

Now here's the problem: because of the interrupt that is activated when there is data coming in, the signal for the servos and motor controller is really unstable and the servos jitter all the time. I know this because when I disable the interrupt, the servos and motors behave perfectly normal. Other forums have suggested to use the servoTimer2 library (which I do) but that didn't change a thing. Also the servos only turn 90 degrees instead of 180 but that could be because I'm running them on 250Hz instead of 50Hz. So if anyone knows how to write to the servos at 50Hz and the motor controllers at 250Hz please let me know.

So does anyone have suggestions? I'm happy with all suggestions so if I have to I will rearrange my entire code to solve this problem. I was thinking about using the using the mills() function, using requestFrom() or disabling interrupt for a while and even using hardware PWM. So maybe that brings you an idea. I'm really stuck here and I have to have it finished in less than a week so any help would be more than welcome!

by the way, english isn't my first language and am really bad at explaining things so if things are not clear I'll be happy to explain!

# Answer
> 2 votes
The core problem is that servo control on an Arduino is done using timer interrupts and not hardware PWM. And of course your I2C reception is also using interrupts.

Since the Arduino only has one level of interrupts you can't interrupt an interrupt, so when you are receiving I2C data the interrupts for the servos cannot trigger and so they get confused with bad timing signals.

You can tackle it in one of three ways (that spring to mind):

1. Don't use interrupts for receiving your data
2. Use hardware PWM instead of timer interrupts for the servos
3. Use a more advanced microcontroller with multiple interrupt priority levels where the timer interrupt can interrupt the I2C interrupt.

---
Tags: arduino-uno, i2c, servo, atmega328, wire-library
---


# Question
Title: How do I handle multiple interrupts and outputs simultaneously?
I'd like to make a musical harp that utilizes break beam sensors.

I'd really appreciate guidance on these two questions:

* How should I go about listening for multiple beam breaks at the same time? I'd like the box to be able to play cords, so I'd need to listen for the break beams while simultaneously taking the action do to other previous break beams. Are there any links to similar projects for guidance on handling multiple inputs (possibly multiple interrupts) at the same time, as well is multiple outputs?
* Where is a good place to start to understand how to output non-buzzer sound with an Arduino? I bought a Adafruit Wave Shield to do the trick, but I'd appreciate advice on using this, or possibly taking an easier route.

My major concern is the first question however, and it makes me think I may need a Pi possibly? But I've never worked with those, so I'd like to avoid it if possible.

Thanks! :)

# Answer
> 1 votes
Most of the examples for that shield seem to suffer from what could be called `delay`itis. If you first convert the piano example to a more state-based approach then the loop you want becomes much simpler:

```
#define NUM_BEAMS 12
// a single octave

char filename[NUM_BEAMS+5]; //init the last 5 chars to ".wav\0"
int previousInputs; //flag variable where each bit is a single beam

void loop(){
    int inputs = readBeams();

    if(inputs != previousInputs){
      previousInputs = inputs;
      if (wave.isplaying) {// already playing something, so stop it!
        wave.stop(); // stop it
      }
      if(inputs == 0){
        return;
      }
      for(int i = 0; i< NUM_BEAMS; i++){
          filename[i] = inputs &(1<<i)?'1':'0';
      }

      if (!f.open(root, filename)) {
        putstring("Couldn't open file "); Serial.print(name); return;
      }
      if (!wave.create(f)) {
        putstring_nl("Not a valid WAV"); return;
      }
      // ok time to play!
      wave.play();
    }

}

```

The SD card in the shield will need 4095 files, each containing the chord that must be played.

No need for interrupts, no messy interrupt based IO. Just a simple `loop()` where you read the input and if different from last time start playing a new file.

If you have a shield that can actually do sound mixing then, instead of needing a file for *every possible chord*, you can start playing the note when the corresponding bit in `started = inputs & ~previousInputs;` is 1 and stop playing the note when the corresponding bit in `ended = ~inputs & previousInputs;` is 1.

# Answer
> 1 votes
I quite like rachet freaks's idea, however whilst making an example for you his answer hadn't been posted. SO i'll chip in anyway!

In general it is possible to control and measure more than one input and output at the same time by the use of millis(). millis() is an arduino function that returns the number of milliseconds since the arduino fired up.

This probably doesnt sound overly useful to you straight away. But millis can be used in place of delay() if used correctly. Essentially you create a long variable to hold the beginning of an event and check the time since that event started with an if statement. If the difference in the current time and the start time is equal to the time you want the event to occur. Stop the event.

I appreciate my explanation might not be overly clear. So I wrote an example sketch. The sketch has two button inputs. And two button outputs. If one of the buttons is pressed one led will blink for 10 seconds, pressing the button mid blink will extend the time the led blinks by another 10 seconds. Whilst this is happening if you press the second button the other led will turn on, but only when the button is pressed. Using delay() to achieve this would not work nearly as well.

```
//Setup led and button pins
int ledPin1 = 3;
int ledPin2 = 4;
int butPin1 = 5;
int butPin2 = 6;

//Setup timers
unsigned long currentMillis = 0;
unsigned long blinkStartMillis = 0;
unsigned long ledOnMillis1 = 0;
unsigned long ledOffMillis1 =0;

//Setup variables to store input and output states.
int ledState1 = 0, ledState2 = 0; //State 1 for on, 0 for off;
int butState1 = 0, butState2 = 0; //State 1 for trigger, 0 for off;

//Setup trigger for event
int blinkTrigger = 0;

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(butPin1, INPUT);
  pinMode(butPin2, INPUT);

  delay(500);
}

void loop() {
    //Sets current millis for this loop
    currentMillis = millis();

    //Reads Button States
    butState1 = digitalRead(butPin1);
    butState2 = digitalRead(butPin2);

    //Setup to start blink if button 1 input is high
    if(butState1) {
      blinkTrigger = 1;
      blinkStartMillis = currentMillis;
    }

    //Handles Blinking
    if(blinkTrigger) {

      //If led1 off, and has been off for 500 milliseconds. led 1 on
      if(ledState1 == 0 && currentMillis - LedOffMillis >= 500) {
        digitalWrite(ledPin1, HIGH);
        ledState1 = 1;
        ledOnMillis = currentMillis;
      }

      //If led1 on, and has been on for 500 milliseconds. led 1 off
      if(ledState1 == 1 && currentMillis - LedOnMillis >= 500) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        ledOffMillis = currentMillis;
      }

      //If led1 has been blinking for more than 10 seconds
      //Stop blinking
      if(currentMillis - blinkStartMillis > 10000) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        blinkTrigger = 0;
      }
    }

    //While Button 2 pressed led 2 on
    if(butState2) digitalWrite(ledPin2, HIGH);
    if(!butState2) digitalWrite(ledPin2, LOW);

}

```

Note: The code style is a bit off because i rushed it, I would also usually use structs to hold the timers and event triggers.

Now for the Wave module rachet is bang on the money, you would need a file for every single note and every single chord.

I hope I helped, if not for your project maybe you may have learnt how to handle more than one event using event timings.

# Answer
> 0 votes
> How should I go about listening for multiple beam breaks at the same time?

use interrupts. it can be done with external interrupts, pin change interrupts, comparator interrupts, analog interrupts, or even timer interrupts, depending on how you intend to approach it.

---
Tags: interrupt, audio
---


# Question
Title: No change in acs 712 readings after connection to load
I would like to measure the amount of power used by a 3w bulb. I am using a 9v battery to power the bulb and an acs712 current sensor to get current usage. However, i get no change in values after i connect the load and it light up. Is my current sensor faulty or? I'm confused.

# Answer
> 3 votes
For such light and low-voltage loads you wouldn't normally use a mains rated high current amplifier like this.

Instead you would just use a simple shunt resistor in the low-side of the circuit:

simulate this circuit – Schematic created using CircuitLab

The voltage dropped across the resistor (and hence the voltage you will read on A0) is proportional to the resistance of the resistor and the current flowing round the circuit.

You want the resistor to be small enough that it doesn't overly affect the operation of the circuit, yet large enough that it drops a voltage you are able to sense at enough resolution.

For example the 1Ω resistor above, with 333mA round the circuit (3W at 9V) would drop (V=IR) `0.3 * 1 = 0.3V`.

While that's not a very high voltage it's small enough to not really affect the circuit, and you can increase the sensitivity of the Arduino by using the 1.1V internal reference instead of relying on the default 5V external Vcc voltage:

```
analogReference(INTERNAL);

```

Or on the Mega2560:

```
analogReference(INTERNAL1V1);

```

---
Tags: arduino-uno
---


# Question
Title: Receiving serial data in groups instead of individually
I have two different Vernier science probes connected to a Vernier shield that connects to an Arduino Uno. I have the Uno connected to an ESP8266 via the Tx.

Here is my Uno code:

```
String sensor1 ="Conductivity Probe ";
float interceptSensor1 = 0.0;
float slopeSensor1 = 960;
String sensor2 ="pH Probe ";
float interceptSensor2 = 13.720;
float slopeSensor2 = -3.838;
int timeBetweenReadings = 2000; // in ms

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

void loop() {
  float analogSensor1 = analogRead(A0);
  float voltageSensor1 = analogSensor1 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor1Reading= interceptSensor1 + voltageSensor1 * slopeSensor1;
  //converts voltage to sensor reading
  String sensor1Output = sensor1 + sensor1Reading;
  Serial.println(sensor1Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
  float analogSensor2 = analogRead(A1);
  float voltageSensor2 = analogSensor2 / 1023 * 5.0;
  // convert from count to raw voltage
  float sensor2Reading= interceptSensor2 + voltageSensor2 * slopeSensor2; //converts voltage to sensor reading
  String sensor2Output = sensor2 + sensor2Reading;
  Serial.println(sensor2Output);
  delay(timeBetweenReadings);
  // delay in between reads for stability
}

```

On the serial monitor every two seconds I get one line of output and it alternates back and forth between the sensors:

```
Conductivity Probe 807.04

pH Probe 4.12

Conductivity Probe 802.35

pH Probe 4.13

Conductivity Probe 802.35

pH Probe 4.12

```

Since I've only got a simple serial line to work with but I need to send multiple, different types of data to the ESP8266, my strategy is to send one line (ex. `Conductivity Probe 807.04`) and use logic on the ESP8226 to parse the string, isolate the float number (`807.04`), and use `Conductivity Probe` to determine how that number gets further used (in my case, to publish to an MQTT feed called `ElectroConductivity`).

The Tx of the Uno + sensors is wired to the Rx of the ESP8266, and here's the ESP8266 code:

```
  while (Serial.available() == 0) {
  }
  sensorReading = Serial.readString();
  Serial.println(sensorReading);

```

The data comes in large groups instead of line by line:

```
pH Probe 4.12
Conductivity Probe 807.04
pH Probe 4.12
Conductivity Probe 807.04

```

I'm new to serial comms and Arduino in general. I'm guessing that there's an issue with how serial is read by the ESP8266.

**EDIT**

When I use `sensorReading = Serial.readStringUntil('\n');` instead my output looks like this:

```
Conductivity PrpH Probe 4.12

Conductivity Probe 816.42

pH Probe 4.12

Conductivity Probe 825.8Conductivity Probe 821.11

Conductivity Probe 821.11

pH Probe pH Probe 4.12

ConductivitypH Probe 4.12

```

# Answer
`readString()` will keep reading until it times out. Instead try `readStringUntil('\n')` to read until you get a new line character.
> 2 votes

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


# Question
Title: avrdude: ser_open(): can't open device "\\.\COM3"?
My computer cannot detect my Arduino Uno anymore,

* Reset button- \> L led light blinks and it turns on forever
* Arduino 1.6.5: Tools-\>Port (greyed out) I remembered that previously it wasn't like this
* Unable to upload any sketch codes into the Uno anymore
* The existing code uploaded onto the Uno is FastLED(FirstLight) and it will work on my LEDs when I plugged them in

I have tried to .... but none fix my issue

* Restart my computer
* Press the reset button on the Uno
* Using the device mananger to change COM ports
* Device manager -\> Other devices -\> (nothing about Arduino Uno is found here)
* Plugged Uno into another computer but still doesn't work
* Reinstalled IDE

Problem shown in sketch,

> avrdude: ser\_open(): can't open device "\\.\COM3": The system cannot find the file specified.
>
> Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

# Answer
I have experienced a similar issue after plugging in another Arduino device. I didn't set up my environment for a long time and thus forgot he iterates the COM-Index. Maybe this is too easy, but you didn't provide much information.

This solved my problem: Open Arduino application \> Tools \> Port \> Change to the target Port

If you are unsure which port to choose from: (on Windows) Open Device Manager \> Connections (COM & LPT) \> Usb Serial Port (COM\[x\]) where "\[x\]" is the index you are looking for.
> 1 votes

# Answer
Try a different arduino w/ your first computer, see if that will work.
> -1 votes

---
Tags: arduino-uno, hardware
---


# Question
Title: Arduino UNO/Nano communication with SP1ML-868 module
Good evening, I'm trying to establish serial communication between an Arduino UNO/Nano (ATMega328P) and a SP1ML-868 RF radio module (http://www.st.com/en/wireless-connectivity/sp1ml.html). I can talk to the radio with an FTDI breakout board, connected directly to my PC, but I can't do it with the Arduino.

As the radio is 3.3V and the Arduino is 5V, I tried to use the logic level converter from Sparkfun in the RX/TX lines, but that didn't work as well.

Any idea as to what I might be doing wrong? Thanks!

**EDIT**
I was able to talk to the radio by uploading a blank sketch to my Arduino and using only the RX/TX pins and the FTDI chip on the board. When I configure the Serial port (i.e. Serial.begin), this no longer works, which leads me to believe the problem is in the ATmega USART configuration. For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

As requested, below is the simple serial echo code I'm using, and an image with the wiring. This assumes the normal RX-\>TX and vice-versa connection. The module is powered through wires underneath its breakout board (3.3v).

```

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

void loop(){
  while(Serial.available() > 0){
    Serial.print((char)Serial.read());
  }
}

```

# Answer
> 1 votes
Not an answer to my question per-se, but I was able to solve my problem.
As mentioned on my comment on the last answer, the SP1ML module's serial communication is handled through an ARM microcontroller. So I got my hands on an Arduino Due, which has an ARM Cortex M3 MCU, and uploaded a serial echo code similar to the one on my question, only now using Serial3 to talk to the module:

```

void setup(){
  Serial.begin(9600);    // Connected to PC
  Serial3.begin(115200); // Connected to SP1ML, Rx-Tx connection
}

void loop(){
  if (Serial.available() > 0){
    Serial3.write(Serial.read()); // Echo to SP1ML
  }
  if (Serial3.available() > 0){
    Serial.write(Serial3.read()); // Echo to serial monitor
  }
}

```

I tried the exact same code on an Arduino Mega (same pins, ATmega2560 MCU) and it didn't work.
Obviously the MCUs are very different, but I have no idea one works and the other doesn't. A wild guess would be that the word sizes are different. In the Atmega, the word size is 16-bits, and in the ARM, the word size is 32-bits.

# Answer
> 0 votes
> For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

This works because in that configuration you are actually using your Arduino as a USB-serial adapter. When you make the RX-RX, TX-TX connection you cannot communicate between the ATmega328P on your Uno but you are also making a RX-TX, TX-RX connection with the ATmega16U2 chip on your Uno that is used as the USB-serial adapter on the board.

I feel that it's problematic to try to use Serial (pins 0 and 1) for communication both with the computer and the module. Instead I would recommend using the SoftwareSerial library for communication between the Uno and the module.

SoftwareSerial doesn't work reliably at 115200 so you should first use the current working wiring to configure the module to communicate at a lower baud rate. 9600 is quite safe but if communications speed is a bottleneck for your application you can probably use a higher baud rate.

Next, wire the module to any unused pins on your Uno other than 0 and 1.

Finally, upload the following code to the Uno:

```
#include <SoftwareSerial.h>

SoftwareSerial SP1MLserial(10, 11); // RX, TX

void setup() {
  Serial.begin(115200);  // set this to the baud rate of the Serial Monitor
  SP1MLserial.begin(9600);  // set this to the baud rate of the module
}

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

```

This is the equivalent of the simple echo code you posted above and can be used to verify that everything is working before moving on to more complex code. I have arbitrarily chosen pin 10 for the Uno software serial RX pin 11 for the TX pin but you can modify the code to any pins that are convenient for you. You should make the connections with the module as RX-TX, TX-RX.

---
Tags: arduino-uno, serial, arduino-nano, rf
---


# Question
Title: Are there any electro-chemical sensors available to measure nutrient contents of soil?
I want to develop a soil fertility testing device and need an electro chemical sensor to do so. I searched the online available sensors but didn't get any source. Does anyone knows anybody in development of such sensors ?

# Answer
You have pH and humidity sensors for Arduino, but "soil fertility" is an unprecise term.

If you do a web search, you will find results for a number of devices that claim to measure soil fertility. I am highly suspect of these devices. Even laboratory testing cannot tell you accurately how fertile your soils are because of the methods used. Most labs test for the presence of inorganic chemals, including nitrogen, potassium, phosphorous and an array of other nutrients plants need. What most of them do not or cannot measure is the amount of plant-available nutrients in the soil. It takes a host of soil organisms to make nutrients in the soil available to plants. If those organisms are not present or are low in numbers, it is difficult for plants to take up nutrients. Fertilizers only exacerbate the problem because they kill off soil organisms, especially mycorrhizal fungi, throwing the entire ecology of the soil out of kilter. There are a couple of laboritories out there that test for soil biology and some nutrients.

Soil is hard. There is a lot of things in soil (compactness, unwanted chemicals/elements, microbes) that can affect the *fertility*, even if you have the right nutrients in it.

For hydroponic (not your case), you have cheap handheld EC/TDS meters. The pH and EC of your reservoir is all you need to measure the *fertility* of your water solution.

Go hydro and stop worrying about your tomatoes.
> 2 votes

---
Tags: sensors
---


title: Timer Prescaler problem

text:
# Question
Title: Timer Prescaler problem
I am working on a project which requires use of 16bit timer . I am using Arduino Uno (Atmega 328p) board and Timer\_1 (16 bit timer ) in Overflow mode. i want to use 1024 prescaler settings.

According to the datasheet of the controller i have to set \[b\]CS10 and CS12\[/b\] bits to use 1024 prescaler but the problem is OverFlow interrupt routine is never fired when 1024 or 256 prescaler is selected .

The Following code works just fine with Prescaler set to 8 or 64.

```
#include <inttypes.h>

volatile uint8_t sCount = 0;

void setup()
{
      Timer_one_16_init(); // configure the timer

      pinMode(13,OUTPUT);

}

void loop()
{
    // do nothing
}

void Timer_one_16_init(){

    TCCR1A = 0;

    // set the pre-scaler to 1024 (slowest)

    TCCR1B |= (1<<CS12)|(1<<CS10);

    // set the bottom / starting value

    TCNT1 = 0x00;

    // set Overflow interrupt

    TIMSK1 |= (1<<TOIE1);

    // enable global interrupt
    sei();

}

ISR(TIMER1_OVF_vect){

    sCount++;

    if (sCount == 60)
    {
        digitalWrite(13,!digitalRead(13));
        sCount = 0;

    }

}

```

i have no idea why this is happening. i have done everything which is given in the datasheet .

Am i doing something wrong ?

Thanks in advance

# Answer
> 2 votes
You must write the clock-select bits to the correct value. The simplest way to do it is to write the proper configuration into the `TCCR1B` register:

```
TCCR1B = (1<<CS12)|(1<<CS10);

```

In your program, you used `|=` instead of `=`. This doesn't write the bits appropriately: it only sets (writes to 1) the bits `CS12` and `CS10` but doesn't clear `CS11`. Since the Arduino core library sets the prescaler to 64 (`CS11` and `CS10` set), you end up with all the clock-select bits sets, in which case the timer is clocked by an external signal on the T1 pin. Not what you want.

---

**Edit**: Judging from the comments, it appears that at least dannyf did not understand my answer, I am therefore adding a clarification. There are two scenarios when you may want to tweak the control registers of a peripheral:

1. The peripheral is normally controlled by the Arduino core library, and you want to use it through that library. Typical case: you want to use a timer to `analogWrite()`, or the ADC to `analogRead()`, but you want to clock the peripheral at a frequency which is not the core's default.
2. You want to use a peripheral directly rather than through the Arduino core. Either you are going to “take it over” from the core, or it's a peripheral the core doesn't use in the first place.

In the first case, you should only touch those bits of the control registers that you must change. The other bits should be left alone, at whatever values the core has set them to. This is the approach of dannyf's answer.

In the second case, it is wiser to *not* rely on the core's default setting, and instead write *every single bit* of the control registers to the values appropriate for your application. This is the scenario of the original question, and the solution proposed in my answer.

For the particular case of this question, the `TCCR1B` register would be set to: ICNC1 = 0, ICES1 = 0, reserved bit = 0, WGM13 = 0, WGM12 = 0, CS12 = 1, CS11 = 0 and CS10 = 1. Combining those bits together gives the setting `TCCR1B = 0x05;`. However, for readability reasons, I prefer to write that value `(1<<CS12)|(1<<CS10)`, as in the question and in my original answer. Some people may prefer to explicitly write every bit, like

```
TCCR1B = (0<<ICNC1) | (0<<ICES1) | (0<<5)    | (0<<WGM13)
       | (0<<WGM12) | (1<<CS12)  | (0<<CS11) | (1<<CS10);

```

Whichever version you prefer is up to you. I personally don't find this latter version any easier to read.

: The values of `ICNC1` and `ICES1` are actually irrelevant in this case.

# Answer
> 0 votes
```
// set the pre-scaler to 1024 (slowest)

TCCR1B |= (1<<CS12)|(1<<CS10);

```

that approach presumes for the CS11 bit. in this case, if CS11 is set, the clock source is routed to the CKI pin, and if you don't apply a clock to that pin, the timer will never overflow.

Two options:

1) do it via two steps: set CS12/CS10 and clear CS11; or 2) do it in one step:

```
TCCR1B = (TCCR1B &~0x07) | (ps & 0x07);

```

ps would be whatever prescaler setting you wish to use.

the proposed solution below,

```
TCCR1B = (1<<CS12)|(1<<CS10);

```

is a typical beginner mistake, and a very dangerous one, as it clears other TCCR1B bits without the programmer even realizing it.

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


# Question
Title: FreeRTOS : Create Tasks but don't start Scheduler
I'm using FreeRTOs on Arduino for the first time. In my setup(), i would like to create my tasks but i have few more configuration to do after so i would like to create my tasks but don't start the scheduler immediately. This is my code currently with xTaskCreate and vTaskScheduler, but my code start the task immediately when they are created :

```
   //Create Tasks
   s1 = xTaskCreate(TaskAcquisition, NULL, configMINIMAL_STACK_SIZE, NULL, 2, &Acquisition);
   s2 = xTaskCreate(TaskStockage,NULL,configMINIMAL_STACK_SIZE + 200, NULL, 1, &Stockage);

.... Some more config

   Serial.println(F("Config finished"));

  //Check errors
  if(fifoData==NULL || fifoSpace == NULL || s1 != pdPASS || s2 != pdPASS){
  Serial.println(F("Creation error"));
  while(1);
  }
  Serial.println(F("Fifo and Tasks created"));

  //starting
  vTaskStartScheduler();

  //if the scheduler start the code don't came here
  Serial.println(F("Ram issue"));
  while(1);

```

Thanks for your help !

# Answer
> 1 votes
You need to `vTaskSuspend` the tasks immediately after creating them.

Then when you need a task to run you `vTaskResume` it.

---
Tags: task
---


title: Arduino I2C via USB Serial cable?

text:
# Question
Title: Arduino I2C via USB Serial cable?
An Arduino UNO is given. I want to establish an I2C communication channel between Arduino UNO and a Linux Machine which have only USB ports available to communicate with peripherals. Currently I can communicate with Arduino board via USB Serial cable (TXD and RXD which are on pins D0 and D1).

My question is: is there any way to use those pins as SCL/SDA to communicate via I2C with Arduino Board?

I am thinking that the only way to accomplish this is to buy an USB to I2C Adapter and connect to A4 (SDA) and A5 (SCL); but maybe I'm wrong.

I have also seen that way: https://gist.github.com/kraftb/8c0bbcc35a9778608d74. Basically to use an intermediate Arduino board.

# Answer
> 0 votes
With SoftwareI2CLibrary you can specify other pins, I haven't tested it with RX and TX.

I would recommend the USB serial interface is fast (2M baud) in perspective to that we are discussing a Arduino with a speed of 16MHz.

# Answer
> -1 votes
The Arduino contains a USB to UART adaptor (made from an ATMega16U2) which then connects to the UART pins 0/1. If you want a different protocol you will need a different adaptor that works with your desired protocol.

---
Tags: arduino-uno, i2c, wire-library
---


title: Arduino only sends HTTP 1.0 requests

text:
# Question
Title: Arduino only sends HTTP 1.0 requests
I'm trying to connect to an http server that uses HTTP 1.1, my problem is that even thought the request is in HTTP 1.1 format and the server does actually use HTTP 1.1(I tried it in a browser) it only responds with HTTP 1.0. I'm using this modified example of the web client, I updated the Ethernet library yesterday and for my server I'm using Node 8.4.0, I'm testing with google first even though I know the server can respond with HTTP 1.1.

Ethernet shield model: Han Run HR911105A 16/02

Arduino: Mega 2560

```
 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
  client.print("GET / HTTP/1.1\r\n");
  client.print("Host: www.google.com\r\n");
  client.print("Content-Type: application/x-www-form-urlencoded\r\n");
  client.print("Cache-Control: no-cache\r\n");
  client.print("\r\n");
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
}

```

With this I get the following response:

Thank you in advance

# Answer
> 0 votes
The device sending the request has no bearing on if it is HTTP 1.0 or 1.1. Only the content has an effect.

That and what is in the path - and I suspect that may be your problem: your are going through a squid proxy - and an old version at that. It is most likely that the proxy is changing the request to be a 1.0 request instead of a 1.1 request.

---
Tags: arduino-mega, http
---


# Question
Title: Determine whether a variable is of an arithmetic type
Is there a way to determine whether a variable is of an arithmetic type or not?

* arithmetic: integer, floating point numbers, boolean values
* not arithmetic: pointers, references; e.g. strings, and *probably* all other implementation- and user-defined types. However if someone for some reason defines `typedef int myInt` `myInt` should be considered arithmetic as well (because it is!)

In a normal C++ program I could use `std::is_arithmetic<T>::value`, where `T` is the type I need to check, but this doesn't seem to work in the Arduino environment. (Am I wrong? If it works, could someone please tell me how to use it?)

I imagine I could make a list of allowed types, e.g. as described in this answer to a similar question (I'm referring to the second option, the Alternative). But given that I don't need to exactly know the type of `T` I was wondering whether there is a more elegant and flexible solution...

# Answer
> Is there a way to determine whether a variable is of an arithmetic type or not?

no. end of the day, those are just bit pieces and it only makes sense to the computer with the right context. Another way to put it, the same bit pieces can and will mean different things under different situations.
> 1 votes

---
Tags: c++, data-type
---


# Question
Title: Servo library unable to control more than 11 servos
I am working on assembling the ROFI robot from Project Biped (http://www.projectbiped.com/prototypes/rofi) and I have not been able to run any arduino program as they will not function correctly.

To be more specific, when I attempt to run 12 servos on a single Arduino Mega, the servos twitch uncontrollably and do not move to the positions which are set in the program. At the same time the power light on the arduino mega blinks and does not turn solid (as opposed to if I use less than 11 servos when the pwr light is solid). I predict it might be the power source but after checking the batteries with the multimeter they check out to be fine (7.6 V). The circuit is pretty simple, I am using a servo shield connected to a 6V regulator connected in parallel to two 7.2 V 1350 mah LiPo batteries. The arduino is connected through the dc power jack to the same circuit in parallel.

Here is the code...

```
   #include <Servo.h>

// 0 Right Ankle (roll)
// 1 Right Lower Leg
// 2 Right Knee
// 3 Right Middle Leg
// 4 Right Upper Leg
// 5 Right Hip (roll)
//LEFT LEG JOINTS
// 6 Left Ankle (roll)
// 7 Left Lower Leg
// 8 Left Knee
// 9 Left Middle Leg
// 10 Left Upper Leg
// 11 Left Hip (roll)

int c=0;

Servo rightAnkle;
Servo lowerLeg;
Servo rightKnee;
Servo rightMiddleLeg;
Servo rightUpperLeg;
Servo rightHip;
Servo leftAnkle;
Servo leftLowerLeg;
Servo leftKnee;
Servo leftMiddleLeg;
Servo leftUpperLeg;
Servo leftHip;

void setup(){
  rightAnkle.attach(0);
  lowerLeg.attach(1);
  rightKnee.attach(2);
  rightMiddleLeg.attach(3);
  rightUpperLeg.attach(4);
  rightHip.attach(5);
  leftAnkle.attach(6);
  leftLowerLeg.attach(7);
  //leftKnee.attach(8);
  //leftMiddleLeg.attach(9);
  leftUpperLeg.attach(10);
  leftHip.attach(11);
}

void loop(){
  rightAnkle.write(90);
  lowerLeg.write(90);
  rightKnee.write(90);
  rightMiddleLeg.write(90);
  rightUpperLeg.write(90);
  rightHip.write(100);
  leftAnkle.write(90);
  leftLowerLeg.write(90);
  leftKnee.write(90);
  leftMiddleLeg.write(90);
  leftUpperLeg.write(90);
  leftHip.write(90);
}

```

# Answer
It sounds to me like you're exceeding the current limits of your power supply. Add up the current drawn by your servos (and their controller(s), and also the current drawn by your Arduino and any other circuits you have. I bet you'll find that at 12 servos, you go over the current limit of your regulator. You might need a higher current regulator or a second one.
> 1 votes

# Answer
> Servo library unable to control more than 11 servos

because the library isn't written to control more.

this approach (https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/) can drive arbitrary number of servos over multiple ports / pins.

it is written for a pic but it has links to AVR implementation as well.
> 0 votes

---
Tags: arduino-mega, servo
---