Arduino Ethernet shield cannot establish connection I bought a Chipdot Ethernet shield from Amazon. It does not have any MAC address on it. I connected this shield to an Arduino Uno. I tried to run the DHCPAdressPrinter code from Ethernet library on it, using the default MAC address of this code. And Serial monitor shows

  Failed to configure Ethernet using DHCP

I have tried all the MAC IDs one by one as suggested on reviews but nothing worked. Is there any way to configure or assign a MAC ID to the Ethernet shield? Or is there are any way to know the Ethernet shield's  MAC address?

Thanks in advance.

The W5100 chip doesn't have a mac address by itself. You can assign any mac address to it that you want. With Ethernet.begin(mac); you assign the mac address to the W5100 chip.
The official Arduino Ethernet shield comes with a paper with a unique mac address. That is a nice service, but that is just a number, the Ethernet shield hardware is without any mac address.

There has been complaints about wrong resistor values near the ethernet connector. Can you read the numbers on those resistors ? They should be labeled as "510" and not as "511" : Arduino forum about ethernet resistors.

The Ethernet Shield uses more power than most other shields, and the W5100 can get pretty hot. Do you have enough power ? Is the 5V pin still above 4.5V ?

It is possible that your router does not accept the old W5100.

If the resistors are okay, I suggest to try an example with both mac and ip: Ethernet.begin(mac, ip);


avrdude: stk500v2_getsync(): timeout communicating with programmer error When I try to upload I get this error. I cannot upload the program into my Arduino Mega ADK board. I tried putting the drivers agiain too, but it does not work.

avrdude: stk500v2_getsync(): timeout communicating with programmer

Is it the problem with the hardware or the system?
Please help me. Thank you :)

I get this problem sometimes with some of my boards. I usually solve the problem following these steps:

Set the compiler on debug/verbose mode to see what's happening
Launch compilation/upload
When the compile phase is done, and the upload process is about to start, press the reset button on the board

Usually that takes care of the problem.


How to change Multiple variable values through Serial Monitor I am trying ... with minimal success to change/Check and also run voids through the serial monitor .the code i  put i am having probles is that when i am try to send a value larger than 9 the value assigns a diffrent number Ex i set to 200 but arduino sets it as 512.. i got around it deviding the value by 1.6 and got me the new number and only works upto 90 , but i am tryn to see how it should be done correctly...

const uint16_t inputLength = 512;
int ss = 0;
int bHold = 0;

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

 void loop() {
  if ( Serial.available() > 0 )
  {
    static char input[inputLength];
    static uint16_t i;
    char c = Serial.read();

    if ( c != '\r' && c != '\n' && i < inputLength - 1)
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      uint16_t array[80];
      uint16_t j = 0;

      if ( !strncmp(input, "ss", 2) )
      {
        char* p = input + 2;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10); //< changed from 16

        for ( uint8_t i = 0; i < j; i++ )
        {
          ss = array[i];
          Serial.println(ss);
        }
      }

      if ( !strncmp(input, "bHold", 5) )
      {
        char* p = input + 5;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10);   //< changed from 16

        for ( uint8_t i = 0; i < j; i++ )
        {
         bHold = array[i];
        // bHold=bHold /1.6;
         Serial.println(bHold);
        }
      }

      if ( !strncmp(input, "Whos There", 10) )
      {
        Serial.print("me");
      }
      if ( !strncmp(input, "hello", 5) )
      {
        Serial.print("hi");
      }
      if ( !strncmp(input, "sa", 2) )
      {
        Serial.print("  ss= ");
        Serial.print(ss);

        Serial.print("  bHold= ");
        Serial.print(bHold);

        Serial.println(" ");
        Serial.println("==============================");
      }
    }
  }
}

Thank you for any tips you can give...

EDIT: I am trying to pass a new value with command on the serial monitor "ss 500"..so that in the arsuino ss = 500. but in this case it makes it equal to 1280.

EDIT2: Chaged the strol to 10...works perfectly ...Thank you TisteAndii!!!!

You are setting the input string's base to 16 instead of 10 in your strtol conversions, which is why you are getting 1280 when you expect 500.


Lowering delay when sending multiple SMS I would like to use Arduino for bulk SMS sending. Right now, when I'm sending an SMS with 160 characters, I have to delay the sending of the next one for 9500 milliseconds. If I don't do that, some of the messages do not get sent. Is it possible to somehow lower that delay (by changing my code, using a different Arduino or SIM model, etc)?  I am using Arduino Uno and SIM800L (external power supply). This is my code.

#include <SoftwareSerial.h>

#define SIM800_TX_PIN 11
#define SIM800_RX_PIN 10

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  int a;
  String b =  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu eleifend nunc. Suspendisse eget eros metus. Nunc ut nunc vel enim placerat egestas. Sed molestie, sapien sit amet bibendum --";
  String d = "";
  int textLen;

  Serial.begin(9600);
  while(!Serial);

  serialSIM800.begin(9600);

  for (a =1; a < 5; a++) {
    textLen = b.length()+2;
    char c[textLen];
    d = "";
    d = b + a;
    d.toCharArray(c,textLen);
    serialSIM800.write("AT+CMGF=1\r\n");
    delay(200);

    serialSIM800.write("AT+CMGS=\"+381*******\"\r\n");
    delay(200);
    //Send SMS content
    serialSIM800.write(c);
    delay(200);

    //Send Ctrl+Z / ESC to denote SMS message is complete
    serialSIM800.write((char)26);
    delay(9500);

    Serial.println("SMS Sent!");
  }
}

void loop() {
}

It because a single SMS has 160 character limit. If you send more than 160 characters, those are transmitted by a process called concatenation(just googled out).
You can send at a faster rate by avoiding this process and sending 2 different messages which are of length less than 160. Hope it satisfies your query.


Arduino HTTP Post request I have a Arduino Mega with Wiznet 5100 Ethernet shield. Am trying to post some data onto localhost for started later on which will be accepted by a website.
But when I try to post the data I get some error. When I try to send the same data via postman it gets accepted . But when it goes from arduino error occurs.
The arduino Code is as follows:

client.println("POST /api/trackers/5a28eddaf57a6e2060e85601/solars/5a3bb2adf57a6e1a71ca135b/arduino_data HTTP/1.0");

client.println("Host: 192.168.6.16");

client.println("Accept: application/vnd.mirasol.v1");
Serial.println("After Accept application vnd");

client.println("User-Agent: Arduino/1.0");
Serial.println("After User Agent Arduino");

client.println("Accept: application/json");
Serial.println("After Accept application json");

client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

client.println("Content-Type: application/json");
Serial.println("After content type application json");

client.println("Connection: close");
Serial.println("After connection close");

client.println();
Serial.println("After client println");

client.println(postdata);
Serial.println("After post data");
Serial.println(postdata);

The output in the serial monitor is as follows:

    connecting...
connected
After Accept application vnd
After User Agent Arduino
After Accept application json
After content length
After content type application json
After connection close
After client println
After post data
{"current":10.50, "voltage":10.50}
H
disconnecting.

And the error shown in localhost is as follows:

2017-12-27 15:21:57 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>

I have the application in Ruby on Rails with Mongoid as the DB.

FYI: New to coding..

Your problem most likely stems from this bit:

client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

You have an extraneous "ln" in there causing the post data length to be on a separate line from the Content-Length:

Content-Length:
23

You should change the first println to a print. Also the order could do with changing to keep things logically grouped:

client.print("Content-Length: ");
client.println(postdata.length());

Serial.println("After content length");

Which would result in:

Content-Length: 23


Help with simple gradually brighter flickering led im a newcomer for arduino and sorry for any grammar error.
So what im trying to do is replicating a flickering effect found on spacecraft thruster when they about to take off where the fire bursting from dim to bright with flickering,similiar to afterburner on aircraft model which use neopixel led but this time only using common led.
I could mimic the flickering on the led with various  brightness level using the simple analogWrite,the problem is i cant really merge them since i use delay which is affecting how fast the flickering effect is and i need 1 sequence of flickering to stay a while before going next to brighter flickering and so on.
My code is quite too simple

    Int led = 9;
    void setup () {
    pinMode (led, OUTPUT);
    }

    void loop() {
    {analogWrite (led, random (10,15));
    delay (30);}

    }

Im thinking adding a new line with higher random led states (ex. 50,100) should be okay,but then the delay which affect the flickering speed are too short and making both line merging useless since its will go to the brightest in no time.
Is there's any way to hold the first dim line for an amount of time then continue to the next brighter line and so on without affecting the filckering delay?
Any help will be appreciated

Thank you!

Before using millis() you can try to create the thruster effect with delay().

I think 40Hz update rate for the led should be enough.
The sketch starts with a random value between 5 and 15 and ends with a random value between 80 and 256.
The part in the middle that gradually increases between those values is a mathematical problem.

// Led mimic spacecraft thruster.
//
// Update rate 40Hz for the led.
// That is a delay of 25ms.

#define RATE 40  // update rate of led in Hz
const int ledPin = 9;   // it must be a PWM pin !

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

  Serial.begin(9600);

  randomSeed(analogRead(A0));
}

void loop() {
  int n;

  Serial.println("10 seconds low brightness");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(5,15));
    delay(1000/RATE);
  }

  Serial.println("5 seconds gradually brighter");
  n = 5*RATE;
  for(int i=0; i<n; i++) {
    //   random start: from 5 to 80     (75 increase)
    //   random end  : from 15 to 256   (241 increase)
    //   The calculation is with long, it might not fit in a 16 bit integer

    int random_start = 5 + int((long(i) * 75) / long(n));
    int random_end   = 15 + int((long(i) * 241) / long(n));
    analogWrite(ledPin, random(random_start,random_end));
    delay(1000/RATE);
  }

  Serial.println("10 second full thrust");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(80,256));
    delay(1000/RATE);
  }

  analogWrite(ledPin,0);
  delay(2000);
}


How can I add additional boards to Eclipse with the Arduino add-on with only a URL, not a zip file I want to add the following boards:

https://redbearlab.github.io/arduino/package_redbearlab_index.json

Which I can add in the Arduino IDE by going to File -> Preferences -> Additional Boards Manager URLs and just pasting it there

Where is the equivalent function in Eclipse, or how do I configure Eclipse to allow me to develop for those boards?

