body: I can confirm that changing ownership/security on the WindowsApps folder half-bricked my machine... it still ran classic windows but every single store App wouldn't run and the store itself stopped working... and I couldn't reset the security back again - 4 hours later and a complete restore with Microsoft's recovery download and a 16GB USB boot load , I'm older and wiser.


sender: user

message:
How to change colors and theme settings in 'Windows Store app' version of Arduino IDE?

In the standard Windows (Win32) version of the Arduino IDE, theme settings like syntax coloring can be modified in C:\Program Files (x86)\Arduino\lib\theme\theme.txt.

For the *Windows Store app* version of the IDE the theme files are stored in protected app storage space.

Is there a simple/safe way to change theme settings for the *Windows Store app* version of the IDE without messing up security settings and inadvertently lowering Windows security?

*(It would be easier and better if theme settings could be moved to the ArduinoData user folder where preferences.txt is stored.)*

sender: assistant

body:
Working from what Ignacio Soler Garcia wrote (which didn't work for me), I tried around and came up with a solution for my case (I downloaded the [OneDarkArduino][1] Theme from GitHub):

 - Unpack the theme if it came in a ZIP file
 - copy the folder called "theme" (there should be a bunch of .txt and .svg files in there)
 - paste it into the folder where all your projects are (usually something like C:\User\Documents\Arduino) - it needs to be named "theme"
 - (re)start the Arduino IDE and now it should start with the new theme already loaded

  [1]: https://github.com/konrad91/OneDarkArduino


message:
RadioHead and DallasTemperature error

The RadioHead library only runs on a very old core for the ATtiny85.
It sends data but I would like to send something useful. The problem is I cannot read any sensors using this core. And on any other core the RadioHead library fails.

[RadioHead library][1]
[ATtiny core][2]

An [old post][3] in the Arduino forum, probably the same issue.

I would like to know what is in the DallasTemperature that conflicts with RadioHead making the code to hang.

The problem appears when I add `DallasTemperature sensors(&oneWire);` to the code.

    // RadioHead ASK
    #include <RH_ASK.h>

    // DS18B20
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #define ONE_WIRE_BUS PB0
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    // Sleep
    #include <avr/sleep.h>
    #include <avr/wdt.h>

    #ifndef cbi
      #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
      #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    // Absolute reference PB to overcome inter-IDE issues
    #define T_PIN PB1 // transmission
    #define L_PIN PB3 // optional LED pin
    #define BAUD 2000

    // Baud rate, receiver, transmitter
    RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

    // the Tickle structure, what a name, ugh
    struct tickle {
      uint16_t id;
      uint16_t value1;
      uint16_t value2;
    };

    // Watchdog
    volatile boolean f_wdt = 1;

    ISR(WDT_vect) {
      f_wdt=1;
    }

    // Sleep
    void system_sleep() {
      cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
      sleep_enable();

      sleep_mode();                        // System sleeps here

      sleep_disable();                     // System continues execution here when watchdog timed out
      sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
    }

    // Setup for Watchdog
    void setup_watchdog(int ii) {
      byte bb;
      int ww;
      if (ii > 9 ) ii=9;
      bb=ii & 7;
      if (ii > 7) bb|= (1<<5);
      bb|= (1<<WDCE);
      ww=bb;

      MCUSR &= ~(1<<WDRF);
      // start timed sequence
      WDTCR |= (1<<WDCE) | (1<<WDE);
      // set new watchdog timeout value
      WDTCR = bb;
      WDTCR |= _BV(WDIE);
    }

    // With set_watchdog at 8 (4 sec.) we cycle from 0 to 14
    // This timer is not precise
    void minute_sleep(int ms) {
      for (int c = 0; c < ms; c++) {
        for (int i = 0; i < 15; i++) {
          system_sleep();
        }
      }
    }

    void setup() {
      // Debugging, if this takes less than a second, check fuses (core)
      if (!driver.init()){
        pinMode(L_PIN, OUTPUT);
        digitalWrite(L_PIN, HIGH);
        delay(500);
        digitalWrite(L_PIN, LOW);
        delay(500);
      }
      setup_watchdog(8);
      sensors.begin();
    }

    void loop()
    {
      if (f_wdt==1) {
        f_wdt=0;
        struct tickle package; // make a Tickle package

        package.id = 38; // hard-coded device ID
        package.value1 = analogRead(PB0); // any positive int up to 2^16
        package.value2 = analogRead(PB2); // any positive int up to 2^16

        // sending data
        driver.send((uint8_t *)&package, sizeof(package));
        driver.waitPacketSent(); // wait for it ~Barney
        minute_sleep(10); // tested: 10 was 10:30, I like
      }
    }

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/
  [2]: https://code.google.com/p/arduino-tiny/downloads/detail?name=arduino-tiny-0100-0018.zip
  [3]: http://forum.arduino.cc/index.php?topic=360460.0

body:
I have experienced many issues when using RadioHead library on ATTiny85 together with the Arduino IDE. Your issue is not the Dallas temp sensor.

The problem lies in that RadioHead uses timer 0 on the ATTiny and changes the prescaler on the timer to match the baudrate you have requested for your tranciever. The change of prescaler changes the way Arduino IDE functions like `delay()`works since those also use timer 0. I believe your Dallas library depends on `delay()` to synchronize the signals on the 1-bus so there you have a conflict between the two libraries.

I solved this by rewriting the RadioHead RHASK files to allow for ATTiny85 timer 1 to be used instead. Here's my code. Although I use [TinyHead][1] instead of RadioHead, the change will be the same as TinyHead is a RadioHead clone.

The only change I made to RH_ASK.h is the code to define whether to use TIMER1 or not.

    // Flag to indicate whether to use timer1 in attiny85.
    #define RH_ASK_ATTINY_USE_TIMER1

The below changes goes into RH_ASK.cpp

First change. Update pre-scaler code and add the pre-scalers used by timer 1:

    // Put these prescaler structs in PROGMEM, not on the stack
    #if (RH_PLATFORM == RH_PLATFORM_ARDUINO) || (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
    #if defined(RH_ASK_ARDUINO_USE_TIMER2)
    // Timer 2 has different prescalers
    PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 32, 64, 128, 256, 3333};
    #else
      #if defined(RH_ASK_ATTINY_USE_TIMER1)
       PROGMEM static const uint16_t prescalers[] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16834, 3333};
      #else
       PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 64, 256, 1024, 3333};
      #endif
    #endif

Second change. This code sets up the timer 1 and goes before the existing code for ATTINY timer0 in function RH_ASK::timerSetup(). please note the "... existing code" part. The existing code for setting up timer 0 goes between the #else and the #endif

    #if defined(RH_ASK_ATTINY_USE_TIMER1)
    #warning RH_ASK_ATTINY_USE_TIMER1 set.
       // figure out prescaler value and counter match value
       // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
       // At 1MHz clock, get 1/8 of the expected baud rate
       prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);
       if (!prescaler)
           return; // fault

       TCCR1 = 0; // Stop the timer
       TCNT1 = 0; // Zero the timer
       GTCCR = _BV(PSR1);  // Reset the prescaler

       // Number of ticks to count before firing interrupt
       OCR1A = uint8_t(nticks);

       TCCR1 = _BV(CTC1); // Turn on CTC mode / Output Compare pins disconnected

       // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
       TCCR1 |= prescaler; // set CS00, CS01, CS02 (other bits not needed)

       // Set mask to fire interrupt when OCIE1A bit is set in TMSK
      #ifdef TIMSK0
       // ATtiny84
       TIMSK1 |= _BV(OCIE1A);
      #else
       // ATtiny85
       TIMSK |= _BV(OCIE1A);
      #endif
    #else
    #warning RH_ASK_ATTINY_USE_TIMER1 not set.
       // use timer 0 (default)
       // figure out prescaler value and counter match value
       // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
       // At 1MHz clock, get 1/8 of the expected baud rate
       prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);

    ... existing code

       // ATtiny85
       TIMSK |= _BV(OCIE0A);
      #endif
    #endif

Third change goes where the vectors are set up. Note the added #if defined for TIMER1 and the corresponding vector. Note also that the vector for timer0 is now called TIM0_COMPA_vect in later RadioHead/TinyHead but the names TIMx and TIMERx are interchangeable.

    #if (RH_PLATFORM == RH_PLATFORM_ARDUINO)
    #if defined(RH_PLATFORM_ATTINY)
     #if defined(RH_ASK_ATTINY_USE_TIMER1)
      #define RH_ASK_TIMER_VECTOR TIMER1_COMPA_vect
     #else
      #define RH_ASK_TIMER_VECTOR TIMER0_COMPA_vect
     #endif
    #else // Assume Arduino Uno (328p or similar)

Mind you that I have had other issues using the DallasTempSensor library. I'm not sure whether the issue is a low quality crystal in my ATTiny or not, but I get garbage readings from my sensor. The same code works flawlessly on my Arduino Nano, so I'm currently investigating whether my ATTiny is too far off in its timings to work properly with that library. I'm also going to try the [OneWire][2] protocol to see whether that one works better. However, the above code change resolved my issues with Arduino IDE and RadioHead/TinyHead.

  [1]: https://github.com/enishoca/TinyHead
  [2]: https://github.com/PaulStoffregen/OneWire


message:
ESP8266 ESP-12 Connection

I am connected with my ESP-12 through a programmer and all the AT functions work correctly. However I do not get a connection when connecting to the ESP8266 module.

*I have done the following:*

Set the mode both: `AT+CWMODE=3`

Connect to an Access Point: `AT+CWJAP="<name>","<password>"` (Responds with WIFI Connected and WIFI Got IP)

Set the Access Point: `AT+CWSAP = "<other_name>","<password>",<channel>,<password_security>`

So at this time it should be connected to my local network and I can connect to it through wifi on my laptop. However when I connect to it, it says 'Connected, No Internet' (The network the esp8266 module is connected to, has internet).

When I troubleshoot problems it says DNS is not responding.

Does anyone have a clue what to do next? Or what I might do wrong?

body:
You can make the ESP8266 behave as a router, see Google for details.  By default it won't do this.

You need to create two separate WIFI networks and then tell the ESP to 'route' traffic between them.

Your ESP needs to form one network (STA mode?).  Your laptop needs to be on one network with the ESP.  The laptop needs to be configured to use the ESP as the gateway and unless your ESP has a DHCP server the laptop needs a static address.

Your ESP also needs to be a client to you router's network, and needs to take an address from the Router's DHCP server.


message:
SPI Problem with K-Thermocouple and Potentiometer?

