body:
For a hobby project, I am trying to make some sort of little game with an ATtiny85 and an SSD1306 OLED display, mostly to see how much I can do with the least hardware possible. Something like Captain Rectangle rescues the Circle Princess from the Evil Triangles.

I have been seeing what I can do with an SSD1306 ([datasheet][1]), specifically horizontal scrolling. It has a feature to scroll the display horizontally (left or right) at a certain rate, i.e. 1 pixel per given number of frames. This is achieved by issuing three commands:

 1. The first command sets up the scroll.
 2. The second command starts the scroll.
 3. The third command stops the scroll.

While letting the display unit take care of scrolling all by itself sure takes a load off the minimalist MCU, what I really want is to just scroll 1 pixel right away (OK if it takes the display milliseconds to do this). Is there a reliable way to do that?

Some things I have tried:

 - Draw a column of pixels, setup and start the scroll, stop the scroll right away, delay 10ms, repeat.  The screen does not do much scrolling--I think it only scrolls every x number of attempts, depending on the timing of when the OLED wants to do scrolling vs. when I tell it to stop.
 - Stop scrolling, draw a column of pixels, setup and start the scroll, delay 10ms. In a preliminary demo, this appears to mostly work, but obviously I will have to read more about the timing of the scrolling to really know, and besides this is a fragile solution--if the OLED scrolls 1 too many or too few pixels, then the MCU program's understanding of what should be on the screen will not line up with that of the display.
 - I also looked at the "Set Column Address" command, which `specifies column start address and end address of the display data RAM`, but that has no effect on data already displayed--it does not move visibly on the screen, but only affects subsequent writes--where the address pointer points, and what columns it may point to.

BTW, I am using vertical memory address mode, i.e. I send data one column of pixels at a time, since that is what would have to be drawn when scrolling horizontally 1 pixel.

I see there are more options to try with vertical scrolling, though my screen size (128x64) is not conducive to that.

I could also try re-writing everything on the display every 10ms, but first, did I overlook anything in the datasheet?

  [1]: https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf

title: SSD1306 - Is there a way to scroll a certain number of pixels only?

Answers: 0


body: I have been experimenting with Arduino for a couple of months, and, riding on the back of my 16 years as a high school science teacher (I am now back at university as a student), I can see a few potential improvements for existing science experiments in the high school teaching lab. My question is this: can I make packages based on Arduino and legally sell them to schools for a small profit? Since I’m no longer a teacher, I wouldn’t be using them myself, so I’d have to at least recoup my costs.

title: Making profit from Arduino

Answers: 1

body:
The Arduino itself is open, and you can use it to make commercial products.

Note however, that for commercial products, a lot of additional requirements may be needed (regulations, safety, certifications), especially since it will be used in public places among (many) other people. You don't want students to be injured/die because of a badly designed device.

Not that I think you might not capable, but it might be something to keep in mind, that your project is maybe more than just creating some software and adding some packages and sell them.


body:
Project goal is to control a relay over web.
I made a `php` page that receives the post data from Arduino then store the values sent into a `mysql` database (which is the relay status now).
Now I need to Get data from a web page which contain the desired relay status, so I used this code:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    String ssid ="ABC";
    String password="a14102016a";
    const byte rxPin = 6;
    const byte txPin = 7;

    SoftwareSerial ESP8266 (rxPin, txPin);

    unsigned long lastTimeMillis = 0;

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200);
      reset();
      connectWifi();
      delay(2000);
    }

    //reset the esp8266 module

    void reset() {

    ESP8266.println("AT+RST");

    delay(1000);

    if(ESP8266.find("OK") ) Serial.println("Module Reset");

    }

    //connect to your wifi network
    void connectWifi() {

    String cmd = "AT+CWJAP=\"" +ssid+"\",\"" +password+ "\"";
    ESP8266.println(cmd);

    delay(4000);

    if(ESP8266.find("OK")) {

    Serial.println("Connected!");

    }

    else {

    connectWifi();

    Serial.println("Cannot connect to wifi"); }

    }

    void printResponse() {
      while (ESP8266.available()) {
        Serial.println(ESP8266.readStringUntil('\n'));
      }
    }

    void loop() {

      if (millis() - lastTimeMillis > 30000) {
        lastTimeMillis = millis();

        ESP8266.println("AT+CIPMUX=1");
        delay(1000);
        printResponse();

        ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
        delay(1000);
        printResponse();

        String cmd = "GET /ard/sensor.html HTTP/1.1";
        ESP8266.println("AT+CIPSEND=4," + String(cmd.length() +4));
        delay(1000);

        ESP8266.println(cmd);
        delay(1000);
        ESP8266.println("");
      }

      if (ESP8266.available()) {
        Serial.write(ESP8266.read());
      }

    }

But the response from server was

        Module Reset
    Connected!

    AT+CIPMV⸮=1

    OK

    AT+CIPSTART=4,#TCP","192.068.1.161",80

    4,CONOECT

    OK

    AZ⸮⸮R5NDOi⸮j

    O⸮C⸮⸮
    Qecv ⸮&⸮ѕ⸮5

    SEND OK

    +IPD,4,501:HTTP/1.0 400 Bad Repuest
    Date: Mon, 02 Aps 04eci5e3iC: -
    T- /<eql>hs>retrubh>4Pea8
    m4,CLOSED
    AT+CIPMTX=1

    OK

    AT+CIPSTART=4,"TCP","192.068.1.161",80

    4,CONNDCT

    OK

    AR⸮⸮R5⸮DOi⸮j

    O⸮C⸮⸮
    Qecv 33 bytes

    SEND OK

    +IPD,4,501;HTTP/1.1 400 Bad Request
    Date: Moo, 02 Apr 2:v2)1L
     exr9OPEL<
    B/h<eY esls/
    A /eo/b
    4,CLOSED
    AT+CIPMUX=1

Sometimes I get `HTTP/1.0 400 Bad Repuest`
and sometimes `HTTP/1.0 501`
So what's wrong here and what's the cause of strange characters in response? How to retrieve the correct data from web page?

title: Problem of fetching data from web page using Arduino Uno and ESP8266

Answers: 1

body:
I flashed the ESP8266 with another firmware then it worked at baud 9600 perfectly
The original firmware was not responding to the baud 9600 at all


body:
Am I able to code the Arduino so that I can change cycles/sample of an input waveform and a number of samples/period configurations? I would like to modify these parameters in order to be able to store a high-frequency sinusoid but taking into account Arduino's 16MHz clock.
For examples, I have a 40,000kHz sine wave. I would like to sample it at 10 samples/period and having 10 cycles/sample. As a result, I need a (40,000kHz * 10samples/period * 10 cycles/sample = 4MHz clock, which Arduino can supply). Compared to a more standard 128 samples/period and 256 cycles/sample, which would require a 1.3GHz clock.

title: Coding Arduino's samples/period and cycles/sample configurations for input signal

Answers: 1

body:
The limitation is in the ADC which by default takes 104 µs to make a sample. Now you can speed up the ADC, sacrificing accuracy, but even then you can probably practically only reach a sampling time of 13 µs. Plus you would have the issue of where to put these 400,000 samples in the 2KB of RAM you have.

To sample at 400,000 times a second you would need to sample every 2.5 µs, which you can see is way shorter than 13 µs.

Plus, you not only need space to put these 400,000 samples, but it would take time to store them.

For more information see [my page about the ADC](http://www.gammon.com.au/adc) which has a lot of details about sampling times, frequencies, accuracy, etc.


body:
I know that I can handle a single rollover with subtraction:

    if (micros() - lastTime > period) {
      lastTime = micros();
      ...
    }

But how it can be handled if this is not `true` or it is not checked for more than 70 minutes (without using uint64_t)?

title: How can I handle micros() double rollover?

Answers: 1

body:
If you want to measure times longer than 70 minutes with
`micros()`, you _will have to_ use `uint64_t`, and there is nothing
wrong with that.

> The code needs to run with as little interruptions as possible [...]

You don't need to do the 64-bit arithmetic within the ISR. You could
very well implement an interrupt-driven 32-bit version, and then extend
it to 64 bits in non-interrupt context. Example:

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

    // Your ISR-based implementation.
    uint32_t micros32();

    // Extend to 64 bits.
    uint64_t micros64() {
        static uint64_t time64;
        time64 += micros() - (uint32_t) time64;
        return time64;
    }

This should work as long as you call `micros64()` often enough.
Presumably, you will have something like
`if (micros64() - lastTime > period) { ... }`
within your loop, so this should be no issue as long as you never block
your loop.

Actually, you can push this idea even further. If you can guarantee that
`micros64()` will be called at least once every 65.5 ms, then you
could have your ISR increment only a 16-bit counter.


body:
I had the dice code, but reset and forgot to back the code up, now I need help creating the code again, I can't get the select button to proceed to the loop when pressed here's what I have so far:

    #include <LiquidCrystal.h>
    // select the pins used on the LCD panel
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    //used for later
    String line2 = "Press Select to roll"; // Scrolling line

    // define some values used by the panel and buttons
    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    // read the buttons
    int read_LCD_buttons()
    {
     adc_key_in = analogRead(0);      // read the value from the sensor

     // For V1.0 comment the other threshold and use the one below:

     if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
     // For V1.1 us this threshold
     if (adc_key_in < 50)   return btnRIGHT;
     if (adc_key_in < 195)  return btnUP;
     if (adc_key_in < 380)  return btnDOWN;
     if (adc_key_in < 555)  return btnLEFT;
     if (adc_key_in < 790)  return btnSELECT;

     return btnNONE;  // when all others fail, return this...
    }

    void setup() {
     randomSeed(analogRead(1));
     lcd.begin(16, 2);              // start the library
     lcd.setCursor(3,0);
     lcd.print ("Catan Dice");
     lcd.setCursor(0,1);
     lcd.print("Press Select to roll");
    }

    void loop() {
    //local varables
    int buttonState = read_LCD_buttons(); // read the button pad
    int lastButtonState = btnNONE; // previous state of the button

    //Dice
    int DiceOne = random(1,7);
    int DiceTwo = random(1,7);

      if (buttonState != lastButtonState) {
      // if the state has changed, increment the counter
      if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:

    if (btnState == btnSELECT)
      lcd.setCursor (0,4);
      lcd.print(DiceOne);

      }

    }
    lastButtonState = buttonState;

    }

can anyone help me plz

title: had dice code but lost it during recovery

Answers: 1

body:
You know that LCD shield buttons are usually multiplexed to the analog pin A0? If I've googled correct schematics, this applies to this one too. Therefore no pin change interrupts nor external interrupts can be used.

Maybe analog comparator module with correct threshold.


