What info should I look for when choosing a solid state relay for arduino? I want to control a phone using an arduino board by connecting each pin of the arduino to a button on the phone using relays to simulate a button being pressed or release by switching a relay (on/off). I am using relays because from what I have seen (Use Arduino to Switch Power On and Off! ) relays are controlled swiches and I am using SSR because I want to use the less space possible.

I'm trying to buy a relay at mouser.com but I don't know what are the values I should look for, for those parameters (Control Voltage Range, Load Voltage Rating, Load Current Rating, Input Current).

If you're only controlling a button, the load current and load voltage are pretty much irrelevant since I'd be surprised if you even used 5% of it's rating in either category. I can't tell you how much you'll need here since I don't know the voltage that the relay will be operated on and the resistance of the path for the load.

What you do need to look at is the voltage and current of the input/control/logic signal. It should allow a 5V control voltage and the current draw for that logic signal should be no more than 40mA, although it's ideal to stick to a lower number (say, 30mA).

However, manually picking out a relay manually isn't ideal for a beginner since it requires a bit of extra components to properly run. A relay module (Amazon) allows you just hook up your wires to the jumpers and terminals of the relay module without any extra soldering (as far as I know they aren't breadboard compatible, thus requiring a custom PCB or having it "flop") or parts.


I'd like to make RC car and remote controller via bluetooth (HC06) At first, I tried to make whole code for an RC car and remote controller, but I realized that it's difficult for me since I have few ideas about C++. So, I changed a few things like turning on the LEDs with switches and servomotors with potentiometer. Here are my code.

Remote controller

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(2,3);
int sw1=13;
int sw2=12;

void setup() {
  BTSerial.begin(9600);
  Serial.begin(9600);
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
}

void loop() {
  int a = analogRead(A0);
  int map_a=map(a,0,1023,0,255);
  int state1=digitalRead(sw1);
  int state2=digitalRead(sw2);

  BTSerial.print('S');
  BTSerial.print(map_a);
  BTSerial.print(',');
  BTSerial.print(state1);
  BTSerial.print(',');
  BTSerial.print(state2);
  BTSerial.print('E');
  delay(100);
}

< RC CAR >

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(2,3);

byte buffer[255];
int bufferPosition;

void setup() {
 BTSerial.begin(9600);
 Serial.begin(9600);
 bufferPosition=0;

}

void loop() {
  {
    if(BTSerial.available()>0){
    unsigned char data = (unsigned char)BTSerial.read();
    buffer[bufferPosition++]=data;
    Serial.println(data);
    delay(100);
    }
}
}

When I checked the result from Serial.println(data) from RC car code,
it was trash...

Can you instruct me what's wrong with this code?

There are some fundamental problems in the code - bufferPosition never stops increasing (until it reaches 32768) and so buffer will overflow. However, neither of these two problems are causing the 'trash', as you are outputting the result of reading the serial, not anything from the buffer.

The problem lies in the casting of the result from BTSerial.read() to unsigned char.

Serial.print() does not like this. Actually it doesn't care, but it won't give you what you expect. It just prints out the value stored - so 'a', which is 97, will come out as '97' on the serial monitor. Serial.print() only outputs ASCII characters when you give it a char or char[].


burn arduino bootloader and compiled sketch at same time How can I write the bootloader and sketch code to an Arduino through the ISP and then write the sketch code again using the Arduino IDE later?

Currently, I can write the bootloader through the ISP and then write the sketch through the Arduino IDE.  This works just like normal.

I can also write the bootloader and sketch through the ISP.  The code runs like normal, but I can't load a new version of the sketch through the Arduino IDE.  It just timesout.

Here's what the IDE says when it attempts to upload the program:

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

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

         Using Port                    : COM5
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

The Arduino IDE creates two hex files after compiling the sketch: one is just the compiled sketch (Sketch.ino.hex) and the other is the compiled sketch with the bootloader code appended to the end (Sketch.ino.with_bootloader.hex).  So, I feel like this should be possible because Arduino produces the file for me.

If you program via ISP, it erases the boot loader, because you do not need it. The whole point of the boot loader is to allow programming over USB. So if you want to use the normal Arduino USB input to program, burn the bootloader and then do not use the ISP.

Note my knowledge of this dates back to older arduino ~1.0 software, it is possible modifications have been made, but the above should still be true. If you have an ISP you do not need the bootloader at all.


Can an Arduino be used to read data from a serial port? People often use Arduinos to send data over serial to other peripherals (flashing firmware onto modules, etc) by pulling RES to ground,  connecting the TX and RX pins to the device being programmed, and then sending data to the Arduino over serial. As an alternative, one could also remove the ATmega instead of grounding RES.

That being said, there should be no reason why one could not receive data from a connected device in the same way. However, no matter what I try, I never succeed in using an Arduino to relay serial input from another device over USB.

I have even tried setting up a simple echo to no avail (even though the TX and RX LEDs flash):

Is it even possible?

Yes, it can, and the wiring diagram you have drawn works perfectly for me using minicom in Ubuntu.

The majority of serial communication is bi-directional anyway - especially when using it to program a device.

There is absolutely no difference between interfacing the built-in USB->UART adaptor to an external device of your choice and interfacing it with the ATMega328P chip. Just because the ATMega328P chip is on the same board doesn't make it in any way special - it is just a UART interfaced device.

If your setup is not working you can try:

Physically remove the ATMega328P chip to see if that is interfering even when held in reset
Check for software that may be interfering with your communication, such as the notorious ModemManager.


How do I know how many memory that Arduino is use after my code is running for a few time When I upload my program to Arduino it says the memory that the program is used. But what if I use a bad management of dynamic memory, or any object is created several times in use a lot of memory and the Arduino memory overload.

How do I know the current size of memory that Arduino is use?

I am thinking about to create a function in Arduino that return me this information if I send it a request command, but also I don't know how do I inspect the Arduino memory.

Note: I am using the Board: Arduino Mega 2560.

I read the question and the answer for Measure SRAN usage

In the question @fuenfundachtzig ask:

Can I determine how much SRAM I have left in the live system?

In my question I am asking about how do I know or monitoring my program memmory. Ok the Measure SRAN usage answer give me the tips or tools to develop my idea, but the question is not the same.

I am tryin to know in an specific time what is the size of my memmory.

example...

void setup() { //doing some configuration };

void loop() {  // invoke some functions and evil function  };

// in other place a evil function

void evil(){
MyClass * instance = new MyClass();
//play with the instance and it class create other instances....
//and a dynamic memmory is used but not deleted.
}

I am trying to know if it happens and how do I detect with Arduino? I am not talking about how much memmory do I left in the live system.

Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.

You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain).

You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.


Arduino Zero - Stepper control (interrupt)? I have a stepper controller board that I need to pulse every 40 uS or so.

I also have I2C sensors and Serial writes to preform.

Currently I run an update call in a tight loop, but the I2C sensors and Serial writes cause considerable delays which makes the motors stutter and come to a halt.

I would like to use an ISR to call the motor update method periodically.

However I cannot for the life of me figure this timer stuff out.

Here's my current attempt:

void TC4_Handler() {
  Stepper::updateAll();
}

void setup() {

  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 0x000F;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
  // ...
}

As Stepper::updateAll(); isn't shown I don't know what it does.  For accurate timing it would make sense to use hardware-operated output-compare output pins like TIOAx and TIOBx, instead of running some code to drive the pins when an interrupt occurs.

If you need to control several wires per motor – such that a pulse on a single output line isn't enough – you might consider using a 74HC595 (or other shift register) to transfer the bits.  Thus, each time an output compare occurs, the  TIOAx and TIOBx line would pulse the ST_CLK (store-clock) line of the SR, to transfer bits from the shift chain flipflops to the output flipflops; then, at its leisure the interrupt routine can shift the next set of bits out to the '595, ready to be transferred at the correct moment, when the next output compare occurs.

During stepper acceleration or deceleration, the timer count-limit would also need to be updated within the ISR.


I don't know how to do the code for an rtc controlling a relay I'm doing a project for my brother witch is an automatic watering thing,
it's all working fine but I just don't know how to repeat the code to make the relay say come on for 5min at 0900 than 5min at 1200 and also 5min at 1700.
how do I do this, I'm not very good at this so I need clear instructions or someone to write it.
pls help.
thank you, James.

here is the code I need to be repeated to meet what I need done, basically I just need the relay to trigger every 4h for 5min. its on an rtc on an Arduino UNO.

#include <DS3231.h>

int Relay = 4;

DS3231  rtc(SDA, SCL);
Time t;

const int OnHour = 19; //SET TIME TO ON RELAY (24 HOUR FORMAT)
const int OnMin = 55;
const int OffHour = 19; //SET TIME TO OFF RELAY
const int OffMin = 56;

void setup() {
  Serial.begin(115200);
  rtc.begin();
  pinMode(Relay, OUTPUT);
  digitalWrite(Relay, LOW);
}

void loop() {
  t = rtc.getTime();
  Serial.print(t.hour);
  Serial.print(" hour(s), ");
  Serial.print(t.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay (1000);

  if(t.hour == OnHour && t.min == OnMin){
    digitalWrite(Relay,HIGH);
    Serial.println("LIGHT ON");
    }

    else if(t.hour == OffHour && t.min == OffMin){
      digitalWrite(Relay,LOW);
      Serial.println("LIGHT OFF");
    }
}

You will most likely find nobody here, who will write the code for you, since this is not a free code writing service. But I will suggest a good way.

  I just need the relay to trigger every 4h for 5min

The phrase "every x hours" screams for using the modulo operator %. Modulo gives you the rest value of an integer division. See these values:

0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
...
7 % 4 = 3
8 % 4 = 0

You see, the modulo 4 operation gives you zero every 4 hours starting with midnight. So make an if statement based on that

if(hour % 4 == 0 && min == 0)

to switch on and

if(hour % 4 == 0 && min == 5)

to switch off. Just change your code in this way and you are done.


What components do I need to build Arduino based water pump controller? I have situation at my home which is causing us a lot of headache. We get drinking water only at midnight and someone has to wake up and switch on electric pump. This electric pump will pump water from water tank present at ground floor to the water tank present on the terrace.

I want to automate this electric pump operation and I have come up with following rules for it:

When water tank at ground floor is almost full then automatically turn on the pump which will push water from ground floor to the tank on the terrace.
When water tank on the terrace is full then switch off motor.

I am a professional software engineer and I have vast experience in Java, Scala, REST API, Big Data and all but I am totally new to Arduino so I do not know which Arduino components I need to build the above mentioned system.

Any guidance will be deeply appreciated.

Thanks,
Chandra

If you are controlling an AC pump, you might look into a PowerTail switch, which allows you to control AC power easily and relatively safely, but of course, if you are working with anything around water, be careful!  http://www.powerswitchtail.com/


Which container to use? So for my project, I am measuring heartbeat of a person in a span of 10s. However, as the number of heartbeats may differ for each person, is it wise to use a vector?

No, you don't want a vector, for a number of reasons:

There is no "vector" unless you add extra (unsupported) code.
Vectors use dynamic memory. Arduinos don't work well with dynamic memory.
It's pointless anyway.

Just allocate an array big enough to contain enough timestamps. In a 10 second period, if you get more than 100 beats, the person you are measuring the heart rate of is most likely in a noticeably "unfortunate" state. That's 600bpm. That's entering panicked mouse territory.

Even with that extreme number of beats an array of 100 32-bit values is only 400 bytes.


collecting & visualizing sensor data - best approach? I'm working on a kite-related project where I'm using Arduino + accelerometer to track data while a kite is in the air. I am struggling a little with the best approach - help on the following questions / issues would be a huge help:

-- how best to grab data only while the kite is in the air? just detect with numbers, use a switch? other ideas?
-- how best to collect the data and transfer to computer for visualization (likely with processing but looking at other options). i'm using this project in workshops with kids in low-income neighborhoods in brazil, so will have limited resources. a laptop will be available -but use of mobile also ideal.

Thank you!
Claudia

Several possibilities; Both at little cost, but since you have an accelerometer, I know your budget is not 0.

1) use a shield with an SD card on the arduino to log the information to a file on the SD card.  Open it later from a laptop or PC.  Hopefully it will have enough room to store data that you can ignore later for pre-flight, post-flight time.  If not, simply add some fixed delay to the start of your program (loop 5 times; wait 1 minute;)

2) some form of remote, like an XBee, or even a wireless WiFi Shield. The setup can be complicated but that would be ideal for real time visualization on a laptop at the flying site.

