body:
My Setup: 3.3v LiFePo battery attached to G and 3.3 pins. Serial-USB connected.

Result: During the following code the blue on-board LED blinked rapidly for a few seconds then went off. I unplugged it to see if it was programmed but the Blink Sketch didn't run. Any help would be greatly appreciated.

    Sketch uses 222,205 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
    Global variables use 31,572 bytes (38%) of dynamic memory, leaving 50,348 bytes for local variables. Maximum is 81,920 bytes.
    C:\Users\jhoxie\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin
    **(Everything below this line was highlighted in red)**
    esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
     setting board to nodemcu
     setting baudrate from 115200 to 115200
     setting port from COM1 to COM3
     setting address from 0x00000000 to 0x00000000
     espcomm_upload_file
     espcomm_upload_mem
     setting serial port timeouts to 1000 ms
    opening bootloader
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
     espcomm_send_command: receiving 2 bytes of data
    Uploading 226352 bytes from C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin to flash at 0x00000000
     erasing flash
     size: 037430 address: 000000
     first_sector_index: 0
     total_sector_count: 56
     head_sector_count: 16
     adjusted_sector_count: 40
     erase_size: 028000
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     setting serial port timeouts to 15000 ms
     setting serial port timeouts to 1000 ms
     espcomm_send_command: receiving 2 bytes of data
     writing flash
    ................................................................................ [ 36% ]
    ................................................................................ [ 72% ]
    ..............................................................                   [ 100% ]
    starting app without reboot
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     espcomm_send_command: receiving 2 bytes of data
    closing bootloader
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete

title: ESP8266 (D1 mini) fails to upload sketches

Answers: 1

body: Thank you for your input. Especially the tip on connecting the battery while connected to usb [tttapa] I finally got it to work by changing the baud rate and messing around with the settings(i.e. board in IDE). I believe I got it to work with the "WeMos D1 R2 & Mini" board whereas I was using the generic esp8266 board.


body:
I'm trying to receive sms and show it on serial monitor.

My code is as follows:

    void setup() {

    Serial.begin(2400);

    Serial.write("AT+CMGF=1\r"); //set GSM to text mode

    delay(1500);

    Serial.write("AT+CPMS=\"SM\"\r"); //Preferred SMS
    //message Storage

    delay(1000);

    Serial.write("AT+CMGL=\"ALL\"\r"); //List SMS Messages
    //from Preferred Storage

    while(1)

     {

       if(Serial.available())

         {

            Serial.write(Serial.read());

          }
      }
    }
    void loop() { }

The output that I am getting is as follows:-

 >AT+CMGF=1AT+CPMS="SM"AT+CMGL="ALL"AT+CMGF=1
 >
 >OK
 >
 >AT+CPMS="SM"
 >
 >ERROR
 >
 >AT+CMGL="ALL"
 >
 >ERROR

This I am not able to use AT+CPMS or AT+CMGL commands. Please help.
The circuit diagram is as follows:-

.![enter image description here](https://i.stack.imgur.com/DtvaI.jpg)

title: Unable to receive and print sms on serial monitor arduino uno and SIM900A

Answers: 0


body: I'm designing a lightweight circuit, but the ATtiny85 micro-controller I'm using to power it doesn't have nearly enough flash memory to store the code for the devices I'll have hooked up to it (It has 8kb of flash). I was wondering if it'd be possible to have the ATtiny use compiled code from an external flash memory chip of larger capacity elsewhere on the board like its own internal memory. Thanks in advance.

title: External Flash Memory for ATtiny85

Answers: 3

body:
No, it's not possible.

AVR chips can only execute code from their internal flash.

body:
Although you cannot run code from external (S)RAM, you can:

- optimize your code (reducing the number of lines of code by):
  - use parameterized functions instead of copying/paste code
  - reduce the type (storage) variables (like constants) which are kept in memory, e.g. instead of 200 integers of 2/4 bytes use 200 bytes
  - instead of storing const calculated array values, calculate them runtime (causing a performance reduction)
  - remove unused libraries
  - strip down used libraries (not needed to remove unused functions)

body:
You could write a small bootloader and load code segments when needed. The internal flash can be written at least 10,000 times so you cannot swap segments too often.

To do this you need to 1) write a bootloader that can load segments from the external flash, 2) partition your sketch into segments, 3) compile and link them to the same address space in program memory, 4) write the segments to the external flash memory.

Extra is handling segment to segment calls as special care is needed by the loader.

An even more elaborate scheme is to allow multiple modules and swap them depending on the execution path (e.g. module to module calls). Segments would be built up of modules, and modules would be reusable between segments. What modules are in memory would depend on some "statistics". This is basically what the instruction cache does in modern processors.

Typical segments could be application level sub-functions such as printing, uploading measurements, etc. Typically functions that are not used very frequently, and where the "background" application is stopped, e.g. data collect.


body:
I am a bit new to both Arduino and Python. My aim is to send commands to Arduino to run a stepper motor. I need to send an array containing the parameters. After consulting many earlier posts like:

<https://stackoverflow.com/questions/27639605/send-a-list-of-data-from-python-to-arduino-using-pyserial>

<https://arduino.stackexchange.com/questions/9627/send-multiple-int-values-from-python-to-arduino-using-pyserial>

I wrote my Arduino code:

    long  incoming[3];

    void setup() {
      pinMode(13, OUTPUT);
      Serial.begin(9600);
      Serial.println("Ready");
    }

    void loop() {
      if(Serial.available()) {
        for (int i = 0; i < 3; i++) {
          incoming[i] = Serial.read();
        }
        Serial.println(incoming[0]);
        Serial.println(incoming[0]);
        Serial.println(incoming[2]);
      }
    }

And the Python(2.7) code:

    from time import sleep
    import serial
    import struct
    ser = serial.Serial('COM6', 9600)

    while True:
         ser.write(struct.pack('>iii',2000,10,220))
         print ser.readline()
         sleep(.5)

Now coming to the problem:

 1. The values printed on the Python shell are completely wrong, including negative values.
 2. If I use >BBB instead of >iii, I am getting the correct result, but I can't go beyond 255, the integer limit. There is a small catch here also, the initial two sets are giving minus values and then it becomes alright.
 3. Further, is there any way to interrupt a running void loop?

Any help is deeply appreciated.

title: Arduino Serial Communication with Python: sending an array

Answers: 2

body:
_If I use >BBB instead of >iii..._ That's because "B" is a byte. So you end up sending 3 bytes:

    struct.pack("BBB", 1, 2, 3)
    \x01\x02\x03

 "i" is an int and has a size of 4, so you send 4*3 = 12 bytes:

    struct.pack("iii", 1, 2, 3)
    \x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00

`Serial.read()` reads 1 byte at a time, so you need to read 4 bytes for each value.

--------------
Here's a function to read a 32-bit int. The drawbacks of this method are that a) it will block until 4 bytes have been read. And b) there's no way to tell if some data has been lost. There are more robust ways to send data with Start-of-Message, End-of-Message, and Check-sum chars. Also, the function assumes the data is sent with the LSB first. But I'll just put this here as an example.

    // Helper macro to merge 4 bytes
    #define TO_INT32(a,b,c,d) (((d)<<24)|((c)<<16)|((b)<<8)|(a))
    int32_t read_int()
    {
      uint32_t result[4];
      for (int i = 0; i < 4; i++) {
        // Wait for data at the port
        while (!Serial.available());
        result[i] = Serial.read();
      }
      return TO_INT32(result[0], result[1], result[2], result[3]);
    }

body:
You can much more easily send an array between Python and Arduino using the inter-compatible libraries [SerialTransfer.h][1] and [pySerialTransfer][2]. Using libraries like this ensures reliable and robust communication between Python and your Arduino.

SerialTransfer.h is installable via the Arduino IDE's Libraries Manager and comes with many examples. The package pySerialTransfer is pip-installable.

  [1]: https://github.com/PowerBroker2/SerialTransfer
  [2]: https://github.com/PowerBroker2/pySerialTransfer


body:
I just started working on a project involving bluno beetle ble. For now, i'm sending the data from beetle to a android app i made.

But, for a fail safe mechanism in case the mobile is not in range or has disconnected from the device, i want to add a SD card reader to the device so i can save the data.

Is it really possible to add SD card reader to beetle ble? If yes, can someone provide any hint on what connections need to be made?

Thanks

title: Beetle ble with SD card reader

Answers: 1

body:
Eventually I got it working. The connections that i made are as follows:

 - SDA pin on beetle -> SDA pin on SD card module
 - SCL pin on beetle -> SCL pin on SD card module
 - GND pin on beetle -> GND pin on SD card module
 - VCC pin on beetle -> VIN pin on SD card module

Then upload the sample code present on arduino IDE, or you can find it here as well: https://www.arduino.cc/en/Tutorial/ReadWrite

There we go!

EDIT: The soldering is tricky for bluno beetle. Detailed instructions can be found [here][1] :

  [1]: http://www.instructables.com/id/Bluno-beetle-breadboard-breakout/


body:
I want to create a file and read it form sd card by arduino. I have used sd card module. I have used this following code. In serial monitor it says "SD card is ready to use." But it can't read or write files. I have formatted the card in FAT32 format.

