title: Arduino programming with multiple loops

text:
# Question
Title: Arduino programming with multiple loops
I was trying to program my Arduino (along with a connected motor controller) to switch from cycle to cycle with this program. It doesn't seem to work however. There's still plenty of storage space and dynamic memory, so those aren't the issue. This is the program:

```
int EnablePin1 = 8;
int duty;
int period;
int cycle;

int PWMPinA1 = 11;
int PWMPinB1 = 3;
int PWMPinA3 = 6;
int PWMPinB3 = 5;

const byte CPin1 = A0;

int CRaw1;
void setup() {

    Serial.begin(9600);

    pinMode(EnablePin1, OUTPUT);

    pinMode(PWMPinA1, OUTPUT);
    pinMode(PWMPinB1, OUTPUT);
    pinMode(PWMPinA3, OUTPUT);
    pinMode(PWMPinB3, OUTPUT);

}

void loop() {
    digitalWrite(EnablePin1, HIGH); //enable the board
    for (duty = 0; duty <= 255; duty += 15)
    {

        analogWrite(PWMPinB1, 0); //Set pinB to 0, when speed is written to pinA

        analogWrite(PWMPinA1, 255);
        delay(850);
        if (PWMPinA1 == 11)
        {
            PWMPinA1 = 3;
            PWMPinB1 = 11;
        }
        else
        {
            PWMPinA1 = 11;
            PWMPinB1 = 3;
        }
   }
   analogWrite(PWMPinA1,0);//end at max speed
   analogWrite(PWMPinB1,0);
   CRaw1 = analogRead(CPin1);

   Serial.println("Feedback");

   Serial.print(CRaw1);

   delay(2000);
   //analogWrite(PWMPinB3, 0);
   for (duty = 255; duty >= 0; duty -= 51) // ramp down speed
   {
       //analogWrite(PWMPinA1, duty);
       analogWrite(PWMPinB3, 0);
       analogWrite(PWMPinA3, 255);
       delay(period);
       //delay(cycle);
       if(PWMPinA3 == 6)
       {
           PWMPinA3 = 5;
           PWMPinB3 = 6;
           //period = 850;
       }
       else
       {
           PWMPinA3 = 6;
           PWMPinB3 = 5;
          //period = 2500;
       }
   }
   analogWrite(PWMPinA3, 0); //set to 0 speed
   analogWrite(PWMPinB3, 0);
   delay(2000);

   digitalWrite(EnablePin1, LOW);// Toggle enable to reset the power chips           if we have had an overcurrent or overtemp fault

   for (cycle = 1000; cycle < 9000; cycle += 4000)
   {
       //cycle=period;
       period=cycle;
   }

 /*for (cycle = 2000; cycle <= 3000; cycle += 1000)
   {
       //cycle=period;
       period=10000;
   }*/
   for (cycle = 9000; cycle >= 1000; cycle -= 8000)
   {
       period=0;
   }

   //delay(2000);  // Swap pins to make the motor change direction

}//end main loop

```

I've also tried having the cycle loops be this:

```
 for (cycle = 0; cycle < 9000; cycle += 3000)
 {
     //cycle=period;
     period=cycle;
 }
 for (cycle = 9000; cycle >= 0; cycle -= 9000)
 {
     //cycle=period/3;
     period=cycle;
 }

```

But that didn't do anything (I can see what PWM pins are powered through LEDs, and the first attempt, the LEDs only lit up for 1 second and the 2nd, they didn't light up at all.

# Answer
> 1 votes
## First things, try to use multiple function and call it from the loop()

You can use some code magic for dealing with multitasking on Arduino. It's a bit tricky to understand but it's working.

Here is an example :

```

const int BROCHE_LED_1 = 13;
const int BROCHE_LED_2 = 12;
const int BROCHE_LED_3 = 11;

const unsigned long BLINK_INTERVAL_1 = 1000;
const unsigned long BLINK_INTERVAL_2 = 500;
const unsigned long BLINK_INTERVAL_3 = 2000;

void setup() {

  pinMode(BROCHE_LED_1, OUTPUT);
  pinMode(BROCHE_LED_2, OUTPUT);
  pinMode(BROCHE_LED_3, OUTPUT);

  digitalWrite(BROCHE_LED_1, LOW);
  digitalWrite(BROCHE_LED_2, LOW);
  digitalWrite(BROCHE_LED_3, LOW);
}

void loop() {

  task_led1();
  task_led2();
  task_led3();
}

void task_led1() {
  static unsigned long previousMillisLed1 = 0;
  static byte etatBrocheLed1 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed1 >= BLINK_INTERVAL_1) {

    previousMillisLed1 = currentMillis;

    etatBrocheLed1 = !etatBrocheLed1;
    digitalWrite(BROCHE_LED_1, etatBrocheLed1);
  }
}

void task_led2() {
  static unsigned long previousMillisLed2 = 0;
  static byte etatBrocheLed2 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed2 >= BLINK_INTERVAL_2) {

    previousMillisLed2 = currentMillis;

    etatBrocheLed2 = !etatBrocheLed2;
    digitalWrite(BROCHE_LED_2, etatBrocheLed2);
  }
}

void task_led3() {
  static unsigned long previousMillisLed3 = 0;
  static byte etatBrocheLed3 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed3 >= BLINK_INTERVAL_3) {

    previousMillisLed3 = currentMillis;

    etatBrocheLed3 = !etatBrocheLed3;
    digitalWrite(BROCHE_LED_3, etatBrocheLed3);
  }
}

```

## Second things, Try to use Real time operating system

You can try to use FreeRTOS, it's work with most arduino and you got lot of infos on the web.

It make multi tasking way more easy than the previous example.

Here is the Docs i've found

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


# Question
Title: creating HTTP persistent connection, to create 'smooth' data over GSM sending
**Project goals**

* Send data over GSM to firebase
* Fast sampling - need to send 16 bytes every half second to firebase
* Send data using GET or POST to server with PHP script, that redirect data to firebase

**Problems -- Extremely low data rate!**

* Using standard GET or POST request from client(arduino) side, is impossible to achieve second (2) project goal.
* **To send data correctly I need to close connection with server, so next data package unfortunately waits(2-6 seconds) for establishing a new connection.**

Is this quite nonsense? I'm using ArduinoHttpClient library.

**My actual Nonsense Connection and fully useless, but works**

```
while(1){

http.post("/test.php","application/x-www-form-urlencoded","data=0");
http.stop(); //closing connection with server

//next instruction take over 5 second to establish new connection :(

http.post("/test.php","application/x-www-form-urlencoded","data=0");
http.stop(); //closing connection with server, whyyy?
}

```

Data are send once per 2 - 6 seconds, this is not even funny. NEED to send data every 0.5 seconds!

So I decided to create super solution, which not works :C

```
while(1){
    http.post("/test.php","application/x-www-form-urlencoded","data=0");
    delay(xxx);
//no connection closing, no wasting time for establishing new one :)
}

```

Just tell my why this connection is not "Keep-Alive", also used with

> http.sendHeader("Connection: Keep-Alive"); or http.connectionKeepAlive();

```
//First run
http.post(blabla);// returns value: 0 & data are logged into firebase
//Second run
http.post(blabla);// returns value: -2 & data are not logged in firebase

```

**my test.php file**

```
<?php
require_once 'firebaseLib.php';
$url = 'https://czujniki-aa5ca.firebaseio.com/';
// --- Use your token from Firebase here
$token = ':-CCCCCCCCCCCCCCCCCCCCCCC';

$arduino_data_post = $_POST['data'];
$firebasePath = '/';

$fb = new fireBase($url, $token);
$response = $fb->push($firebasePath, $arduino_data_post);
sleep(2);

```

# Answer
The ArduinoHttpCliemt library's HttpClient.stop() method does two things. It resets the state of the HttpClient object and stops the underlying Client connection (TCP connection). If HttpClient.stop() is not called, the internal state is not good to call get() or post() again.

The method resetState() is called in HttpClient.stop() to reset the internal state of the HttpClient object. But resetState() is protected. To call it we must modify the library header file.

In HttpClient.h make resetState() public (by moving 'protected:') and then in sketch call resetState() before post(). It will put the HttpClient object into initial state without disconnecting the underlying TCP connection.
> 1 votes

---
Tags: gsm, http, datalogging, tcpip, iot
---


# Question
Title: How to convert 0-5v inverted serial to 0-3.3v non-inverted serial
This weather stations has a 0-5v serial output. I'm trying to read the serial output with the Adafruit 32u4 feather board and I get nonsense data out of it. When I hook the Ultimeter up to my serial-\>usb cable I get the normal data output. When I hook up the Ultimeter to a 5v arduino via SoftwareSerial in inverted mode I get proper data. But I need to connect this weather station to a 3.3v Feather board's hardware uart which doesn't seem to be able to operate in inverted mode. Is there a 5v -\> 3.3 level converter that also will invert the serial signal ?

# Answer
I think you're looking for an inverting amplifier. This can be done with either a BJT or a MOSFET (assuming your input is enough to turn the MOSFET on). Here's an example with a BJT:

simulate this circuit – Schematic created using CircuitLab

The output range is independent of the input and is defined by the supply voltage.
> 0 votes

# Answer
Base \> Collector is not good ,for NPN transistor.

Because "Base -\> collecter" is PN.

So use LM393 for level convert.

LM393 is open collecter.
> 0 votes

# Answer
I ended up using a simple voltage divider to reduce the 5v to 3v and used SoftwareSerial to read the inverted serial. Thanks everyone.
> 0 votes

---
Tags: serial
---


# Question
Title: Mega <> esp8266 comms sending baffling data
I have Wemos Mega-ESP8266 board. I have uploaded a simple WebSocket server on the ESP...

```
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

const char* ssid     = "SKYNET";
const char* password = "yourdogsfavouriteauntysmaidenname";

WebSocketsServer webSocket = WebSocketsServer(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

    //Serial.printf("[%u] get Message: %s\r\n", num, payload);

    switch(type) {
        case WStype_DISCONNECTED:
            break;

        case WStype_CONNECTED:
            {
              IPAddress ip = webSocket.remoteIP(num);
              Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
            }
            break;

        case WStype_TEXT:
            {
              String _payload = String((char *) &payload[0]);
              Serial.print(_payload);
            }
            break;

        case WStype_BIN:
            {
              hexdump(payload, lenght);
            }
            // echo data back to browser
            webSocket.sendBIN(num, payload, lenght);
            break;

    }
}

void setup() {

  // Set up serial comms
  Serial.begin(115200);

  // Set up WiFi
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED) {
     Serial.print(".");
     delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  delay(500);

  // Set up web socket
  Serial.println("Start Websocket Server");
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
  webSocket.loop();
}

```