From Eclipse, I have tried Window-> Properties -> Arduino and from there "Private Library Path" and "Private hardware path", and I have tried pointing them to "C:\Program Files (x86)\Arduino\hardware" and "C:\Program Files (x86)\Arduino\libraries", but that didn't seem to change anything (i.e. no new board options, even after running Eclipse as admin) - while the boards show up (examples and all) in the Arduino IDE

With arduino eclipse plugin 2.4 you simply install the boards with the arduino ide -like you described- and you can use then in the arduino eclipse plugin.

Version 3.0 (that is the nightly as 3.0 still needs to be released) contains it's own boards and library manager in windows->preferences->arduino.


Arduino Leonardo Pro Mini will not begin sketch when connected to BIOS not an OS I have an Arduino Leonardo that I am using to emulate a Keyboard using the keyboard.press function with the Keyboard.h libraries. I have gotten the Keyboard.press function to work on my windows and mac- the keystroke I used was CTRL N to test- this worked well. So my ultimate goal was to emulate a keystroke ,F1, on a PC that is not running an OS- meaning I want the sketch to run in BIOS. for context, This keystroke (F1) tells the computer to use the a bootable USB to run a certain MathWorks OS.
The problem, when it is plugged in the Arduino shows that power is receieved by lighting the POWER LED but it does not begin the sketch. The RED LED that usually flashes ( TX or RX im not sure) when it is running a sketch is not happening (not illuminating).
How can I troubleshoot this and what could be happening? I have read that maybe too much serial info is going to the board so it confuses the board and does not begin the sketch.

I appreciate all the following help!!

Because the computer doesn't have a full OS at POST time any USB keyboards attached to the system have to operate in a special "Boot Keyboard" mode.

  Keyboards that implement the USB Boot Keyboard profile specified in the USB Device Class Definition for Human Interface Devices (HID) v1.11 and are explicitly configured to use the boot protocol will interrupt the CPU every time the keyboard is polled even if there is no change in state unless the USB controller overrides this behavior, and are limited to 6-key rollover (6KRO). This profile is intended to allow the BIOS to handle a USB keyboard in the absence of a USB-aware operating system. The recommended profile for keyboards that are not in boot mode in this specification limits keyboards to 6KRO and causes them to respond to an interrupt with a status report at least every half second even if there is no state change in the keyboard unless the USB controller overrides this behavior in order to implement typematic (the function that causes keys to repeat when they are held long enough). However, keyboards in non-boot mode are free to implement an alternative HID profile.

  -- Wikipedia

Since it was not expected that anyone would be using the Leonardo to operate in the BIOS that functionality has never been implemented. The choice was to implement the entire system, which would have left less room for your sketch, or to just implement the parts that the majority of people would find useful (that is keyboard, mouse, joystick, etc) and leave out the extra stuff, leaving as much room for sketches as possible.

They chose the latter, since as I am sure you are well aware: "The needs of the many outweigh the needs of the one".

For your rather specific case it may be easiest to butcher an old USB keyboard and work out which pair of inputs to the matrix, when connected together, perform the function you require and design some small interface circuit to allow the Arduino to trigger that function.


How to know which event fired first? I want to automate the chicken coop of my grandmother. To do so, I want to use Arduinos and NodeMCUs, respectively. I want to check if all chickens are in the coop at night and then close a little door. I was trying to use RFID technology and tag the chickens with a little RFID tag but the read range I got was too short to get it working properly. Now, I am trying to implement a light gate with two small lasers and two receivers. I want to detect the direction (in or out) of the chickens. I got the lasers working and I get a signal (1  and 0 = light gate interrupted). I have to know which of the two laser detectors first detected a 0 (zero). I have no idea how to implement this in code. I was trying to use timers to no avail. I also was trying to use interrupts (see small code fragment).

I hope I made clear what I am trying to achieve. Please tell me if and how I can improve this question. Any google fu was to no avail. Every hint/help is greatly appreciated.

#include <Arduino.h>

// Functions
void pin_ISR();

const int detectorPin = 3;     // the number of the detector pin
const int ledPin =  13;      // the number of the LED pin
const int Laser = 6;
// variables will change:
volatile int buttonState = 1;         // variable for reading the status

void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(detectorPin, INPUT);
pinMode(Laser, OUTPUT);
digitalWrite(Laser, HIGH);
// Attach an interrupt to the ISR vector
attachInterrupt(digitalPinToInterrupt(3), pin_ISR, CHANGE);
}

void loop() {
Serial.print(buttonState);
delay(100);
}

void pin_ISR() {
Serial.println("There was an interrupt!");
buttonState = digitalRead(detectorPin);
digitalWrite(ledPin, buttonState);
}

Consider using quadrature encoding to detect travel direction using two light beams. A method used in older mechanical mouse pointer devices and track balls. Using an Arduino to decode quadrature encoding is talked about in many places on the web.

Place beam A and beam B such that a chicken waling out of the coop will activate beam B first and beam A second.

Because the activation of beam B occurs first we know the chicken is walking out of the coop.  If beam A occurred first we know the chicken is walking into the coop.

The shape of a chicken is irregular and a chicken may change its mind half way out of the coop.  These and other unexpected anomalies may lead to unexpected results.  Consider supplementing the beams with a PIR sensor outside the coop to confirm there are no chickens left outside.


Serial.println using too much memory (not Strings) I want to feed thousands of analog vibration sensor readings into an array as fast as possible, and then analyze them. Here is my sketch:

const int pSensor1 = A0;
const int aSize=10000;

int a[aSize];

void setup()
{
  pinMode(pSensor1, INPUT);
  Serial.begin(9600);
}

void loop()
{
  for (int i = 0; i < aSize; i++) a[i] = analogRead(pSensor1);

  int RMS = 0;
  for (int i = 0; i < aSize; i++) RMS += pow(a[i], 2);
  RMS = sqrt(RMS/aSize);

  Serial.println("Hello");
}

This compiles and runs fine. My problem arises when I try to change the last line to:

Serial.println(RMS);

I get the error:

  Arduino: 1.8.12 (Windows 10), Board: "Arduino Nano, ATmega328P"

  Sketch uses 3270 bytes (10%) of program storage space. Maximum is
  30720 bytes. Global variables use 20188 bytes (985%) of dynamic
  memory, leaving -18140 bytes for local variables. Maximum is 2048
  bytes. data section exceeds available space in board Not enough
  memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for
  tips on reducing your footprint. Error compiling for board Arduino
  Nano.

Why does attempting to Serial print a single floating point variable use 985% of dynamic memory?

Probably if you don't print them then the compiler sees that array is never used for anything so it gets optimized away.  It sees that it is useless code that doesn't affect anything and simply removes it.  Once you print it then it actually has to be included in the compiled code.

Think about this.  The Arduino you are using has 2000 bytes of memory.  One int takes 2 bytes.  You want 10,000 of them.  That's 20,000 bytes of memory.  20,000 bytes will never ever fit into 2,000 bytes.  You need to choose a more reasonable number of samples.


Does upload using `ICSP`overwrite the bootloader? If I compile a sketch then upload using ICSP does it overwrite the bootloader?

I am using Arduino program and Arduino Uno as ICSP.

Yes.
When you program using ISP you overwrite everything in the chips flash, even the bootloader.

This has some pro's and con's:

Pro: The program starts immediately, meaning it doesn't wait to check if there's any programming coming in before starting your sketch.
Con: You need to use ISP to program your Arduino again or to upload the bootloader again.

Normally there is not really any reason for not having the bootloader present but if you are programming bare Atmel chips without a serial interface this way might be preferable.


Attiny85 - Method to discard glitched ADC values? I have a problem i need to solve so i will simply it as much as possible.

Basically there is a system with a micro-controller where it reads 2 sensors. These 2 sensors are of variable resistance type, aka their measuring value is output as different resistance. For example one is a pressure sensor where at 0psi the sensor has a value of 20ohms to ground, and for 100psi it has a value of 120ohms. The sensor is connected between ground and a fixed value resistor so the output acts like a voltage divider.

The micro-controller seems to be multiplexing by switching pull up between each 2 sensors (probably because using a single ADC), at random times (as the microcontroller performs other functions) but approx. every 80ms for each sensor, and about 40ms between each sensor. So at 0ms it reads one sensor, at 40ms the other sensor, and at 80ms back at the first sensor and so on. I have no idea why they haven't used a fixed pull-up, but the pull-up is only done when the controller wants to read the sensor for only about 120us.

I wanted to read these sensors to input to an ECU, without affecting the original device. Thus the easiest solution i could think off as the pull-up isn't always high to perform a read, was to add another microcontroller (in my case a Digispark based on the ATtiny85 running at 16.5MHZ). Alternatively i could open up the device and modify it to use a fixed pull-up but let's say i want to avoid this route. The digispark essentially reads both sensor outputs and when it sees a voltage above ground it outputs it to the ECU. I have since then updated the program to check the ADC values it reads so that it is between the nominal range of the sensor. And while this works there are times where the ADC will read a wrong value and output it to the ECU which looks as random spikes and dips in the data.

Look at my following code:

  const int oil_in = 0; //P5
  const int temp_in = 1; //P2
  const int oil_out = 1; //P1
  const int temp_out = 4; //P4
  int oil_value = 0;
  int oil_value_good = 0;
  int temp_value = 0;
  int temp_value_good = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(oil_out, OUTPUT);
  pinMode(temp_out, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  oil_value = analogRead(oil_in);
  if (oil_value > 106 && oil_value < 466)
  {
    oil_value_good=oil_value;
    analogWrite (oil_out, oil_value_good/4);
  }

    temp_value = analogRead(temp_in);
  if (temp_value > 113 && temp_value < 920)
 {
    temp_value_good=temp_value;
    analogWrite (temp_out, temp_value_good/4);
  }
}

Each ADC pin has a range of acceptable values. These correspond to the MIN AND MAX nominal values for each sensor. However there are times where the ADC will read at the wrong time and it will output either a MIN or a MAX value depending on the condition. I can replicate this on the breadboard by having the input to the ADC reading a nominal value, and by shorting it to either ground or VCC (5V) i can sometimes trick the ADC to read a MIN or MAX value. And since the next measurement will be done after some time, the output will produce these spikes. Since there is no sync between the readings these error data can be sometimes be outputed for 1-1.5s.

I've tried thinking hard about this problem, but i am not sure for a certain solution that will eliminate this problem. ADC interrupts, changing ADC pre-scaler, filtering of data, problem the reading window is really small (100-120us).

Also nominal ADC input values for each sensors are between 0.56V-2.33V for one sensor, and 0.6V-4.68V for the other sensor. Not sure if the interrupt can even be activated at such low voltage.