3) probably the easiest/least expensive - a cheap bluetooth transmitter.

eBay

This method would allow a bluetooth mobile to collect and visualize the data. This device connects to the serial lines on an arduino, (pin 0&1) and standard Serial.Write() function can be used.  Any terminal program for your mobile will be able to receive the data. You could also get fancy and write your own if you want to visualize it. You may be able to find something already existing, like this

In cases 2 & 3 you will need a way to xmit the data. I use MQTT. A protocol just for this, but it is TCP only. I also use it with JSON (eg Json for Arduino to manage the data.  You will need to find the same. Look at MQTT-SN as a possibility, or you can just write your own serialization protocol based around JSON without too much difficulty.


SIM800L project not working I got a SIM800L, same as the one under this link, Quickstart SIM800 (SIM800L) With Arduino, and played around with an Arduino Nano and Uno. I had a few problems, at the start, not getting it work properly. It turned out that my Nano 5V pin wasn't enough for the SIM unit. It works fine with Uno though.

There is the code I tested the GSM (same link) and got it working somehow, I got simple AT commands and managed to send an SMS. But after I dismantled the connections and the next day I tried again... Nothing. I can see the SIM unit connects to network as the LED blinking slows down to once every 3 seconds but when I type commands in nothing happens in the serial monitor. It doesn't give errors or anything, just nothing happens on the serial monitor.

I did wire it incorrectly, once with the Tx/Rx, but that shouldn't damage the unit, should it?

I tried to upload different programs to my Arduino and they work fine so that shouldn't be the problem. Is there a way to reset the SIM800 unit? Or am I missing something here?

The module needs a good 5v supplier as it might have a peak of 1A or 2A, when it registers to the network or connects to 3G.

You need to make sure that you share the ground between the power supplier and you use some 2 pins on your arduino to connect the GSM module.
Dont try to get a fast baudrate as software serial doesnt work, try with 9600 to start then see if it response to the AT command.

SIM800 is a very simple module, try with an FTDI in case you want to make sure you didnt break your Arduino.

For more help, share your schematic how you have connected the arduino.


Reading sensor data over MUX I will start by saying I am very new to using Arduino.  The project I am planning is to create several arrays of sensors (each array will consist of 4 DS18B20 sensors and one temperature/humidity sensor) and using a MUX connected to Arduino I want to read the data from each [ten] array.  I have found sketches I can modify to do this task in a continuous cycle but I need to be able to display data from an array for an extended time period of several minutes.  My Arduino will output to a 3.2" LCD so there is only enough screen space to show data for one array at a time.

The DS18B20 is a 1-Wire device and doesn't require a multiplexer, each device has its own address on the bus and you can connect a lot of them with a single wire. Depending on the humidity sensor you pick you may be able to use the same bus for it as well.

It is harder to find 1-Wire humidity sensors, but you could use a DS2438 Smart Battery Monitor which also includes an ADC to give you values from an analog humidity sensor.

The challenge of designing your project will be setting up an easy to understand display and controlling how/when it changes.


Help a noob, no idea on Programming, only started 2 days ago Help please As said no programming skills only started 2 days ago when Nano arrived.
Heads in bits. This is how far i got. Any help much appreciated..
int EMagnetPin = 8;
int solenoidPin = 9;
int ReedPin = 13;

void setup()
{
  pinMode(EMagnetPin, OUTPUT);     // assign pin type
  pinMode(solenoidPin, OUTPUT);   // assign pin type
  pinMode(ReedPin, INPUT);        // assign pin type
  Serial.begin(9600);             //serial port open

void loop()
{
Serial.print(digitalRead(ReedPin));
if (digital REad(ReeddPin)==0 ) {
digitalWrite(solenoidPin,HIGH);

                  // Once magnet applied to Reed Switch Will activate the below

  digitalWrite(EMagnetPin, low);
  delay(11000);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(500);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(22500);
  digitalWrite(EMagnetPin, HIGH);
  delay(500);
  digitalWrite(EMagnetPin, low);
  delay(500);                          // Stops EMagnet
  digitalWrite(solenoidPin, HIGH);     //Start Solenoid
  delay(500);
  digitalWrite(solenoidPin, low);
  delay(500);
                    // Program Ends

I presume you got some errors, like this:
/tmp/arduino_modified_sketch_836883/sketch_oct30a.ino: In function 'void setup()':
sketch_oct30a:13:3: error: a function-definition is not allowed here before '{' token
   {
   ^
sketch_oct30a:37:17: error: expected '}' at end of input
       delay(500);
                 ^
exit status 1
a function-definition is not allowed here before '{' token

You have to read those. At the end of a function you need a closing brace. So, setup for example would look like this:
void setup()
{
  pinMode(EMagnetPin, OUTPUT);     // assign pin type
  pinMode(solenoidPin, OUTPUT);   // assign pin type
  pinMode(ReedPin, INPUT);        // assign pin type
  Serial.begin(9600);             //serial port open
}   // <------- ADD THIS

Ditto for the end of the loop function.
The next problem is this line:
    if (digital REad(ReeddPin) == 0 ) {

The function "digitalRead" is spelt like that, not as two words. Also you misspelt "ReedPin" as "ReeddPin".
You have to go carefully through your code, look at the error messages, and fix them one by one. C++ is case-sensitive, you can't just thrown in extra spaces in the middle of words, and you have to be consistent with your variable names (ie. not misspell them).

I suggest you do a C++ tutorial, or find an Arduino tutorial. These are basic coding mistakes made by beginners. With a bit of practice, and some working through examples, you will stop making them.


Bizarre compilation problem -- only compiles with the addition of a single Serial.println() line? I have a SwitchDoc Labs DS3231 Real Time Clock Module that I am using with an Arduino Mega.  It's connected to 3.3V and the SDA(20)/SDL(21) pins.  I'm also using SwitchDoc's RTC_SDL_DS3231_ARDUINO library (see link to the example sketch below).

I can compile and run the example provided with the library just fine.  However, I'm running into a very bizarre compilation problem when I remove the Clock set function calls in the setup.

Rather than take up the space and copy the code that works I'll just link to it on github: 100% working for me example.

The problem I am running into happens when I remove (or comment out) the section in the setup function that sets the time:

void setup() {
  // Start the I2C interface
  Wire.begin();
  // Removed code
  // Start the serial interface
  Serial.begin(9600);
}

Then I get the following error when I try to compile/verify the sketch:

/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/../
lib/gcc/avr/4.3.2/../../../../avr/lib/avr6/crtm2560.o: In function `__vector_default':
(.vectors+0x90): relocation truncated to fit: R_AVR_13_PCREL against symbol `__vector_36'
defined in .text.__vector_36 section in core.a(HardwareSerial.cpp.o)

If I add back just one single clock set call it will compile:

void setup() {
  // Start the I2C interface
  Wire.begin();
  Clock.setYear(15);  //Set the year (Last two digits of the year)
  // Start the serial interface
  Serial.begin(9600);
}

However, the truly strange thing is that if I simply add a Serial.println() line to the setup function, the sketch compiles too!

void setup() {
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  // Adding the following line allows the sketch to compile
  Serial.println("Why does this work now???");
}

Thanks for any help.

Update: This seems to be a linker bug. Quick fix: upgrade your
Arduino installation. See the end of this answer for details. What
follows is the first version of this answer, with a detailed explanation
of the error message.

You have a problem linking the interrupt vector table with your program.
I quite understand what the error message means, but I do not understand
how in the world you can possibly have this error. This should not
happen. I will try to explain the error anyway.

The Arduino Mega is based on an AVR chip. The AVR instruction set has
“jump” and “call” instruction that come in two flavors:

“absolute” jumps and calls (opcodes: jmp and call) can address the
whole flash memory, which means you can branch from any part of the
program to any other part, without restrictions.
“relative” (a.k.a. “PC-relative”) jumps and calls (opcodes: rjmp and
rcall) have limited range: they can only bring you to nearby places,
no more than 4 K from your starting point.

The relative flavors take less space and execute faster, they are thus
better if the destination is close enough. On the smaller AVR chips
(up to 8 K of flash), they can access the whole flash, then these
chips lack the absolute flavors.

How the vector table is normally linked

Every program you build for an AVR starts with an “interrupt vector
table”. This is a series of jump instructions that are automatically
executed whenever an interrupt triggers: if the n-th supported
interrupt triggers, then the hardware automatically loads and executes
the n-th jump instruction, which will jump the execution of the
program to the corresponding ISR (interrupt service routine). The
table is chip-specific: on the smaller AVRs (up to 8 K), it's a
table of rjmp, whereas on the bigger ones it's a table of jmp. This
table is part of the CRT (C run time) provided by the avr-libc library
in a file named crtXXX.o, where XXX is a code identifying the chip. The
Arduino Mega being based on the ATmega2560 chip, it's CRT is crtm2560.o.

I disassembled my own copy of crtm2560.o and found this vector table:

00000000 <__vectors>:
   0:   0c 94 00 00     jmp 0
   4:   0c 94 00 00     jmp 0
   8:   0c 94 00 00     jmp 0
   ...
  e0:   0c 94 00 00     jmp 0

You can see these are all jmp instructions (absolute flavor), as
expected for any AVR with more than 8 K of flash. The address of
the jump, however, is always 0, which is obviously wrong. This is
because the proper addresses cannot be known until the program is fully
built. When you build your program, the linker will put all the pieces
together. It will then know where the ISRs are, and it will patch the
vector table to make it correct. This kind of patching is known as
“relocation”, and the linker performs this based on some “relocation
records” included in the CRT. Here are the relevant records from my copy
of crtm2560.o:

RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_CALL        __init
00000004 R_AVR_CALL        __vector_1
00000008 R_AVR_CALL        __vector_2
...
00000090 R_AVR_CALL        __vector_36  [*]
...
000000e0 R_AVR_CALL        __vector_56

The record I marked with [*] means: “at offset 0x90 into the vector
table there is an absolute jump or call instruction, and the instruction
should be modified to point to __vector_36”. This tells the linker
how to fix the table when building the program.

If I instead disassemble a CRT for a smaller chip, I get a smaller table
made of rjmp (instead of jmp) instructions, and the relocation
records look like this:

RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_13_PCREL    __init
00000002 R_AVR_13_PCREL    __vector_1
00000004 R_AVR_13_PCREL    __vector_2
...
00000032 R_AVR_13_PCREL    __vector_25

These records mean “at offset XXX into the vector table there is a
PC-relative jump or call instruction, and the instruction should be
modified to point to __vector_XXX”.

Your error message

Your error message provides the following information:

“crtm2560.o”: this is your CRT, where the vector table and the
relocation records live.
“.vectors+0x90”: this means the problem is at offset 0x90 into the
vector table.
“R_AVR_13_PCREL against symbol `__vector_36'”: this means there
is a relocation record of type R_AVR_13_PCREL (PC-relative jump or
call) referencing __vector_36. Here seems to be the problem.
“defined in [...] core.a(HardwareSerial.cpp.o)”: this __vector_36
is part of the serial port code from the Arduino core library.
“relocation truncated to fit”: __vector_36 is too far to be reached
by a PC-relative jump, thus the linker could not relocate properly.

The problem seems to be that the relocation record is of type
R_AVR_13_PCREL, which is what you expect on smaller chips but not on
your ATmega2560. You normally expect R_AVR_CALL.

Now, about the strange behavior: the exact point where the ISR lands
when the program is built is difficult to predict. Add or remove a few
lines in your code and the linker may bring the pieces together in a
different order. Then, the infamous __vector_36 may end up being in
range or out of range of a relative jump. Given the nature of the error,
the behavior you find “strange” is actually quite normal.

Further debugging

The root of the problem seems to be an incorrect relocation record in
your CRT. You can try to disassemble the CRT to see what is wrong:
search your computer for a file named crtm2560.o, probably in
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/lib/avr6
or a similar place. The tool needed for disassembling is called
“avr-objdump” and should be hidden somewhere in your Arduino
installation folder. Once you find the files, start a terminal and type

/path/to/avr-objdump -d /path/to/crtm2560.o

with “/path/to” replaced by the actual paths. You should see something
very much like the first listing of my answer, with lots of jmp
instructions. If you have rjmp instructions instead, then something is
already wrong at this level.

To see the relocation records, type:

/path/to/avr-objdump -r /path/to/crtm2560.o

The output should look like my second listing, with lots of R_AVR_CALL
records. If you have R_AVR_13_PCREL instead, the records are wrong.

If this is the problem, then the obvious fix would be to replace the
broken CRT with a sane one. You may try to reinstall the whole Arduino
package. If you still have a corrupted CRT, you should report the error
to the Arduino folks. Then you may try to fetch a fresh copy of the
avr-libc and replace the relevant
parts of your Arduino installation. Replacing just the CRT may or may
not work: I don't know whether the last version of the CRT has
incompatibilities with older versions of the rest of the libc.

Update: this is a linker bug

I did some research, and I now believe you have hit a linker bug. There
is a gcc option called -mrelax that allows some link-time
optimizations. One if them is to have the linker replace some absolute
jumps and calls by the smaller and faster relative ones. Obviously, this
is only possible if the target address is within reach of the relative
jumps or calls. There was a bug in old versions of the GNU linker (up to
2.22) where, under some obscure circumstances, it would erroneously
believe the target was reachable, only to find out later that it was
not. This bug mainly affected the interrupt vector table, producing the
kind of error message you are seeing now.

Here is a partial timeline of this bug and its fix:

November 2011: this is filed as
bug 13410
on the bug tracker for the GNU binutils package.
January 2012: Vidya Praveen, from Atmel, publishes a fix.
February 2012: the fix is committed to the development version of
binutils.
October 2012: GNU binutils 2.23 is released, including the fix.
The same month, the bug is reported again as
issue 1071
on the Arduino issue tracker.
June 2013: Paul Stoffregen links this new issue to the old bug.
June 2014: Arduino gets an updated
toolchain
including binutils 2.23.2, which fixes the bug in the development
version of Arduino.
July 2014: Arduino 1.5.7 beta is
released including the
updated toolchain.
September 2014: Arduino 1.0.6 is released with the old toolchain.

A workaround for the bug has been
published by Mark Anderson on stackoverflow. The real fix, however,
would be to upgrade to the latest Arduino package (1.6.1 as of this
writing).


Particle Spark (Arduino) How to flash 2 LED sequences at the same time? I can't find any information that relates to my problem. The few things I did find confused me (I'm quite new to this).

I'm trying to flash 2 sequences of 4 lights at the same time. I can get 1 set flashing but I don't know how to run other sequences at the same time. My probably laughable attempt at the code is below:

int led1 = D0;
int led2 = D1;
int led3 = D2;
int led4 = D3;
int led5 = D4;
int led6 = D5;
int led7 = D6;
int led8 = D7;

void setup() {
  setupPart1();
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  setupPart2();
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  pinMode(led8, OUTPUT);
}

void loop() {
  loopPart1();
  digitalWrite(led1, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led1, LOW);
  digitalWrite(led2, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led2, LOW);
  digitalWrite(led3, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led3, LOW);
  digitalWrite(led4, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led4, LOW);
  loopPart2();
  digitalWrite(led5, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led5, LOW);
  digitalWrite(led6, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led6, LOW);
  digitalWrite(led7, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led7, LOW);
  digitalWrite(led8, HIGH);
  delay(500); // delayed for half a second
  digitalWrite(led8, LOW);
}

I cover this exact question in my web page: http://www.gammon.com.au/blink

Example code that blinks two LEDs at different rates:

// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop


Controlling stepper motor direction with push buttons I'm trying to control the direction of three 28byj-48 stepper motors using the ULN2003 drivers. I am using 6 push buttons, 2 for each motor. what I want is for each motor to be stationary by default and rotate forward when I press on one button and reverse when I press the other.

You can find my code below. When I use the same approach for coding for one motor, it works fine with a suitable speed. But once I add all 3 motors, motor A and C perform fine but with low speed, motor B keeps rotating forward from the start, stops while I'm pushing its forward button and nothing happens when I push its reverse button. I have checked my circuit several times and there's nothing wrong with it.

#include <Stepper.h> //including stepper motor library

//defining pins section

// pins for motor A:
int stepAIN1Pin = 5;
int stepAIN2Pin = 4;
int stepAIN3Pin = 3;
int stepAIN4Pin = 2;

// pins for motor B:
int stepBIN1Pin = 9;
int stepBIN2Pin = 8;
int stepBIN3Pin = 7;
int stepBIN4Pin = 6;

// pins for motor C:
int stepCIN1Pin = 13;
int stepCIN2Pin = 12;
int stepCIN3Pin = 11;
int stepCIN4Pin = 10;

int stepsPerRevolution = 2048; // amount of steps per revolution for the 28BYJ48 motor

int buttonA1Pin = A5;  // pushbutton 1 pin for clockwise rotation of motor A
int buttonA2Pin = A4;  // pushbutton 2 pin for counter clockwise rotation of motor A

int buttonB1Pin = A3;  // pushbutton 1 pin for clockwise rotation of motor B
int buttonB2Pin = A2;  // pushbutton 2 pin for counter clockwise rotation of motor B

int buttonC1Pin = A1;  // pushbutton 1 pin for clockwise rotation of motor C
int buttonC2Pin = A0;  // pushbutton 2 pin for counter clockwise rotation of motor C

Stepper myStepperA(stepsPerRevolution, stepAIN1Pin, stepAIN3Pin, stepAIN2Pin, stepAIN4Pin); // stepping sequence for motor A

Stepper myStepperB(stepsPerRevolution, stepBIN1Pin, stepBIN3Pin, stepBIN2Pin, stepBIN4Pin); // stepping sequence for motor B

Stepper myStepperC(stepsPerRevolution, stepCIN1Pin, stepCIN3Pin, stepCIN2Pin, stepCIN4Pin); // stepping sequence for motor C

void setup()
{
  // Setting up the pushbutton pins to be an input:
  pinMode(buttonA1Pin, INPUT);
  pinMode(buttonA2Pin, INPUT);

  pinMode(buttonB1Pin, INPUT);
  pinMode(buttonB2Pin, INPUT);

  pinMode(buttonC1Pin, INPUT);
  pinMode(buttonC2Pin, INPUT);

myStepperA.setSpeed(15); // Setting the speed for motor A

myStepperB.setSpeed(15); // Setting the speed for motor B

myStepperC.setSpeed(15); // Setting the speed for motor C
}

void loop()
{

int buttonA1State, buttonA2State, buttonB1State, buttonB2State, buttonC1State, buttonC2State;

  buttonA1State = analogRead(buttonA1Pin);
  buttonA2State = analogRead(buttonA2Pin);

 if ((buttonA1State != 0) && !(buttonA2State != 0))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(stepsPerRevolution/8);

 if (((buttonA2State != 0) && !(buttonA1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(-stepsPerRevolution/8);

  buttonB1State = analogRead(buttonB1Pin);
  buttonB2State = analogRead(buttonB2Pin);

 if (((buttonB1State != 0) && !(buttonB2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(stepsPerRevolution/8);

 if (((buttonB2State != 0) && !(buttonB1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(-stepsPerRevolution/8);

  buttonC1State = analogRead(buttonC1Pin);
  buttonC2State = analogRead(buttonC2Pin);

 if (((buttonC1State != 0) && !(buttonC2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(stepsPerRevolution/8);

 if (((buttonC2State != 0) && !(buttonC1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(-stepsPerRevolution/8);

  }

Try using digitalRead() for button presses. Chances are your buttons, especially when on a breadboard, don't return exactly 0 for analogRead().

IMHO, simple On-Off switches should always connect your pin to either Vcc or GND, with either the internal pullup turned on (if connected to GND), or an external pulldown resistor in place.

To debug this, you might want to Serial.println() the values of your button states to your Arduino IDE and observe if their values are like you'd expect.


DS1307RTC Outputting cryptic 165/165/2165 date. What are some possible fixes? My board.

I think I have it wired correctly (the lights aren't, but the board is).

I've read through the first few Google results to no avail.

My sample code to test the chip:

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
     rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
    }

void loop () {
DateTime now = rtc.now();

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" (");
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
Serial.print(") ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();

Serial.print(" since midnight 1/1/1970 = ");
Serial.print(now.unixtime());
Serial.print("s = ");
Serial.print(now.unixtime() / 86400L);
Serial.println("d");

// calculate a date which is 7 days and 30 seconds into the future
DateTime future (now + TimeSpan(7,12,30,6));

Serial.print(" now + 7d + 30s: ");
Serial.print(future.year(), DEC);
Serial.print('/');
Serial.print(future.month(), DEC);
Serial.print('/');
Serial.print(future.day(), DEC);
Serial.print(' ');
Serial.print(future.hour(), DEC);
Serial.print(':');
Serial.print(future.minute(), DEC);
Serial.print(':');
Serial.print(future.second(), DEC);
Serial.println();

Serial.println();
delay(3000);
}

Serial output:

`RTC is NOT running!
2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

2165/165/165 (Tuesday) 165:165:85
 since midnight 1/1/1970 = 1551138385s = 17952d
 now + 7d + 30s: 2019/3/5 12:16:31

Put in the following line in void setup():

Wire.begin();

(Assuming Wire library has been included.)
This will set up the I2C connection between the Master (Arduino) and the Slave (RTC).

For more generic use, the syntax is: Wire.begin(address);

The complete code is:

void setup () {
  Wire.begin();
  Serial.begin(9600);
  //rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // UNCOMMENT TO SET TIME & DATE TO THAT AT COMPILATION.
  //rtc.adjust(DateTime(2017, 8, 31, 14, 45, 14 )); // UNCOMMENT TO SET TIME & DATE MANUALLY. (YEAR, MONTH, DAY, 24-HOUR, MINUTE, SECOND)

}


Buzzing on computer speakers when LEDs are on I have an Arduino Nano connected via USB to a Mac Mini. When the LEDs come on, an external speaker connected to the Mini starts to hum/buzz quite loudly. If the LEDs are turned off, the buzz stops.

The speaker and the Mac mini are both powered independently, and are plugged into one wall socket, while the 5V power supply to the LEDs and the Nano is plugged into a different socket (of the same outlet).

What could be causing the buzz and what are the possible remedies?

If this is the same project you described in this question(readers: "112 WS2811s in series" causing interference), your external speaker may not be filtered very well against energy radiated by nearby un-shielded wiring. Try a pair of headphones in place of the speaker - does it also buzz? If not, the speaker (system) is probably picking up the interference. If so, the pickup is probably within or near the Mac mini.

You could try a few simple solutions (or at least tests that might narrow the problem):

shielded audio cable from the Mac mini to the speaker;
shielding the speaker enclosure and grounding the shield;
shielding the connections to the LED string (obviously shielding the LED string itself is likely to be aesthetically undesirable);
separating the speaker from the LED strip by more distance;
powering the mini from batteries - at least long enough to learn whether the power wiring might be involved.


Arduino an sparkfun microled problem In on of my projects i am using sparkfuns MicrOLED library. Downloaded it from github, installed as usual but no code calling that library compiles. Error is SPF_MicrOLED.h no such file or directory.

It is strange as the library is installed, example sketches are in the examples menu but they don`t want to compile ether, same error. Not sure what to do. Tried also to rename microled library folder but same error.

Error is SPF_MicrOLED.h no such file or directory.

That is to be expected because the library doesn't contain a file named SPF_MicrOLED.h.

It does contain a file named SFE_MicroOLED.h. Use the correct filename in your #include and the problem will be solved.


Initializing pointer to vector of objects inside another object i want to create a somewhat complex structure of classes in an arduino. The short story is: a Device has Presets, and each Preset has a Patterns. For that i created the following structure (i am only posting the important stuff, if something is missing let me know):

INO file

#include "LedDevice.h"

LedDevice device;

void setup() {
  device = LedDevice(10, 10, 10);
}

void loop() {
  Serial.println(F("Ticking"));
  device.Tick();
  delay(500);
}

LedDevice

#if !defined(_LEDDEVICE_H)
#define _LEDDEVICE_H

#include "Preset.h"
#include<Arduino.h>

class LedDevice {
public:
  Preset* Presets[];

  LedDevice(){}
  LedDevice(int numPixels, int numPresets, int numPatterns)
  {
    *Presets = (Preset*)malloc(sizeof(Preset) * numPresets);

    for (int p = 0; p < numPresets; p++)
    {
      Presets[p] = new Preset("test", numPixels, numPatterns);
    }
  }

  void Tick()
  {
    Serial.print(F("Preset ")); Serial.println(Presets[0]->Name);
    Presets[0]->Tick();
  }
};

#endif  //_LEDDEVICE_H

Preset

#if !defined(_PRESET_H)
#define _PRESET_H

#include "Pattern.h"

class Preset {
public:
  char *Name;
  int NumPatterns;
  Pattern* Patterns[];

  Preset(char* name, int numPixels, int numPatterns) : NumPatterns(numPatterns)
  {
    Name = (char *)malloc(strlen(name) + 1);
    strcpy(Name, name);

    *Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p] = new Pattern(numPixels);
    }
  }

  void Tick()
  {
    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p]->Tick();
    }
  }
};

#endif

Pattern

#if !defined(_PATTERN_H)
#define _PATTERN_H

class Pattern {
public:

  Pattern(int numPixels){}

  void Tick(){}
};

#endif

The code compiles but when i run the full version (this is a simplified version of the code) i get some strange behavior, so i would like to know if i am doing the initialization of the Presets and Patterns correctly.

Also when i try to print the Preset name in the LedDevice Tick function i get strange characters, so either i am not initializing the string correctly or the pointers to the Presets are wrong.

Can you tell if anything is not being done correctly in the constructors?

This is wrong:

Device device;

void setup()
{
   device = Device();
}

I don't know what your intentions are, but the first line instantiates device. You don't need to do anything in setup here. It sort-of looks like you are trying to call the constructor but that is called when the class instance is created (in the first line).

Preset* Presets[];

What's this? A pointer to an array of zero length?

    *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets);

Now you are allocating memory for a pointer to the array to be big enough to hold the contents of the array.

for (int p = 0; p < NumPresets; p++)
{
    Presets[p] = new Preset("test", NumPixels, NumPatterns);
}

Now you are allocating memory for the contents of the array again.

There is too much dereferencing going on here. Please post a Minimal, Complete, and Verifiable example. For example, make the classes in question do not much. Then make code we can actually work on.

  I realize the first call is to the default constructor, but in the setup i do the real construction ...

Well, you can't call the constructor twice. What is commonly done is to do nothing (or almost nothing) in the constructor, and then make a begin function which you call in setup. This function can then do whatever is required at the proper time.


Does ATmega328 on Uno need to be burned? I'm new to the Arduino world so please bear with me. I'm not sure whether the ATmega328 bootloader needs to be burned. What I'm reading is all that needs to be done is plug the board into the computer by USB cable. Then burning the 328 is also mentioned. I appreciate any help.

If you bought an Arduino Uno the bootloader comes pre-programmed.

"The ATmega328 on the Uno comes preprogrammed with a bootloader that allows you to upload new code to it without the use of an external hardware programmer. It communicates using the original STK500 protocol (reference, C header files)." - from the oficial page.

Might want to take a look at this discussion if you're confused.


L298 works only when touched The following image is my connection of l298 with Arduino.

This is the program.

int ENA = 10; // MCU PWM Pin 10 to ENA on L298n Board
int IN1 = 9;  // MCU Digital Pin 9 to IN1 on L298n Board
int IN2 = 8;  // MCU Digital Pin 8 to IN2 on L298n Board

int ENB = 5;  // MCU PWM Pin 5 to ENB on L298n Board
int IN3 = 7;  // MCU Digital pin 7 to IN3 on L298n Board
int IN4 = 6;  // MCU Digital pin 6 to IN4 on L298n Board

void setup()
{

pinMode(ENA, OUTPUT); //Set all the L298n Pin to output
pinMode(ENB, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
}
void DRIVEONE()
{
// Run the motors on both direction at fixed speed
digitalWrite(IN1, HIGH); // Turn HIGH motor A
digitalWrite(IN2, LOW);
analogWrite(ENA, 200); // TO set the turning speed to 200 out of possible
range 0 to 255

digitalWrite(IN3, HIGH); // turn HIGH motor B
digitalWrite(IN4, LOW);  // To set the turning speed to 200 out of possible
range 0 to 255
analogWrite(ENB, 200);
delay(2000);  // Delay to 2 seconds
void loop()
{
DRIVEONE();
delay(100);
}

The program seems to work fine but the motors run only when I touch all the 15 pins in L298 as shown in the second image.
I don't understand why the motors aren't running without touching those 15 pins.

I have connected the L298 to a 12V rechargeable battery and Arduino to a 9V battery.
Please help me understand what is wrong here.
Thank you.

Your schematic does not show a connection from the ground line of the 12V battery to the GND connection on the Arduino.  This is required.


How to use the ESP32 WROOM GPIOS above #18 with arudino ide? I am using the Arduino IDE version 1.8.8 I am trying to control an ESP32-wroom. The gpios for pins 16 and 17 are working. I have some relays on GPIO's 18 and 19 that I'd also like to be able to control. I also have no control over GPIO's that are over 17 I've tried 18 through 27 and I can't toggle them.

#define relayPin3 18
#define relayPin4 19

int relayflag = 0;
void loop() {
  delay(1000);
  if (relayflag == 0){
    digitalWrite(relayPin3, LOW);
    digitalWrite(relayPin4, HIGH);
    relayflag =1;
  }
  else
  {
    digitalWrite(relayPin3, HIGH);
    digitalWrite(relayPin4, LOW);
    relayflag = 0;
  }

}

I noticed that GPIO's 18 and 19 are also shared with spi ports.

Does the digitalWrite command work for any GPIO or is it in use by another library? Is there some other command to get access to the GPIO's I need to use? Some library I need to modify.

Found the answer, albeit a simple one. This is my first go around with arudino so it will look ridiculous to those who program microprocessors (including myself)

You need to declare the pin to be an output before use. The inconsistent thing is, this only happens sometimes. For some of the pins you don't need to use pinMode for them to work.

  pinMode(relayPin1, OUTPUT);


WORDS in ATmega328 datasheet note I came across something strange while reading the datasheet for the microcontroller in the Arduino Uno board.

It is the (8) note in pg.296-297 of this datasheet: what does WORDS mean in that context?

See jwpat7's answer.
My answer is correct re address word BUT
his points out that "Words" are being addressed and not bytes.  While my answer is not wrong, his is more likely to be what the writer meant in his excessively cryptic footnote.

A Byte is most usually used to refer to an 8 bit quantity.

A "word" is usually used to refer to a multi-Byte variable with the length depending on both processor type and context.

In this case, on page 296, table 28-19 information is given on the format of 4 byte Instructions. These instructions are NOT referred to as Words although in some other contexts they might be.

However,  the "Write Program memory page" instruction contains the address of a memory page. This address is made up of a 16 bit field comprised of 2 Bytes - an MSB and an LSB.
The notation "Words" is shown against the MSB and the LSB to denote (not very clearly) that a single 16 bit "Address Word"is formed by the MSB + LSB combination.


Switching LED on and off using microcontroller I am new to microcontrollers and just become confused trying to solve the following problem:

An ATmega32 chip is connected to four on/off switches (SW0-SW3) and 4 LEDs (LED0-LED3). SWi is connected to PAi.  LEDi is connected to PA(4+i).

How will I code in such a way that turning a switch on, turns the corresponding LED on? For example, turning SW1 on will turn LED1 on. I am confused in the part that after taking input what will I send to port A? Multiple switches can be switched on at the same time.

For clarification:

switch0 is connected to PA0
switch1 is connected to PA1
switch2 is connected to PA2
switch3 is connected to PA3

LED0 is connected to PA4
LED1 is connected to PA5
LED2 is connected to PA6
LED3 is connected to PA7

A common approach is, to read the input pin, check the read value and then write to the output pin.
As the events on the input pin are generally asynchronous to your code, you have to check it more than once, which means in fact you have to check it regularily.

So in your arduino sketch you could write:

loop()
{
  uint8_t pin1=digitalRead(PA0);
  if (pin1==HIGH)
  {
     digitalWrite(PA4, HIGH);
  }
  uint8_t pin2=digitalRead(PA1);
  if (pin2==HIGH)
  {
     digitalWrite(PA5, HIGH);
  }
  // and so on
}

I assume you have already done the prerequisites in your setup() routine.


How to produce 6 PWM signals with 60 degrees phase shift? How to produce 6 PWM signals with 60 degrees phase shift using Arduino Uno 6 PWM pins like in the image below?

Using hardware it's not possible. Simply because you effectively only have three PWM timer units, each with two compare outputs.

That means you have three timebases, which are each compared with two values for two PWM signals each.

You would need a single master timebase with six independent offsettable counters with comparison for your needs.

It would be possible to (roughly) do it in software, though, depending on your needs. You get jitter from software generated PWM, due to interrupts getting in the way of your smooth execution. However you have complete control over how the waveform is generated. Instead of a 0-X duty cycle you could program it to have an X-Y duty cycle. And with all of them taken from the same counter value it's then all synchronised 100%.


RGB led strip is too dim I'm following this tutorial to build an Arduino powered RGB led strip controller but I'm facing two problems:

When I use digitalOutput the lights are too dim.
When I use PWM the leds change so slightly that I can barely detect a change.

These are the parts I'm using:

Wemos D1 mini
a USB cable to power the Wemos
1k ohm resistors
TIP31c transistors
A power outlet 12V 1A to power the strip (which works fine with the original controller unit)

The circuit connected as presented in the tutorial (like the circuit below) doesn't work, the board does not start.

If I disconnect the board GND from the outlet GND then the board starts but the leds are too dim to be visible

What am I doing wrong?

simulate this circuit – Schematic created using CircuitLab

The Wemos D1 Mini is a 3.3V device. With a 1k base resistor, the most base current you're going to get is (3.3V / 1k ohm) = 3.3mA.

Looking at the datasheet, the current gain (h_FE) for the TIP31 transistor is no more than 50. So the maximum current you will pass from collector to emitter is 50*3.3mA = 165mA.

Your base resistor is too large and is limiting the current to your LED strip to no more than 165mA per channel. Try reducing the base resistor to 150 ohm. The TIP31 can handle continuous collector current of 3A, so you ought to be safe with a 1A power supply, and 150 ohm resistor.

UPDATE:

Per @Gerben's comment, the ESP8266 can source a maximum of 12mA from a GPIO pin, so you should not use lower than a 225 ohm base resistor on the initial TIP31. A Darlington pair would look something like:

simulate this circuit – Schematic created using CircuitLab


Arduino Shield Pin Conflict I have a Freetronics Etherten and am trying to use the NFC Shield - both the board and shield are trying to use Pins D10,D11,D12,D13

So my question - Is there an elegant way to have these two work together.  This really applies to any combination of shield with conflicting pins.  I'm thinking maybe use some in between headers or M/F jumper wires?

Is there a neat way to do it?

You need this: https://www.sparkfun.com/products/11002
"The Go-Between Shield “goes between” two shields that aren’t compatible and effectively reassigns the pins. This trickery is achieved by isolating the top and bottom sides of the shield with surface mount headers and breaking them out into tables of jumpers that can be bridged to divert signals to and from different pins."


Can all Arduino Due pins be used as digital input/output? I am using an Arduino Due for a project. I am running out of digital pins, using 22 to 53. Can pins 0 to 13 and SCL1, SDA1 be used as digital inputs?

How about analog pins (A0 to A11) and DACs?

Thanks!

Bear in mind that this has nothing to do with "Electrical Engineering".
This simply is an arduino question. And should be asked on arduino Stack Exchange.

Yes.

They can be used as input/output pins. [Simple 'tutorial']
If that even isn't enough or not working on your type of arduino, you can use I/O expanders or shift registers.
Check them out on the internet. [I/O expanders]


Arduino SIM5320e HTTP GET request to 000webhost.com Im having trouble getting a successful HTTP GET request to a domain under 000webhost.com

I am trying to do a GET request which sends data to a php file on my domain and save it to MySQL database. I also did this first on my browser and it works fine so I don't think there are problem in my php file.

MY DOMAIN: wastedb.000webhostapp.com

But if I try to send a request to dweet.io, it works as expected.

I am using a modified version of Adafruit_FONA library and will post the code snippet and response from serial monitor below.

Here are the parameters that I used for the WORKING GET request:

Host Address: www.dweet.io

Host: dweet.io

Response from Serial monitor for dweet.io (working):

---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="www.dweet.io",80,1
<--- OK
---> AT+CHTTPSSEND=64
<--- >
---> GET /dweet/for/gearhead?hello=world HTTP/1.1
Host: dweet.io

<--- OK
---> AT+CHTTPSSEND
<--- OK
<--- +CHTTPSSEND: 0
---> AT+CHTTPSRECV?
<--- +CHTTPSRECV: LEN,361
---> AT+CHTTPSRECV=361
<--- OK
+CHTTPSRECV: DATA,361
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Date: Wed, 30 Jan 2019 00:16:43 GMT
Connection: keep-alive
Content-Length: 196

{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing
---> AT+CHTTPSCLSE
<--- OK
---> AT+CHTTPSSTOP
<--- OK

As we can see, the Arduino received a JSON response from the website.

Here are the parameters that I used for the NOT WORKING GET request:

Host Address: wastedb.000webhostapp.com

Host: wastedb.000webhostapp.com

Response from Serial monitor for wastedb.000webhostapp.com (NOT WORKING):

---> AT+CHTTPSSTART
<--- OK
---> AT+CHTTPSOPSE="wastedb.000webhostapp.com",80,1
<--- OK
---> AT+CHTTPSSEND=113
<--- >
---> GET /wastedb/get_location.php?lat=14.640155&lon=120.974920&stat=LOW HTTP/1.1
Host: wastedb.000webhostapp.com

<--- OK
---> AT+CHTTPSSEND
<--- ERROR

Am I missing something here? Seems like the shield cannot find the Host Server I provided for my website.

EDIT: It is working now. The only solution that worked for me is to find another hosting site.

Try just using IP address for the Host line instead. I did the same thing for POST and it works fine for me.

Example:

Host: 13.xxx.xx.xx


Using two sensors with delay concurrently I want to use an ultra-sonic sensor and the led concurrently. I want the led to blink every 0.2 seconds and the ultra-sonic to measure distance without regard to the blinking.

The problem is I have the following code for blinking:

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

which makes the ultra-sonic sensor to be delayed as well, but I want it to keep measuring distance.
Any tips?

There is a non-blocking library that works similar to delay() Virtual Delay. This sketch turns your Uno's built-in LED ON for 1 second, then OFF for 200ms, repeatedly.

#include <Arduino.h>
#include "avdweb_VirtualDelay.h"

VirtualDelay delay1, delay2;

void setup(){

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // This sequence has a deadlock.
  if(delay1.elapsed()){
    digitalWrite(LED_BUILTIN, LOW);
    delay2.start(200);
  }

  if(delay2.elapsed()){
    digitalWrite(LED_BUILTIN, HIGH);
    delay1.start(1000);
  }

  // This breaks the deadlock. You can start with any
  // delay object you want e.g. delay2.start(0);
  DO_ONCE(delay1.start(0));

  // Your code here.

}

The library's author has an excellent tutorial on their website: avdweb Virtual Delay timer for Arduino.


BLE Python with GUI on OSX Has anyone connected BLE devices with Python + GUI on OSX? I've looked into a few libraries (most are old), but one that has the most success if Adafruit's BlueFruit library. However, this library works poorly with GUI's since it requires use of the main event loop (which GUI's usually use). After doing a bunch of Google searches, I couldn't find any good examples of using a GUI with Python + BLE. There seems to be no good BLE libraries for Python either.

Specifically looking for help integrating BLE with Kivy, but other GUI toolkit examples should be fine.

Also trying to gauge interest in this to see if I can do development to solve this (if it really is a problem).

If you are still searching for a lib check out:
https://github.com/adafruit/Adafruit_Python_BluefruitLE

Its specifically made for BLE communication on OS X or Linux by wrapping the corebluetooth and its Linux equivalent bluez in a python lib. Windows is not supported at this moment.

Unfortunately there is no documentation to it. You will have to read the examples and search for specific functions in the lib manually.


atmega16 in Arduino Board I had a very common question. Why a additional MEGA used in most of the Arduino Boards. Arduino board Mega2560 also have a MEGA16U2 controller on board which i think is used for programming via USB. Is there any other specific usage of atmega16 on arduino board.

Thanks

It's an ATmegaU2, which has USB hardware and handles the USB communication. It passes the hex file on to the bootloader in the main microcontroller. That is its only job.


Powering ESP8266 module from arduino nano I'm just starting up with arduino and i have few simple questions.

Why shouldn't i power ESP8266 WiFi module directly from arduino nano 3.3V rail? There are bunch of tutorials explicitly avoiding this or using resistors and i would like to know why?
Could i use something like a Mean Well Switching Power Supply, 5V 10A to power the Arduino Nano and therefore have stable voltage by avoiding batteries and by doing so, connect ESP8266 directly to arduino without fear of breaking something?
Could Arduino nano be powered through USB? And if yes, would it be then safe to connect ESP module to arduinos' 3.3V rail?

Why shouldn't i power ESP8266 WiFi module directly from arduino nano 3.3V rail?

The 3.3V rail of the Arduino is not meant to provide much current. The onboard regulator is a simple linear voltage regulator, which will dissipate the extra power as heat. As you draw more current through it, it will get hotter and finally get fried, as it cannot dissipate the created heat. The ESP chip needs multiple hundreds of mA, especially, when it is connecting to a wifi network. The onboard voltage regulator of the Arduino cannot handle this much. So you cannot power it over the Arduino.

I don't really know, what you mean with "using resistors".

  Could i use something like a Mean Well Switching Power Supply, 5V 10A to power the Arduino Nano [...] connect ESP8266 directly to arduino without fear of breaking something?

Yes, you can power the Arduino with this power supply, but you should power the ESP through the Arduino. Not through the 3.3V, nor through the 5V rail (which will fry the protection diode, I think). Instead you should power the ESP directly from the power supply, in parallel to the Arduino. Often ESP modules have their own voltage regulator, that regulates the voltage from 5V to 3.3V. If that is the case for you, you should use this input of the ESP module with the power supply. If you don't have a 5V capable regulated input on your ESP module, you will have to use a dedicated voltage regulator for that. In that case be sure, that the voltage regulator can provide enough power for the ESP (with some headroom on top).

  Could Arduino nano be powered through USB? And if yes, would it be then safe to connect ESP module to arduinos' 3.3V rail?

Yes, the Arduino Nano can be powered over USB. But again you must be sure to not draw too much current from the Arduino. Between USB and the 5V rail is a diode, that will be destroyed, if you draw too much current through it. And the standard USB port can only provide up to 500mA. And regarding the 3.3V rail: All the explanations above about the 3.3V rail apply here again, since the USB voltage (5V) is regulated down to 3.3V by the linear voltage regulator. So: No, you still cannot power the ESP through the Arduino. It's not about the power supply here, but about the electronic parts inbetween.


Why do I get different results when compiling the same code with different ide? I have a basic code about reading true rms.I compiled the same code with arduino ide and atmel studio, then ran it in a proteus simulation.I'm trying to measure how long the read_rms() function takes.
My mcu:attiny84
1.experiment)I have added board to arduino ide with board manager.And I chose attiny84 and internal 1Mhz from tools menu in arduino menu.
The result was that the read_rms() function took 23.25 milliseconds.
2.experiment)I compiled the same code without any changes in Atmel Studio.Device,attiny84 selected.
The result was that the read_rms() function took 44 milliseconds.
44 miliseconds vs 23.25 miliseconds. Why?
Note:The following settings are selected in the proteus.Internal RC Osc. 8 Mhz,and CKDIV8=Programmed.
My code:
#define F_CPU 1000000UL
#include <avr/io.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
const uint8_t muxbits = 1<<MUX3 | 1<<MUX2 | 1<<MUX1 | 1<<MUX0;

void adc_init()
{
    ADMUX = 0;    //Vcc_ref_
    ADCSRA = (1<<ADEN)|(1<<ADPS1)|(1<<ADPS0); //adc_enable_and_prescaler_8_ 125000 Hz (1000000/8)
    //first_try
    ADCSRA |= (1<<ADSC);
    while ((ADCSRA & (1<<ADSC)) != 0);
}

uint16_t adc_read(uint8_t channel)
{
    ADMUX = (ADMUX & ~muxbits) | channel;
    // start_single_convertion
    ADCSRA |= (1<<ADSC);

    // wait for conversion to complete
    while ((ADCSRA & (1<<ADSC)) != 0);

    return (ADC);
}

double read_rms()
{
    uint16_t i=0;
    uint16_t a_data=0;
    uint32_t sum=0;
    float avarage=0;
    double rms=0;
    for(i=0;i<200;i++)
    {
        a_data=adc_read(1);

        sum=sum+(a_data*a_data);
    }
    avarage=(float)sum/200;
    rms=sqrt((double)avarage);

    return rms;

}

int main(void)
{

    DDRA|=(1<<7);
    PORTA &=~ (1<<7);
    adc_init();

    while(1)
    {

    read_rms();
    PORTA ^= (1<<7);// TOOGLE_PA7   for_measure_time_of_read_rms()_with_oscilloscope

    }
}

Different compilers produce different machine code.
As Majenko pointed out, the Arduino IDE's compiler, which happens to be GCC, uses float even when you write double.
The Atmel Studio creates double for double, using twice as much bits.
Calculating with more bits takes longer.


how does a bluetooth on android works and what are the best alternative in saving data receive from bluetooth? Can anyone confirm this for me although I have tested it myself but when I send a string of data from my android app and send it to arduino say for example data = bluetoothPort.read(); inside an if statement then when I try to use the data in another if statement for example Serial.print(data); inside another if statement it will only show a blank line which let me believe that none of the data are saved. also when a receiving a string of data for example a string of abcde and send it to arduino for example data = bluetoothport.read() and then Serial.print(data) the serial monitor shows abcde as expected but what really happens is data has the value of a then prints then replace by b then print then replace by c then print then replace by d then print then replace by e. Am I wrong or somehow right? are there any work around or parts I need that will make me store data as a whole so that I can use it for other thread or a better code to store string of data?

#include <IRremote.h>
#include <SoftwareSerial.h>

SoftwareSerial bluetoothPort(4,5);
const int RECV_PIN = 12;
const int SEND_PIN = 13;

IRsend irsend;
IRrecv irrecv(RECV_PIN);

decode_results results;
char data;

void setup()
{
   bluetoothPort.begin(9600);
   Serial.begin(9600);
   irrecv.enableIRIn();
}

void loop()
{
   if (bluetoothPort.available() > 0)
   {
       data = bluetoothPort.read(); //received bluetooth data from android
   }

   if(irrecv.decode(&results))
   {
       irreceived(); //received IR code from a remote then sends it to my android
       irsend.sendNEC(data, 32)
   }
 }

 void irreceived()
 {
     Serial.println(results.value, HEX);   //receive value of 489010
     bluetoothPort.println(results.value, HEX); //send value to android
     irrecv.resume();
 }

so the above is a simple sketch that receive data from a remote controller then send it to my android app then when I resend it back to my arduino I would like the data to be able to receive all the data instead of saving it per letter/number and also be able to store it for other statement to use.

Serial communications only consist of one character. That is what serial is - the sending of one character at a time.

How you then deal with those characters, combining them into strings, interpreting them as numbers, whatever, is completely up to you to program.

There is no such thing as a string in serial communications. There is only the character.

The Arduino API has a few (badly implemented IMHO) helper functions that can get a whole string (kinda), but it is much better (both from a learning perspective and an implementation perspective) to do it yourself.

I have a little tutorial here that may help you get to grips with it.


Cloud function getting stopped Parse.com in loop when calling from Arduino-yun I have created a cloud function using the Parse.com Javascript SDK and I am calling those functions from Arduino. Following is code for the hello function:

Parse.Cloud.define("hello", function(request, response) {
                response.success("This is hello function");
}); //hello function Block

I am calling this function from the Arduino side using the following code:

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

  while (!Serial);

  Parse.begin("***zE0uUjQkMa7nj5D5BALvzegzfyVNSG22BD***", "***Ssggp5JgMFmSHfloewW5oixlM5ibt9LBSE***");
  //commented my keys with * here only

  // In this example, we associate this device with a pre-generated installation
  Parse.getInstallationId();
  Parse.startPushService();
}

void loop() {
  Serial.println("Start loop");
  demoBasic("meeting", 0);
}

void demoBasic(String functionname, int light) {
  char fnname[11];
  functionname.toCharArray(fnname, 11);

  Serial.print("In ");
  Serial.print(functionname);
  Serial.println(" Function");

  ParseCloudFunction cloudFunction;
  cloudFunction.setFunctionName(fnname);
  cloudFunction.add("light_sensor", light);
  cloudFunction.add("value", "Arduino Hello");//parameters

  ParseResponse response = cloudFunction.send();
  Serial.println(response.getJSONBody());
}

Problem is that I am getting response 8 times only. After that whole program flow gets blocked. What is the problem?

Give this a shot, I really hate String, maybe that 8-times thing has to do with memory issues caused by it.

void loop() {

  char functionToCall[8] = "meeting";
  Serial.println("Start loop");
  demoBasicCharArray(functionToCall, 0);
}

void demoBasicCharArray(char *functionname, int light) {

  Serial.print("In ");
  for (byte i=0;i<sizeof(functionname);i++){
    Serial.print(functionname[i]);
  }
  Serial.println(" Function");

  ParseCloudFunction cloudFunction;
  cloudFunction.setFunctionName(functionname);
  cloudFunction.add("light_sensor", light);
  cloudFunction.add("value", "Arduino Hello");//parameters

  ParseResponse response = cloudFunction.send();
  Serial.println(response.getJSONBody());
}


How to regulate a led on-board? There is blink project consisting 3 sections:

1 - regulation of the led brightness using a potentiometer

2 - whenever: the button is pressed - the led is on

-   the button is released - the led is off

3 - change state of a led statically

The question is that:

May I make this project on-board?
I am curious that, if I will try making this project on-board (Arduino UNO) will the Arduino damaged?

Pin 13, which is the on-board LED, is not a pwm pin. So you cannot Control the brightness of that LED on-board. You will have to use another LED and a PWM pin.


Reading an output analog pin with an input analog pin I am having a hard time understanding why I can't read one analog pin's output with another analog pin. The docs state to put a delay in between, which I've done (I've tried up to one second with the same results). I've got this minimized code:

void setup() {
    Serial.begin(9600);
    pinMode(A0, INPUT);
    pinMode(A5, OUTPUT);
}

void loop() {
    for (int i=0; i<1024; i++){
      analogWrite(A5, i);
      delay(100);
      Serial.println(analogRead(A0));
    }
    Serial.println("done");
    delay(10000);
}

When it starts, it displays 6-9 for a few dozen iterations, then suddenly jumps to ~1018 and remains throughout the rest of the run.

A5 is connected directly to A0 via a 4" jumper cable. Nothing is connected to AREF. If I connect AREF to 5v, the output does not change but by a single digit. If I connect it to ground, it immediately outputs 1023.

I'm hoping this is a "do'h" moment here. Can someone please let me know what I'm not doing correctly?

Update: This is a legit Arduino Uno R3 board. When I connect A0 directly to 5v+, I get 1023 as expected as the output.

Can someone please let me know what I'm not doing correctly?

the analog (output) pins on those chips are not exactly analog: they are pwm output pins. as such, their output is either 0 or 1, nothing in between, with the chance of being 1 equal the duty cycle.

that kind of output can be a steady "analog" if you run it through a low pass filter - the simplest would be an rc filter where the r is in serial with the c.

so if you hook th epwm pin up to a rc filter and adc the output of that rc filter, you will get a real "analog".


Lipo Battery level display using nodemcu I'm designing a connected collar for pets for a project, for this I am using a nodemcu on ESP8266 powered by a Lipo battery I'm guessing around 1000mAh of capacity is enough for a respectable autonomy (? any advices).
Lipo model : https://www.lipolbattery.com/lithium%20polymer%20battery.html
In order to charge the battery I have found this USB LiPo charger (https://learn.sparkfun.com/tutorials/lipo-usb-charger-hookup-guide/all), my first question is: Is it still usable for higher capacity LiPo batteries (1400mA)?
Also I would like to display the battery level via and RGB LED (example: green is for battery FULL battery and RED for LOW battery level in need of charging) is there any way to do this? Thank you

It is still usable for higher capacities. I recommend you tp4056 and some step up converter.
You can use resistor divider (that drops safely voltage to nodemcu 3.3v) and connect its output to an analog pin of your nodemcu. Values of resistors must be high, like 10k.
You can simply connect your diode to nodemcu and code if voltage is less than 3.2v let the red diode turn on, when above 3.8v let the green diode turn on


how to make arduino as mind thought reader? I'm trying to create arduino base mind reader... And for that I thought that EEG electrode connected to arduino and then the data send to arduino in 01 form .. But I facing problem in how to convert this or which wave (alpha, beta,delta)give very high or acutrate result.

Even if the answer provided by Mike is really doable and can be implemented you should really think about what you want to reach and what is your goal.

The big difference between EEG and mind readers is that the process of thinking, even if you can record all that waves: alpha, gamma,... can be never decoded to get useful informations. I mean: you can record and get a confirm that you have more gamma waves when you are doing meditation. Or that aplha and beta wave are going to be much more present when waking up or in particular hours of the days, but you never get an image of what the person is thinking or what are its emotions... That because you can get some waves coming from the brain but you cannot reconstruct the billion of processes that are happening inside the brain.

A lot of researcher are trying to decoder those informations to move as an example an arm or a leg. But it is the front edge of the reasearch really not doable with an Arduino....

Anyway good luck!


Trouble with NRF24L01 I've been trying on and off to try and get my nrf24l01's working for some time and they never seem to work. Right now I'm just trying to turn a led on and off over the radio and it isn't working.

Here's the code for the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define button 5
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
boolean buttonState = 0;
void setup() {
  pinMode(5, INPUT_PULLUP);
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}
void loop() {

  buttonState = digitalRead(button);
  radio.write(&buttonState, sizeof(buttonState));
}

And here's the code for the receiver

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

int led = 2;
RF24 radio(7, 8); // CE, CSN
boolean buttonState = 0;
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
 radio.startListening();
  while (!radio.available());
  radio.read(&buttonState, sizeof(buttonState));
  if (buttonState == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else
  {
    digitalWrite(led, LOW);
  }
}

I have the voltage regulator which steps the 5v arduino to 3.3 to the chip so I don't think not having a capacitor (what others recommended) is a problem. I have both radio chips hooked up to arduino nanos.

For the transmitter and receiver I have CE=7,CSN=8, SCK=13, MO=11, and MI=12

I also know that my led is working and the code for my button is working. Is there a problem with my code or is there a chance that my chips are broken even if im using a voltage regulator

It is not easy to find the problem remotely. Here is what I would do:

My first problem have always been connections. I gave up using breadboards and other connectors. Use soldering instead to be sure your circuit is properly connected.
Add some Serial.println() in both codes to see what exactly is going to be sent, and what has been received.
On the sender code, add a delay(100) to the loop. That would give the module buffers a chance to process.
You can improve it more by checking for the button value you read with the old value, and only send the value if the state has changed.


What is actually an IC (Integrated Circuit)? They say that you must know what IC your board has before loading a new program from the Arduino IDE and that the information is available on the top of the IC, but where is it exactly and what is an IC?

It's funny that you have a picture of one in your profile pic. :)

The arrow points to the most obvious integrated circuit or chip in you pic, there is another square one to the left of the TX and RX markings.  There are lots of different types of ICs -- most are black and come in different shapes and sizes, different number of legs, but most have some form of writing on the back that Google can use to locate the data sheet, or general help.  Have a quick look on Wikipedia for a more authoritative description.


TimerOne.h library for nodeMCU Following is the code I found in Arduino example files. It compiled fine on Arduino UNO. But there was an error when I tried to compile it for nodeMCU 1.0(ESP 12E Module).

#include <TimerOne.h>
void setup() {
  pinMode(13,OUTPUT);
  Timer1.initialize(5000000);//5 sec
  Timer1.attachInterrupt(timerIsr);
}
void loop() {}
void timerIsr(){
  digitalWrite(13,!digitalRead(13));
}

Following was the error message. I had this kind of error previously on OneWire.h and I solved it by replacing the OneWire.h library with another OneWire.h library that was made especially for nodeMCU.

Error msg:

Arduino: 1.8.3 (Windows 8.1), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from D:\iox Prime\TEC project\code\building modules\timerIsrDemo\timerIsrDemo.ino:1:0:

C:\Program Files (x86)\Arduino\libraries\TimerOne/TimerOne.h:39:20: fatal error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

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

I searched the library everywhere in the internet to solve this error but end up with no success. I wish somebody modifies the existing library for me. Thank you for the help.

I have found a solution. There is a library called Ticker.h
I found this on github: https://github.com/esp8266/Arduino/tree/master/libraries/Ticker

Following is my demo code:

#include <Ticker.h>
Ticker ticker;
void setup() {
  pinMode(D7,OUTPUT);
  ticker.attach(1,isrFunc);//tickerObj.attach(timeInSecs,isrFunction)
}

void loop() {}
void isrFunc(){
  digitalWrite(D7,!digitalRead(D7));
}

For me, this code worked seamlessly on nodeMCU. Thank you.


When is it necessary to use "float" instead of "int"? I'm very new to Arduino and I am making a code for a pedometer.  I have a lot of variables and I have used "int" multiple times, but I just came across a code with "float".
Now because my coding background is next to none, I don't really understand the concept of a float and when it's appropriate to use one.
Could someone please give me an explanation.
Thanks!

An integer is a whole or natural number.  Computers use integers for counting and comparisons.  Computers can count precisely using integers and comparisons of two integers can be absolutely true or false.

To make a float or floating-point number, a computer uses two integer numbers.  It uses one integer as the mantissa and the other as the exponent.  Computers use floats for calculations involving very large, very small or fractional values.  In other words the set of real numbers.  Computers can not count very well using floats.  Computer can not even compare two floats very well. That is to say, you may get different results from different computers when testing if two different floats are the same or not. This is due to rounding error.

Consider that the set of real numbers between 0 and 1 to be infinite.  However, intuitively, we know computers can not keep track of an infinite number of unique values between 0 and 1.  After all, computers use a float to do this and a float has a finite number of bits in it's mantissa and exponent.  The difference, if any, between the actual real number from, say, a calculation and the next possible float value is commonly referred to as the roundoff error.  In a program, a difference, for example, in the order of operation is enough to cause different roundoff errors to occur resulting in two slightly different float value results.

Rounding errors are what we end up with for allowing float values to grow very large or very small or to contain factional amounts.  Fortunately, floats are exactly what we need when computers are asked to calculate very large, very small or fractional numbers.

In embedded programming we rarely use floats.  They take up more of our limited RAM space than integers.  And it is rare that we need to calculate very large or very small numbers.  Usually, in embedded programming, we are counting events or measuring sensors.  Usually integers are preferred or are sufficient for our purposes.

Addressing your specific application (pedometer):

It is anticipated you would prefer to track distances in miles.  And it is practical to assume a good pedometer displays factional miles.  You can use floats to calculate this value.  A rigorous programmer would cast their integers as floats when mixing them in equations to make it clear to the compiler what is desired.


if two arduinos are connected by I2C and one of them is using an ethernet shield, does that grant both of them access to the internet? i have two arduino mega and they send data to each other by an I2C connection. But one of those arduinos is connected to an ethernet shield which allows it to send data to a web server. Being both connected does that mean that they both can send or access the web server. Sorry if any ambiguity was found but I didnt find a better way to ask this question.

I2C does not automatically share resources between two connected devices. You would not be able to share an Internet connection from a Mega connected via I2C to another Mega which has an Ethernet shield.

However, you could write code for both Megas that implements a two-way communication in which the non-shield Mega sends requests or commands to the one with the Shield, and then passes that data back to the non-shield Mega.

However, you, as the coder, would be responsible for designing such a protocol and implementing it. It would be quite a task probably.


ESP8266 does not reconnect to WiFi on reboot The ESP8266 is supposed to remember the WiFi credentials and reconnect to the network (if it is available) after each reboot.  That was the topic of this question: Does the ESP8266 somehow remember wifi access data?

I was observing that behavior and something has changed, I think when I updated via Board Manager in the Arduino IDE.  Now the credentials are lost each time that the device reboots. I've tried going back to earlier versions, but I have not been able to roll back to a version of the board definition that restores the old behavior.

Here's a sample sketch that I boiled down for testing:

#include <ESP8266WiFi.h>

char ssid[] = "ssid";
char pss[]  = "pass";

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

  Serial.println("Started");

  pinMode(0, OUTPUT);
  pinMode(2, OUTPUT);

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Not connected");
    WiFi.begin(ssid, pss);
    digitalWrite(0, LOW);
    digitalWrite(2, HIGH);
  } else {
    Serial.println("Connected");
    digitalWrite(0, HIGH);
    digitalWrite(2, LOW);
  }
}

void loop() {
  Serial.println("Loop");
  delay(500);
}

The first time through, of course, it hits the first case and prints "Not connected."  On reboot, however, I was expecting it to hit the second case and print "Connected".

I'm programming via the Arduino IDE.  The board is the Adafruit Feather HUZZAH ESP8266.  I've tried lwIP v1.4 and lwIP v2 in version 2.4.1 of the board.  I started rolling back versions from there got the same run-time results.

So, questions:

Is this a known bug of the ESP8266 modules in recent versions?
Is there some aspect of the WiFi configuration that's preserved on the board when I upload a new sketch? If so, how do I roll back?

The esp8266 SDK libraries starts the STA connection, but it is handled by other thread then the Arduino sketch. You can wait for this connection in setup with waitForConnectResult. It returns status().

  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Not connected");
    WiFi.begin(ssid, pss);
    digitalWrite(0, LOW);
    digitalWrite(2, HIGH);
  } else {
    Serial.println("Connected");
    digitalWrite(0, HIGH);
    digitalWrite(2, LOW);
  }

to connect with remembered STA mode, ssid and password, but with static IP address

  WiFi.setAutoConnect(false);
  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);
  WiFi.begin(); // uses remembered ssid and password
  WiFi.waitForConnectResult();


Shortest time interval that Arduino Uno R3 can read I am doing a light speed determination experimsmt. Lightspeed is around 3*10^8 m/s. For this, I need to measure time interval between 2 light sensors in nanoseconds, Somewhere about 50ns. Is this possible using the Uno R3? I know the clock is 16MHz only but is the clock irrelevantto the topic? If it is not possible, Some tips would be helpful. Thank you.

Sorry for irrelevant tags. No suitable tags found.

At 16MHz, the quickest operation that the cpu can do (a one cycle operation) will take 62.5 nanoseconds (1/(16*10^6) seconds). That means the best resolution you could conceivably have is 62.5 ns chunks. It will take considerably longer than one clock to respond to an outside event though, so making an experiment will be really tough even then.
Maybe you could build an experiment like the Fizeau apparatus where the arduino measured pulses of light that make it back through the slit? Those would be measured in microseconds. The arduino could change the speed of the grooved wheel and maximize the returning pulse width, reading the rpm then gives you the speed of light.
I'll note that since the meter is defined by the speed of light, and the foot defined by the meter, You would not be measuring the speed of light in feet or meters per second; you would be measuring the length of a meter given how long a second is, or vice versa.


Connecting multiple DHT 11 sensors I want to collect data (both Humidity & Temperature) from 80 sensors. let's say I have 80 "DHT 11 Humidity & Temperature" sensors (for ex. in a warehouse) and one Arduino Uno R3 pack. It's clear that arduino has no so many pins to connect. I'm sorry that I don't know if it's possible. If so, what can I use to achieve this?
Thank you all for your suggestions.

Analog multiplexers are one way, but they tend to have a significant resistance when on, and this could cause the protocol not to work.
For 80 channels you need 7 bits addressing. Say you have an 8-input multiplexer, then a 3-bit address indicates which of the 8 inputs is selected. Use 10 of these, all with the three address lines connected, and you have 10 outputs from 80 inputs.
Next, use a 16-input multiplexer to select which of the 10 inputs you want to use. For this multiplexer you need 4 address lines. Together with the other 3 address lines you have 7 address lines, enough to select 1 of up to 128 sensors. But I repeat, this approach may not work if the multiplexer's resistance is too high.

A more robust (albeit more expensive) is to use analog switches to connect/disconnect each sensor. Analog switches (Analog Devices has a lot of them) have on-resistances down to < 1 ohm, so the sure should be OK for the application.
To control the long series of switches you could use a daisy chain of 74HC595 shift registers, which only requires a couple of I/Os on your controller, but gives you virtually unlimited outputs.


What is the physical location of the U1A symbol on Arduino Uno? I'm trying to find an easy way to allow an Arduino Uno to determine if it's being powered from USB or the DC barrel jack. In this thread, one user recommends wiring the output of the on-board comparator op-amp (U5A pin 1) into the digital input pin.

I couldn't find U5A on the current schematic, but I think he's actually referring to U1A pin 1. Is this correct?

Unfortunately, I'm not sure where on the physical Arduino that device is located. I have one in front of me, and almost none of the parts are labeled on the silk screen. How do I find out where it is? I've googled for Arduino Uno part placement schematics, but all I'm finding are blurry unlabeled low-res images.

The op-amp is a LM358 so you can look at the ICs themselves. Also it's a dual comparator with 8 pins. On my example image below you can see it below the crystal. I can't comment if that's the correct way to sense what you need, but it seems the comparator output should be 1 if there is external power applied. You could check with a multimeter.


Arduino is not recognized by any computer I have an Arduino Uno R3 and when I plug it into any computer, the computer doesn't recognize the Arduino. I checked up and the LEDs are working fine and when I open the device manager it doesn't show any Unkown Device.

What it could be? Could the ATMega be dead? I tried on two Windows 7 and one Linux machines, none recognized the Arduino.

The reason that it is not connecting can be anything from wrong driver installation to the dead Atmega 16u2 chip. But I must exclude the former option as you said you'd tried on different OS and different computers. So double check the driver installation. And if does not work try to find out whether Atmega16u2 is fried or not. One solution might be to reflash the original firmware through an external ICSP programmer. If don't have any programmer but another arduino uno you might try out the gamon's tutorial on flashing firmware on the little USB to serial interface chip.
Anyway if your arduino is new and official you can get the right support online on arduino.cc. but if it is a clone you may try to contact the reseller whom you bought from.