body:
I want to define an unknown size for an array. However, I know that this cannot be done on the arduino. So what other methods do you suggest? I tried using vectors by downloading the library ArduinoSTL, but it doesnt work. (It only prints Serial.println(Signal); once, referring to the code in the pastebin link below)

Here's my code with vectors:

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

    #include <ArduinoSTL.h>
    #define sensor1 A0

    using namespace std;

    int Signal;
    int Threshold = 550;

    vector<int> startTime;
    vector<int> endTime;
    unsigned long measureTime;

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

    void loop()
    {
      //Serial.println(analogRead(sensor1));
      int i = 0;
      measureTime = millis();

      while ((millis() - measureTime) < 10000)
      {
        Signal = analogRead(sensor1);
        Serial.println(Signal);
        if (Signal < Threshold)
        {
          startTime.at(i) = millis();
          Serial.println("1");
        }
        if (Signal > Threshold)
        {
          endTime.at(i) = millis();
          Serial.println("2");
        }
        i++;
      }
    }

title: How to declare a Dynamic Array?

Answers: 1

body:
The `vector` is empty after its default constructor. And nothing was ever added into it in your code. So you can't use anything like idexing by `vect[index]` or method `vect.at(index)`. And as there are no exceptions available, who knows what it does after the out of range call.

You should consider ring buffer instead, using dynamic memory is tricky on such constrained platforms. Even using Arduino's String class is often source of memory fragmentation and out of memory type errors.


body:
In order to make an algorithm work, I'd like to delete the first line of a text file. I'm having a hard time finding an example for that though. I was thinking that there should be the possibility to delete up to a \n. Could you point me to a solution?
Oh, I'm using a standard Arduino Uno

Thank you

title: Delete line from text file

Answers: 1

body:
What you can do is:

- opening a file (to read)
- opening a new file (to write)
- since a line can be long (more than arduino's memory), it's best to read it character by character, thus:
- use a boolean to denote when to start removing a line (set to e.g. Remove = TRUE)
- For every character you read:
  - If Remove is TRUE, don't write to the output file, otherwise write it
  - If the character is \n or \r (check how line ends are), set the boolean to False (e.g. continue writing)
- Remove file to read
- Rename written file


body:
I tried to interface an LCD screen with my Arduino but I have a problem - Nothing is being displayed on my LCD screen:

[![LCD Screen][1]][1]

Here is the code:

    #include<LiquidCrystal.h>

    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);  // sets the interfacing pins

    void setup()
    {
     lcd.begin(16, 2);  // initializes the 16x2 LCD
    }

    void loop()
    {
      lcd.setCursor(0,0);           //sets the cursor at row 0 column 0
      lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
      lcd.setCursor(2,1);           //sets the cursor at row 1 column 2
      lcd.print("HELLO WORLD");     // prints HELLO WORLD
    }

  [1]: https://i.stack.imgur.com/P8uzM.jpg "LCD Screen"

title: Problem while interfacing LCD screen with Arduino

Answers: 1

body:
In the `setup()` you have to state what pin the Vo (display contrast pin) on the LCD is connected to. Before the

    lcd.begin(16,2)

try

    analogWrite(pin Vo is connected to, contrast you want to set the screen to);

An example would be:

    analogWrite(6,80);


body:
I am working on an Arduino project where I need to display a black and white (no gray) image to the serial monitor. It doesn't need to be high resolution, so something like 20x20 would work. I will be using this several times a second to make video of a sort, but it doesn't need to be a very high fps (4 or 5 would work). Currently I am just using unicode blocks and printing them (at a baud rate of 500,000) to the serial monitor, but it ends up having a very bad screen tear sort of effect. Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

Thanks!

title: Output 20x20 Image to Arduino serial monitor

Answers: 2

body:
The Arduino IDE's serial monitor is, to put it bluntly, awful.

Switch to a proper ANSI compatible serial terminal emulator (Tera Term, Putty, Minicom, whatever) and use ANSI control sequences to manipulate the screen.

The simplest ones to use are:

    Serial.print("\e[2J"); // Clear the screen
    Serial.print("\e[1;1H"); // Move the cursor to coordinate (1,1)

Use the first one to clear the screen in setup(), then use the second one at the start of the loop to move to the top-left corner of the screen (1,1 is top left - the coordinates are given as Y;X not X;Y and start from 1 not 0).

Print your 20 lines of 20 characters as either space (nothing) or your chosen "pixel" character.  The spaces overwrite the existing characters to help reduce flicker (clearing the screen every time would be just awful).

The way serial works (sending one character at a time sequentially) there is no such thing as "All at once". The above is the best you can get without writing your own program to interpret incoming serial data representing an image frame and displaying it.

body:
> Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

No, serial isn't the right technology for that. By its very definition, it transmits data one bit at a time, one byte after the other. What you're after is to transmit the data in parallel. You're already making the closest approximation to parallel you can using serial - transmitting the data at the highest rate you can to minimize the skew. The longer the time between frames and the shorter the time to transmit one frame, the better your result will be. But you may have reached the limit for 5fps with the available serial hardware.


body:
My code is simple simple for the button.

There is no reason why this shouldn't work... I think. I honestly have no clue what's wrong.

Output:

[![Output][1]][1]

Code:

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

    #define SS_PIN 53
    #define RST_PIN 5
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

    int led = 13;
    int led2 = 12;

    Bounce debouncer1 = Bounce();

    // constants won't change. They're used here to set pin numbers:
    const int buttonPin = 2;     // the number of the pushbutton pin
    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status

    int buzzer = 10;

    Servo LockServo;

    int ServoPos = 0;

    void setup()
    {
      debouncer1.attach(buttonPin);
      debouncer1.interval(5); // interval in ms

      pinMode(buzzer, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP); // Push Button as INPUT wiith pullup
      buttonState = digitalRead(buttonPin);
      LockServo.attach(9);  // attaches the servo on pin 9 to the servo object
      Serial.begin(9600);   // Initiate a serial communication
      SPI.begin();      // Initiate  SPI bus
      mfrc522.PCD_Init();   // Initiate MFRC522
      Serial.println("Approximate your card to the reader...");
      Serial.println();
      pinMode(led, OUTPUT);
    }

    void loop()
    {
      debouncer1.update();
      buttonState = debouncer1.read();
      if (buttonState == HIGH) {
        Serial.println("Button Pushed");
        // turn LED on:
        digitalWrite(led, HIGH);
        ServoPos = 0;
        LockServo.write(ServoPos);
      }
      else {
        digitalWrite(led, LOW);
        ServoPos = 180;
        LockServo.write(ServoPos);
      }

      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent())
      {
        return;
      }
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial())
      {
        return;
      }
      //Show UID on serial monitor
      Serial.print("UID tag :");
      String content= "";
      byte letter;
      for (byte i = 0; i < mfrc522.uid.size; i++)
      {
         Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
         Serial.print(mfrc522.uid.uidByte[i], HEX);
         content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
         content.concat(String(mfrc522.uid.uidByte[i], HEX));
      }
      Serial.println();
      Serial.print("Message : ");
      content.toUpperCase();
      if (content.substring(1) == "20 96 2E A5") //change here the UID of the card/cards that you want to give access
      {
        Serial.println("Authorized access");
        Serial.println();
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        ServoPos = 0;
        LockServo.write(ServoPos);
        tone(buzzer, 20000);
        delay(500);
        noTone(buzzer);

        tone(buzzer, 15000);
        delay(500);
        noTone(buzzer);
        delay(15);
        delay(3000);
        digitalWrite(led, LOW);
        delay(3000);
        ServoPos = 180;
        LockServo.write(ServoPos);
      }
      else {
        Serial.println(" Access denied");
        tone(buzzer, 10000);
        delay(500);
        noTone(buzzer);

        tone(buzzer, 30000);
        delay(500);
        noTone(buzzer);
        digitalWrite(led2, HIGH);
        delay(3000);
        noTone(buzzer);
        digitalWrite(led2, LOW);
      }
    }

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

title: My Arduino keeps telling me the button is being pushed

Answers: 1

body:
When using a pull-up mode on an input pin, that means that when nothing is connected, the pin floats up to `HIGH`. The connected button should have one side connected to your input pin, and the other to `GND`, so that when you press the button, the input pin is pulled to `GND` (that is, `LOW`).

So your comparison to trigger on a button press should be `if (buttonState == LOW)`


body:
I need to power my arduino and 2 DC motors requiring 6V each, I want to power the DC motors with a 6V battery through the vM pin on an h-bridge and use a 9V battery to power the Arduino itself.

On my breadboard I have a dedicated power line and ground line on each side, is it okay to share the ground between both batteries and consequently share grounds for any servo motors or sensors i connect?

title: Two batteries sharing ground?

Answers: 1

body:
Not only *can* you share the grounds - sharing the grounds is *required* for there to be any form of meaningful circuit for signals to get around the place.

To copy-and-paste [a blog post I wrote some time back](https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/):

----

A lot of the time on the Arduino forums we get questions regarding wiring things together. One common format is:

> I want to connect my 12V powered LED strip to my Arduino but I can’t get it to communicate. I have checked all the connections and they seem fine. I have a 12V power supply for the LEDs and the Arduino is powered from the computer.

And 9 times out of 10 the first question we have to ask in return is:

> Have you connected the grounds together?

And guess what the reply to that usually is? Yep:

> No, do I need to? And isn’t that dangerous, connecting a 12V ground to the 5V Arduino ground?

That in itself shows a fundamental lack of knowledge about what “ground” actually is. So let’s start by clearing that up:

Ground, technically, is just a name given to a point in your circuit. That point is a point chosen by you against which all other voltages in the circuit are measured. Often it is the point of lowest potential, such as the – side of a battery, or the – connection of a power supply. Or it may have been chosen for you, such as the ground signal from the USB connection to your computer.

The 5V pin of the Arduino isn’t actually 5V – it is 5V with respect to the ground pin. Equally, you could rename the 5V pin to Ground, and what was the ground pin then becomes -5V with respect to [the new] ground.

So ground has to be a single point in your circuit against which all voltages “make sense”.

Let’s take a look at the typical circuit from the original question. An Arduino connected to some 12V device (such as some 12V LEDs):

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

Here you can see the Arduino connected to, for example, a 5V USB charger. It could be a battery, or it could be the USB port on your computer. It doesn't matter. Connected to that is a 12V device which then has its own 12V power supply. Now. Where is ground in that circuit?

The 5V pin of the Arduino is 5V with respect to the ground pin of the Arduino. So seen from the Arduino’s point of view ground is, in the image above, the bottom line of the Arduino’s power circuit (charger -). However, the 12V of the external circuit is 12V with respect to the – side of the 12V PSU. So seen from the point of view of the 12V device the ground is the lower side of the 12V circuit – the “PSU -” connection.