My code is :

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

    int CS_PIN = 10;

    File file;

    void setup()
    {

      Serial.begin(9600);

      initializeSD();
      createFile("test.txt");
      writeToFile("This is sample text!");
      closeFile();

      openFile("test.txt");
      Serial.println(readLine());
      Serial.println(readLine());
      closeFile();
    }
    void loop()
    {
    }

    void initializeSD()
    {
      Serial.println("Initializing SD card...");
      pinMode(CS_PIN, OUTPUT);

      if (SD.begin())
      {
        Serial.println("SD card is ready to use.");
      } else
      {
        Serial.println("SD card initialization failed");
        return;
      }
    }

    int createFile(char filename[])
    {
      file = SD.open(filename, FILE_WRITE);

      if (file)
      {
        Serial.println("File created successfully.");
        return 1;
      } else
      {
        Serial.println("Error while creating file.");
        return 0;
      }
    }

    int writeToFile(char text[])
    {
      if (file)
      {
        file.println(text);
        Serial.println("Writing to file: ");
        Serial.println(text);
        return 1;
      } else
      {
        Serial.println("Couldn't write to file");
        return 0;
      }
    }

    void closeFile()
    {
      if (file)
      {
        file.close();
        Serial.println("File closed");
      }
    }

    int openFile(char filename[])
    {
      file = SD.open(filename);
      if (file)
      {
        Serial.println("File opened with success!");
        return 1;
      } else
      {
        Serial.println("Error opening file...");
        return 0;
      }
    }

    String readLine()
    {
      String received = "";
      char ch;
      while (file.available())
      {
        ch = file.read();
        if (ch == '\n')
        {
          return String(received);
        }
        else
        {
          received += ch;
        }
      }
      return "";
    }

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

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

title: Error while creating file on sd card

Answers: 0


body:
I'm trying to have an ESP8266 ESP-12 to serve as Access Point and Station at the same time, delivering the same webpage in both cases.
This is what I have:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>
    #include <EEPROM.h>
    #include <DNSServer.h>
    #include <ESP.h>

    const byte DNS_PORT = 53;
    DNSServer dnsServer;

    MDNSResponder mdns;
    ESP8266WebServer server(80);

    String ssid = "";
    String password = "";
    String webPage = "";

    void setup(void){

      IPAddress Ip(192, 168, 1, 1);
      IPAddress NMask(255, 255, 255, 0);
      WiFi.softAPConfig(Ip, Ip, NMask);
      WiFi.softAP(conf_ssid.c_str());
      WiFi.mode(WIFI_AP_STA);
      Serial.begin(115200);
      delay(1000);
      Serial.println("");
      Serial.println("Soft AP Started");
      Serial.println("");

      /* Setup the DNS server redirecting all the domains to the Ip */
      dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
      dnsServer.start(DNS_PORT, "www.example.com", Ip);

      //connectToWifi();
      getCredentials(); //Reads Home WiFi credentials from the EEPROM
      if (ssid != "" and password != ""){
        WiFi.begin(ssid.c_str(), password.c_str());
        while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.print(".");
        }
        WiFi.mode(WIFI_AP_STA);
      }
      server.begin();

      // When no password is present
      if ((ssid == "" and password == "") or (ssid == "Error")){
        // ****** MAIN PAGE ******
        server.on("/", [](){ /* HANDLES CREDENTIAL INPUT */   });
        server.begin();
      }
      else // If we have ssid and password -- check if we have connection
      {
        webPage += "
Main Webpage
";
        Serial.println("");
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());
        server.begin();
        //if (mdns.begin("esp8266", WiFi.localIP())) {
         // Serial.println("MDNS responder started");
        //}

        server.on("/", [](){
          server.send(200, "text/html", webPage);
        });
        Serial.println("HTTP server started");
      }
    }

    void loop(void){
      dnsServer.processNextRequest();
      server.handleClient();
    }

Basically, it reads the credentials from the EEPROM, if there is no credential, a WiFi configuration page is displayed, otherwise it also connects to the WiFi serving the Main Webpage to both AP and Station.

The issue is that, even though I can see the AP and a ping from my PC to the WiFi Station's Ip works, I can only access the webpage if I'm connected via AP, not via Station.
Any thoughts?

Many thanks.

title: ESP8266 - AP+STA mode not working properly

Answers: 0


body:
I am doing a project in which three IR sensors are used for getting three fingers's gesture to control the movements (left, right, forward, backward) of two motors.

The threshold value of IR sensor output is 450 mV for getting  signal to be passed.

I am not understanding how to design different conditions for different movements of motors

    int firstanalogPin = 1;     // Infrared Sensor (Right lead) connected to analog pin 1

    int val1 = 0;           // variable to store the value read

    int enablePin = 1;
    int LeftMotorForward = 10; // Pin 10 has Left Motor connected on Arduino boards.
    int LeftMotorReverse = 9; // Pin 9 has Left Motor connected on Arduino boards.

    int RightMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
    int RightMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards

    void setup()
    {
        pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
        pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
        pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
        pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
        Serial.begin(9600);          //  setup serial
    }

    void loop()
    {
        val1 = analogRead(firstanalogPin);    // read the input pin
        Serial.println(val1);                           // debug value

        if (val1 >700) // forward
            digitalWrite(LeftMotorForward, HIGH);
        else
            digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor ON
        if (val1 >700)
            digitalWrite(RightMotorForward, HIGH);// turn the Right Motor ON
        else
            digitalWrite(RightMotorForward, LOW);// turn the Right Motor ON
    }

title: Low cost IR sensor based finger gesture recognition controlled wheelchair

Answers: 1

body:
What is it that you have a problem with?  You have made the motors move forward.  So if you want just 3 different exclusive motions Forward, Left, Right.

What you could do is have 1 finger control the direction, 1 finger control left and 1 control right.

       OFF       ON
    F1 Forwards  Backward
    F2 Left Off  Left On
    F3 Right Off Right On

So to go straight forwards F2 & F3 have to be greater than 700.

To turn left F3 > 700 && F2 < 700  (Right motor on will make the chair turn left)

To reverse then you need F1 > 700.

etc.

Ensure that the conditions are if/else ifs otherwise its going to get messy.


body:
I have a **byte** variable CardNumberByte with a value of E8 if i print out as HEX:

    Serial.println(CardNumberByte, HEX)

which returns E8.

What I would like to do is to "append 0x as prefix" so that it is equivalent to

    Char CardNumberByte=0xE8;

how should i concatenate 0x to CardNumberByte?

[here][1] is the reason i need to do so.

Thanks

  [1]: https://arduino.stackexchange.com/questions/39861/how-to-convert-an-hex-string-to-an-array-of-bytes

title: add 0x to a byte

Answers: 3

body:
The answer to the question you asked is:

    Serial.print("0x");
    Serial.println(CardNumberByte, HEX);

But what you want to do according to the comment you posted is *parse* `"E8"` to give you `0xE8`.

    int parseHex(char* input){
        int result = 0;
        while(input && *input){
            if(*input >= '0' && *input <= '9'){
                result <<= 4;
                result+= *input - '0';
            }
            if(*input >= 'a' && *input <= 'f'){
                result <<= 4;
                result+= *input - 'a'+10;
            }
            if(*input >= 'A' && *input <= 'F'){
                result <<= 4;
                result+= *input - 'A'+10;
            }
            input++;
        }
        return result;
    }

body:
Here you have:

      char buffer[20];
      snprintf(buffer, sizeof(buffer), "0x%X", 1234);
      Serial.println(buffer);

You have to study the classic C print functions.

body:
I've looked at you question and the question you linked two and I've tried to join the dots to give you an answer, so I might be well off the mark, but...

I think you might have misunderstood what `0x28` means.

0x?? means that the ?? represent a hexadecimal number rather than a decimal number.

So 10 (Ten) in decimal is the same as 0x0A in hex or B00001010 or in binary or even 012 in octal.  (See https://www.arduino.cc/en/Reference/IntegerConstants for more details)

So you want to have some code that says:

    char Address = 0x28;

This is assigning the hexadecimal value 28 to the variable `Address`.  You could also write:

    char Address = 40;

In this case you are assigning the value decimal 40 (which is hex 28) to the variable.  If you want to write strange code that is misleading you could write:

    char Address = '(';  // ( is ASCII character 0x28 or 40 - Don't do it like this!

One other important thing here is that the `char` type in this case is not being used as type that holds a printable character, its being used as a signed 8 bit number.


body:
I have an arduino mini with an ultrasonic sensor conected to the pins 2 and 3, and a RGB LED connected to the 4,5, and 6, I want to include a wake up and sleep functionality that wakes up when receive a high signal in another pin as 7.

I have seen that normaly the pins for that are 2 and 3, as in the arduino web: [Arduino sleep web][1]

But can it be done with another pin?

  [1]: http://playground.arduino.cc/Learning/ArduinoSleepCode

title: waking up arduino mini with a external signal

Answers: 2

body:
Arduino Mini has only two interrupt capable pins: 2 and 3. You have to move your sensor to other pin.

From the AtMega328p datasheet:

> If a level triggered interrupt is used for wake-up from Power-down,
> the required level must be held long enough for the MCU to complete
> the wake-up to trigger the level interrupt. If the level disappears
> before the end of the Start-up Time, the MCU will still wake up, but
> no interrupt will be generated. The start-up time is defined by the
> SUT and CKSEL Fuses.

body:
As well as the normal external interrupts INT0 and INT1 you can also wake the chip through a variety of other interrupts. One of those is the *pin change* interrupt.

In the datasheet is a table of what is available in the different sleep modes, and what can wake you from that sleep mode. I have compressed the table to remove a lot of the stuff you don't care about at the moment and just show the "wake-up sources":

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

As you can see both INT and PCINT can wake from all modes (along with TWI [Wire.h] slave mode address matching).

The note (3) on the table just says that for INT0 and INT1 it must be a LOW level interrupt, not a RISING or FALLING. No mention is made of the type of interrupt for PCINT.

So yes, since pin 7 has PCINT facilities (all pins on the ATMega328P have PCINT) you can configure that as a wake-up source and wake the MCU using pin 7.

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


body:
I want to make a servo change its angle using my mouse. When I move mouse horizontally the servo should change its angle correspondingly.
This is the sketch I wrote, unfortunately the servo doesn't move one bit. HELP.

Processing Code:

    import processing.serial.*;
    Serial port;
    void setup() {
      size(256, 150);
      println("Available serial ports:");
      // if using Processing 2.1 or later, use Serial.printArray()
      println(Serial.list());
      port = new Serial(this, Serial.list()[1], 9600);
    }

    void draw() {
      // draw a gradient from black to white
      for (int i = 0; i < 256; i++) {
        stroke(i);
        line(i, 0, i, height);
      }
      // write the current X-position of the mouse to the serial port as
      // a single byte
      port.write(mouseX);
      println(mouseX);
    }

Arduino Code:

    #include <Servo.h>
    Servo myservo;
    void setup() {
      // initialize the serial communication:
      Serial.begin(9600);
      // initialize the servo:
      myservo.attach(10);
    }
    void loop() {
      byte pos;
      // check if data has been sent from the computer:
      if (Serial.available()) {
        // read the most recent byte (which will be from 0 to 255):
        pos = Serial.read();
        // set the angle of the servo:
        myservo.write(map(pos, 0, 255, 0, 180));
      }
    }

title: Interface Processing with Arduino to operate a servo by MouseX

Answers: 1

body:
When you try and solve a problem you want to focus on just one part at a time.  If I have understood what you are doing correctly then you are trying to:

 1. Get a computer to talk to an Arduino over serial
 2. Get an Arduino to position a servo
 3. Get an Arduino to decode information sent by the computer
 4. Get the computer to code the information
 5. Get the computer to draw graphics.

You can try and ice a cake, feed a baby, talk on you mobile and drive a truck all at the same time, it doesn't mean its a good idea.  When you crash what was the cause?  You haven't got a clue, you were too busy trying to do all that not analyse what is happening at the same time.

So, what I'm trying to say is break it down.  Normally with motors the problem is related to power, people assume that the Arduino can provide enough power for a servo, that's not always the case.

I would:

 1. Write a program that sets the servo to 10 hard coded positions.
 2. Write a program that sets the servo to the position manually entered on the command line.
 3. Write a program that draws the gradient, interprets the user entry and writes the command to be sent to the Arduino to the command line.
 4. Write a program that runs on the Arduino and echoes what it receives over the serial line to some "other output mechanism"  (Connecting the computer via SoftwareSerial might be a good idea).

And once they are all working as you expect connect them all together and it will all magically work :)

