# Question
Title: Saving EEPROM after programming on Arduino uno
I am using an Arduino Uno, and I use the EEPROM to store some presets. It works fine. But, when I reprogram the Arduino, the EEPROM gets wiped out. Is there a way to prevent this, and have the EEPROM not change after the Arduino is programmed?

I am using a USBtinyISP programmer.

Thank you very much for your help, and advance.

Here is the verbose result of my programming:

```
Sketch uses 5,298 bytes (16%) of program storage space. Maximum is 32,256 bytes.
Global variables use 286 bytes (13%) of dynamic memory, leaving 1,762 bytes for local variables. Maximum is 2,048 bytes.
/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/bin/avrdude -C/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cusbtiny -Uflash:w:/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
        Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
        Copyright (c) 2007-2014 Joerg Wunsch

        System wide configuration file is "/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
        User configuration file is "/Users/fed/.avrduderc"
        User configuration file does not exist or is not a regular file, skipping

        Using Port                    : usb
        Using Programmer              : usbtiny
avrdude: usbdev_open(): Found USBtinyISP, bus:device: 006:003
        AVR Part                      : ATmega328P
        Chip Erase delay              : 9000 us
        PAGEL                         : PD7
        BS2                           : PC2
        RESET disposition             : dedicated
        RETRY pulse                   : SCK
        serial program mode           : yes
        parallel program mode         : yes
        Timeout                       : 200
        StabDelay                     : 100
        CmdexeDelay                   : 25
        SyncLoops                     : 32
        ByteDelay                     : 0
        PollIndex                     : 3
        PollValue                     : 0x53
        Memory Detail                 :

                                 Block Poll               Page                       Polled
          Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
          ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
          eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
          flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
          lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
          signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

        Programmer Type : USBtiny
        Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
        To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex"
avrdude: writing flash (5298 bytes):

Writing | ################################################## | 100% 7.80s

avrdude: 5298 bytes of flash written
avrdude: verifying flash memory against /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
avrdude: load data flash data from input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
avrdude: input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex contains 5298 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 4.98s

avrdude: verifying ...
avrdude: 5298 bytes of flash verified

avrdude done.  Thank you.

```

# Answer
> 1 votes
You can change the fuses for `Atmega328` to preserve `EEPROM` during chip erase (for `ISP` programming). Basically, if you are using `USBTiny` connected to the `UNO` by `3x2` pin header, you are using `ISP programming`. Which means chip erase erases also `EEPROM` if fuse `EESAVE` is `1` (unprogrammed).

Uploading over the **`Arduino bootloader`** (it means you have the `UNO` connected directly into the computer and there is no other device like `USBTiny`). The `EEPROM` should be preserved then.

---
Tags: arduino-uno, eeprom, programmer
---


title: Writing serial data on a pin on Arduino

text:
# Question
Title: Writing serial data on a pin on Arduino
I want to write some data (GPS) to a digital port on Arduino. As far as I understand sending data via a pin as if it were USB is possible. But I don't know what function to use. digital.Write doesn't expect any data or strings. How do I write serial data on to a digital pin