[![Results of both K-Thermocouple by itself and the whole circuit together][1]][1][![A diagram of my circuit][2]][2]I have a setup where the Arduino reads input from the k-thermocouple and uses that info to regultate the an output voltage through a potentiometer. I know the potentiometer is not faulty because able to read the output from the wiper when I run the program but for some reason, k-thermocouple is stuck at 0 Celsius. I know that the k-thermocouple is not faulty either because it works accordingly when I run a program specifically by itself.

Does anybody know why there is a problem with how the k-thermocouple is operating in junction with the potentiometer? Here is a declarations of my program.

    #include <SPI.h>

    // K-couple dependent DigiPot Regulator

    #include "SPI.h"
    #include "max6675.h"

    byte address = 0x10;
    int CLK = 13;
    int CS = 10;
    int SDI = 11;
    const int ktcSO = 12;
    int ktcCS = 9;
    int ktcCLK = 13;

    MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

    int digitalPotWrite(int value) //Everything that happens when the DigiPot is
    called
    {
      digitalWrite(CS, LOW); // Chip Select is ACTIVE LOW (so now it's selected)
      SPI.transfer(address);
      SPI.transfer(value);
      digitalWrite(CS, HIGH);
    }

    void setup()
    {
      SPI.begin();
      pinMode (CLK, OUTPUT);
      pinMode (CS, OUTPUT);
      pinMode (SDI, OUTPUT);
      Serial.begin(9600);
      // give the MAX a little time to settle
      delay(500);
    }

    void loop()
    {
      if (ktc.readFahrenheit() < 60)  // While it's still in Safe Zone
      {
        digitalPotWrite(255);
        // Show the current temp in C and F
        Serial.print("Deg C = ");
        Serial.print(ktc.readCelsius());
        Serial.print("\t Deg F = ");
        Serial.print(ktc.readFahrenheit());
        int sensorValue = analogRead(A0);
        float voltage = sensorValue * (5.0 / 1023.0);
        Serial.print("\t V = ");
        Serial.println(voltage);
        int clockValue = analogRead(A1);
        Serial.print("\t Clock = ");
        Serial.println(clockValue);
      }
            if (ktc.readFahrenheit() < 65) // While in Caution Zone
            digitalPotWrite(51);
            else if (ktc.readFahrenheit() < 70)
            digitalPotWrite(102);
            else if (ktc.readFahrenheit() < 75)
            digitalPotWrite(153);
            else if (ktc.readFahrenheit() < 78)
            digitalPotWrite(184);
            else if (ktc.readFahrenheit() < 80) //Getting into Danger Zone
            digitalPotWrite(204);
            else if (ktc.readFahrenheit() < 81)
            digitalPotWrite(214);
            else if (ktc.readFahrenheit() < 82)
            digitalPotWrite(224);
            else if (ktc.readFahrenheit() < 83)
            digitalPotWrite(235);
            else if (ktc.readFahrenheit() < 84)
            digitalPotWrite(245);
            else (ktc.readFahrenheit() < 85); //Complete Shutoff
            digitalPotWrite(255);
        {
         Serial.print("Deg C = ");
         Serial.print(ktc.readCelsius());
         Serial.print("\t Deg F = ");
         Serial.print(ktc.readFahrenheit());
         int sensorValue = analogRead(A0);
         float voltage = sensorValue * (5.0 / 1023.0);
         Serial.print("\t V = ");
         Serial.println(voltage);
         int clockValue = analogRead(A1);
         Serial.print("\t Clock = ");
         Serial.println(clockValue);
        }
    }

Also, the code I used to test the K-Thermocouple is one that can be found on the internet (with just a little bit of adjustments)...

    // Sample Arduino MAX6675 Arduino Sketch

    #include "max6675.h"

    int ktcSO = 12;
    int ktcCS = 9;
    int ktcCLK = 13;

    MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

    void setup() {
      Serial.begin(9600);
      // give the MAX a little time to settle
      delay(500);
    }

    void loop() {
      // basic readout test

       Serial.print("Deg C = ");
       Serial.print(ktc.readCelsius());
       Serial.print("\t Deg F = ");
       Serial.println(ktc.readFahrenheit());
       int clockValue = analogRead(A1);
        Serial.print("\t Clock = ");
        Serial.println(clockValue);

       delay(500);
    }

  [1]: https://i.stack.imgur.com/bxBKN.png
  [2]: https://i.stack.imgur.com/kDCY7.png

body:
The wiring diagram, if accurate, shows a couple of problems.

First, A0 has nothing attached to it, so `sensorValue` may read in as zero or some small random number.

Second, attaching the digital pot's analog output pin 6, P1W, to the Uno's digital input pin 12 is pointless.  Instead connect P1W to whatever it is supposed to control.  If you want to handle data *from* the MCP42X1, connect its pin 13, SDO, to an Uno input.