(Sorry if I'm teaching you to suck eggs, if you have already done all this ignore me)


body:
I am doing a prototype using ATmega8L-8PU to detect temperature and control a relay and buzzer, but the schematic seems not work, therefore I do a simple test to verify the AVR's pins are working perfectly or not.

I using the example sketch - Blink to control Digital-13 to let LED blink. It is work.

Then I do a second sketch to test all pins (Due to leak of LED, I test first 8 pins.) It failed. Second Sketch is quite simple and strict forward: blink D0-D7 LED one by one.

    char i, j, pcnt = 1;

    char startDigitalPin = 0;
    char maxDigitalPin = 7;

    void setup()
    {
     digitalWrite(13, HIGH);
     delay(100);
     digitalWrite(13, LOW);
     delay(100);

     digitalWrite(13, HIGH);
     delay(100);
     digitalWrite(13, LOW);
     delay(100);

     digitalWrite(13, HIGH);
     delay(100);
     digitalWrite(13, LOW);
     delay(100);

     // put your setup code here, to run once:
     for(i=startDigitalPin; i<=maxDigitalPin; i++) {
      pinMode(i, OUTPUT);
      digitalWrite(i, LOW);
     }
    }

    void loop()
    {
     // put your main code here, to run repeatedly:
     digitalWrite(13, HIGH);
     delay(1000);
     digitalWrite(13, LOW);
     delay(1000);

     digitalWrite(13, HIGH);
     delay(1000);
     digitalWrite(13, LOW);
     delay(1000);

     digitalWrite(13, HIGH);
     delay(1000);
     digitalWrite(13, LOW);
     delay(1000);

     for(i=startDigitalPin; i<=maxDigitalPin; i++) {
      for(j=i; j<=maxDigitalPin; j++) {
       digitalWrite(j, HIGH);
       delay(100 * pcnt);
       digitalWrite(j, LOW);
       delay(100 * pcnt);
      }

      digitalWrite(i, HIGH);
      delay(200 * pcnt);
     }

     pcnt++;

     if(pcnt > 10) {
      pcnt = 1;
      delay(8000);
     }
    }

Question:

 1. Why I using Blink example sketch, D13 is work fine, the LED light on with normal bright.
 2. Why second sketch, the D13 LED super dark, but it light on.

Check it out these 2 videos in youtube.
https://www.youtube.com/watch?v=sknNPxqg5zc
https://www.youtube.com/watch?v=KWsdP3egsvY

I have burn a bootloader to [ATmega8L-8PU][2] ([Summary Datasheet][3]) using Arduino IDE 1.6.5 with [MiniCore][4], Config: ATmega8 External 8MHz.

Parts in my bearboard using:

 1. ATmega8L-8PU
 2. 2 x 22pf
 3. 1 x 100nf
 4. 1 x 8MHx crystal
 5. 9 x LED with 330Ohm resistor

  [1]: https://gist.github.com/allenchak/4f7ca448da72c1cd762b83dde1af26aa
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2486-8-bit-AVR-microcontroller-ATmega8_L_datasheet.pdf
  [3]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2486-8-bit-AVR-microcontroller-ATmega8_L_summary.pdf
  [4]: https://github.com/MCUdude/MiniCore

title: ATmega8L power issue

Answers: 1

body:
I tested your sketch after adding `pinMode(13, OUTPUT)` in the setup, and it works as you intended.

But, as you don't post your schematic, I was only able to chech on-board LED blinking.

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

      for (int i=0; i < 3; i++) {
       digitalWrite(13, HIGH);
       delay(100);
       digitalWrite(13, LOW);
       delay(100);
      }

     // put your setup code here, to run once:
     for(i=startDigitalPin; i<=maxDigitalPin; i++) {
      pinMode(i, OUTPUT);
           digitalWrite(i, LOW);
     }
    }

I also reduce your code using a `for` loop.


body:
Arduino Pro Mini commonly comes in two packages, 5V 16MHz and 3.3V 8MHz.

 1. The only difference between those two boards are regulator and clock crystal, right?
 2. What happens if I supply 2V to VCC pin of 5V 16MHz board?
 3. What happens if I supply 2V to RAW pin of 5V 16MHz board?
 4. What happens if I supply 5V to VCC pin of 3.3V 8MHz board?
 5. What happens if I supply 5V to RAW pin of 3.3V 8MHz board?

I read from some websites stating that Arduino Pro Mini power consumption can be reduced by removing regulator.

 6. Does removing regulator cause VCC pin = RAW pin?

[Jean][1] created a custom board for Arduino Pro Mini rated at 1MHz 1.8V.

 7. Which pin should I supply voltage after changing fuse setting? (Jean changed the fuse setting but I am not sure where to connect the supply voltage of 1.8V)
 8. Related to question 7, is there a need to remove regulator to supply 1.8V?
 9. Can I supply higher voltage (3V) on board with 1.8V fuse setting?

Reason for question/ Confusion

I want to power Arduino Pro Mini using 3V coin cell. Battery voltage decreases after usage to around 2V. I am thinking of simply inserting 3V coin cell to Arduino with 1.8V setting. But regulator may hinder the operation. That is why I am confused. Sites I visited states the possibility of using lower voltage after changing fuse setting but did not mention where to connect and whether regulator need to be removed.

Furthermore, ATmega328p datasheet states the VCC range is 1.8V to 5.5V. If that is so, why not just plug those voltage to VCC pin of Arduino Pro Mini instead of specifically 5V or 3.3V. Question 1-5 should clear my confusion on this.

  [1]: https://www.iot-experiments.com/arduino-pro-mini-1mhz-in-arduino-ide/

title: Powering Arduino Pro Mini with different voltage, fuse setting

Answers: 1

body:
Read the datasheet once more. A certain voltage is needed for a certain clock frequency. There is a graph somewhere.

Since the Atmega328p is able to run up to 5.5V for VCC, that 5.5V is for every clock frequency.

Using 2V for VCC is not enough to run it at 16MHz. According to the datasheet even 3.3V is not enough. But 3.3V and 16MHz will work (it is outside the specifications though).

The RAW pin is the voltage before the voltage regulator, right ? Depending on the voltage regulator you can apply a large range of voltage.
See the [pinout][1].

When you remove the voltage regulator, the RAW pin is open. Sometimes I remove the voltage regulator and use 3 AA batteries and feed the 4.5V into the VCC (or 5V pin) of a 8MHz ATmega328p board.

1. Yes. The bootloader and sketch have to know the clock frequency. A sketch compiled for 8MHz is for a 8MHz Arduino board and a sketch compiled for 16MHz is for a 16MHz Arduino board.
2. 2V is too low. 3.3V should work.
3. 2V is too low. 3.3V depends on the voltage regulator.
4. No problem. The voltage regulator gets a reverse voltage.
5. No problem.
6. No. See the schematic.
7. To VCC.
8. Not a "must", but it is highly preferred to remove the voltage regulator, so no current is leaking towards the voltage regulator which gets a reverse voltage.
9. Yes. The fuses are to lower/disable the BOD, so a higher voltage is no problem.

This is the best tutorial about the power of the Atmega328p : [Nick Gammon about Power][2]

**ADDED**

I forgot to mention to remove the led as well.
This is a [Pro Mini with a coin cell][3].

Lowering the clock speed will make it run at lower voltages, but that will not always reduce the used energy. Doing a calculation at a slow speed takes more time than the same calculation at high speed (and going into sleep mode after that).

**ADDED 2**