# Answer
Using the arduino library "software Serial" (https://www.arduino.cc/en/Reference/SoftwareSerial) you can use any pin to write/read serial data.
> 2 votes

# Answer
The Aruduino Uno uses an ATmega328P which only has 1 hardware UART to help the software communicate serially with the outside world. If you are already using this hardware resource (for example through the normal Arduino serial library), it is unavailable to talk to a 2nd external device. In such a case you can emulate a UART in software using this Software Serial Library in exchange for some processor time (that is, using a software emulated serial port will slow down your program's execution).
> 0 votes

---
Tags: serial, communication
---


title: Read and parse continuous serial stream

text:
# Question
Title: Read and parse continuous serial stream
I'm trying to read in and parse a message in the form of `X123987` continuously streaming into a serial port. There are no new lines or control characters other than the `X` which marks the beginning/end of the message. The message contains two, three-character components, ex: `123`, and `987`. I'm trying to copy bytes as their read into a char array, and then on the control character, return the result, but while this compiles, I don't get any output, and it crashes constantly.

```
#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11);

char _byte_received;
char _buffer[10];
char _value[10];

bool OnReceive()
{
  if (RS485Serial.available())
   {
    digitalWrite(13, HIGH);
      _byte_received = RS485Serial.read();
      if (_byte_received == 'X') {
        strcpy(_value, _buffer);
        memset(_buffer, 0, 10);
        return true;
      } else {
        strcat(_buffer, _byte_received);
        return false;
      }
    digitalWrite(13, LOW);
   } else {
    return false;
   }
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(13, OUTPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.write(_value);
    Serial.println("");
  }
}

```

Output:

```
Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:

```

I expect to see `value: 123987`

# Answer
In `OnReceive`, you are concatening a string with a char. This may be the cause of the resets.

As a side note, you don't really need to use `strcat`, `strcpy` and other `str` functions. You can make your sketch lean by accesing the arrays directly, like this:

```
char _buffer[10];
int index = 0;

bool OnReceive()
{
  bool status = false;
  if (RS485Serial.available())
  {
    digitalWrite(Pin13LED, HIGH);
    char _byte_received = RS485Serial.read();
    if (_byte_received == 'X') {
      _buffer[index] = 0; // Mark the end of string.
      index = 0;
      status = true;
    } else {
      _buffer[index++] = _byte_received;
      // ToDo: check for overflow;
    }
    digitalWrite(Pin13LED, LOW);
  }

  return status;
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Receive);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.print(_bufer);
    Serial.println("");
  }

```
> 1 votes

---
Tags: serial
---


# Question
Title: Comparison of Board Shape between Arduino MEGA and Arduino DUE
I'm using KiCAD to design boards, and while it has a lot of Arduino templates, it doesn't have one for the Arduino Due. Now, I've did some searching, and it looks like the Arduino MEGA is very similar to the Arduino DUE, not the specifications, but the number of I/O pins and the overall shape of the board. I couldn't find a straight answer, so I decided to ask here: Can the template of the Arduino MEGA be used as a template for the Arduino DUE when designing custom 'shields' and such based on the number of I/O pins and overall layout?

# Answer
> 2 votes
> The Due has the same footprint as the Mega 2560.

source

---
Tags: arduino-mega, arduino-due, shields, pcb-design
---


# Question
Title: Buzzing on computer speakers when LEDs are on
I have an Arduino Nano connected via USB to a Mac Mini. When the LEDs come on, an external speaker connected to the Mini starts to hum/buzz quite loudly. If the LEDs are turned off, the buzz stops.

The speaker and the Mac mini are both powered independently, and are plugged into one wall socket, while the 5V power supply to the LEDs and the Nano is plugged into a different socket (of the same outlet).

What could be causing the buzz and what are the possible remedies?

# Answer
If this is the same project you described in this question(readers: "112 WS2811s in series" causing interference), your external speaker may not be filtered very well against energy radiated by nearby un-shielded wiring. Try a pair of headphones in place of the speaker - does it also buzz? If not, the speaker (system) is probably picking up the interference. If so, the pickup is probably within or near the Mac mini.

You could try a few simple solutions (or at least tests that might narrow the problem):

* shielded audio cable from the Mac mini to the speaker;
* shielding the speaker enclosure and grounding the shield;
* shielding the connections to the LED string (obviously shielding the LED string itself is likely to be aesthetically undesirable);
* separating the speaker from the LED strip by more distance;
* powering the mini from batteries - at least long enough to learn whether the power wiring might be involved.
> 1 votes

---
Tags: power, led, audio
---


title: Write PWM with only 8 bit? (Timer2)

text:
# Question
Title: Write PWM with only 8 bit? (Timer2)
I have a problem with the Servo library.

I need to read a PPM signal and create a PWM signal of each channel. The problem is that PPM has a higher resolution than PWM so I want to use the 16 bit Timer1 for reading PPM. However the Servo library that writes the PWM signal also uses Timer1.

Is it possible to generate a PWM signal with 8 bit / Timer2? And has someone made an example, or an explanation about, how to do that?

# Answer
Yes, Arduino Servo library uses Timer1 (and other ones, depending on Arduino boards) to manage FastPWM via software interrupts. Timer2 is used by tone() function: be careful if you are using that function.

A good **example using Timer2** to generate PWM is the **Infrared remote library for Arduino**. If IR\_USE\_TIMER2 is defined it will use Timer2. The key code is at IRremote.cpp where the ISR is managed.
> 2 votes

# Answer
Here is a simple example from my page about timers of using Timer 2 to output a square wave of 50 kHz:

```
const byte LED = 3;  // Timer 2 "B" output: OC2B

const long frequency = 50000L;  // Hz

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

  TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2B on compare
  TCCR2B = bit (WGM22) | bit (CS21);         // fast PWM, prescaler of 8
  OCR2A =  ((F_CPU / 8) / frequency) - 1;    // zero relative
  OCR2B = ((OCR2A + 1) / 2) - 1;             // 50% duty cycle
  }  // end of setup

void loop()
  {
  // do other stuff here
  }

```
> 2 votes

# Answer
> Is it possible to generate a PWM signal with 8 bit / Timer2?

yes. I implemented multiple approaches, some on avrs and some on pics but the basic principles are the same: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

that post provided a list of links to other implementations - one of them off a timer 2 on avr.
> 1 votes

---
Tags: pwm, timers
---


title: SD card fail of initializing

text:
# Question
Title: SD card fail of initializing
I have an Arduino Mega and a catalex card reader which yesterday worked, but today I tried another time and the sd card where not detected, I am using the example code from Arduino website for the card info. I have tried conecting the reader to the SPI ports in the middle of the board and it was not solved. Anyone has another idea of what can be failing?

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

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
// MKRZero SD: SDCARD_SS_PIN
const int chipSelect = 10;

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
  }

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {

}

```

# Answer
Add these Two Lines for better initialization of SD card:

```
void setup{
    pinMode(10, OUTPUT); // change this to 53 on a mega(don't follow this!!)
    digitalWrite(10, HIGH); // Add this line
}

```

Check this link, may be useful to your current problem.
> 1 votes

---
Tags: arduino-mega, sd-card
---


title: Arduino, Serial and wrapper class

text:
# Question
Title: Arduino, Serial and wrapper class
I am working on an Arduino project, that would use HardwareSerial object reference stored in a class and call methods on it. However, there is problem with writing output using the reference.

Minimal use case to demonstrate behavior is in following files:

## main.ino

```
#include <Arduino.h>
#include "testclass.h"

TestClass testClassInstance(Serial);

void setup() {

}

void loop() {
    testClassInstance.print("Hi There\r\n");
    delay(1000);
}

```

## testclass.h

```
#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <Arduino.h>

class TestClass {
public:
    TestClass(HardwareSerial &serial);
    void print(const char * text);

private:
    HardwareSerial _serial;
};

#endif

```

## testclass.cpp

```
#include "testclass.h"

TestClass::TestClass(HardwareSerial &serial) : _serial(serial) {
    _serial.begin(9600);
    _serial.print("Initializing\r\n");
}

void TestClass::print(const char *text) {
    _serial.print(text);
}

```

After reset, there are only two characters sent: "In"

In the example above, initialization is done before setup() method and Serial's state is probably reset before calling it. Having changed that to dynamic allocation in setup method did not change this behavior as well.

## modification of main.ino

```
TestClass *testClassInstance;

void setup() {
  testClassInstance = new TestClass(Serial);
}

```

There might be problem with passing the reference to Serial, but in that case I would expect to not have any output at all.

Any help is greatly appreciated.

# Answer
> 2 votes
You can't do complex tasks (or anything that relies on the Arduino API in any form) in your constructor. Simply because that all gets called *before* the Arduino API initializes, and in so doing the serial port gets disabled.

Instead you should do your complex operations and API-based operations in `.begin()`, which is why 99.99% of all libraries (*including HardwareSerial*) have a `.begin()` method.

# Answer
> 0 votes
I have debugged deeper and the problem was somehow passing HardwareSerial to constructor as parameter with `HardwareSerial &serial`.

When changing it to pointer `HardwareSerial *serial` and using access via pointer-type variable, everything works.

Many thanks for suggestions.

---
Tags: serial
---


title: Arduino DUE Interrupt 1MHz

text:
# Question
Title: Arduino DUE Interrupt 1MHz
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks.

```
volatile boolean l = false;

void TC6_Handler()
{
    TC_GetStatus(TC2, 0);
    digitalWrite(41, l = !l);
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk((uint32_t)irq);

    TC_Configure(tc, channel,
    TC_CMR_WAVE |
    TC_CMR_WAVSEL_UP_RC |
    TC_CMR_TCCLKS_TIMER_CLOCK1|
    TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

    TC_SetRA(tc, channel, 1); //50% high, 50% low
    TC_SetRC(tc, channel, 1);

    PIO_Configure(PIOC,
    PIO_PERIPH_B,
    PIO_PC25B_TIOA6,
    PIO_DEFAULT);

TC_Start(tc, channel);

}

void setup(){
pinMode(41,OUTPUT);
startTimer(TC2, 0, TC6_IRQn);
}

void loop(){
}

```

# Answer
I'm not 100% certain without my Due in front of me to test this, but as far as I can see, you are configuring your clock to run at 42MHz with "TC\_CMR\_TCCLKS\_TIMER\_CLOCK1" and are getting the timer to trigger when the count is "1" with "TC\_SetRC(tc, channel, 1);", which would give you 42MHz, not 4MHz.

Since the clock timer still increments during the TC6\_Handler() function, I'm guessing that the interrupt triggers a second time before it has exited the function the first time causing a hang.

Try changing your code to "TC\_SetRC(tc, channel, 42000000 / 4000000);" to see if that works. Your interrupt will still be triggered every 10 ticks of the timer which will only give you 20 ticks of the CPU clock to do your work and exit. I suspect this may still be too little time to exit before the next interrupt is triggered. If you still don't get the result you want, try reducing the frequency considerably to see if your timer is actually getting configured correctly. I don't think you can get exactly 4MHz as the Due timer frequencies are not divisible by 4000000, unless my brain is a little fuzzy this morning and I'm missing something obvious...

If you do need to optimise the code inside your handler so it can run faster, let me know and I'll post some ideas when I can get near my Due and my source code for reference.

You could always check out this link that I used when I needed to understand how to set up a timer for my own projects: http://2manyprojects.net/timer-interrupts Should that link go dead before you have a chance to read up, this is the example source from that page I modified for my own purposes:

```
// These are the clock frequencies available to the timers /2,/8,/32,/128
// 84Mhz/2 = 42.000 MHz
// 84Mhz/8 = 10.500 MHz
// 84Mhz/32 = 2.625 MHz
// 84Mhz/128 = 656.250 KHz
//
// 42Mhz/44.1Khz = 952.38
// 10.5Mhz/44.1Khz = 238.09
// 2.625Hmz/44.1Khz = 59.5
// 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds)

// 84Mhz/44.1Khz = 1904 instructions per tick
const int led_pin = 13;
int state = false;
int interruptCtr = 1;
int S = 0;

void setup()
{
  pinMode(led_pin, OUTPUT);
  /* turn on the timer clock in the power management controller */
  pmc_set_writeprotect(false);       // disable write protection for pmc registers
  pmc_enable_periph_clk(ID_TC7);     // enable peripheral clock TC7

  /* we want wavesel 01 with RC */
  TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
  TC_SetRC(TC2, 1, 131200);
  TC_Start(TC2, 1);

  // enable timer interrupts on the timer
  TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
  TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

  /* Enable the interrupt in the nested vector interrupt controller */
  /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */
  NVIC_EnableIRQ(TC7_IRQn);
}

void loop()
{
  // do nothing timer interrupts will handle the blinking;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERRUPT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TC7_Handler()
{
  // We need to get the status to clear it and allow the interrupt to fire again
  TC_GetStatus(TC2, 1);
  state = !state;
  digitalWrite(led_pin, state);

  if( interruptCtr++ >= 6 )
    {
     interruptCtr = 1;
     S = !S; // are we flashing S or O
     if( S ) // set time till next interrupt
        TC_SetRC(TC2, 1, 131200); // 131200 / 656000 = .2 seconds
     else
        TC_SetRC(TC2, 1, 656000); // 656000/ 656000 = 1 second
    }
}

```
> 2 votes

# Answer
When I'm working with timers on my Due I always keep my code low level so my solution for your problem would be:

```
// These are the clock frequencies available to the timers /2,/8,/32,/128
// 84Mhz/2 = 42.000 MHz
// 84Mhz/8 = 10.500 MHz
// 84Mhz/32 = 2.625 MHz
// 84Mhz/128 = 656.250 KHz
//
// 42Mhz/44.1Khz = 952.38
// 10.5Mhz/44.1Khz = 238.09
// 2.625Hmz/44.1Khz = 59.5
// 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds)

#define SPEED(x) 42 * x

// 84Mhz/44.1Khz = 1904 instructions per tick
const int led_pin = 13;  //PB27
int interruptCtr = 1;
int S = 0;

void setup()
{

    pmc_set_writeprotect(false);       // disable write protection for pmc registers /**always the first thing to do*/

    // Enable pin 13 with direct port manipulation
    REG_PIOB_PER = 1<<27;
    REG_PIOB_OER = 1<<27;
    REG_PIOB_OWER = 1<<27;

    /* turn on the timer clock in the power management controller */
    pmc_enable_periph_clk(ID_TC0);     // enable peripheral clock TC0

    //Enable interrupt in NVIC before starting interrupt
    NVIC_EnableIRQ(TC0_IRQn);

    //Wavesel on rising edge with timer clock1 (42MHz)
    REG_TC0_CMR0 = TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1;

    //Enabel RC compare interrupt
    REG_TC0_IER0 = TC_IER_CPCS;

    //Set the timer register c
    REG_TC0_RC0 = SPEED(200000);  //SPEED() converts us to clock ticks

    //Start timer
    REG_TC0_CCR0 = TC_CCR_SWTRG | TC_CCR_CLKEN;
}

void loop()
{
  // do nothing timer interrupts will handle the blinking;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERRUPT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TC0_Handler()
{
  // We need to get the status to clear it and allow the interrupt to fire again
  REG_TC0_SR0;

  //get curretn pin state (REG_PIOB_ODSR & PIO_PB27) and invert it. AND this result with the pin bit to only set pin 27 to high/low
  REG_PIOB_ODSR = (~(REG_PIOB_ODSR & PIO_PB27)) & PIO_PB27;

  if( interruptCtr++ >= 6 )
  {
    interruptCtr = 1;
    S = !S; // are we flashing S or O
    if( S ) // set time till next interrupt
      REG_TC0_RC0 = SPEED(200000); //0.2 seconds
    else
      REG_TC0_RC0 = SPEED(1000000); //1 second
    }
}

```

With this code you should be able to increase the switching frequency to theoretically 42MHz. But due to the time the interrupt needs to run it will be reduced to something about 10MHz or less but even this is much higher than your 334KHz.
> 1 votes

# Answer
This works

```
int unsigned A[2500];
int unsigned S;
void setup()
{
  Serial.begin(9600);
  //pinMode(30, OUTPUT);
  REG_PIOB_OWER = 0xFFFFFFFF;     // Enable PORT B
  REG_PIOB_OER =  0xFFFFFFFF;     // Set PORT B as output port
  REG_PIOD_OWER = 0xFFFFFFFF;     // Enable PORT D
  REG_PIOD_OER =  0xFFFFFFFF;     // Set PORT D as output port
  REG_PIOC_OWER = 0xFFFFFFFF;     // Enable PORT C
  REG_PIOC_OER =  0xFFFFFFFF;     // Set PORT C as output port
  /* turn on the timer clock in the power management controller */
  pmc_set_writeprotect(false);     // disable write protection for pmc registers
  pmc_enable_periph_clk(ID_TC7);   // enable peripheral clock TC7

  /* we want wavesel 01 with RC */
  TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
  TC_SetRC(TC2, 1, 42);// 1 MHz
  TC_Start(TC2, 1);

  // enable timer interrupts on the timer
  TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
  TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

  /* Enable the interrupt in the nested vector interrupt controller */
  /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */
  //NVIC_EnableIRQ(TC7_IRQn);
}

void loop()
{
int unsigned MSBs = 0;
int unsigned LSBs = 0;
int unsigned C = 0;
int unsigned B = 0;
int unsigned i = 0;
//int unsigned long B1 = 0;
//int unsigned B2 = 0;
int unsigned MSBMask = B11111111;
MSBMask << 8;

 //Serial.println(base, DEC);
//delay(100);
 //Serial.println(ratio, DEC);
//delay(100);
for(i=0; i<2500; i++)
{
  //C = 20000/2*sin(2*PI*(90000/0.0025*i+10000)*i);
  C = 20000*sin(2*PI*i);
 // A[i] = sin(2*PI*(10+90/25*i)*1/1000);
   //A[1] = sin(2*PI*(10+90/25*i)*1/1000);

  MSBs = C >> 8;
  LSBs = C & MSBMask;
   //Serial.println(C, BIN);
  //Serial.println(MSBs, BIN);
 // Serial.println(LSBs, BIN);
MSBs = MSBs << 12;
LSBs = LSBs << 1;
B = MSBs+LSBs;
A[i] = B;
 //Serial.println(B, BIN);
 //Serial.println(A[i], BIN);
//delay(100);
}

NVIC_EnableIRQ(TC7_IRQn);
while(1){}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// INTERRUPT HANDLERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void TC7_Handler()
{
 TC_GetStatus(TC2, 1);// We need to get the status to clear it and allow the interrupt to fire again
  //int i=0;
  REG_PIOD_CODR = 0x1 << 9;// clear pin 30 on due
 // REG_PIOD_CODR = 0x1 << 10;// clear pin 32 on due

REG_PIOC_ODSR = A[S];//set outout pins to array entry

REG_PIOD_SODR = 0x1 << 9;// set pin 30 on due, commanding DAC to take commended Analog output,
   S++;
   if(S>2500){S=0;}

}

```
> 0 votes

# Answer
> I need to update with freq 1MHz. ...No luck.

no kidding.

think about interrupt overhead. and how much it takes away the processing power if you interrupt at 1 million times a second.

think DMA if available on your chip. If not, think a faster chip or compromise on your 1Mhz expectation.
> 0 votes

---
Tags: arduino-due, interrupt
---


title: analogRead() hangs

text:
# Question
Title: analogRead() hangs
With this code I try to send a measurement over 443MHz using RadioHead. All parts work but when combined they fail. This chip used is an ATtiny85.

The function 'measure' torpedoes the entire program. If it is used, it will compile but it will never run Setup or Loop. I know this because I use a Logic Analyzer and Software Serial. I can see the Serial Port, PB1, hanging high.

I would like to know what is so wrong about function `measure` that it undermines all code..

```
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <RH_ASK.h>   // local libs at
#include <powernap.h> // /home/thijs/.platformio/lib

#define TICKLE_ID 192

#define SENSOR1_PIN 2
#define SENSOR1_PWR 4
#define SENSOR2_PIN -1
#define SENSOR2_PWR -1

#define SOFTWARE_SERIAL_TX_PIN 1
#define SOFTWARE_SERIAL_RX_PIN -1

#define RADIOHEAD_BAUD 2000
#define RADIOHEAD_TX_PIN 0
#define RADIOHEAD_RX_PIN -1

struct tickle {
  uint16_t id = TICKLE_ID;
  uint16_t value1;
  uint16_t value2;
};

Napper napper;
SoftwareSerial mySerial(SOFTWARE_SERIAL_RX_PIN, SOFTWARE_SERIAL_TX_PIN);
RH_ASK driver(RADIOHEAD_BAUD, RADIOHEAD_RX_PIN, RADIOHEAD_TX_PIN);

void senddata(int hygro) {
  mySerial.print("Senddata");
  struct tickle package; // make a Tickle package
  package.id = TICKLE_ID; // hard-coded device ID
  package.value1 = 0; // any positive int up to 2^16
  package.value2 = hygro; // any positive int up to 2^16
  driver.send((uint8_t *)&package, sizeof(package));
  driver.waitPacketSent(); // wait for it ~Barney
}

int measure() {
  mySerial.print("Measure");
  pinMode(SENSOR1_PWR, OUTPUT); // enable sensor
  pinMode(SENSOR1_PWR, HIGH); // turn on sensor
  delay(100); // wait for sensor to settle

  int i; // int for counter
  int data = 0; // data container

  for (i = 0; i < 5; i++){ // cumulate 5 measurements
    data = data + analogRead(SENSOR1_PIN);
  }

  data = data / 5; // avg of measurements
  pinMode(SENSOR1_PWR, LOW); // turn off sensor
  pinMode(SENSOR1_PWR, INPUT); // disable sensor
  mySerial.print(data);
  return data; // return avg measured value
}

void setup() {
  mySerial.begin(600); // 600 baud serial
  mySerial.print("Setup"); // logging the start
  driver.init(); // initialize the RadioHead library
  napper.setup_sleep(); // initialize the Napper library
}

void loop() {
  mySerial.print("Loop"); // start of loop
  int measurement = measure(); // measure data
  senddata(measurement); // send data
  napper.napminutes(1); // deep sleep for 1 minute
}

```

**\[EDIT\]**
I thought the problem to be this, and then to be that. This is how I debug, I start somewhere and work my way back. Currently it looks like my own library PowerNap is the culprit, I have tested with other Sleep code and it works. I can only be sure after more tests and isolated code running.

# Answer
Interesting question but nothing seems wrong in the `measure()` function unless the mistake `pinMode` is used instead of `digitalWrite`. I suggest in the for loop keep a slight interval between the measurements. lets say about 50ms. if the problem still presets lets start the debugging. set a serial message in every critical point and pin point the exact location the code hangs.
> 1 votes

# Answer
> analogRead() hangs

you started this journey thinking a particular routine (measure()) is the problem and you now are blaming analogRead() to be the source of your ills.

it will serve you much better for you to step back and ask yourself if your thought process is at fault here.

while you haven't provided much information on what it is that's not working, you have provided more than enough information to suggest that the issue is not measure() nor analogRead().

you may find this hard to understand now but debugging is far less about convincing yourself where the wrongs are. instead, it is about convincing yourself what you think right is wrong.
> 0 votes

# Answer
Personally I think its a memory size issue, but the only real changes you need to make to measure is change pinMode to digitalWrite (as you have spotted) and personally I think you should remove the other pinMode statements and leave the pin setup the whole time, unless you are using it for something else.

```
int measure() {
  mySerial.println("Measure");
  pinMode(SENSOR1_PWR, OUTPUT); // enable sensor
  digitalWrite(SENSOR1_PWR, HIGH); // turn on sensor
  delay(100); // wait for sensor to settle

  int data = 0; // data container

  for (int i = 0; i < 5; i++){ // cumulate 5 measurements
    data = data + analogRead(SENSOR1_PIN);
  }

  data = data / 5; // avg of measurements
  digitalWrite(SENSOR1_PWR, LOW); // turn off sensor
  // pinMode(SENSOR1_PWR, INPUT); // disable sensor - If you do this the "sensor" floats.
  mySerial.println(data);
  return data; // return avg measured value
}

```
> -1 votes

---
Tags: c++, atmel, attiny85
---


# Question
Title: Programming ATmega328p on external board with FT232R
I am making a 100W AC-DC linear power supply, for which I want to show output Voltage and Output current on LCD display. I already used shunt resistor and voltage resistor to bring both values to analog pins on my ATmega328P in DIP socket, which has an Arduino bootloader on it. I want to programm my ATmega328P on the board without taking it off everytime and putting it into Arduino UNO board to just programm it and put it back, so how can I integrate a programmer onto board? I intend to use the FT232R ic, which I think would work more than fine for this application. On finished product I want to have a USB connector on the case just to update/correct the software.

# Answer
I suggest use ICSP(In circuit serial programming) feature of the Atmega 328 chip. Grab the .hex file from the arduino IDE and a USB ISP external programmer to write the program to the chip. Here you will have to use a 6 pin header on your custom board to take out the pins which are used to program the atmega.
> 1 votes

# Answer
I use an FTDI cable with my home-builds. Then the board doesn't need the interface hardware (it's in the cable) and the MCU doesn't need to be removed.

I put a 6-pin male header on the board to match 6-pin female socket my cables come with. The header is direct-wired to the Tx, Rx, +5, & Gnd pins. If you have an auto-reset circuit on your board, connect the RTS pins to that. Then, reprogramming is as simple as connecting your board and clicking 'upload'. Without the auto-reset circuit, you just hold the reset button while you click upload, count 3, and release the reset.

Update:

You can do it with only 4 pins on the board. If I understand correctly, just wire Tx, Rx, +5 & Ground of the Arduino to the 4 pins and replace the Arduino-end socket on the FTDI cable with one wired to match however you wired the board. If you use **L**-shaped male pins, they'll lie parallel to the board and won't add any height (above what is already on it).
> 0 votes

---
Tags: usb, atmega328, ftdi
---


# Question
Title: Millisecond timestamp (13 digits) in Arduino
How can I store a 13 digits int in Arduino?

For example, current timestamp is: 1500666822235

An uint32\_t can only hold 10 digits max.

64 bits integer does not seem to be supported on RFduino.

# Answer
**18446744073709551615**
That 20 digits. It is the maximum value of a `uint64_t`. Even the Arduino Uno can use the `uint64_t`. Perhaps the `Serial.print` does not support it, but the compiler supports it.

Which processor does your RFduino have ?

Where does the timestamp come from ? Perhaps you are asking the wrong question. Perhaps this is a xy-problem.
> 5 votes

# Answer
> How can I store a 13 digits int in Arduino?

create a multi-byte type.

a 40-bit (32+8 bits), or a 96-bit (32+32+32) would hold a ton.

or BCD.
> 3 votes

---
Tags: programming, c
---


title: Arduino: Connect UNO to A7 AI Thinker

text:
# Question
Title: Arduino: Connect UNO to A7 AI Thinker
I just cannot connect or send AT command from my UNO to A7 AI Thinker module. This is the connection:

```
UNO    ->    A7
TX     ->    RX
RX     ->    TX
USB    ||    5V    -> External Power Supply
GND    ->    GND

```

Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

Different case if I use USB TTL to A7

```
USB TTL   ->   A7
VCC (5v)  ->   5V
GND       ->   GND
TX        ->   RX
RX        ->   TX

```

Then it is OK, I can send all AT command, SMS, Call, etc from the serial monitor.

Just what is happening with UNO? Does my UNO RX TX Faulty? How to check it?

# Answer
> 0 votes
> Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

The problem is with your connections to the Uno. Although it seems wrong, the correct connection when you're using the Uno as a USB-serial adapter to communicate with the A7 AI Thinker module from Serial Monitor is:

```
Uno                A7
TX (pin 1)   ->    TX
RX (pin 0)   ->    RX

```

The RX and TX markings on the Uno refer to the pins on the ATmega328P microcontroller. But you're not using that microcontroller, you're communicating between the USB-serial chip on the Uno and the A7. The RX line of the USB-serial chip is connected to the TX pin of the ATmega328P and thus to pin 1, the TX pin of the USB-serial chip is connected to the RX pin of the ATmega328P and thus to pin 0. For this reason the connection between the Uno and A7 shown above are actually an RX-TX, TX-RX connection between the USB-serial chip and the A7.

If you were communicating between the ATmega328P on your Uno and the A7 then the connections you used would have been correct.

---
Tags: gps, gsm
---


# Question
Title: Sending string over serial to nodejs app. Why does it get chunked?
I'm sending a string from my sketch over Serial port as follows:

```
Serial.println(F("Found ILI9341 LCD driver"));

```

On the other side, I have a nodejs app using the serialport npm module, with something like this:

```
var SerialPort = require('serialport')
var serialPort = new SerialPort('/dev/ttyACM1', {
  baudrate: 9600
})

// it opens the connection and register an event 'data'
serialPort.on('open', function () {
  console.log('Communication is on!')
})

// when your app receives data, this event is fired
// so you can capture the data and do what you need
serialPort.on('data', function (data) {
  console.log('data received: ' + data)
})

```

Communication works, but on nodejs side I get the output chunked, as if it had line breaks, like this:

```
Communication is on!
data received: Pa
data received: int!
data received:

data received: Fou
data received: nd I
data received: LI93
data received: 41 L
data received: CD d
data received: rive
data received: r

```

Why does this happen?

# Answer
> 5 votes
It seems I needed to add a `parser` to SerialPort nodejs module, in order to specify how the input should be treated.

I changed my code to this:

```
var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline

var serialPort = new SerialPort('/dev/ttyACM0', {
  baudrate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
  console.log('data received: ' + data)
})

serialPort.on('open', function () {
  console.log('Communication is on!')
})

```

Basically, I'm specifying a `Readline` parser, which matches with the `Serial.println` function calls on my arduino sketch. Now the console output works as expected:

```
Communication is on!
data received: Found ILI9341 LCD driver

```

---
Tags: serial, communication, string, node.js
---


title: SPI Arduino communication

text:
# Question
Title: SPI Arduino communication
I want two Arduino cards to communicate with each other using SPI and move the servo motor with potentiometer as a result. I've done the pre-burning led or the led burning led on the SPI, I am waiting for your help. I will give the code below.

MASTER Arduino code

```
#include <SPI.h>
/* SPI haberleşmesinde Master olarak görev yapan Arduino kodu */
const int pot=A0;   // Servo kontrol potunu bağlayacağımız analog giriş.
int potdurum=0;
int pos = 0;
const int SSpini = 8;
/* Slave görevindeki Arduino'nun seçilmesi için 8 bumaralı pin SS olarak belirlendi */

void setup()
{
  Serial.begin(9600);
  pinMode(SSpini, OUTPUT);
  /* SS pini çıkış olarak ayarlandı */
  digitalWrite(SSpini, HIGH);
  /* Slave olan Arduino başlangıçta haberleşmeye geçmemesi için SS pini HIGH yapıldı */
  SPI.begin();
  /* SPI haberleşmesi başlatıldı */
}

void loop()
{
  potdurum=analogRead(pot);
  pos= map(potdurum,0,1023,0,180);//Pottan okunan değeri  180e oranlıyoruz.
  veriGonder(pos,SSpini);
}

/* SPI üzerinden veri göndermek için yazılmış fonksiyondur */
void veriGonder(int veri, int SSpini)
{
  digitalWrite(SSpini, LOW);
  /* Diğer Arduino'nun veri dinlemeye başlaması için SS hattını LOW düzeyine çekmeliyiz */
  delay(1);
  /* Kısa bir süre bekleyelim */
  Serial.print("Aci Degeri = ");
  Serial.println(veri);
  delay(15);
  SPI.transfer(veri);
  /* veri karakteri diğer Arduino'ya yollandı
  * Fonksiyon diğer arduino'dan gelen veriyi vermektedir
  * Geri gelen veri LEDDurumu değişkeninde tutulmuştur
  * Bu değişken Seri port üzerinden bilgisayardaki Serial monitöre yollanmıştır
  */
  digitalWrite(SSpini, HIGH);
  /* Haberleşmeyi bitirmek için pin LOW konumuna çekilmiştir */
}

```

SLAVE Arduino code

```
#include <Servo.h>
int i = 0;
Servo myservomotor;

void setup()
{
  Serial.begin(115200);
  myservomotor.attach(3);
  pinMode(MISO, OUTPUT);
  pinMode(SS , INPUT);
  /* MISO pini OUTPUT, SS pini INPUT olarak ayarlandı */

  SPCR  |= 0b11000000;
  SPSR  |= 0b00000000;
  /* Slave mod ve interrupt için ayarlamalar yapıldı */

  sei();
  /* Interruptlar çalıştırıldı */
}

void loop()
{
}

/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
  /* Interruptlar durdurulmuştur */
  while(!digitalRead(SS))
  {
      SPDR = i;
      i ++;
      if ( i > 255)
        i = 0;
      while(!(SPSR & (1 << SPIF)));
      /* SPI hattında veri aktarımı bitene kadar bekle */
      int gelenVeri;
      gelenVeri = SPDR;
      myservomotor.write(gelenVeri);
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);
      delay(15);

//      if(gelenVeri == 'a'){
//        digitalWrite(SERVO,HIGH);
//      }else if(gelenVeri == 'b'){
//        digitalWrite(SERVO,LOW);
//      }
      /* SPI üzerinden gelen verinin değerine göre LED'in konumu değiştirildi */
  }
  sei();
  /* Interruptlar başlatılmıştır */
}

```

# Answer
```
/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
 ...
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);

```

Don't do serial prints inside an ISR.
> 2 votes

---
Tags: spi, c++
---


# Question
Title: Reading an output analog pin with an input analog pin
I am having a hard time understanding why I can't read one analog pin's output with another analog pin. The docs state to put a delay in between, which I've done (I've tried up to one second with the same results). I've got this minimized code:

```
void setup() {
    Serial.begin(9600);
    pinMode(A0, INPUT);
    pinMode(A5, OUTPUT);
}

void loop() {
    for (int i=0; i<1024; i++){
      analogWrite(A5, i);
      delay(100);
      Serial.println(analogRead(A0));
    }
    Serial.println("done");
    delay(10000);
}

```

When it starts, it displays 6-9 for a few dozen iterations, then suddenly jumps to ~1018 and remains throughout the rest of the run.

`A5` is connected directly to `A0` via a 4" jumper cable. Nothing is connected to `AREF`. If I connect `AREF` to 5v, the output does not change but by a single digit. If I connect it to ground, it immediately outputs `1023`.

I'm hoping this is a "do'h" moment here. Can someone please let me know what I'm not doing correctly?

Update: This is a legit Arduino Uno R3 board. When I connect `A0` directly to 5v+, I get `1023` as expected as the output.

# Answer
For a start, A5 is not a valid pin to do analogWrite to. On a Uno they are marked with the "~" symbol, and are pins: 3, 5, 6, 9, 10, 11.

Thus the code will treat it as a digitalWrite, and will write LOW up to 127 and HIGH after that. From the code in wiring\_analog.c:

```
    case NOT_ON_TIMER:
    default:
        if (val < 128) {
            digitalWrite(pin, LOW);
        } else {
            digitalWrite(pin, HIGH);
        }

```

You are then just reading back (close to) 0 or 1023.

---

Second, PWM output is not what you can read back using analogRead. An analogRead reads a voltage level, whereas PWM output is just 0s and 1s interleaved at the PWM frequency, and with a width of the duty cycle.

See https://www.arduino.cc/en/Reference/AnalogWrite, in particular:

> The analogWrite function has nothing to do with the analog pins or the analogRead function.

---

Third, writing 1023 to analogWrite is out of range. See the documentation from the page linked above:

> **Parameters**
>
> pin: the pin to write to.
>
> value: the duty cycle: between 0 (always off) and 255 (always on).

You can see that the most you can write is 255 (not 1023).

---

### References
> 1 votes

# Answer
> Can someone please let me know what I'm not doing correctly?

the analog (output) pins on those chips are not exactly analog: they are pwm output pins. as such, their output is either 0 or 1, nothing in between, with the chance of being 1 equal the duty cycle.

that kind of output can be a steady "analog" if you run it through a low pass filter - the simplest would be an rc filter where the r is in ***serial*** with the c.

so if you hook th epwm pin up to a rc filter and adc the output of that rc filter, you will get a real "analog".
> 1 votes

# Answer
Your program is correct and I suspect the error is in the hardware. Arduino uses its internal timer and creates a high frequency PWM on the corresponding pin upon a `analogueWrite()` is called. Here what we should notice is the DC switching in the appropriate pin is not noticeable in most cases. (If you give it to an LED you can adjust its brightness).

But what you have done now is not correct. Since there is no current flowing in the pin there will not be a analogue voltage actuality. It is 5V and 0V switching in a high frequency. Those are the values which the `A0` pin will see.

So try fixing a capacitor between the pin and the ground. and a 1k resistor to create a slight current flow to stabilize the voltage. then let us know your readings.

simulate this circuit – Schematic created using CircuitLab
> 0 votes

---
Tags: arduino-uno, analogread, analogwrite
---


title: UECIDE: linker error with U8g2 library

text:
# Question
Title: UECIDE: linker error with U8g2 library
This sketch:

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

//  OLED display.
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
void setup() {
  u8g2.begin();
}
void loop() {
}

```

Compile OK with Arduino 1.8.3, but under UECIDE 0.8.9-pre15 fails to link, with this message:

```
Compiling...
• Preprocessing...
• Compiling sketch...
• Compiling core...
‣ arduino
• Compiling libraries...
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ SPI [/home/look/.uecide/libraries/Communications/arduino/SPI]
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ Wire [/home/look/.uecide/libraries/Communications/arduino/Wire]
• Linking sketch...
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::write(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:248: undefined reference to `u8g2_DrawGlyph'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::initDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:101: undefined reference to `u8x8_InitDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::clearDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:104: undefined reference to `u8g2_ClearDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::setPowerSave(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:107: undefined reference to `u8x8_SetPowerSave'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::home()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:278: undefined reference to `u8x8_utf8_init'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2_SSD1306_128X64_NONAME_1_HW_I2C':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_Setup_ssd1306_i2c_128x64_noname_1'
collect2: error: ld returned 1 exit status
Compiling Fail

```

Both IDEs are set for Arduino Pro Mini 3.3V 8Mhz. In UECIDE I'm using GCC 4.9.2 for AVR. I copied the same U8g2 source code to both Arduino and UECIDE own libraries directory.

U8g2 library is version 2.15.2 by Oliver, installed via Arduino IDE and copied to the UECIDE libraries directory,

The problem, so far, only happens with U8g2 and not other libraries.

How do I solve this problem?

# Answer
> 1 votes
The layout of that library is in a non-standard format with folders that UECIDE doesn't know to look for or how to deal with.

The main culpret is the inclusion of big chunks of code in a "clib" directory (why on earth?!?!) which doesn't get included in the compilation. Then on top of that you have header files in there that are referenced both from inside it and outside it.

The simplest fix is just to copy and move the files to better locations:

```
$ cd ~/Documents/UECIDE/libraries/U8g2/src
$ mv clib/*.c .
$ cp clib/*.h .

```

Note you *move* the source, but *copy* the headers. That's to get around the problem of the headers being referenced from two locations with relative paths.

The problem stems from UECIDE having (by necessity) much stricter rules than the Arduino IDE over the layout of a library. This is to facilitate better identification and categorization of the libraries so that recursive dependency detection can take place.

---
Tags: arduino-ide, compilation-errors, avr-gcc, gcc, uecide
---


title: 12V from Arduino Uno

text:
# Question
Title: 12V from Arduino Uno
I don't think it's possible, but I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).

However, I don't have an external power supply. I can add an adapter (12V/1A) to my Arduino with the barrel input, but I wonder where to get 12V from? I only see 5V or 3.3V outputs.

And as far as I know all GPIO output 5V ... so how can I get 12V (or maybe a bit less but more than 5V) out of an Arduino? (and what safety measurements I should take to not ruin my Arduino?)

# Answer
> 1 votes
In crude terms the power supply of the Arduino is along these lines:

simulate this circuit – Schematic created using CircuitLab

It's actually more complex than that, especially concerning the USB power input, but that doesn't matter here.

As you can see the barrel jack (your 12V supply) first goes through a diode. Then it gets fed to the 5V regulator. The VIN pin also goes to the same pin of the 5V regulator, so it will see 12V minus the voltage drop of the diode (~0.7V).

So you can provide 12V to the barrel jack and use the VIN pin as an 11.3V supply.

# Answer
> 1 votes
> I want to drive my 433 MHz transmitter (FS21000A) from a 12V 'supply', to get more power (and thus more range).

that only works if the transmitter works at 12v and isn't powered through a regulator.

if not, applying 12v to it does nothing but generating some heat or damage, worse yet.

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


# Question
Title: inttypes vs Arduino defined integral types
In my Arduino projects I use both Arduino types and types defined in the "inttypes.h" file, which #includes stdint.h. So far I've always written code only for the ATmega328P microcontroller (either in the UNO board or "standalone").

To be clear, in this question I'm referring to the following types:

* "Arduino": `char`, `int`, `long`; `byte`, `word`, `unsigned long`
* inttypes: `int8_t`, `int16_t`, `int32_t`; `uint8_t`, `uint16_t`, `uint32_t`

---

* What is the actual difference between e.g. `int` and `int16_t`?
* Is implicit conversion between corresponding types always possible, or should I avoid it even if the compiler doesn't complain? (quite often in my programs I pass an `int16_t` as `int` argument to a function and it always works, but is it good practice to do it, in general?

# Answer
> 4 votes
> * "Arduino": `char`, `int`, `long`; `byte`, `word`, `unsigned long`
> * inttypes: `int8_t`, `int16_t`, `int32_t`; `uint8_t`, `uint16_t`, `uint32_t`

A better classification would be:

* C and C++: `char`, `int`, `long`, `unsigned long`
* "Arduino": `byte`, `word`
* inttypes: `int8_t`, `int16_t`, `int32_t`; `uint8_t`, `uint16_t`, `uint32_t`

I generally avoid the Arduino-specific types, as they are quite non-standard, and do not usually exist outside the Arduino world. As for the other types, just like Michel Keijzers suggests, I use the C types when I do not care much about the exact size. `int` is guaranteed to be at least 16 bits, but is likely to be 32 bits on a 32-bit architecture. It is a good default type, as it is supposed to be efficiently handled on any architecture. These types allow you to write portable code that automatically selects the "right" integer width for whatever architecture it is been compiled for.

If you care about the exact size, which can often be the case in a memory-constrained environment, use the types from inttypes.h. And do not worry about implicit conversions: as long as both types are wide enough to hold the numbers you need to store, a type conversion, whether implicit or explicit, always preserves the value.

# Answer
> 2 votes
int can be depending on the hardware architecture and is mostly 16 or 32 bit. However, an int16\_t is always 16 bit, regardless of the hardware architecture.

It will go wrong when you have a 32 bit architecture (for an int), and you are going to cast it to an int16\_t, than you lose the MSB 16 bits. Although I think the compiler will give a warning in this case (so in your case you are ok, but it can prevent a lot of work when you port your code to a 32 bit architecture).

However, all Arduinos have int defined as 16 bit, except the Due and SAMD based boards, see: Arduino reference for int (updated after the comment of per1234 below, thanks for that).

Normally I use integer when I don't care much about the type (and know it will stay under 32768, like for most indices in loops). But if you define a (large) array it's better to use an explicit type, or if you know for sure the value will never be higher than 32768 (int8\_t) or nonnegative and 65535 (uint8\_t).

Also, for the 'eye' unsigned char for an unsigned 'integer' value upto 255, uint8\_t looks better than a 'char' which seems more like a character instead of a value.

---
Tags: data-type
---


title: What's in an Arduino?

text:
# Question
Title: What's in an Arduino?
I've been using an Arduino Uno Rev. 3 for a few projects and would like to switch to using a bare Atmega328 chip so I can keep everything on the same board. I've seen the Arduino on breadboard tutorial which is fine, but the Arduino board itself has a lot of other components that aren't in the tutorial. I realize I can go look up the actual design itself, but I'm looking for a high level description of what most of the components are used for.

I'm not interested in programming through the Arduino IDE, so I don't need parts for serial programming and such. But I'm wondering if leaving out some other components would leave me at a disadvantage. For example, the datasheet recommends connecting AVCC to VCC with an LC circuit for ADC noise cancellation, but the arduino on breadboard tutorial doesn't mention this and I otherwise never would have known.

# Answer
> 5 votes
You did not specify what Arduino board you are talking about. It would have been useful to tag the question with the appropriate board name. In the following, I assume you want something similar to an Arduino Uno, i.e. an ATmega328P at 5 V and 16 MHz.

> I realize I can go look up the actual design itself \[...\]

You should. There really isn't that much to it.

Let us take a look at the Uno rev. 3 schematic, and see what may be useful to you:

* ATmega16U2 and associated circuitry: This is for USB communication. You have no use of it if you are not doing USB.
* 3.3 V regulator: This is for providing the Arduino 3.3V output. Only a convenience feature, not used by the Arduino itself. You should leave this out unless you need a 3.3 V supply.
* 5 V regulator. Only you know how you want to power your board. This regulator is needed unless you have some reasonably stable 5 V supply like, e.g., a USB bus.
* ISCP header: This is rarely used on an Arduino, but you are very likely to use it in your custom board, as ICSP is the easiest way to program an ATmega with no bootloader.
* Reset button: Not always needed, as you can just power-cycle your board.
* 10 kΩ pullup on RESET: Your board is very likely to work just fine without this, but there is a little risk that you suffer from random resets. You want this resistor on anything that is “production”-like, for reliability concerns.
* Decoupling capacitors: Just like the RESET pullup, the board may work without them, but they provide reliability.
* The MOSFET and OP-amp right before the 3.3 V regulator: This is for automatically switching between the Vin and USB power supplies. Unlikely to be useful on a custom board.
* Ceramic resonator: For running the ATmega at 16 MHz, you need either this or, for better timing characteristics, a quartz with suitable capacitors.
* LEDs: You know if you want them.
* AREF capacitor: Only useful if you do analog readings, as it reduces noise.

# Answer
> 2 votes
It all depends on you want, and what you are talking or thinking about, when you ask What is an Arduino. There are two main things that I associate with Arduino: A family of Development Boards (maybe a hardware family of development boards) and a Software built to work with that development boards. This let me to answer you using that two focuses:

1. The hardware focus

I understand that the Arduino boards were intended to bring the electronics and programming, closer to artists. Also, as any development board, the Arduino boards allows the user to test the most quantity of features of the core microcontroller used in the board (for Arduino UNO, the Atmega328P). Thus implying that the most of components included are to allow you a "safe" development workaround.

Now, when you have worked in a project so many time that you are ready to replicate your design, maybe for a commercial implementation, an Arduino board can take up more space that if you design your own board, well by you are not going to use all the pins or well by that you noted that you are not going to mess up the microcontroller or other components (maybe you did it the necessary times to know it) and you want to choose a smaller package that don't needs an easy microcontroller replacement, or finally because you want to include in a single board all the components and circuitry you used for your project and remove the ones you are not going to use, that is the case you mention, and you can do more things... if you want to work from a CR2032 battery you won't need the regulator and so...

2. The software focus

When you decide to use your own circuitry, maybe you also want to program the IC by yourself, not through the 2K bootloader preprogrammed, but by your own ISP programmer. There are many workarounds using the Arduino IDE, but as apparently you don't want to use the Arduino IDE, the ISP programmer would be your programming interface.

**A conclussion?**: The minimal things you have to bear in mind to put in run the Atmega328P (and maybe most of microcontrollers) are 3: polarization, clock and Reset. The other things (the LC network you mentioned, the RC network I will mention, and so...) can improve the microcontroller stability and performance.

1. Polarization. Depending on the board, the DC supply used can be either 5V or 3.3V. Check the voltage used by your board.
2. Clock/Oscillator. See and reply the oscillator configuration used in the board. Then search where you can set up (in your IDE or code) the oscillator speed. Overall if you decide or want to use the internal oscillator, obtaining a minimal circuit or by playing with arduino config files. Note that, as example with the 328P, using the internal oscillator means that you are not going to reach the max number of MIPS the 328P can reach (with the internal you have 8MIPS, but you can use an external crystal up to 20 MHz to get 20 MIPS)... It really matters if you are going to do many processing tasks.
3. Reset. Please do not let it open, send it to VCC through a 10Kohm resistor, and (if available) additionally to GND with a 100nF ceramic capacitor.

# Answer
> 0 votes
There is very little on an Arduino aside from the chip itself, the regulator (sometimes) and the crystal / oscillator (sometimes).

> But I'm wondering if leaving out some other components would leave me at a disadvantage.

Leaving out some parts will give you a disadvantage for some applications but give you an advantage for others; the same for adding some parts.

The right question is to figure out what you want to achieve with a given application and design towards that goal.

For minimum implementations, I have done plenty of nothing but the MCU - ghetto style.

On the flip side, there are plenty of applications where the MCU is literally buried in a sea of other parts: C8051F350 based LCR meter for example. so what to put in and what to take out is really application dependent.

---
Tags: arduino-uno, hardware, avr, electronics
---


title: ATmega328p - ISC00 with INT1?

text:
# Question
Title: ATmega328p - ISC00 with INT1?
I was reading about external interrupts using the ATmega328p, and I saw in the chip datasheet under the paragraph "Bits 3:2 – ISC1n: Interrupt Sense Control 1 \[n = 1:0\]" the following table:

```
Value | Description
------+------------------------------------------------------------
00    | The low level of INT1 generates an interrupt request.
01    | Any logical change on INT1 generates an interrupt request.
10    | The falling edge of INT1 generates an interrupt request.
11    | The rising edge of INT1 generates an interrupt request.

```

From what I understand from the table title and the definition in the datasheet that ISC1n where n=1|0, is dedicated for INT1. And that ISC0n where n=1|0, is dedicated for INT0. However, in the table above, the value 00 is described as "The low level of INT1 generates an interrupt request.".

What I don't understand is how can ISC0n where n=1|0 be dedicated for INT0 but in the table above the value 00 (or ISC00) is used for INT1 ? I could totally be missing something but I would appreciate any guide.

# Answer
> From what I understand from the table title and the definition in the datasheet that ISC1n where n=1|0, is dedicated for INT1. And that ISC0n where n=1|0, is dedicated for INT0.

This is correct.

> \[...\] in the table above the value 00 (or ISC00) is used for INT1

This is your misunderstanding. The value "00" in the table does not mean ISC00. The "Value" column of the table is the value you get by concatenating the bits ISC11 and ISC10. Thus:

* "Value = 00" means ISC11 = 0 and ISC10 = 0
* "Value = 01" means ISC11 = 0 and ISC10 = 1
* "Value = 10" means ISC11 = 1 and ISC10 = 0
* "Value = 11" means ISC11 = 1 and ISC10 = 1
> 1 votes

# Answer
It's a typo. My revision of the datasheet (revision G) properly says "INT0".
> 2 votes

---
Tags: interrupt, atmega328, avr
---


# Question
Title: Arduino Mega Timer1 in pure C problem - doesn't work
Does somebody know what can be wrong in this, where I try to set Timer1 interrupt in Arduino Mega in C code only. I'm trying CTC Mode and the purpose is LED blinking with 1\[s\] Period.

I work with documentation program doesn't work completely.

```
 #include <avr/io.h>
 #include <avr/interrupt.h>

 void setup()
 {
   //LED -> PB7 (Digital pin 13
     DDRB |= (1<<PB7);

  //FCPU = 16MHz, Prescaler :256 | CTC
   TCCR1B |= (1<<CS12) | (1<<WGM12);
   TIMSK1 |= (1<<OCIE1A);  // Compare Match A interrupt allowing
     OCR1A = 62500;

    sei();
    }

  void loop()
  {

   }

   ISR(TIMER1_COMPA_vect)
   {
     PORTB ^= (1<<PB7);
    }

```

# Answer
> 1 votes
> I work with documentation program doesn't work completely.

simple:

1) check out the datasheet; 2) identify those registers needed to get tmr1 to work; 3) set or clear, as appropriate, ***ALL*** bits that are needed. Do NOT rely on default values. 4) done.

