# Question
Title: Nested for loop used to evaluate a two dimensional array of integers
I am trying to use a nested for loop to evaluate and change numbers within the two dimensional array. Basically these numbers are minutes, or hours. This function is meant to reset the button controlled numbers when they go above 23 (hours) or above 59 (minutes) and also from going below 0. The two dimensional array that I made also has three arrays that need to be skipped (P1\[0\], P1\[2\] and P1\[10\] because they do not contain any time variables. When I click the buttons and increment the numbers nothing unusual happens they just don't bounce back like they are supposed to.

Here is the two dimensional array:

```
int P1[][12] = { //0-10
  {0}, //MODE
  {0, 0, 0, 0,}, //TOD variables
  // OnHR, OnMin, OffHr, OffMin
  {0}, //DOW
  {0, 0, 0, 0,},  //Sunday
  {0, 0, 0, 0,},    // OnHR, OnMin, OffHr, OffMin
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},  //Saturday
  {0, 0, 0, 0, 0,} // Temperature variables
  //Sensor, GreaterThan/LessThan, Temp, Buffer, State
};

```

Here is the for loop that doesn't seem to work:

```
void HrMinBounce() {
  int i = 0;
  int q = 0;

  for (int i; i < 10; i++) { //iterating down Plug arrays
    for (int q; q < 4; q++) {
      if (i != 0 || i != 2) { //non time arrays
        if (q == 0 || q == 2) { //hours
          if (P1[i][q] > 23) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 23;
          }
        }//End of hours
        if (q == 1 || q == 3) { //minutes
          if (P1[i][q] > 59) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 59;
          }
        }//End of minutes
      }
    }
  }
}

```

I have 5 of these arrays, so I was hoping to make one loop that could take care of all 5 at once. Here is my previous loop that works but I would have to copy and paste a whole lot to get the result without the extra for loop.

```
void MinHrLimit() {
  int i = 0;

  for (int i; i < 3; i++) {
    if (i == 0 || i == 2) {
      if (P1[1][i] > 23) {
        P1[1][i] = 0;
      }
      if (P1[1][i] < 0) {
        P1[1][i] = 23;
      }
    }
  }
}

```

# Answer
> 2 votes
```
            if(i != 0 || i != 2){ //non time arrays

```

Let's see.

* If i is 0 then that is true (it isn't 2)
* If i is 1 then that is true (it isn't 0 or 2)
* If i is 2 then that is true (it isn't 0)
* If i is 3 then that is true (it isn't 0 or 2)

In fact that expression is always true. You probably want:

```
            if(i != 0 && i != 2){ //non time arrays

```

---

```
   void MinHrLimit(){
      int i = 0;

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

```

You don't need the declaration of `i` there, because it is redefined in the `for` loop. In the `for` loop the variable `i` has an undefined value. You really want:

```
   void MinHrLimit(){

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

```

# Answer
> 0 votes
a few pointers:

1) your array has unevent number of items. so an array of struct is likely more useful here;

2) use brackets liberally, if you want to be sure of sequence of computation, like:

```
if ((i == 0) || (i == 2)) {

```

3) if you are going to use a lot of date / time types, think about unix time\_t data type. it simplifies coding considerably, and makes your code much more portable.

# Answer
> 0 votes
Your problem here is not in your code. It's in the data structures: you are doing it the wrong way. Of course, it *can* work, but not only is your approach wasteful of RAM, it will also inevitably lead to code that is difficult to write, to understand, to debug and to maintain.

You should really try hard to make your data structures as clean as possible. I would argue that clean data is even more important than clean code. If your data mode is clear and makes sense, then clean code flows naturally. If your data model is contrived, your code will always look awkward.

Here is how I would go about structuring your data. First thing: you are using (hour, minute) pairs to represent times. Thus, here is the obvious way to put them:

```
struct Time {
    int8_t hour, minute;
};

```

Notice the variable type: `uint8_t` takes only one byte, and it can represent numbers from −128 to +127. Now, this is the right place to write a function that clamps the numbers to the allowed values. In C, this would be a plain function. But since we are writing C++, it makes more sense to make it a method of the `struct`. Thus:

```
struct Time {
    int8_t hour, minute;
    void limit() {
        if (hour > 23)   hour = 0;
        if (hour < 0)    hour = 23;
        if (minute > 59) minute = 0;
        if (minute < 0)  minute = 59;
    }
};

```

It seems all your times come in pairs, with an “on time” and an “off time”. So here is a data structure for such a pair:

```
struct OnOffTime {
    Time on_time, off_time;
    void limit() {
        on_time.limit();
        off_time.limit();
    }
};

```

I added the convenience method `limit()`, so you can limit an `OnOffTime` rather than having to always explicitly limit moth times.

Then, you have a “mode” variable. A mode is normally represented as an `enum`, where each possible mode is given a name. Using names instead of numbers makes everything clearer. For the temperatures and the day of week, I would use the type `uint8_t`, which takes only one byte and can represent a number from 0 to 255. Then, your 2D array becomes an instance of this:

```
struct Settings {
    enum { MODE_FOO, MODE_BAR, MODE_BAZ, MODE_QUX } mode;
    uint8_t doy;
    OnOffTime tod, days[7];
    uint8_t temperatures[5];
};

```

You can probably find better names for the fields of the struct. And you should.

So, back to the original problem: how to apply the `limit()` method to all the times in all your 5 settings. Here it goes:

```
const int settings_count = 5;

Settings P[settings_count];

void HrMinBounce()
{
    for (int i = 0; i < settings_count; i++) {
        P[i].tod.limit();
        for (int j = 0; j < 7; j++) {
            P[i].days[j].limit();
        }
    }
}

```

As you see here, the code is short and easy to understand. This is the benefit of well though data structures: the code that follows is more natural.

---
Tags: arduino-ide, array
---


title: Timer1 firing immediately

text:
# Question
Title: Timer1 firing immediately
I'm trying to use Timer1 to get fired once a certain event occurs (about 1ms after the event). Using the timer to get a periodic interrupt works fine, but the very first interrupt fires immediately, rather than after the time I want it.

```
#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  Serial.println("start");
}

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  cli();
  TCNT1 = 50000;

  // if (micros() - stack[0] < 500) return; // work around guard would skip stray 1st interrupt

  stack[ctr++] = micros();

  if (ctr > ENTRIES)
    TIMSK1 &= ~(1 << TOIE1);

  sei();
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;
    cli();

    TCNT1 = 64000; // tick in around 1ms
    TCCR1A = 0;
    TCCR1B = (1 << CS10); // no prescaler
    TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt

    sei();
  }
}

```

When you enter `t` on the console it enables the interrupt and - unexpectedly - the timer fires at once. The next one comes after 1ms. A sample output looks like

```
start
testing
0: 8
1: 980
2: 980
3: 980
testing
0: 8
1: 980
2: 980
3: 980

```

Uncommenting the guard yields

```
start
testing
0: 988
1: 972
2: 976
3: 976

```

How can I modify my code (except setting a guard in the beginning of the ISR) so it is triggered once AFTER 1ms.

# Answer
> 1 votes
Interrupt flags are set even without interrupt enable flags, so there is pending overflow that you didin't cleared. And guess what happens after enabling `TOIE1` flag. It gets handled by `ISR`. That's on behalf of Arduino's `analogWrite()` PWM outputs (all timers are up and running in 8bit mode and 1.024ms period).

Btw global interrupts are disabled and reenabled inside of `ISR` handler by hardware so you shouldn't have `cli()` and `sei()` in it.

Also there is another issue - counter mode is preset to 8bits and much bigger prescaler, so the first round is way off.

```
void setup() {
  Serial.begin(115200);
  Serial.println("start");
}

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  TCNT1 = 50000U;
  stack[ctr++] = micros();
  if (ctr > ENTRIES)  TIMSK1 &= ~(1 << TOIE1);
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;

    TCCR1A = 0;           // you have to change the timer mode before changes
    TCCR1B = 0;           // stop the timer
    TIFR1 |= _BV(TOV1);   // clear the overflow interrupt flag by writing 1 to it
    TCNT1  = 50000U;      // tick in around 1ms / this makes more sense if it's set correctly
    TCCR1B = _BV(CS10);   // no prescaler ?????  REALLY???? this one is prescale by 8
    TIMSK1 |= _BV(TOIE1); // enable timer overflow interrupt
  }
}

```

---
Tags: timers
---


# Question
Title: I change ESP8266 baudrate and now it doesn't work
I was trying some AT commands using the monitor of the Arduino Web Editor with an Arduino Uno and a ESP8266 module. It was working at 115200 bauds but then I changed it with `AT+CIOBAUD=19200` and now it can't communicate.

How can I change the baudrate to 115200?

Now I see this:

# Answer
> 4 votes
Have you tried setting the web editor's baud rate to both the old and the new values? I ask because the CIOBAUD command has been obsolete for a while now so, depending on the age of your device, it may have done nothing. The command was replaced by "AT+UART\_CUR" and "AT+UART\_DEF" which have a different syntax.

See this answer to a similar question.

Update:

Yes, here's an example:

```
// Declare a serial object to talk to ESP8266
SoftwareSerial EspSerial(WIFITX_PIN, WIFIRX_PIN);  // RX, TX

void setup(void){
   // Init WiFi serial
   EspSerial.begin(9600);
   delay(10);
}

```

I've used 9600 baud in my example since SoftwareSerial may not work well at faster speeds.

Update 2:

> Is it possible to send AT commands from the code instead of the monitor?

Yes, easily. Once the above code has run (and note that I've deleted an unnecessary line since update 1), you can send strings to the ESP with EspSerial.print() and EspSerial.println(). Here's an AT command example:

```
// Set 9600 baud, standard 8-bit frame, and save as power-on default:
EspSerial.println("AT+UART_DEF=9600,8,1,0,0");

```

---
Tags: serial, esp8266, communication, linux, baud-rate
---


# Question
Title: Parsing sd card file to polymorphic objects
I am trying to read a file from sd card and parse them to polymorphic objects, then have an array of pointers to them so i can access them later.

I was wondering what the best format would be to save these objects in, i was looking at https://github.com/bblanchon/ArduinoJson but i don't know if it's possible to deserialize them to the right object.

Is this even possible?

# Answer
There is no such thing as serialization/deserialization in C++. You can read the data values from an object, and you can write data values to an object, as long as you either expose the properties as `public`, or create "getter" and "setter" member functions.

It is then up to you to store and retrieve that data in whatever form you like.

You could store the raw RAM data that corresponds to an object, however if there are any pointers in that object they will be stored as just that - a pointer - which will be meaningless when reloaded. So it's better to store the data values manually.

How you store the data depends on what the data is. Yes, you can use JSON format if you so choose - it has good abstraction for storing strings, escaping special characters, etc. So it would be quite convenient - however, it's quite a heavyweight arrangement. A lighter method would be to store binary data directly, but that is inflexible and can't easily store different types of data in different ways for different objects.

CSV format is quick and easy to parse, but you have to manually deal with things like commas in data strings, etc.
> 1 votes

---
Tags: teensy
---


# Question
Title: Connecting Arduino Uno WiFi Developer Edition to the Internet
I recently bought an Arduino Uno WiFi Developer Edition from here. Although all the other functionality appears to work (I’m able to upload/run programs, read sensors I plug in, etc.), I am not able to connect the Arduino to the internet. The Arduino has a built in ESP8266 chip which is compatible with the WiFi Link library, however, running ScanNetworks in the Arduino mac IDE (File \> Examples \> WiFi Link \> ScanNetworks) doesn't work, nor does it print any errors. Other example files in that library don't work either. The CheckWiFiLinkFirmwareVersion program in the same library will print the welcome message "WiFi Link firmware check." but nothing after that.

I have tried every other WiFi library I could find in the library manager window (Sketch \> Include Library \> Manage Libraries), namely

* Arduino Uno WiFi Dev Ed Library
* WiFiEsp
* WiFi101
* WiFi

However, none of them work. Is the Arduino's WiFi chip defective, or am I doing something wrong? One reviews on the website that I bought the Arduino from said this (see lenny):

> Arduino.org (which is different from arduino.cc) has not made software available to access the WiFi capabilities of this board. As far as I can tell, the wifi cannot be used. They keep saying that the software is coming soon.
>
> See this thread on their forum: http://www.arduino.org/forums/uno/arduino-uno-wifi-arduinowifi-library-incomplete-solution-for-mqtt-tcp-udp-socket-communication-540

In summary, is the Arduino Uno WiFi Developer Edition known to be defective? If not, what am I doing wrong? If it is, could I potentially get a WiFi shield and use that instead of the built in chip? I have other shields for the Arduino (e.g. an SD card shield) that are working fine.

# Answer
> 1 votes
Do you have access to the Webgui?

with the Webgui you can configure the wifi settings. you do not need to upload sketches for this. It is a good test if there is no defect.

Connect your PC Wi-Fi or with your smartphone directly to the Aduino uno wifi. Start your browser and type in the following IP: 192.168.240.1 and now you should see the WebGUI.

# Answer
> 0 votes
The correct WiFi library for that board is here:

If that is not working you may have a defective board. Maybe the ESP8266 firmware is incorrect.

# Answer
> 0 votes
I am sure it is not defective. You just don't understand how it works, because of it's architecture. In addition the original firmware and the UnoWifiDefEd library are strange and limited. I recommend using WiFi Link firmware and library. I currently write a community documentation for the Uno WiFi & WiFi Link

---
Tags: arduino-uno-wifi-dev-ed
---


# Question
Title: Getting wrong values from serial.read() connected to a Raspberry Pi
I set up a serial connection and sending integers from a Raspberry Pi to an Arduino.

This is the Python code in my Raspberry Pi:

```
import serial
ser = serial.Serial('/dev/ttyACM2', 9600)
ser.write(str(x_value));

```

And this is the command line output for `x_value`:

> -38 -38 -38 -40 - 38 - 39 - 40 - 12 18 26 25 49...

They are x coordinate values I generated and they range from -100 to 100. And here's the Arduino code for receiving serial data:

```
int ByteReceived;

void loop() {
  while(1) {
    if (Serial.available() > 0) {
      ByteReceived = (Serial.read());
      Serial.print(ByteReceived);
      Serial.print("\n");
    }
  }

```

On the serial monitor I'm receiving these numbers:

> 46 45 51 48 45 53 52 45 49 52 45 52 55 55....

They are numbers between 40-60 and no way proportional to the values I sent from `serial.write`.

I'm really confused right now. Can someone help me to figure out what caused this problem?

Thank you so much.

# Answer
> 3 votes
```
ser.write(str(x_value));

```

Writes the string representation of the integer `x_value`, which is a sequence of ASCII characters.

```
ByteReceived = (Serial.read());
Serial.print(ByteReceived);

```

Reads a character (byte) and prints to the value (again as a sequence of characters).

```
45 51 48 45 53 52 45 49 52 45 52 55 55....

```

`45` is ASCII character value for the character '-', `51` is the character '3', `48` is '0' and so on.

Cheers!

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


title: Concave button wiring with Arduino

text:
# Question
Title: Concave button wiring with Arduino
I am new to working with Arduino and I have a basic question.

I have an entire circuit set up and functioning, but I would like to add an arcade style button (Larger concave style) like this.

So my question is, how would I go about wiring this button to the Arduino? I don't need this button to control any lights or any other functions. The basic function of this button is for my code to register if the button is pressed or not. I also have the code done. I just want to know how to wire this.

Also I don't know if this helps, but I already have two normal tactile buttons (with 4 pins) in the circuit connected with a pull-up resistor and I know how to connect them. I just have no idea how to go about with only 2 pins.

Any help would be greatly appreciated. Thanks.

# Answer
A simple switch, frequently called single pole single throw, will have only two pins. A switch works by breaking the circuit. This is shown in a wiring diagram in this manner:

It matters not that the switch in this image is not the same switch as in the image you linked, the operation is identical. You may find momentary switches with similar appearance and identical diagrams. The difference is that one has to hold the button to make (or break) a circuit, which reverts once released.

You mention four pins. Those switches are electrically identical to the SPST switch, except that you may find you can control two independent circuits that both activate when the button is pressed. That would be a double pole single throw. There is also the possibility that the four-pin switch has common connections on each side. That is to say that if you connect your circuit to one pin, it is conductive to the other on on the same side, while the closure of the switch will also equally effect the two pins on the opposite side. I've found some tiny switches that have this arrangement, ostensibly to provide for four points to solder to the circuit board, making for a more sturdy attachment.

One can find some useful switch information on Electronics Hub, which is too exhaustive to cover here.

There are many other types of switches
> 1 votes

---
Tags: arduino-uno, button, wires, breadboard
---


# Question
Title: Reading from a pin Arduino Uno (assembly)
I am creating a project in which an Arduino reads (gets) a value from a DHT sensor. The DHT sensor returns two values:

1. Temperature
2. Humidity

My assembly code:

```
sbi ddrd,5
cbi ddrd,2
sbi portd,5

start:

in r16,Pind2
cpi r16,80
brne On

jmp start

On:
cbi portd ,5
jmp start

```

After the code, the light remains turned on, but if the sensor sends '80' and I get it correctly it should be turned off.

Question: Am I Using the write way to read a pin?

# Answer
You are simply reading the state of the input pin - this won't work.

Study the datasheet for the DHT22, available from Sparkfun or eslewhere.

To get data from the DTH22, you must first send a start signal, wait a specified time, then watch the level of the data line, measuring the time of each bit to determine whether it is a 1 or 0, and store the bits in five 8-bit variables. You can then examine those variables to determine the temperature and humidity.
> 2 votes

# Answer
Instructions for **writing** to an individual output bit:-

```
 sbi portd,5 ; make Port D output bit 5 high (set)

 cbi portd,5 ; make Port D output bit 5 low (clear)

 sbi pind,5  ; toggle Port D output bit 5 (low -> high, high -> low)

```

Instructions for **reading** an individual I/O pin:-

```
 sbis pind,2 ; skip next instruction if Port D pin 2 is high

 sbic pind,2 ; skip next instruction if Port D pin 2 is low

```
> 2 votes

---
Tags: atmel-studio
---


# Question
Title: Arduino IDE documentation for WiFi.connected()
I'm including this library "ESP8266WiFi.h" at the top of my sketch. I can find documentation on `WiFiServer.available()`, but didn't find for `WiFi.connected()`, which is called in a server sketch after getting the client.

Clearly it's a test whether (once? I believe) the client is connected or not (and hasn't been explicitly closed in the server's side). It may seem obvious but some documented info would be helpful though.

# Answer
You'll find it defined in `WifiClient.h`. The version I am using is, in `WifiClient.cpp`:

```
uint8_t WiFiClient::connected() {
  if (!_client)
    return 0;
  return _client->state() == ESTABLISHED || available();
}

```
> 1 votes

---
Tags: arduino-ide, wifi
---


title: Garbled high bits on serial output

text:
# Question
Title: Garbled high bits on serial output
I'm trying to send the byte `0x5A` (`0b01011010`) on the serial output of an Arduino Due. My program is based on this example project, but I've stripped out all the unrelated parts:

```
#![feature(lang_items)]
#![no_std]
#![no_main]

extern crate sam3x;

pub mod rust_base;
use sam3x::*;
use sam3x::hal::peripherals::{Peripheral};
use sam3x::drivers::led::{Led};
use sam3x::hal::rtt::{init_timer, wait_ms};
use sam3x::hal::pmc;
use sam3x::hal::uart;

#[link_section=".vectors"]
pub static VECTOR_TABLE: VectorTable =
    VectorTable {
        reset_handler : start,
        exceptions    : [0; 14],
    };

fn start() -> ! {
    init_timer();
    pmc::enable_peripheral_clock_0(Peripheral::PioC);

    let led = Led::connect(Peripheral::PioB, 27).expect("Wrong pin for led.");
    let tx = uart::Tx::init(uart::BR_9600);

    let mut led_on = true;
    led.on();
    loop {
        tx.write_byte(0b01011010);

        wait_ms(250);
        if led_on {
            led.off()
        } else {
            led.on()
        }
        led_on = !led_on;
    }
}

```

As you can see, all I do is send out the byte `0x5A` four times a second, with some LED blinking just to show the program is running.

My problem is that if I connect a serial terminal program with 9600-8N1 settings, I am not getting `0x5A`; instead, I am getting mostly `0xBA`, and sometimes a `0x9A` slips through.

Writing out the bits:

```
0101 1010    5A
1011 1010    BA
1001 1010    9A

```

Note that the lower nybble is always correct, which is why I don't think it's a serial communication setting issue; also, it's pretty clear from `uart::Tx::init`'s implementation that it defaults to no parity bits.

# Answer
> 1 votes
It seems this error is specific to the Rust ARM library I am using; quoting from https://github.com/klangner/sam3x/issues/9:

> It looks that at bound rate=9600 the timer sends data with the speed of ~888. And then computer can't understand the output.

Based on this, I started playing around with the baud rate I pass to the library when initializing it, and using 11000 instead of 9600 empirically seems to work (i.e. I am seeing a steady stream of `0x5A` on my PC receiving at 9600).

---
Tags: serial, arduino-due
---


# Question
Title: What do the pins on this KS0107+KS0108 display do?
I got this display on ebay and I have no instructions on how to use it. I can guess what most of them do but I'd rather be sure I know what they all are instead of messing around trying to guess. The ebay page said the screen is a KS0107+KS0108 128x64 display.

Is there any documentation on what these pins do and which ones I need to connect to my arduino uno to get it working?

# Answer
glcd-arduino (GLCDv3) is an unofficial Arduino library that supports Graphic LCDs (GLCD) that use the KS0108 (or equivalent) chip.
> 2 votes

---
Tags: lcd, pins
---


# Question
Title: MySensors GatewaySerial code not compiling
I am trying to compile GatewaySerial code from MySensors library for my Arduino Leonardo and it gives me EEPROM errors.

Gateway code:

```
/**
* The MySensors Arduino library handles the wireless radio link and protocol
* between your home built sensors/actuators and HA controller of choice.
* The sensors forms a self healing radio network with optional repeaters. Each
* repeater and gateway builds a routing tables in EEPROM which keeps track of the
* network topology allowing messages to be routed to nodes.
*
* Created by Henrik Ekblad
* Copyright (C) 2013-2015 Sensnology AB
* Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
*
* Documentation: http://www.mysensors.org
* Support Forum: http://forum.mysensors.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
*******************************
*
* DESCRIPTION
* The ArduinoGateway prints data received from sensors on the serial link.
* The gateway accepts input on seral which will be sent out on radio network.
*
* The GW code is designed for Arduino Nano 328p / 16MHz
*
* Wire connections (OPTIONAL):
* - Inclusion button should be connected between digital pin 3 and GND
* - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series
*
* LEDs (OPTIONAL):
* - To use the feature, uncomment any of the MY_DEFAULT_xx_LED_PINs
* - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved
* - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly
* - ERR (red) - fast blink on error during transmission error or recieve crc error
*
*/

// Enable debug prints to serial monitor
#define MY_DEBUG

// Enable and select radio type attached
#define MY_RADIO_NRF24
//#define MY_RADIO_NRF5_ESB
//#define MY_RADIO_RFM69
//#define MY_RADIO_RFM95

// Set LOW transmit power level as default, if you have an amplified NRF-module and
// power your radio separately with a good regulator you can turn up PA level.
#define MY_RF24_PA_LEVEL RF24_PA_LOW

// Enable serial gateway
#define MY_GATEWAY_SERIAL

// Define a lower baud rate for Arduino's running on 8 MHz (Arduino Pro Mini 3.3V & SenseBender)
#if F_CPU == 8000000L
#define MY_BAUD_RATE 38400
#endif

// Enable inclusion mode
#define MY_INCLUSION_MODE_FEATURE
// Enable Inclusion mode button on gateway
//#define MY_INCLUSION_BUTTON_FEATURE

// Inverses behavior of inclusion button (if using external pullup)
//#define MY_INCLUSION_BUTTON_EXTERNAL_PULLUP

// Set inclusion mode duration (in seconds)
#define MY_INCLUSION_MODE_DURATION 60
// Digital pin used for inclusion mode button
//#define MY_INCLUSION_MODE_BUTTON_PIN  3

// Set blinking period
#define MY_DEFAULT_LED_BLINK_PERIOD 300

// Inverses the behavior of leds
//#define MY_WITH_LEDS_BLINKING_INVERSE

// Flash leds on rx/tx/err
// Uncomment to override default HW configurations
//#define MY_DEFAULT_ERR_LED_PIN 4  // Error led pin
//#define MY_DEFAULT_RX_LED_PIN  6  // Receive led pin
//#define MY_DEFAULT_TX_LED_PIN  5  // the PCB, on board LED

#include

void setup()
{
    // Setup locally attached sensors
}

void presentation()
{
    // Present locally attached sensors
}

void loop()
{
    // Send locally attached sensor data here
}

```

Error:

```

In file included from /home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.cpp:20:0,
                 from /home/szymex/Arduino/libraries/MySensors/MySensors.h:64,
                 from /home/szymex/Arduino/libraries/MySensors/examples/GatewaySerial/GatewaySerial.ino:86:
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp: In function 'bool transportAssignNodeID(uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp:503:3: note: in expansion of macro 'hwWriteConfig'
   hwWriteConfig(EEPROM_NODE_ID_ADDRESS, newNodeId);
   ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp: In function 'void transportSetRoute(uint8_t, uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MyTransport.cpp:1065:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_ROUTES_ADDRESS + node, route);
  ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'void _begin()':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:140:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_PARENT_NODE_ID_ADDRESS, MY_PARENT_NODE_ID);
  ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'bool _processInternalMessages()':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:56:114: error: 'eeprom_update_block' was not declared in this scope
 #define hwWriteConfigBlock(__buf, __pos, __length) eeprom_update_block((void*)(__buf), (void*)(__pos), (__length))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:415:4: note: in expansion of macro 'hwWriteConfigBlock'
    hwWriteConfigBlock((void*)&_coreConfig.controllerConfig, (void*)EEPROM_CONTROLLER_CONFIG_ADDRESS,
    ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp: In function 'void saveState(uint8_t, uint8_t)':
/home/szymex/Arduino/libraries/MySensors/hal/architecture/AVR/MyHwAVR.h:54:82: error: 'eeprom_update_byte' was not declared in this scope
 #define hwWriteConfig(__pos, __val) eeprom_update_byte((uint8_t*)(__pos), (__val))
                                                                                ^
/home/szymex/Arduino/libraries/MySensors/core/MySensorsCore.cpp:499:2: note: in expansion of macro 'hwWriteConfig'
  hwWriteConfig(EEPROM_LOCAL_CONFIG_ADDRESS+pos, value);
  ^
exit status 1

```

# Answer
> 0 votes
Fixed here: https://github.com/mysensors/MySensors/issues/1007 I needed to update Arduino IDE, reinstall board definitions and MySensors library

---
Tags: arduino-ide, arduino-leonardo, eeprom, compilation-errors
---


# Question
Title: How to embed a 5V-range Arduino-based controller in a 12V-range DC circuit?
We have an installation that provides:

* a common line (C), which divides into two wires;
* an input line (I), which carries the signal from a button (between I and C there's normally 0V, and 12V when the button is pressed);
* an output line (O), which carries a signal to a bell (between O and C there's always 12V).

simulate this circuit – Schematic created using CircuitLab

A controller is to close the OC circuit every time a given temporal pattern shows in I (say, a concrete Morse-like -short/long- sequence of pulses), so the bell will ring if the concrete word is recognized at the input. Such a controller has been implemented in C++ and uploaded to an Arduino Nano, and it works fine on a protoboard, with a button as input and led as output, all in the same electrical range.

Since both the IC and the OC are 12V circuits, and the controller is in the 5V range, what is the *minimal circuit* to embed the controller between the IC and the OC circuits?

# Answer
> 0 votes
easy:

1) use a transistor's b-c junction;

2) use a mosfet;

3) use a relay, solid state or mechanical;

4) find a chip with 12-compliant pins;

...

# Answer
> 1 votes
Just use a **transistor that can handle 12**V with the base connected to the Arduino and that's it...

Maybe I didn't get what you were trying to say, but anyway, I think that's what you are looking for.

# Answer
> 1 votes
I think you can use "mosfet" control 12v with 5v voltage also if you think this is insufficient you can add the relay, control relay with mosfet without how much voltage as you want. I made disco lights with rgb strip led and when I run the circuit different time and different type of led turn on and turn off I used 3 mosfets and 3 arduino outputs the strip led work with 12v.

---
Tags: arduino-nano, relay, electricity
---


# Question
Title: Arduino Yun not showing anything on the serial monitor
I am having issues with the ArduinoYun. It's not showing any data in the serial monitor. The sensor lights up when I plug it in but that's about it and the code seems to compile but nothing is coming through. I am using the Adafruit color sensor. I have SDA/SCL connected to pins 4 and 5. The servo is connected to pin 3. The rest is just on Vin and GND.

```
#include "Servo.h"
#include "Wire.h"
#include "Adafruit_TCS34725.h"

const int redPos = 160;
const int orangePos = 130;
const int yellowPos = 100;
const int greenPos = 70;
const int bluePos = 30;
const int nonePos = 0; // Kein Objekt erkannt

Servo myservo;

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_1X);

void setup() {
  Serial.begin(9600);
  Serial.println("Makerblog.at - MuMs Color Sensor");
  if (tcs.begin()) {
    Serial.println("Sensor gefunden");
  } else {
    Serial.println("TCS34725 nicht gefunden ... Ablauf gestoppt!");
  while (1);
  }
  // Der Servo hängt am PWM-Pin 3
  myservo.attach(3);
  // Servo in Grundstellung fahren
  myservo.write(0);
  delay(1000);
}

void loop() {
  uint16_t clearcol, red, green, blue;
  float average, r, g, b;
  delay(100); // Farbmessung dauert c. 50ms
  tcs.getRawData(&red, &green, &blue, &clearcol);
  average = (red+green+blue)/3;
  r = red/average;
  g = green/average;
  b = blue/average;

  // Clear-Wert und r,g,b seriell ausgeben zur Kontrolle
  // r,g und b sollten sich ca. zwischen 0,5 und 1,5
  // bewegen. Sieht der Sensor rot, dann sollte r deutlich über 1.0
  // liegen, g und b zwischen 0.5 und 1.0 usw.
  Serial.print("\tClear:"); Serial.print(clearcol);
  Serial.print("\tRed:"); Serial.print(r);
  Serial.print("\tGreen:"); Serial.print(g);
  Serial.print("\tBlue:"); Serial.print(b);

  if ((r > 1.4) && (g < 0.9) && (b < 0.9)) {
    Serial.print("\tROT");
    myservo.write(redPos);
  } else if ((r < 0.95) && (g > 1.4) && (b < 0.9)) {
    Serial.print("\tGRUEN");
    myservo.write(greenPos);
  } else if ((r < 0.8) && (g < 1.2) && (b > 1.2)) {
    Serial.print("\tBLAU");
    myservo.write(bluePos);
  } else if ((r > 1.15) && (g > 1.15) && (b < 0.7)) {
    Serial.print("\tGELB");
    myservo.write(yellowPos);
  } else if ((r > 1.4) && (g < 1.0) && (b < 0.7)) {
    Serial.print("\tORANGE");
    myservo.write(orangePos);
  } else {
    Serial.print("\tNICHT ERKANNT");
    myservo.write(nonePos);
  }
  Serial.println("");
  delay(100);

```

# Answer
Assuming the code works, you should be able to change the position of the servo by altering the initialized color values. Currently they are:

```
 const int redPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int greenPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

```

If, for example, the positions of Red and green are to be swapped all that is needed is to alter the code like this:

```
 const int greenPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int redPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

```

The numbers, according to the Arduino's servo driver web page, are the angle in degrees the servo will be moved to after executing the call to the Arduino servo driver.

Given the above, if a new color violet were to be added to the original set of colors the first change would be to move the servo positions slightly higher to make room for the new color.

```
 const int redPos = 160;
 const int orangePos = 135;
 const int yellowPos = 110;
 const int greenPos = 85;
 const int bluePos = 60;
 const int violetPos = 35;
 const int nonePos = 0;

```

The next change would be to alter the ranges of the color test code. As you did not specify what hardware you are using to detect colors, you will have to experiment to find the combination of red, green & blue which matches the new color violet. The code used for detecting blue is:

```
 else if ((r < 0.8) && (g < 1.2) && (b > 1.2))

```

Likely violet contains more red and may be detectable with a line of code like this:

```
 else if ((r > 1.0) && (g < 1.2) && (b > 1.2))

```

The position of this test may be important depending on how the detector works. It may be best to place it after testing for orange. Remember to use the new initialized variable such that you code may look like this:

```
else if ((r > 1.0) && (g < 1.2) && (b > 1.2)){
  Serial.print("\tVIOLET");
  myservo.write(violetPos);
}

```
> 0 votes

---
Tags: sensors, servo, adafruit
---


title: How to get ESP8266 firmware version?

text:
# Question
Title: How to get ESP8266 firmware version?
I am going to update the firmware of an ESP8266 module, but first I would like to know the current version or name.

How can I get it? Maybe with an AT command?

This is my ESP8266 module:

# Answer
ESP8266 and the AT firmware are products of Espressif. They have everything documented on the web site.

The AT command for version is `AT+GMR`.
> 2 votes

---
Tags: esp8266, communication, firmware
---


# Question
Title: Arduino 101 accelerometer drift or calculation error?
I want to calculate the displacement of the Arduino 101 board compared to the starting point (only in the x direction so far).

In below data I'm swinging the board multiple times in circles around my laptop and then putting it back at the origin a few seconds later.

Regardless if 1ms-100ms between the loops, the numbers show no sign of the board returning to the origin. I've calibrated the accelerometer x-axis as closely as possible.

Am I doing something wrong in deriving the acceleration/velocity/distance, or is this the level of compounding error to expect?

If so, can combining gyro data correct acceleration (thought it mainly worked the other way around)?

I have a GPS meant for correcting position but was hoping any drift wouldn't be this quick.

EDIT: I was incorrect re. use of gyro data; the attitude of the board, which was not consistent in my swings, will effect the acceleration output. Gyro data can be used to calculate and "cancel out" this gravitational impact, and get a more accurate (linear) acceleration (http://www.cl.cam.ac.uk/research/dtg/www/files/publications/public/abr28/ojw28\_thesis.pdf). Will report back in a few days.

Code:

```
#include "CurieIMU.h"

float gravity = 9.80665; // to convert G forces (1 m/s2 = 0.101972 g; 1 g = 9.80665 m/s2)
long t1; // create object for first time reference, set time just before the loop later on

// Variables that are dependent on value from last loop
float vx, vy, vz;
float imu_x, imu_y, imu_z;

void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial to open

  Serial.println("Initializing IMU device...");
  CurieIMU.begin(); // start accelerometer / gyro
  CurieIMU.setAccelerometerRange(2);  // accelerometer range to 2G - might need to be greater later on (18 m/s2 highest possible now)

  /*

  // Auto-calibration to ensure accelerometer doesn't drift
  CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS, 0); // 89.69999 creates both positive and negative spikes
  delay(1000);
  CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS, 0);
  delay(1000);
  CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS, 1);
  delay(1000);

  */

  // Hardcoded accelerometer offsets after testing
  CurieIMU.setAccelerometerOffset(X_AXIS,89);

  // Fetch the offsets from the IMU
  float x_offset = CurieIMU.getAccelerometerOffset(X_AXIS);
  float y_offset = CurieIMU.getAccelerometerOffset(Y_AXIS);
  float z_offset = CurieIMU.getAccelerometerOffset(Z_AXIS);

  Serial.println("Current x_offset, y offset, z offset");
  Serial.print(x_offset, 6);
  Serial.print("\t");
  Serial.print(y_offset, 6);
  Serial.print("\t");
  Serial.println(z_offset, 6);
  delay(5000);

  t1 = millis(); // set the first time reference

  Serial.println("ax_g (g), ax (m/s2), t1 (ms), t2 (ms), td (ms), tds (s), vx (m/s), imu_posx (m)");

}

void loop() {

  // Fetch G forces
  float ax_g, ay_g, az_g;   //scaled accelerometer values
  CurieIMU.readAccelerometerScaled(ax_g, ay_g, az_g); // read accelerometer measurements from device, scaled to the configured range

  // Convert G force to m/s2
  float ax = ax_g / gravity;
  float ay = ay_g / gravity;
  float az = az_g / gravity;

  // Calculate time since last loop
  long t2 = millis();
  float td = t2 - t1; // time delta in ms
  float tds = td / 1000; // delta in seconds for easier logic

  // Calculate current velocity: velocity (m/s) = velocity (m/s) + acceleration (m/s2) * deltaTime (s)
  vx = vx + ax * tds;
  vy = vy + ay * tds;
  vz = vz + az * tds;

  // Calculate position: position (m) = position (m) + velocity (m/s) * deltaTime (s)
  imu_x = imu_x + vx * tds;
  imu_y = imu_y + vy * tds;
  imu_z = imu_z + vz * tds;

  // Print the values
  Serial.print(ax_g, 6);
  Serial.print("\t");
  Serial.print(ax, 6);
  Serial.print("\t");
  Serial.print(t1);
  Serial.print("\t");
  Serial.print(t2);
  Serial.print("\t");
  Serial.print(td, 6);
  Serial.print("\t");
  Serial.print(tds, 6);
  Serial.print("\t");
  Serial.print(vx, 6);
  Serial.print("\t");
  Serial.println(imu_x, 6);

  // Reset start values for next loop
  t1 = millis();

  delay(1);

}

```

# Answer
> 1 votes
The Arduino 101 contains the Intel® Curie™ Module, this module contains an Inertial Measurements Unit or IMU for short among other sensors and peripherals

The IMU of this module is Bosch BMI160 which is a low cost MEMS IMU, this IMUs typically suffer from systematic errors and random/stochastic errors, the following diagram summarize them:

If we take the bias error as an example of those errors, an uncompensated accelerometer bias introduces an error proportional to time (t) in the velocity and proportional to t^2 in the position. For example, consider a case where accelerometer bias is 10 m/s^2. If this bias offset is not removed from the measurements, it can generate a 500 m error in position after 10 seconds and 12.5 km error after 50 seconds. Let us back to our IMU, if we read the data sheet the Zero-g error "or bias" is 40mg for the 8g sensing accelerometer and Ta = 25 Celsius with normal VDD and the IC has been assembled on board. If we just consider this 40mg bias error "dropping other error sources" it is 0.392266 m/s^2 so after 10 seconds the position offset will be 1.96133 meter even if you don't move the Arduino. I suggest you read "MEMS-Based Integrated Navigation" book here it will give you a good vision about MEMS based inertial sensors and basic navigation concepts.

---
Tags: accelerometer, arduino-101
---


title: How to reduce sketch size?

text:
# Question
Title: How to reduce sketch size?
How to reduce sketch size?

I got an error that “Sketch uses 30,044 bytes (104%) of program storage space. Maximum is 28,672 bytes.”

I can't reduce function in sketch.I can't change ATmega32u4,now. The sketch has function of measuring sensor,logging on SD,connection with BLE module.

So please tell me hack.

Or,how to increase flash memory size?

I tried to change type of String to Char.

# Answer
> 4 votes
Some generic techniques you can try:

* Remove duplicate code and put it in a function.
* If you have duplicate code that is ALMOST duplicate, parameterize it (i.e. add a function, make the difference a parameter(s) of the function and call from various locations with different argument(s).
* Use a micro controller with more Flash memory.
* Minimize the data storage, limiting array sizes for example (if these are in flash RAM).
* If you use precalculated arrays, remove them and create a function calculating them real time (this will be a performance cost of course).
* Check for dead code inside functions. A smart compiler will already remove uncalled functions, but do not check inside functions.
* Remove or minimize debug/print statements. Each character cost a byte, which adds up quickly with many strings.
* Try to remove complete libraries, like removing the Serial for print statements used only for debugging.

# Answer
> 2 votes
There's no magic bullet. You have to work through your code and see what you can remove safely. If you have duplicate code, put it in a function and call this. If you `Serial.print` a lot of text, considering saving up on that. etc etc etc

# Answer
> 2 votes
> How to reduce sketch size?

without your code, tough to be specific. but generally:

1) try not to use floating pointmath;

2) try not to use printf() or its derivative;

3) try to minimize large arrays;