I upload via the Arduino IDE & everything looks fine except the ESP doesnt send any information back through the serial monitor (yes I have the DIP switches correct for serial \<\> ESP comms).

I tried to see if was sending anything through the Mega via Serial3, the mega code (DIP switches set accordingly & ESP serial switch set to RX3). Mega code...

```
// Input buffer from ESP8266
String temp;

void setup() {
  // Set up serial comms
  Serial.begin(115200);   // Debug to Serial Monitor
  Serial3.begin(115200);  // From ESP8266
}

void loop() {
  while (Serial3.available()) {
      Serial.println(".......");
      Serial.println("In from ESP8266");
      temp = Serial3.readString();
      Serial.println(temp);
      Serial.println(".......");
  }
}

```

So now I get 2 one time messages to the serial monitor..

```
.......
In from ESP8266
[WS-Server] Server Started.

.......
.......
In from ESP8266
pm open,type:2 0

.......

```

I have no idea where these messages are being generated or why the ESP isnt sending the serial messages on set up eg the IP address for the ESP etc.

Any idea what's going on here?

**Edit 1:** Addition info asked for in comments (or at leat I think this is what was asked for)

**Edit 2:**

DIP switch settings for flashing the ESP - OFF, OFF, OFF, OFF, ON, ON, ON

DIP switch settings ESP \> serial monitor - OFF, OFF, OFF, OFF, ON, ON, OFF (RX switch to TX0)

DIP switch settings for ESP \> Mega \> serial monitor - ON, ON, ON, ON, OFF, OFF, OFF (RX switch to TX3)

**Edit 3** I have to press the red reset button after flashing the ESP8266 & it works BUT as soon as I unplug & restart nothing again! The client connects, sends the same data but it doesnt get echoed back via the serial comms. The only way to get to work again is to reflash the ESP8266 and hit the reset button.

**Edit 4** Swapped out the board & now nothing works again. Uploads look fine but no serial comms at all from the ESP8266.

# Answer
The esptool auto-reset feature by default sets io 0 LOW over the RST line and then makes a reset over the DTR line to put the esp8266 into flashing mode. After the upload the esptool resets the board over the DTR line.

On this board Mega+WiFi, only the DTR line is wired like for AVR MCU. For flashing the io 0 pin is put LOW with the pin 7 of the DIP switch manually. So the reset after upload sets the esp8266 back to flashing mode.

The esp8266 arduino package changed from version 2.5.0 the upload tool to the python version of the esptool which makes this reset after upload. This reset can be turned off by changing the command line of the esptool in platform.txt (`--after no_reset` in `tools.esptool.upload.pattern` before `write_flash`)
> 3 votes

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


# Question
Title: Controlling multiple 12v solenoids with 5v relay modules (Arduino Reset Issue)
I have 4 12V(1A) solenoids running on a 12V(4.16A) power supply. Each solenoid circuit is controlled by a 5V relay module connected to the Arduino Uno (powered by USB).

The solenoids actuate properly but eventually the Arduino resets, typically when multiple solenoids are turned on/off in fast succession. This is accompanied by random character artifacts on the LCD display (connected to the Uno) during operation but before the reset.

From what I've gathered there are back EMF surges occurring when the solenoids lose their charge. Here are some possible remedies I've found:

1. Add a flyback diode (IN4004) to each solenoid circuit. (Redirect the surge)
2. Add a capacitor (4700 - 10,000 uF) to the 5v supply (from the Uno) for the relays. (Filter the surge)
3. Provide a separate 5v power source to the relay modules instead of using power from the Uno. (Isolate the surge)

Any input on which solution(s) should be applied or other possible causes for the Uno reset and LCD distortion is appreciated.

# Answer
Some of those 5V "digital" relays can be wired using a separate power supply for the relays and the Arudino. You have to move a jumper to use separate power supplies.

My guess is that you're powering both your Arudino and your relay coils from the same 5V supply, and when you energize all 4 relays at the same time you draw too much current and the Arduino doesn't get enough voltage and resets.

Read up on your relay modules, and either re-wire them using 2 different 5V supplies, or switch your 5V supply to a higher current supply. (and possibly adding a filtering capacitor to the Arduino to smooth out the power fluctuations as the relays energize and de-engergize)

I used a 4-channel relay unit in a project of mine that has optical isolation of the relay control lines, and can be wired to use separate power supplies for the Arudino and the relay power. When wired with separate power supplies, the relay's control lines just draw CMOS logic levels to control the different relay channels, and get the power for the coils independently from the microcontroller's power.
> 3 votes

# Answer
## Here is another path to explore :

* Try to use separate rail for the 5v relays
* Use a transistor or darligton array (such as ULN2003) for controling your 5v relay.
* ALWAYS put a feedback diode when you use an inductive load it can break your Arduino !!

## My analyse :

* Arduino and many other µc have limited output current on IO, be sure to not overload these value by using transistor or darligton array.
* The voltage regulator on the Arduino can provide around 200 mA of power. I you are overloading the value use an external power supply for your circuit.
* The solenoid can draw lot of current of the power supply, try to measure if a voltage drop occur on loads. It can cause the arduino to reset due to low voltage.
> 0 votes

---
Tags: arduino-uno
---


title: Arduino components

text:
# Question
Title: Arduino components
I’m teaching and learning coding with MicroBit and was wondering if these components are compatible with MicroBit. The specific kits labeled for MicroBit are twice the price but the components look similar. Just trying to save a few bucks. Would this kit work with my MicroBit?

# Answer
It looks like the MicroBit runs on 3.3V versus 5V for most Arduino boards. You'd need to use 3.3V components.

It looks like the kit you linked to is built for (and includes) a 5V Arduino, so those accessories would not work with your MicroBit.

There are other Arduino boards that run on 3.3V. Look for 3.3v accessories. Those should work.

## EDIT:

---

I assume that the MicroBit is capable of I2C interfacing. If so, you should look at the SparkFun Qwiic system. It's a setup with 3.3V I2C serial interface in a 4-wire ribbon cable with a standard connector. You can easily daisy-chain Qwiic devices by just plugging Qwiic cables between them, and they are reasonably priced. I bought some of them thinking I could use them with my Arduino projects, only to discover that they use 3.3V, so I can't use them without I2C voltage translation interfaces, which makes them much less appealing.
> 1 votes

---
Tags: components
---


# Question
Title: expected unqualified id-before '/' token ------ can someone help, please
```
/* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

/------------------------------------------------------------------------

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
/-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
/-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  deley(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}

```

# Answer
> 2 votes
OK, you just had a couple of minor typos.

It's nice to break up your code for readability, but single-line comments comments start with a double slash `//`, rather than a single.

Also, you had mis-spelled 'delay' in your loop.

---

This should compile without errors:

```
/* Multiple State Handling
* 05-22-2019
*/

#define button 3                        //Push button on D3
#define lowbeam 5                       //Low Beam on D5
#define highbeam 6                      //High Beam on D6
#define gate 7                          //Gate on D7

//------------------------------------------------------------------------

int state = 0;                          //integer to hold current state
int old = 0;                            //integer to hold last state
int buttonPoll = 0;                     //integer to hold button state
//-------------------------------------------------------------------------

void setup() {
  pinMode(button,INPUT);                //button set as input
  pinMode(lowbeam,OUTPUT);              //relays set as outputs
  pinMode(highbeam,OUTPUT);
  pinMode(gate,OUTPUT);

  digitalWrite(lowbeam,LOW);            //initial state as off
  digitalWrite(highbeam,LOW);           //initial state as off
  digitalWrite(gate,LOW);               //initial state as off

}
//-------------------------------------------------------------------------
void loop() {

                                        //debouncing routine to read button
  buttonPoll = digitalRead(button);     //poll state of button
  if(buttonPoll == 1){                  //check if it has been pressed
    delay(50);                          //wait 50msec
    buttonPoll = digitalRead(button);   //poll button again
    if(buttonPoll == 0){                //if it is 0 consider 1 press
      state = old +1;                   //increase state by 1
    }}
  else{                                 //if button has not been pressed
  delay(100);                           //wait 100ms
  }
  switch (state) {                      //react to button press & state
    case 1:                             //if state is 1
      digitalWrite(lowbeam,HIGH);       //lowbeam relay on
      digitalWrite(highbeam,LOW);       //highbeam relay off
      digitalWrite(gate,LOW);
      old = state;                      //set old state as current state
      break;
    case 2:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,HIGH);
      digitalWrite(gate,LOW);
      old = state;
      break;
    case 3:
      digitalWrite(lowbeam,LOW);
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,HIGH);
      old = state;
      break;
    default:                            //if state if no 1,2,3
      digitalWrite(lowbeam,LOW);        //all relays off
      digitalWrite(highbeam,LOW);
      digitalWrite(gate,LOW);
      old = 0;                          //reset to all off/state 0
      break;
  }
}

```

---
Tags: arduino-uno
---


title: Code with if multible conditions

text:
# Question
Title: Code with if multible conditions
My project has 4 float switches, 2 valves and 3 pumps. I created a sketch and uploaded it. But my project keep all "OUTPUT" at "HIGH" all the time. I couldn't find what the problem, can you help?

This is my sketch:

```
#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
DS3231  rtc(SDA, SCL);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

void setup()
{
  rtc.begin();
  lcd.begin(16,2);
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  //rtc.setDOW(TUESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(1, 15, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(6, 6, 2017);   // Month, Day, Year

 //Setup FLoat Switch Pins
  pinMode (x, INPUT);
  pinMode (y, INPUT);
  pinMode (z, INPUT);
  pinMode (w, INPUT);

 //Setup Irrigation Valves
  pinMode(WaterIn, OUTPUT);  //irrigation "in" valve
  pinMode(WaterOut, OUTPUT);  //irrigation "out" valve

//Setup Pumps
  pinMode(Pump1, OUTPUT);
  pinMode(Pump2, OUTPUT);
  pinMode(Pump3, OUTPUT);
}  // end of setup

void Calendar(){

 lcd.setCursor(0,0);
 lcd.print("Real Time Clock  ");
 lcd.setCursor(0,1);
 lcd.print("Time: ");
 lcd.print(rtc.getTimeStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Date: ");
 lcd.print(rtc.getDateStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Day: ");
 lcd.print(rtc.getDOWStr());
 lcd.print("           ");
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Temp: ");

 lcd.print(rtc.getTemp());
 lcd.print(" C");
 lcd.print("          ");
 delay(1000);
}  // end of setup

void Valves(){
    int pinToTurnHigh = 24;
    if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))  //Condition 1
    {
        pinToTurnHigh = WaterIn;
        pinToTurnHigh = Pump1;
        pinToTurnHigh = Pump2;
        pinToTurnHigh = Pump3;
    }
    if ((x == LOW) && (y == LOW) && (z == HIGH) && (w == HIGH))  //Condition 2
    {
       pinToTurnHigh = WaterOut;
    }
    resetAllPumpValve();
    digitalWrite(pinToTurnHigh, HIGH);
}  // end of setup

void resetAllPumpValve(){
     digitalWrite(WaterIn, LOW);
     digitalWrite(Pump1, LOW);
     digitalWrite(Pump2, LOW);
     digitalWrite(Pump3, LOW);
     digitalWrite(WaterOut, LOW);
}  // end of setup
void loop()
{
    Calendar();
    Valves();
    resetAllPumpValve();
}  // end of loop

```

# Answer
> 1 votes
chrisl made an excellent analysis of your program and the problems therein. I would just want to add a point about how to handle the `Calendar()` function. You have been given the suggestion to look at the Blink Without Delay Arduino tutorial, and I second that suggestion. This is indeed the first thing you should do.

However, once you have studied that tutorial and you try to apply it to your specific problem, you will notice that yours is somewhat harder than blinking an LED. The reason it is harder is that you have to manage a more complex system state. The LED has only two states, and it periodically transitions between them as:

* `LOW``HIGH``LOW`

Your display routine will instead have four states and make the following transitions:

* `SHOW_TIME``SHOW_DATE``SHOW_DAY``SHOW_TEMP``SHOW_TIME`

The relevant programming concept for dealing with this kind of system is called a “finite state machine” and I suggest you also study this finite state machine tutorial. This tutorial proposes a very generic `switch`/`case` control structure for programming an FSM. However, if there is some behavior common to all states (in your case: the fact that each one lasts for exactly one second), you can factor that behavior out of the `switch`/`case` construct.

Here is what I would propose as a non-blocking `Calendar()`. First, put this near the top of the program, along with the other constants:

```
const LCD_DISPLAY_TIME = 1000;  // display each item for 1,000 ms

```

Then, is `setup()`, right after initializing the LCD:

```
lcd.setCursor(0, 0);
lcd.print("Real Time Clock ");

```

As a general rule, `setup()` is the right place for anything that only needs to be done once, at the start of the program.

And finally, the `Calendar()` function to be called from `loop()`:

```
void Calendar()
{
    // Do nothing unless it's time to refresh the display.
    static uint32_t last_change = -LCD_DISPLAY_TIME;
    if (millis() - last_change < LCD_DISPLAY_TIME) return;
    last_change += LCD_DISPLAY_TIME;

    // Switch to the next item: Time -> Date -> Day -> Temp -> Time
    lcd.setCursor(0, 1);
    static enum { SHOW_TEMP, SHOW_TIME, SHOW_DATE, SHOW_DAY } state;
    switch (state) {
    case SHOW_TEMP:
        lcd.print("Time: ");
        lcd.print(rtc.getTimeStr());
        state = SHOW_TIME;
        break;
    case SHOW_TIME:
        lcd.print("Date: ");
        lcd.print(rtc.getDateStr());
        state = SHOW_DATE;
        break;
    case SHOW_DATE:
        lcd.print("Day: ");
        lcd.print(rtc.getDOWStr());
        state = SHOW_DAY;
        break;
    case SHOW_DAY:
        lcd.print("Temp: ");
        lcd.print(rtc.getTemp());
        lcd.print(" C");
        state = SHOW_TEMP;
        break;
    }
    lcd.print("           ");  // pad
}

```

# Answer
> 4 votes
It is not clear, what the code actually should do (what behaviour you are trying to achieve), so I will only look into the obvious programming problems.

1. The following declarations at the global scope seem to be pin numbers:

```
int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

```

But in the `Valves()` function yout treat them as they were representing the value of that pins. That is not the case. If you want to read the state of a pin, you cannot do

```
if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))

```

You are just comparing the pin number with `HIGH`, which is defined as `1`. That cannot work. You have to actually read the pin using it's pin number, which looks like this:

```
if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH)

```

And that can be shortened to:

```
if( digitalRead(x) && digitalRead(y) && digitalRead(z) && digitalRead(w) )

```
2. Inside of the mentioned if statements you set a variable multiple times without doing anything with it. Any consecutive write to this variable will overwrite the previous value. After the code block

```
pinToTurnHigh = WaterIn;
pinToTurnHigh = Pump1;
pinToTurnHigh = Pump2;
pinToTurnHigh = Pump3;

```

The variable `pinToTurnHigh` is 27 (Pump3). The values, that you assigned right before that line, are lost. You actually have to do something with the variable, or the first 3 lines of that block makes no sense.
3. In most cases it is not a good idea, to use variables with changing values to handle pin numbers, since that will make the code difficult to understand. The circuitry is mostly hardwired, it will not change. So there is no need to assign pin numbers to a changing variable. Instead you can directly do, what you need to do with a constant pin number. (Actually the code optimizer, that comes with the compiler, can optimize the not-changing pin-number variables out, so that you wrote them in your code, but the actually code might not have them.) Here it seems, that you want to write a `HIGH` value to all the mentioned pins. You can do that directly:

```
digitalWrite(WaterIn, HIGH);
digitalWrite(Pump1, HIGH);
digitalWrite(Pump2, HIGH);
digitalWrite(Pump3, HIGH);

```

Here it is important to understand, that `digitalWrite()` is only working on 1 single pin at a time. If you want to set multiple pins with it, you have to call it multiple times with the according pin numbers.
4. Now the timing of your code: The `Calendar()` function will block the rest of the code for about 4s, because you used that much of `delay()`. During that time the Arduino cannot react to anything. The switches will not do anything either (since the Arduino is busy waiting in the `delay()` instead of checking the switches). The code, that is called after the `Calendar()` function, contains no `delay()`s, so it will run very fast. In the `Valves()` function you first reset all the pumps and valves to `LOW`. Then you write `HIGH` to one pin (as mentioned above I assume, that you wanted to write them all on condition). After that the program will go back to the `loop()` function and execute the `resetAllPumpValve()` function again, which will set all the outputs to `LOW`.

All in all that means, that the Arduino is fiddling thumbs inside the `Calendar()` function, without doing anything else. Then he will reset, set and reset the pins again. Since there is not timing code in there, this will happen very fast. So the pins have to be `LOW` most of the time and being turned on about every 4s for a tiny amount of time (a low number of milliseconds, since that is about the time to execute `digitalWrite()` or it's siblings). The motors or values will hardly have time to move with that.

For solving this you might want to look into the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It shows a non-blocking coding style, that will only do something, if it is the time to do it. Much like when you bake a pizza. You will not sit in front of the oven and wait patiently, until the pizza is fully baked. You will put it into the oven and regularly (maybe every 5 min) look, if the pizza is ready to eat. In the meantime you would do other things. Thats what is done there by using the `millis()` function, that will return the number of milliseconds passed since the programs startup. You can look into the example and google about it to learn more. It has been covered numerous times throughout the internet.

That's it for now. To really help you with the logic of the program, you will first have to get these parts right.

Have fun while learning :-)

# Answer
> 1 votes
I would add to Chrisl's answer by saying that, if you wanted to make the code more compact, you could represent the 4 boolean variables by a single byte,

e.g. w HIGH + x HIGH + y LOW + z LOW = 1100.
e.g. w HIGH + x HIGH + y LOW + z HIGH = 1101.

Then it would be easier to implement a `switch` statement instead of `if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH)` etc.

For example:

```
byte state;

void setup(){}

void loop(){
 // insert code to read state
 switch (state)
 {
     case 1:
         // insert code to be run if state = 0b0001;
     break;

     case 13:
         // insert code to be run if state = 0b1101;
     break;

     default: // code to be run if state doesn't match any cases
 }
 // insert other code
}

```

If you were willing to use the ATmega's digital 30-37 pins then you could use the AVR's port command `PINC` to read all of the HIGH/LOW states at once, using a single instruction. I leave this as an exercise for you to try!

---
Tags: coding-standards
---


# Question
Title: Switch Control Between Two Different Techniques
I have implemented PID control of a generator governor to maintain a constant RPM using an Arduino Uno. It works pretty well, but there is a tradeoff between stabilty and response time. Using PID values that allow it to respond without oscillation is also about half as fast as the old mechanical governor.

I came up with a plan to use a CT to sense the AC amps and have the Uno rapid the throttle servo to a known value determined manually. Either using a lookup table or an interpolation algorithm, I haven't yet checked the linearity of the amps vs. throttle angle. The idea is to use a table (or interpolation) to get the governor close, and then let the PID fine tune it.

My hangup is that I'm not sure how to switch between lookup control and PID control as needed.

Pseudo-code:

analogRead(AMPS); myservo.write(table\_Val); somehow\_switch\_to\_PID; myservo.write(PID\_value);

# Answer
> the PID is looking at the RPMs and giving an output but that output is being ignored because another operation has servo control.

PID is not something, that happens somewhere in the background without you having any control. On the Arduino it is done in software, so you can totally control it. Why should you run a PID calculation, if you don't use the value? The solution is to simply only do the appropriate calculation depending on the RPM at any given time. No need to do 2 calculations at the same time. I will form that into a code with explanations:

You have 2 ways of calculating the needed servo values:

1. Your "getting close" method
2. The PID method

To switch between those methods you need to make a decision based on the RPM. If the RPM is outside of your interval, the first method is used. If it is inside, the second will be used. Decision/conditionals are often wrote with an `if else` statement. Look at this (not tested) code snippet:

```
int target_rpm = 700;
int half_interval = 20;
int current_servo_pos = 0;

void loop(){
    current_rpm = analogRead(AMPS);

    if(current_rpm > target_rpm - half_interval && current_rpm < target_rpm + half_interval){
        // Do the PID calculation here and save the result in current_servo_pos
    } else {
        // Do the "getting close" calculation here and save the result in current_servo_pos
    }

    myservo.write(current_servo_pos);
}

```

I didn't go into detail about the actual calculation, since that is not important here. You may use any calculation, that you like there. For PID you can find libraries, that do the calculation for you, for example here at github.

The code will simply decide based on the RPM, what calculation should be used. If the RPM goes out of the interval for some reason (maybe is was disturbed and lost some speed), it will automatically use the "getting close" method until it is again inside of the interval.

Note: The numbers, that I used here, are arbitrary. You should change them to what ever you need.
> 1 votes

---
Tags: arduino-uno, servo, pid
---


title: Arduino Micro + Max4466 - Noise on A0

text:
# Question
Title: Arduino Micro + Max4466 - Noise on A0
I've got an Arduino Micro, and a MAX4466 ECM / AMP breakout board (https://www.adafruit.com/product/1063). I'm powering the Arduino Micro from the USB port.

On the MAX4466 (to the Arduino), I've wired VCC to 3.3v, GND to GND, and OUT to A0. I've also wired 3.3v to AREF.

Using the following code, I'm noticing significant noise spikes on the output, as shown in the graph below.

I'm not entirely sure what I've done wrong here, and would appreciate any input / criticism that could lead to getting a clean signal.

```
void setup()
{
   Serial.begin(9600);
   analogReference(EXTERNAL);
}

void loop()
{
   Serial.println(analogRead(0));
}

```

# Answer
> 1 votes
The OP itself solve it:

> Ok - so I suspected that it was the Arduino at fault.. Turns out it's a cheap Chinese clone. After purchasing an official Micro, and wiring up the same component, I'm getting a nice clean signal (bar a small amount of acceptable noise), which is reflecting input tones accurately. Thanks again for all the input!

# Answer
> 0 votes
Interesting plot. Gives me the impression that your reference is sagging, consider adding some local storage (tant/ceramic capacitors) across the cpu's power in pins and across the cpu's Reference pin. Would also be interesting to know if adding more delay between measurements would improve performance. Thanks for sharing you issue.

---
Tags: analogread, arduino-micro, analog-sampling
---


# Question
Title: Why am I getting this error- "exit status 1 expected ';' before '{' token "
```
void setup()
{

  pinMode{13, OUTPUT};

}

void loop() {

  digitalWrite{13, HIGH};

}

```

# Answer
> 3 votes
Try parentheses instead of curly braces:

```
void setup() {

pinMode(13, OUTPUT);

}

void loop() {

digitalWrite(13, HIGH);

}

```

# Answer
> 0 votes
The solution is already give, but here an explanation:

`{` and `}` are used to group multiple statements together, either for a function, if, while, for loop and so on.

E.g.

```
if (i == 1)
{
  // Statement 1
  // Statement 2
}

```

or a function

```
void f()
{
  // Statement 1
  // Statement 2
}

```

`(` and `)` are used to specify parameters:

```
void f(int a, int b)
{
  ...
}

```

A function with two parameters.

When calling this function, the following is used:

```
f(1, 2);

```

Calls function `f` with `a = 1`, and `b = 2`.

So in general: `{` and `}` is for grouping statements, `(` and `)` for parameters.

# Answer
> 0 votes
I made same mistake when I started working with C

you have

```
pinMode{13, OUTPUT};

```

which should be

```
pinMode(13, OUTPUT);

```

the curly brackets are basically for Start and End of a function.

Bill

---
Tags: arduino-uno
---


# Question
Title: Emulating a generic Mifare USB peripheral device with RFID-RC522
# Hardware

### Dev Board: Arduino Nano V3.0

### Module: RFID-RC522 13.56 MHz

### Cable: USB A - USB Mini B

---

# Configuration

### Physical

### Code

```
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from a PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9               // Configurable, see typical pin layout above
#define SS_PIN          10              // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);       // Create MFRC522 instance

void setup() {
    Serial.begin(9600);                 // Initialize serial communications with the PC
    while (!Serial);                    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();                        // Init SPI bus
    mfrc522.PCD_Init();                 // Init MFRC522
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

```

*See: https://github.com/miguelbalboa/rfid/tree/master/examples*

---

# Goal

### Generic USB-Compatible Mifare NFC Read/Writer

So, you can get these devices that just plug directly into your regular computer via USB, and basically function as an ordinary HID or peripheral device. I have various different ones from when I was investigating the security implications associated with CRYPTO-1 & MiFare Classic access control cards. They all basically work the same, and produce/dump the same standard output.

The thing is, I have little experience with Arduino, and hardware development in general. The Arduino USB Port is obviously used for serial communication with the IDE for programming the MEGA328P, and I can use the IDE's serial interface, plotter, etc. But it doesn't seem to want to play with any of the other applications (MiFare Classic Universal tooKit, etc.) that "just work" with the (unaffiliated) commercial/store-bought devices.

# Answer
You have to use Arduino Mini and Keyboard.h library which comes with arduino IDE. Arduino Nano does not have HID capable processor.

Try this with mini:

```
#include <Keyboard.h>

void setup() {
 // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
 // connected to ground:
 pinMode(2, INPUT_PULLUP);
 Keyboard.begin();
}

void loop() {
 //if the button is pressed send the message
   if (digitalRead(2) == LOW) {

     Keyboard.print("Hello!");

   }
}

```

I will build same thing now, just tested Arduino Mini and will add rc522 to it.
> 3 votes

---
Tags: arduino-nano, usb, rfid, terminal
---


# Question
Title: HD44780 DDRAM addressing on the second line
I write bytes to HD44780 display DDRAM to display characters and it works weird on the second line. I use 16x2 model and I write "0123456789" string from address X on.

According to the datasheet:

> In a 2-line display, the cursor moves to the second line when it passes the 40th digit of the first line.

So when I set X to 40, the string appears from the beginning of the second line. So far so good. But when I change X to different values, this appears on the second line:

```
X=39 ... 123456789
X=40 ... 0123456789
X=41 ... 0123456789
...
X=47 ... 0123456789
X=48 ... 89
X=49 ... 789
...
X=56 ... 0123456789
X=57 ... 0123456789
...
X=64 ... 0123456789
X=65 ...  0123456789
X=66 ...   0123456789

```

Since address X=64 it works as expected, so increasing X by one shifts the string to the right by 1 character. The datasheet also says

> However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH (79). When N is 1 (2-line display), AAAAAAA can be 00H to 27H (39) for the first line, and 40H (64) to 67H (103) for the second line.

So the second line starts at 40H (64), not 40, it seems. Is it a confusion? What is the idea between address 40-64? It would make sense if the second line was address 28H-40H. I don't see the explanation in the datasheet. Also, how the DDRAM works for 20 characters per line and 4 lines displays?

# Answer
> 2 votes
Your confusion here is mixing "digit" and "byte". The two are not the same.

HD44780's can never have more than two rows. If you look at the block diagram you can see there are 16 "COM" connections. Those are the rows of the characters - 8 per line. That gives at most 2 lines of text.

20x4 displays are actually 40x2 displays but sliced in half and stacked. The 21st character of the first line is actually the first character of the 3rd line.

These two lines are split into two separate blocks of memory. One starts at 0x00 and the other at 0x40. The two blocks are pretty much completely separate. There is nothing of any interest to you between 0x28 and 0x3F. In fact that memory may not even exist - however those addresses may map to other addresses within memory. This will purely be an artifact of how the memory is addressed internally.

For simplicity of decoding the addresses the two blocks of memory are distinguished purely by the most significant bits of the address. The lower bits, then, will always be the same for the same location in both lines of text. That is, for the same horizontal character position on the display the first row (COL0-COL7) will have the same address in memory as the second row (COL8-COL15) except the most significant bits.

Since the HD44780 operates in blocks of 40 bits (8 characters, 5 bits per character) for its displays and uses "extension modules" to give each extra block of 8 bits (which is why you get 8, 16, 20, etc widths) having the two lines of text with truly consecutive memory addresses would make decoding the addresses needlessly difficult. So they don't.

If you take an example of the 3rd character horizontally on the display the pixel address in memory will be (note: this is the *pixel* address, which is 5x what the character address would be after the data has been generated from the internal character set):

```
Line 1: 0x02 = 0b00000010
Line 2: 0x42 = 0b01000010

```

Since the memory itself is 80 bytes and designed to be no more than 40 characters wide with 1 or two rows, there necessarily has to be a dead zone between the blocks of addresses. If the addresses were completely contiguous, so that the first character of the second row (character 40) was the 40th address in memory, the memory addresses would look like this:

```
Line 1: 0x02 = 0b00000010
Line 2: 0x2a = 0b00101010

```

Mapping those two addresses to the signals COM0-COM7 and COM8-COM15 would be considerably harder and take far more complexity in the design of the chip - which the manufacturer certainly doesn't want.

It is far simpler to add a little bit of logic into the cursor control which says "If the cursor moves from position 39 to 40 then set the memory address to be 0x40".

So when writing successive characters to the display the cursor logic hides the segmented memory from you. But if you are directly manipulating that segmented memory then you have to take that segmentation into account.

---
Tags: lcd, display
---


# Question
Title: Problem in defining a variable as multiplication
I have a simplest code to turn on and off a led. The variable holding time definition is `onTime`, using Arduino Nano.

When it is written as: `onTime=1000*30`, all is good.

When `onTime` is greater than this, `if` loop does not return `true` value when needed ( see code below ).

BUT when writing it implicit as `onTime=60000`, and not `onTime=1000*60` code run OK.

I'm guessing that value of 30\*1000 - has to be something with `int` value.

CODE:

```
int enbPin = 10;
bool onState = true;
unsigned long onPeriod = 60*1000; // <----
unsigned long startTime = millis();
void setup() {
  // put your setup code hee, to run once:
  Serial.begin(9600);
  pinMode(enbPin, OUTPUT);
  digitalWrite(enbPin, onState);
  Serial.println("START");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (millis() - startTime >= onPeriod ) {
    onState = !onState;
    startTime = millis();
    digitalWrite(enbPin, onState);
    Serial.println(onState);
  }
}

```