How do you think i should proceed?

Kind regards

I have no idea why they haven't used a fixed pull-up, but the pull-up
  is only done when the controller wants to read the sensor for only
  about 120us.

If you want to get a good resolution in the resistance measurement, the
resistance of your pull-up should be in the same range as the resistance
of your sensor. If your sensors have low resistance, this means the
voltage divider will draw significant current. In order to save energy,
it makes sense to power the voltage divider only while you are doing the
measurement.

  the reading window is really small (100-120us).

That's short indeed. If you analogRead() a single channel in a tight
loop, you will get one reading every 108.6 µs (128×14 CPU
cycles ÷ 16.5 MHz), and you have a small risk of missing the
window. If you are reading two channels, then you have about 50% risk of
missing the window.

Here is what I would do:

Set the ADC prescaler to 64 instead of 128. This way you will get one
reading roughly every 54 µs, and at least one sample (but more
often two) during the reading window.
Read a single channel in a tight loop, until you get a value above
your minimum. Then take one more reading and use the largest of the
two as your “good” value.
Switch to the other channel and go back to step 2.

This assumes that outside the reading window your ADC input reads close
to zero, as it is grounded through the sensor, with no pull-up. You then
have, on each channel, a train of positive pulses, and you want to
measure the height of those pulses. There is a small risk of you
sampling the rising edge of a pulse, which could give a wrong value
which is nevertheless above your minimum. If this happens, then the next
sample will be near the center of the pulse. That's why I recommend
taking one extra sample and using the largest of the two.


For Loop function to iterate through outputs after interrupt I would like help to continuously loop over my output pins after each sleep cycle.  I am trying to increment through each output pin during each successive interrupt.  Introducing this myIteration function causes immediate incrementing to final output pin and eliminates sleeping.
EDIT
To clarify a bit and clean up the code, I am having trouble getting the loop to increment over the output pins each time the interrupt is triggered.  It stays on the initialized pin value after each interrupt.
The reason I separate the if (state=HIGH) into two consecutive statements is because when I do not the debug LED remains on.
#include <LowPower.h>

const byte interrupt_pin = 2;                             // declare interrupt pin for PIR trigger
int musicPins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11};          // Initialize pins that play music in array, elements from 0 to 8
volatile byte state = LOW;                                // trigger threshold starts low
int pinCount = 9;
int previous = 0;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);                           // use builtin LED for debug
  pinMode(interrupt_pin, INPUT);                          // set interrupt pin as input

    for (int thisPin = 0; thisPin < pinCount; thisPin++) {      // set all music pins as High to start with no music during sensor initialization
    digitalWrite(musicPins[thisPin], HIGH);
    }
    for (int thisPin = 0; thisPin < pinCount; thisPin++) {      // set all music pins as outputs
    pinMode(musicPins[thisPin], OUTPUT);
    }

  delay(5000);                                            // wait so sensor can initialize
}

void loop() {

  attachInterrupt(digitalPinToInterrupt(interrupt_pin),interrupt_routine,RISING); // must attach each loop
  LowPower.powerDown(SLEEP_FOREVER,ADC_OFF,BOD_OFF);      // MCU sleep until interrupt
  detachInterrupt(digitalPinToInterrupt(interrupt_pin));  // remove interrupt

  if (previous==10){                                      // when variable gets to 10 reset to zero
    previous=0;
  }

  if (state==HIGH){                                       // PIR senses motion, sends high signal
    digitalWrite(LED_BUILTIN,HIGH);                       // debug LED turns on
    myOnIteration();                                      // musicPin number x turns on
    delay(100);                                           // wait to stabilize
    digitalWrite(LED_BUILTIN,LOW);                        // debug LED turns off
  }
  if (state==HIGH){                                       // separate statements to guarantee next steps happen
    myOffIteration();                                     // musicPin number x turns off
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);       // sleep for 8s after musicPin plays

  }

  previous++;                                             // increment before attaching next interrupt

}

////////Functions//////////
void interrupt_routine(){
  state = HIGH;
}

void myOnIteration() {                                    // cycle through output pins turning on once per interrupt
for (int count = previous; count < pinCount; count++) {
        digitalWrite(musicPins[count], LOW);
      }
}

void myOffIteration() {                                   // cycle through output pins turning off once per interrupt
for (int count = previous; count < pinCount; count++) {
        digitalWrite(musicPins[count], HIGH);
      }
}

Original code is updated with final version. A motion sensing interrupt iterates over multiple voice playback output pins and sleeps at low power for rest of time.


If Arduino connected to computer and opened up Serial Monitor, will Tx and Rx pin still be working? Suppose one connected two of the Arduino Uno boards through Rx and Tx pins. Then, if one or both of the Arduino boards were connected to computer, and possibly opened up Serial Monitors, will Tx and Rx pin still be working? i.e. will Arduino still communicate through Rx and Tx pin when it's communicating to computer? If not how to make them working while connect to computer?

Suppose one connected two of the Arduino Uno boards through Rx and Tx
  pins.

I assume you will connect the TX of one Arduino to the RX of the other
one and vice versa, which is the right way to connect them. As
theSealion explained in his answer, you shouldn't connect two TX Pins
together.

  if one or both of the Arduino boards were connected to computer, and
  possibly opened up Serial Monitors

If you do that, the Arduino won't even notice.

Well, to be more accurate... there is a small chip on the Uno, near the
USB connector, labeled “MEGA16U2”. This chip is used as a USB/serial
converter, and it will notice when you connect the USB link and when
you open the port. However, the main chip (the big PDIP28), which is the
microcontroller that runs your sketch, will neither know nor care.

  will Tx and Rx pin still be working?

Absolutely.

  will Arduino still communicate through Rx and Tx pin when it's
  communicating to computer?

The RX will not communicate with the computer. What will happen is:

Whatever your Arduino writes to its serial port will be received by
both the other Arduino and the serial monitor.
Whatever you send through the serial monitor will be lost.
When you Serial.read(), you will get whatever was set by the other
Arduino.

The reason of this behavior is a 1 kΩ resistor that sits between
the Mega16U2's TX and the main microcontroller's RX. When you connect
this RX to the other Arduino's TX, which is low impedance (≈ 25 Ω),
that TX will “win”: a low impedance output overwhelms a high impedance
one.


Is the Arduino library so slow? I have a plan to operate 5MP camera module with the arduino Due. But I wonder if I can use the arduino libraries that include digitalRead, digitalWrite and so on. But some people said that it is a bad idea. Especially I found that people wrote values on registers instead of using the library, when they control ov7670 with Uno.

Contrary to this, ArduCam uses the libraries, even for OV5642!. Here is the link
https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM_Mini_OV5642_Video_Streaming/ArduCAM_Mini_OV5642_Video_Streaming.ino

So could anyone please let me know, if it is okay to use such library and never to use register directly? With 'register' I mean arduino's register, not camera's.

I guess the system clock and existence of FIFO would affect the answer. But still I don't know how to evaluate their effect analytically.

Unless you have a really large number of read/write operations and very tight time constraints, I doubt you are going to have any significant advantage in terms of speed.

Accessing the bits in a port together, rather than individually is certainly more efficient, both in terms of time and space, but it might cost in readability, depending on how comfortable you are with leaving the Arduino libraries behind.

You can have also a look at this thread.

Notice that the maximum gain happens only when all the pins you have to read or write belong to the same register.


What is the output of A0 - A5? I'm new to Arduino Uno, When I run this piece of code, I get numbers 340 to 370.

This is my question, why it returns 340 to 370 which correspond to 1.66 to 1.80 actual voltage? since I don't have any input equipment plugged into these pins so it must return zero voltage if i'm right in other words why default values in these pins are in this range of numbers ?

void loop() {
int val = analogRead(A0) ; //A1, A2 ...
Serial.println(val) ;

}

You will get varying values on each read. A pin’s input is said to be floating if nothing is connected, which in simple terms can be explained as it just acting as an antenna for whatever electric noise is present in your environment. Its state is unknown, and utterly meaningless. If you hold a spinning electric motor close to the pin, you can see the values rise and fall more clearly.

Use a high value (10K or more) pull-down or pull-up resistor to partially mitigate this jitter. A pull-down would bring the read value down to around 0, and a pull-up would bring it up to around 1023.

Furthermore, it’s a good idea to always smoothen out analogRead (5-10 reads, ~25-50ms apart, average the values out) to get a good reading if precision is important. This is especially valid if you use longer wires, have an unshielded case, or use a switched mode power supply. Twisting the wires (GND and wiper IIRC, otherwise correct me) to a potentiometer helps.

Edit: You can use pinMode( A0, INPUT_PULLUP ); - it provides a 20-50Kohm pull-up, though I don’t trust this and always use 1/4W resistors instead. It saves space though, and is quite handy.


Random Servo Movement with Arduino Uno Recently, I have been working on a project involving 8 Tower Pro sg90 servos and an Arduino Uno. The issue I am running into is that the servos will randomly move when connected, without even receiving a signal from the
Arduino.
Specifically, sometimes the servos will work perfectly and the input move the servos fine, but then all of the sudden the servos will start twitching and moving erratically back and forth. Then I disconnect power and plug it back in and I will sometimes work again or sometimes not.
I don't think power is the problem because I am powering the servos externally with a 5.5v power supply which can provide 2.5 amps. I also made sure to have a common ground between the Arduino and the power supply. Additionally I don't think this is an issue of a broken servo because I have this problem with all eight. In my code I have input pins to control the servos which are just buttons. These buttons also have pull down resistors, so I don't think the input is the problem either. I am using the Arduino servo library.
The only other thing I can think of is external frequency interference, because some of the circuitry and wiring is close together, but none of the wires are very long and I even tried putting a ferrite bead on the servo cables but to no avail.
If anyone has any ideas about a solution to my problem which I have not tried yet that would be amazing!
Thanks - Xander
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;
Servo servo7;
Servo servo8;

void setup(){
  pinMode(5, INPUT);
  pinMode(4, INPUT);
  pinMode(3, INPUT);
  pinMode(2, INPUT);
  pinMode(1, INPUT);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  servo1.attach(13);
  servo2.attach(12);
  servo3.attach(11);
  servo4.attach(10);
  servo5.attach(9);
  servo6.attach(8);
  servo7.attach(7);
  servo8.attach(6);
}