When a low voltage is supplied (for example 2V to a 5V 16MHz Arduino board), the voltage regulator will not work. How much current/voltage is still passed on depends on the voltage regulator. With the BOD disabled, and the microcontroller runs below its required voltage, anything weird can happen. Parts of the chip will work and parts will not. That is why the BOD was invented in the first place (to reset the chip and avoid weird things to happen). I think it is very unlikely that the microcontroller will get damaged with a (too) low voltage.

  [1]: http://www.pighixxx.com/test/2016/07/pro-mini-pinout/
  [2]: https://www.gammon.com.au/power
  [3]: http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/


body:
I bought around 2 years ago the Spectrum Analyzer Shield from Sparkfun, but I never had the time to do something with it. Recently I found the time to start a project to build a graphical equalizer. For that I use the Spectrum Analyzer Shield to split the left and right audio channel into 7 different bands. After I finished to build my first LED-Matrix panel and tested it out with the Spectrum Analyzer Shield I thought that everything works as it should. I made than the second LED-Matrix panel and tested everything again. Well, the result was odd. I noticed that the order of the bands inside of my arrays are switching around between every restart of my Arduino. Here are two example outputs. I played a 64 Hertz tone and expected to see an increase for the right and left channel for the first band.

    Band0 R:70 ,L: 76 | Band1 R:92 ,L: 81 | Band2 R:548 ,L: 83 | Band3 R:108 ,L: 575 | Band4 R:76 ,L: 108 | Band5 R:64 ,L: 82 | Band6 R:63 ,L: 83 |
    Band0 R:67 ,L: 78 | Band1 R:87 ,L: 83 | Band2 R:552 ,L: 82 | Band3 R:108 ,L: 575 | Band4 R:80 ,L: 109 | Band5 R:68 ,L: 83 | Band6 R:63 ,L: 78 |
    Band0 R:77 ,L: 75 | Band1 R:88 ,L: 78 | Band2 R:546 ,L: 83 | Band3 R:105 ,L: 575 | Band4 R:79 ,L: 109 | Band5 R:61 ,L: 79 | Band6 R:59 ,L: 77 |
    Band0 R:73 ,L: 74 | Band1 R:92 ,L: 85 | Band2 R:546 ,L: 84 | Band3 R:113 ,L: 572 | Band4 R:78 ,L: 105 | Band5 R:58 ,L: 74 | Band6 R:65 ,L: 78 |
    Band0 R:71 ,L: 77 | Band1 R:92 ,L: 82 | Band2 R:550 ,L: 84 | Band3 R:107 ,L: 573 | Band4 R:76 ,L: 107 | Band5 R:59 ,L: 76 | Band6 R:59 ,L: 79 |

After restart of the arduino (pressed 5 sec the reset button)

    Band0 R:71 ,L: 576 | Band1 R:86 ,L: 106 | Band2 R:545 ,L: 87 | Band3 R:107 ,L: 82 | Band4 R:76 ,L: 78 | Band5 R:55 ,L: 80 | Band6 R:61 ,L: 79 |
    Band0 R:71 ,L: 575 | Band1 R:83 ,L: 105 | Band2 R:549 ,L: 80 | Band3 R:109 ,L: 87 | Band4 R:75 ,L: 79 | Band5 R:55 ,L: 84 | Band6 R:64 ,L: 78 |
    Band0 R:69 ,L: 575 | Band1 R:88 ,L: 103 | Band2 R:546 ,L: 79 | Band3 R:109 ,L: 82 | Band4 R:73 ,L: 79 | Band5 R:63 ,L: 78 | Band6 R:62 ,L: 84 |
    Band0 R:70 ,L: 575 | Band1 R:87 ,L: 103 | Band2 R:547 ,L: 84 | Band3 R:106 ,L: 82 | Band4 R:76 ,L: 78 | Band5 R:61 ,L: 80 | Band6 R:61 ,L: 90 |
    Band0 R:71 ,L: 574 | Band1 R:83 ,L: 106 | Band2 R:550 ,L: 79 | Band3 R:109 ,L: 84 | Band4 R:77 ,L: 77 | Band5 R:57 ,L: 85 | Band6 R:60 ,L: 81 |
    Band0 R:64 ,L: 576 | Band1 R:92 ,L: 109 | Band2 R:549 ,L: 80 | Band3 R:105 ,L: 80 | Band4 R:75 ,L: 72 | Band5 R:56 ,L: 76 | Band6 R:60 ,L: 80 |

I experienced the same issue with the source code from Sparkfun: https://github.com/sparkfun/Spectrum_Shield/blob/HW_1.6_FW_1.1/Firmware/SparkFun_Spectrum_Demo/SparkFun_Spectrum_Demo.ino

I modified this code only slightly to log everything.

    void Read_Frequencies(){
      //Read frequencies for each band
      for (freq_amp = 0; freq_amp<7; freq_amp++)
      {
        Frequencies_One[freq_amp] = analogRead(DC_One);
        Frequencies_Two[freq_amp] = analogRead(DC_Two);
        digitalWrite(STROBE, HIGH);
        digitalWrite(STROBE, LOW);

        Serial.print("Band");
        Serial.print(freq_amp);
        Serial.print(" R:");
        Serial.print(Frequencies_One[freq_amp]);
        Serial.print(" ,L: ");
        Serial.print(Frequencies_Two[freq_amp]);
        Serial.print(" | ");
      }
      Serial.println("");
    }

Hopefully I'm doing something fundamental wrong, if not that would mean I have to buy a new Shield :/

title: Sparkfun Spectrum Analyzer: Problems with frequency bands

Answers: 0


body: I have an Arduino Uno. It has a 3.3v pin that I would like to use to power another module that requires 3.3v, and nothing more. If I power my Arduino Uno with a 9 volt battery, will this pin output 3.3v, or will it give more than that?

title: Can I use the Arduino Uno's 3.3v pin while powered by a 9 volt battery?

Answers: 1

body: The 3.3v is regulated and will always output 3.3v if the device is powered on.


body:
How can I create a function that can control a DC motor's speed and direction?

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

    configMotor(int speed, direction){
       pwmVal = speed;

       //need help with code for picking direction
    }

    //move FORWARD
    void moveForward(){
      analogWrite(pwn, pwmVal);
      delay(sDelay);
      digitalWrite(ina, HIGH);
      digitalWrite(inb, LOW);
    }

    //move BACKWARD
    void moveBackward(){
      analogWrite(pwn, pwmVal);
      delay(sDelay);
      digitalWrite(ina, LOW);
      digitalWrite(inb, HIGH);
    }

I don't know what to write in the code for `configMotor` function so that it can choose going forward or backward.

title: Writing a new function: configMotor(speed, direction)

Answers: 1

body:
All you need to do is pass a parameter to config that says forward or backwards (was direction).
This parameter then sets the values of that the pins INA/B will be set to, because they are opposite.

Does that make sense?  If not add a comment with you question and I'll try and clarify.

    int inaDirection = LOW;
    int inbDirection = LOW;

    void configMotor( int speed, bool forwards = true)
    {
       pwmVal = speed;
       inaDirection = forwards?HIGH:LOW;   // ? and : are the same as an if statement, just more compact.
       inbDirection = forwards?LOW:HIGH;
    }

    // move no need for forward and reverse anymore
    void move()
    {
        analogWrite(pwn, pwmVal);
        delay(sDelay);
        digitalWrite(ina, inaDirection);
        digitalWrite(inb, inbDirection);
    }


body:
I have a mono jack audio act as analog input for arduino UNO. The microphone outputs voltage that varies in terms of `amplitude` (volume) and `frequency`. In order to get the high sampling rate, I use prescaler 16 and set high baudrate for serial communication to print the value. I save the analog read from that jack audio to `buffer` array with maximum value is 256 (8-bit). This is my code (I modify from the Nick Gammon's blog about ADC [here][1]) :

    const byte adcPin = 0;  // A0

    const int MAX_RESULTS = 256;

    volatile int results [MAX_RESULTS];
    volatile int resultNumber;

    void setup ()
      {
      Serial.begin (230400);
      Serial.println ();

      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;
      TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
      TIMSK1 = bit (OCIE1B);
      OCR1A = 39;
      OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
      ADCSRA |= bit (ADPS2);  // Prescaler of 16
    //  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
      ADMUX = bit (REFS0) | (adcPin & 7);
      ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
      ADCSRA |= bit (ADATE);   // turn on automatic triggering

    }

    // ADC complete ISR
    ISR (ADC_vect)
    {
        results[resultNumber++] = ADC;
        if(resultNumber == MAX_RESULTS)
        {
          ADCSRA = 0;  // turn off ADC
        }
    }

    EMPTY_INTERRUPT (TIMER1_COMPB_vect);

    void loop () {

      while (resultNumber < MAX_RESULTS)
        { }

      for (int i = 0; i < MAX_RESULTS; i++)
      {
        Serial.println (results [i]);
      }
    }

With that code, I got a nice result of sinusoidal graph represented audio value up to 4000 Hz like this :

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

But one thing that didn't work is if I change the volume or frequency (while displaying data) of analog input (jack audio), the graph I print and display via serial plot audio **won't change**. So I had to close it and open again to see the change. The question is how can I achieve the continuous and real time reading of this ? Thank you very much.

  [1]: http://gammon.com.au/adc
  [2]: https://i.stack.imgur.com/irwJY.png

title: Arduino continuously reading ADC value using interrupt

Answers: 1

body:
reset the `resultNumber` to 0 after you have written it to serial. and turn interrupts back on

    void loop () {

      while (resultNumber < MAX_RESULTS)
        { }

      for (int i = 0; i < MAX_RESULTS; i++)
      {
        Serial.println (results [i]);
      }
      resultNumber = 0;
      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF)| bit (ADPS2) | bit (ADATE);
       // turn ADC back on
    }


body:
[![enter image description here][1]][1][![d][2]][2]

I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.

Here is the schematic:

[![enter image description here][3]][3]