# Answer
`unsigned long onPeriod = 60ul * 1000;`

`ul` makes 60 to unsigned long and then the calculation has place for result.

without `ul` the constants and the result are `int` and it overflows
> 4 votes

# Answer
Juraj already told you how to fix this.

Some more info on why:

## (Edited)

By default, the C/C++ compiler uses the smallest size that can hold the specified value for integer constants, starting with the "native" integer size on the platform it's compiling for. For a 16 bit device like an AVR-based Arduino, an int is 16 bits. A signed 16 bit int can hold a value from -32768 to 32767.

(As pointed out by AnT in his comment, if you declare an integer constant of 60,000, the compiler automatically promotes it to the larger long int type.)

It evaluates expressions assuming int constants are of type int unless their value doesn't fit in an int. If you try to do math with an int and a long int, or store the results of int math into a long, the int gets "promoted" to the larger data type first.

In your expression:

```
unsigned long onPeriod = 60 * 1000;

```

The compiler first evaluates the right side of the expression, `60 * 1000`, as `(int)60 * (int)1000)`. Since it treats both parts of that expression as 16 bit signed ints, it does the multiplication using 16 bit integer math. The result of the multiplication is 60,000, which is too large to store in a signed int, so the intermediate calculation overflows.

It then tries to store the result to an `unsigned long`. It promotes the now-overflowed value to an unsigned long and stores the (garbled, and thus wrong) result into the unsigned long destination.

By either expressing either or both values as an unsigned long constant, or casting one or both of them to an unsigned long type, the compiler then promotes both values to unsigned longs before doing the math on them, so the result doesn't overflow before being assigned to the destination variable.
> 1 votes

---
Tags: data-type
---


# Question
Title: Split serial monitor output to only save part of the output
This is the output i get from the serial monitor from using a HM10 in . How could i go about splitting the data using arduino uno. I only want to save the last 12 digits before the :- (4CAA0DE091B7) for it to then be in a format to send as an SMS using a GSM module

```
OK+Set:1OK+Set:1OK+RESETOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-073OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-042OK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-081OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-079OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-059OK+DISC:00000000:00000000000000000000000000000000:0000000000:7D2A86B2A8CD:-082
OK+DISCEOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-062OK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-073OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-079OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-089OK+DISC:00000000:00000000000000000000000000000000:0000000000:0CF98919DB7C:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-041OK+DISC:00000000:00000000000000000000000000000000:0000000000:56
OK+DISISOK+DISC:00000000:00000000000000000000000000000000:00000OK+DISISOK+DISCEOK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-080OK+DISC:00000000:00000000000000000000000000000000:0000000000:7F4B515BC186:-081OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:0CF98919DB7C:-077OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-070OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-077OK+DISC:000
OK+DISCEOK+DISISOK+DISC:00000000:00000000000000000000000000000000:0000000000:4AAC2B4B1C7C:-075OK+DISC:00000000:00000000000000000000000000000000:0000000000:4CAA0DE091B7:-076OK+DISC:00000000:00000000000000000000000000000000:0000000000:38F9D379C9E5:-063OK+DISC:00000000:00000000000000000000000000000000:0000000000:649BDE9A25C5:-078OK+DISC:00000000:00000000000000000000000000000000:0000000000:DF12A8020D32:-044OK+DISC:00000000:00000000000000000000000000000000:0000000000:42AB41C03534:-059OK+DISC:00000000:00000000000000000000000000000000:0000000000:446B17218E0C:-071OK+DISC:00000000:00000000000000000000000000000000:0000000000:7D2A86B2A8CD:

```

# Answer
implement a circular buffer of say 30 characters.

clear the circular buffer

read into the circular buffer, char by char

when the last 13 characters in the buffer are: `:4CAA0DE091B7` Then the prior 12 characters are the data of interest
> 1 votes

---
Tags: arduino-uno, programming, bluetooth, c, gsm
---


# Question
Title: Understanding MOSFET parameters - Dimming/Switching LED strip
I'm trying to create a dimmable/ switchable 12v LED strip using an Arduino board and a MOSFET. Many tutorials can be found doing so such as this youtube link.

I've bought a LM317T before I had any substantial knowledge regarding MOSFETs. Trying to understand using some tutorials ( each one used different MOSFET ) made it partialy clear what parameters to look for in such project mainly using this link, **but** some left in the dark - and this is the reason for this post ( and to understand why my MOSFET is not suitable ).

I'll compare with one suggested, FDC855N

1) It has to be "Logic Level" MOSFET, meaning Vgs has to be 5v: from what I **understand**, 0v at the gate you get 0v at the drain and at 5v at the gate you get maximum Vsource. it is correct ?

1a) FDC855N Vgs's value is +/- 20v, how is it Logic Level ? will Vdrain @Vgs=5v will be different when @Vgs=17v ?

1b) Why in FDC855N Vgs have 2 values when Rds(on) is noted? one is 10V and other is 4.5v ?

2) Vgs(th) stands for minimal voltage needed for current flow at to drain. it is correct ?

2a) why is it noted as @Vgs=Vds ?

3) why Rds(on) is important for ? only for power dissipation purposes ?

I'll be glad to have answers for those question in comparison to the 317T MOSFET, since 317T datasheet has a different terminology :(

Appreciate any help, Guy

# Answer
First of all, the LM317 and the are FDC855N different types of devices. The LM317 is a voltage regulator whereas the FDC855N is a discrete MOSFET.

A MOSFET will act as a fast switch allowing you to control the LED's brightness using Pulse Width Modulation.

For what you're trying to do, you can think of the MOSFET as a voltage-controlled switch. If the voltage between the gate and source (Vgs) is greater than the threshold (Vgs(th)), then the current will flow from the drain to the source (Ids).

1) Yes, anything over the typical Vgs(th) of 2.0V, will turn on the switch and cause *current* to flow; you need to provide a voltage across the drain and source (Vds).

1a) 20V is the maximum rating of Vgs, if you applying anything greater, you'll damage the device.

1b) In reality, the MOSFET is more complicated than just an on/off switch. The gate to source voltage (Vgs) determines how *hard* the switch is turned on, so increasing Vgs will turn the switch on harder and reduce the resistance (RDS(on)) between the gate and source.

2) Yes, this is essentially correct. The relationship follows a curve and Vds(th) represents an inflection point. This plot from page 3 in the datasheet shows the curve for different temperatures. You can see that the 25C line is basically zero until Vgs reaches about 2.75 volts and then it increases rapidly.

3) RDS(on) is the resistance between the drain and source when the MOSFET is on. You can treat the drain to source path like a resistor and use RDS(on) to determine the power dissipation. For example if your RDS(on) were 0.1 ohm and the current through the drain is 1.5A, then you would be dissipating I^2\*R = (1.5)^2\*(0.1) = 0.225 , which is below the maximum allowable steady-state power dissipation of the device (Pd) of 0.8 W.
> 3 votes

---
Tags: mosfet
---


# Question
Title: NRF24 CE and CSN connections without I/O pins easily accessible
I want 2 Arduinos communicating to each other, but only in one direction. Arduino A = tx and Arduino B = rx.

I have this working fine connecting CE and CSN on each NRF24 to pins 4 and 5 on each Arduino and using the nRF24L01 library. No problem.

Since Arduino A will always ONLY be transmitting and Arduino B will always ONLY be receiving, can I do this with CE and CSN instead:

Arduino A --- put CSN to GND and put CE to 3.3V Arduino B --- put CSN to 3.3V and put CE to 3.3V

As to why? This would simply help me interface the NFR24 to existing custom PCB's I've made which have no ***easy*** access to I/O pins. My PCB's do have easy access to MISO, MOSI, and SCK.

# Answer
No, you really do need the CE pin for both TX and RX modes. See the following excerpts from the nRF24L01 datasheet. They work practically the same for nRF24L01+:
> 2 votes

# Answer
It seems the CE pin is only used for TX, or to put it into standby. I think you can just connect it to VCC.

The CSN is required for SPI.

PS this RF24 library supports using the same pin for both CE and CSN. You'd have to define `RF24_TINY` for this to work.
> 1 votes

---
Tags: nrf24l01+
---


# Question
Title: What type of power supply is the Arduino Due’s 5v pin and what is its current?
I’m looking to use a Futaba Servo with my arduino Due and was told it requires a “high current 5 volt supply” and I don’t know much about current so excuse my arrogance. I know the arduino Due has a 5 volt pin. **But what type of power supply is it**? (Linear power supply, switching power supply, etc.) and **how much current does it provide**? If I get this information to my instructor he can tell me if it will suffice.

Thank you!

# Answer
> 0 votes
An Arduino should not be used as a power supply for a servo. The 5V pin is connected to the the 5V supply of the USB connector, **OR** to the output of a step-down buck regulator converting the DC barrel jack to 5V.

None should be considered "high current" for servo or motor use.

Most PC USB ports will max out at 500mA current output unless the device connected asks for more from the PC. The Arduino does not.

The buck-converter controller chip is a LM2434, whose datasheet specifies 1A maximum output current.

Driving motors or servos will draw enough current, intermittently, to overload either of those and will likely cause the Arduino to reset.

If you need to power a motor-type device, power it separately from the control signals. Power should go from the source to the motor, and the control signal from the Arduino to the servo, making sure to connect the ground wires of all to each other (motor, Arduino, power source).

---
Tags: power, pins, arduino-due
---


title: Use ATTiny as a battery-backed RAM?

text:
# Question
Title: Use ATTiny as a battery-backed RAM?
So, I found an interesting article the other day, and I'm trying to build a project that could benefit from a battery-backed memory (no wear limits, but keeps data over power cycling). The article lists how an extremely small current from an LED (acting as a photocell in the lit room) accidentally powered the AVR during a RAM-endurance test.

But, what if this is done on purpose with a battery?