void loop(){
  if(digitalRead(5)==LOW){
    servo1.write(120);
    delay(20);
  }
  else{
    servo1.write(50);
    delay(20);
  }
  if(digitalRead(4)==LOW){
    servo2.write(110);
    delay(20);
  }
  else{
    servo2.write(200);
    delay(20);
  }
  if(digitalRead(3)==LOW){
    servo3.write(120);
    delay(20);
  }
  else{
    servo3.write(50);
    delay(20);
  }
  if(digitalRead(2)==LOW){
    servo4.write(110);
    delay(20);
  }
  else{
    servo4.write(200);
    delay(20);
  }
  if(digitalRead(1)==LOW){
    servo5.write(120);
    delay(20);
  }
  else{
    servo5.write(50);
    delay(20);
  }
  if(digitalRead(A3)==LOW){
    servo6.write(110);
    delay(20);
  }
  else{
    servo6.write(200);
    delay(20);
  }
  if(digitalRead(A2)==LOW){
    servo7.write(120);
    delay(20);
  }
  else{
    servo7.write(50);
    delay(20);
  }
  if(digitalRead(A1)==LOW){
    servo8.write(110);
    delay(20);
  }
  else{
    servo8.write(200);
    delay(20);
  }
}

You call servoX.write() repeatedly, even when no button has changed. Each call turns off interrupts briefly while the servo value is being updated. This happens, maybe 40 times/sec and may be messing up the servo timing in some non-constant way. Try only calling the servoX.write() functions once, only when its button-state has settled into a new state.
Update:

could you provide an example please

  bool prevButton5 = LOW;            // one of these for each button
    :                                // outside of the loop() func.
    :

  if(digitalRead(5) != prevButton5){  // button changed?
    prevButton5 = !prevButton5;       // save new button state
    if(preButton5 == LOW){            // (your same code from here down)
      servo1.write(120);
      delay(20);
    }
    else{
      servo1.write(50);
      delay(20);
    }
  }

Make a boolean for each button.
Wrap each of your button segments as I did for button5. Notice that your code is now executed only if the associated button has changed, so you will have many fewer servoX.write() calls.

That isn't the totally best way to do it. I made it as straightforward as I could, even though the additional code gets replicated for every button. I'd probably write a single function that manages one button and one motor, and call that function for each button / motor pair.
I also ignored the concept of switch-bounce to keep the number of changes low, but you should look it up and consider it. Switch-bounce is apparent bouncing of the switch contacts for a few milli-seconds during the change from open to closed or vice-versa, which leads to several make-break-make.....-make cycles (or the reverse) when you push or release the button. I'd probably make (or search for) a button debounce function and call it for the particular button I'm testing if I see that button has changed.
First try the "rude and crude" fix I suggested and get that working. Then if you're interested, try making one or more of the refinements.
Update:
the servos still jitter and twitch esspecailly when
I move the whole arduino and wires around.

That suggests either or both of

cross-talk;
the plug wires' connections being less than solid, especially when the wires move.

Try:

laying out the servo cables to keep them away from each other as much as possible;
wiring only a few of the servos, and in different combinations;
also try commenting out the code - or not - for those servos you disconnected in the previous step.

If it turns out to be the plug-in wires and if this project is intended to actually be used for something, I'd suggest using a screw-terminal shield on your Uno to attach the servo wires more securely.


Serial Monitor (user input) I'm trying figure out how to make the serial monitor printing specific content based on the user input. For instance if the user has typed '1' it should constantly print ("Hello") and when user has typed '2' it should print ("Bye") and vice versa. I'm new to programming, so I would be grateful if any can help me with this.

  String readString;

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

       void loop()
       {

         if(Serial.available()>0)

         {
            char c = Serial.read();
            readString +=c;
            delay(2);

                   if (c == '1')
                    {
                     delay(1000);
                     Serial.println("Hello");
                     c = "";
                    }

                                 if (c == '2')
                                  {
                                    delay(1000);
                                    Serial.println("Bye");
                                    c = "";
                                  }
             else
            {
             readString= "";
            }
          }
        }

You have most of what is needed but you have it structured incorrectly.

Because you want to print continuously, you need to split your program into 2 sections. One section deals with the serial input and the other with the printing.

The serial handling part checks if there are any characters to be read. If so, it simply stores the character that you read into a global variable.

The printing part executes every time through the loop and prints the value you want based on the global variable, which may, from time to time, change if something new arrives on the serial port.

This code is untested:

char cMode;

void loop()
{
  if(Serial.available())
  {
    char c = Serial.read();

    if (c == '1' || c == '2')
      cMode = c;
  }

  if (cMode == '1')
    Serial.println("Hello");
  else if (cMode == '2')
    Serial.println("Bye");

  delay(1000); // to slow down the loop?
}


Uploading code to Arduino wirelessly I have been working on a project watch which would work best if it is entirely sealed (to waterproof it). The watch may need future updates, but I will be unable to send code to it using a usb connector or isp programmer without opening the case. What is the best way to connect my PC with this watch wirelessly?

I gather that the serial ports are usually used to send code via the usb, and that most Bluetooth modules use serial coms to communicate with the Arduino.

The Arduino that I am using is an Arduino Pro Mini clone.

Any help will be greatly appreciated.

You could use ESP8266 and ESP-LINK firmware to update the arduino firmware over the wire. Its also enables you to debug it wirelessly. What it does is provide a serial link but over wifi. Just like connecting it via cable.


Print string from arduino to serial monitor I want to send text over serial monitor to Arduino and make Arduino return that string back to me over serial monitor.

I have made this function which reads from serial input and returns a string object.

String readSerial() {
    String input;
    while(Serial.available() > 0)
        input.concat(Serial.read());
    return input;
}

In the loop() I have:

if(Serial.available()) Serial.print(readSerial());

If I just do something like Serial.print("Hello world!"); everything is fine. But, if I try to return string object I get lot's of numbers.

I guess Serial.print doesn't know how to read String object and returns ASCII codes of characters or something?

[update]
I have checked it, and it's indeed outputing ASCII codes. For Hi I get 72105.

[update]
I have updated my readSerial function to use this :

input += (char)Serial.read();

But now I'm getting carriage return and new line after every character:

[SEND] Hi
H(CR)
i(CR)

So, how can I make it return my text so that is readable?

String.concat() takes a String as the second argument. Serial.read() returns an int. The compiler creates code that converts the int into a String similar to this:

input.concat(String(Serial.read()));

This is not what you want.

Let's tell the compiler what you really want instead:

input.concat((char)Serial.read());

This will tell the compiler to do the following:

input.concat(String((char)Serial.read()));

We are now having the compiler call the correct String constructor, and the code will work as we expect.


HM-10 only works when holding button My HM-10 bluetooth module is behaving weird.

In order to have it operate normally, I have to keep holding the small black button on it. If I ever release the button, it just disconnects from my phone (if it was connected) and doesn't show on the bluetooth devices list anymore, and its red LED light becomes low, not bright as usual.

It operated normally before.

How can I fix this?

What would some possibles causes be for this weird behavior?

UPDATE: picture showing the button on lower right corner.

I just had to connect the RX/TX jumpers. There was no real issue.

I though connecting the power jumpers was enough to just see HM-10 on my phone, since I didn't care about any data. Turns out if the RX/TX jumpers are not connect, the module behaves weird.


Problem with interrupts and 4x encoders on Nano 33 BLE I have a Pololu 4x encoder and am trying to write some code to make it work on my Nano 33 BLE. (Interestingly enough, the issue preventing some pre-existing libraries from working for me is the same issue that I'm about to describe here...)

When I turn the motor shaft clockwise, these are the signals that I get (first bit in each pair is channel A, second bit channel B):

11 -> 10 -> 11 -> 10 -> 11 -> 10

Note how channel A's value never changes, and B's value toggles back and forth.

Likewise, for the counterclockwise direction:

01 -> 11 -> 01 -> 11 -> 01 -> 11

This is of course wrong, as the channels' values should be something like 00 -> 10 -> 11 -> 01 -> 00 as the shaft turns. As a matter of fact, that is exactly what I get when I run the exact same code on a regular Arduino Nano.

Does anyone know what's going on? Here's my code. AFAIK I'm not using interrupts incorrectly or anything, at least for the regular Nano.

#define PIN_A 2
#define PIN_B 3

volatile int val = 0;
volatile bool newVal = true;

void encoder() {
  int a = digitalRead(PIN_A);
  int b = digitalRead(PIN_B);
  val = ((a << 1) | b);
  newVal = true;
}

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

  pinMode(PIN_A, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, CHANGE);

  pinMode(PIN_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_B), encoder, CHANGE);
}

void loop() {
  if (newVal) {
    Serial.print(bool(val & 0b10));
    Serial.print(bool(val & 0b01));
    Serial.println();
    newVal = false;
  }
}

EDIT: After taking a look at the following diagram, it appears that the erroneous encoder patterns match those in which only rising edges are detected. So for some reason, attachInterrupt() is acting as if the CHANGE argument were RISING instead for the Nano BLE.

Best practice would be to use a single interrupt for the encoder.  BLE has a faster processor and your code is not frame-based so that just might affect it also.  This code doesn't do exactly what your code did but it will use val to track position as a number.
It can also be made a bit finer using CHANGE instead of RISING, but for debugging bare bones means less that can go wrong.

#define PIN_A 2
#define PIN_B 3

volatile int val = 0;
int oldVal;
//volatile bool newVal = true;

void encoder() {
  if(digitalRead(PIN_B)) ++val;
  else --val;
}

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

  pinMode(PIN_A, INPUT_PULLUP);
  pinMode(PIN_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN_A), encoder, RISING);
}

void loop() {
  if (val != oldVal) {
    oldVal = val;
    Serial.println(oldVal);
  }
  delay(500);
}


How to switch program in arduino using android app? I have 2 programs made for my arduino.The first one is for solving a maze automatically and the second one is for controlling the robot with a android app.I wanted to control the robot with the app I made as soon as it has finished solving the maze.
                   Is it possible to upload both the program in the arduino and run it one at a time?If so can you tell me how?

Once I made a sketch to run multiple programs. I wrote a setup and loop function for every different "program", (e.g. setup_p1, setup_p2, ... loop_p1, ...) and then wrote a simple main sketch to handle them all.

In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.

I choose to use a callback because it's faster than just checking the mode every time, at least in my case

// callback for loop function
typedef void (*loopfunction)();
loopfunction currentloop;