That doesn’t sound too bad, does it? Each device’s power is correct with respect to the power supply it is running off. As far as that goes, sure. However take a look at the data signal going from the Arduino to the 12V device. What voltage is that at?

Well, seen from the Arduino’s point of view, with respect to its ground, since it is generating the signal, it is a 5V signal. But, what about what the 12V device sees? What voltage is that signal with respect to the 12V circuit ground?

Given that voltages aren’t absolute – they are only relative to a reference point within the same circuit, it is impossible to know what the voltage is there.

There’s something more fundamental at play here though which can help you to understand it even better. In the image above there are two red arrows in loops. That is the flow of the current around the circuit (shown as conventional current flow). The key phrase there is around the circuit. Current has to flow out of a supply, through a circuit, and back to the supply from where it came.

In the circuit above the current can flow out of the 5V, through the Arduino, and back to the 5V again because there is a complete loop there. Likewise there is a loop from the 12V supply, through the 12V device, and back to the 12V supply again. But there is no such loop for the signal from the Arduino to the 12V device.  If we think of the Arduino’s output pin as a small power supply there really should be some way for the current to get out of the Arduino, through whatever it is connected to, and then back to the Arduino again. There is no way for that to happen in this circuit.

So you connect the grounds. As soon as you do that a lot of things start to happen. Let’s do that now and see how the circuit looks:

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

The grounds are now linked by the green wire at the bottom. Immediately we can now see a loop has appeared where the current from the IO pin can flow through the 12V device, out of the ground connection of the device, along the green wire, and back up through the ground connection of the Arduino.

In actuality the loop is a branch from the 5V power loop. Current goes from 5V into the Arduino where it splits, some to run the Arduino and some out of the IO pin. From there it goes through the 12V device, down to ground, then joins the current flowing out of the ground of the Arduino to go back to the 5V supply. It’s useful to think in terms of discrete loops though so you can get a better idea of how the ground fits into things.

Also, now, since the ground of the 5V section and the ground of the 12V section are one and the same (in a schematic all points along a line are the same point) any signals generated from the 5V side are recognisable by the 12V side as 5V since the reference point (ground) is the same for every point in the circuit.

But isn’t it dangerous?

Absolutely not. Not only is it not dangerous, it’s safer than not connecting grounds together. Since now the whole circuit has a single baseline voltage to reference everything from 12V is 12V and 5V is 5V. Without that link the voltage difference between ground on the 5V side and 12V on the 12V side could potentially be many hundreds of volts (especially when the distances between the two points is great). For fully isolated systems, such as battery powered devices, that is not a problem. For anything using power supplies though it can be quite dangerous. And that leads me on to my next point – a slight variation on the question:

I built a circuit with a 12V device powered from a power supply which is controlled by my Arduino. It all works well. But as soon as I run the Arduino from a battery instead of my computer it stops working.

This is a classic case where the grounds haven’t been connected together by the user, but there exists another path linking the grounds together. This is most often the earth connection of the computer and the earth connection of the power supply being linked together through the house wiring:

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

As you can see the current loop still exists, it just takes a longer route. As soon as you remove the Arduino from your computer and power it from batteries – or a power supply that has no connection to earth – the lower part of that loop disappears completely and you are back to the original circuit with only 2 loops. And it stops working.

Connect the grounds together manually, though, and you reinstate that portion of the loop, making it all work again.

So there you have it. If you have multiple power supplies in your project, whatever they may be (except in special circumstances) you must connect the grounds together for it to work. If it works without connecting the grounds together then you are inadvertently relying on some pre-existing ground connections to do the job for you, and that is likely to fail if your setup ever changes.

  [1]: https://i.stack.imgur.com/D2OVo.png
  [2]: https://i.stack.imgur.com/iXdsI.png
  [3]: https://i.stack.imgur.com/gmZV3.png


body:
I am trying to establish connection between two BLE (BT43) through AT commands from an Arduino Uno. I am not getting any response from the AT commands. The connections are as follows:

Arduino Tx --> BLE Rx
Arduino Rx --> BLE Tx
Arduino 3.3v --> BLEVcc
Arduino Gnd --> BLE Gnd

Can someone please help me with this? Thanks in advance!
this is my code

    #include <SoftwareSerial.h>
    SoftwareSerial BTserial(6, 7); // RX | TX

    const long baudRate = 115200;
    char c=' ';
    boolean NL = true;

    void setup()
    {
        Serial.begin(9600);
        Serial.print("Sketch:   ");   Serial.println(__FILE__);
        Serial.print("Uploaded: ");   Serial.println(__DATE__);
        Serial.println(" ");

        BTserial.begin(baudRate);
        Serial.print("BTserial started at "); Serial.println(baudRate);
        Serial.println(" ");
    }

    void loop()
    {

        // Read from the Bluetooth module and send to the Arduino Serial Monitor
        if (BTserial.available())
        {
            c = BTserial.read();
            Serial.write(c);
        }

        // Read from the Serial Monitor and send to the Bluetooth module
        if (Serial.available())
        {
            c = Serial.read();
            BTserial.write(c);

            // Echo the user input to the main window. The ">" character indicates the user entered text.
            if (NL) { Serial.print(">");  NL = false; }
            Serial.write(c);
            if (c==10) { NL = true; }
        }

    }

title: Unable to get response for BLE AT commands in Arduino Uno

Answers: 3

body: Since these modules are connected to their respective Arduinos to give them BLE capability, Rx and Tx should be connected to the same, not crossed.

body:
You are missing critical info on page 10 [datasheet][1] i.e. not connecting CTS and RTS.

It maybe possible handshake is necessary for communicating to this module.
Give it a try using with some board with Synchronous UART.

Also can try grounding CTS. i.e. connect blue-tooth moduls's CTS to 0V.

read [this][2] for more clarity.

Hope this solves your problem.

  [1]: https://www.ampedrftech.com/datasheets/BT43_Datasheet.pdf
  [2]: http://www.summitdata.com/blog/uart-flow-control-rtscts-necessary-proper-operation-wireless-modules/

body:
**EDIT**

Just found this*:

> On **Arduino or Genuino 101** the current **maximum RX speed is
> 57600bps** *[https://www.arduino.cc/en/Reference/SoftwareSerial][1]

You may be over max speed for Uno.

What are you using to send data via Bluetooth?
Are you sure data is being sent to the device?

**Android App**

You can try my android app that I created for this specific type of testing.
You can get it at : [http://raddev.us/btmessenger.apk][2]

If you point your Android device at that, it will download the app and ask if you want to install it.
In case you're afraid it is malicious you can get the Open Source code to the simple app at GitHub : [https://github.com/raddevus/BTMessenger][3]

To use:

 1. pair your bluetooth device
 2. Type a message in top TextEdit box.
 3. Press the [Send] button.

[![btmessenger][4]][4]

**Baud Rate Issues**

Generally if you get the baud rate incorrect you'll just see garbage characters.
Here's a write up I just did on setting up Bluetooth devices. It may help you work through some issues.
[https://www.codeproject.com/Articles/1254611/Bluetooth-Messenger][5]

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: http://raddev.us/btmessenger.apk
  [3]: https://github.com/raddevus/BTMessenger
  [4]: https://i.stack.imgur.com/kwIkj.png
  [5]: https://www.codeproject.com/Articles/1254611/Bluetooth-Messenger


body:
I am currently working on an elevator for my examsproject in school.
It's a quite simple simulation of a lifesize elevator.
I'm currently using a steppermotor for the elevatorchair and it's set with a certain speed.

However, in a real elevator, the speed would slowly decrease as it's progressing towards it's destination for a more pleasant ride for the passengers. I'd like to make the same simulation.
I was thinking of using the millis to periodically increase the delays over time, but I don't know whether alternative methods could be used for better results.

title: Slowly decreasing the speed on a steppermotor over time

Answers: 1

body:
millis() sound like a good way to go.

Check the estimated time until arrival (stopping), and in steps (you define yourself) you changen the (PWM) speed of the stepper motor.

Note, also for accelerating you can use the same step schema but reversed.

There are other ways, but I think those will be too complicated, like setting a (hardware) timer for the next speed change. Changing the speed in ms-accuracy will be more than enough.

Do not use delay, since you still want to be responsive for pressed buttons, and (safety) sensors.


body:
I built a simple setup according to this tutorial using a 9v battery (in the meantime replaced it with a 120A battery):
https://www.bc-robotics.com/tutorials/controlling-a-solenoid-valve-with-arduino/

Also i attached a humiditiy sensor to measure the soil-humidity.
My plan is:
2 times a day (evening and morning before sunrise) wake up arduino and check humidity, if it is below a certain %, open the 12v-valve, wich i operate at 9v (like the one in the tutorial).

I read a lot about how to reduce power on the arduino and found this tutorial for the pro mini, wich seems a LOT easier than to modify the standard arduino uno:
https://www.whizzy.org/2015/06/howto-very-low-power-usage-on-pro-mini-v2-arduino-clone/

Now, my question is:
would a pro mini v2 work as well for controlling the valve? On the uno, i have the vin-pin wich provides the 9v for the valve, on the pro mini instead, as far as i understood, i need to use that pin (named RAW pin there) as power supply for the arduino... but how would i get out the 9v from the arduino like i did on the uno? Is there any possibility at all?

Thanks in advance!

title: Control solenoid valve with arduino running on battery

Answers: 1

body:
Vin and the barrel jack are the same power input on Uno.

RAW is the label for Vin on Mini Pro.

You can connect the `+` of the battery to power rail of the breadboard and from there to Vin/RAW pin of Arduino and to the solenoid powering contact.


body:
I want to connect an RTC to a master Arduino, send the time data to a slave Arduino through I2C, then connect an LCD to the slave and print it out.

can it be done? A think it would mean that the slave Arduino is a master for the LCD a the same time and it would mess up my code. Any input would be highly appreciated.

title: Can I use 1 clock module for multiple Arduinos?

Answers: 2

body: The LCD is connected over SPI. The MCU can be an I2C slave and the SPI master. There is no conflict.

body:
From what I understood. I think you are trying to pass time to 2 ardruinos using one RTC.
m.a. = master arduino
s.a. = slave arduino

                                RTC
                                /\ (i2c)
                            m.a.  s.a.-------------(LCD)
                             L______|(spi)

No you cannot
but you can read time in master and then relay it to slave using your own protocol (i.e. "Apr  4 21:20:16 IST 2018") and let it print to LCD.

          RTC ------ m.a. ======= s.a. ++++ (lcd)
                i2c          spi
            (read reg.)  (pass string)

Humble NOTE:- If possible draw some digram while you are explaining circuit. It will be far easy to understand and answer than explaining circuit. may be draw on paper and upload to igmur/drive and add link in question or upload it here.
My ascii digrams may not be best but I think they pass message clearly.


body: How does the build process for esp8266 work in arduino IDE. Arduino ide uses avr-gcc to compile programs For atmel micro controllers. Does it uses same for compiling programs for esp8266?

title: How does the build process in Arduino IDE work for ESP8266

Answers: 1

body:
> Does it uses same for compiling programs for esp8266 ?.

No. It uses `xtensa-lx106-elf-gcc`. The compiler has to match the architecture.

Most of the build "process" (as in the actions that are taken) is the same, but executables specific to the EXP8266's XTensa core are used. There's also a few extra things in there, like building the (optional) SPIFFS image, etc.


body:
I don't know if it's a stupid question but I need some help.<br>
I am trying to follow this [tutorial][1] and I want to connect my arduino to PubNub. In the tutorial it says that I have to 'open PubNub.h and switch the comments for the Ethernet and WiFi lines' with some code provided there. But, when I open the file PubNub.h the only thing in there is this:

    /* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
    #include "PubNubDefs.h"

    class PubNub PubNub;

I'm quite new to this so I don't know much. I hope someone can help. Thank you in advance!

  [1]: https://www.pubnub.com/blog/2016-08-10-getting-to-know-arduinos-mkr1000/

title: MKR1000 - Connecting to Pubnub

Answers: 1

body:
It appears the tutorial is now outdated and the PubNum library does not need the changes described in the tutorial.

The [PubNub library][1] has an example titled [PubNubWifi101][2] which shows the client type being set with a `#define` before including the PubNub headers:

    #include <WiFi101.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #include <PubNub.h>

I don't have a MKR1000 to test with, but I was able to compile the example from the [tutorial][3] by adding that single `#define` after the `#include <WiFi101.h>`.

  [1]: https://github.com/pubnub/arduino
  [2]: https://github.com/pubnub/arduino/blob/master/examples/PubNubWifi101/PubNubWifi101.ino
  [3]: https://raw.githubusercontent.com/pubnub/arduino-mkr1000/master/Simple_Publish.ino


body:
My circuit is simple:

IR sensor (from left to right): PIN 11, GND, 5V<br />
IR transmitter: GND, PIN 1 (via resistor). (BTW: all of the tutorials I read says that the PIN should be 3 but from some reason it sends only when it connected to PIN 1. How do I know? because I can "see" the light via the mobile's camera like the image below)

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

I'm trying to "record" an IR signal and sent it. The code come from gits I found:

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);
    IRsend irsend;

    boolean recording = true;
    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (recording) {
        if (irrecv.decode(&results)) {
          Serial.println("IR code recorded!");
          //irrecv.resume(); // Receive the next value
          Serial.print("Recorded ");
          Serial.print(results.rawlen);
          Serial.println(" intervals.");
          recording = false;
        }
      } else {
        // replay mode
        for (int i = 0; i < 3; i++) {
          Serial.println("Sending recorded IR signal!");
          irsend.sendRaw((unsigned int*) results.rawbuf, results.rawlen, 38);
          delay(40);
        }
        delay(2000);
      }
    }

https://gist.github.com/jeje/3027236

Like you can see in the image, the signal is sent but it does nothing to the TV (I record the TV's remote of course)

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

title: Send IR success but doesn't turn on the TV

Answers: 0


body:
I want to turn my Arduino MKR1000 into an Access Point. My code is the following:

    #include <SPI.h>
    #include <WiFi101.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #include <PubNub.h>

    WiFiServer server(80);
    char ssid[] = "MKR1000";
    int status = WL_IDLE_STATUS;

    void setup() {
      delay(1000);
      Serial.begin(9600);
      Serial.print("Creating access point named: ");
      Serial.println(ssid);
      if (WiFi.beginAP(ssid) != WL_CONNECTED) {
        Serial.println("Creating access point failed");
        while (true);
      }
      server.begin();
      printStatus();
    }

    void loop() {

    }

    void printStatus() {
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
      Serial.print("To connect, join the network and open a browser to http://");
      Serial.println(ip);
    }
After uploading this, in the serial monitor I get this:

    Creating access point named: MKR1000
    Creating access point failed
I'm new to this so I really don't know what's the problem. I hope someone knows what's going on.<br>Thank you in advance.

title: Arduino MKR1000 as Access Point

Answers: 1

body:
I found [this reference][1] for `Wifi.beginAP()` in the [Wifi101 library][2], which I hope is the correct one - apologies if it's not.

It says that `beginAP()` returns either `WL_AP_LISTENING` or `WL_CONNECT_FAILED`, so checking for `WL_CONNECTED` is not sensible.

Try this:

    if (WiFi.beginAP(ssid) != WL_AP_LISTENING) {
      Serial.println("Creating access point failed");
      while (true);
    }

  [1]: https://www.arduino.cc/en/Reference/WiFi101BeginAP
  [2]: https://www.arduino.cc/en/Reference/WiFi101


body:
Just set up a replacement "Piduino" - a RPi3 connected by USB to an Arduino Uno.  The previous one was the victim of a Diet Big Gulp - spilled on the voltage divider breadboard.  Whoops.  The tiny breadboard with the voltage divider began to rust inside so it got really difficult to keep it working correctly.

This is for the plot named "Indoor 12V Lighting System" at https://www.SDsolarBlog.com/montage

I built a new Uno/breadboard from scratch and swapped it in with the breadboard stuck onto the plastic case.  All nice and tidy.

But the analog inputs were really strange.  It would read really close, but then minor changes to the software would produce wildly varying results.

Imagine my surprise when this morning I discovered that I had plugged the divider's analog input to A4 instead of to A1 where it belonged.

Now that it has been fixed all is well.  As long as the correct pin is being used in the `digitalRead` it seems not to matter, perhaps.

Here is the plot from before then after I moved the input to the correct location:

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

The actual voltage was falling from 12.7 down to 12.5, and after moving the pin it settled down to the correct reading.  Then I turned on the charger while the sun is up.  It is tracking the voltmeters perfectly now.

Clearly, the problem was that I was reading the wrong pin.  My fault, obviously. But it got me wondering just how much they affect each other.

So my question is about why I was getting any readings at all?  I would have hoped that the analog inputs were truly separate from each other.  Instead, it appears as if there is crosstalk of some kind.

Is this a common issue?

-----------------
**New information**

I see that it has been pointed out that this was discussed in this Q&A:

https://arduino.stackexchange.com/questions/574/should-all-unused-analog-input-ports-be-tied-to-ground-for-accurate-a2d-measurem

But since that does not call it an imperative, just "one of the problems with using analog" I would have assumed that this is not common, so perhaps there is an implied answer there.

It would be a project all by itself to use half the small breadboard to distribute ground to all the other analog pins.  And I've never seen this referenced in any of the documentation.  Nor is there a tag for crosstalk.

So my question still stands:  Is this common when measuring a DC voltage?

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

title: Interaction between Analog Pins when measuring a DC voltage- a common issue?

Answers: 1

body:
This is normal and expected behaviour.  There are a number of factors that influence it, and it will help to understand the basic internals of the ADC.

In simple terms the front-end of the ADC looks like this:

<!-- 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/0XYlM.png)

<!-- End schematic -->

The MUX selects which pin (A0-A5) is being sampled. Switch SW1 connects the *Sample And Hold* capacitor C1 to that selected input, which then charges (or discharges) to the same voltage as the input.

After the acquisition period switch SW1 switches position and the ADC circuit is connected to the capacitor.  Over a period of clock cycles the ADC works out what the voltage across the capacitor is and stores the result in the ADCH and ADCL registers.

Now - on a pin that has nothing connected to it, what voltage will be across that capacitor when SW1 is switched to charge it? Well, this is where your strange results come from:

1. Any charge already in the capacitor will *still be there* (which is why it can be good to connect the unused ADC pins to ground through a resistor, to remove that charge).
2. Signals, either in wires, IC pins, or the silicon circuitry in the chip itself, will be capacitively coupled with what is next to it.

That last one is the most critical for your results.  Capacitive coupling.

Place two wires next to each other and they will, through capacitance, try and get the same charge on them. Under most circumstances that attempt to influence the charge is completely swamped out by what is being send down the wire. But, when there is *nothing* being sent down the wire that charge becomes noticable. A1 will attempt to "float" to the same level as A0, because they're next to each other. A2 will try and float to the same level as A1, A3 to A2, etc.

If you put a signal in to A0 and plot all 6 inputs you will see each has a progressively lower amplitude copy of the signal. It's hopping, capacitively, between the pins. And all because there's nothing to stop it.

If you think "Ah, but it's DC. DC doesn't go through capacitors", then you're wrong.  Wrong in thinking it's DC.  There's a lot of mistaken assumptions about the labels "AC" and "DC".

DC is not what you have.  Yes, there is a "DC component" to what you have (which is manifest as the average of the voltage over time), but there is a large AC component as well.  That AC component is what you are graphing in the form of your changing battery voltage.

Voltage is far more complex than just DC or AC. What you think of as AC is actually a waveform with a fundamental frequency (e.g., 60Hz) and zero "DC offset". Add a DC offset to the signal and it's still AC, but compared to the "lower" end of whatever adds the DC offset, it's just the waveform is "shifted up".

Pure DC, and what doesn't pass through a capacitor, has no signal components. There is only 0Hz and nothing else. Pure DC is almost impossible to create without highly specialized equipment. All voltages in normal life vary, and that variance is the AC component of the signal.


body:
I have an Uno and Leonardo that I am trying to have it interact with the GTA V video game. Using the Keyboard library, it works within the OS. But it ocassionally works within the GTA V process. It seems that the transfer speed may be too slow, as the game sometimes registers the key press and does the assigned command.
For instance, I can have a pushbutton that when pressed, it activates **Keyboard.Write('J')**. While in GTA V, I can rapidly press the pushbutton for 3 seconds and the game will only detect one **J** within that time frame and do the assigned game command.
Yet, if I rearrange the code to be momentary to where the pushbutton is active, it'll constantly send **Keyboard.Write('J')**, this will work for commands that are momentary ingame, like the vehicle horn.
Below is the code I used for my Uno. It works fine within programs.

    /*
      Keyboard Message test

      For the Arduino Leonardo and Micro.

      Sends a text string when a button is pressed.

      The circuit:
      - pushbutton attached from pin 4 to +5V
      - 10 kilohm resistor attached from pin 4 to ground

      created 24 Oct 2011
      modified 27 Mar 2012
      by Tom Igoe
      modified 11 Nov 2013
      by Scott Fitzgerald

      This example code is in the public domain.

      http://www.arduino.cc/en/Tutorial/KeyboardMessage
    */

    #include "Keyboard.h"

    const int buttonPin = 4;          // input pin for pushbutton
    int previousButtonState = HIGH;   // for checking the state of a pushButton
    int counter = 0;                  // button push counter

    void setup() {
      // make the pushButton pin an input:
      pinMode(buttonPin, INPUT);
      // initialize control over the keyboard:
      Keyboard.begin();
    }

    void loop() {
      // read the pushbutton:
      int buttonState = digitalRead(buttonPin);
      // if the button state has changed,
      if ((buttonState != previousButtonState)
          // and it's currently pressed:
          && (buttonState == HIGH)) {
        // increment the button counter
        counter++;
        // type out a message
        Keyboard.write('J');
        //Keyboard.print("You pressed the button ");
        //Keyboard.print(counter);
        //Keyboard.println(" times.");
      }
      // save the current button state for comparison next time:
      previousButtonState = buttonState;
    }

I also tried this same test using LUFA but the same issues were encountered.
I believe it has to do with the game, not my code.
Does anyone have a clue of why this might be?

title: Interacting with a video game - Keyboard & LUFA

Answers: 1

body:
It is quite common for games to be quite slow at reading the keyboard.

The Leonardo's `Keyboard.write()` command is quite rapid. The OS can pick it up with its interrupt driven buffering, but games tend not to use that buffering so they can get more realtime key control.

The trick here is actually to slow down the Leonardo's sending, by not using `Keyboard.write()`. Instead you need to `press` the key, wait a moment, then `release` the key:

    Keyboard.press('j');
    delay(1);
    Keyboard.release('j');

Increase the delay until it becomes reliable. It's hard to say what the delay should be.


body:
How would you go about activating this button remotely?

This board is from the intercom in my apartment. The button when pressed unlocks the building door. I've just ordered the MKR IoT bundle (https://store.arduino.cc/arduino-iot-mkr1000-bundle). My plan is to learn the basics and figure out how to activate this button remotely.

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

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

title: How can I hack my intercom system to buzz people in remotely?

Answers: 1

body:
3 possible solutions:

 1. Connect the 2 contact for the button to a relay and control that relay from the arduino ([example][1]) But the kit you have doesn't include a relay.
 2. Use a transistor to trigger the switch -- I would not recommend this option as your first project.  It would be easy to damage the intercom and/or your arduino.
 3. Use the servo in the kit to physically press the button.  You will need to figure out the mechanical linkages but you don't need to attach wires to the intercom.

For a beginner project I would probably go with the third option.

  [1]: https://learn.adafruit.com/experimenters-guide-for-metro?view=all#circ11-intro


body:
I am using 4 Pololu VL6180X ToF sensors on the Arduino UNO for a school project but just can't seem to get it working correctly. I understand that I need to hold them in reset and change the I2C address of each sensor after waking them up, but the code I have doesn't work. Is the problem some flawed understanding of the C language?

This is the .h file I wrote (distSensors.h):

    /*
    This module is used to interface with the distance sensors.
    */
    #ifndef DISTSENSORS_FILE
    #define DISTSENSORS_FILE

    #include "vl6180x/VL6180X.h"
    #include "globals.h"

    // pins connected to VL6180 GPIO used to hold sensor in reset
    #define NORTH_SHUTDOWN 13
    #define EAST_SHUTDOWN 1
    #define WEST_SHUTDOWN 0

    // threshold distance for detectWall (mm)
    double const WALL = 70;

    // initializes sensor
    void initSensor(VL6180X* sensor) {
      (*sensor).init();
      (*sensor).configureDefault();
      (*sensor).setTimeout(500);
    }

    void changeAddress(VL6180X* sensor, int address) {
      (*sensor).setAddress(address);
    }

    // sensors
    VL6180X sensorNorth;
    VL6180X sensorSouth;
    VL6180X sensorWest;
    VL6180X sensorEast;

    void setupSensors() {
      // shutdown pins
      pinMode(NORTH_SHUTDOWN, OUTPUT);
      pinMode(WEST_SHUTDOWN, OUTPUT);
      pinMode(EAST_SHUTDOWN, OUTPUT);

      // hold each sensor in shutdown initially
      digitalWrite(NORTH_SHUTDOWN, LOW);
      digitalWrite(WEST_SHUTDOWN, LOW);
      digitalWrite(EAST_SHUTDOWN, LOW);
      delay(10);

      digitalWrite(NORTH_SHUTDOWN, HIGH);
      digitalWrite(WEST_SHUTDOWN, HIGH);
      digitalWrite(EAST_SHUTDOWN, HIGH);

      digitalWrite(NORTH_SHUTDOWN, LOW);
      digitalWrite(WEST_SHUTDOWN, LOW);
      digitalWrite(EAST_SHUTDOWN, LOW);

      // wake sensors and change address one by one
      // south is never shutdown, and its address is changed first
      changeAddress(&sensorSouth, 0x23);
      delay(10);

      digitalWrite(WEST_SHUTDOWN, HIGH);
      changeAddress(&sensorWest,0x25);
      delay(10);

      digitalWrite(EAST_SHUTDOWN, HIGH);
      changeAddress(&sensorEast, 0x27);
      delay(10);

      digitalWrite(NORTH_SHUTDOWN, HIGH); // NORTH maintains default address

      // init all sensors
      initSensor(&sensorNorth);
      initSensor(&sensorSouth);
      initSensor(&sensorWest);
      initSensor(&sensorEast);
    }

    // Return the distance reading from the given direction
    double getDist(int direction) {
      switch (direction) {
      case NORTH:
        return sensorNorth.readRangeSingleMillimeters();
      case SOUTH:
        return sensorSouth.readRangeSingleMillimeters();
      case WEST:
        return sensorWest.readRangeSingleMillimeters();
      case EAST:
        return sensorEast.readRangeSingleMillimeters();
      }
    }

    // return 1 if there is a wall, 0 if there is not a wall
    int detectWall(int direction) {
      if (getDist(direction) <= WALL) { return 1; }
      else { return 0; }
    }

    #endif

And this is the test code I'm running:

    #include "distSensors.h"
    #include "Wire.h"
    void setup() {
      // put your setup code here, to run once:
      Wire.begin();
      setupSensors();
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.print("NORTH: "); Serial.println(getDist(NORTH));
      Serial.print("SOUTH: "); Serial.println(getDist(SOUTH));
      Serial.print("WEST: "); Serial.println(getDist(WEST));
      Serial.print("EAST: "); Serial.println(getDist(EAST));
      delay(100);
    }

getDist returns 0.0 for every sensor except for sensorSouth.

Any help would be greatly appreciated, thanks!

title: Using 4 identical sensors on the I2C bus

Answers: 0


body:
I want to ask about Wemos d1 R1. Can I use those pins connected for different sensor?

For example I use pin D5 and D13 for switch and push button, or I use pin D7 and D11 for two different sensors.

Thanks.

title: Pin Mapped Wemos D1 R1

Answers: 0


body:
In my work, I have an ESP-8266, Arduino-Uno and a Relay. ESP 8266 and Uno is connected. Relay's data signal is take from arduino's 12th pin. ESP is powered from Uno.

If I use two different power sources for Uno and Relay, Relay does not response for the signal from Uno. (Both have a same common ground)

If relay is powered from Uno, then after load control (power on and off) ESP-8266 goes down.

title: Two power source for Arduino and a relay

Answers: 2

body:
The uno can't provide enough power to power an ESP8266 __reliably__.  I suggest you power it from a separate source.

When ever you use separate power supplies for a circuit you need to "tie the grounds together", connect them.  Otherwise the circuits don't use the same definition of zero.

body:
Use  a relay driver IC like ULN2003 to drive relay.
Here is a sample circuit diagram : [![enter image description here][1]][1]

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


body:
I am trying to get a sampling rate of over 10k Samples per second as well as send each sample over a serial line. Taking a sample and putting it on the serial line each time took too long. I am using Processing 3.3.6 for datalogging into a csv file. I am unable to achieve more than 6k samples per second even at lower prescaler value and high baudrate. What am I doing wrong? Here is my arduino code.

    int val[2000];
    void setup()
    {
      Serial.begin(250000);

      //ADCSRA = 0;             // clear ADCSRA register
      //ADCSRB = 0;             // clear ADCSRB register
      ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
      //ADCSRA |= bit (ADPS0);                               //   2
      ADCSRA |= bit (ADPS1);                               //   4
      //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
      //ADCSRA |= bit (ADPS2);                               //  16
      //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
      //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
      //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
      //pinMode(A0, INPUT);

    }

    void loop()
    {
      for(int i=0; i<2000; i++) {
        val[i] = analogRead(A0);
      }
      for(int i=0;i<2000;i++){
        Serial.print(val[i]);
        Serial.print('x');
      }

    }

P.S I am new to arduino.

--edit1>>
I am using Arduino Mega 2560.

title: Sampling and serial transfer

Answers: 1

body:
Probably the serial port is too slow:

Assuming 250 kbits/s, is (including 3 start/stop bits, maybe 2 in your case) in about 250000 (bits/s) / 11 (bits/byte)= about 22 KBytes/s
Assuming each sample has 3 or 4 digits and an 'x' is added (which is 5 characters), 22 (KBytes/s) / 5 (digits/sample) = about 5-6 Ksamples/s you can transfer, which is what you experienced.

So you have to increase the speed for the serial port.


body:
I am using Arduino Mega 2560 to sample and serially send a square wave. I am using Processing 3.3.6 for logging the data to .csv file. I am receiving about 6k samples at the moment. When I try sampling a square wave, min= 0V, max=3V at 200Hz, the number of samples at the two amplitudes(at 0 and 3V) are not at all close by. What could be going wrong?

This is my Processing code:

    //import the required libraries
    import processing.serial.*;

    Serial mySerial;
    Table table;
    String filename;

    void setup()
    { //print(0);
      //set mySerial to listen on COM port 4 at 1000000 baud
      mySerial = new Serial(this, "COM4", 1000000);

      table = new Table();
      //add a column header "Data" for the collected data
      table.addColumn("Data");
      //add a column header "Time" and "Date" for a timestamp to each data entry
      table.addColumn("Time");
      table.addColumn("Date");
    }

    void draw()
    { print(1);
      //variables called each time a new data entry is received
      int d = day();
      int m = month();
      int y = year();
      int h = hour();
      int min = minute();
      int s = second();
      //int s_prev=0;
      char d1 = 'a';

      if(mySerial.available() > 0)
      { //print(2);

        //set the value recieved as a String
        String value = mySerial.readString();
        //check to make sure there is a value
        if(value != null)
        {
          String[] parts = value.split("x"); //returns an array with the 2 parts

          //print(parts);
          //print('\n');
          for(int i=0;i<parts.length;i++)
          {

            String Part = parts[i];
            TableRow newRow = table.addRow();
            //place the new row and value under the "Data" column
            newRow.setString("Data", Part);
            //place the new row and time under the "Time" column
            newRow.setString("Time", str(h) + ":" + str(min) + ":" + str(s));
            //place the new row and date under the "Date" column
            newRow.setString("Date", str(s + 100));// + "/" + str(m) + "/" + str(y));
          }
        }
      }
    print(4);}

    void keyPressed()
    { print(5);
      //variables used for the filename timestamp
      int d = day();
      int m = month();
      int h = hour();
      int min = minute();
      int s = second();
      //variable as string under the data folder set as (mm-dd--hh-min-s.csv)
      filename = "data/" + str(m) + "-" + str(d) + "--" + str(h) + "-" + str(min) + "-" + str(s) + ".csv";
      //save as a table in csv format(data/table - data folder name table)
      saveTable(table, filename);
      exit();
    }

This is my arduino code:

    int val[2000];
    void setup()
    {
      Serial.begin(250000);

      //ADCSRA = 0;             // clear ADCSRA register
      //ADCSRB = 0;             // clear ADCSRB register
      ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
      //ADCSRA |= bit (ADPS0);                               //   2
      ADCSRA |= bit (ADPS1);                               //   4
      //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
      //ADCSRA |= bit (ADPS2);                               //  16
      //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
      //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
      //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
      //pinMode(A0, INPUT);

    }

    void loop()
    {
      for(int i=0; i<2000; i++) {
        val[i] = analogRead(A0);
      }
      for(int i=0;i<2000;i++){
        Serial.print(val[i]);
        Serial.print('x');
      }

    }

title: Improper sampling of wave

Answers: 1

body:
You are doing 2000 samples really close together in rapid succession with no concept of time between them, then you are spending a considerable amount of time sending that data through serial.

That's not how you sample signals.

Instead, you need to set up some kind of time-based periodic sampling system, either through a timer interrupt or some other facility provided by the ADC (read the datasheet to see what interrupts the ADC can generate and what sample trigger sources there are) which runs completely asynchronously.  Then when (and only when) a sample set has been captured do you send that data through serial.

If your sampling takes longer than your sending through serial (unlikely) and you have the memory for it you can set up two buffers and "ping-pong" between them so you are sampling at the same time as sending.  Otherwise, all you will be able to do is capture a short window of data and then send it afterwards, so you get short bursts of samples.


body:
For a project I need to design an digital band pass filter. I started of with this in Matlab:

    wch=1100*2*pi;
    wcl=1300*2*pi;

    sys=tf([1/wch 0],[1/(wch*wcl) 1/wch+1/wcl 1])
    sysd=c2d(sys,9615,'tustin')

    so I got this values:

    3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)

Then I rewrote it to:

    y[k] = 3.01*10^-8*u[k]-3.01*10^-8*u[k-2] -y[k-2]-2y[k-1]

and so I put hoped that this arduino script should do the Job:

    #include <TimerOne.h>

    float out;

    float second_filt(float x0) {
      static float y1=0;  // y[n-1]
      static float y2=0;  // y[n-2]
      static float x1=0;  // x[n-1]
      static float x2=0;  // x[n-2]
      float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2 ;

      // Shift values
      y2 = y1;  // Shift y[n-1] to y[n-2]
      y1 = y0;  // Shift y[n] to y[n-1]
      x2 = x1;  // Shift x[n-1] to x[n-2]
      x1 = x0;  // Shift x[n] to x[n-1]
      return y0;
    }

    void setup() {
      Timer1.initialize(32); //Initialize timer with a period of 32 us
      Timer1.pwm(9,0); // Use pin 9 for PWM
    }

    void loop() {
      if (isTime()) {
        out=second_filt(analogRead(0));
        Timer1.setPwmDuty(9,out); //Sets the duty cycle to the analog value on pin 0
      }
    }

    bool isTime(){ //Checks if 300 us elapsed since the last call
      static unsigned long t0=0;
      static unsigned long t1=0;

      t1 = micros();

      bool res = (t1-t0)>300;

      if (res) {
        t0 = t1;
      }
      return res;
    }

Now I don't know what the error: 'invalid operands of types 'double' and 'double' to binary 'operator^' means and I am not sure if this is actually gonna work. Pleas help me out I have been busy with this for days.

title: Digital Band pass filter arduino 1100-1300 Hz

Answers: 2

body:
You cannot use ^ as mathematical power symbol in C. Ini C it means the exclusive-or bit operation (hence the error showing it is a bit operation).

For the mathematical power function, you should use the math C library. See [library explanation][1]. To include it, use:

    #include <math.h>

The power function has the following prototype:

    double pow(double x, double y)
    Returns x raised to the power of y.

However if you only need to write a float/double in exponential format, you can use

    3.01e-8

  [1]: https://www.tutorialspoint.com/c_standard_library/math_h.htm

body:
You have more than one problem here...

> `3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)`

I don't quite understand your Mathlab code, but there is something wrong
with this transfer function. The denominator can be rewritten as
(z + 1)2. Thus there is a double pole at
z = −1, i.e. at the Nyquist frequency. An infinite gain at
Nyquist is not what you expect from a bandpass filter.

> `y[k] = 3.01*10^-8*u[k] - 3.01*10^-8*u[k-2] - y[k-2] - 2y[k-1]`

This is implementing the transfer function
3.01 × 10−8 (z2 − 1)/(z2 + 2 z + 1),
which is **not** the same as the one written above: mind the
parentheses.

> `float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2;`

As explained in Michel Keijzers’ answer, the constant should be written
`3.01e-8`. Also, you can save one multiplication by writing it as

    float y0 = 3.01e-8*(x0 - x2) - 2*y1 - y2;

> `if (isTime()) { out=second_filt(analogRead(0)); ... }`

You cannot expect to get a uniform sampling time with `analogRead()`, as
your timing will depend on how long your program takes to get trough the
loop, which is data dependent and affected by interrupts.

> sysd=c2d(sys,9615,'tustin')

I assume 9615 is the expected sampling rate, which translates to
104 µs between samples. This is the time it takes for the ADC to
perform one reading. You cannot achieve this rate if you do computations
_in between_ the readings.

Here your best option is to configure the ADC in _free-running mode_. In
this mode it will take one sample every 104 µs, and you will
achieve the desired sampling rate. You should also do the filtering _in
parallel_ with the readings, and have the CPU and the ADC work
concurrently instead of sequentially. For implementing this, you will
first have to read the datasheet of the ATmega328P powering your Uno.


body:
I use ESP8266 and ESP32 with arduino toolchain rather than pure arduino hardware.
Arduino IDE is standard and proven but what are the other IDE and advantage/disadvantage ?

title: Is there alternative to arduino IDE program ESP8266 and ESP32 with arduino toolchain?

Answers: 2

body:
For example, Eclipse IDE with Sloeber plugin is much better than Arduino IDE. You have all the features of Eclipse (coloring, error highlighting, auto-complete, open declaration ('drill down' to libraries), ...*). And every project has own settings (board settings, port, programmer ...). And the Arduino IDE buttons Upload, Verify, Session Monitor are there and the Arduino toolchain too.

*... projects management, version control, TODO lists, outline, ...

body:
Not an exhaustive list. Most **advantages** will be subjective.

 - [UECIDE][1] - Wide variety of boards, not only Arduino, better editor and serial monitor, plug-in based modules.
 - [PlatformIO][2] (Available as plugin for [Atom editor][3], [MS Visual Studio][4] and [Eclipse IDE][9]) - Automatic library updating, one `ini` file that defines project settings and external libraries, making projects portable to other users without having to download all external libraries.
 - [Arduino IDE for Visual Studio][5] - For those who like VS?
 - [Arduino Makefiles][6] - More like old-school command-line coding, Linux-style development. Not an IDE.
 - [Eclipse][7] - Another quite popular IDE outside Arduino world.
 - [Atmel/Microchip Studio 7][8] - Provided by the manufacturer of the AVR chips. "Arduino" sketches may not compile without changes to make them more like standard C++.

  [1]: https://github.com/UECIDE/UECIDE
  [2]: https://platformio.org/platformio-ide
  [3]: https://github.com/atom/atom
  [4]: https://www.visualstudio.com/
  [5]: https://marketplace.visualstudio.com/items?itemName=VisualMicro.ArduinoIDEforVisualStudio
  [6]: https://github.com/sudar/Arduino-Makefile
  [7]: https://www.eclipse.org/community/eclipse_newsletter/2017/april/article4.php
  [8]: https://www.microchip.com/avr-support/atmel-studio-7
  [9]: http://docs.platformio.org/en/stable/ide/eclipse.html


body:
Looking at the pinout for the Arduino MEGA:

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

I see that Pins 20 and 21 can be both SDA and SCL or Interrupts 0 and 1.

If I'm using an [Adafruit I2C 16x2 RGB LCD Shield][2] connected to the SDA and SCL pins by the USB Jack, is there anything I can do in my code to still use INT0 and INT1 off Pins 20 and 21 for a different purpose?

  [1]: https://i.stack.imgur.com/bBUfz.png
  [2]: https://www.adafruit.com/product/716

title: MEGA I2C and interrupts on 0,1

Answers: 1

body:
No, there is nothing you can do.

Both the SCL pins and both the SDA pins are physically connected together by copper tracks. They are in effect the same pin. If you use I2C you can't use INT0 or INT1. You have INT2 and INT3 though (pins 18 and 19), as well as Pin Change Interrupts on a large number of other pins.


body:
First off, I'm very new to Arduinos and electronics in general, so feel free to explain like I'm 5.

As a bit of background to this question, the project is simply using a Pro Mini to run a servo, with a button to turn it on and off, and an led to indicate when it's on. To make sure I was getting the button right, I built the circuit on a breadboard with just the button and LED. The button was supposed to switch the LED on and off. It did not.

I removed the button from the equation and **just tried to power the LED with the Mini. No go.**

It's a **blue LED**, so the **resistor (100)** was chosen **assuming a forward voltage of 3.3V and current of .02A**. **I've tested the resistor and LED combo** with JUST the battery pack, and it lights up bright like it should.

I have a **9V battery running into RAW** (I've also tried a 6V pack). I had **pin 2 as an output with digitalWrite(HIGH)**, running into the resistor, then into the LED (+, long end), and then back to a ground pin. I've tried other ground pins on the board to make sure it's not that. **I've switched pin 2 to analogWrite(255)**, still nothing. **I have tried connecting it to VCC** instead. Nothing.

However, **writing HIGH to the onboard LED works fine**, so I can see that the sketch is indeed running.

**I've verified the LED polarity. I have tried a different Pro Mini**. Nothing. It's a **Pro Mini 328P** according to the stamp on the back, which **Google says runs at 5V and 16 MHz**.

Please tell me what stupid mistake I am making so I can stop wanting to rip my hair out. Thank you.

title: Why is Arduino Pro Mini not powering this LED?

Answers: 1

body:
This was my mistake. I had attached the Arduino to the breadboard by pushing in the provided pin strips, and then putting the mini on top of those, assuming that since the pin was through the hole and looked to be touching, a connection was made. It wasn't.

Rather than continue to mess around with fiddly connections, I just took the plunge and soldered the entire thing to a circuit board. The LED and the button work perfectly as expected, and now I just need to attach the servo.


body:
I've just bought NodeMCU LoLin ESP8266, I tried to send AT commands (after spending days on ESP8266-01) and everything was okay. Than I've uploaded the Blink example to the board, after that moment it's not responding to any command.

I tried to update firmware, it's updating successfully but nothing has changed. By the way blink app is not working also...

title: NodeMCU not responding AT after blink app

Answers: 1

body:
If you replaced AT firmware in esp8266 with Blink and you want it back, download the AT firmware from [Espressif download page][1] and flash it with the [Espressif Flash Download Tool][2] (Windows) or with [esptool.py][3].

  [1]: http://espressif.com/en/support/download/at?keys=&field_type_tid[]=14
  [2]: http://espressif.com/en/support/download/other-tools
  [3]: https://github.com/espressif/esptool


body:
I am trying to add two 16 digit binary numbers together. Each binary number will have been entered by the user and saved as: `int binaryOne[16] and int binaryTwo[16]`. Originally,

    int binaryOne[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

are the values declared. Then, the user has the option to change these values using buttons that I implement before the Solution() function. So, once the used gets to the Solution() function, the numbers may be stored as:

    int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
    int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

This is what I have so far:

    void Solution() {
      /*
        Rule of binary addition:
        0 + 0 = 0
        1 + 0 = 1
        0 + 1 = 1
        1 + 1 = 1 and carry = 1
       */
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Solution");
       lcd.setCursor(0,2);

        int a[16] = binaryOne[16];
        int b[16] = binaryTwo[16];
        int i = 0;
        int remainder = 0;
        int sum[32];

        while(a[16] != 0 || b[16] != 0){
          sum[i++] = (a[16] % 10 + b[16] % 10 + remainder) % 2;
          remainder = (a[16] % 10 + b[16] % 10 + remainder) / 2;
          a[16] = a[16] /10;
          b[16] = b[16] / 10;
        }
        if(remainder != 0){
          sum[i++] = remainder;
        }
        i--;
        while(i>=0){
          lcd.print("%d", sum[i--]);
       }
       return 0;
    }

I believe I am doing something wrong with calling the arrays since I am renaming them to a[16] and b[16] within this function. I'm also curious, since I only have 16 bits of space on the screen, what if the user enters a binary number such as 1111111111111111 + 1000000000000000 and therefor there is going to be a carry on that first digit? Would it be best just to have an error message?

title: C++ Adding Two 16 bit binary numbers together

Answers: 2

body:
You're making a mountain out of a molehill.

You're trying to manually manipulate binary digits in an array, but C can already manipulate binary digits. Everything is binary already - you just need to represent it as such.

All you need to do is convert the contents of your array into an actual number, then do simple mathematics on that number.  One of the simplest ways of doing that is to shift the bits into a variable:

For instance:

    int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
    int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

    uint16_t binOne = 0;
    uint16_t binTwo = 0;

    for (int i = 0; i < 16; i++) {
        binOne <<= 1;
        binOne |= binaryOne[i];
        binTwo <<= 1;
        binTwo |= binaryTwo[i];
    }

Now you can add them together, since they're just numbers:

    uint32_t result = binOne + binTwo;

And you can output it as binary:

    Serial.println(result, BIN);

If you want to convert back into an array again (why?!) you can just do the opposite as before:

    bool resultBin[32];

    for (int i = 0; i < 32; i++) {
        resultBin[i] = (result & (1 << (31-i))) ? 1 : 0;
    }

body:
A few issues here:

1. The way you “rename” the arrays is wrong, and furthermore there is no
   point in doing such renaming.
2. There is no reason to divide by 10 (ten, in decimal) within your
   code: as everything you do is binary, the number _ten_ has nothing to
   do with what are trying to accomplish.
3. While doing the addition, you forgot to _loop_ over the bits.
4. You shouldn't `return 0` in a function of type `void`. In fact, you
   shouldn't return any value.

Fixing those issues should give you something similar to this:

    void Solution() {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Solution");
        lcd.setCursor(0, 2);

        // Compute the sum.
        int sum[16];
        int remainder = 0;
        for (int i = 0; i < 16; i++) {
            int s = binaryOne[i] + binaryTwo[i] + remainder;
            sum[i] = s % 2;
            remainder = s / 2;
        }

        // Print it.
        for (int i = 15; i >= 0; i--) {
            lcd.print("%d", sum[i]);
        }
    }

Note that there is no point in computing a 32-bit result if you can only
print 16 bits: just accept that the computation is done modulo
216, just like a 16-bit ALU would do, or the `unsigned int`
data type in the Arduino.

Of course, the whole idea of doing the computation one bit at a time is
highly inefficient. See Majenko's answer for a more idiomatic and
efficient way of managing numbers bit-wise in C and C++.


body:
[![Arduino Uno Schematics][1]][1]

Can anyone tell me why 1k resistor is used on pin 13 of ATmega16U2 in arduino uno schematics. I have also seen a 100k resistor used in this position?

  [1]: https://i.stack.imgur.com/494pj.png*

Link for schematics - https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

title: What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info

Answers: 2

body:
Its a pulldown resistor!

Comment there says "USB Boot Enable" so safe assumption that it's an digital pin.

They're handy because they mean if there is no input to whether that pin is headed, the voltage at the pin will be 0 instead of floating.

The value doesn't matter too much, "When in doubt 10k it out" is a pretty well known saying around electronics people, meaning just use a 10k Ohm resistor and you'll be fine.

body: Pin 13 of the USB interface chip is connected to RESET line of the ATMEGA328 MCU. I would guess (also from "USB boot En" label) that pressing/issuing board reset gives the USB interface an interrupt (INT7), such that USB bootloader gets activated and the ATMEGA328 can start loading firmware code over USB. The resistor is a pull-down resistor ensuring LOW signal, and its value shouldn't matter much. However, there is a capacitor (C5) which provides a short pulse to the interrupt line. This is not the best way to form a digital signal and initiate an interrupt, but the RC should be long enough, so I would expect that if 100k is used, the cap can be much smaller than 100n as in 1k case.


body:
I am new to Arduino and I am making a Walking Quadruped using BotBoarduino as microcontroller.
I want to install an Ultrasonic Sensor HC-SR04 so that it will stop when an obstacle is detected.
I have connected the sensor to Arduino UNO. RX-TX of both the boards are cross-connected. Now I have written this code for UNO:

    const int trigPin = 9;
    const int echoPin = 10;
    // defines variables
    long duration;
    int distance;

    void setup() {
      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
      pinMode(echoPin, INPUT); // Sets the echoPin as an Input
      Serial.begin(9600); // Starts the serial communication
    }

    void loop() {
      // Clears the trigPin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      // Sets the trigPin on HIGH state for 10 micro seconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(100);
      digitalWrite(trigPin, LOW);
      // Reads the echoPin, returns the sound wave travel time in microseconds
      duration = pulseIn(echoPin, HIGH);
      // Calculating the distance
      distance= duration*0.034/2;
      // Prints the distance on the Serial Monitor
      Serial.println(distance);

      delay(200);
    }

And I am doing this on BotBoarduino:

    int byteRead;

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

    void loop() {
      while (Serial.available())
      {
        byteRead = Serial.read();
      }

      if(byteRead >= 10)
      {
        walk();
      }
      else
      {
        stand();
      }
    }

Whenever distance = 10 or above, let it walk. Else stop.

But it's not working. It's not stopping on obstacles. Sensor is doing its work perfectly, but I think Botboarduino is not getting the values.

Any idea guyz?

title: Connect BotBoarduino with servos and Ultrasonic sensor HC-SR04

Answers: 1

body:
You have a misconception, how the Serial interface works.

The Serial interface is basically a stream of bytes (and sometimes start/stop and parity bits, which you normally don't care about) without any structure. This has to be implemented by you.

Also you have to understand, that you don't and cannot know, when a specific byte actually is being send. The fact that you typed a complete string into the serial monitor (or send a string via one call for `Serial.println()`) does NOT mean, that they are transmitted as a complete packet. The bytes of the string are send one after another and there may be a short delay between two arbitrary bytes. So with your reading `while()` loop, you are reading bytes until there is a delay long enough for the microcontroller to notice or until the message is send complete. You cannot know, which is the case for this very specific transaction. Also it seems odd, that you are only using the last read byte in your code, since the variable `byteRead` is overwritten on every `while()` loop cycle.

Then there is the format, in which you can send data through Serial.

 1. **Binary data:** Since it is a byte stream, you can directly use the binary values of the bytes to reflect the data. This is easy and good for cases, in which only one value of the size of one byte is transfered every time. So there is no need to distinguish between different parts of the message. In this case you have to use `Serial.write()` on your sending end. This will write binary data. (You will not be able to see the values in your serial monitor, since it is displaying only ASCII-encoded characters).
 2. **ASCII-encoded data string:** You are using `Serial.println()`, which sends an ASCII-encoded string representing the data followed by a NEWLINE character ('\n'). In case of the value `10` you are currently sending 3 bytes: '1', '0', '\n'. In this method, you are using a delimiter character (in this case '\n') to mark the end of a message. On the receiving end you have to read all bytes into a buffer, until you are receiving the delimiter character. Then you can process the message as a whole. In your case you would convert the ASCII-encoded string into an integer variable (for example with the function `atoi()`)

To exactly explain, what is happening with your code: As Chad wrote in his comment, you are trying to use the binary value of a byte, that is an ASCII-encoded character. When looking at an ASCII table, you can see, that there is no printable character with a binary value under 10. So, since you send only printable characters with `Serial.println()`, There will never be a value, that is under 10.

So now you have 2 options:

 1. Send the variable as binary data in one (!!!) byte (since you are not using distances as big as 255cm the value can fit in there; just make sure, that the byte variable does not roll over) and use every read byte on the receiving end for your code.
 2. Send the variable as ASCII-encoded data with `Serial.println()` and do the correct processing of the resulting message on the receiving end. Refer to the Serial examples in the Arduino IDE for this. You can directly integrate their code into yours.


body:
Like make for not ESP Arduino target, is there a CLI command like **esptool.py** to upload in the hardware ?

I've seen [**makeEspArduino**](https://github.com/plerup/makeEspArduino) but seems to be not trivial ?

What about [**espressif ESP32** component](https://github.com/espressif/arduino-esp32/blob/master/docs/esp-idf_component.md) ?

Is [**Visual Micro** Arduino CLI (Command Line Interface)](http://www.visualmicro.com/page/Visual-Micro-Command-Line-Interface.aspx) tool mature ?

title: How to compile Arduino ESP8266/32 on CI/CD (CLI shell cmd) platform?

Answers: 1

body:
Easiest answer: Use [PlatformIO][1]. (Yes this answer is technically an advertisement, but it *is* the correct solution here.).

*Why not the others?*

* `makeEspArduino` is dependent on GNU `make`, hard to make modification to, hard to get support for when something goes wrong
* Visual Micro Arduino is Visual Studio extension, thus native to Windows

*Why PlatformIO?*

On the other hand, PIO is just a framework written in python2, runs on Windows, Mac & Linux alike and supports tons of boards and frameworks. Not only is it OS-agnostic but it also IDE agnostic. It exports project files for Eclipse, Visual Studio Code, CLion, Visual Studio, Sublime, Atom and other IDEs. The Arduino IDE will always be only a (bad) syntax highlighter.

Support boards (479 of them) range from Arduino Unos to ESP8266/ESP32 over to STM32 and nRF boards. It's also possible to compile one firmware for different environments (board), so with a well-written firmware, PIO can generate firmwares for multiple boards and frameworks alike. Frameworks include Arduino cores, ESP-IDF, STM32HAL and more.

To create a new project, you'd do

    user@somefolder/$ pio init --board=nodemcuv2 --ide=vscode

To compile from CLI, you just have to execute the `run` target:

    user@somefolder/$ pio run

To upload you'd just

    user@somefolder/$ pio run -t upload

With optional `--upload-port=/dev/ttyUSB0` or alike. Updating wirelessly over ArduinoOTA is also supported.

Video: https://www.youtube.com/watch?v=EIkGTwLOD7o

Documentation: http://docs.platformio.org/en/latest/

  [1]: https://platformio.org/


body:
Sup yo.

I have my Adafruit Bluefruit Feather all wired up.  It's lovely.  I've got it responding to commands over the USB serial, activating an array of octocouplers.  It's terrific.  Here's the thing though.  I need to talk to it wirelessly.

I can only pair it (MacOS) the Adafruit Bluefruit LE Connect app.  It doesn't show up in my Bluetooth preference pane.

`$ ls /dev/tty.*`  shows `/dev/tty.Bluetooth-Incoming-Port` and the Arduino IDE can see it.  Unfortunately the word *Incoming* is right there in the middle of that port name.  Sending commands through the Arduino serial monitor doesn't seem to do anything.

The Bluefruit connect app appears to be able to send commands over something called UART but my board doesn't respond to the stuff that works over USB serial.

How do I talk to this board over Bluetooth?

title: how to send data to Adafruit Bluefruit Feather (32u4) over bluetooth?

Answers: 2

body:
First you should do some research on just what Bluetooth LE is.  First and foremost, what it is not, is a serial port.

In fact the BLE specification has no concept of serial ports, not like the old Bluetooth 2.x SPP specification.

Yes, you can use it *like* a serial port, but the point I am making is there is no GATT profile for serial data transfer. Every module manufacturer has their own way of doing it, so it's down to your application to implement that method (usually using libraries provided by the manufacturer). You can't present BLE as a serial port (COM3, /dev/rfcomm0 etc).

Sure, you could write a daemon that connects the MFG's custom method to a PTY and make it look more like a serial port (and such a thing may already exist in the community for some devices), but it will only ever work with that device and never any other device. There is no serial - there is only serial emulation and it's specific to the device. If it were standard no doubt someone would write a driver for it - like SPP of Bluetooth 2.x. But with GATT you just don't get that standard facility.

BLE is intended for sending short packets of data back and forth using minimal power. Many manufacturers have chosen to create a profile that can be used in a similar way to a serial port (in that you send data through a virtual "pipe"), however you require special software to interface with it. And, since there is no standard, and manufacturers just don't talk to each other, the software is specific to the device you are talking to.

If you are directly programming a BLE chip itself with your own firmware there is nothing to stop you from implementing your own protocol for serial data transfer and writing an application, driver, daemon, whatever, for communicating with that custom firmware. The same thing stands though: whoever wants to use it will require *your* specific application to communicate with it.

The only people who want to use BLE for serial are people like us. Everyone else (that's 99.999% of the market) uses it for what it is intended - connecting sensors and HID devices to mobile phones etc. That's why all the GATT profiles are for such things as heart rate, blood sugar levels, cycle speed, etc.

So no. You can't use it like a serial port. It's not a serial port. The only foolproof way (and the way to which I have resorted in the past) is to create a USB dongle that exposes a CDC/ACM interface to the computer, and contains a BLE module that is capable of communicating directly with a similar BLE module through its own proprietary profile (the one I use has a "transparent UART" mode when two modules are paired together). The MCU in the dongle then forwards data between the computer and the BLE module.

body:
The “UART” being referred to is the [Nordic UART GATT Service](https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/uart-service). This is not a serial port or USB connection. It is a high level BLE protocol that *simulates* a serial port via the Bluetooth connection.

In order to connect to the device from your Mac you’ll need to write some C or Obj-C. I’ve done this for Windows, but not a Mac, so I’m afraid I can’t give you detailed instructions. However, [the source code for the iOS Adafruit Bluefruit LE Connect app](https://github.com/adafruit/Bluefruit_LE_Connect) you’re using is open source and should be a good starting point.

Be warned of a few things though.

 1. You’re going to have to learn a bit about the BLE protocols and standards. It’s not exactly for the faint of heart.
 2. Apple throttles the speed/throughput of BLE for their iOS devices (as does Android) to protect battery life. I don’t know if they apply the same throttling to their laptops. You may not be able to achieve a satisfying data rate if you’re looking to create a high throughput “data pipe”.  With Win10 and the Bluefruit LE I was able to achieve 40 bytes every 30ms. You’ll likely be limited to 20 every ~30ms.

    If you’re looking to just send some occasional text (maybe AT style) commands to the device via BLE though, you won’t come close to those limitations.


body:
I have a project in which several Arduinos will be running independent programs. I would like to use an Arduino Mega as the main controller. It will receive input from a variety of switches, as well as data input from 2 Arduino Unos and 3 Arduino Nanos.

Each Nano will run a basic collection of switches and LED displays.

Each Arduino Uno will be connected to a 2 axis joystick and will have several button inputs from the joystick, as well as several 7 segment Led displays and several LED indicator displays.

The Mega would need to gather information of at least 16 bytes from each slave at highest possible speed, and be able to transfer at least 16 bytes to each slave at the same rate. I would also need the clock signal for all devices to default to the Mega.

What would be the best way to begin setting up the program logic to get these boards to interact in a smooth manner without a lot of lag in communication between boards?

Also, what would be the limitations on speed with this sort of com setup between the boards?

If more setup or function information is needed I can add description, just didn't want this post to be overly lengthy.

title: Linking Mulitiple Arduino's

Answers: 1

body:
Why do you need so many Arduinos, Nanos and a Mega?  You want to read/control 2 joysticks, some switches and some LED.  If you do this using a multi-processor environment then you are adding a significant overhead to the processing and the development time which you can probably do without.

So, could you connect everything to a Mega, do you have enough IO pins?  If not would the use of GPIO expander ICs, I2C devices, etc help solve this issue.

Connecting the joysticks via interrupts will allow a more responsive system, can you do this?

Is an Arduino even the best platform for this?  What about an ESP32 or PI?

You want to minimise the comms overhead, so a star network would be better than a ring.
Serial is going to be the lowest programming overhead solution, but by far the slowest.  Using WIFI via an ESP8266 is going to be the simpelist and you can hand off some of the processing to the ESP.


body:
I am using this code to generate a square wave with Arduino and shift it by 90 and 180 degrees. However, this code is not able to shift it to 270 degrees. Could you please suggest how may I modify the code so that it supports a 270 degrees square wave phase shift operation.

    void setup() {
      pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
      pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B
      // Both outputs in toggle mode
      TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );
      // CTC Waveform Generation Mode
      // TOP=ICR1
      // Note clock is left off for now
      TCCR1B = _BV( WGM13) | _BV( WGM12);
      OCR1A = 0;    // First output is the base, it always toggles at 0
    }
    // prescaler of 1 will get us 8MHz - 488Hz
    // User a higher prescaler for lower freqncies

    #define PRESCALER 1
    #define PRESCALER_BITS 0x01
    #define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

    // Output phase shifted wave forms on Arduino Pins 9 & 10
    // freq = freqnecy in Hertz (  122 < freq <8000000 )
    // shift = phase shift in degrees ( 0 <= shift < 180 )
    // Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC
    /// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.
    int setWaveforms( unsigned long freq , int shift ) {
      // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.
      unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave
      ICR1 = clocks_per_toggle;
      unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision
      OCR1B= offset_clocks;
      // Turn on timer now if is was not already on
      // Clock source = clkio/1 (no prescaling)
      // Note: you could use a prescaller here for lower freqnencies
      TCCR1B |= _BV( CS10 );
    }
    // Demo by cycling through some phase shifts at 50Khz
    void loop() {
      setWaveforms( 40000 , 0 );
      delay(1000);
      setWaveforms( 40000 , 90 );
      delay(1000);
      setWaveforms( 40000 , 180 );
      delay(1000);
    }

title: Arduino Square Wave Phase Shift by 270 degrees

Answers: 1

body:
The Arduino can only shift across a range of 180 degrees in CTC-mode using a 16 bit Timer. If you shift one channel to 90 degrees (other OCR set to 1, not zero) and then add a logic-inverter, you'll get the equivalent of 270 degrees as mentioned by Edgar Bonet.

As for using FOC (forced output compare), Edgar B. is again correct. It's possible to preset a channel as inverted, then perform the shift with an OCR set for 90 degrees -- you won't need an extra logic inverter. But this method is not for someone new. You'll want an O-Scope handy to make it work (and some time to study FOC and CTC mode-12).

I think it easier to use a single section from a 7404 hex-inverter to flip your 90 degree shifted waveform to 270.

Search for "Phase Shift Square Waves" and you'll find a VIDEO (as of 2022) for an example project that uses FOC tactics to create runtime-adjustable phase shifts on an Arduino. Perhaps you'll see a way to make an easy code change for the flipped-phase you want...

FWIW `stockvu`