Here is my code:

    #include <Servo.h>
    Servo servo1;

    int button = 2; //Assigning pin 2 for the momentary button
    int buttonval = 0; //Creating a variable for the buttons value
    int green = 12;
    int red = 13; //Assigning the green and red LED to pin 12 and pin 13
    int red = 13;
    int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
    int Open = 7;
    int Closedval = 0; //Creating two blank variables for the states of the switch
    int Openval = 0;

    void setup() {
      servo1.attach(4); //Assigning the data pin for the servo
      servo1.write(1); // Giving a starting speed to the servo
      pinMode(button, INPUT); // Setting up the input pin for the momentary button
      digitalWrite(button, HIGH); //  turn on pull up resistors
      pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
      pinMode(Open, INPUT);
      pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
      pinMode(red, OUTPUT);
      digitalWrite(Closed, HIGH);
      //Turning on pull up resistors for the two inputs from the toggle switch
      digitalWrite(Open, HIGH);
    }

    void loop() {
      Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
      Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

      if (Closedval == HIGH) {
        servo1.write(180);
        // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
      }

      if (Openval == HIGH) {
        servo1.write(86);
        // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
      }

      digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
      digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
    }

Any help would be appreciated.

  [1]: https://i.stack.imgur.com/9wbtL.jpg
  [2]: https://i.stack.imgur.com/JifOe.jpg
  [3]: https://i.stack.imgur.com/AJx1S.png

title: How do I set a continuous servo to turn on until a switch is flicked?

Answers: 2

body:
Your are not debouncing your input buttons, which means that `digitalRead(Closed)` (and Open) will be HIGH in one execution of `loop` and in the next pass, 3 millis later, it will be LOW.

The servo probably need over 50ms to complete the action (you don't said what servo are you using).

You need to wait for the action to be completed before trying to move it in another direction.

You didn't post your schematic, so may be you wired things wrong. How can we know?

Usually the first step when you find a problem is add `Serial.print` to know what is working and what not, and then correct the problem.

body:
I seem to have got this working just by doing the following code:

<!-- language: lang-cpp -->

    #include <Servo.h>
    Servo servo1;

    int green = 12;       //Assinging the green and red LED to pin 12 and pin 13
    int red = 13;

    int Closed = 8;       //Assinging the Inputs of the toggle switch to 8 and 7

    void setup()
    {
      servo1.attach(4);    //Assigning the data pin for the servo
      servo1.write(86);     // Giving a starting speed to the servo

      pinMode(Closed, INPUT);        //Setting up the inputs for the two states of the toggle switch

      pinMode(green, OUTPUT);        //Changing the pin modes to OUTPUT for the two LEDS
      pinMode(red, OUTPUT);

      digitalWrite(Closed, HIGH);    //Turning on pull up resistors for the two inputs from the toggle switch

      delay(50);
      servo1.write(65); // start the motor opening
    }

    void loop() {
      if (digitalRead(Closed) == HIGH) { //If the toggle switch is changed then turn the servo in the oppisite direction
        servo1.write(100);
        if (digitalRead(Closed) == LOW) { // If the toggle switch is changed again then turn the servo off
          servo1.write(86);
        }
      }
    }

Instead of using an external button I have had to use the reset button.


body:
I've been messing with the Adafruit Neopixel lib, and I'm trying to replace some of the delay functions with mills ( so that I don't block the serial port ). So far I have the following code;

    void loop() {
      currentMillis = millis();

      colorWipe(strip.Color(255, 0, 0), 50); // Red
      colorWipe(strip.Color(0, 255, 0), 50); // Green
      colorWipe(strip.Color(0, 0, 255), 50); // Blue
      colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
    }

    void colorWipe(uint32_t c, uint8_t wait) {
      if (currentMillis - previousMillis >= 200) {
        for(uint16_t i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, c);
          strip.show();
          //delay(wait);
          Serial.println("Light");
          previousMillis = currentMillis;
        }
       Serial.println("Done");
      }
    }

The issue I'm running into ( and I do understand this is fundamental concept in Arduino programming ) is how to run sequential functions, like the ones in loop, while still not blocking the main loop. The way this currently functions, it runs through the first colorWhipe loop and then just keeps iterating.

title: How do I call functions sequentially without using the Delay function?

Answers: 3

body:
I'm assuming you want to run each `colorWipe` for 200 ms, one after another.

You need a state machine to timing each `colorWipe`, like this:

    void loop()
    {
     static int state = 0;
     static unsigned long previousMillis = 0;
     unsigned long currentMillis = millis();

     if(currentMillis - previousMillis >= 200) {
      previousMillis = currentMillis;

      switch(state) {
      case 0 :
       colorWipe(strip.Color(255, 0, 0), 50); // Red
                state++;
       break;

      case 1 :
       colorWipe(strip.Color(0, 255, 0), 50); // Green
                state++;
       break;

      case 2 :
       colorWipe(strip.Color(0, 0, 255), 50); // Blue
                state++;
       break;

      case 3 :
       colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
       Serial.println("Done");
       state = 0;
      }
     }
    }

    void colorWipe(uint32_t c, uint8_t wait)
    {
     for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      //delay(wait);
      Serial.println("Light");
     }
    }

In each `loop` you will be waiting 200 ms before doing anything. When the times comes, you will enter the `if` with `state==0` and you will execute the first 'colorWipe'. After that, you *advance* the state by adding 1 to `state` variable.

Then you will be entering `loop` and doing nothing for another 200 ms. When that time pass, you will enter the `ìf` with state==1. Now the second `colorWipe` will be executed.

When the last colorWipe is executed, you set `state` to zero and begin again.

body:
Assuming the commented out delay in colorWipe should still happen then you need to nest the state machines:

    void loop()
    {
        static bool waiting=false;
        static int state = 0;
        static unsigned long previousMillis = 0;
        unsigned long currentMillis = millis();
        if(waiting){
            if(currentMillis - previousMillis >= 200){
                waiting = false;
            }
        }

        if(!waiting  && currentMillis - previousMillis >= 50) {
            previousMillis = currentMillis;

            switch(state) {
            case 0 :
                if(colorWipe(strip.Color(255, 0, 0))){ // Red
                    state++;
                    waiting = true;
                }
                break;

            case 1 :
                if(colorWipe(strip.Color(0, 255, 0))){ // Green
                    state++;
                    waiting = true;
                }
                break;

            case 2 :
                if(colorWipe(strip.Color(0, 0, 255))){ // Blue
                    state++;
                    waiting = true;
                }
                break;

            case 3 :
                if(colorWipe(strip.Color(0, 0, 0, 255))){ // White RGBW
                    state++;
                    state = 0;
                }
                break;
            }
        }
    }

    int wipeState = 0;
    bool colorWipe(uint32_t c)
    {

        strip.setPixelColor(wipeState , c);
        strip.show();

        Serial.println("Light");
        wipeState++;
        if(wipeState == strip.numPixels()){
            wipeState = 0;
            return true;
        }
        return false;
    }

body:
Here's an OOP solution. (It seems a lot of Arduino programmers shy away from C++ classes, but I use them all the time).

Since you don't want to block `loop()`, you need to create a function that will set the pixel (if time has expired) and return immediately. I would create a class to encapsulate the pixel strip.

The way this works is the class has a `loop()` function that needs to be called every time in the main program's `loop()` function. The class's `loop()` will either return (almost) immediately or it will update the pixel. Which will also be very quick. This allows you to do other things in the main `loop()`.

Disclaimer: I just whipped this up, there may be bugs.

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

    // A class to encapsulate the neo pixel strip.
    class color_strip {
        protected:
        Adafruit_NeoPixel pixels;
        uint32_t last_ms;
        uint32_t color;
        uint32_t duration = 0;
        int current_pixel;
        bool first_time;

        public:
        // Constructor
        color_strip(int num_pixels, int pin) {
            strip = Adafruit_NeoPixel(num_pixels, pin, NEO_GRB + NEO_KHZ800);
        }

        // Call this from setup()
        void setup() {
           strip.begin();
        }

        // Call this to start a wipe
        // param duration_ms is how long the entire wipe should take
        void wipe(RGB color, uint32_t duration_ms) {
            // Calculate how long to light each pixel
            duration = duration_ms / strip.numPixels()
            // Initialize this data for loop()
            last_ms = millis();
            first_time = true;
            this->color = strip.Color(color.red, color.green, color.blue);
            current_pixel = 0;
        }

        void loop() {
            // Is there something to do? Only if duration != 0
            if (0 != duration) {
                // Time to change pixel?
                uint32_t current_ms = millis();
                if (current_ms - last_ms >= duration || first_time) {
                    first_time = false;
                    // Finished the entire wipe?
                    if (current_pixel == strip.numPixels()) {
                        duration = 0;
                    }
                    else {
                        // Set the pixel
                        strip.setPixelColor(current_pixel++, color);
                        strip.show();
                        // Save
                        last_ms = ms;
                    }
                }
            }
        }

        // Returns true if doing a wipe, else false
        bool working() {return duration != 0;}
    };

Usage: you can create an array of colors. You then cycle through all these colors. If you want to add more colors, simply add to the array.

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

    // Helper struct to store rgb
    struct RGB {
        byte red, green, blue;
    };
    RGB all_colors[] = {
        {255, 0, 0},
        {0, 255, 0},
        {0, 0, 255},
        {0, 0, 0}
        // Add more colors here, if needed
    };
    // Need to keep track of the current color being displayed
    byte current_color = 0;
    const byte num_colors = sizeof(all_colors) / sizeof(all_colors[0]);

    // Here's the actual object
    // Change the parameters to whatever they need to be in your setup
    color_strip strip(number_of_pixels, pin_number);

    void setup()
        // Call the class setup function
        strip.setup();
    }

    void loop()
    {
        // If the strip has completed its wipe, set it to next color
        if (!strip.working()) {
            current_color = (current_color + 1) % num_colors;
            strip.wipe(all_colors[current_color], 1000);
        }
        // Call the class loop(). It will return quickly so won't block
        // the rest of the program
        strip.loop();

        // Do other stuff here...
    }