4) use functions instead of macros;

5) use modular programming;

...

> Or,how to increase flash memory size?

1) use a bigger chip;

2) use onboard eeprom;

3) use outboard eeprom / flash / fram / ....

4) divide up the tasks among multiple chips;

...

# Answer
> 2 votes
If you're using donated libraries to run your hardware (such as the Dallas Temperature library) or provide software features (like SimpleTimer), the authors often provide a full complement of features, some of which you may not need. I often make my own versions of these libraries that provide the functionalities I must have, and cut out the others. I can always add one or two of them back into whichever sketch needs them, without burdening other sketches with their overhead.

In SimpleTimer, for instance, I seldom have need for enable/disable timer or for a timer that runs N-times and then stops, so I have a version of the library with those functions removed.

If you've declared some text strings or other data to live in Flash, and you have more spare RAM than spare Flash, let some of those objects live in RAM instead. Or reduce the length of output strings that are stored in Flash by writing more tersely, even at the cost of clarity in the output, or eliminating that outpu altogether (which eliminates not only the string data but the code to print it, as well).

Can you reduce any code segments or algorithms with more space-efficient code? Can you eliminate some functionality to save code space?

Note that trimming buffers and arrays won't help because those are in RAM, and data packing, such as storing a number of booleans as distinct bits within a word, will actually increase your code size (this is a common way to reduce RAM requirements when you can afford the code to do the packing/unpacking, but you have the opposite problem!).