However, neither of those problems appears to be related to misreading the MAX6675 temperature.  I don't know of a good approach to solving that problem, but if I were working with the circuit, would remove the wire between P1W and the Uno's digital pin 12, and would use 12 as the input from the MAX6675; that is, would wire it to d12 instead of d8, and instead of `int ktcSO = 8` would say `const int ktcSO = 12`.  Also, I'd probably replace the bit of code

      }
      else
      {
        while (ktc.readFahrenheit() < 85)
          {

with just a closing `}`.  In the Arduino paradigm, `loop()` runs repeatedly, and the if–else sequence adequately guards each of the `digitalPotWrite()` calls.

Note, the `digitalPotWrite()` function should be defined or declared before any calls to it appear.  Instead of placing that function at the end, put it before  `loop()` or before `setup()`.


message:
Robot beeping when power set to 0

I am working on an Arduino Uno robot project for college, I have modified my robot to beep and light up when he bumps into a wall or reverses, my robot works fine except for one very annoying problem, when my robots power is switched to 0 to turn him off he starts to beep as though he is bumping and I have no idea why!

My code:

    #include <Servo.h>                           // Include servo library

    Servo servoLeft;                             // Declare left and right servos
    Servo servoRight;

    byte wLeftOld;                               // Previous loop whisker values
    byte wRightOld;
    byte counter;                                // For counting alternate corners

    void setup()                                 // Built-in initialization block
    {
      pinMode(7, INPUT);                         // Set right whisker pin to input
      pinMode(5, INPUT);                         // Set left whisker pin to input
      pinMode(8, OUTPUT);                        // Left LED indicator -> output
      pinMode(2, OUTPUT);                        // Right LED indicator -> output

      tone(4, 3000, 1000);                       // Play tone for 1 second
      delay(1000);                               // Delay to finish tone

      servoLeft.attach(13);                      // Attach left signal to pin 13
      servoRight.attach(12);                     // Attach right signal to pin 12

      wLeftOld = 0;                              // Init. previous whisker states
      wRightOld = 1;
      counter = 0;                               // Initialize counter to 0
    }

    void loop()                                  // Main loop auto-repeats
    {

      // Corner Escape

      byte wLeft = digitalRead(5);               // Copy right result to wLeft
      byte wRight = digitalRead(7);              // Copy left result to wRight

      if(wLeft != wRight)                        // One whisker pressed? (Output on the left is not the same as the right)
      {                                          // Alternate from last time?
      tone(4, 3000, 1000);                       // Beep for 1 second as we hit the wall (BK)
        if ((wLeft != wLeftOld) && (wRight != wRightOld))
        {
          counter++;                             // Increase count by one
          wLeftOld = wLeft;                      // Record current for next rep
          wRightOld = wRight;
          if(counter == 4)                       // Stuck in a corner?
          {
            wLeft = 0;                           // Set up for U-turn
            wRight = 0;
            counter = 0;                         // Clear alternate corner count
          }
        }
        else                                     // Not alternate from last time
        {
          counter = 0;                           // Clear alternate corner count
        }
      }

      // Whisker Navigation
      if((wLeft == 0) && (wRight == 0))          // If both whiskers contact
      {
        bump();                                  // Call bump function
        backward(1000);                          // Back up 1 second
        reverseBeep();                           // Call reverseBeep function
        turnLeft(800);                           // Turn left about 120 degrees
      }
      else if(wLeft == 0)                        // If only left whisker contact
      {
        bump();                                  // Call bump function
        backward(1000);                          // Back up 1 second
        reverseBeep();                           // Call reverseBeep function
        turnRight(400);                          // Turn right about 60 degrees
      }
      else if(wRight == 0)                       // If only right whisker contact
      {
        bump();                                  // Call bump function
        backward(1000);                          // Back up 1 second
        reverseBeep();                           // Call reverseBeep function
        turnLeft(400);                           // Turn left about 60 degrees
      }
      else                                       // Otherwise, no whisker contact
      {
        forward(20);                             // Forward 1/50 of a second
      }
    }

    void forward(int time)                       // Forward function
    {
      servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
      servoRight.writeMicroseconds(1300);        // Right wheel clockwise
      delay(time);                               // Maneuver for time ms
    }

    void turnLeft(int time)                      // Left turn function
    {
      servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
      servoRight.writeMicroseconds(1300);        // Right wheel clockwise
      delay(time);                               // Maneuver for time ms
    }

    void turnRight(int time)                     // Right turn function
    {
      servoLeft.writeMicroseconds(1700);         // Left wheel counterclockwise
      servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
      delay(time);                               // Maneuver for time ms
    }

    void backward(int time)                      // Backward function
    {
      servoLeft.writeMicroseconds(1300);         // Left wheel clockwise
      servoRight.writeMicroseconds(1700);        // Right wheel counterclockwise
      delay(time);                               // Maneuver for time ms
    }

    void bump()                                  // Light and sound code for when the robot bumps a wall (BK)
    {

      tone(4, 3000, 1000);                       // Play tone for 1 second
      digitalWrite(8, HIGH);                     // Left LED on
      digitalWrite(8, LOW);                      // Left LED off

    }

    void reverseBeep()                           // Light and sound code for when the robot reverses(BK)
    {

          for (int i = 0; i < 3; i++)
          {

            digitalWrite(8, HIGH); // Left LED on
            tone(4, 1600, 400);                     // Beep (Pin 4, 1600Khz tone for 400ms) (BK)
            digitalWrite(8, LOW); // Left LED off

          }

    }

I am using this breadboard setup
http://learn.parallax.com/tutorials/robot/shield-bot/robotics-board-education-shield-arduino/chapter-5-tactile-navigation-6

The custom functions `bump()` and `reverseBeep()`are my custom functions to control the bumping and reversing beep and LED light up.

Does anyone know why he beeps when the power switch is set to 0?

body:
By beeping I assume you mean a 1 second been with no flash from the LED.
The only place in you code that can happen is when the whiskers are not equal.  I think the whiskers are powered by the shield you have turned off, in which case I suspect they are floating.  Is it possible to power these direct from the board, bypassing the off switch?

The easiest way to fix it would be to allow the processor to know when the Off switch is on and off.  Wire the 5V from the shield to the Arduino via a resistor of ???Ohms and read that pin before doing anything in loop().


message:
Arduino Zero: Enable RTTI

I need dynamic casts for my project, I'm getting:

    error: 'dynamic_cast' not permitted with -fno-rtti

It appears that RTTI (run-time type information) is disabled with the `fno-rtti` compiler flag.

How do I change this?

body:
It apparently is true that “RTTI (run-time type information) is disabled with the `fno-rtti` compiler flag”; however, looking at `compiler.c.flags` and `compiler.cpp.flags` in `platform.txt`, no `fno-rtti` compiler flag is set, suggesting that gcc sets it by default.

One way to turn off `fno-rtti` is adding a `-frtti` flag into the appropriate flags string in `platform.txt`.  As a side effect, this will affect all sketches subsequently compiled, rather than only those that need dynamic casts.

Note, on a microcontroller, a more-appropriate way to deal with the problem is getting rid of the need for dynamic casts, via function overloading.

*Edit 1:* On Linux, typical file paths to `platform.txt` are like `/opt/arduino-1.6.3/hardware/arduino/avr/platform.txt` or `/opt/arduino-1.8.0/hardware/arduino/avr/platform.txt`.  I don't know the location on OSX.  However, a command like `locate *avr/platform.txt` should reveal its location.  (If [`locate` is a new install on your system, first run `updatedb`](http://osxdaily.com/2011/11/02/enable-and-use-the-locate-command-in-the-mac-os-x-terminal/), which may take a while.)


message:
Why is my boards.txt file not being found?

I'm using the `ino` command line tool for the first time. When attempting to build my first sketch I run:
`ino build` in the project directory.

I get the following error:

    Searching for Board description file (boards.txt) ... FAILED
    Board description file (boards.txt) not found. Searched in following places:
      - /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino
      - /usr/local/share/arduino/hardware/arduino
      - /usr/share/arduino/hardware/arduino

What's going wrong here?

I've found an open issue here: https://github.com/amperka/ino/issues/240
But I'm wondering if anyone has a workaround.

body:
I got a hack to work  (macOS) by symlinking the files to where `ino` expected them to be.  But now I'm running into this issue: https://github.com/amperka/ino/issues/149

FWIW:

    cd /Applications/Arduino.app/Contents/Resources;
    ln -s Java ../Java;
    cd /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino;
    ln -s boards.txt avr/boards.txt;

Did it for me as far as finding boards.txt goes.

Still Broken otherwise. (Not marking as answer)


message:
How to connect arduino with local network

I am trying to connect Arduino with local network. This will act as a web server, client would be android mobile app or web browser. These are on same local network.

Do I need Ethernet Shield or ESP8266 to make Arduino accessible with local network IP ? Is there any way to connect without Ethernet Shield ?

body:
To connect to a network you need a network interface.  This could be an Ethernet interface, a Wifi interface or something that supports TCP/IP.  The easiest way of doing this is with ether an Ethernet 'shield' of a WIFI 'shield'.

In either case there are a range of options, from full shields to smaller boards that connect via jumper wires.  One important consideration is the longer the wires the more chance for signal degradation and loss of comms.  So direct plug in boards are probably better.

Probably the easiest way to do it is to use a ESP8266-??, but using an ESP as a network interface is like only using your PC for email.  The ESP is faster and has more memory than the Arduino, so it would be better to program that as the web-server and get the Arduino to feed it the data.

You could use Bluetooth, radio, etc, but that's just making life hard for yourself.

You could also look at the Arduinos that have networking built in.


body:
If you get yourself a board with an ESP8266 (say, Wemos D1, NodeMCU etc) this will allow you to do what you require and connect wirelessly to a local network. You can do this either with the Arduino using the ESP8266 as a shield or alternatively you can use the 8266 board on its own (it's a more powerful MCU than the Arduino!!)

Hope this helps.


message:
Where to connect shield in USB power supply for Arduino?

I'm making a 5 volt portable regulated power supply (using LM7805 regulator IC) for Arduino UNO. I'm planning to use a USB connector as its output socket, this way I can just plug it into the Arduino to power it.

My problem is where do I connect the USB sockets's shield? (Not an Arduino shield - I am talking about the USB cable's shield).

[![enter image description here][1]][1]

As far as I know it should be connected to the ground if it is a host device - can we consider the power supply as a host device?

  [1]: https://i.stack.imgur.com/o3ulW.jpg

body: If the supply for the Shield is 5V, then you can use one of the 5V lines on the Arduino to power the Shield, plus a common ground of course.


body:
A similar question has been asked in the Electrical Engineering Stack Exchange: [EMI/ESD protection for USB interface?][1]

> As for the SHIELD connection, you are correct - it is the metal casing of the connector and the braided shield of the USB cable that connects so it, which is likely referenced to protective Earth somewhere on the PC side of things. For EMI reasons it should not be directly tied to the GND signal connection, but should be connected through some impedance. I've seen both parallel resistor / capacitor (as you've shown) and ferrite bead connections between them. --Adam Lawrence

A good technical explanation was written by Ali Chen in his answer to [this question][2]:

>[Ali Chen's Answer to Structure of a USB 2.0 connector][3]

In the answer, Ali recommends using a 330 ohm resistor in parallel to a 0.1uF capacitor between the digital ground and the protective earth (shield).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/W3kJK.png)

<!-- End schematic -->

  [1]: https://electronics.stackexchange.com/a/151018/104097 "EMI/ESD protection for USB interface?"
  [2]: https://electronics.stackexchange.com/q/269244/104097 "Structure of a USB 2.0 connector?"
  [3]: https://electronics.stackexchange.com/a/269252/104097 "Ali Chen's Answer to Structure of a USB 2.0 connector"


message:
Arduino powered car not running when touching ground

I hacked a cheap car I connected both motors to L298N Dual H-Bridge Motor Controller and all things are working good. Motors are running fast. But when I put the car on the ground to run. It runs so slow. I am using 4.5V for L298N.
What can I do to run it fast on ground?

I have tried PWM but it does not work.

What can be the causes of this?

body: It cannot draw enough current I suppose. When wheels are free-spinning, the load on motor is very small. When you put it on ground, the load increases, and it is slow because there is not enough current to drive the load


message:
Can you pass the entries of a strut array to a int array? if so how?

typedef struct {
      uint8_t  pitch;
    }LearnNote;

    #define  MAX_NOTE  500

    LearnNote  Noteseq[MAX_NOTE];

    int learnindex=0;
    void loop() {
     MIDI.read();
    }

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity){
    Noteseq[learnindex].pitch=pitch;
    learnindex++;
    }

body:
Its not very clear what you are asking, but I think you are saying can you do this

    uint8_t anArray[MAX_NOTE];
    anArray = Noteseq.pitch;

In general the answer is no.  However in this **specific** case off the top of my head I think you probably can (maybe).  You have a struct which only contains bytes.  The compiler will probably pack the sequentially so you will effectively have a contiguous sequence of bytes which you would be able to copy to the byte array by doing:

    memcpy (anArray, Noteseq, MAX_NOTE);  // THIS IS BAD PRACTICE!

You can only do this in this case because the types are both 8bit numbers.  Its not a good idea to do this copy between an array of structs and a POD type array is just asking for trouble.

Instead use a function to do it.

    int* CopyPitch (LearnNote* source, int* destination, int count)
    {
        for (int i = 0; i < count; ++i)
        {
            destination[i] = source[i].pitch;
        }
    }
(You should really check for null pointers and stuff, but its just an example)


message:
comparing the entries of two arrays

i am trying to compare the elements of two arrays before the code goes on to the next sequence. The elements of note[x] are filled with the note values of a song. and i want to be able to input values from a midi controller into learn[x]. how can i compare array learn[ ]  to array note[ ] before the showsequence(); is incremented?

     const int x = 100;
        int note[x];
        int learn[x];
        int largestindex = 0;
        int learnindex=0;
        void showsequence();
        void readsequnce();
        const int PLAY = 1;
        const int TRYAGIN = 2;
        int state=0;

     void loop() {
         if (state == PLAY) {
            showsequence();
            readsequnce();
          }
          else if (state == TRYAGIN) {
            incorrect();
           }
         MIDI.read();
        }
        void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
        learn[learnindex]=pitch;
         learnindex++;
        }

     void showsequence() {
          //Add a new index to the end of the songseq
          SongSeq[largestindex];
          largestindex++;
          //loop through the songseq
          for (int index = 0; index < largestindex; index++) {
            SongSeq[index]();
          }
        }

          void readsequnce() {
          static uint16_t nextkey;
          bool mademistake = false;
           nextkey=0;
           learnindex=0;

           if (array_cmp(learn, note, largestindex, largestindex) == true){
                   // do this if they are equal
                   lcd.setCursor(16, 2);
            lcd.print("True");
             }else{
                   // do this if they are different
                   lcd.setCursor(16, 2);
            lcd.print("False");
             }
        }

     boolean array_cmp(int *a, int *b, int len_a, int len_b){
             int n;

             // if their lengths are different, return false
             if (len_a != len_b) return false;

             // test each element to be the same. if not, return false
             for (n=0;n<len_a;n++) if (a[n]!=b[n]) return false;

             //ok, if we have not returned yet, they are equal :)
             return true;
        }

body:
It depends what sort of comparison you want to do.  If you want to see if `note[x] == learn[x]` then that's what you do.

If you want to see if all the notes match all of learn then you'll need to put the comparison in a loop.

    for (int n = 0; n < MAX_NOTE && note[n] == learn[n]; ++n)
    {
        // Empty loop
    }

If you want to see if the first n notes match the current note and the proceeding n notes then its a bit more complex, but its just a loop.

    int n = 0;
    for (int l = currentPos;
    (l > (currentPos - 10)) && (note[n] == learn[l]);
     l--, n++)
    {
        // Empty loop
    }

If it is something else you want, please can you try and describe it in idiot proof terms so I can understand it.