body:
I am using an Accelerometer (on the MPU6050) and connected it to the **Arduino Due**. In order to filter the signal I am using an IIR Filter with the following transfer function:

H(z) = Y(z)/X(z) = B/A

B = 0.00000376 + 0.00001127*z^(-1) + 0.00001127*z^(-2) + 0.00000376*z^(-3)

A = 1 - 2.9372*z^(-1) + 2.8763*z^(-2) - 0.9391*z^(-3)

which is an IIR 3th Order Butterworth, Cutoff Freq: 0.5Hz, Samling Freq: 100Hz. These numbers can be calculated by any IIR calculator.

Thus, then discrete equation is:

y[n] = 0.00000376*x[n] + 0.00001127*x[n-1] + 0.00001127*x[n-2] + 0.00000376*x[n-3] + 2.9372*y[n-1] - 2.8763*y[n-2] + 0.9391*y[n-3]

I first tried it on the Arduino UNO. Then I found out that decimal point **precision** (float & double) on the UNO is **only 6-7 digits**. But the therm "B" in the transfer function has for example (0.00000376) **9 digits**. I thought this is the porblem, so I switched to Arduino Due and now I am using double (instead of float) which should have **enough precision**.

It is still unstable. It is not oscillating but getting bigger. I also tried an IIR 4th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz. This one is oscillating.

However, the only IIR that seems to be stable is an IIR 3th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz.

I have no idea so far what the problem is. Could anyone help please?

title: Why is this IIR Filter unstable on the Arduino Due?

Answers: 1

body:
1. The precision of a float is about 7 **significant** digits. The
   constant term of B in your transfer function (0.00000376) has only 3
   significant digits.
2. Your transfer function has a pole at _z_ = 1. It is thus not really
   stable, but only _marginally_ stable. Any parasite DC component in
   the input will make the output drift without bounds.

It seems to me that your problem is not related to the implementation of
the filter on the Arduino, but rather to the filter design. Where did
you get that transfer function from?

**Edit**: I looked at the filter you are trying to make. It turns out it
is very sensitive to the precision of the coefficients of A(z). If you
try to add these coefficients, they _almost_ cancel out: their sum is
about 3e-5. At zero frequency, both A and B are 3e-5, and the transfer
function, which is their ratio, is 1. By rounding the coefficients to
four decimal places, you made the cancellation exact, and the transfer
function infinite.

Just write the transfer function with more decimal places in the
coefficients and it should work:

H(z) = 3.75592×10−6 (1 + 3 z−1 + 3 z−2 + z−3)
         ÷ (1 − 2.9371759 z−1 + 2.8763097 z−2 − 0.9391038 z−3)


body:
I'm trying to connect an Arduino Mega to my WAMP server's database using MySQL connector for attendance logging. But it shows "Connection failed".

What is my WAMP server's IP address?

I connect my laptop and Arduino with a router so:

- My laptop is 192.168.1.2
- My Arduino is 192.168.1.3

I think this is correct.

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

    /*
      MySQL Connector/Arduino Example: basic insert
      This example demonstrates how to issue an INSERT query to store data in a
      table. For this, we will create a special database and table for testing.
      The following are the SQL commands you will need to run in order to setup
      your database for running this sketch.

      CREATE DATABASE test_arduino;
      CREATE TABLE test_arduino.hello_arduino (
        num integer primary key auto_increment,
        message char(40),
        recorded timestamp
      );

      Here we see one database and a table with three fields; a primary key that
      is an auto_increment, a string, and a timestamp. This will demonstrate how
      to save a date and time of when the row was inserted, which can help you
      determine when data was recorded or updated.

      INSTRUCTIONS FOR USE

      1) Create the database and table as shown above.
      2) Change the address of the server to the IP address of the MySQL server
      3) Change the user and password to a valid MySQL user and password
      4) Connect a USB cable to your Arduino
      5) Select the correct board and port
      6) Compile and upload the sketch to your Arduino
      7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
      8) After the sketch has run for some time, open a mysql client and issue
         the command: "SELECT * FROM test_arduino.hello_arduino" to see the data
         recorded. Note the field values and how the database handles both the
         auto_increment and timestamp fields for us. You can clear the data with
         "DELETE FROM test_arduino.hello_arduino".

      Note: The MAC address can be anything so long as it is unique on your network.

      Created by: Dr. Charles A. Bell
    */

    #include <Ethernet.h>
    #include <MySQL_Connection.h>
    #include <MySQL_Cursor.h>

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

    IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here
    char user[] = "root"; // MySQL user login username
    char password[] = ""; // MySQL user login password

    // Sample query
    char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

    EthernetClient client;
    MySQL_Connection conn((Client *)&client);

    void setup() {
      Serial.begin(115200);
      while (!Serial); // wait for serial port to connect
      Ethernet.begin(mac_addr);
      Serial.println("Connecting...");
      if (conn.connect(server_addr, 3306, user, password)) {
        Serial.println("Connected Successfully...");
        delay(1000);
      } else
        Serial.println("Connection failed.");
    }

    void loop() {
      delay(2000);
      Serial.println("Recording data.");
      // Initiate the query class instance
      MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
      // Execute the query
      cur_mem->execute(INSERT_SQL);
      // Note: since there are no results, we do not need to read any data
      // Deleting the cursor also frees up memory used
      delete cur_mem;
    }

title: How to connect an Arduino and a WAMP server's MySQL database?

Answers: 1

body:
As gre_gor pointed out, it looks like your connecting to the wrong ip.

Change:

    IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here

To:

    IPAddress server_addr(192, 168, 1, 2); // IP of the MySQL *server* here


body:
Our project consists of an old wooden barrel, whose top lid is opened/closed with a simple linear actuator. I am a bit afraid that it might crush somebody's fingers while closing.

How could I detect trapped objects effectively?

Elevators often have light barriers, but the problem here is that the opening has a 360° border.
Force sensitive resistors seem to be an option too. However, since the border is a circle, I guess applying them would not work too well (folding issues) and look bad on a vintage barrel.

*I'm very sorry if I maybe created a duplicate here and I would like to encourage me to provide links to similar questions. I simply couldn't come up with useful search words for my problem.*

title: Physical safety: Prevent linear actuator from crushing my fingers

Answers: 1

body:
The easiest way to prevent things becoming trapped is to take reasonable steps to prevent things getting near the "danger zone", so a barrier 2 metres around the barrel would be a good start.  Probably it would be an impractical idea, but...

A physical barrier of some sort would be the best idea, because that is less likely to suffer a failure than an electronic system (well assuming it has been designed right).  If you are using an electronic system then it needs to "fail-safe", when it suffers a failure it must adopt its safe state (barrel open).

You could surround the lid with IR lights and receivers in the lip.  They would need to be spaced at a distance where an arm/finger couldn't get between the lid and lip without breaking a beam.  This solution would only work over the last few inches, because of the angle of the beams.  If all receivers had a signal the it would be safe to close.  The problem is the receivers would need to be close together to prevent transgression.

Monitoring the current drawn by the actuator and the position of the actuator might be another.  I am assuming that there is an increase in current draw when the lid actually closes, and a similar increase in draw when something is trapped.  If the lid isn't fully closed when the current increases then something is trapped.

The final way I can think of is probably the most effective.  As the barrel closes don't close it the last few inches, allow it to 'fall' as the actuator descends.  This means if there is an object in there the actuator isn't pulling the lid down and the object will hold the lid against gravity.  This would be done by having a channel in the mounting block for the actuator 'pin'/ connection point to slide up and down.

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

OK Its not an electrical solution.

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


body:
I'm trying to use Grove LED Bar with Arduino

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

> Grove – LED Bar is comprised of a 10 segment LED gauge bar and an
> MY9221 LED controlling chip. It can be used as an indicator for
> remaining battery life, voltage, water level, music volume or other
> values that require a gradient display. There are 10 LED bars in the
> LED bar graph: one red, one yellow, one light green, and seven green
> bars. Demo code is available to get you up and running quickly. It
> lights up the LEDs sequentially from red to green, so the entire bar
> graph is lit up in the end.

In the github example there are `Clock pin`, `Data pin` and `Orientation`.

    // Arduino Clock pin, Data pin, Orientation
    // Grove_LED_Bar bar(7, 6, 0);

https://github.com/Seeed-Studio/Grove_LED_Bar/blob/master/LP examples/BasicControl/BasicControl.ino

But I have no idea what are they. Where can I find the documentation for them?

  [1]: https://i.stack.imgur.com/yXUPw.gif

title: What is Clock pin and Data pin, Orientation in Grove LED bar

Answers: 2

body:
on the LED circuit board there are a few connections, notably DI and DCKI.

The DI pin is the data pint and DCKI is the clock pin.

According to the [header][1] orientation is about which way the pins are oriented red-to-green or green-to-red. It affects at which end led 1 is.

[1]: https://github.com/Seeed-Studio/Grove_LED_Bar/blob/master/Grove_LED_Bar.h

body:
**How to connect Grove to your board**

You need a Grove Expansion Board which to attach the Grove modules. The Grove Expansion Board provides the processing power, and the modules offer the input sensors and output actuators of your system. There are many Grove Expansion Board for different platform already, they include Arduino UNO, Particle Phone, BeagleBone board etc.

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

**Features**

There are intotal 16 grove connectors on the Base Shield, here we use a table to show the details.

**Specification**

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

Apart from the rich grove connectors, on the board you can also see an RST button, a green LED to indicating power status, ICSP pin, a toggle switch and four row of pinouts. There is no need to explain the RST button and LED, but you really need to know below two features that is very important for your usage.