void setup()
{
  // Set dip-switch pins as input
  pinMode(MODE_PIN2,INPUT_PULLUP);
  pinMode(MODE_PIN1,INPUT_PULLUP);
  pinMode(MODE_PIN0,INPUT_PULLUP);

  // Concatenate the dip-switch values
  byte mode = 7 - ((digitalRead(MODE_PIN2) << 2) | (digitalRead(MODE_PIN1) << 1) | digitalRead(MODE_PIN0));

  // choose the correct mode
  switch(mode)
  {
    case 0: // Shutdown - do nothing
            break;
    case 1: // Program 1
            setup_p1();
            currentloop = loop_p1;
            break;
    case 2: // Program 2
            setup_p2();
            currentloop = loop_p2;
            break;
    ...
  }

  // Not a valid program: halt
  if (!currentloop)
  {
    while(1);
  }
}

void loop()
{
  // Execute the current loop
  currentloop();
}


Do I need to use the PWM pins in order to control brushless motors Arduino Uno? I am building a quadcopter with this schematic:

It works very good but i have the pins on 3,5,6,9 = PWM pins. Is it possible to use "regular" pins instead? I will add more modules later on so i will most likely run out of PWM pins.

I could of course try it right now but i want to ask first so i could potentially avoid to destroy any items!

No, you need to use PWM in order to control the ESCs which, in turn, control the motors. If you need more PWMs you might add daugtherboard based on other ICs which might provide additional PWM outputs via I2C or serial interface.

In some non critical conditions (ESCs are critical for a quadcopter) you can simulate PWM by switching a plain digital pin HIGH and LOW very quickly, but that is not as reliable as using hardware PWM.


Exit status 1 can't compile I am a complete beginner with very little knowledge. I am trying to do a switch in Arduino UNO using a guide I found on the internet but it won't compile. The servo motor should function if it is switched on loadstate == HIGH. I have no idea what "exit status 1" is or how to fix it, help.

#include <Servo.h>
    Servo myservo;

    int buttonPin = 3;
    int reading;
    int state = 0;
    int Loadstate = 0;

    int pos = 0;
    int trig = 13;
    int echo = 11;

void setup() {
  // put your setup code here, to run once:

    pinMode(buttonPin, INPUT);
    pinMode(ledPin, OUTPUT);
    pinMode (trig ,OUTPUT);
    pinMode (echo ,INPUT);
    myservo.attach(7);

}

void loop() {

    long duration, distance;

    digitalWrite (trig, LOW);
    delayMicroseconds (2);
    digitalWrite (trig, HIGH);
    delayMicroseconds (10);
    digitalWrite (trig, LOW);
    duration = pulseIn(echo, HIGH);
    distance = (duration/2) / 29.1;

      reading = digitalRead(buttonPin);

  if (state == 0 && reading == HIGH){
        state = 1;
        Loadstate = !Loadstate;
  }
  if (state == 1 && reading = LOW){
        state = 0;
  }

  if (Loadstate == HIGH){
      if (distance <= 30 && distance >= 0){
          for (pos = 0; pos<90; pos +=1){

            myservo.write(pos);
            delay(15);
        }

        delay(1000);

          for(pos = 90; pos>=1;pos-=1){
            myservo.write(pos);
            delay(15);
        }
        }
        }
}

ledPin is not defined. You should define it somewhere.
if (state == 1 && reading = LOW){ is not valid syntax. You need to use == not = to compare values.


USB and Arduino: Power Arduino, charge LiPo, and transfer data at the same time I was hoping to design my own Arduino board for a recent project of mine, a portable project that was powered by a 3.7 LiPo battery. Most ideally, I wanted to replace the USB B port with a single USB Micro port that implements the following features:

Provides power to the Arduino while it is plugged in (just like a regular Arduino does).
Connect the D+ and D- pins of the USB to the Arduino somehow to allow for on-board programming (however the Arduino accomplishes this already, I'll refer to this as the "onboard usb/serial converter"). I want it to keep it programmable on-the-go.
Charges an on-board 3.7V LiPo Battery. I was hoping to use Adafruit's PowerBoost 500 Shield as a reference for my schematic.

However, I haven't been able to find a schematic or example that implements all 3 features above at the same time from the same USB port. I don't have much experience with charging circuits, so the following questions might sound dumb. Below are some solutions I was thinking of that probably won't work, but I wanted to make sure:

Connect the Output Voltage of the LiPo Battery to the V+/GND supply of the USB cable (probably not safe to connect all V+ sources together).
Just connect the D+/- data cables to the "onboard usb/serial converter" without connecting the Vbat/Vusb somehow, have the USB V+/GND connect to the LiPo charging circuit, and the Battery Voltage power the Arduino.

I know some devices have this charging/data-transfer functionality (e.g. my phone can transfer photos to my computer while being powered on and charging at the same time), but I'm wondering how it's possible to have similar functionality for an Arduino board. Any advice?

Absolute worst case, I'll just have 2 USB ports, one for charging the LiPo and one for Serial Communication/Programming

EDIT: The idea of using an ATMega32U4 seems appealing (despite the 3.3V vs 5V operating voltage), mainly because it has a pin for VBUS for USB and Vcc for main power. But I was wondering how to do this on say an ATMega328P that doesn't have a pin for VBUS.

I'd recommend using the Arduino Leonardo as a reference for your circuit. Its pretty much the same as an Arduino UNO but has a built in USB interface so you don't need the USB-Serial converter.

I'd also recommend running the chip at 3.3V. That way you can use a linear regulator to regulate the 3.7V battery voltage down. Otherwise you'd need a boost converter to bump the voltage up to 5V which needs more parts.

If you follow those recommendations then all you will need is a LiPo charging IC to handle the charging. You'll need to add an ISCP header to flash the initial Leonardo bootloader, but after that you can use USB and the Arduino IDE to program it.

I did exactly this for a school project a while back. You can find the schematics here: https://github.com/seanwatson/ece4416-project/blob/master/hardware/rev2/sw-4416-project-v2-sch.pdf


HIGH and LOW reversed i've got a seven-segment-display on my arduino-nano and want to write some numbers on it. The problem is that HIGH and LOW seems to be reversed.
If the output should be

0

it displays

-

I could solve this, replacing all HIGH and LOW through HIGHX and LOWX, and defining them reversed:

 #define HIGHX 0x0
 #define LOWX 0x1

but this is reversed and not a good solution...

The wiring is correct like this (just GND not connected):

But if i connect the GND, the hole display isn't showing something anymore.

With the given schematic both your logic for segments and digits should be active high, so it looks like you made a mistake. Especially because you say it doesn't work anymore when you connect ground. Check that you have the right transistor and that it's connected correctly: Emitter should go to ground, collector to the display's common cathode. (Check that your displays are common cathode!)

It's not a good idea to define some version of high as low, that's only confusing. Instead name the signals:

#define DISPLAY_SEGMENT_ON HIGH
#define DISPLAY_DIGIT_ON HIGH

The image can be found at several places on the Internet, so I guess you didn't draw it. This is a common cathode display, and the transistors are NPN types. If your displays are common anode then the whole thing flips upside-down: The Ground rail becomes Vcc, and the NPN transistors should be PNP types. Then you will indeed have inverted logic, and you should define:

#define DISPLAY_SEGMENT_ON LOW
#define DISPLAY_DIGIT_ON LOW


How can I get the source files for Arduino libraries? I've been looking for a while inside Arduino's files to find the core library. However, I haven't found them yet. Where on my hard drive can I obtain the core library files (.cpp and .h) necessary for all Arduino code?

Looking around on Google, I couldn't find a way to find the above files. I did see something about getting an .a file while Arduino is compiling, however, that isn't what I want. I want to browse the code and look at functions such as delay to see how they would react when given the values not expected. (i.e. Will my code stall if I use delay(-200); by not being to exit the loop, or will it create a black hole and disrupt the space-time continuum?)

The code is also available online for those times you don't have the IDE installed:

https://github.com/arduino/Arduino


NEO-6M is working but it doesnt show data So I'm having a little bit of difficulty here in my NEO-6M. The problem is it doesn't show any data in my serial monitor. My NEO-6M Led is already blinking so its already ok.

RX -> Pin3 , TX -> Pin4 , VCC -> 3.3v , GND -> GND

  Serial Monitor:

Code:
https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino

I found a solution to my problem. On my first setup, I separate my GND of NEO-6M to Arduino and put connect it in breadboard that has powerboard on it because I thought it is only for electrical purposes but it doesn't since I encounter it.

Solution:

  The GND of every module must still connect on the Arduino.


Why does my Esplora only send serial data when the serial monitor is on? I've noticed that when I'm sending serial data to my computer's serial monitor, the tx light only lights up when the serial monitor is open.  When I close the monitor, it seems to stop sending data.  Is this a normal thing?

The reason I ask is because I'm really trying to send data from my esplora to an uno, and I notice that despite (1) having the grounds of both arduinos connected and (2) connecting the esplora's tx pin (reset_lcd) to the uno's rx pin (pin 0) and the esplora's rx pin (dc_lcd) to the uno's tx pin (pin 1), the tx light on the esplora and the rx pin on the uno don't light up at all.

What could be the problem?

Esplora is based on a MCU with native USB. The native USB reports connected only when it really connects. You have in setup() a while loop until the USB Serial is valid. The skech waits there for connection. Comment out the while (Serial) loop.

The TX and RX LEDs of Esplora are connected to the native USB port Serial interface. They will not light for the Serial1 interface.

You should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.


ATmega328p simple shortcircuit button I am trying to get a simple button (GPIO shortcircuit) to work. I have chosen Pin D0 as input and Pin D7 as output. It works fine in an Arduino sketch but I can't get it to run in pure C. What am I doing wrong? I bet I got the bits all wrong...

My code:

DDRD = 0b11111110; // set all port D pins to Output besides pin 0, which is set to input
PORTD = 0b11111111; // set all D pins to WRITE / PULL-UP
int a = PIND & 1; // a is 0 or 1, depending on whether pins D0 and D7 are physically connected

It doesn't work though, a is never zero, whether the pins are connected or not.

Here is my complete code sample, where the on board LED depends on my pins connection state:

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
 DDRB |= _BV(DDB5);
 DDRD = 0b11111110;
 PORTD = 0b11111111;

     while(1) {
        int a =  PIND & 1;
        if(a != 0)
             PORTB |= _BV(PORTB5); // blink on
         else
             PORTB &= ~_BV(PORTB5); // blink off
         _delay_ms(1000);
    }
}

The problem here is you set pull-up on D0. So even if button is not pressed it will be at high state because of pull-up. You would need pull-down for this to work (Arduino does not have it).

The pullups are useful if you want to connect pin to GND when button is pressed. When button is not pressed it will have defined state (HIGH because of pull-up) and when pressed it will be pulled LOW by button. You can imagine pull-up as a resistor to Vcc.

So for this to work I would put the other end of button to GND and it will work (One end to D0, second on GND). Condition in code should be altered (a == 0) but otherwise all can be the same.

Other option is to connect external resistor in range 1K-100K Ohm between pin D7 and GND and turn off pull-up in code. That resistor would serve as pull down.

Just one more note. If you are not using other pins it is the best to leave them as inputs. Setting an "unused" pin as output and setting it to HIGH can damage the pin if you accidentally connected it to GND (because in previous sketch you experimented something).


Can I use only Ruby or Crystal Lang with an Arduino? I am new to Arduino. I have used other SBCs before and ran some ruby script to automate many tasks.

I know Ruby and Crystal programming languages.

Can I use Ruby or Crystal solely on Arduino for creating basic robot?

You could bridging via Firmata: https://playground.arduino.cc/Interfacing/Ruby/
Another resource is https://code.tutsplus.com/articles/using-ruby-to-program-arduino--cms-21893
You will need to Flash your Arduino with Firmata and then program in Ruby.
I'm not sure if that would work with Crystal.


How to assign text stored in a local file to a string at compile time I'm developing a program that uses the HTML server in the WiFi101 library.

My hardware does not have SD card storage so all source html needs to be stored as strings in the sketch at compile time.  To aid in development I want to keep my html files separate from the sketch and include them at compile time.

Is there a way to use #include in the Arduino IDE and assign the included file to a string/char array constant?  If so can the path to the included file be relative to the sketch's path?

Notes:
Similar question on Stack overflow:
https://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char

Edit:
There are lots of great answers here to solve this in a more robust fashion. The correct thing to do is setup a proper build system.  If I were to set this up I'd be temped to try something like Gulp since you could easily minify/lint your web content.
As this is a small project I ended up just running the HTML through a minifier service and copy/pasted into strings.

I found another way to include a literal file (html, css, or other) and assign it to a constant string without resorting to make files:
Add one line of code on top of your html (css, js, etc) file, and another at the bottom, and save it with an extra .h extension. Then include that file in de Arduino IDE.
This could easily be done by a (manually executed) script, every time those files are changed.
const char *indexHtml = R"====( // added by script
<html> <!-- original .html file -->
.
.
.
</html> <!-- end .html -->
)===="; // added by script