---
Tags: arduino-mega, interrupt
---


# Question
Title: ATtiny85. How do I burn a bootloader? What is the process?
I want to use all six I/O pins of an ATtiny85, that means also using the reset pin as an I/O pin, however, I found out that if I disable the RESET pin, I can no longer program the ATtiny using an ISP programmer.

However, I found out that there are bootloaders for ATtiny which, as far as I understand, allow me to program the ATtiny through USB, without the need of the RESET pin.

**My question is**: How do I burn such a bootloader (such as micronucleus for example) to the ATtiny85? And how do I need to connect the ATtiny to USB after that (like this?)? How do I program it after that? Keep in mind that in terms of burning bootloaders and modifying fuses, I am a complete newbie.

Also, I'm using the ArduinoISP sketch as my ISP programmer since I don't have a real ISP programmer, but as far as I read, that won't be a problem.

EDIT: I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:

# Answer
I have just finished my Arduino-Plugin with full integration of TinySafeBoot (TSB) for ATtiny84A, ATtiny85 and ATmega328P.

The project can be found here:
https://mesom.de/atflash/index\_english.html https://mesom.de/atflash/tinysafeboot/index\_english.html

You could use it as it is now, and then use the Reset Pin as an analog in. Only watch for the voltage never to go below `0.6 * VCC`.