---
Tags: arduino-nano, sketch-size
---


# Question
Title: MAX7219 library that can compensate for poorly designed/miswired 8x32 panel?
I have this sample code:

```
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

#define MAX_DEVICES 4
#define CLK_PIN   11
#define DATA_PIN  12
#define CS_PIN    10

MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

void setup(void) {
  P.begin();
  P.print("PPPPPPPP");
}

void loop(void) {
}

```

And this is how it lights up the display:

I presume that the code displays text incorrectly, because the display manufacturer has connected individual 8x8 displays "differently than any library expects" (i.e. in red I have annotated the column addresses for my display, while with green I have annotated what they would have to be for this library to show text correctly).

I have two questions:

1. Is there any good Arduino graphics library that would allow me to fix from software the addressing issue specific to my display?
2. Since in the future I plan to make a 16x64 display out of 4 of these, then is there a library capable of doing that as well (i.e. have vertical font size of 12-16 pixels)?

# Answer
The issue is minor. It looks like the library was designed for a slightly different matrix display / wiring.

Take a look at the library and it likely maps the input buffer to segment / dot-matrix information. Play with that.

The author did 99% of the work for you. You just need to finish the last 1%.
> 1 votes

---
Tags: led, display, max7219
---


# Question
Title: How to send signal ONCE when within constant range of sensor?
I am working on a project to have a open/close a solenoid at certain ranges (using HC-SR04 ultrasonic sensor).