1.Power Compatible:

Every Grove connector has four wires, one of which is the VCC. However, not every micro-controller main board needs a supply voltage of 5V, some need 3.3V. That's why we add a power toggle switch to Base Shield v2 so that you can select the suitable voltage of the micro-controller main board you are using via this switch.

For example, if you are using Arduino UNO with Base Shield v2, please turn the switch to 5v position; while using Seeeduino Arch with Base Shield v2, please turn the switch to 3.3v.

2.Board Compatible:

The pinout of Base Shield V2 is the same as Arduino Uno R3, however Arduino Uno is not the board one that the Base Shield V2 is compatible with, here we listed the boards that we have confirmed that can be used with Base Shield V2.

    Arduino Uno

    Seeeduino V4.2

    Arduino Mega / Seeeduino Mega

    Seeduino LoraWan

    Arduino Leonardo / Seeeduino Lite

    Arduino 101

    Arduino Due

    Intel Edison

    Linkit One

  [1]: https://i.stack.imgur.com/R4UVX.jpg
  [2]: https://i.stack.imgur.com/bAh8k.png


body:
Sometimes the servo moves unnecessarily without moisture sensor giving out any readings.

Another problem is that the servo moves very slowly. Is there a way to counter this problem?

<!-- language: lang-cpp -->

    const int VAL_PROBE = 0; // Analog pin 0
    const int MOISTURE_LEVEL = 250; // the value after the LED goes ON
    #include <Servo.h>
    Servo myservo;

    void setup() {
      myservo.attach(9);
      Serial.begin(9600);
    }

    void Servo(int state) {
      digitalWrite(13, state);
    }

    void loop() {
      int moisture = analogRead(VAL_PROBE);

      Serial.println(moisture);

      if(moisture > MOISTURE_LEVEL) {
        myservo.write(90);
      } else {
        myservo.write(0);
      }
      delay(1);
    }

title: This is a flood sensor. Moisture sensor and servo working together but it shows different errors

Answers: 0


body:
Finally got some time to play with my Arduino. I downloaded the Arduino editor and wrote a quick sketch which worked fine.

I then downloaded the Visual Studio extension from  VisuaMicro. I configured it to point towards my Arduino directory, which in my case is : C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt

I created a new Arduino project and copied the same sketch it. When I try to build it I get errors as below:

    Compiling debug version of 'Sketch1' for 'Arduino/Genuino Uno'
    Build Folder:
    file:///C:/Users/bbbsb/AppData/Local/Temp/VMBuilds/Sketch1/uno/Debug
    Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE
    1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL
    0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL
    2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART
    5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL
    7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE
    9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA
    11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE_HARDWARESERIAL1
    13;VM_DEBUGGER_TYPE_HARDWARESERIAL2 14;VM_DEBUGGER_TYPE_HARDWARESERIAL3
    15;VM_DEBUGGER_TYPE_NET_UDP 16;VM_DEBUGGER_TYPE_USBAPI
    17;VM_DEBUGGER_TYPE_SERIALUSB 18;VM_DEBUGGER_TYPE
    VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
    Architecture Tools:
    file:///C:/Program Files/WindowsApps/
    ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/
    Api: 1.1706.25-9.061
    Sketch Book: file:///C:/Users/bbbsb/Documents/Arduino
    Sketch Include Paths
    Core Include Paths
    Include Path     file:///C:/Program Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/cores/arduino
    Include Path     file:///C:/Program Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/variants/standard
    Searching for libraries ...
    "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
    DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
    DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
    DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
    DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11  -
    DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
    DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
    DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
    DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
    DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
    DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805  -
    DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
    Access is denied
 Preprocess: "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
    DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
    DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
    DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
    DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11 -
    DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
    DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
    DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
    DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
    DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
    DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
    DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805 -
    DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
    Object reference not set to an instance of an object

 An error was encountered during the 'Deep Search' library discovery process.
Debug build failed for project 'Sketch1'

I've obviously not setup something correctly but cnnot work out what?
Any ideas?

title: Visual Studio for Arduino - Deep Search Issue

Answers: 2

body: If I remember well, you have to "import" the libraries for your project from within Visual Micro.

body: I had the same problem and just tried it as per1234 suggested: installed the full windows version (not the windows app version), configured the VS extension accordingly and now it builds (same code).


body:
I would like to create a tachometer with the light sensor OPB704WZ.

I followed this schema [https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/][2] on a bread board (for now), and tried to measure the voltage difference on the signal pin (green on the schema).

[![Light sensor][1]][1]

Problem is, I don't see a clear difference between a white surface and a black one; It does change if I put the sensor closer or further away, but that's about all I can see.

Is there something else I need to add to my wiring to make the difference between high and low depending on the luminosity more obvious? I know others have been able to use this sensor for the same purpose.

  [1]: https://i.stack.imgur.com/2YlmM.png
  [2]: https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/

title: Wiring light sensor OPB704WZ to Arduino Due

Answers: 1

body:
You expect that the white surface to reflect the infrared light and the black surface does not.

Your theory is correct; white surfaces should reflect pretty much all light and the black surface should absorb all light.

The problem is that the black surface is reflecting enough light to turn the photo-transistor on.

The theory is correct but in the real world this is not perfect. For example a white surface is not completely white. Likewise no black surface is completely black.

We also know that a mirror is much better at reflecting light than a white surface. The black surface could be shiny. I am looking at my shiny black monitor stand, and even though it is black I can still see the reflection of the window.

I suggest trying with a number of black surfaces (such as paint, card, cloth) and finding the one that works best. I would imagine that chalk board paint would work well at absorbing and diffusing the infrared light. Also experiment with the distance away from the surface. You may have to move it further away from the surface.

If I am imagining your tachometer right, your sensor will see a reflective surface and then it will see empty space (and then repeat). This should work fine. Give it a try.


body:
First of all, I'm new so please don't think this is dumb. I am creating a light culture with RGB LEDs that should play to programmed music. I have uploaded the following code to a spark fun redbird for now, but will later put it on a arduino mega. My circuit is working fine mostly except for the fact that the lights and music play separately and not next to each other. Note: this is just trial code, I will put my own music and light sequencing in later.

    const int buzzerPin = 6;    // connect the buzzer to pin 6
    const int RED_PIN = 11;
    const int GREEN_PIN = 12;
    const int BLUE_PIN = 13;
    const int RED_PIN2 = 8;
    const int GREEN_PIN2 = 9;
    const int BLUE_PIN2 = 10;
    const int songLength = 18;  // sets the number of notes of the song

    const int DISPLAY_TIME = 100;
    // Notes is an array of text characters corresponding to the notes
    // in your song. A space represents a rest (no tone)

    char notes[songLength] = {
      'c', 'd', 'f', 'd', 'a', ' ', 'a', 'g', ' ', 'c', 'd', 'f', 'd', 'g', ' ', 'g', 'f', ' '};

    // beats[] is an array of values for each note. A "1" represents a quarter-note,
    // "2" a half-note, and "4" a quarter-note.
    // Don't forget that the rests (spaces) need a length as well.

    int beats[songLength] = {
      1, 1, 1, 1, 1, 1, 4, 4, 2, 1, 1, 1, 1, 1, 1, 4, 4, 2};

    int tempo = 113;  // The tempo is how fast to play the song (beats per second).

    void setup()
    {
      pinMode(buzzerPin, OUTPUT);  // sets the  buzzer pin as an OUTPUT
       pinMode(RED_PIN, OUTPUT);
      pinMode(GREEN_PIN, OUTPUT);
      pinMode(BLUE_PIN, OUTPUT);
       pinMode(RED_PIN2, OUTPUT);
      pinMode(GREEN_PIN2, OUTPUT);
      pinMode(BLUE_PIN2, OUTPUT);
    }

    void loop()
    {
      mainColors();        // Red, Green, Blue, Yellow, Cyan, Purple, White
      int i, duration; //

      for (i = 0; i < songLength; i++) // for loop is used to index through the arrays
      {
        duration = beats[i] * tempo;  // length of note/rest in ms

        if (notes[i] == ' ')          // is this a rest?
          delay(duration);            // then pause for a moment
        else                          // otherwise, play the note
        {
          tone(buzzerPin, frequency(notes[i]), duration);
          delay(duration);            // wait for tone to finish
        }
        delay(tempo/10);              // brief pause between notes
      }

      // We only want to play the song once, so we pause forever
      }
      // If you'd like your song to play over and over, remove the while(true)
      // statement above

    int frequency(char note)
    {
      int i;
      const int numNotes = 8;  // number of notes we're storing
      char names[numNotes] = {
        'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'    };
      int frequencies[numNotes] = {
        262, 294, 330, 349, 392, 440, 494, 523    };

      // Now we'll search through the letters in the array, and if
      // we find it, we'll return the frequency for that note.

      for (i = 0; i < numNotes; i++)  // Step through the notes
      {
        if (names[i] == note)         // Is this the one?
        {
          return(frequencies[i]);     // Yes! Return the frequency and exit function.
        }
      }
      return(0);  // We looked through everything and didn't find it,
      // but we still need to return a value, so return 0.
    }

    void mainColors()
    {
      // Red
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, LOW);
      digitalWrite(BLUE_PIN, LOW);
       digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Green
      digitalWrite(RED_PIN, LOW);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, LOW);
        digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, LOW);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Blue
      digitalWrite(RED_PIN, LOW);
      digitalWrite(GREEN_PIN, LOW);
      digitalWrite(BLUE_PIN, HIGH);
       digitalWrite(RED_PIN2, LOW);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Yellow (Red and Green)
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, LOW);
        digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, LOW);
      delay(DISPLAY_TIME);

      // Cyan (Green and Blue)
      digitalWrite(RED_PIN, LOW);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, HIGH);
        digitalWrite(RED_PIN2, LOW);
      digitalWrite(GREEN_PIN2, LOW);
      digitalWrite(BLUE_PIN2, HIGH);
      delay(DISPLAY_TIME);

      // Purple (Red and Blue)
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, LOW);
      digitalWrite(BLUE_PIN, HIGH);
        digitalWrite(RED_PIN2, LOW);
      digitalWrite(GREEN_PIN2, HIGH);
      digitalWrite(BLUE_PIN2, LOW);
      delay(DISPLAY_TIME);

      // White (turn all the LEDs on)
      digitalWrite(RED_PIN, HIGH);
      digitalWrite(GREEN_PIN, HIGH);
      digitalWrite(BLUE_PIN, HIGH);
        digitalWrite(RED_PIN2, HIGH);
      digitalWrite(GREEN_PIN2, LOW);
      digitalWrite(BLUE_PIN2, LOW);
      delay(DISPLAY_TIME);
    }