As an alternative you could modify the fuses in `boards.txt` to have this pin available:
Go to Arduino Preferences and click on the link to `preferences.txt` (Mine: `/Users/stefan/Library/Arduino15/preferences.txt`). In this folder navigate to `/packages/atflash/hardware/avr/0.1.0`. Open the `boards.txt` and go to the section
`ATTSB85.name=ATtiny85 (TSB)(Int. 8 MHz)`

Change the line
`ATTSB85.bootloader.high_fuses=0xdf`
to
`ATTSB85.bootloader.high_fuses=0x5f`

Restart Arduino and burn bootloader via Arduino menu.

---

If you even then want to get another Pin from ATtiny85: you can change the bootloader to use just one Pin for RX and TX (see the TSB website). But why all the effort? Simply take the ATtiny84A. It has 14 Pins instead of 8 and costs nearly the same.

Stefan
> 2 votes

# Answer
* Yes, there are USB interfaces for ATtiny85. Just look at one of the open hardware designs out there, e.g. Digispark.
* An USB interface is going to require two pins, so using one to save one pin doesn’t strike me as cost effective.
* I agree with @FAD, that you don’t really need an USB stack, and simply could do a time-delay-at-boot thing with the UART pins.
* HVSP (the high voltage programming) is not hard to do. If you’re already comfortable with ArduinoISP, you can try ScratchMonkey, which uses the same approach (with a 12V power supply and one transistor) to do HVSP programming.
> 2 votes