body:
Start by assuming they match. Loop over each element pair, compare them, and set a flag when you find a pair that don't match.

    bool they_match = true; // assume they match
    for ( int i = 0; i < x; i++ ) { // for each note/learn element
      if ( note[i] != learn[i] ) { // check if they don't match
        they_match = false; // they don't mach, so set flag
        break; // stop looping
      }
    }

At the end `they_match` will be `true` if note[] and learn[] match, or `false` if they don't.

I would suggest you learn how control structures work.
https://www.cs.fsu.edu/~myers/c++/notes/control1.html
https://www.cs.fsu.edu/~myers/c++/notes/control2.html


message:
Is there a manometer available to use with Arduino?

I used an analog manometer in a plumb system. I would like to actually track information about water pressure across an entire building on different points and record all this information to analyze changes on pressure. I was wondering if there is a manometer that can be used with arduino. Or if there is some other homemade solution?

If there is any electronic sensor with an analog output that would be enough.

body: Bruno, there are a number of sensors available, try an Ebay search, to do what you want.  However, you need to determine what pressure range you are looking at.  As you mention manometer I assume you are working in the mBar range but to me that would be at odds with the pressure typically seen in whole building systems.  An Ebay search on 'Pressure transducers' will yield a good range of devices, likely to be primarily industrial types and some using wheatstone bridge type outputs.  you may need an op-amp circuit to buffer / amplify the output signal but virtually all sensors can be interfaced to an Arduino with the correct conditioning cicuitry.  As you are aware to measure pressure all sensors will need to be invasive into the pipework.


message:
waiting for a set number of inputs in an array to be reached