```
#include <NewPing.h>2

#define Relay1 7
#define Relay2 8

NewPing SonarRight(12, 11, 400);

void setup() {
  pinMode(Relay1, OUTPUT);
  pinMode(Relay2, OUTPUT);
}

void loop() {

  unsigned int uS1 = SonarRight.ping();
  delay(50);

  if (uS1 / US_ROUNDTRIP_CM > 15)
    digitalWrite(Relay1, HIGH);
    delay(100);
    digitalWrite(Relay1, LOW);
    delay(1000);

  if (uS1 / US_ROUNDTRIP_CM < 5)
    digitalWrite(Relay2, HIGH);
    delay(100);
    digitalWrite(Relay2, LOW);
    delay(1000);
}

```

I got the sensor to ping correct and the distances are reading accurately. I have it to where once sensor reads that the object is more than 15cm away, the solenoid opens but it keeps clicking open until the object goes back to the dead zone (5-15cm). Same thing when less than 5cm. Essentially what i am trying to accomplish is to have the solenoid fill up a tank when the water level get low. So when the water drops 10cm (x\>15) the solenoid opens and then once the water is replenished (x\<5), the solenoid closes.

How do i go about doing this without sending a constant OPEN/CLOSE to the solenoid? Is there a way to make a loop to have it send a the signal only once until it exits that defined range?