# Answer
True, if you use the reset pin as IO then you need a special programmer that I believe provide high voltage (12v if i remember) or something like that to apply a 12v source to that pin to force it into programming mode then program using a normal programmer (or another arduino). However, what you are looking for is something like what is being done in the Arduino. The arduino is programmed with a special bootloader through ISP so when you power the microcontroller that bootloader will execute first and for few milliseconds will check the UART pins for activities and if it sees something valid it switched into programming mode where it waits for the new code to come through UART (not ISP) and write that into the program location, otherwise the bootloader will simply hand the code execution to the existing program if any.

**Here is a simple explanation of how it works:** Let say your microcontroller flash size is 1KB, and the bootloader is 100B so your program can be stored at location 101B+, and its max size is (1KB-100B). So when the bootloader starts and there is no activitiy on the UART pins it jumps to the location of your program (at 101B) while if programming activity is detected it starts reading the new code and overwrites the flash starting at 101B (so it won't over write itself).

And you will need the USBASP to program the bootloader for the first time. And you don't program the ATtiny85 through usb since that chip doesn't support USB, however, you use a USB to serial chip/module that emulates serial protocol over the USB. Some atmel microcontrollers have built in serial support and others can be done through software emulation.

* And as Chris suggested, don't disable the reset pin until you test and validate that your bootloader works.
> 1 votes

# Answer
> I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:

it is infinitely better than your arduinoisp.

google avrdude / avrdudess.
> 0 votes

---
Tags: usb, attiny, bootloader
---


# Question
Title: Why does my PIR sensor stay high with ESP8266 breakout board?
I have a PIR sensor attached to a Amica nodeMCU board routing 5v from VIN and attached via USB port for testing. When motion is deteted it connects to the internet and sends data to IFTTT which i receive a notification on my phone.

When I power up, the PIR pauses for calibration and then immediately goes HIGH and fires the motion detected call which i receive on my phone. However From then on it never goes LOW but every 5-8 minutes sends another HIGH call through even if there is no motion.

**Testing**

* Tried using separate 5v supply to PIR same thing happens
* I have tried both retrigger modes (H & L) and experienced the same result
* The same happens with the Adafruit featherwing huzzah board.
* I have tested the PIR without a micro-controller and can confirm that it **functions correctly** *-lighting an led*
* I have tested with an Arduino Nano with the same code and it **functions correctly** *\- lighting an led*

**My Code** modified version of Arduino Playground PIR Project

```
//Sends IFTTT every 5 minutes it detects motion

#include <ESP8266WiFi.h>
//WiFi Settings

// Set up macros for wifi and connection.
#define SSID "my-network"    // SSID
#define PASS "mypassphrase"      // Network Password
#define HOST "maker.ifttt.com"  // Webhost
//-------------------------------
const char* streamId   = "test";
const char* privateKey = "mysecretkey";

//PIR Settings
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

int  interval = 1000; // Wait between dumps
boolean lockLow = true;
boolean takeLowTime;
int ledPin = 1;
int pirPin = 2;    //the digital pin connected to the PIR sensor's output
int nPIR_detect;
int motion = 2;

int minSecsBetweenUpdates = 300; // 5 minutes
long lastSend = -minSecsBetweenUpdates * 1000l;
//-------------------------------

// Begin Setup
void setup(){
  Serial.begin(115200);
  pinMode(pirPin, INPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for(int i = 0; i < calibrationTime; i++){
    Serial.print(".");
    delay(1000);
    }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
   nPIR_detect = 0;

  // Test ESP8266 module.
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
 if(digitalRead(pirPin) == HIGH){
       digitalWrite(BUILTIN_LED, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec");
         sendData(String(motion));
         delay(50);
         }
         takeLowTime = true;
       }

     if(digitalRead(pirPin) == LOW){
       digitalWrite(BUILTIN_LED, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause,
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){
           //makes sure this block of code is only executed again after
           //a new motion sequence has been detected
           lockLow = true;
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
}

void sendData(String motion){

  //Send the motion to IFTTT value1
  Serial.print("connecting to ");
  Serial.println(HOST);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(HOST, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/trigger/";
  url += streamId;
  url += "/with/key/";
  url += privateKey;
  url += "?value1=";
  url += "motion";

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + HOST + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");

}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Connection");
    return true;
  }
  else{
    Serial.println("No Connection");
    return false;
  }
}

```

OQ: Why does my PIR sensor stay high with ESP8266 breakout board?

*In essence, I never see the serial message "motion ended at.."*

# Answer
> 2 votes
I'm sure you have probably done both these, but just in case you haven't...

I see from your code you are using Pin 2 for the PIR sensor. I'm sure your not as dumb as I am every time I program a ESP8266, but check you have connected the PIR to pin 2, that's not the connection labelled D2 its GPIO2, which may or may not be labelled.

Assuming that's right then the next possible problem may be that GPIO2 is shared with TXD1, its possible that this is being used. So try moving to GPIO4.

# Answer
> 1 votes
I have the same issue with Huzzah and a PIR. The PIR is noisy and I get a false high every 10-20s while the code runs without any problem on an UNO. I think it is a problem of HF coupling from wifi interfering with the PIR's amplification circuit. I will try shielding and caps/ferrites to get rid of the HF on the PIR or use another power supply and couple the signal line via optocoupler.

# Answer
> 1 votes
The solution I found to this problem is use a 10k resistor between the PIR sensor output and the input pin of the ESP8266.

Not sure if 10K is the best value, someone else may find a better value, but for now, for me its working great.

John

---
Tags: esp8266
---


# Question
Title: Get hour with ctime (time library with ESP8266)
```
#include <ESP8266WiFi.h>
#include <time.h>

const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
  Serial.println("\nWaiting for time");
  while (!time(nullptr)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
}

void loop() {
  time_t now = time(nullptr);
  Serial.println(ctime(&now));
  delay(1000);
}

```

This is my code, but it shows the time like this: Sun Jul 23 15:21:12 2017. But what I want it to do is to only show the current hour, not everything. Is it possible to do that?

# Answer
> 3 votes
The easiest way is to use the standard function localtime() or gmtime() and the struct tm.

```
void loop() {
  time_t now;
  struct tm * timeinfo;
  time(&now);
  timeinfo = localtime(&now);
  Serial.println(timeinfo->tm_hour);
  delay(1000);
}

```

---
Tags: esp8266, wifi, time
---


# Question
Title: How to measure resistance of TFT Touchscreen
I'm using a TFT Touchscreen shield with my Arduino UNO, and I'm running "tftpaint" example by Adafruit.

I've noticed that when initializing the Touchscreen object, a resistance value must be provided. Library default is 300, but a comment in the code says:

```
// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it

```

How should I perform such measurement? Where do I put the probes of my multimeter? FYI, my shield is this one:

# Answer
As pointed out in other answers and comments, step one was trying to get a datasheet for this component. I couldn't find a datasheet for the shield, but here is the link from the vendor I bought it from, and they provided with some articles were they explained how to perform the resistance measure. However, I then noticed the answer was in the example code itself.

Btw, the shield it's indeed based on SPFD5408 as correctly suggested by user Michel Keijzers on his answer.

So, in turns out the hint to which pins were X+ and X- was actually in the example code I'm using. Here the Touchscreen object is initialized:

```
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

```

Notice the usage of constants `XP` and `XM`. The names stand for "X-plus" (X+) and "X-minus" (X-). Now if we look a couple of lines above where these constants are defined, we see this:

```
#define YP A3
#define XM A2
#define YM 9
#define XP 8

```

In particular, we see that `XM` (i.e. "X-") is mapped to analog pin `A2`, and `XP` (i.e. "X+") is mapped to digital pin `8`.

Now, by looking at how the shield couples with arduino, we can see that analog pin `A2` of the Arduino board, connects with pin labeled "`LCD_RS`" in the shield, and that pin `8` connects with pin labeled "`LCD_D0`".

This is a picture (found online) of the bottom side of the shield, were we can see the labels for each pin:

Finally, with a multimeter at those pins, I measured the resistance and it was 292 Ohms. Not so different from the default of `300` in the library, but it's still a good thing to have the correct value.
> 5 votes

# Answer
Your TFT seems like this: TFT LCD SPFD5408

I cannot find a datasheet, but normally the X+ and X- are shown on the device... if not, try to find the datasheet and look for the pin numbers.
> 1 votes

---
Tags: arduino-uno, shields, library, adafruit, tft
---


# Question
Title: What would be the Western / American equivalent of the Troyka Shield and modules?
I'm taking an online course on Arduino robotics, produced by the Moscow Institute of Physics and Technology. The lectures are translated into English, but all of the parts referenced are by the Russian company Amperka.

It seems the key parts I need to follow along are

As fun as it would be to order from the Russian store, there are several practical reasons I'd prefer an American (or Western) equivalent. If they even ship to the US, payment would be difficult, shipping slow, instructions in Russian, etc, etc.

I've spent time and money shopping around Adafruit and SparkFun, but as an Arduino beginner, I'm not 100% sure which parts are analogous to these Russian ones. If a more experienced hobbyist recognizes any of these and can help me identify it, that would be most appreciated.

I think the Troyka components are a necessity, but the Matryoshka Z is a "nice to have" bundle of components. I'm using Arduino Uno, so compatibility with that would be preferable, but I think one of his Russian controllers is supposed to be a clone of the Leonardo, so if these parts only work with a Leonardo that's fine too.

The shield is shown here:

In this view it's combined with its modules using this special snap-together PVC:

The instructor said that he helped invent the PVC components, so I guess there may not be an American version of that yet (or is there)?

# Answer
This probably has no complete, general solution.

The Troyka Shield looks to be just a prototype shield with footprints for ground/power/data cables. Likely you can just use a different mechanism to connect things, solder some additions to an everyday proto shield, or you could relatively quickly duplicate this in a PCB design program and have boards made.

There are probably many alternatives for the mechanical structure, ranging from cardboard and foam tape or hot glue to various toy building block sets, or you could try to duplicate their idea by making some grids on an everyday 3D printer. Likely none of these satisfy formal ESD concerns - but then, Arduino projects are usually considered disposable enought that people rarely worry about this.

The modules are going to be the most problematic part. They seem to encompass many of the peripheral parts and chips usually used in Arduino projects, and most of those are already available in canonical modules from a range of vendors like Adafruit, Sparkfun, Seeed, etc on down to clones and simple executions of chipmaker's recommended circuits. So for most of these, you'll probably have no problem finding a *substitute*, the possible complication is if you have enough understanding of the details of each assignment to make any necessary changes to accommodate for differences in pinouts, components values, etc between the specified Troyka module and the chosen substitute.

You may in the end find it's better to just follow tutorials written around the specific parts and modules you find more readily available for purchase, and thus avoid the needs to translate the details.

Do beware however, that there are some *really bad* tutorials out there on the Internet - some in places like Instructibles are simply terrible engineering to the point where it is a minor miracle if they even worked once for their authors, and even some on the Arduino site cut corners in ways that can't be recommended.
> 2 votes

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


# Question
Title: Change Token authentication method to MQTT authentication method(username, password, client_id, ssid, passwd)
I have a mq135 sensor abd nodemcu ESP-12E module to calculate air quality and monitor it via Cayenne platform.

How can I edit this below code to add and connect my Nodemcu ESP-12E module to cayenne with MQTT authentication(username, password, client\_id, ssid, passwd) method?

We can’t add Nodemcu with token method, we should use MQTT authentication instead to add and connect nodemcu module to cayenne.

```
 #include “MQ135.h”
 #include “CayenneDefines.h”
 #include “CayenneWiFi.h”
 #include “CayenneWiFiClient.h”
 #define CAYENNE_DEBUG
 #define CAYENNE_PRINT Serial
 #define VIRTUAL_PIN 5
 #define ANALOGPIN A0

char token[] = “”; // Insert your token here
char ssid[] = “”; // Insert your SSID here
char pwd[] = “”; // Insert your SSID password here
MQ135 gasSensor = MQ135(ANALOGPIN);

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Cayenne.begin(token, ssid, pwd);
}

void loop() {
// put your main code here, to run repeatedly:
Cayenne.run();
// float rzero = gasSensor.getRZero(); //this to get the rzero value, uncomment this to get ppm value
// float ppm = gasSensor.getPPM(); // this to get ppm value, uncomment this to get rzero value
// Serial.println(rzero); // this to display the rzero value continuously, uncomment this to get ppm value
// Serial.println(ppm); // this to display the ppm value continuously, uncomment this to get rzero value
// Cayenne.virtualWrite(VIRTUAL_PIN,ppm); // uncomment after rzero define and get your ppm calculation
}

```

# Answer
> 0 votes
You could have readily answered this question for yourself merely by looking at the example for the Cayenne-MQTT-ESP8266 library.

The key part being:

```
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "MQTT_USERNAME";
char password[] = "MQTT_PASSWORD";
char clientID[] = "CLIENT_ID";

Cayenne.begin(username, password, clientID, ssid, wifiPassword);

```

It is not readily possible to know if this is the same Cayenne library you were using before, as you neglected to specify what you were using. The includes are different, but that could be a version difference, or it could be evidence of an entirely different approach.

---
Tags: arduino-ide, esp8266
---


title: Powering on the PC

text:
# Question
Title: Powering on the PC
I located the two pins that are responsible for powering up the PC. They are connected to the `Power On` button and one pin has an output of `5 V` while the other is the `ground`.

So far so good, the problem is when I connect the `5 V` one to the Arduino `VIN` and a ground cable from the PC power source to the Arduino `GND`, instead of powering my board, the PC starts and then promptly stops, as if I pressed the `power button` and did not release it.

It seems that electricity passes through the Arduino without powering it. I tested the `VIN` and `GND` pins with a normal breadboard power source and they are not broken, as the board starts up with no problem.

Why is the computer starting up instead of powering the Arduino? How can I use my Arduino to start up the PC?

My plan was to power the Arduino with the `5 V` pin and send a `digitalWrite(somePin, HIGH)` for a short amount of time to the ground pin from the PC that would normally be connected to the power button, thus "closing" the circuit like the normal case button would.

# Answer
The two pins aren't +5V power and ground.

One of them will be what you think, the other will be a signal wire with a pull up/down.

So if the ground wire really is ground then the other wire is the button input and is pulled up with a resistor, probably in the 10k region.

You can't power an arduino with a ~10k resistor in series with the power, it's just not going to work. But it will pull enough current to make it look like the button is pressed all the time.

What you need to do is:

1) Find out which pin is the signal pin. The easiest way to do this is find some other ground point on the computer (e.g. from one of the HDD power connectors) and measure the voltage from that to the button wires when the button is pressed. If both wires go to 0V then it's the wire that's normally +5 that is the signal, if they go to +5 then it's the wire normally at 0V that's the signal.