How do i have code wait for an x number of inputs be reached in an array before doing anything else?

    int largestindex = 0;
    int learnindex=0;

        void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
        learn[learnindex]=pitch;
         learnindex++;
        }

        while(learn[largestindex]==0){
              MIDI.read();
              if (learn[largestindex]!=0){
               break;
                  }

body:
If the call to `MIDI.read()` is a blocking call (it stays in there until it has a value) then you are pretty close:

    const int NumberOfInputs (42);
    for (int index = 0; index < NumberOfInputs; ++index)
    {
        MIDI.read();
    }

You can simplify you handler by post incrementing the learnindex counter as you use it.  (Post increment will happen after the value has been 'used')

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
    {
        learn[learnindex++] = pitch;
    }

When you increment a variable on its own line its usually better to pre increment it, because you aren't using the value and it might result in quicker execution.  However remember you are increasing the value before using it, so if you use it as above you end up accessing the array element one higher than you intended to!

    int learnIndex = 0;
    ++learnindex;            // Pre-increment it to 1
    learn[learnIndex++] = 1; // Set element 1 to 1.
    learn[++learnIndex] = 3; // Set element 3 to 3.


message:
How to code Arduino to follow schedule

I'm working on my system and I have to make arduino repeat such action or block of code if its the set time .. I'm using DS3231 module to track date and time .Example If I set the time in 6:00 AM and when the arduino reads the module and it turns out that its already 6:00 AM the arduino will now execute some action or the block of code .. sorry for my english ..

body:
This example shows a simple way of conditionally processing an event at a given time of day, once per day. The example allows 59 seconds of accuracy but in reality if the Arduino is free to read the time this will happen almost exactly at 6.00am.

You need to declare and populate currentTime and currentDate by reading the DS3231. This example assumes the currentTime is in millis.

    unsigned long action1_LastDoneDate;
    unsigned long TIME_600AM = 21600000; // millis 6.00 am = 6*60*60*1000
    unsigned long TIME_601AM = 21660000; // millis 6.01 am

    void setup()
    {
     action1_LastDoneDate=0L;
    }

    void loop()
    {
     //make sure we have not processed today
     if (action1_LastDoneDate != currentDate)
     {
       //make sure the time is within range
       if (currentTime>=TIME_600AM && currentTime<TIME_601AM)
       {
         //save off the current date so we don't try do process this alarm again
         action1LastDoneDate = currentDate;
         //now do the 6am stuff
       }
     }
    }


body:
Check out how the DS3231 Alarm functions work.  They will interrupt even a delay() statement.  At the appointed time the specified function is called.

This same question was answered here:

https://arduino.stackexchange.com/questions/30638/how-to-set-alarms-on-the-ds3231-easily?rq=1

For another way to see how to set this up, let me refer you to this article:

[Build Programmable Time-based Switches Using a Real Time Clock][1]

The code can be downloaded [Here][2]

  [1]: https://www.allaboutcircuits.com/projects/build-programmable-time-based-switches-using-a-real-time-clock/
  [2]: https://www.allaboutcircuits.com/login/?redirect=https//www.allaboutcircuits.com/projects/build-programmable-time-based-switches-using-a-real-time-clock/


message:
GPS autonomous robot

I am working on a GPS autonomous robot using Arduino, HMC5883 compass, Adafruit GPS module and I have managed to sort of complete the coding for it and I tried compiling / verifying it and I get an error. It would be helpful if anyone could assist help me find out what I am doing wrong in my code as I have spent 2 days looking for what I have done wrong and if someone could suggest a better way of writing my code or even improving it here code I appreciate it. HERE IS MY CODE http://textuploader.com/drhfa

Error:

    GPS_move_:468: error: unterminated argument list invoking macro "radians"

body:
I cannot compile because there are libraries missing. However, after auto-formatting the code I have this list of problems:

* Many lines lack semicolons at the end (check your variable definitions near the top of the code)
* You have an extra bracket in one of your `radians()` calls (the one that is giving the error I guess): `differencelongitude = radians((longitudeWaypoint2 - (longitudeWaypoint1));`
* There is an unterminated string literal: `Wire.send("A);`
* You have a colon instead of a semicolon: `turn_left():`

There may be more but as I cannot even begin to compile I cannot find them easily - also there may be similar errors in any included files you have created.


message:
String array glitch

For a project, I was asked to design a presentation on Arduino. I now have run into the problem of my code suddenly stopping. It worked fine one day, I entered a new item in the array, it stopped working. It looked like I was being returned all newlines insteaed of debug info. Can anyone help?

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    int slide = 0;
    const int slideNum = 13;
    const String data[] = {
      "What is Arduino?\nArduino is a board\nthat can be used to\neasily program",
      "that can be used to\neasily program\ncomplex behaviors.",
      "Purpose\nMoney\nEase of Use",
      "How are they\ncontrolled?\nIDE, C++, Library\n",
      "Commonly Used\nCommands\ndiditalWrite();\ndidgitalRead();",
      "Commands\ndiditalWrite();\ndidgitalRead();\npinMode();",
      "diditalWrite();\ndidgitalRead();\npinMode();\nanalogWrite();",
      "didgitalRead();\npinMode();\nanalogWrite();\nanalogRead();",
      "Arduino Types\nUno\nMega 2560\nLeonardo",
      "Uno\nMega 2560\nLeonardo\nNano",
      "Mega 2560\nLeonardo\nNano\nMini",
      "Leonardo\nNano\nMini\nEthernet",
      "Nano\nMini\nEthernet\nBluetooth",
      "THE END"};

    //Addr: 0x3F, 20 chars & 4 lines
    LiquidCrystal_I2C lcd(0x27,20,4);

    void setup()
    {
      lcd.init();
      lcd.backlight();
      lcd.setCursor(0, 0);
      lcd.print("Send Newlne to start");
      Serial.begin(9600);
    }
    void loop()
    {
      while (Serial.available() <= 0){
      }
      Serial.println("Current: " + String(slide));
      while (Serial.available() != 0){
        Serial.read();
      }
      next();
      if (slide == slideNum){
        for(;;){
        }
      }
    }

    void next(){
      String local = data[slide];
      String current[4];
      for (int i = 0; i != 4; i++){
        current[i] = local.substring(0, local.indexOf("\n"));
        local.replace(local.substring(0, local.indexOf("\n")), "");
        current[i].trim();
        local.trim();
        Serial.print("i=" + String(i) + ", current=" + current[i]);
        Serial.println(", local="+local);
      }
      lcd.clear();
      for (int i = 0; i != 4; i++){
        Serial.println(current[i]);
        lcd.setCursor(0,i);
        lcd.print(current[i]);
      }
      //lcd.print(data[slide]);
      slide += 1;
      Serial.println("New: " + String(slide));
    }

body:
Since you haven't provided all of your code, I can't say for sure exactly what caused your problem except that Arduino String operations employ dynamic allocation a lot. This will cause heap fragmentation, which is especially bad on a chip like the ATmega328 with little RAM and subsequently cause weird issues like you're getting. I would guess that initializing the String members of the array takes up a lot of heap space while fragmenting it and when you added one more string, you ended up with a stack-meets-heap situation at some point in `loop()`.

You're a lot better off with an array of compact strings using an array of pointers to `char` i.e. `const char * array[] = ...` since the strings are literals and so already known at compile time.


message:
home automation - What's a compact way to control a light switch with Arduino without interacting with high voltage?

To be clear, this question is not about physically wiring into the light switch to control the lights - simply pressing on the switch from the outside. I apologize in advance if my electrical vocabulary isn't up to par - I'm very new to this.

I have been developing an Android app that allows me to control Particle Photon boards over the internet, and I have already installed a board that turns my computer on and off. However, I am researching ways to automate the lights (ceiling lights, not lamps) without interacting with high voltage. I have not been able to find any good information.

Does anybody have any advice?

body:
Walmart and others sell battery-operated units that can flip switches to turn lights off or on. Example: [AutoChron Wireless Light Switch Timer](http://www.simplygoodstuff.com/autochron_wallswitch-timer.html?gclid=CMLn9c6hwdMCFQa2wAod2_gKjw), as seen in following picture.

[![AutoChron Wireless Light Switch Timer][1]][1]

You could buy one of these (for about $25) then hack into it and attach wires to the *On* and *Off* buttons to allow an Arduino to simulate presses of those buttons.  The unit would move the switch handle accordingly.

  [1]: https://i.stack.imgur.com/mVewf.jpg


body:
you can glue an LED controlled by an MCU into the sensor hole of a dusk to dawn sensor. these are available in [socket](http://www.acehardware.com/product/index.jsp?productId=3766930) and [outlet](https://www.touchandglow.com/product-p/s-711.htm) shapes, are UL certified, and require no messy wiring. I've been able to switch an outlet model by duct-taping an ESP8266's built-in LED against the window; can it get any simpler?

Here's a working example's parts, exploded for easy identification.
[![enter image description here][1]][1]

You can spot an inline socket-to-outlet adapter, a dusk-to-dawn sensor, a bulb, a cheap nodeMCU ESP8266 devboard, a short micro usb cable, a USB wall wort, and an RGB LED module attached to dupont wires. I'm wiling to bet anyone here can figure out how these pieces fit together to make a $10 "smart bulb". You can get most of these parts at the local home center, and everything shown on amazon/ebay.

Of course you won't get a lot of respect from EEs, but you will get the job done quickly and safely, and the opto-isolated controls work with any platform. I have cheaper/smaller build i've moved onto, but i still have several of these switch builds in-place for years and they work great.

I would recommend getting a dusk-to-dawn switch that is labeled as being compatible with LED bulbs; they tend to use a lower-"bleed" IGBT instead of the older/cheaper diac/triac combo which causes some low-energy bulbs to flicker when off.

  [1]: https://i.stack.imgur.com/Sssd3.jpg


body: A clumsy way would be to use a servo motor connected to the mechanics of the switch, somehow.  Or in a dimmer, replace the rotating knob with the output of a servo, thus simulating it turning.  Not sure if that's what you were after.


body:
I have built a 'switch-flip' controller that just attach to the regular light switch. The controller has both RFM69 radio and Bluetooth module in it so it can use iPhone (iOS app only for now) to control the switch on/off.

[![enter image description here][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/PgybG.jpg
  [2]: https://i.stack.imgur.com/00WKd.jpg


message:
Transistor amplifier to drive speaker using Arduino PWM

I have been working on a project lately which uses Arduino to play a wav file from SD card. I am using TMRPCM library which made the job very easy. But the problem is that the output sound in the speaker is very low. I am using the below single transistor circuit with my Arduino to drive 1.2W / 8ohm speaker
[![enter image description here][1]][1]
But the Audio output is barely audible. And i have tried many speakers with different wattage but same result.

I am wondering that is there is something wrong with the Wav file i have used for my project. It is 16000Hz/ 8 bit unsigned PCM coded. So in a nutshell my questions are

1) **How can i improve the sound obtained from my speaker by making modifications in the transistor amplifier circuit?**

2) **Was the less audible sound is due to the Wav file i have used?**

Kindly help me out, thanks in advance.

  [1]: https://i.stack.imgur.com/mvfzL.jpg

body:
Your amplifier arrangement is fundamentally flawed. At the moment you are "tickling" the top end of the electromagnet in the speaker - that is, you are energising it when the Arduino outputs a HIGH, and leaving it energised to de-energise by itself when the Arduino outputs a LOW.  Coupled with that the fact that a PCM file outputs PWM with a carrier frequency much higher than a tone() function (and ideally above human hearing frequencies) you end up with almost nothing happening on the speaker.

The classic Class A amplifier has a different arrangement:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/8wg5z.png)

<!-- End schematic -->

With that arrangement the transistor and R1 form a simple RTL inverter. Size R1 to give the output current you need for your speaker (lower resistor = more power = more heat = bigger transistor as well). R3 and C2 remove the high frequency switching from the PWM (you could also replace R3 with a suitable inductor if you want less losses from the resistor). C1 removes the DC offset from the signal to give the full swing to the speaker and prevent excess clipping and heating.

It's not an efficient design by any means. A better "first stage" (replacing R1 and Q1) would be a high drive output logic gate (one of the CD4000 series, since it can run from 12V). I have seen AND gates used before - this also gives the benefit that you can use the second input to the AND gate as a MUTE signal. The rest (R3, C1, C2) remains the same.

The advantage of using a logic chip instead of the RTL arrangement is that it gives a more efficient "Push-Pull" output which can deliver much more current with far less heat losses.

Instead of the speaker you could connect an audio power amplifier to the output of C1 to then drive a more powerful speaker. In this case you can most likely remove the first stage (Q1/R1/R2) and drive the RC filter directly from the Arduino.


body:
You might try an audio transformer in the circuit, following a low-pass filter to smooth the PCM signal.  Here's a picture of suitable inexpensive transformers (from [alexnld.com](http://alexnld.com/product/10pcs-1300-8-ohm-audio-transformer-ee14-transformateur-audio-pos-transformador/); but similar transformers are available on Ebay etc.):

[![1300:8 audio transformer, about 1/2" on a side][1]][1]

The effect of the transformer in the circuit is transforming the high voltage, high impedance output of the transistor driving circuit to the low voltage, low impedance needed at the speaker.  The impedance ratio of the transformers in the picture is 1300 Ω to 8 Ω.

  [1]: https://i.stack.imgur.com/k6TWi.jpg


body:
"It is 16000Hz"

That's pretty high frequency. Is your hearing good enough for that? Many folks couldn't hear it.


body:
First, do not get fooled by some that answer that 16kHz is a pretty high, nearly unhearable frequency. You're talking about sampling rate here. Then 16khz is pretty low end (although maybe on the edge of what's possible with the microcontroller, I don't know that off the top).

I would recommend introducing a negative supply rail to majenko's design as you can not expect a circuit to output negative voltages (i.e the negative halfwaves of an audio signal) without a negative supply...

As others already pointed out the transistor you use is a pretty poor choice. There is a transistor selection guide available [here](https://www.mouser.com/catalog/supplier/library/pdf/FairchildBipolarPower.pdf).
It has an audio section, take a look at that!


message:
Calculating with millis()

The following code works fine until I turn the `if (tijd - action >= 500)` into `if (tijd - action >= 1000)`

I wonder why this fails.

If I just loop and print the `tijd - action` it has no problem with it and runs well beyond 1000.

The Logic Analyzer on the software serial only returns **'255'** when it fails, I also wonder what that means.

The core I use is [this one][1]
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2

**[update]**

with "start"

    Sketch uses 3070 bytes (37%) of program storage space. Maximum is 8192 bytes.
    Global variables use 146 bytes (28%) of dynamic memory, leaving 366 bytes for local variables. Maximum is 512 bytes.

with "starting"

    Sketch uses 3072 bytes (37%) of program storage space. Maximum is 8192 bytes.
    Global variables use 148 bytes (28%) of dynamic memory, leaving 364 bytes for local variables. Maximum is 512 bytes.

**script**

    #include <SoftwareSerial.h>
    #include <avr/sleep.h>
    #include <avr/wdt.h>

    #define TX_PIN 4
    #define RX_PIN -1

    #ifndef cbi
      #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
      #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    SoftwareSerial mySerial(RX_PIN, TX_PIN);

    unsigned long tijd;
    unsigned long action = 0;

    volatile boolean f_wdt = 1;
    ISR(WDT_vect) {
      f_wdt=1;
    }

    void system_sleep() {
      cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
      sleep_enable();

      sleep_mode();                        // System sleeps here

      sleep_disable();                     // System continues execution here when watchdog timed out
      sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
    }

    void setup_watchdog(int ii) {
      byte bb;
      int ww;
      if (ii > 9 ) ii=9;
      bb=ii & 7;
      if (ii > 7) bb|= (1<<5);
      bb|= (1<<WDCE);
      ww=bb;

      MCUSR &= ~(1<<WDRF);
      // start timed sequence
      WDTCR |= (1<<WDCE) | (1<<WDE);
      // set new watchdog timeout value
      WDTCR = bb;
      WDTCR |= _BV(WDIE);
    }

    void setup() {
      mySerial.begin(2400);
      mySerial.print("Starting..");
      setup_watchdog(8);
      pinMode(0, OUTPUT);
    }

    int zie = 0;

    void loop() {
      if (f_wdt==1) {
        digitalWrite(0, HIGH);
        tijd = millis();
        mySerial.print(".");
        mySerial.print(tijd - action);
        zie+=1;
        if (tijd - action >= 500) { // fails when set to 1000
          digitalWrite(0, LOW);
          action = tijd;
          mySerial.print("z");
          mySerial.print(zie);
          mySerial.print(".");
          system_sleep();
        }
      }
    }

  [1]: https://github.com/SpenceKonde/ATTinyCore

body:
> if I change the string "Starting.." to "Start" it will run fine! This probably has something to do with filling up the RAM of the Tiny, right?

That symptom does suggest RAM overflow, in spite of the relatively low RAM use (28%) reported during compilation.

To reduce memory use slightly more, you can move the string `"Starting.."` to PROGMEM by changing from line 1 below to line 2.

      mySerial.print("Starting..");     // line 1
      mySerial.print(F("Starting.."));  // line 2

To save another handful of RAM bytes, change lines like `mySerial.print(".");` and `mySerial.print("z");` to `mySerial.print('.');` and `mySerial.print('z');`.  That is, you are printing single-character strings; each string has a null terminating byte; instead just print single characters.

References and discussion of the F() macro include [1](https://forum.arduino.cc/index.php?topic=110307.0), [2](http://forum.arduino.cc/index.php?topic=158375.0), [3](http://forum.arduino.cc/index.php?topic=91314.0), [4](https://www.arduino.cc/en/Reference/PROGMEM), [5](https://www.baldengineer.com/arduino-f-macro.html) and also see  [How do I squeeze code to fit onto an ATTiny](https://arduino.stackexchange.com/q/33318).  Also, there are some really compact software serial libraries targeted for ATtinies, which may save hundreds of bytes of flash and dozens of bytes of RAM.


message:
Making MCUs Arduino Compatiable

I have recently just built a custom arduino using the schematics found on their website. As awesome as this little processor is, I need more power. I have been thinking of making my own MCU, but wanted to know if it is possible to make them compatible with the arduino software. It would be very nice to not have to rewrite my existing programs.

If so, how would I go about doing that? If this is not a possibility (or just not a good idea for any reason), which language should I learn to start programming these upper level MCUs.

If I do have to start using a different language, what kind of software do I use to upload the code to these processors? And do they have the common features like Serial Monitor and Serial Plotter like the Arduino IDE does.

body:
The Arduino IDE supports a whole list of micros:

http://forum.arduino.cc/index.php?topic=145065.0

Some of those have a lot more power than the others. But to answer your question, no you cannot say take an ARM and use the Arduino IDE with it. It all comes down to your compiler and environment. At work we use ARm based processors and Keil uVision to program and Flip to program them. At my previous job we used Freescale Kinetis micros with CodeWarrior to flash and write the software. It all depends on what you decide to go with to fit your application, but it all boils down to it's all C or assembly if you decide to go that way.


body:
You are speaking of ***porting***. The arduino environment is built around a set of libraries and commands that are designed to abstract the low level access to a simpler high level language. In order to make arduino code work on a new microcontroller, you would have to rewrite and recreate the libraries using the low level access of your target microcontroller.

For example, Energia is a port of the Arduino libraries to the Texas Instruments MSP430 line of microcontrollers. Since not all features are the same, some code does not just drop in directly but additional code or libraries could be added to fix that. Even the Arduino IDE, the program used to write code and program the arduino was ported.

It would not be a trivial thing to port an entire library base.

<hr>

As to your other questions, you would code your new microcontroller in any language it's programmer and compiler can use. Likely C or C++. Arduinos are typically programmed in C++. You should look into the manufacturer of your MCU to find out what software to use, and what libraries they offer. They likely do not offer something like the serial monitor right out of the box.


message:
Diorama Controller Part 2 - Need More Outputs

For background see my original [post][1].  I've decided to not to use batteries and have it wired up with wall power.

I wish to use the Arduino Pro Mini 5V as the controller for my diorama project.  I have five completed buildings which will all have LEDs (with only two wired up so far).  The two currently wired buildings have multiple "zones/rooms" that can have its LEDs activated separately.

Building 1 is a saloon with rooms above.  It has a total of 7 zones/rooms.

Building 2 is a store with a doctor's office above and rooms in the back of each.  It has 4 rooms.

With this setup, I am able to use the software to simulate people coming and going within the rooms.  It's pretty neat.

However, I'm currently at 11 outputs out of the Mini.  I'm running out of pins.  How can I have more outputs?

  [1]: https://arduino.stackexchange.com/questions/31966/using-an-arduino-for-a-diorama-controller

body:
I think I understood what you want. If you want to control more LED's with less pins, consider using a shift register. For example, sn74hc595 could increase your digital outputs drastically. It has 8 bits, so you can have 2^8 combinations of outputs with it! For example, 0000 0001 is something, and 0000 0010 is something else, and so on. Check it out! I hope this helps :)

https://learn.sparkfun.com/tutorials/shift-registers - Basic knowledge about shift registers
http://www.bc-robotics.com/datasheets/sn74hc595.pdf
Other shift registers are great as well


message:
Port manipulation in Arduino using byte value

I'm trying to write PORTB and PORTD in ATmega328P using byte system like this,

        //  PD7  PD6  PD5  PD4  PD3  PD2  PD1  PD0
        //  N     N    N    N    N    U    U    U
        //  7     6    5    4    3    2    1    0
        //======================================
        //  PB7  PB6  PB5  PB4  PB3  PB2  PB1  PB0
        //  X     X    1    1    1    1    1    1
        //  C     C    13   12   11   10   9    8
        //======================================
        //C-Crystal Pins/U-Un used/N-Used/X-unknown value

        byte pins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};

        //uint16_t style1=1365; //10101010101
        //uint16_t style2=682;  //01010101010

        void setup() {
          for (int i = 0; i < 11; i++) {
            pinMode(pins[i],OUTPUT);
            PORTD=B00000000;
            PORTB=B00000000;
          }

        }

        void loop() {
          PORTD=B10101000;
          PORTB=B00101010;
          delay(1000);
          PORTD=B01010000;
          PORTB=B00010101;

        }

According to this , Port value should be swapped.
But, It's still remaining given value of the code before delay()

What is the problem in this code?

body:
>What is the problem in this code?

No problem, it *does* change the bits of port D and B from 0B10101000 and 0B00101010 to 0B01010000 and 0B00010101 respectively.

However, microseconds later `loop()` runs again and changes them back to  0B10101000 and 0B00101010 for a full second.

To better see what's happening, add a second `delay(1000);` statement, placing it just before the closing brace.


message:
Problem with SIM800L GSM module and servo

I have a SIM800L GSM module like in this link, ![the GSM module I have](https://i.stack.imgur.com/CkraF.png).

![this is the servo I have](https://i.stack.imgur.com/NFMBF.jpg).

The problem is when I connect the GSM to my Arduino Uno the GSM turns on for a while and then turns off. I tried to connect it with a 9-volt battery and an LM7805 voltage regulator, but I have the same problem. Attached to the Arduino are an LM35 temperature sensor, two LEDs, a buzzer, an LCD, a GSM module, a gas sensor and a servo.

The other problem is with the servo. I tested the servo and it works fine but when the servo stops moving, it starts to shake. I do not know what the problem is.

body:
You SIM800 module will pull 2Amps when its transmitting.  If your servo is also trying to overcome the inertia at the start of a movement it will pull 4+ times its normal running current.

A 9 volt battery will let you pull a couple of hundred milliamps.  So when the GSM transmits you system will shutdown.

You need a proper power supply or a battery pack that can put out these levels of peak current (3+Amps)


message:
3x3 LED Matrix with less pins

I'm building an audio cable tester/soldering station.  XLR cables have 3 pins and they can be wired in a few ways depending on what you want to do.  The basic cable is connected 1 for 1 and I want to make a system to verify if each pin is connected to the good ones on the other connector.

Picture the male and female connectors side by side.  The 3 pins on the male connectors will be connected to 3 digital outputs and the 3 pins on the female connector will be connected to 3 digital inputs.  That way, I can turn one of the outputs High and check my 3 inputs to see where that pin on the male connector is wired on the female connector.  Then I can walk the remaining outputs and find out how the rest of the cable is wired.

That part is all good, I can output the wiring via the Serial.print() command and the result is good.  The thing is that I would like to show the result with LEDs.  It brings me up to 9 LEDs in a 3x3 matrix.  I can use 9 outputs to show the result, but it seem like there could be a much better way.

The two solutions I see are the following:

 1. Buying addressable LEDs and interface them with my Uno
 2. Use 6 outputs, one for each row and one for each column.  Each row represents one pin on the male connector, each row represents one pin on the female connector.  So while I walk my 3 pins I can turn on the corresponding row and columns, then turn off that row and go to the next one, turn on the corresponding columns, etc.  I feel like this would work, but I'm wondering if the LEDs will flicker or if the refresh will be fast enough not to be noticeable.

What would you suggest?  Am I on the wrong track with solution #2?  Is there another way that does not require that many outputs?  I'm already up to 12 IO pins taken with #2 and 15 with #1.  It seem like a lot for such a simple build...

body:
Option #2 can definitely work, it is based on a widely adopted side effect of human vision called Persistence Of Vision, abbreviated with POV, which is used in Television, LED cubes and many other display devices.

You *SHOULD* notice no flickering if you manage to keep a refresh rate above 24 FPS (Frames Per Seconds or full refreshes), but not all human being are the same, that's why we tend to aim at 60 or 100 FPS to ensure flickering is not perceivable by anybody.

What you *WILL* notice though is a reduced brightness as each LED will be turned on only for a fraction of time.

So, naming your pins as `COL1` to `COL3` and `ROW1` to `ROW3`, you can refer to the following schematic:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/Yp5Q2.png)

<!-- End schematic -->

You can further extend your option #2 by using an external IC, commonly referred as LED drivers: not something you need unless you get short of outputs.


body:
It might be most cost- and time-effective to use an SPI-interfaced [MAX7219-based 8x8 LED module](https://www.ebay.com/p/?iid=272482869928&lpid=82&&&ul_noapp=true&chn=ps).  These cost a couple of dollars.  Typically they include an 8x8 array of single-color LED chips, mounted under a cover.  The MAX7219 handles LED multiplexing and allows software control of brightness as well as resistor control.

To represent 9 items in a 3x3 arrangement, you could use 4 LEDs per item, so that rows 1 and 2; 4 and 5; 7 and 8 represent rows of items, with LED rows 3 and 6 remaining blank; and similarly for the columns.

Note, with four output lines you can control 12 LEDs, multiplexed via [“charlieplexing”](https://en.wikipedia.org/wiki/Charlieplexing).  But the time and cost of setting that up probably would be somewhat more than just using a MAX7219 module.


message:
serial.write if condition

I am trying to do a simple serial communication control via sending a char and using it as an if condition, the arduino part is below

    char incomingchar;
    void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
    //        Serial.write("g"); // does not work when I explicitly write here either as opposed to through python.
    }

    void loop() {
        if (Serial.available()) {
                // read the incoming char:
                incomingchar = Serial.read();
                   if (incomingchar=="g"){
                  Serial.println("hello world!");}
                  else{
                  Serial.println(incomingchar);
        }
    }
    }

And here is the Python code:

    import serial;
    ser=serial.Serial('COM3',9600,timeout=1)
    ser.write(b'g')
When I run this, the python program returns a '1', and so does the arduino program in the serial monitor.

Note, if I directly set Serial.write('g'), it simply types out 'g' in the monitor and does nothing else from the loop.

body:
You declare `incomingchar` as a `char`. In your `if` you compare that char to a string (double quotes) `incomingchar=="g"`. I think you want to compare it to a `char` (single quotes) like this:

    if ( incomingchar == 'g' ) {
      // do something
    }


message:
NodeMCU powered with battery and use WiFi

I'm running a project with a nodeMCU DevKit and my project runs smooth if I run it connected through the usb wire to the computer.

I need to run my project using battery and I tried with a ICR14500 battery (3.7V and 700mAh). I connected the battery to the Vin pin but the NodeMCU doesn't send the data to the cloud.

When I run it with the battery I have detected some random behaviour, some times the led on the ESP8622 is blinking continiously and the total board power consumption is around 130mA!

Any idea what can be happening?

body:
ESP8266 require 3.3v input.  Some boards require 5V (from USB) and have regulators on.  How do you know that supplying 3.7v to Vin will work?

As to the high power consumption I would suspect it might be the WIFI transmitting.


body:
I am sure my NodeMCU requires 5V power, not 3.7V, and the high power consumption is related to Wifi - a notoriously high user of power!

This is why many battery driven ESP8266 related projects contain sleep mode stuff, to attempt to significantly reduce power consumption.


body:
It seem to be a problem with onboard regulator such as AMS1117.
ESP are really sensitive to power instability.
For every of my project i need to put capacitor on alimentation to prevent bugs.
I think you dont have enougth voltage to work properly with your regulated input.
To correct this issue you should put two battery to get 7.5 volt on the regulated input.
Another solution is using 3.3v input to pass trought the regulator.


body:
For the deep sleep problem maybe you should try with lower time value such as 10 second for example. For me it's a problem with the duration .

I've never seen this kind of problem on my project but try with lower value and tell me what you got !


body: The vin pin will work with anything above 5v as it goes via ams1117 to drop it to 3.3, to provide 3.3v directly connect to pin which says 3v directly on nodemcu lolin board


body:
If your battery is fully charged it’ll supply abount 4.2V.
The ESP should be able to handle up to 4.7V fine (according to [this forum post](https://forum.makehackvoid.com/t/esp8266-operating-voltage-range-and-sleep-current/286)), except that it’ll draw more current. So there’s no immediate need to go through the regulator.

If you’re battery-powering and want to use deep sleep, also consider using a different regulator with a lower quiescent current (e.g. MCP1702), otherwise the AMS1117 is already drawing at least 4mA.

Blinking and non-operation of the ESP is a sign for errors during boot, e.g. causing boot loops, typically caused by unstable power-supply, e.g. insufficient voltage or that the power supply cannot fulfill the peak current requirements (abount 200mA for the ESP).

My suggestion to be failsafe: just connect two batteries is series (7.4V nominal) and go through a 3.3V regulator.


message:
Why Liquid crystal display doesn't give output in code below?

I've been working on project for children showing the codes used by atc transponder. I've used a keypad and a 16×2 display , where user types a 4 digit code and display shows condition related to the code
E.g. typing 7500 on keypad will show hijack on display

What has went wrong??

    My code is ------
        #include <LiquidCrystal.h>
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(8, 9, 10, 11, 12, 13);//RS,EN,D4,D5,D6,D7
    #include <Keypad.h>//header for keypad commands enabling
    const byte ROWS = 4; // Four rows
    const byte COLS = 4; // Three columns
    // Define the Keymap
    char keys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'#','0','*','D'}
    };
    // Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
    byte rowPins[ROWS] = { 0, 1, 2, 3 };
    // Connect keypad COL0, COL1 and COL2 to these Arduino pins.
    byte colPins[COLS] = { 4, 5, 6, 7 };
    //  Create the Keypad
    Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    char inputArray[4]; //array to gather user keypad presses
    char Vfr[4] = {'1','2','0','0'}; //array to hold keypad password
    char Gliders[4] = {'1','2','0','2'};
    char Hijack[4] = {'7','5','0','0'};
    char Comfail[4] = {'7','6','0','0'};
    char Emerg[4] = {'7','7','0','0'};
    char Mic[4] = {'7','7','7','7'};

    int i = 0;
    int state = 1;

    void setup()
    {
      for(int k=8;k<14;k++)
      {
        pinMode(k,OUTPUT);//pins 8-14 are enabled as output
      }
      lcd.begin(16, 2);//initializing LCD
    }

    void loop()
    {
    while (state = 1);
    {
     lcd.setCursor(0, 0);

     char key = kpd.getKey();

     //if a key is presseds
       if(key)
         {

         inputArray[i] = key; //store entry into array
         i++;
         lcd.clear(); //print keypad character entry to serial port

         if (key=='C');
           {
             lcd.setCursor(0, 1);
             lcd.print("Reset");
             i=0; //reset i
           }

         if (i == 4) //if 4 presses have been made
           {
             {

             //match input array to password array

               if (inputArray[0] == Vfr[0] &&
               inputArray[1] == Vfr[1] &&
               inputArray[2] == Vfr[2] &&
               inputArray[3] == Vfr[3])
                  {
                   lcd.setCursor(0, 1);
                   lcd.print("VFR");
                  }
             }

             {

             //match input array to password array

               if (inputArray[0] == Gliders[0] &&
               inputArray[1] == Gliders[1] &&
               inputArray[2] == Gliders[2] &&
               inputArray[3] == Gliders[3])
                  {
                   lcd.setCursor(0, 1);
                   lcd.print("GLIDERS");
                  }
             }

             {

             //match input array to password array

               if (inputArray[0] == Hijack[0] &&
               inputArray[1] == Hijack[1] &&
               inputArray[2] == Hijack[2] &&
               inputArray[3] == Hijack[3])
                  {
                   lcd.setCursor(0, 1);
                   lcd.print("HIJACK");
                  }
             }

             {

             //match input array to password array

               if (inputArray[0] == Comfail[0] &&
               inputArray[1] == Comfail[1] &&
               inputArray[2] == Comfail[2] &&
               inputArray[3] == Comfail[3])
                  {
                   lcd.setCursor(0, 1);
                   lcd.print("COMMFAIL");
                  }
             }

             {

             //match input array to password array

               if (inputArray[0] == Emerg[0] &&
               inputArray[1] == Emerg[1] &&
               inputArray[2] == Emerg[2] &&
               inputArray[3] == Emerg[3])
                  {
                   lcd.setCursor(0, 1);
                   lcd.print("EMERGENCY!");
                  }
             }

             {

             //match input array to password array

               if (inputArray[0] == Emerg[0] &&
               inputArray[1] == Emerg[1] &&
               inputArray[2] == Emerg[2] &&
               inputArray[3] == Emerg[3])
                  {
                   lcd.setCursor(0, 1);
                   lcd.print("EMERGENCY!");
                  }
             }

             {

             //match input array to password array

               if (inputArray[0] == Mic[0] &&
               inputArray[1] == Mic[1] &&
               inputArray[2] == Mic[2] &&
               inputArray[3] == Mic[3])
                  {
                   lcd.setCursor(0, 1);
                   lcd.print("MILITARY IC");
                  }
             }
           }
    }
    lcd.print(key);
    }
    }

body:
    while (state = 1);

This line is a loop that will go around forever so long as you can set the variable state to 1.  What you mean is:

    while (state == 1)

You don't need semicolons at the end of conditionals, here is another:

     if (key=='C');

If you fix those two bugs, you'll get a lot further.


message:
WDT and RadioHead with delay()

The core I use is [this one][1]
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2
[RadioHead ASK library][2] (slimmed down)

What I want to do is:

 - deep sleep
 - wake up every minute
 - turn on sensor
 - take measurement
 - transmit data
 - back to sleep

This works when I test it seperatly, where it goes awry is when I combine RadioHead with WDT and then try to use a delay. This always hangs.

Probably a timer issue, I am looking for a work around.
I need the delay because I need to start the sensor, wait .5 sec and then take a measurement. Maybe I should give the ATtiny85 just some job to keep it busy for 0.5 sec?

This is working code, when I uncomment `//  driver.init();` it will fail.

    // RadioHead ASK
    #include <RH_ASK.h>

    // Sleep
    #include <avr/sleep.h>
    #include <avr/wdt.h>

    #ifndef cbi
      #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
      #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    // Absolute reference PB to overcome inter-IDE issues
    #define T_PIN 1 // transmission
    #define L_PIN 3 // optional LED pin
    #define S1 A2
    #define S2 A1
    #define BAUD 2000

    // Baud rate, receiver, transmitter
    RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

    // Watchdog
    volatile boolean f_wdt = 1;

    ISR(WDT_vect) {
      f_wdt=1;
    }

    // Sleep
    void system_sleep() {
      cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
      sleep_enable();

      sleep_mode();                        // System sleeps here

      sleep_disable();                     // System continues execution here when watchdog timed out
      sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
    }

    // Setup for Watchdog
    void setup_watchdog(int ii) {
      byte bb;
      int ww;
      if (ii > 9 ) ii=9;
      bb=ii & 7;
      if (ii > 7) bb|= (1<<5);
      bb|= (1<<WDCE);
      ww=bb;

      MCUSR &= ~(1<<WDRF);
      // start timed sequence
      WDTCR |= (1<<WDCE) | (1<<WDE);
      // set new watchdog timeout value
      WDTCR = bb;
      WDTCR |= _BV(WDIE);
    }

    void setup() {
    //  driver.init();
      setup_watchdog(8);
    }

    void loop()
    {
      if (f_wdt==1) {
        pinMode(0, OUTPUT);
        digitalWrite(0, HIGH);
        delay(500);
        digitalWrite(0, LOW);
        delay(500);
        system_sleep();
      }
    }

  [1]: https://github.com/SpenceKonde/ATTinyCore
  [2]: https://github.com/Thijxx/TinyHead

body:
The RH_ASK library uses `timer0`, which is also used for `millis` and `delay`.

Quick workaround is to use the standard AVR delay instead.

    #include <util/delay.h>

    ...

    _delay_ms(500)


message:
Syntax for declaring more than one serial pins of Arduino mega?

How can I declare multiple serial ports for Arduino Mega as it has been in the example below?

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(18,19); // RX, TX  //how this syntax can be modified for multiple Rx module?

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

    void loop(){
       Serial.write(45); // send a byte with the value 45

       int bytesSent = Serial.write(â€œhelloâ€); //send the string â€œhelloâ€ and return the length of the string.
    }

body:
If you mean the built in serial ports then just user the other objects that are pre-declared as per:

https://www.arduino.cc/en/Serial/Begin


body:
From the [official docs on serial](https://www.arduino.cc/en/Reference/Serial):

>The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).

Which means, you use `Serial1` for serial on pins 19 and 18 instead of `Serial`:

<!-- language: c++ -->

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

    void loop(){
       Serial1.write(45);    // send a byte with the value 45

       int bytesSent = Serial1.write("hello"); //send the string "hello" and return the length of the string.
    }


message:
Arduino serial port implementation

It might be an obvious answer to this, but I can't find it via a quick google search. To give my question a bit of more context, I'm writing an application which simulates a communication with Arduino via serial port, therefore I need to know how it is implemented internally.

From my previous experience with micro-controllers, the serial port is normally presented in micro-controller as two separate queues, one for TX and another for RX. For transmit out of MC, my software writes a byte to the end of transmit queue, and MC hardware reads byte from the beginning of the queue, converts it to bits, and toggles the pin to transmit data/parity/stop bits. And it keep doing that until queue is exhausted. The opposite happens for receive queue.

Am I right in assuming that Arduino has similar implementation with two separate queues? In particular, I want to read and write to serial port simultaneously.

body: Yes. Arduino has two buffers. See the [HardwareSerial.h](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h#L42-L55) and [HardwareSerial.cpp](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp)


body:
I have a lengthy post about Arduino serial communications: https://arduino.stackexchange.com/questions/19756/how-does-serial-communications-work-on-the-arduino

In short, the hardware (on an Atmega328 like on the Uno) has a two-byte receive queue (so you can be putting one byte into memory while the next byte is being received). It has a one-byte send queue.

Lengthier queues are implemented in software using interrupts to move data from the RAM queues in/out of the hardware queues.


message:
Switch to drive Arduino and optocoupler

At the moment I have a switch that connects to a digital pin on an Arduino as per the schematic below.  (Obviously there is an pull-up resistor on the pin).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/AT8pD.png)

<!-- End schematic -->

I now want this switch to also connect to another Arduino via an optocoupler. Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

body:
>Is it as simple as just adding the optocoupler between the switch and ground with the necessary resistor for it?

Probably not, because of two issues.  First, adding circuit elements between the switch and ground raises the voltage the pin will see when the switch is closed, which might keep a switch closure from registering as a low pin voltage.  For example, with Vcc=5V, table 30.2 *DC Characteristics* in the Rev. 8271J 11/2015 ATmega328P datasheet shows the guaranteed maximum input low voltage as 0.3 Vcc and the guaranteed minimum input high voltage as 0.6 Vcc; that is, 1.5 V and 3 V if Vcc=5V.  If the voltage drop across the optocoupler is between 1.5 and 3 V then the pin might register high or low with no guarantee which.

Second, if the pullup is large, not enough current will flow to trigger the optocoupler.  For example, at Vcc=5V if the internal pullup is used and the optocoupler drops two volts, I/O Pin Pull-up Resistor Current will be about 80 μA, too little to trigger a typical optocoupler.  (See figure  35-17, *ATmega328P: I/O Pin Pull-up Resistor Current vs. Input Voltage (Vcc = 5V)* in datasheet.)

What you might do instead is use two optocoupler channels in parallel or series, one for each of the Arduinos.  The switch lets current pass through an appropriate resistor or resistors and the optocoupler inputs;  optocoupler outputs go to  Arduino inputs.

Or, tie one side of the switch to +5V and the other to a resistor in series with an optocoupler input.  Connect the first Arduino's input pin to the low side of the switch.  I think that input will register low when the switch is open.  It will register high when the switch is closed.


message:
Arduino Zero - Stepper control (interrupt)?

I have a stepper controller board that I need to pulse every 40 uS or so.

I also have I2C sensors and Serial writes to preform.

Currently I run an update call in a tight loop, but the I2C sensors and Serial writes cause considerable delays which makes the motors stutter and come to a halt.

I would like to use an ISR to call the motor update method periodically.

However I cannot for the life of me figure this timer stuff out.

Here's my current attempt:
<!-- language-all: lang-cpp -->

    void TC4_Handler() {
      Stepper::updateAll();
    }

    void setup() {

      // Timer stuff
      // Set up the generic clock (GCLK4) used to clock timers
      REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                        GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                         GCLK_GENCTRL_GENEN |         // Enable GCLK4
                         GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                         GCLK_GENCTRL_ID(4);          // Select GCLK4
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      // Feed GCLK4 to TC4 and TC5
      REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                         GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                         GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      REG_TC4_COUNT16_CC0 = 0x000F;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
      while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

      //NVIC_DisableIRQ(TC4_IRQn);
      //NVIC_ClearPendingIRQ(TC4_IRQn);
      NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
      NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

      REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
      REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
      // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

      REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                       TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                       TC_CTRLA_ENABLE;               // Enable TC4
      while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
      // ...
    }

body:
As `Stepper::updateAll();` isn't shown I don't know what it does.  For accurate timing it would make sense to use hardware-operated output-compare output pins like TIOAx and TIOBx, instead of running some code to drive the pins when an interrupt occurs.

If you need to control several wires per motor – such that a pulse on a single output line isn't enough – you might consider using a 74HC595 (or other shift register) to transfer the bits.  Thus, each time an output compare occurs, the  TIOAx and TIOBx line would pulse the ST_CLK (store-clock) line of the SR, to transfer bits from the shift chain flipflops to the output flipflops; then, at its leisure the interrupt routine can shift the next set of bits out to the '595, ready to be transferred at the correct moment, when the next output compare occurs.

During stepper acceleration or deceleration, the timer count-limit would also need to be updated within the ISR.


message:
Arithmetic mean for sensor

This is the code I am currently using, but I want to add an arithmetic
mean to it. My goal is: when the pin A0 reads 5 values, I get the average
on which the fan and led will depend to be turned on and off, instead of
5 separate measurements.

<!-- language: lang-c++ -->

    int tempPin = A0;
    int fan = 3;
    int led = 8;
    int temp;
    int tempreal;
    int tempMin = 20;
    int tempMax = 30;

    void setup()
    {
      Serial.begin(9600);
      pinMode(fan, OUTPUT);
      pinMode(led, OUTPUT);
      pinMode(tempPin, INPUT);
    }

    void loop()
    {
      temp = analogRead(tempPin);
      tempreal = temp * 0.48828125;
      delay(1);
      if(tempreal > tempMax)
      {
        digitalWrite(fan,HIGH);
        digitalWrite(led,LOW);
        delay(1);
      }
      else if (tempreal < tempMin)
      {
        digitalWrite(fan,LOW);
        digitalWrite(led,HIGH);
        delay(1);
      }
      else if (tempreal >  tempMin && tempreal <  tempMax)
      {
        digitalWrite(fan,LOW);
        digitalWrite(led,LOW);
        delay(1);
      }
    }

**Edit** by Edgar Bonet – The OP added in a comment to my answer:

“I tried [averaging consecutive readings]. It worked as you would expect
but it still does not solves my problem. My sensor is only getting right
values in the beginning of the scanning and then it varies. That is why
I wanted to make average value but it still does not work. Sadly I think
I wont be able to change sensor, but is there any other way to
camouflage this problem?”

Below is a screenshot showing both correct (✓) and incorrect (✗)
readings:

![Example readings](https://i.stack.imgur.com/UmEHM.png)

body:
Seems too simple. am I missing something?

    --- arithmetic-mean.ino.orig 2017-04-27 19:37:01.386458500 +0200
    +++ arithmetic-mean.ino 2017-04-27 19:38:14.458114972 +0200
    @@ -16,8 +16,11 @@

     void loop()
     {
    -  temp = analogRead(tempPin);
    -  tempreal=temp * 0.48828125;
    +  temp = 0;
    +  for (int i = 0; i < 5; i++) {
    +    temp += analogRead(tempPin);
    +  }
    +  tempreal = temp * 0.48828125 / 5;
       delay(1);
       if(tempreal > tempMax)
       {


body:
A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations.

You can achieve similar results via exponential smoothing.

Yn = (1−α) Yn−1 + α Xn

Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.

With some thoughts, it can be done with integers and without loss of precision.

edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.

the sampled data is a simulated sine wave:

1000 * sin(2pi*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.

So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/6lRO7.png

the window I picked is 4.

As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.


body:
See Arduino Tutorials Smoothing
https://www.arduino.cc/en/tutorial/smoothing

Create an array to hold a series of readings. And a variable to hold the sum.

Incrementally cycle through the array, subtracting the oldest value from the sum and replacing it in the array with the current reading. Divide by the number of readings for the average.

Remember to allow for a delay in each reading as is appropriate for the sensor.


body:
You could use a moving average. It will update at each cycle whenever you take a new reading. Suppose you want to average over N readings:

<!-- language: lang-c++ -->

    double moving_average(double old_average, double new_value) {
        double new_average = old_average;
        new_average -= old_average/N;
        new_average += new_value/N;
        return new_average;
    }

I edited the function above. I had typed one of arguments incorrectly.


body:
> My sensor is only getting right values in the beginning of the scanning and then it varies. That is why I wanted to make average value but it still does not work.

I had a similar problem. It turned out that I was reading writing and transmitting too fast. It means that since it seems that reading and writing can be interrupted during "their job", when you read a variable and in the same time someone is writing on that you're reading garbage. In my opinion this can be fixed by the application of "semaphores" or mutex or reducing the call of the reading. Randomly it would happen again but less frequently.

An idea can be found here
https://forum.arduino.cc/index.php?topic=132813.0

Best

Gian Maria


message:
Generate 1.7 Mhz with PWM in Uno?

I have this code:

    void setup() {
      pinMode(11, OUTPUT);
      TCCR2B = 0;
      TCNT2 = 0;
      TCCR2A = _BV(WGM21);
      TCCR2A |= _BV(COM2A0);
      OCR2A = 249;
    }

    void loop() {
      soundBuzzer();
    }

    void soundBuzzer() {
      TCCR2B |= _BV(CS21);
    }

    void silenceBuzzer() {
      TCCR2B &= ~_BV(CS21);
      TCNT2 = 0;
    }

(Got it from [here][1]).

And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.
Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?

  [1]: http://forum.arduino.cc/index.php?topic=51457.msg368422#msg368422

body:
Expanding from my comment... any signal level generated by this kind of
microcontroller can only last for an integer number of CPU cycles. In
order to generate it, you first have to compute the timing
characteristics of the desired signal in terms of CPU cycles:

<!-- language-all: lang-none -->

    period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

The closest you can get is 9 cycles, which gives the frequency

    frequency = 16 MHz ÷ 9 = 1.778 MHz

Assuming this is acceptably close to your target, you can configure a
timer to do it. The example code you provided uses Timer 2 with the
OC2A output set to toggle mode. This approach can only give periods
which are an _even_ number of cycles, thus I am using the regular
“non-inverting fast PWM” mode instead in the solution below. In this
mode, the pin OC2A cannot be used with a controlled frequency, then I
changed it to OC2B (pin 3 on the Uno). Here is the code:

<!-- language: lang-c++ -->

    const uint8_t OUTPUT_PIN = 3;  // = OC2B
    const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

    void setup()
    {
        pinMode(OUTPUT_PIN, OUTPUT);
        TCCR2B = 0;           // stop timer
        TCNT2  = 0;           // reset timer
        TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
               | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
               | _BV(WGM21);  // ...ditto
        TCCR2B = _BV(WGM22);  // ...ditto
        OCR2A = PERIOD - 1;
        OCR2B = PERIOD/2 - 1;
    }

    void soundBuzzer() {
        TCCR2B |= _BV(CS20);  // F_CPU / 1
    }

    void silenceBuzzer() {
        TCCR2B &= ~_BV(CS20);
        TCNT2 = 0;
    }

The generated signal is slightly asymmetric: it stays HIGH during
4 cycles and LOW for 5 cycles. If you want a symmetric signal
(50% duty cycle), you can set `PERIOD` to 10 (5 cycles HIGH
and 5 cycles LOW), but then the frequency drops to 1.6 MHz.

**Edit**: You could also replace your Arduino Uno by a cheap ATtiny85
microcontroller, or maybe an Arduino-compatible dev board based on it,
like the [Trinket][] or the [Digispark][].

This microcontroller has a built-in PLL which allows it to run one of
its timers at 64 MHz, even though the CPU is running much slower.
A 64 MHz timer allows you to hit the target 1.7 MHz frequency
to within 1%:

    64 MHz ÷ 38 = 1.684 MHz

[Trinket]: https://www.adafruit.com/product/1501
[Digispark]: http://digistump.com/products/1