Please note that i have not actually used it for its intended purpose im supply moving an object back and forth to simulate water distance.

Thanks

# Answer
> 1 votes
You have to add a (global) variable that stores the last send command (to open/close).

When you send a command, you save it in the global variable.

And you only send a command when it is different than the command send the last time, so only CHANGES are sent.

The best way to do this is to make a specific function, e.g. SetSolenoid(bool open);

```
#define SOLENOID_OPEN  TRUE
#define SOLENOID_CLOSE FALSE

bool _currentSolenoidStatus = false; // Assume closed

```

In your loop:

```
...
if  ... condition when solenoid should be be opened
{
    SetSolenoid(SOLENOID_OPEN);
}
...
if  ... condition when solenoid should be be closed
{
   SetSolenoid(SOLENOID_CLOSE);
}

```

Function to open/close solenoid open (only when changed):

```
bool SetSolenoid(bool status)
{
    if (_currentSolenoidStatus != status)
    {
        // Send status to solenoid
        _solenoidStatus = status;
    }
}

```

---
Tags: arduino-uno, programming, sensors, signal-processing
---


# Question
Title: HC-05 Bluetooth module doesn't read data correctly from my Android phone
I have made a home automation project where am using an Arduino Uno and HC-05 Bluetooth module and an Android app. I did everything properly but when I send commands from my Android app it works sometimes and sometimes it doesn't work.

I checked these commands on the serial monitor and found that data command I recieve at serial monitor did not match the commands which I send from my Android app. For example my Android app send command "ON1" but on serial monitor it shows "OL1?". I thought it might be a problem with the HC-05 so I changed it and used a new HC-05 module, but the problem is still there.

This time I checked the commands from another Android app (Bluetooth Terminal HC-05) and there was the same problem. Sometimes it read the command correctly app and sometimes it read something else.

I am so confused weather the problem is in my hardware side or software side.I tried a lot but didn't get any solution about my problem anywhere. Can anybody help me please?

This is the Arduino code of my project:

```
#include <SoftwareSerial.h>
SoftwareSerial Genotronex(2, 3); //TX, RX  pins of arduino respetively
String command;
void setup() {
  Genotronex.begin(9600);
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
}

void loop() {
  while (Genotronex.available()) {
  //Check if there is an available byte
    to read
    delay(10); //Delay added to make thing stable
    char c = Genotronex.read(); //Conduct a serial read
    command += c; //build the string.
  }
  if (command.length() > 0) {
    Serial.print(command);
    if (command == "ON1") {}
    //this command will be given as an input to switch on light1
    digitalWrite(9, HIGH);
  } else if (command == "OFF1") {
    //this command will be given as an input to switch off light1 simillarly other commands work
    digitalWrite(9, LOW);
  } else if (command == "ON2") {
    digitalWrite (10, HIGH);
  } else if ( command == "OFF2") {
    digitalWrite (10, LOW);
  } else if (command == "ON3") {
    digitalWrite (11, HIGH);
  } else if (command == "OFF3") {
    digitalWrite (11, LOW);
  } else if (command == "ON4") {
    digitalWrite (12, HIGH);
  } else if (command == "OFF4") {
    digitalWrite (12, LOW);
  } else if (command == "ON5") {
    digitalWrite (13, HIGH);
  } else if (command == "OFF5") {
    digitalWrite (13, LOW);
  } else if (command == "all on") {
    //using this command you can switch on all devices
    digitalWrite (9, HIGH);
    digitalWrite (10, HIGH);
    digitalWrite (11, HIGH);
    digitalWrite (12, HIGH);
    digitalWrite (13, HIGH);
  } else if (command == "off") {
    //using this command you can switch off all devices
    digitalWrite (9, LOW);
    digitalWrite (10, LOW);
    digitalWrite (11, LOW);
    digitalWrite (12, LOW);
    digitalWrite (13, LOW);
  }
  command = "";
} //Reset the variable

```