2) Fine a real power source. Most PC power supplies have an always on supply that will be at 5V when the PC is off. Use that to power the arduino.

3) Now you know which wire is the signal wire and have a usable power source you can connect the signal wire to one of the arduino pins and drive it to the correct state. Ideally you'd do this via an open collector type interface so that you don't get two different things pulling to very slightly different idle levels.
> 3 votes

# Answer
The signal you found is called `PS_ON` and it is an *active\_low* input which should be *momentarily* grounded by a switch to *toggle* the PC power supply's on/off state.

Trying to use this instead as a power *source* for the Arduino loads it, causing it to drop, the Arduino to brown out and release it, and then the process repeats.

As @Andrew mentioned, you need to find the 5v standby power *supply* output, and use that as the Arduino's power source instead. This is called `VSB`. Since it is already regulated to 5V, you can't pass it through the Arduino's Vin as it will not meet the regulator's dropout voltage needs. Instead you should route it in as an external 5v source, much as done with the USB power input.

To activate the signal, you'll then want to use a `digitalWrite()` to briefly set the output *low* (not high).

However, when you are not driving it low, rather than driving it high (to a voltage potentially higher than the power supply pulls it up to), what you should do is simulate an `open collector` output by changing the pin mode to an input, *without* pullup.
> 0 votes