(Article here: https://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/)

The problem with this idea (since the RAM can already be backed up, as shown in the article, though the author does not seem to have considered this) is that **I need a way to keep an array of memory ignored by the C initializer**. It would be the height of hilarity to have the memory survive the power-off event only to be nuked by the chip's powerup reset code. The listed example at that article would work, for the first requirement, but would break almost anything else I might try to do (since it overrides the *entire* initializer). (Comment on the reset issue: https://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/#comment-598)

Also, assuming I tried this, would I simply damage the pin rather than provide power? I plan to use a pin continually set to `input` attached to the positive side of a lithium coin cell, with a common ground. In theory, powering the AVR (and I think at any voltage) through the VCC pin would cause the chip's diodes to disconnect the battery, but if it's unplugged, the core would receive enough power to keep the RAM alive.

Of course, my question is whether it would instead stupidly try to keep the core *running* when power is disconnected (in the original article, the nanowatts from the LED couldn't do that, so it's forced to shut down, but I don't know if this is solely due to power limits or if it would shut down the main systems if there's no connection over VCC). In this case, it might try to draw more than the 1mA rating over that parasitic supply, and try to power the entire chip when I don't want it to (thus frying the clamping diode or something equally bad).

I wonder if it would be possible simply to put a large resistor (10K? 1M?) in series with the battery in this case? That would automatically limit the supply to less than 1mA.

# Answer
> 2 votes
Expanding on my previous comment...

> I need a way to keep an array of memory ignored by the C initializer

You can achieve this by instructing the compiler to store the array in the “.noinit” memory section:

```
int my_array[ARRAY_LENGTH] __attribute__((section(".noinit")));

```

Your array will end up sitting somewhere between the .bss and the heap (if any), and will not be touched by the `__do_clear_bss` routine from the C startup code.

> my question is whether it would instead stupidly try to keep the core *running* when power is disconnected

Most likely. In order to avoid that, I suggest you enable the brown-out detection by setting the `BODLEVEL` fuses. This feature of the ATtiny is specifically meant to prevent the CPU core from running if the supply voltage is below some configurable threshold.

# Answer
> 0 votes
For anyone wanting to know further how I implemented this, I did set the BOD fuse on my device. Still, not wanting that sort of fun (referring to having the chip try to actually *run* via the backfed power) to happen at all, I wired a 1M resistor in series with the supply backfed through the pin (which was set to INPUT in all cases. HIGH would result in attempting to charge the backup battery, and LOW may well sink the input current and negate the benefits) in an effort to force the current to be high enough to power the RAM but too low for it to run. It also makes sure that too much current cannot flow through the pin.

My results were somewhat inconsistent, and it doesn't help that the device can actually end up powered by whatever indicator LED is added to show that it worked!

Still, there's a good chance that this can be used as an NVRAM if the code is written for it. As for that, just store an array with the values, and write onReceive and onRequest code to index that and send it back out!

Fair warning: If the power bus is connected to other components, the AVR won't keep its memory. Use a diode to prevent power from escaping.

---
Tags: power, avr, attiny85
---


# Question
Title: Adafruit Circuit Playground Express interrupt not working
I have interrupts attached to pins 4 and 5 which correspond to the left and right inbuilt buttons on the circuit playground express (https://learn.adafruit.com/adafruit-circuit-playground-express/pinouts). For some reason the right button interrupt works perfectly however the left interrupt doesn't even trigger. Here's the code:

```
#include <Adafruit_Circuit_Playground.h>
#include <Adafruit_CircuitPlayground.h>

volatile bool leftState = false, rightState = false;

void left()
{
    if (CircuitPlayground.leftButton())
        leftState = !leftState;
}

void right()
{
    if (CircuitPlayground.rightButton())
        rightState = !rightState;
}

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

    attachInterrupt(digitalPinToInterrupt(4), left, CHANGE);
    attachInterrupt(digitalPinToInterrupt(5), right, CHANGE);
}

void loop()
{
    Serial.print(leftState);
    Serial.print("\t");
    Serial.print(rightState);
    Serial.print("\n");
}

```

# Answer
Pin 4 on Zero can't be used with attachInterrupt. It is pin PA08 of the SAMD21 and this has NMI as interrupt control function in EIC and can't be used as EXTINT.

Adafruit Circuit Playground maps PA28 to pin 4, but the description of the pin is left as for Zero and doesn't declare interrupt capability.

In file `arduino/hardware/samd/1.6.21/variants/circuitplay/variant.cpp` change the line for pin 4 to

```
  { PORTA, 28, PIO_DIGITAL, (PIN_ATTR_DIGITAL), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_8  },                           // GPIO D4 / Left Button

```

Packages are located in ~/.arduino15/packages/ on Linux and %userprofile%\AppData\Local\Arduino15\packages\ on Windows (AppData is a hidden folder).

Warning: In variant.cpp the overview comment's table describes Zero, not Circuit Playground.

Note: It is not beneficial to read a button with interrupt. You can only set some flag in interrupt and then handle it in the loop(). But then you can directlly check in loop the state of the pin, because it will be active many loops even if the user pushes it for a short time.
> 2 votes

---
Tags: adafruit
---


# Question
Title: Is there a digital/ultrasonic Anemometer for Arduino?
I use Arduino DUE and I noticed that many forum users use the TX-23U Wind Sensor.

https://www.amazon.com/Crosse-Technology-TX-23U-Weather-Stations/dp/B0016MYA7U

Also, many people tried to create a DIY ultrasonic anemometer like this; https://soldernerd.com/category/arduino-ultrasonic-anemometer/

Instead of using the DIY ultrasonic anemometer, I wanted to purchase one but I couldn't find one.

Is there an ultrasonic anemometer which I can purchase and connect it with my Arduino DUE?

3.3V power, non-mechanical rotation, I2C/SPI/UART support are the requirements. Thanks.

# Answer
Frame challenge: pick a sensor that complies with your needs and specification - especially the performance characteristics you're interested in, e.g. range of wind speed to measure, required accuracy and resolution, response time and data acquisition rate, to name just a few. Don't look for something specific to Arduinos to not unnecessarily narrowing down your options. Then design or adapt an appropriate interface to make them both work together.

Common interfaces of "industrial grade" ultrasonic anemometers (e.g.  and ) are RS232/RS422/485, so technically UART, though in need of level shifters or a RS-485/RS-422 transceiver, e.g. Maxim. Some also offer analogue output that might be feed into an Arduino's analogue in after matching voltage levels.

I would assume that I2C/SPI are rather uncommon as these are for short-distance, intra-board communication not for connecting a separate sensor module.

The same thought applies to the power supply, I recommend to drop the requirement of powering the sensor with 3V3 put rather select a power supply for a sensor available and affordable. The anemometers available at the linked vendors typically list a supply voltage of 5-30VDC or 6-24VDC.
> 1 votes

# Answer
You can see this one: SONIC-ANEMO-MICRO https://lcjcapteurs.com/en/girouette-anemometres-capteur-vent/sa-micro-2/
> 1 votes

---
Tags: sensors
---


# Question
Title: Possible to determine at runtime whether a pointer is declared PROGMEM?
Is it possible to determine at runtime whether a pointer points to `PROGMEM`'ed values or regular values? This would give some flexibility when writing code that handles both.

# Answer
Not really, if you are asking whether you can determine (simply from its value) whether 0x100 is in RAM or PROGMEM. Both are possible candidates for a memory location.

The `F()` macro works around this by changing the *type* of a variable at compile-time, so that the compiler can select a suitable method of printing. For example:

```
Serial.println ("Hello, world");
Serial.println (F("Hello, world"));

```

In this case the appropriate `println` function is chosen at compile-time by the compiler, based on the type (one would be a `const char *`, the other a `__FlashStringHelper` type).

You are best off designing a way (similar to the `F()` macro) where you can make the decision at compile time.
> 2 votes

# Answer
> Is it possible to determine at runtime whether a pointer points to PROGMEM'ed values or regular values? This would give some flexibility when writing code that handles both.

The AVR MCUs are Harvard Architectures. Data and program memory spaces are separated. There are also several data memory spaces, e.g. SRAM, EEPROM, PROGMEM. Each of these have there own address space, and special instructions are used to access them.

In software anything is possible :) so it is possible to unify the address spaces and use a run-time mechanism to do the respective read and write. A simple method is to use the most significant bits to determine the address space. For instance,

```
SRAM 0x0000..0x7fff
EEPROM 0x8000..0x8fff
PROGMEM 0x9000..0xffff

```

SRAM pointers are as usual, EEPROM pointers have an extra 0x8000, and PROGMEM pointers an extra 0x9000.

The next step is to write a simple mapping function from the unified address space to the separate memory address spaces. This can be wrapped into a C+++ smart pointer and/or a simple C++ class hierarchy.

An example of this technique can be found in 1) Forth Virtual Machine for Arduino, https://github.com/mikaelpatel/Arduino-FVM (see https://github.com/mikaelpatel/Arduino-FVM/blob/master/src/FVM.cpp#L85), 2) RPN Postscript/Forth Command Shell for Arduino, https://github.com/mikaelpatel/Arduino-Shell (see https://github.com/mikaelpatel/Arduino-Shell/blob/master/Shell.h#L1059).

Cheers!

PS: An interesting detail with the AVR architecture is that the registers 0..31, and the io-registers, are mapped to the SRAM address space.
> 1 votes

---
Tags: c++, progmem, sram, memory
---


# Question
Title: How can I make FastLED set every 2 LEDs to the same color?
I'm controlling an WS2812 LED strip in which every 2 leds is controlled together - they are setup as "eyes" in a prop. I'm looking to control hundreds of these, so in an effort to save RAM I'd like to have each byte in the LED color array represent 2 LEDs. That is to say that when the FastLED library writes to the data lin I want it to duplicate every byte going out.

I've dug into FastLED code but get lost around the timings deep down in the code.

Any ideas?

# Answer
* The FastLED community appears to live at this reddit.com site. Consider asking your question there.
* It is unknown if the following will exceed the current limitations of the Arduino platform you are using. But, consider sending the same data to two different strings of LEDs simultaneously. Briefly, each LED strips off the 1st packet of data and sends the balance of data through to the next LED. Two different strips should behave the same if given the same data. Thereby creating the effect you described (pairs of LEDs behaving the same).
> 1 votes

---
Tags: attiny, ws2812
---


# Question
Title: Parsing and comparing strings on Arduino: different behaviour from gcc?
I am trying to parse a simple string, print the result of the parsing via serial.println, and trigger a function on the basis of the received command. I wrote the code below, which perfectly works in c (see the c file attached). However, the behaviour of the same code on the arduino IDE is completely different and I really can't figure out why.