title: Multitasking for music light sculpture

Answers: 1

body:
You need a *state machine*. It goes like this:

You divide your actions in states. Each state is a collection of actions that must performed in group (sequentially). In your case, you have one state for each note and for each ligth color and a duration.

Now, your score (music + light) is made of a sequence of states:

    > state 1: Play Fa, Light up RED - Duration 500ms.
    > state 2: Play Re, Light down RED - Duration 200ms. ...
    >
    > state n: Play Fa, Light up BLUE - Duration 250 ms.

You have many states; put them in an array and then loop across the array.

The code looks like this:

    typedef struct {
     int note;  // Musical note
     int color; // Led color
     int length; // Duration in ms
    } STATE;

    STATE score[] = {
     {0, 0, 0},
     {FA, BLUE, 500},
     [RE, RED, 400},
        ...
       {FA, GREEN, 400}
       };

    int state = 0;

    void loop()
    {
     static unsigned long stateStart = 0;

     if(state == sizeof(score) / sizeof(STATE)) {
      //  reset and start again
      state = 0;
      stateStart = 0;
     }

     if(millis() - stateStart >= score[state].time) {
      // Advance state and play next thing
      state++;
      playNote(score[state].note, duration);
      playColor(score[state].color);
      stateStart = millis();
     }

    }

    void playNote(int note, duration)
    {
     // Play a note.
    }

    void playColor(int color)
    {
     // Light up a color.
    }

Note: this is just the general idea. You must adapt and adjust things, like how you code note and colors. You better Google "Arduino state machine".

My code probably contains errors, but I gave you a starting point.

You have to implement playNote and playColor.


body:
I'm using a Windows computer, and if I recall correctly I installed the IDE using the installer, so I probably don't need to manually install the drivers. However, I can't figure out how to set up the serial port with the Arduino. For me under Tools, there's no "Serial Port" option but instead "Serial Monitor" and "Serial Plotter."

When I tried to upload my file, it failed. When I clicked Serial Plotter, it gave this error message:

    Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

    Sketch uses 940 bytes (2%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
    local variables. Maximum is 2048 bytes.
    avrdude: ser_open(): can't open device "\\.\COM1":
    The system cannot find the file specified.

    Problem uploading to board.
    See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
    Board at COM1 is not available

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

How am I supposed to resolve this?

title: I need help setting up my Arduino Uno with the port

Answers: 1

body: I figured it out by following the tutorial by Adafruit. I had to install it manually in order for it to work.


body:
I have made a custom-development hardware for our school, where you can plug in an Arduino Due. It is mainly for driving all kind of motors and reading sensor signals. Therefore I added a custom SAM board into board.h based on a copy of the Arduino Due. Furthermore I need a global PWM frequency on all PWM Channels of 20 kHz. So I also changed the variants.h file.

(I have not found a solution that is setting all the underling Timer/Counters for PWM on the Due Pins 2, 3, 4, 5, 6, 7, 8, 13 to 20 kHz by user code, I think this is only possible with the variants.h file - because some timers can not be reset after they where set within the Arduino IDE once)

**The Question now:**
Today all students have to find and modify their variants.h file, which can be located almost anywhere! (Sometimes it is located in the support packages of Matlab...).

Is there an easy solution to give the students one .zip containing the Arduino IDE already with the custom Board included?
There is the Arduino IDE working without installation for download on the Arduino website. But how can I add my custom SAM board to it?

title: Arduino Due custom platform for school and library installation

Answers: 1

body:
1. Exit the Arduino IDE.
1. Create a folder in the Arduino IDE installation folder named `portable`. This will cause the Arduino IDE to run in [portable mode](https://www.arduino.cc/en/Guide/PortableIDE).
1. Start the Arduino IDE.
1. Tools > Board > Boards Manager
1. Wait for the download to finish.
1. Click on "Arduino SAM Boards".
1. Click "Install".
1. Wait for installation to finish.
1. Make your modifications to the Arduino SAM Boards hardware package installed at `{Arduino IDE installation folder}/portable/packages/arduino/hardware/sam`.
1. If necessary, configure **File > Preferences** to your liking.
1. Exit the Arduino IDE.
1. Zip the Arduino IDE installation folder.

When you run the Arduino IDE in portable mode it causes hardware packages installed via Boards Manager to be installed to the portable folder, rather than a folder outside the Arduino IDE installation folder. It also stores preferences.txt in the portable folder. This means you can supply a .zip file that contains a copy of the Arduino IDE with the customized Arduino SAM Boards package already installed.

By default it will also set the sketchbook folder to be there but that can be changed via **File > Preferences > Sketchbook location** if you like.


body:
I just displayed the value for floor( 1.0f ) and surprisingly, it's 0.

Anyone knows about that? Is there a fix in libc expected any time soon?

I've been looking at libc::floor.s but it's a bit dodgy and 1) I don't want to break my other existing code and 2) don't have time for that so I'll add an epsilon at the moment (but that defeats the purpose of floor)...

Thanks for posting any fix or idea on how to bypass the issue.

title: floor( 1.0f ) bugged?

Answers: 1

body:
I ran this sketch:

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

    void loop() {
      Serial.println(floor(1.0f));
    }

It outputs "1.0"


body:
I had seen some tutorials on how to assemble an Arduino on a breadboard. They all just place the external crystal oscillator according to the circuit and then, just burn the bootloader and it starts working. According to my little knowledge the fuse bits have to be set before using the external clock.

My question is - How does the microcontroller know which clock to use internal or external? Is there any setting already in the bootloader that tells the microcontroller to use the external clock?

title: How does the microcontroller know which clock to use?

Answers: 1

body: Burning the bootloader via the Arduino IDE also sets the fuse bits according to its configuration files.


body:
As I connected my arduino-uno board and made sure of the "Board" selected, and the "Port" selected as well. There is a problem while uploading, I tried updating the arduino IDE, reinstalling all the arduino drivers, I tried to borrow a new arduino board from a friend and I am 100% sure it is working.

The message I get from the IDE:

    Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

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

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1d
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1d

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Thanks in advance!

title: Can't upload arduino code on the board due to some programmer issues

Answers: 2

body:
Try changing baud rate to 9600.

Another thing to check is the chip your Uno has. My Uno has the atmega328. Make sure you select that board.

body:
I faced the same problem while uploading.

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

To solve that I changed my port to another USB port and I selected the particular port, Its uploaded successfully. But it's in MacBook not in Windows.

Try this once, by changing the port.


body:
Context
-------

I keep the board in sleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot.

In the following schematic, **SW-R** is actually used to reset the board.

If I hold **SW-D5** or **SW-D6** *while* pushing **SW-R**, the code can detect which button I pushed.

Problem
-------

I don't want to have to push 2 buttons at the same time and, *being new to electronic*, I don't know how to wires things up so it reset and set a pin to HIGH simultaneously.

Question
-------

How can I reset the board and trigger a HIGH on an IO corresponding to a button while it boot?

Considering the HIGH only need to be hold for less than a second, can it be simply achieved with capacitors and/or transistors? If so, how? Or any other suggestion?

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

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

<!-- End schematic -->

The actual code example only contain 1 button but I'll have many.

<!-- language-all: c -->

    #include <Spi.h>
    #include <Arduino.h>
    #include <ESP8266WiFi.h>

    int buttonPin = D5;

    void setup() {
      pinMode(buttonPin, INPUT);
      pinMode(BUILTIN_LED, OUTPUT);

      int buttonValueAtBoot = digitalRead(buttonPin);
      Serial.begin(115200);
      Serial.println();

      if (buttonValueAtBoot == HIGH) {
        // I want to trigger this code pushing only 1 button
        // should also work with many buttons
        Serial.println("button was pressed");
      }

      digitalWrite(BUILTIN_LED, HIGH);
    }

    void loop() {
      delay(5000);
      ESP.deepSleep(0);
    }

title: How to reset an arduino while being able to know which button has been pressed?

Answers: 1

body:
Just found that I can change pins behavior. Inverting things a little bit, I can get my pins to work as LOW instead of as HIGH.

That way, I only need 1 button to trigger a reset and change pin status. Plus, grounding the reset is done temporarily because of the capacitor, which is what I need.

Here is the new schema

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

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

<!-- End schematic -->

New code
----

    #include <Spi.h>
    #include <Arduino.h>
    #include <ESP8266WiFi.h>

    int buttonPin = D5;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(BUILTIN_LED, OUTPUT);

      int buttonValueAtBoot = digitalRead(buttonPin);
      Serial.begin(115200);
      Serial.println();

      if (buttonValueAtBoot == LOW) {
        Serial.println("button was pressed");
        digitalWrite(BUILTIN_LED, HIGH);
      }

      // Avoid problem when the button is hold
      while (digitalRead(buttonPin) == LOW) {
        // wait before going to deepsleep
        // or the capacitor will be drained
        delay(1);
      }

      Serial.println("going to sleep");
      ESP.deepSleep(0);
    }

    void loop() {
    }