# Answer
I suspect that you plan won't work. The Arduino's digital pins only support 20-40mA. I think you would be better using the Arduino to control a transistor or relay and interfacing that with the switch.
> -1 votes

---
Tags: electronics, wires, electricity
---


# Question
Title: Programming other Atmel chips(excluding Atmega 328 and 168)
How can we program any other chips of Atmel using Arduino Nano as a Arduino ISP ? Excluding the Atmega 328 and 168.

# Answer
> 1 votes
Since you say:

> Excluding the Atmega 328 and 168.

I'm going to assume that you already understand the general process for using your Nano as an ISP.

The Arduino IDE includes the **Arduino AVR Boards** hardware package which provides hardware definitions for specific configurations of:

* ATmega328P
* ATmega168
* ATmega2560
* ATmega1280
* ATmega32U4
* ATmega8

If your hardware matches the configuration of one of the Arduino AVR Boards then you only need to select that board from the **Tools \> Board** menu.

It is also possible to program many other Atmel microcontrollers or alternative configurations of the microcontrollers included with the Arduino AVR Boards hardware package with your Nano but you will first need to install the 3rd party hardware package that contains the definitions for the part you want to program. You can find a fairly comprehensive list of these hardware packages here:

https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls

Once you have found the hardware package that contains the necessary definitions you will need to install it. For this you have two options:

### Boards Manager

The easiest installation option Boards Manager. Most Arduino hardware packages allow this type of installation (and certainly all of them on the above list):

* Copy the Boards Manager package index URL.
* File \> Preferences \> Additional Boards Manager URLs \> paste URL \> OK
* Tools \> Board \> Boards Manager
* Wait for downloads to complete.
* Scroll down until you see the entry for the hardware package you want to install. Click on it.
* Click "Install".
* Wait for installation to finish.
* Click "Close"

### Manual Installation

Another option is to manually install the hardware package. For a simple package this would involve:

* Download the hardware package
* Copy the contents of the downloaded file to {sketchbook folder}/hardware. You can find the location of your sketchbook folder at **File \> Preferences \> Sketchbook location**.
* Restart the Arduino IDE if it's running

After installation you will only need to select the correct board from the **Tools \> Boards** menu. In some cases selecting a board may also add custom menu items to the Tools menu that can be used to adjust the configuration of the board (part, clock, BOD, etc.).

> using Arduino Nano as a Arduino ISP

Note that the correct term is **Arduino as ISP**. There is a programmer named ArduinoISP that is completely different from the Arduino as ISP. The confusion is increased by the sketch used on the Arduino as ISP being named ArduinoISP.

---
Tags: arduino-ide, arduino-nano, atmel
---


title: Arduino and 2 MOSFETs

text:
# Question
Title: Arduino and 2 MOSFETs
I want to turn on 2 bulbs using 2 MOSFETs. The problem is that they both turn on when it should turn up just one light.

Code:

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

void loop() {
  digitalWrite(13,1);
  digitalWrite(13,0);
}

```

See circuit below:

# Answer
> 3 votes
Try adding a delay into your loop. In your code pin 13 will toggle very rapidly, much too fast to see it. For example:

```
void loop() {
  digitalWrite(13,HIGH);
  delay (1000);
  digitalWrite(13,LOW);
  delay (1000);
}

```

---

It doesn't look wired correctly. For an N-channel MOSFET the Source should go to ground, like this:

# Answer
> 0 votes
The following circuit diagram works perfectly.

# Answer
> -1 votes
i prefer you to use relay to control any ac appliance with arduino it very much safe...

Just follow this circuit diagram and use 5v relay in your project it will always work fine.....

---
Tags: mosfet
---


# Question
Title: How to store/get MIDI SystemExclusive data?
In the MIDI library from the Arduino (FourtySeven MIDI library), there exist a function to get the length and bytes of a System Exclusive message:

Functions

```
getSysExArray()
template<class SerialPort , class Settings >
const byte * MidiInterface< SerialPort, Settings >::getSysExArray

getSysExArrayLength to get the array's length in bytes.

```

However, since the Arduino Mega (in my case) has only 8 KB of memory, how can I get a MIDI SysExclusive message which is longer?

Also, I even have added a 128 KB SRAM (23LC1024), but that doesn't help me if I cannot store it in pieces.

Ignacio Vazquez-Abrams mentioned I should 'read' the message, however what message do I get if the system exclusive message is too large to be stored in (internal) SRAM? The read message (see here also does not have a partial read.

Update:

After a test with a large message, it seems the message is not received by the Arduino MIDI library.

# Answer
> 1 votes
This library tries to make its programming interface as simple as possible, which means that SysEx messages are put completely into a buffer in the internal memory, which means that larger messages cannot be handled.

The only way to handle larger messages is to read the bytes directly from the serial port, and parse the MIDI messages yourself. (The MIDI specification has a helpful flowchart about MIDI parsing in the first appendix.) When you have detected the start of your large SysEx, you can then do whatever you want with the following bytes, e.g., handling them as a stream, or write them to external RAM)^.

---
Tags: array, sram, midi
---