# Answer
I suggest to have a look at this answer: Change the baud rate of HC-05

In many case and especially when you send data from Android and receive bad data on Arduino, it's because the speed is not set correctly. On the other side (getting data from the Arduino), it's a bit more complicated. You have to build your own "time out" system on Android as the Bluetooth library don't have such a feature.
> 1 votes

---
Tags: bluetooth, softwareserial, hc-05
---


title: Arduino int problem

text:
# Question
Title: Arduino int problem
I made a counter to count pulses:

```
int count  = 0 ;
.
.
.
setup()
{
}

while (count <= 35000)
{
  digitalWrite(9, HIGH);
  delayMicroseconds(500);
  digitalWrite(9, LOW);

  count = count + 1;
}

```

But when I try `while(count <= 40000)`, it does not stop counting.

# Answer
`int` in AVR GCC is 16 bits. ***All*** possible `int` values are less than 32767.
> 7 votes

# Answer
You have reached the maximum number that an `int` can represent. That is **32767**.

`int` is a variable type that is made up of **16 bits**. It is **signed**, meaning that it can represent positive and negative numbers.

Out of the **65536** (ie. **2^16**) possible numbers from the 16 bits, half of them represent negative numbers and the remaining half represents positive numbers (including zero). Or in other words, **-32768 to 32767**.

If you don't need negative numbers, then you can change your variable type to `unsigned int` which will use numbers up to a maximum of **65535**. So it becomes:

```
unsigned int count = 0;

```
> 2 votes

# Answer
> But when I try while(count \<= 40000), it does not stop counting.

"int" has a range from -32k to +32k-1. so "count \<= 40000" will always be true as count is "int".
> 0 votes

---
Tags: programming
---


# Question
Title: Setting reading frequency SCT013 current sensor code using Arduino Uno
I found this code below for the Arduino platform to obtain current measurements from the SCT013 sensor, and I am wondering how can I define the 'delay' or 'frequency' of my readings? I'd be looking for 200Hz.

Code:

```
//
#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon1;                   // Create an instance

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

  emon1.current(5, 60);             // Current: input pin, calibration.
  //calibration is explained bellow
}

void loop()
{
  double Irms = emon1.calcIrms(1480);  // Calculate Irms only

  Serial.print(Irms*230.0);        // Apparent power
  Serial.print(" ");
  Serial.println(Irms);            // Irms
}
//

```

# Answer
> 1 votes
you skip reading when the last read is less than 1000/200 = 5ms ago.

```
unsigned long lastRead;

void loop()
{
   unsigned long currentMillis = millis();
   if(currentMillis - lastRead >= 5){

      double Irms = emon1.calcIrms(1480);  // Calculate Irms only

      Serial.print(Irms*230.0);        // Apparent power
      Serial.print(" ");
      Serial.println(Irms);            // Irms
      lastRead = currentMillis;
    }

}

```

# Answer
> 0 votes
If you want a 200Hz sample rate this code doesn't work for you.

With this line: `double Irms = emon1.calcIrms(1480);` you take 1480 samples as fast as Arduino can.

If you want 200Hz sample rate, read analog ping every 5ms using millis() function. And when you have enough samples you can calculate the rms current https://en.wikipedia.org/wiki/Root\_mean\_square

This is an example code:

```
unsigned int sample_time = 0;
int readings[200];  //num samples 200
int i = 0;

setup() {
}

loop() {
    if (millis() - sample_time > 5){
        readings[i] = readAnalog(A0);
        i++;
        sample_time = millis();
    }
    if (i > 200)
         Caculate_Irms();
         i = 0;
}

```

---
Tags: arduino-uno, sensors, current
---


# Question
Title: Combing two codes to make it work on the same time but not affecting the other code?
I am trying to make a game where there are arrows going towards an object (in this case I printed x) and you have to evade the arrows. When you press the button it is supposed to print x on the top row and clear the bottom row with printing nothing and if you don't press the button its supposed to print x on the bottom row and nothing on the top. Then the for loop is supposed to print arrows randomly going from right to left.

**Problem: When I actually run the code I only see the x every time the arrow hits the (0,1) or (0,0) position.**

**I want the x to be there all the time.**

```
#include <LiquidCrystal.h>
// init the lcd display according to the circuit
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

String line2 = " x ";
int xPosition;
int yPosition;
int yConstant;

void setup()  {
  lcd.begin(16, 2);
  // put your setup code here, to run once:
  int switchState = 0;
  pinMode(7, INPUT);
  int leftjump = 0;
  pinMode(8, INPUT);
}

void loop() {
  ///////////////////////////////
  //supose tp print arrow randomly going from right to left
  xPosition = 15;
  yPosition = random(0, 10);
  if (yPosition > 5) {
    yConstant = 1;
  }
  else yConstant = 0;
  lcd.setCursor(xPosition, yConstant);
  for (int xPosition = 15; xPosition > 1; xPosition--) {
    lcd.print("<-");
    delay(100);
    lcd.clear();
    lcd.setCursor((xPosition), yConstant);
  }
  ////////////////////////////
  // suppose to print x on the top row and print nothing on buttom row
  //and otherwise when button is not pressed print x on bottom and
  //print nothing on top row
  int rightjump = 0;
  rightjump = digitalRead(7);
  if (rightjump == 1 ) {
    lcd.setCursor(0, 0);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 1);
    lcd.print("  ");
  }
  else if ( rightjump == 0 ) {
    lcd.setCursor(0, 1);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 0);
    lcd.print("  ");
  }
}

```

# Answer
> -1 votes
There is one big problem with your program, and it is here:

> `delay(100);`

Using `delay()` is bad practice. The Arduino does *nothing* useful while delaying. Quite importantly, it cannot respond to user input. And to make matters worse, you have this delay inside a loop. This means your program will be stuck inside the loop for 1.4 seconds. And during this time it will not take care of reading the button, nor drawing the player on the screen.

The solution is to use `millis()` to manage your timings, and *never* block your program while waiting for something. The approach is well explained in the Blink Without Delay Arduino tutorial. In a nutshell: on every loop iteration, you check the clock and, if it's time to do some particular task, you do it. If it's not time, well, you simply don't do it. Most importantly: you don't wait. If you don't do something on this loop iteration, no worries, you will do it on some other iteration.

With this approach, there are some pieces of information (e.g. arrow position) that will have to be remembered from one loop iteration to the next. This can be done by storing that in global variables. I prefer to to use `static` local variables though, to keep the information confined to where it belongs.

Here is my try at your `loop()`. Notice that both the arrow and the player are managed through the same pattern: `if (it needs to be updated right now) { update it; }`

```
void loop() {
    static uint32_t last_arrow_move;  // last time the arrow moved
    static int arrow_x, arrow_y;
    const int player_x = 0;
    static int player_y;

    // Update the arrow position every 100 ms.
    if (millis() - last_arrow_move >= 100) {
        last_arrow_move += 100;

        // Erase the arrow at its old position.
        lcd.setCursor(arrow_x, arrow_y);
        lcd.print("  ");

        // Move one cell to the left.
        arrow_x--;

        // If too far left, then send a brand new arrow.
        if (arrow_x < 2) {
            arrow_x = 15;
            arrow_y = random(0, 2);
        }

        // Draw the arrow at its new position.
        lcd.setCursor(arrow_x, arrow_y);
        lcd.print("<-");
    }

    // Get the updated player position.
    int new_player_y;
    if (digitalRead(7) == HIGH) {  // "jump" button pressed
        new_player_y = 0;
    } else {
        new_player_y = 1;
    }

    // Update the player if he moved.
    if (new_player_y != player_y) {

        // Erase the player at its old position.
        lcd.setCursor(player_x, player_y);
        lcd.print(" ");

        // Move.
        player_y = new_player_y;

        // Redraw at the updated position.
        lcd.setCursor(player_x, player_y);
        lcd.print("x");
    }
}

```

# Answer
> 0 votes
You have a nested loop. When your for loop is **finished** moving the arrow to column 0 then, and only then, the " x " is displayed, exactly as predicted. You can start by drawing the x from inside the for loop (before the delay) that will make it visible all the time. It's a start anyways.

# Answer
> -1 votes
> Combing two codes to make it work on the same time but not effecting the other code?

the simplest would be to have two arduino and run each piece on one of them.

---
Tags: programming, lcd, button
---


# Question
Title: How do I stop a servo motor at the current position when using a serial port? I want it to remain in one position when receiving "0"
I am working on a project where I would like values received from an Xbox Kinect will activate components on my Arduino. Currently, I am trying to get a servo motor to turn on and rotate when the value is "1" and to remain in one position (currently written as 120degrees) when the value is "0". However, I can turn on the motor and initiate rotation just fine, but when I let go of the mouse (and it shows that the value "0" is being sent in Processing and on the Serial Monitor), the motor just keeps spinning. This is my current code:

```
char val; // Data received from the serial port
#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
}

void loop() {
  if (Serial.available())
  { // If data is available to read,
    val = Serial.read(); // read it and store it in val
  }
  if (val == '1') { // If 1 was received
    Serial.print ("1");// turn the LED on
    for (pos = 0; pos <= 120; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
    for (pos = 120; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }
  }
  if (val == '0') {
    Serial.print ("0");
    pos = 120;
    myservo.write(pos);
  }
}

```

# Answer
Are you sure the mouse is not sending a continuous stream of 1s? If that were the case then, because of buffering, all the 1s will serviced before the servo stops. For example, a sequence of 11111 followed by a 0 will cycle the movement 5 times before it stops and prints the 0.
> 1 votes