The variable name can be derived from the original filename. The result is saved with an extra .h extension. In the .ino (or .cpp) you can then include this file:
#include index.html.h

This will compile in the Arduino IDE.


ESP 01 lost its firmware when it disconnected Hi I am using Arduino uno & ESP-01

ESP-01 is working well when I put firmware to ESP, for example, wifi spreading or AT command is okay.

but when I disconnect arduino from PC(disconnect USB connection)

ESP-01 suddenly do not work anything. no spread wifi, no AT command reaction..

so I always have to re-input the firmware to ESP again, for make it work again.

How can I make maintain ESP-01 's firmware?

picture is my connection status. thank you

You have io 0 puled LOW so the esp-01 firmware starts in flashing mode and the firmware starts immediately after flashing (no reset).

Remove io 0 to ground connection and add a pull-up for io 0 over a 10kOhm resistor if you want the esp-01 to start normally.

Note: powering the esp-01 from the 3.3 V pin of Uno (150mA max) could be insufficient for esp8266 WiFi operations at top transmit power (according to specs it can draw to 170 mA).


Use Unix terminal instead of the Monitor on Arduino IDE I want to make a shell or C script that interprets the Arduino serial input to run commands. For that, I will need to make that script be the Serial monitor for my arduino. Another reason I want to use scripts or the command line as a Serial I/O is because the Arduino monitor function freezes the IDE.

My arduino's serial port is /dev/tty.usbmodem1d112

This is what I have tried so far:

cat /dev/tty.usbmodem1d112 < This returns absolutely nothing
screen /dev/tty.usbmodem1d112 < This Prints output, but has problems with input.
cat < /dev/tty.usbmodem1d112 < Same result as cat without the < symbol.

Sometimes, I also get annoying Resource Busy messages. This makes me re-plug the Arduino board.

OS X (10.9.5) Arduino IDE latest version. Arduino M0 pro board.

You'll need to condition the serial line with the stty command to get this to work. One of the easier ways to do it is to start by using the Serial Monitor and running the command:

stty -g < /dev/tty.usbmodem1d112

That will show you all of the settings that the Serial Monitor used to conditions the line. The -g flag to stty tells it to give you the results in a form that can be used as the arguments to another stty command. You could do this like this:

echo -n 'stty ' > stty.arduino ; sudo stty -g -f /dev/tty.usbmodem1d112 >> stty.arduino

chmod +x stty.arduino

The first line creates a shell script to condition the serial line. The second line makes it executable so that you can run it as a shell command – ./stty.arduino. The sudo runs the command as root (with elevated privilege) which allows you to open the port even though the Serial Monitor will already have it open.

If you want you could move the command into a directory on your $PATH (for example ~/bin) so that it can be found regardless of where your current directory is.

After getting set up you can see the output from Serial.println() on the Arduino by doing:

./stty.arduino

cat < /dev/tty.usbmodem1d112

Depending on what you are trying to do, you might find the expect or script commands helpful. Expect (man page) lets you automate interactions with a text based application or process. Script (man page) creates a transcript of your interactions on the command line with another program or process.


ATmega 8 wrong timing with Arduino NG bootloader I have build simple Arduino ISP programmer, which works fine on ATmega 328 chips (when I select Arduino UNO board) and a ton of others (tiny45, tiny2313). But, when I want to program an ATmega8 chip, it writes it succesfuly, but then the chip runs at 1/16 of the desired speed! (for example a delay(1000) in code takes 16 seconds real-life). I have a 16 MHz crystal oscillator with capacitors connected to the chip, so I thought that the problem is not there but... when I remove the crystal, the chip still runs the same, it still takes 16 seconds.
So I assume two possibilities:

the crystal is somehow broken, so the chip runs from some internal
thing? But I tried multiple crystals, all the same,

OR

I am doing something wrong, but I really don't know what...

Does somebody have an idea what may be wrong or how to test it? Or feel free for more details...Thanks

EDIT: In IDE, I am selecting "Arduino NG or older" and then I select ATmega8  as processor. I am uploading the sketches directly, without bootloader.

Ok, I finally solved it, so I will write it here so somebody may learn from it in the future :) The problem was really in the fuses, thanks Chris Stratton. Most of my chips were bought already modified for working with Arduino. But this ATmega 8 had the factory fuses, which were setting it for working with internal 1MHz oscillator. You can read and your write your fuse settings with avrdude, so I set them to arduino default (lfuse 0xDF, hfuse 0xCA, from boards.txt). Now it works perfectly even without uploading bootloader.


Why can't I use 3V output of arduino pro mini? I have an Arduino pro mini and I tested digital write of an pin and it is 3.2V and then I connected it to a 3V motor, but when I connected the motor to it, The voltage drops under 0.2 Volt, Can any one describe the science behind voltage drop ?

I know I've better use a transistor and separate the motor power but, what you should do when you have a single 3V power source? and I know there are some motor driver chips, but is it possible to keep it simple?

NEVER drive a motor directly from an Arduino IO pin.  You will kill the Arduino.

It's not a question of voltage, it's a question of current, and that is where the transistor comes in.  If you have a 3.3V Arduino (as it sounds like you have) then you may be able to drive the motor using the 3.3V output of the Arduino (VCC pin? Not sure with that model) and a transistor. That is the simplest arrangement.

simulate this circuit – Schematic created using CircuitLab


Arduino Nano TX LED is on My Arduino nano make weired thing...
The TX LED is on when i define a Variable and a digital Pin as output. Do you now if it is a error in the code? If I upload a clear new sketch the LED is off.

~Nico

Code:

int ok = 1;
int err = 0;
int x1 = 2;
int x2 = 3;
int x3 = 4;
int x4 = 5;
int x5 = 6;
int x6 = 7;
int y1 = 8;
int y2 = 9;
int y3 = 10;
int y4 = 11;
int y5 = 12;
int y6 = 13;
int value1 = digitalRead(14);
int value2 = digitalRead(15);
int value3 = digitalRead(16);
int test = digitalRead(17);

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(16, INPUT);
  pinMode(17, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

}

You configure serial pins as output, this may be your issue.

also, you're calling some digitalRead() before setup call, you would have to do that in the loop.


VCNL4000 Proximity/Light sensor I want to use the VCNL4000 Proximity/Light sensor s.
http://www.adafruit.com/products/466?&main_page=product_info&products_id=466

In the package i've this 6 pin connector but the VCNL has 5 pins (i now i can connect it by myself with male jumper) but  what am i missing here?
I assume that it is not an "accident" that the thing has one more pin then the sensor ; )

You can just cut off the extra pin. Adafruit probably just had a bunch of 6 pin headers in their stock.


Arduino + Codeblocks C++ I'm writing the code for my Arduino board using Code::Blocks editor. When I create a new project, there is AVR Project and Arduino Project under Projects category. Which one do I select?

You can select, what you want. If you want to build an Arduino Project, you should choose "Arduino Project". If you don't want to use the Arduino Framework, you can choose "AVR Project".


PCA9685 seemingly no PWM output Arduino Uno when attempting to do LED dimming Just for a quick test I've wired up the Arduino to a PCA9685 board (similar to http://www.ebay.com.au/itm/PCA9685-16-Channel-12-bit-PWM-Servo-motor-Driver-I2C-Module-For-Arduino-Robot-AU-/162059198475?hash=item25bb7b200b:g:S7IAAOSw9ZdXKa7h) as follows

5v > Vcc & V+
GND > GND
A4 > SDA
A5 > DCL
OE > Not connected

I've wired a 1k resistor in series and an LED in between PWM0 and GND

The same LED dims fine when powered directly via PWM from the Arduino.

The power light on both boards come on and +5v is available at the V+ pins.

The library I'm attempting to use is https://github.com/kasperskaarhoj/PCA9685-Arduino-Library and from what I can tell the I2C address I've configured "works"