```
#include <string.h>

void rcv_msg(char *rcv_msg) {

  char *all_tokens[2];
  int i = 0;

  all_tokens[i] = strtok(rcv_msg, "{,}");
  while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{,}");
  }

  char *command = all_tokens[0];
  char *value = all_tokens[1];

  /*
  //These printls do not work, they are ignored, why?
  Serial.println("all_tokens[0]: ");
  Serial.println(all_tokens[0]);
  Serial.println("all_tokens[1]: ");
  Serial.println(all_tokens[1]);
  */

  if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {

    Serial.println("message 1: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }

  if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {

    Serial.println("message 2: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }
}

void setup() {

    Serial.begin(115200);
}

void loop() {

    char msg1[] = "{message_1,1}";
    char msg2[] = "{message_2,0}";

    Serial.println("Send msg1: ");
    rcv_msg(msg1);
    delay(5000);

    Serial.println("Send msg2: ");
    rcv_msg(msg2);
    delay(5000);
}

```

This code gives the following output on the serial monitor, which is wrong:

Send msg2: message 2: message\_2 {message\_2,0}

Send msg1: message 2: message\_1 {message\_2,0}

Send msg2: message 2: message\_2 {message\_2,0}

Send msg1: message 2: message\_1 {message\_2,0}

Firstly, I don't understand why at the beginning, message 2 is printed before message 1, although message 1 was sent first. Second it is not clear to me the comparison done with strcmp is always returning the message 2.

More importantly, why running the same code in c has instead the correct output? I wonder if there is any error in my arduino code. BTW, I am testing the code on Teensy 3.2 but I plan to use it also on Arduino Uno.

The c code (which is perfectly working is this:

```
#include <string.h>
#include <stdio.h>

void rcv_msg(char *rcv_msg) {

    char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value
    int i = 0;

    all_tokens[i] = strtok(rcv_msg, "{, }");
    while (all_tokens[i] != NULL) {
        all_tokens[++i] = strtok(NULL, "{, }");
    }

    printf("all_tokens[0] : %s \n", all_tokens[0]);
    printf("all_tokens[1] : %s \n", all_tokens[1]);

    char *command = all_tokens[0];
    char *value = all_tokens[1];

    printf("command : %s \n", command);
    printf("value : %s \n", value);

    if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }

    if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }
}

int main() {

    char msg1[] = "{message_1, 1}";
    char msg2[] = "{message_2, 0}";

    rcv_msg(msg1);
    rcv_msg(msg2);

}

```

# Answer
Both versions of your code have undefined behavior. On the given input your code will call `strtok` *three times* and store its result into the array *three times*: for the first token, for the second token and, finally, for the null pointer. You store all three (including that null pointer!) into the `all_tokens` array, which has size `2`.

You are obviously aware of the potential array overrun danger: you even wrote this comment in your code

```
char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value

```

and yet in the following cycle

```
int i = 0;

all_tokens[i] = strtok(rcv_msg, "{, }");
while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{, }");
}

```

you still insist on storing more than two values into `all_tokens` array.

---

Also, the second version of your code uses completely different message key values (why is it suddenly `"motor1_pattern1"` instead of `"message_1"`?), which makes it unclear how you compared the functionality of the second version with the functionality of the first.
> 1 votes

---
Tags: arduino-ide, teensy
---


title: cannot upload my program to arduino uno

text:
# Question
Title: cannot upload my program to arduino uno
I bought new Uno yesterday, i made my programme, and i compile it. it was good compiled. however, when i upload the programme to my Uno, it cannot be uploaded and there was a message like this

avrdude: stk500\_getsync() attempt 10 of 10: not in sync: resp=0x1b Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Help me please

# Answer
> 0 votes
1. Make sure u have selected the right COM port
2. Make sure nothing is connected to the pin 0 and 1 in arduino

This happens because the Arduino IDE could not find Arduino Board Connected to the system.

---
Tags: upload
---


title: Multiple defintion error, Linker error

text:
# Question
Title: Multiple defintion error, Linker error
Trying to create an elf file for two sets of files in different folders.

```
LIDARBOT.h
-----------
#ifndef LIDARBOT_H_
#define LIDARBOT_H_

#include <avr/io.h>
#include "drivers/motors.h"

#endif

LIDARBOT.C
----------
#include "LIDARBOT.h"
int main(){
  pwmtimersetup();
    while (1) {
    }
}

motors.h
--------
#ifndef MOTORS_H_
#define MOTORS_H_

#include <avr/io.h>

void pwmtimersetup(void);

#endif

motors.c
--------
#include <avr/io.h>
#include "motors.h"

void pwmtimersetup(void){
  // Timer pre-scalar for ~490 Hz is 8
  TCCR0B &= ~((1<<CS02)||(1<<CS00));
  TCCR0B |=  (1<<CS01);
  // Set Compare Output Mode to Toggle PWM
  TCCR0A &= ~(1<<COM0A1);
  TCCR0A |=  (1<<COM0A0);
  // Waveform Generation Mode: WGM02 = 1, WGM01 = 1, WGM00 = 1
  TCCR0B |= (1<<WGM02);
  TCCR0A |= (1<<WGM01)||(1<<WGM00);
  OCR0A = 125;
  DDRD |= (1<<DDD4)||(1<<DDD2);
  PORTD |= (1<<PORTD4);
  PORTD &= (1<<PORTD2);
}

```

I can make a consolidated object file but not an elf file to load onto my board. Output below:

```
avr-gcc -g -Os -Wall -Werror -Wextra  -mmcu=atmega328p -DF_CPU=1000000UL -Wa,-ahlmns=LIDARBOT.lst -o objects/LIDARBOT.o \
source/LIDARBOT.c \
source/drivers/motors.c \
-I/home/manu/C/Arduino/LIDARBOT/libraries/

avr-gcc -g -Os -Wall -Werror -Wextra -mmcu=atmega328p -DF_CPU=1000000UL -o elf/LIDARBOT.elf objects/LIDARBOT.o
objects/LIDARBOT.o: In function `__vector_22':
(.text+0x7c): multiple definition of `__bad_interrupt'
/usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.text+0x0): first defined here
objects/LIDARBOT.o: In function `__vectors':
(.text+0x0): multiple definition of `__vectors'
/usr/lib/gcc/avr/5.4.0/../../../avr/lib/avr5/crtatmega328p.o:(.vectors+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [Makefile:191: elf] Error 1

```

I am kind of lost. What could be my mistake here? If I see an error like this how do i start to debug?

# Answer
You forgot the -c flag to your first command. That means you have first compiled your program into a full elf file. Then you try to link that elf file with the standard startup libraries again (it already contains them) into another new elf file.

And so you get duplicate entries in it.

Add -c to your first command, which means "compile only, don't link" to create object files not an elf file.
> 2 votes

# Answer
Thank you guys for your input, AnT and Majenko. I realized my issue which was trying to link a .o file into another one. So I corrected my make file by individually compiling but not linking the source files with the -c option. I then made my final elf file using the unlinked .o files.
> 0 votes

---
Tags: arduino-uno, c, avr-toolchain
---


# Question
Title: Sharing serial output from one to many arduinos (plus a computer) via USB hub
I am trying to send rotary encoder output from an UNO to seven Trinket M0s *and* a computer via a (powered) USB hub.

Currently the UNO → Laptop bit works great, serial monitoring works via the hub for everyone and I'm able to get a master/slave connection going between the UNO and a Trinket via Arduino's Wire library. But Wire uses pins, and I haven't had any luck finding a similar solution for USB. Thus far, the best leads seem to be around using something like `stty` in a bash script to listen for what each port is up to but I'm so far in over my head at this point that that might just be wishful thinking.

I'm not looking for a solution here, just some suggestions as to where to head next. Specifically:

1. Is the Wire library useful for USB communication? Is there something similar (master/slave-wise) that would be helpful?
2. Assuming the serial/listen thing works, are there good ways to re-route data to different ports? Currently my best guess is something like `$ echo $encoderVal > /dev/cu.usbmodem?????` to each one individually ... but that might be a completely noobish notion.)
3. i2c keeps on coming up in searches, but looks like overkill. Is that a direction to head?
4. Is this all completely nuts?

Anyways, thanks to everyone in advance.

# Update

Ok! Thanks to the advice of @Gerben and @chrisl I ended up routing everything around with PySerial, and (for the extremely limited purposes of this little project) it works well! Here's what is currently working:

```
import serial
from time import sleep
import os

# Connect to each Arduino individually
serialUno = serial.Serial("/dev/cu.usbmodem141101", 9600, timeout=0)
serialTrinket1 = serial.Serial("/dev/cu.usbmodem1414401", 9600, timeout=0)
# (+ 6 more. serialTrinket2, serialTrinket3, etc)

# Open a text file to save the encoder value in
f = open("encoderVal.txt", "w")

while True:
  # Read encoderVal from the UNO
  data = serialUno.read(9999)
  if len(data) > 0:

    # Send data to each trinket
    serialTrinket1.write(data)

    # Save val to text file to Unity
    with open('encoderVal.txt', 'r+') as f:

      # Wipe the file so it's only the most recent value
      f.truncate()
      dataStripped = data.strip()

      # Return the last int in the data stream
      dataSplit = dataStripped.split('\n')
      f.write(dataSplit[-1])

  sleep(0.05)

# Close serial connections & file on interrupt
serialUno.close()
serialTrinket1.close()
f.close()

```

As for the laptop end of the equation, I abandoned the serial library that I *had* been using in favor of this Unity-to-Python tool, which works perfectly.

The only issue thus far is that PySerial loses the occasional few bytes here and there, which outputs a wonky number ever 30 or so. That'll be tomorrow's project. Thanks everyone for your help!

# Answer
> 0 votes
> Is the Wire library useful for USB communication? Is there something similar (master/slave-wise) that would be helpful?

The Wire library does I2C communication, which has absolutely nothing to do with USB. Actually the USB connection on the Uno is not native. The Atmega328P on the Uno only has a Serial (UART) interface, which is onboard connected to another chip (Atmega82U or others), which has native USB support. That chip will do the USB communication. The driver on the PC will then emulate a Serial COM port, so that it is something like a "Serial COM port over USB" connection. USB is complex and you should not tinker with it directly, unless you are very advanced in this direction. And I don't think, doing that would help you here.

> Assuming the serial/listen thing works, are there good ways to re-route data to different ports? Currently my best guess is something like $ echo $encoderVal \> /dev/cu.usbmodem????? to each one individually ... but that might be a completely noobish notion.)