# Answer
fairly simple:

```
switch (serial_received()) {
  case -1: break; //-1=nothing received
  case  0: break; //0 received
  case  1: servo_pos = ...; servo_move2(servo_pos); break; //update servo position
  case  .... //other commands
  default: ...
}

```

you can fill in the functions with whatever appropriate for your environment.
> -1 votes

---
Tags: arduino-uno, serial, servo, code-review, serial-data
---


title: Tinyduino I/O line voltage level

text:
# Question
Title: Tinyduino I/O line voltage level
Does anyone know what the I/O line voltage level is on the Tinyduino?

Tinyduino

I want to run a MAX7219 LED array with it, like this one:

LED Array

# Answer
Whatever your power supply voltage is. If you run it from 5V you get 5V IO. If you run it from a 3V coin cell you get 3V IO.
> 2 votes

---
Tags: led, max7219
---


title: Help: Using if-else on two switch state

text:
# Question
Title: Help: Using if-else on two switch state
# Problem

I'm stuck on triggering different switch. I'll explain what each of my switch should do. Output of this setup : No output from `relayPin`

`mainPin`

* Main power of the switch to control `relayPin` — keeps on/off
* Override `reedPin` state
* Let `SecondState`

`reedPin`

* Secondary power switch to control `relayPin` — depends on `mainPin` on/off state
* Overridden by `mainPin`
* Let `FirstState`

\*another explanation in comment

Is it caused by coding or hardware? Pardon my ignorance, it is my beginner code. I would appreciate any help, thank you.

# Code

```
const int reedPin = 8; // Reed Switch
const int mainPin = 9; // Main Switch
const int relayPin = 6; // Relay

int FirstState = 0;
int SecondState = 0;

void setup() {
    pinMode(relayPin, OUTPUT);
    pinMode(reedPin, INPUT);
    pinMode(mainPin, INPUT);

}

void loop() {
    FirstState = digitalRead(reedPin);
    SecondState = digitalRead(mainPin);
    if (FirstState == HIGH) {
        digitalWrite(relayPin, LOW);
    }
    else if (SecondState == HIGH) {
        digitalWrite(relayPin, HIGH);
    }
    else {
        digitalWrite(relayPin, HIGH);
    }
}

```

Only `else if (SecondState == HIGH) {` works in output.

# Schematics

# Answer
Draw a truth table and look at it from there. From your words, it is confusing. From your code it looks like this:

```
mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     HIGH

```

So:

```
void loop() {
      digitalWrite(relayPin, !digitalRead(mainPin));
}

```

If you want:

```
mainPin    reedPin   relayPin
HIGH        LOW      LOW
HIGH        HIGH     LOW
LOW         LOW      HIGH
LOW         HIGH     LOW

```

then:

```
void loop() {
      digitalWrite(relayPin, !(digitalRead(mainPin) || digitalRead(reedPin)));
}

```
> 0 votes

---
Tags: programming, hardware, switch
---


# Question
Title: Where is CLKPR located on Ubuntu 16.04 with Arduino 1.8.3
I would like to see the definition of CLKPR. I guess that similarly to PORTB and other registers, it should be defined by the toolchain? (see Where is PORTB defined? )

* Am I right?
* Where should I look for this toolchain on Ubuntu 16.04? I tried *locate* and *find* commands in terminal with various strings relating to the toolchain expected path / files, but could not find it (tips and tricks on how I may look for such paths in the future would be welcome ;) ).

# Answer
`grep` is the command you want:

```
foo@bar:~/arduino-1.8.2$ grep -r CLKPR .
Binary file ./hardware/tools/avr/avr/lib/avr35/crtattiny167.o matches
Binary file ./hardware/tools/avr/avr/lib/avr35/crtat90usb82.o matches
Binary file ./hardware/tools/avr/avr/lib/avr35/crtatmega8u2.o matches
...
Binary file ./hardware/tools/avr/avr/lib/avr5/crtat90pwm161.o matches
Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega649p.o matches
Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega168pa.o matches
./hardware/tools/avr/avr/include/avr/io90pwm216.h:#define CLKPR   _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom329.h:#define CLKPR   _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom165p.h:#define CLKPR   _SFR_MEM8(0x61)
...
./hardware/tools/avr/avr/include/avr/iom48p.h:#define CLKPR _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom644pa.h:#define CLKPR _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/ioa6289.h:#define CLKPR _SFR_IO8(0x3C)
./hardware/arduino/avr/bootloaders/caterina-Arduino_Robot/Caterina.h:       #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
./hardware/arduino/avr/bootloaders/caterina-LilyPadUSB/Caterina.h:      #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
./hardware/arduino/avr/bootloaders/caterina/Caterina.h:     #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))

```

So it's defined in the IO header for the chip you are using (`hardware/tools/avr/avr/include/avr/io[chip].h`). So for the '328p that's `hardware/tools/avr/avr/include/avr/iom328p.h`.
> 0 votes

---
Tags: frequency, avr-toolchain
---


title: Can I change Vcc to some other pin?

text:
# Question
Title: Can I change Vcc to some other pin?
I was working on an Arduino Uno and while carrying it to my teacher the wire's pin got stuck into the Vcc of 5 V. Can I set Vcc to other inputs? If so, then how?

# Answer
No, you can't. Well, you can if all you want is a few mA (just set a pin to OUTPUT and HIGH), but chances are you need more than that. So no.
> 1 votes

# Answer
The VCC pin is not programmable.

However, both ICSP buses have a pin that connects to the 5V VCC line. See the diagram here: https://i.stack.imgur.com/wKz2l.png These are both male headers while the pin marked 5V is a female header so you will need to use a different connector than what you used previously.

If you choose to go this route, you should use the bottom ICSP header (opposite side of the board from the USB) as it is wired directly to the ATEMEGA328 chip. For this same reason, you should be very careful if you are trying to apply or draw power from any of the 5V pins as they are not protected by a fuse.
> 0 votes

---
Tags: arduino-uno, pins, voltage-level, hardware, input
---


# Question
Title: How to add prefactor to clock frequency at compile time?
I want to use an Arduino Mega at 8MHz because my power supply is bad and I have only 4.3V (no way I can fix that), which is outside the operation range of the ATMega1280 at 16MHz. I think the right way to do it is to put a pre-factor 2 on CLKPR (tell me if I am wrong)? I know that several pages explain how to do so in a sketch: see How can you reduce the clock frequency of an Arduino Mega? , https://playground.arduino.cc/Code/Prescaler .

However, both those methods reduce the Mega frequency at run time, by setting the CLKPR register during the setup loop or another function, mess up with the *millis()*, *delay()*, *Serial* etc, and in addition I guess this means that the Mega is running at an out-of-spec 16MHz until the prefactor is set in the setup loop (?). So my question (I searched for it but found no answer) is:

* Can one set the clock prefactor at compile time, so that:
    + the compiler knows about it,
    + the *millis()*, *delay()*, *Serial* and similar are not disturbed
    + the register is set immediately at boot (i.e. no need to change the registers in the setup)

?

# Answer
1 and 3 can be solved by putting it in one of the initialization sections. 2 can be solved by creating and using a board.txt entry with the appropriate FCPU.

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

void __attribute__((naked, section(".init1"))) preprescale(void)
{
  clock_prescale_set(clock_div_2);
}

```
> 2 votes

# Answer
Clock speed is controlled by fuse settings and as such can be set at compile time - whether that will conflict with your bootloader is anyone's guess.

Gcc-avr allows fuse settings but you will need to burn it separately. F\_CPU needs to be changed accordingly.
> 0 votes

---
Tags: arduino-mega, frequency
---


title: Making a menu through serial

text:
# Question
Title: Making a menu through serial
I'm working on a project for a robot and I'm trying to make a menu that can run on start up where the user can calibrate the mid-point for the servos (so they're stationary) and the ldrs so it can tell between black lines and white paper. So, I've made the menu a switch case where it calls the calibration when user enters a value, the calibration routines are their own functions.

What I want to know how to do is how to make it so when the user is finished with a calibrator it will go back to the menu function and also how to get the menu to exit on user input. So far when the menu calls a function it will just loop on it.

The menu:

```
void Menu(){

  Serial.println("|****************************|");
  Serial.println("|**|Ardnoid Configuration |**|");
  Serial.println("|**|        Menu          |**|");
  Serial.println("|****************************|");
  Serial.println("");
  Serial.println("Select one of the following options:");
  Serial.println("1 LDR configuration");
  Serial.println("2 Servo calibration");
  Serial.println("3 Exit configuration menu");

  while(!Serial.available()){}
  int i = Serial.parseInt();

  switch(i){

  case 1:
    break;
  case 2:
    while(srvConOn == true){
      srvConfig();
      }
    break;strong text
  case 3:
    Serial.println("Leaving configuration menu");
    break;
  default:
    Serial.println("Unrecognized command, try again!");
    }
 }

```

and the servo calibration:

```
void srvConfig(){

Serial.println("");
Serial.println("Begin servo stop calibration routine");

int x = 0;

  while(x == 0){

    Serial.println("Enter values for servos until both are stationary");
    delay(100);

    Serial.println("Enter value for left servo");
    while (!Serial.available()) {;}
    left = Serial.parseInt();
    Serial.println(left);
    delay(100);

    Serial.println("Enter value for right servo");
    while (!Serial.available()) {;}
    right = Serial.parseInt();
    Serial.println(right);
    delay(100);

    srvR.write(right);
    srvL.write(left);

    Serial.println("have both servos stopped?");
    Serial.println("1 = Yes | 2 = No");

    int j;
    while (!Serial.available()) {;}
    j = Serial.parseInt();

    if (j == 1) {
      Serial.println("Saving calibration");
      EEPROM.write(leftMid, left);
      EEPROM.write(rightMid, right);
      srvConOn == false;
      x == 1;
      } else if (j == 2) {
        Serial.println("Try again");
        Serial.println();
        }
  }
}