The sketch I'm trying to run is (which is one of the example sketches with the address I2C altered):

#include <Wire.h>
#include <PCA9685.h>

PCA9685 ledDriver;

void setup()
{
  Serial.begin(9600); // set up serial
  Serial.println("Serial Started");

  Wire.begin();           // Wire must be started!
  ledDriver.begin(B000000);  // Address pins A5-A0 set to B111000
  Serial.println(ledDriver.init());

}

void loop()
{
  // Notice: setLEDDimmed cannot be used in a loop to give you a pleasant
  // "turning-up" of the LED. This is because each time you set a level for a LED
  // it will calculate random timing intervals for the PWM function in the chip
  // This is done in order to distribute current consumptions of the full time period.
  for(int level=5;level>=0;level--)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
  for(int level=0;level<=5;level++)  {
    for(int i=0; i<16; i++)  {
      ledDriver.setLEDDimmed(i,level*20);
      delay(100);
    }
  }
}

Serial monitor outputs:
Serial Started
1

So it looks like the device is detected and I expect that the commands are sent but nothing happens.

I've also tried one other library and setting the duty cycle to 100% on/off just to see if I could get output with no luck. It just seems that all the PWM pins are dead. I also tried wiring up the OE pin and setting it high/low with no luck.

Any thoughts on how I might be able to get the board to output something or how I can test further would be appreciated. I'm beginning to think that maybe the IC is damaged as I've tried most the pins with no luck.

I'm out of ideas and haven't worked with I2C or PCA9685's before at all so any help would be appreciated :)

The LED should be (with its inline current limiting resistor) between VDD and the LED pin, not to ground - and then configure the pin for Open Collector mode.


Software Gate on a PWM port I'm using a PWM port and outputting a freq. Is it possible to pulse the PWM port using software to simulate a pulse gate. For example, I'd like to output a freq of 111hz, but would like to gate that freq at .5-7hz. Is this possible to do all in software without external hardware. I'm using a Teensy board which is similar to an Arduino, but has 3 independent PWM ports. Any ideas on whether this possible?

If you can configure the PWM to run at 111 Hz (I don't know how
this is done on the Teensy), then “gating” it is as simple as turning
the PWM on and off at the desired frequency:

uint32_t half_period;  // half the gating period in microseconds

void set_gate_frequency(float freq_in_hz)
{
    half_period = (1e6 / 2) / freq_in_hz;
}

void loop()
{
    static uint32_t last_toggle = 0;
    static bool pwm_is_on = false;
    if (micros() - last_toggle >= half_period) {
        if (pwm_is_on) {
            digitalWrite(PWM_PIN, LOW);
            pwm_is_on = false;
        } else {
            analogWrite(PWM_PIN, 128);  // PWM with 50% duty cycle
            pwm_is_on = true;
        }
        last_toggle += half_period;
    }
}


How do I turn off a 12V 3A RGB LED strip? I'm trying to understand how to control an RGB LED strip, I set up all the TIP120 (because I could get my hands on an n-channel mosfet), if I power everything in this way I can change colours and everything:

but now I'm facing a dilemma now, whats the correct way to manage to switch my power strip ON/OFF based on an input from a pir sensor? I mean, how can I handle 12V 3A (requested by my led strip), how do I correctly wire my Arduino up in order to make it switch the LED strip ON/OFF?

That's pretty simple: when you turn off all the colours you are actually turning off the entire strip with very minimum leakage current in each of the three FETs.


Getting no such directory file error when compiling I recently got my wifi module and connected it to my Uno. I am now trying to send a http request. I have the code that comes with the esp8266wifi library in which it demonstrates and gives an example on how to send a http request. This is the code:

CODE.

I am getting the following error

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

In file included from C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

                 from C:\Users\Yasmeen\AppData\Local\Temp\arduino_modified_sketch_200757\HTTPSRequest.ino:14:

C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include <queue.h>

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

Obviously it seems to be an file path error but I'm not sure why. I've imported the library through the Arduino IDE.. But maybe the way I aquired the library was wrong? What I did was download the esp8266wifi folder (here) and zipped the file and imported it.. is that okay to do?

The ESP8266WiFi library is for programming the ESP8266 directly. You are trying to compile source code for the ESP8266 for the Arduino UNO, that obviously won't work.

A Beginner's Guide to the ESP8266


Controlling EL wire or panels with arduino I understand that el wire and paper needs a special power source known as an inverter to light it up.

If I wanted to control it from an arduino, what point would I connect the arduino to the light or inverter?

upstream slow blinking

The simplest approach:
Use a relay to turn the lights on and off. Control that relay with an Arduino.
("How to turn a relay on and off with an Arduino?" is a separate question).

Cut either one of the wires feeding power into the EL inverter ("upstream of the inverter"),
and connect the 2 cut ends of the (formerly) one wire to the contacts of the relay.

power source ---- (relay contacts) ---- EL inverter ---- (EL wire)
           +--------------------------------+    +---------+

downstream slow blinking