Since you have a complete Unity game, you have to program something in that direction. Using the bash seems not good here. I don't know, if you can communicate with serial COM ports from Unity (since I haven't worked with it yet), but doing this in Python works like a charm. There are many tutorials out there, that show how to do it.

> i2c keeps on coming up in searches, but looks like overkill. Is that a direction to head?

If that is an overkill depends on your exact requirements for the system. Sure, the I2C protocol has a bit of overhead, but maybe you need the functionality.

> Is this all completely nuts?

Currently it seems a bit like that. I think, this due to you not having a good structure for the project. To help you with that, I will explain some possibilities below.

---

As I understood, you have the following setup: The Uno has a rotary encoder, that controls a game on the PC. All boards (Uno and Trinkets) have one LED strip, that should light up depending on what happens in the game.

You have now 2 basic structures for the communication:

1. Doing everything over an own USB connection. This is what you sketched above. Every board has it's own serial COM port (which actually get's emulated over USB by the driver) on the PC and your game/program on it has to connect to all these and send the appropriate data. Sure this is a possible design, but it comes with downsides: Currently it doesn't seem, that you already have implemented the communication program. That is important in this design, but that's not really about Arduino and depends on how you are programming the game in Unity (haven't done that before and don't know how to connect a serial device to it. Maybe through a python script). The second problem is, that you will have choose the serial port for every board, when you start the game. The port numbers/names are not always the same; it's up to the operating system to set these. That's not a great usablity.
2. You can use other communication interfaces between the boards directly. In this case only the Uno would be connected via USB to the PC and every data would go through the Uno. What kind of interface you should use depends on your exact requirements. Since you didn't specify them in detail, I will explain some examples:

* **Every Trinket get's the exact same data and nothing must be read from them:** In this case you can use the Serial (UART) interface. It uses the pins, that are marked with RX (receiving pin) and TX (transmitting pin). Normally this connection is only between 2 boards, but it is possible to simply connect multiple receivers (with their RX pin) to exactly 1 transmitter (with it's TX pin).

    The Uno has one hardware Serial interface, which is also used to communicate with the PC. If it is OK, that the PC also get's the data, which is meant for the Trinkets, (and the Trinkets get the data, that are meant for the PC) you can use this interface and wire the Uno's TX to all Trinket RX pins. You can google how to read data from the interface with the `Serial` library, which is directly available with Arduino. If you don't want the PC to get the same data, you can set up a `SoftwareSerial` interface (with the library with that name). That provides the same interface, but is handled in software, because the Uno doesn't have another hardware Serial (UART) interface.

    In both cases you would transmit the data from the PC (data out of the game) via the USB serial port to the Uno, which then in turn sends it further to all the Trinket boards. They read the data and act accordingly. Everytime the Uno senses new rotary encoder positions, it will send data to the PC.

    For connected the Uno with a Trinket, you only need 2 wires in this design (1 for Uno TX to Trinket RX and 1 ground wire). Of course, you also would have to provide power to the Trinkets. Please see below for that matter.
    * **Every Trinket can be address individually and data can also be read from them:** In this case I2C can be the way to go. For the communication you need at least 3 wires (SDA, SCL and ground). Every Trinket joins the I2C bus with a configured address. The Uno acts as master on the bus. He can call a Trinket by it's address and send or request data. The I2C protocol is more structured than serial (UART), because it is divided into transmissions. This works great, if the Trinkets can all get different data, and if you also want to read data from them. Be sure to give very Trinket a unique address on the bus. For the program part look into the `Wire` library.
    * **Individual sending and receiving in a very fast manner**: If you need the individual data transmitting and reading from I2C, but you also need the communication to be very fast, you can use SPI. The SPI bus doesn't use addresses, but Slave Select pins. You need 1 pin on the master (Uno) for every slave device. If you want to communicate with one Trinket, you pull it's Slave Select pin to LOW. This bus needs 5 wires (MISO, MOSI, SCK, Slave Select and ground), but the communication can be very fast; way faster than I2C. Look into the `SPI` libary for the programming of this.

---

**Providing power:** Depending on your design and the number and type of the LEDs, you have to look into, how you supply the needed power to the boards. In the design, that you sketched above, (every board directly to USB) the boards themselves should have enough power, but LED strips can be very power hungry, getting fast to currents over 1A. The pinout of Adafruits Trinket M0 shows a maximal current of 500mA from the Vusb pin. The 5V pin of the Uno can handle about 200mA (as I remember, currently not sure. You can google this).

If you choose a design with only the Uno connected to USB, you might need an extra power supply, so that you can provide the power for all Trinkets and their LEDs with it. Please adhere to the current limits of the components, or you may fry your boards.

I hope, that help's. Have fun

# Answer
> 1 votes
First, read a bit about USB, it is an entire protocol, not just a hardware/pin based interface. It is actually quite involved. Then it will be clearer to you why a USB (from the Nano) solution will be... difficult.

Based on my understanding, I would use your #2 idea and what has been suggested, and do the following...

1. Setup the Uno as a USB slave, not a master.
2. Using the PC, connect to the Uno and the Trinkets.
3. When the PC gets data from the Uno have the PC "repeat" it to the Trinkets.

I think this will be the easiest and quickest solution.

---
Tags: serial, i2c, usb, wire-library, port-mapping
---


# Question
Title: How to remove Adafruit Pro Trinket bootloader flashing startup sequence
From what I understand, the Pro Trinket has "Optiboot" which allows it to detect which boot loader you are trying to use, one for USB and one for FTDI. When it's in this "bootloader state" the red LED on pin 13 buses for 10 seconds before it starts to run the program I've programmed.

Can I remove this Optiboot functionality? Would that entail permanently choosing a single boot loader/interface?

One problem I have with this is that along with the LED on 13, it causes the LED strip I have attached to pins 9, 10, 11 to blink. I would also really like to not have to wait 10 seconds to start running code.

Here's the page on Adafruit's site that talks about the bootloader\[s\] on the Pro Trinket.

Thanks!

# Answer
You could take the Pro Trinket bootloader source code and tweak it to your needs, burn it, and make sure you have patience and debugging skills.

From the author's (Frank Zhao) source code, it seems that this is the 10 seconds loop you are referring to, located in **main.c**, line #456:

```
if ( ((usbHasRxed != 0) && (timeout > USBBOOTLOADER_TIMEOUT)

```

The `USBBOOTLOADER_TIMEOUT` variable which is defined to `10` at the top of that file, line #70:

```
#define USBBOOTLOADER_TIMEOUT 10

```

and is progressed after 'roughly' 1 second, at line #496:

```
// roughly 1 second
#if (F_CPU == 12000000)
    if (t1ovf > 183) {
    #elif (F_CPU == 16000000)
    if (t1ovf > 244) {
    #endif
        t1ovf = 0;
        timeout++;
    }

```
> 1 votes

# Answer
Just program the pro trinket using ISP. (not using the USB connector). For example by using an Arduino as a ISP-programmer.

If you are brave, you could change the bootloader to only run when the reset button was pressed, and not at power-up. I've done exactly that for the regular trinket (see my github)
> 1 votes

# Answer
I'd be careful to remove that section because these ten seconds are not only where the board detects which bootloader to use but also when it is accepting a new sketch at all. So if you'd get rid of that, you wouldn't be able to upload new sketches anymore i guess.
> 0 votes

# Answer
**It is actually much simpler than the other answers suggest. There is no need to remove/overwrite the bootloader.** You can just disable the bootloader by setting the appropriate fuse bit.

In order to do so, you need an ISP programmer. As you might know, you'll loose the ability to upload code though USB/FTDI. But you can restore that ability at any time, just by resetting the appropriate fuse bit to its original value.

## Step 1: Connect your trinket through an ISP programmer

There is no ISP header on the trinket, but you can easily build one or just use jumper wires to connect the individual pins directly to the programmer. Pinout can be found at learn.adafruit.com. You need to connect MISO, MOSI, SCK, RST, VCC and GND.

## Step 2: Determine current fuse configuration

```
avrdude -c usbtiny -p m328p

```

*If you're using a different programmer than the USBTinyISP, replace `usbtiny` with the appropriate identifier. List possible values by specifying a bogus identifier, eg. `avrdude -c foo`.*

Among some other things, avrdude should return a line containing the current fuse values. It should look similar to the following:

> avrdude: safemode: Fuses OK (E:FD, H:D0, L:FF)

We're interested in the *high* fuse (H:D0). `D0` indicates that the bootloader is enabled. Actually, any even number means the bootloader is enabled.

## Step 3: Calculate new fuse value

We want to set the `BOOTRST` bit of the *high* fuse. It is the least significant bit of the fuse, which equals the number 1. So all we need to do is increment the value by 1.

In the example, the new fuse value is `D1`.

*If you are unsure how to calculate the fuse value, you can use the Fuse Calculator. Choose ATMega328P as your device, enter the fuse values as reported by avrdude at the very bottom under "Current settings", then click apply. Uncheck `BOOTRST` in the "Manual fuse bits configuration" section, then you will see the new fuse value in the bottom section, where you entered the original value.*

## Step 4: Program new fuse value

```
avrdude -c usbtiny -p m328p -U hfuse:w:0xd1:m

```

Again, replace `usbtiny` with the identifier of your programmer. If you calculated a different value than `D1`, replace `0xd1` with your approriate value. **However, if your original value for the high fuse was `D0`, then your new value *is* `D1`.**

## Done!
> 0 votes

---
Tags: bootloader
---


# Question
Title: Programing AVR 32u4 via ISP with other ISP device connected
I have a custom PCB with an Atmega 32u4 chip. I program the chip with AVRDUDE via ISP after it is has been mounted onto the PCB. All is well.

I now want to add wireless capability via the NRF24L01. The NRF communicates with the 32u4 via ISP. Can I still program the 32u4 on the PCB after the NRF has been mounted or will there be a problem since they are both connected to the ISP pins?

# Answer
Yes, that is possible and I've done the exact same thing with an ATmega328 which controls a DAC via SPI. If it wasn't possible ISP wouldn't be an option whenever SPI is already in use. You should make sure that the NRF's CS pin is high while flashing the firmware, otherwise it might corrupt a checksum verification or memory readout.

Note the difference between ISP (in-system programming) and SPI (serial peripheral interface). Even though ISP uses SPI and they have similar abreviations they are not the same.
> 1 votes

---
Tags: programming, isp
---