```

# Answer
You could put your switch/case inside an infinite loop, and return from the `Menu()` function when the user presses '3'. E.g.:

```
void Menu() {
    Serial.println(menu_banner);
    for (;;) {
        switch (Serial.read()) {
            case '1': ldrConfig(); break;
            case '2': srvConfig(); break;
            case '3': return;
            default: continue;  // includes the case 'no input'
        }
    }
}

```
> 0 votes

---
Tags: serial
---


# Question
Title: Servo start to turn like madman with simple if statement
I tried to write a simple program. Press button 1 servo goes to position 1, press button 2 servo goes to position 2.

But when I hook everything up my Servo goes full Crazy mode. It starts to jiggle back and forth like a madman. Even when I unhook the buttons.

What is the mistake I made? Any help is appreciated :D

Thanks in advance

```
/* Sweep
     by BARRAGAN <http://barraganstudio.com>
     This example code is in the public domain.

     modified 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Sweep

    modified 5-12-2017
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);         // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == HIGH) {
    myservo.write(173);        // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == HIGH) {
    myservo.write(97);         // tell servo to go to position
    delay(25);                 // waits 25ms for the servo to reach the position
  }
}

```

# Answer
Please, connect the buttons to the ground and change the code:

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;        // variable for reading the pushbutton status
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 5;    // the number of the pushbutton pin

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  if (buttonState == LOW) {
    myservo.write(173);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
  if (buttonState2 == LOW) {
    myservo.write(97);              // tell servo to go to position
    delay(300);                       // waits 25ms for the servo to reach the position
  }
}

```

Pull-up resistors get a high input level when the buttons are open. Otherwise, electromagnetic interference may occur.
> 1 votes

---
Tags: arduino-uno, arduino-nano, servo
---


# Question
Title: How Atmel Studio 7 compile Arduino code?
Atmel stated in their website:

> Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.

I wonder how they do it? Is it just a plug-in meaning that we still have to install Arduino software? Or do they have their own compiler and debugger?

# Answer
It is almost always the case that a high-level environment like an IDE provides an interface to an existing tool-chain rather than being truly an all-in-one mega-application, which would a maintenance nightmare. Atmel Studio 7 is no exception, and according to Atmel, uses and includes (quite likely by downloading it during the install process) the GCC tool-chain.

> Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

Probably for the Arduino libraries, which are contained within the Arduino IDE executable.
> 1 votes

# Answer
Atmel Studio allows for the arduino .ino file to actually be compiled as a c++ project. Doing so allows true debugging, and stepping through all arduino code. It was actually insightful as it walked me through **ARDUINO's main() function**, which is normally tucked away nicely in a library never to be seen.

The IDE allows for highly useful features such as refactoring, find and replace, syntax highlighting and much more. I found it very useful, and a pleasant upgrade from the arduino IDE.

I often switch back and forth between the Arduino IDE and Atmel Studio, very easy to do.

Installing the Arduino software allows Atmel Studio to locate the libraries when it is installed.

By installing the Vmicro(visual Micro) toolbar, things really come together, and seem very seamless.
> 0 votes

---
Tags: atmel-studio
---


title: I keep getting stray '/302'.

text:
# Question
Title: I keep getting stray '/302'.
I even rewrote the code and it still didn't work. How can I fix this?

```
#include "pitches.h"
void setup() {
    // put your setup code here, to run once:
    pinMode(4, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
  tone(4, NOTE_D4, 500);
  digitalWrite(dayOne, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, LOW);
  digitalWrite(Shamash, LOW);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay(350);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(Shamash, HIGH);
  tone(4, NOTE_A4, 250);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay(350);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(Shamash, LOW);
  tone(4, NOTE_D5, 500);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay (350);
  tone(4, NOTE_A4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(Shamash, HIGH);
  delay (350);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_F4, 250); //Oh chanukah oh chanuka come light the meora
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(Shamash, HIGH);
  delay (350);
  tone(4, NOTE_F4, 250); //Oh chanukah oh chanuka come light the meora
  delay (350);
  tone(4, NOTE_A4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(Shamash, LOW);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(daySix, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay(350);
  tone(4, NOTE_D5, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(daySix, LOW);
  digitalWrite(Shamash, LOW);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(daySix, HIGH);
  digitalWrite(daySeven, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay (350);
  tone(4, NOTE_A4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(daySix, LOW);
  digitalWrite(daySeven, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(daySix, HIGH);
  digitalWrite(daySeven, HIGH);
  digitalWrite(dayEight, HIGH);
  digitalWrite(Shamash, HIGH);
  delay (350);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(daySix, LOW);
  digitalWrite(daySeven, LOW);
  digitalWrite(dayEight, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_F4, 500); //Oh chanukah oh chanuka come light the meora
  delay (700);

  tone(4, NOTE_F4, 250);
  digitalWrite(dayOne, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayTwo, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayThree, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayFour, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(Shamash, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayFive, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(daySix, HIGH);
  delay (50);

  tone(4, NOTE_G4, 250);
  digitalWrite(daySEVEN, HIGH);
  delay (50);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayEIGHT, HIGH);
  delay (50);
  tone(4, NOTE_G4, 250);
  delay(250);

  tone(4, NOTE_A4, 250);
  digitalWrite(dayEight, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(daySeven, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(daySix, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayFive, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(Shamash, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayFour, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayThree, HIGH);
  delay (50);

  tone(4, NOTE_G4, 250);
  digitalWrite(dayTwo, HIGH);
  delay(50);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayOne, HIGH);
  delay(50);
  tone(4, NOTE_G4, 250);
  delay(250);

  delay (300);
  tone(4, NOTE_F4, 500);
  delay (700);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 500);
  delay (700);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_E4, 250);
  delay (350);
  tone(4, NOTE_F4, 750);
  delay (1000);

  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 250);
  delay (350);
  tone(4, NOTE_A4, 250);
  delay (350);
  tone(4, NOTE_G4, 250);
  delay (350);
  tone(4, NOTE_F4, 500);
  delay (700);
  tone(4, NOTE_F4, 500);
  delay (700);
  tone(4, NOTE_G4, 500);
  delay (700);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_E4, 250);
  delay (350);
  tone(4, NOTE_D4, 500);
  delay (700);
  delay (2000);
}

```

# Answer
The Stray /302 is saying that the compiler found some random unicode character that it didn't understand. You should put your code into some text editor that will allow you to see the unicode characters and go find it. It will probably be a lot easier if you'll format that code instead of trying to cram it all in one line.
> 3 votes

---
Tags: arduino-uno, code-review
---


# Question
Title: ATTiny85 Serial communication with Bluetooth Module
For a simple project I would like to use a ATTiny85 connected to a HC-06 Bluetooth Module so it can talk to my Android phone.
I wrote a code for my Arduino Uno and worked as expected. When I changed the code to use on my ATTiny85 I got an error saying that `'Serial' was not declared in this scope` and assumed that the ATTiny does not support Hardware Serial.
I need to read a String when received and sleep the MCU when not receiving. I went to use SoftwareSerial and was not able to get a String, just the first char.
I approached it in some was, like defining a `char string[10];` as global and `string[i] = mySerial.read(); i++;` inside the loop, but it keeps not working. Whether it is the sleep, or my work to read data, I couldn't make it work.
Can someone provide a way to put a ATTiny85 to sleep, wake up to receive a String through Serial and sleep til the next data through Serial, please?

To sleep I'm using

```
void sleep() {
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  // woke up
  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear Sleep Enable bit

  sei();                                  // Enable interrupts
}

ISR(PCINT3_vect) {

}

```

And my loop is something like

```
char inputString[10];
int i = 0;

void loop() {
  sleep();

  if (serial.available() > 0) {
    char inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
      //Do something and reset i
    } else {
      inputString[i] = inputChar;
    }
    i++;
  }
}

```

Thanks to all.

# Answer
Hello,

I think you should do this:

```
char inputChar = '';    //this in global
while (serial.available()) {
    inputChar = serial.read();
    if (inputChar == '2') {    //Char to break
        //Do something and reset i
    } else {
        inputString[i] += inputChar;    //= to +=
    }
    i++;
}

```
> 0 votes

---
Tags: serial, softwareserial, attiny, attiny85
---


title: MAX31855 giving NaN after some readings

text:
# Question
Title: MAX31855 giving NaN after some readings
In my current project I am measuring temperature using K-type thermocouple and MAX31855 breakout board and Arduino uno.

I have used Adafruit-max31855 library and example code from that library. But monitoring on serial monitor after some reading it is giving **NaN**.

Here is the code I have used:

```
#include "Adafruit_MAX31855.h"

int thermoDO = 5;
int thermoCS = 6;
int thermoCLK = 7;

Adafruit_MAX31855 thermocouple(thermoCLK, thermoCS, thermoDO);

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

  Serial.println("MAX31855 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
   Serial.print("Internal Temp = ");
   Serial.println(thermocouple.readInternal());

   double c = thermocouple.readCelsius();
   if (isnan(c)) {
     Serial.println("Something wrong with thermocouple!");
   } else {
     Serial.print("C = ");
     Serial.println(c);
   }
   //Serial.print("F = ");
   //Serial.println(thermocouple.readFarenheit());

   delay(1000);
}

```

Circuit Diagram:

Output:

What could be the possible error for this and how can I solve this?

# Answer
Try to `Serial.println(thermocouple.readError())`. It will give you an error code, which is a bit field:

* 1 = open circuit
* 2 = short to ground
* 4 = short to Vcc

C.f. the datasheet.
> 2 votes

---
Tags: arduino-uno, serial, temperature-sensor
---