Alternative approach:
Use at least 2 pieces of EL wire.
Wire one always-on;
use a relay to connect or disconnect the other wire ("downstream of the inverter"). (The relay and controlled wire can be either directly connected to the inverter, or end-to-end connected to the always-on wire -- it doesn't matter for this application).

                                   always on
power source ---- EL inverter ---- (EL wire) ---- (relay contacts) ---- (EL wire)
           +----------+    +---------+   +-------------------------------+

Control that relay to control the EL wire with an Arduino, same as before.

dimming and PWM

Many low-cost relays are rated for only about 10,000 operations, so if you use them to blink for a long or short part of each second, they're only guaranteed to last for about 3 hours.
If you want to blink faster than that (and most people dim EL lights by blinking them much faster than that), you'll have to use something other than a relay.

Also, most people seem to want to do the switching "downstream" of the inverter, so they can "share" a single EL inverter and use it to power lots of independently controlled pieces of EL wire.

Perhaps the simplest approach is to use an off-the-shelf zero-crossing solid-state relay (SSR).
("How to wire a SSR to an Arduino?" is a separate question).

power source ---- EL inverter
          +-----------+   | |
                          +----- EL wire (always on)
                          | +-----+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          ... etc.

Because most SSRs are overkill for this application -- most of them have heatsinks bonded to high-power triacs designed to handle far more current than we need to light up a EL wire --
some people save a few dollars by assembling their own SSRs out of zero-crossing optocouplers, triacs, etc.
(A lower-cost, low-power triac is more than adequate for controlling EL wire, even without a heatsink).

The SparkFun EL Escudo Dos Arduino shield for controlling electroluminescent wire(c)(d);
Diana's SparkFun EL Sequencer(e)(f)(g);
the seeedstudio EL Shield(h)(i)(j)(k);
Tully Gehan's Cool Neon Arduino Shield(m)
etc.
uses such zero-crossing optocouplers, triacs, etc.
(requires a separate EL inverter).

According to some people on the Arduino forums talking about EL wire(n)(p),
some people save a few pennies by using normal optocouplers rather than zero-crossing optocouplers. Non-zero-crossing optocouplers seem to work fine for short pieces of EL wire but seems to destroy the triacs (failing "always on") with a few dozen feet of EL wire.

Some people save a few more pennies by skipping the optocoupler,
wiring the Arduino directly to the control gate of the triac, and the VCC pin of the Arduino directly to the MT1 pin of the triac.
(q) (r) (s) (t)
If there were some way to only turn the triac on near the zero-crossing, this could work great; but without zero-crossing control, this has the same problems as the above normal non-zero-crossing optocouplers.

always-on

The "extra" always-on bit of EL wire is because some people say
"never run the inverter without at least 1 foot of EL attached"(a) because running some EL inverters with no load "can damage the inverter"(b).


nRF24L01+ RF24 library - can send but can't receive I'm prototyping out a board with temperature, humidity, windspeed sensors, and using an NRF2401+ board to send values to a Raspberry Pi base station that will record the data.

Using a Leonardo clone board, I'm able to successfully run the pingair_dyn sketch to send test payloads to the RPi and receive acks.  (So I know the RPi can send and recieve OK.)

Moving the same NRF2401+ to a breadboard setup with an ATMEGA328P-PU, the same sketch can send payloads which are received on the RPi, but always hits the timeout trying to get the ack (which the RPi is dutifully sending).

In fact when running pingair_dyn as a receiver, it just spins in the loop waiting for radio.available() to return true, which it never does.

The immediate problem is that radio.available() is always returning false.  So basically I can send but can't receive.

I have checked my wiring several times, and I'm mostly confident that it's right.

  CE - physical pin 14 (arduino digital pin 8 )
  CSN - physical pin 13 (arduino digital pin 7)
  SCK - physical pin 19, per atmega328 datasheet
  MOSI - physical pin 17, per datasheet
  MISO - physical pin 18, per datasheet

In the software, I construct the RF24 instance:

  RF24 radio(8,7);

Any ideas?  I tried swapping CE <--> CSN, then nothing worked.  Is there some wiring problem that would cause XMIT to work but RECV to fail?

I've tried putting a 2.2 uF capacitor across the 3.3V - GND as I've seen mentioned in other threads, but no difference.

Any suggestions on what is useful information to dig out of the RF24 library to give some idea of what's going on?

More background

Here is the RF24 debug info from the mega328

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1    = 0xf0f0f0f0d2 0xf0f0f0f0e1
RX_ADDR_P2-5    = 0xc3 0xc4 0xc5 0xc6
TX_ADDR       = 0xf0f0f0f0d2
RX_PW_P0-6    = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA       = 0x3f
EN_RXADDR    = 0x02
RF_CH      = 0x4c
RF_SETUP    = 0x07
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x3f 0x04
Data Rate    = 1 MBPS
Model       = nRF24L01+
CRC Length    = 16 bits
PA Power    = PA_MAX

Here is the debug info from the base station (Raspberry Pi):
pyRF24/examples/pingpair_dyn/

================ SPI Configuration ================
CSN Pin          = CE0 (PI Hardware Driven)
CE Pin           = Custom GPIO22
Clock Speed      = 8 Mhz
================ NRF Configuration ================
STATUS           = 0x0e RX_DR=0 TX_DS=0
MAX_RT=0 RX_P_NO=7     TX_FULL=0         RX_ADDR_P0-1     =
0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR          = 0xe7e7e7e7e7
RX_PW_P0-6       = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA            = 0x3f
EN_RXADDR        = 0x03
RF_CH            = 0x4c
RF_SETUP         = 0x07
CONFIG           = 0x0e
DYNPD/FEATURE    = 0x3f 0x04
Data Rate        = 1MBPS
Model            = nRF24L01+
CRC Length       = 16 bits
PA Power         = PA_MAX

The pins could be wrong for ATMega328.

It should be.

NRF24L01 - Arduino UNO
GND - GND
VCC - 3.3V
CE - 7
CSN - 8
SCK - 13
MOSI - 11
MISO - 12

or B. You need to connect a 500uF electrolytic capacitor to your NRF24L01+ VCC and GND pins directly. To reduce noise related issues. With clone arduinos/cheap regulators/clone NRFs then noise might start creating issues especially with receiving.


Can both the 3.3V and 5V pins on the Arduino be used at once for power? I'm supplying power to Arduino via PC USB.

Yes.

Here's a block diagram of how the Arduino power is arranged:

As you can see the USB power is fed through a FET (P-channel MOSFET) to isolate it when there is external power applied (as decided by the comparator COMP).  External power is fed through a 5V regulator and is fed to the same point as the USB power.  Thus you get the same 5V at the same point regardless of if you have USB or Barrel Jack power.  From there the 5V (wherever it comes from) is fed into a 3.3V regulator.  The 5V pin on the Arduino is connected directly to the 5V point where the USB and the 5V regulated input are connected. The 3.3V pin is connected directly to the output of the 3.3V regulator.

So no matter what input power arrangement you use - barrel jack, USB power, battery connected to the V IN pin (not shown, but connects to the barrel jack), or regulated 5V into the 5V pin, you get access to the same 5V and 3.3V power on the 5V and 3.3V power pins.


Can I use the nRF8001 Bluefruit LE Breakout on 3.3V instead of 5V on my Arduino Uno? I have an nRF8001 Bluefruit LE Breakout module and when I check images on how to wire it, the schematic looks like this with the 5V connection:

I was wondering whether it was possible to use the 3.3V instead. I looked at the documentation, it says this:

  By connecting 5.0V on the VIN pin, all of the signals will be level shifted between 5V for the Arduino and 3.3V for the nRF8001, meaning you don't need to worry about damaging the IC by providing logic levels that it can't safely handle.

And this, which confirms that it works, right?

  If you are using 3.3V logic, simply connect 3.3V from your development board to the VIN pin on the nRF8001 breakout.

I am pretty new, so I want to make sure, so I do not destroy any modules.

https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up

Yes. That nRF8001 board runs on 3.3V. And do make sure that using it with a 5V-Arduino, they put a regulator that steps down 5V to 3.3V. Which is why if you have 3.3V already, you connect it to Vin, and you're good to go.


Uploading Sketches from Windows Command Line The resources I've found regarding the Command Line interface seem to be out of date so I was hoping to find someone with experience using it. I'm currently running Arduino 1.5.6-r2 BETA on Windows 8.1 looking to upload code to an Arduino Leonardo.

I'm trying to create a script(Powershell) file that I can just use to upload code without user intervention. The actual upload part using Arduino CLI is just straight not working for me. If my understanding is correct I should have it already due to my version of the Arduino IDE but none of the functionality works so I'm doubting myself.

Source: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc

This is the command I'm attempting to run from Windows Command Prompt:

C:\Program Files (x86)\Arduino\arduino.exe --board arduino:avr:leonardo --port COM3 --upload C:\Users\Dev\Documents\Arduino\myProject\myProject.ino

Any insight into what I'm missing would be very much appreciated!

EDIT: Additionally, if anyone could provide information regarding the build/upload process which could lead me to a solution from within C# that would be even more amazing.

Turns out that the Ignoring Bad Library Name error that I had been receiving regardless of if I ran Arduino IDE through command line or standalone was the issue. For whatever reason it was blocking the script with a dialog that then failed the upload regardless of if I manually moved through the popup.

Final setup for those looking for this in the future:

Windows 8.1 x64 with Arduino IDE version 1.5.6-r2(I will revert to 1.0.5 and test with that, and report results) using a Leonardo board. Command is as follows:

Working Directory: C:\Program Files (x86)\Arduino

arduino --board arduino:avr:leonardo --port COM14 --upload C:\Users\Dev\Documents\Arduino\sketch_jun06a\sketch_jun06a.ino

EDIT: As promised, I attempted this with version 1.0.5-r2 and was unsuccessful. Potentially a 1.5.+ feature.


RTClib library dependency on Wire library I downloaded the RTClib library from https://github.com/adafruit/RTClib.  In every provided example, #include <Wire.h> is written immediately above #include "RTClib.h" at the top of the sketch.

Why is this necessary?  I know the RTClib library requires the functionality of the Wire library but, if this is the case, why can't I just #include <Wire.h> at the top of RTClib.h?  I have tried the latter, even using just the following sketch, but my sketch failed to compile.

RTClib.h:

// Code by JeeLabs http://news.jeelabs.org/code/
// Released to the public domain! Enjoy!

#ifndef _RTCLIB_H_
#define _RTCLIB_H_

#include <Wire.h>
...

#endif // _RTCLIB_H_

Sketch:

#include "RTClib.h"
void setup() {}
void loop() {}

Not getting too formal here, The arduino IDE looks at which libraries are included in the top level sketch when deciding what libraries to include in the compilation.

It would make sense for only RTClib.h to include Wire.h yes, but the IDE does not get the information to add Wire to the compilation list that way. It is a quirk of the IDE that makes implementing libraries that use other libraries a bit more painful.


User interface solutions Are there "user intefrace" solutions for Arduino based gadgets? Solutions, that is, accepted as something more or less standard by the community. I am unaware of the relevant keywords, if there are some, so let me explain:

A modern computer has a standard keyboard and a standard mouse, which together cover 99.99% of all the imaginable needs. Of course, you can plug the Arduino gadget into a computer via USB and enjoy full control via the Firmata protocol, for instance. What are the more lightweight solutions, if a laptop is too heavy, yet a pair of buttons not smart enough? In the range of smartphone to something calculator-like?

Sorry for being vague; it's a newbie question.

I doubt there are any standards for this. The reason is that 'hardware' solutions are very much more flexible than PC solutions (which by default have a keyboard, mouse and monitor) and not much more.

Hardware solutions on the other hand can have any kind of different displayed, touch screen, sensors of all kinds, leds/lights, hardware/mc controlled motors, relays, communication means etc.

The only user interface solutions are probably the libraries which can be used for some hardware, e.g. display driver drivers, led drivers, sensor libraries etc.

Especially to combine multiple hardware items (like on a PC the mouse, keyboard and monitor) gives a user interface 'experience'. Since hardware solutions have many more different hardware options, there is not a clear 'solution' for combining so many different hardware.


How to actually concatenate two Strings? I'm using the SPISlave library, and I have the following code snippet:

String arg;

SPISlave.onData([arg](uint8_t *data, size_t len) {
  data[len] = 0;
  arg += String((char *)data);
  // ...
}

The compiler doesn't like my string concatenation, though:

  /home/lars/sketch_apr01a/sketch_apr01a.ino: In lambda function:
  sketch_apr01a:65:12: error: passing 'const String' as 'this' argument
  of 'String& String::operator+=(const String&)' discards qualifiers
  [-fpermissive]
         arg += String((char *)data);

I've tried other versions as well, with similar results:

arg.concat((char *)data)
arg = arg + String((char *)data)
arg += String((const char *)data)

So how exactly do I write this unusual operation?

Your lambda is capturing arg by copy, which is most certainly not what
you want. And since it doesn't have the mutable qualifier, the
captured parameters are not modifiable. Hence the compiler error.

You could get rid of the error by qualifying the capture as mutable,
but you would then be modifying the captured copy of arg, not the
original one. The correct solution would be to capture the String by
reference instead of capturing by copy. See Lambda
expressions.

But then, I concur with Michel Keijzers that avoiding Strings altogether
is a better option.


How can I measure maximum range of my ohm meter? Hello everyone I am working on a project that will measure ohm value of a resistor .
Schematic / article link
https://create.arduino.cc/projecthub/iasonas-christoulakis/how-to-make-an-arduino-ohm-meter-90fda8
And
Here is the code below
int analogPin= 0;
int raw= 0;
int Vin= 5;
float Vout= 0;
float R1= 1000;
float R2= 0;
float buffer= 0;

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

 void loop()
{
raw= analogRead(analogPin);
if(raw)
{
buffer= raw * Vin;
Vout= (buffer)/1024.0;
buffer= (Vin/Vout) -1;
R2= R1 * buffer;
Serial.print("Vout: ");
Serial.println(Vout);
Serial.print("R2: ");
Serial.println(R2);
delay(1000);
}
}

There need to be a known and another unknown resistor.
The ohm value of known resistor is supposed to be 1k ohm
So my question is, what is the max ohm range will my arduino ohm meter will be able to measure of the unknown resistor with 1k reference resistor and how to calculate it?
5 - 10% accuracy is enough for me
Thanks for giving me your attention :D


How to initialize digital output pin as low I need to define a pin as output for relay module but when i do it in setup section, relay is activated (low - 0) automatically then i deactivated immediately with coding digitalWrite(pin, 1) but this issue results the relay is activated then deactivated within miliseconds. But I want to know that is it possible to define a pin as output but low in default.

void setup(){
  pinMode(pin,OUTPUT);
  digitalWrite(pin,1);
}

void loop(){
  if(start_relay){
    digitalWrite(pin, 0);
  }
}

There are two solutions:

Use the pin as a open-collector pin as in the answer of VE7JRO.
Switch the pin between input (high) and output with low. I prefer
to use the INPUT_PULLUP.
Write the output value before setting the pinMode.

All the microcontrollers of the AVR family (ATtiny and ATmega chips) allow to set the output value before setting the pin as output. This will enable the pullup resistor, but when it is done in the right order, that is fine.

Because this is a common way to use the microcontrollers and processors, the Arduino libraries allow to use that. The Arduino libraries for the SAMD processors (Arduino Zero, M0 and MKR) are written to allow that as well.

void setup() {
  digitalWrite(pin,HIGH);     // pre-set output value to HIGH
  pinMode(pin,OUTPUT);        // set to output, it will be HIGH
}

void loop() {
  digitalWrite(pin,LOW);
  delay(1000);
  digitalWrite(pin,HIGH);
  delay(1000);
}

When the relay module has floating inputs (as far as I know they do not) then you need extra hardware to pull the signal high with a pullup resistor to keep the relays disabled during reset.