Genuino 101 - Can't upload my sketch - Timeout Error I'm trying to run a sample sketch on my Genuino 101 but the following error shows up. Here is a verbose version.

Starting download script...
Args to shell: [/home/userk/.arduino15/packages/Intel/tools/arduino101load/1.6.9+1.28/x86/bin /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin /dev/ttyACM0 verbose ATP1BLE000-1541C5635 141312]
Serial Port: /dev/ttyACM0
BIN FILE /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Flashing is taking longer than expected
Try pressing MASTER_RESET button
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
ERROR: Timed out waiting for Arduino 101 on /dev/ttyACM0

I have installed the Intel Curie package with the Boards Manager and tried to press the Master Reset button, the reset and a combination of both. Nothing.

I have also tried the suggestions provided in this question but they did not work. I am using Ubuntu 16.04. Do you have any advice?

EDIT: Same problem with Windows 10/8/7.

Is the Genuino 101 board been recognized by the OS? Sounds like your board is not being recognized by the system.

For windows, open up your device manager before plugging into the PC. After plugging in, the device manager should refresh and display the board in the COM Port section.

For Linux (in your case Ubuntu), you can use the dmesg | tail cmd to check whether your board is being detected when you plug in the Genuino 101 board.


Assigning value to a struct byte order So i have struct:
typedef struct sendPacketStruct {
  byte header = headerByte;//0x55
  unsigned int time;//2 bytes
  int height;//2 bytes
};

And i do this:
    sendPacketStruct sendPacket;

    sendPacket.time = 84;//0x54
    sendPacket.height = 100;//0x65

    Serial.write((byte*)&sendPacket, sizeof(sendPacket));

But when i receive it at the other end the hex bytes are:
55 54 00 64 00
So the first byte is correct as the header 0x55, but the 2x 2 byte values time and height are there but shifted.
eg it should be 00 54 not 54 00

The answer is that arduino is little endian, so the byte order is correct. I was just expecting big endian order as ive seen in some other network protocols. If that is desired instead I can just do some bit shifting and re-arranging.


Where is documentation on Arduino's Internal Interrupts? First time arduino programmer here...however I have programmed the TI MSP430 in the past...

I am trying to figure out how to configure internal Interrupt Vectors on this Arduino Uno.

In the Arduino IDE, I am skeptical about writing lines of code like

ISR(TIMER1_CAPT_vect) {
    Serial.Print("Entered Capture Vector");
}

Because it doesn't appear to matter what I type inside ISR(), for instance I can write
    ISR(GibERisH) {
    }

And it still compiles and uploads to the arduino. What?! Also how could Arduino IDE know what the heck TIMER1_CAPT_vect is without having the library?

I found a list of interrupt vector names here: http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html

But I can not find documentation ANYWHERE ELSE on what to call these interrupt vectors.

Should I abandon the Arduino IDE and go with the Atmel Studio 6.2 (There is a juicy looking arduino plug-in...)? I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

EDIT: I realized my problem was I was looking for documentation for the atmega16U2 (that does something else on the board), not the atmega328P.

The vector names are all defined within the header files for the main chip in the compiler.  The IDE doesn't need to know anything about that kind of thing - that's all up to the compiler.

Look for the files "lib/avr/include/avr/io*.h within the compiler in your chosen IDE.  In there are all the chips and all their definitions.

For instance, the ATMega328P definition (iom328p.h) has this list:

#define INT0_vect         _VECTOR(1)   /* External Interrupt Request 0 */
#define INT1_vect         _VECTOR(2)   /* External Interrupt Request 1 */
#define PCINT0_vect       _VECTOR(3)   /* Pin Change Interrupt Request 0 */
#define PCINT1_vect       _VECTOR(4)   /* Pin Change Interrupt Request 0 */
#define PCINT2_vect       _VECTOR(5)   /* Pin Change Interrupt Request 1 */
#define WDT_vect          _VECTOR(6)   /* Watchdog Time-out Interrupt */
#define TIMER2_COMPA_vect _VECTOR(7)   /* Timer/Counter2 Compare Match A */
#define TIMER2_COMPB_vect _VECTOR(8)   /* Timer/Counter2 Compare Match A */
#define TIMER2_OVF_vect   _VECTOR(9)   /* Timer/Counter2 Overflow */
#define TIMER1_CAPT_vect  _VECTOR(10)  /* Timer/Counter1 Capture Event */
#define TIMER1_COMPA_vect _VECTOR(11)  /* Timer/Counter1 Compare Match A */
#define TIMER1_COMPB_vect _VECTOR(12)  /* Timer/Counter1 Compare Match B */
#define TIMER1_OVF_vect   _VECTOR(13)  /* Timer/Counter1 Overflow */
#define TIMER0_COMPA_vect _VECTOR(14)  /* TimerCounter0 Compare Match A */
#define TIMER0_COMPB_vect _VECTOR(15)  /* TimerCounter0 Compare Match B */
#define TIMER0_OVF_vect   _VECTOR(16)  /* Timer/Couner0 Overflow */
#define SPI_STC_vect      _VECTOR(17)  /* SPI Serial Transfer Complete */
#define USART_RX_vect     _VECTOR(18)  /* USART Rx Complete */
#define USART_UDRE_vect   _VECTOR(19)  /* USART, Data Register Empty */
#define USART_TX_vect     _VECTOR(20)  /* USART Tx Complete */
#define ADC_vect          _VECTOR(21)  /* ADC Conversion Complete */
#define EE_READY_vect     _VECTOR(22)  /* EEPROM Ready */
#define ANALOG_COMP_vect  _VECTOR(23)  /* Analog Comparator */
#define TWI_vect          _VECTOR(24)  /* Two-wire Serial Interface */
#define SPM_READY_vect    _VECTOR(25)  /* Store Program Memory Read */

Further, _ISR() is just a macro.  It creates a suitable function prototype for your function, and if that happens to include a valid vector then it becomes an ISR.

#  define ISR(vector, ...)            \
    extern "C" void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
    void vector (void)

That is defined in "avr/interrupt.h" in the compiler's include files.  With your gibberish you'd end up with:

extern "C" void GibERisH (void) __attribute__ ((signal,__INTR_ATTRS));
void GibERisH (void) {
    // something here
}

With a real vector you'd get the more meaningful:

extern "C" void _VECTOR(7) (void) __attribute__ ((signal,__INTR_ATTRS));
void _VECTOR(7) (void) {
    // something here
}

Of course, _VECTOR() itself is a macro:

lib/avr/include/avr/sfr_defs.h:#define _VECTOR(N) __vector_ ## N

So that further expands out to:

extern "C" void __vector_7 (void) __attribute__ ((signal,__INTR_ATTRS));
void __vector_7 (void) {
    // something here
}

And magically, that new function name of __vector_7 is directly referenced from the standard vector handling code in the startup library crt of the AVR compiler.


Arduino Uno with UsbSerial Android library w/ baud rate over 9600? I am having no issues talking to Android at baud rate of 9600. But once I raise the baud rate to anything higher Android seems to become deaf. When I try to read the Serial output using putty all seems fine.

Has anyone had success with baud rate over 9600 when talking to Android?

I am using the felHR85/UsbSerial library.

I have no enough reputations to make a comment so I will drop my two cents here.

Are you changing the baudrate at both sides?

I have been using the arduino's built-in UART library for a while using different baudrates with no problems. Your problem could be an issue related to the library you are using.


Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?) For now, I'm using an Arduino Uno alone including its 328p (no other external chip to program).

I would like to change its fuses to internal 8 Mhz clock (because then I'll move the 328p out of the Arduino Uno), and for simplicity I'd like to do it from Arduino IDE.

Here is what I tried:

I created a new entry in boards.txt copy-pasted from Uno, fuses modified, like this:

atmega328p.name=Atmega328p
atmega328p.upload.tool=avrdude
atmega328p.upload.protocol=arduino
atmega328p.upload.maximum_size=32256
atmega328p.upload.maximum_data_size=2048
atmega328p.upload.speed=115200

atmega328p.bootloader.tool=avrdude
atmega328p.bootloader.low_fuses=0x62
atmega328p.bootloader.high_fuses=0xD9
atmega328p.bootloader.extended_fuses=0xFF
atmega328p.bootloader.unlock_bits=0x3F
atmega328p.bootloader.lock_bits=0x0F
atmega328p.bootloader.file=optiboot/optiboot_atmega328.hex

atmega328p.build.mcu=atmega328p
atmega328p.build.f_cpu=8000000L
atmega328p.build.board=AVR_UNO
atmega328p.build.core=arduino
atmega328p.build.variant=standard

I selected this board in Tools > Board: Atmega328p
I tried to Upload any sketch (and not Upload with programmer since I have no other chip connected to the Arduino Uno), hoping it would modify the fuses during the (successful) Upload process.

I think it didn't work (when I move the 328p outside of the Uno it doesn't work).

How can I change the fuses for an Arduino Uno directly from Arduino IDE, to enable internal 8 Mhz clock?

PS: "Tools > Burn Bootloader" does not succeed, but I think this is normal, since there is just the Arduino Uno, and no other chip / nothing to use as a "Programmer":

  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

You need a programmer to burn fuses.  If you have another arduino then you can use the Arduino as ISP example sketch in the IDE.  You can't burn fuses just using the USB cable like you upload code with.  The only reason that can talk to the chip at all is because there is another chip to convert it to serial and a bootloader on the 328P to allow it to upload code via serial.


l298n voltage loss when motor attached Im trying to power a brushless DC Motor (Tamiya 300054358) through the l298n attached to an Arduino.
The l298n is powered by an external 9V source and the logic of the l298n is powered by the Arduinos 5V, wich is also powered by the 9v.
Both components using the same ground.
The code looks good and i can successfully adjust the power-output for the motor between 6-9V.
As soon as is attach the Motor, the volage drops do somewhere around 0-1V and the motor isnt turning.
When i attach the motor directly to the power source, it runs fine, so the power should be enough. (in the original RC car its powered by an 7V battery).
I tried some smaller motors just to be sure and the problem is similar. The motor is turning, but very slowly.
I also tried to connect the batterypack instead of the extern power source just ending up with the same result.
Do you have any ideas, where the problem could be at?
Thanks in advance

From an L298N datasheet:

TOTAL DC CURRENT UP TO 4 A

From motor's "datasheet":

I'm no expert in electric motors and driving them, not even sure I'm novice level, but I just don't see you driving a motor anything near this current draw with this part.  If by some miracle you can, it will be horribly inefficient owing to the losses associated with the voltage drops that Gil mentions.
For a motor that operates with this much current I would expect a practical h-bridge setup to have discrete mosfets, perhaps mounted to a heatsink.


I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328) I've been working on a project with I2C protocol where an ATmega328 (Arduino) configured as slave, receives messages from an ATtiny (ATtiny85, ATTinyCore by SpenceKonde) configured as master, or from an ESP8266 (ESP-01, Arduino core) configured as master.

All using the standard wire library, powered with 3.3v (LM1117 regulator), SDA and SCL 4.7kohms pull-ups.
The ESP pins used are RX and TX, with 330ohms pull-ups.

Individually, it works (ATtiny to ATmega; ESP to ATmega), but when i connect the three on the same bus, after the first message it stops working and the ATmega doesn't receive more messages.

Code (modified for readability)

ATmega slave:

#include <Wire.h>

const int ADDRESS = 56;

void receiveEvent() {
    Serial.println(Wire.read());
}

void setup() {
    Serial.begin(9600);
    Wire.begin(MY_ADDRESS);
    Wire.onReceive(receiveEvent);
}

void loop() {
}

ESP master:

#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
const int SDA_PIN = 1;
const int SCL_PIN = 3;

void setup(){
    Wire.begin(SDA_PIN, SCL_PIN);
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'e';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(2500;)
}

ATtiny master:

#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
// SDA = 0; attiny85 pin 5
// SCL = 2; attiny85 pin 7

void setup() {
    Wire.begin();
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'a';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(1000);
}

After some research I found out that the wire library can only work with a single master, is this correct? And the esp can only work in master mode.

Am I doing something wrong, or is this simply not possible?

Are there any protocol alternatives for this design?
A single device that only cares about receiving messages, and multiple other devices that only care about sending messages to the central.

Thank you for your time!

If you have 1 receive only device, and 2 send-only devices, why not make the receive-only device the master, but have it poll (periodically, repeatedly ask) the slave devices to send any data they have pending. That way, there is only one master, and it only asks for data when it's ready (that is, not receiving from some other device.)

One purpose of a master/slave bus system is to avoid contention (two or more devices talking at the same time.) The master tells each device when to send, and only listens after it asks.


Sizing relays for audio circuit? Non-technical person here, so please be gentle. I moved into a place that has ceiling speakers in each room (I tried, but they don't come apart, aren't marked other than manufacturer, and that is a company that went out of business 15+ years ago). So, let's assume they are 8 ohm speakers.

I have a media amplifier, and have successfully played music over all the speakers so I know that they work.

My wife would like the ability to select which speakers are on or off, so I'm thinking a quick Arduino project and relay board with 8-12 relays... but I'm not sure how to estimate the load, so I don't know how to appropriately size the relays.

Any suggestions on the best way to do this, or should I just get mains-rated relays and over-engineer the heck out of this?

If you can estimate speaker power, it probably is reasonable to use the ordinary power formula P = I²R for estimating the current the relay needs to handle.  Typically, high-power speakers of a given kind are bigger than low-power speakers of the same kind.  But as you can see from pictures of
5W,
10W, and
40W speakers, some 10W speakers are smaller than some 5W speakers, and some are bigger than 40W speakers, so power estimation based on speaker size can be difficult.

If you have access to the sound source (tuner or player or whatever, connected to an amplifier) you may find output power listed on the amplifier.

In any case, due to the I² term in the power formula, the range of current to plan for is relatively small.  For example, if 5W is going to an 8Ω speaker, 5/8 = I², and I =  0.79 A.  If it's 40W, then I = 2.24 A.  This range is likely to be handled ok by relays sold for ordinary use with Arduino systems.

Note 1: A relay's current rating ordinarily is derated significantly when the relay is used to switch DC or high-voltage AC.  Audio is low-voltage AC and relay derating probably isn't needed.  Note 2: The current a relay can safely switch in a live circuit may be much less than the unswitched current that closed contacts can carry.  This might not be a problem with low-voltage audio.  Note 3: Some commercial high-wattage audio distribution systems operate at higher voltages (see, eg, wikipedia's high-voltage audio distribution systems article, re 70.7 V etc systems); if you have one of those – as amplifier labeling might reveal – the example calculations shown above would need adapting.


Assigning float to 10 decimal place for longitude,latitude I'm quite a novice in arduino programming. I am doing a small home project and I am using sim808 to obtain GPS data.

My question is quite simple but i can't find any solution online.

Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat, 10);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon, 10;

This code display Longitude and Latitude data on serial monitor to 10 decimal place perfectly.

But when after setting the Longitude and Latitude to float.When I use this code, I don't get a valid gps data.

Longitude = (sim808.GPSdata.lon, 10 );
Latitude = (sim808.GPSdata.lat, 10 );

Please help, Thanks.

(edited)
I understand my error in coding for the above.

In fact, I am using a DF robot shield sim 808 for vehicle tracking. I am uploading my GPS data, longitude, latitude and speed to Ubidots. The only difficulty is in saving accurate data.

I am using this codes

Longitude = sim808.GPSdata.lon;
Latitude = sim808.GPSdata.lat;
Speedperkm = sim808.GPSdata.speed_kph;

client.add("Longitude", Longitude);
client.add("Latitude", Latitude);
client.add("Speed per Km", Speedperkm);

The code is working fine but only GPS data of 2 decimal place is being uploaded. If data of up to 6 decimal place is uploaded then the system will more accurate.

That my problem that I am trying to solve.

But when after setting the Longitude and Latitude to float.When I use
  this code, I don't get a valid gps data.

Some statements in C/C++ are not what they might seem. The value of the statements:

Longitude = (sim808.GPSdata.lon, 10 );
Latitude = (sim808.GPSdata.lat, 10 );

Are actually the same as:

sim808.GPSdata.lon;
Longitude = 10;
sim808.GPSdata.lat;
Latitude = 10;

Which is then optimized to:

Longitude = 10.0;
Latitude = 10.0;

That is, when using list notation, the value of the expression is the same as the value of last expression in the list.

The other answers have covered the fact that float and double on Arduino (AVR-GCC) are only 32-bit, and that gives 6 to 9 significant decimal digits precision.

Cheers!


Arduino Serial Writing Array Problem I am trying to communicate Pc - Arduino Uno.

My Arduino code is here: (It is working as below)

int ndx = 0;
char pack[12];
void setup() {
Serial.begin(9600);
while(!Serial){;}
}

  void loop() {

   while(Serial.available() ){
    char rb = Serial.read();
    pack[ndx] = rb;
    ndx++;
    Serial.write(rb);
    if(ndx == 12){
        ndx=0;
      }
    }
    }

If I try in

Serial.write(rb);

Like that:

Serial.write(pack[ndx]);

Program is acting weird, I mean sending weird bytes. I do not know what is the reason. Can you help me, please? What is going on in code?
My python code:
https://github.com/mucahitkayadan/Python

you replace Serial.write(rb); to Serial.write(pack[ndx]); and get?:

char rb = Serial.read();
pack[ndx] = rb;
ndx++;
Serial.write(pack[ndx]);

then you read an uninitialized array item on the next index


Dual power supply using Arduino uno and nano I had a very vague thought. I was wondering if I could I create a dual power supply using an Arduino uno and a nano. Can the  ground terminals of both the boards be shorted and the 5 volt terminals be used as +5v and -5v . Is this possible? Would it damage the board??

No, because both 5V terminals are +5V.

If both boards are powered by completely isolated power supplies then you could connect the +5V of one to GND on the other. One will then have all its signals and logic negative to your ground level, but normal compared to its own ground level. Managing it though and keeping things separate (no shared ground between two sets of peripherals, etc), would be tricky. And the moment you plug one into your computer the whole lot could go up in smoke.


Logging small capacitance I'm measuring capacitance of a system using a multimeter, and found that the value is very small (fluctuate from 50pF to 100 pF). The system is dynamic so the capacitance changes over time.

Now I need to log this value to some text file (csv for example). How could I do this with Arduino? If it's resistance, I could have built a simple voltage divider and sense the voltage using ADC. Also C is very small, I haven't been able to construct some measuring circuit for C.

For capacitance as small as pF, The RC time constant method yields dirty results on an Arduino board.

You can use the Arduino pins built in small capacitance (which is in Pf itself) to create a "capacitance divider" circuit and calculate much like you would resistance from a voltage divider circuit.

See this excellent post by Nethercott for reference
Arduino capacitance meter


EEPROM put and get not working on ESP8266 (NodeMCU) The Arduino documentation provides two examples to store data in the EEPROM.

https://www.arduino.cc/en/Reference/EEPROMPut stores data in the EEPROM and the EEPROMGet example reads the data back and writes it out.

These examples work fine on my Arduino Uno, but on my ESP8266 (NodeMCU) the EEPROMGet example code is unable to retrieve the data EEPROMPut should have stored previously. Instead it's just returning some random bits and bytes.

Any ideas? I haven't found anything about known incompatibilities related to the ESP8266 boards...

The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.

In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.

Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also here).


Why is int only 2 bytes? When using C/C++ on other platforms, the int type is typically 4 bytes (or potentially more). However, on Arduino, it's only 2 bytes.

Why is it different? Does it affect performance if I always use the 4 byte long instead?

The ATmega328 used in a lot of Arduinos is a 8-bit microcontroller. This means that registers are 8-bits, the data bus is 8-bits, the ports are 8-bits. There are some minimal 16-bit aspects to the system (e.g. one of the timers), but nearly everything is 8-bits.

Therefore, most operations handle 8-bits at a time. Working on anything except 8-bits (i.e. 16-bit or 32-bit integers and floating point numbers) requires what could essentially be described as software emulation, where the compiler uses multiple instructions to work on these larger variables.

8-bits is obviously adequate to address a 8-bit port. It's also enough to deal with many loop counters, return values, and ASCII characters. It isn't really enough though when dealing with numbers. A signed 8-bit int (int8_t) can only represent -128 -> +127. Unsigned (uint8_t) can only represent 0 -> 255.

8-bit integers are quite limiting. C/C++ int must represent at least -32,678 -> +32,767 so maps to int16_t - the smallest size that will do so. This gives a good balance of range and efficiency. This is especially important when beginners are learning - overflow is not really something that non-programmers understand.

There is a performance impact of doing this however, because most 16-bit operations take at least twice as long as an 8-bit operation, and use twice as many registers. This may or may not make a difference to you.

Many of us switch to the native types such as int8_t and uint8_t as it gives you far more control.


Reading many analog signals in arduino I need to measure around 50 - 100 analog sensors (resistors). This poses two challenges:

Arduino has fewer analog pins. I'm targeting something small like arduino Mini or Nano, which can have up to 8 analog pins. The solution for this could be several multiplexors like this one. Is there a better option? Is this the best way to read so many analog sensors with Arduino? I am thinking also in several arduino mini talking through wifi / bluetooth with the main one which would also aid with Problem #2.
There would be a lot of cables for this setup, and I need to keep it all as flat and flexible as possible. So I was thinking of some kind of adesive copper conductor, paper printed circuit or plastic. The thing is that it would become difficult to create if I do it myself. What would be the easiest way to achieve a multi-track, flexible circuit for substituing Arduino cables?

Your question doesn't specify speed, cost, accuracy, or size, and it skimps on electrical and physical details (referring merely to 50–100 resistors and “a lot of cables”) so perhaps can't be properly answered.

ADC's (analog-digital converters) typically are high-impedance devices that measure voltages.  A resistor may be measured in many ways, a few of which are:

Place a known voltage across it; measure current through it
Drive a known current through it; measure voltage across it
Drive some current through it; measure both voltage and current using four-terminal sensing
Measure how long it takes a given capacitor to charge to a trip point, using a known voltage through the resistor under test
Use known resistances to null a Kelvin bridge

For some of the techniques listed above, measurement accuracy is little affected by multiplexer resistance; others might need to use a low-resistance MUX made with relays instead of a MUX ic like the 74HC4067.  Some of the techniques are suitable for wide ranges of resistance, others not; and some for high accuracy, others not.

Suggested Approach

Anyhow, those comments aside, circuits like the following might do the job.  If you have eight analog inputs on your Arduino, you could use up to eight multiplexers to measure up to 128 resistors.

In Figures 1 and 2 above, Rx is a typical unknown resistance, and Rs is a known standard resistor.  Both figures represent voltage divider circuits.

Effect of multiplexer transmission gate resistance

Let Rm denote multiplexer transmission gate resistance.  Rm is unimportant if the circuit of Figure 1 is used because Rm is tiny compared to the input impedance of a unity-gain follower op amp stage.

Rm might or might not be important if the circuit of Figure 2 is used. (a) If Rm differs somewhat from one multiplexer channel to another, Figure 2 may be unsuitable because calibration will be cumbersome.  (b) If Rm is comparable to Rx, Figure 2 is unlikely to produce high-accuracy results.

Whether unity-gain followers are necessary

Whether you need unity-gain followers depends mostly on the size of resistors you are measuring.  Arduino analog inputs are high-impedance (10⁸Ω, but with about 14pF capacitance to Vcc/2).  Atmel suggests analog source impedances of 10KΩ or less for best results.  [See (1,2,3) for additional discussion.]  Briefly:  If Rs+Rx is likely to exceed 20-40KΩ and you wish to measure quickly, use unity-gain followers.

Resistance Formulas

Let Vt be the voltage at the lower end of Rs in either figure.  Vt is the voltage that will be measured at an analog input Aj.

In Figure 1, because Vt = Vcc·Rx/(Rx+Rs), we have Rx = Vt·Rs/(Vcc-Vt).

For the circuit in Figure 2, an additional resistance Rm is in series with Rx, so Vt = Vcc·(Rx+Rm)/(Rx+Rm+Rs), whence Rx = Vt·Rs/(Vcc-Vt)-Rm.  If Rs and Rx are large (eg 40KΩ and 10KΩ) then ignoring Rm may cause only a fraction of a percent of error.  But if Rm is comparable to either of Rs or Rx, either use the circuit of Figure 1 or devote some inputs of each multiplexer to use as calibration inputs.

Analog input reference voltage

If Vcc is 5 V and we choose Rs four times as large as the largest resistance value that you intend to measure, then Vt will be between 0 and 1 V.  You can use an analogReference() call like analogReference(INTERNAL) [or analogReference(INTERNAL1V1) on a Mega] to set the analog reference voltage at 1.1 V, to maximize accuracy of measurement and to minimize the amount of current required through Rx.

Advantages of Figure 2

Unless Rm is a problem (as discussed above) the following advantages of Figure 2 suggest its use:

Lower power requirements:  In Figure 1, all the resistors under test always have current going through them.  In Figure 2, only 1/16 of the resistors are powered at any given time.  Also, by raising \EN to shut down the 4067's (or 74HC4067's if used) all the resistors can be powered off.
Less wiring and fewer parts:  At most eight Rs parts are needed, rather than one Rs per Rx.  Each Rx connects to ground and to one mux input, rather than to ground and to the junction of a mux input with an Rs.

Cable Note

For either figure, seven or eight wires run from the Arduino to each 4067 subcircuit.  One wire from each subcircuit carries Vt back to an analog input.  The other wires connect to all subcircuits in parallel: four channel select lines (A, B, C, D in figures, or S0-S4 in datasheets); Vcc; ground; and \EN unless that line is wired to ground.  Each 4067 subcircuit should have a bypass capacitor, eg 10-100 nF, from Vcc to ground.  Boards like the “Geeetech CD74HC4067 Analog Digital MUX Breakout Board” shown below (about $5 on ebay) might be used, or you could design a custom board and have it made at OSHPark or Seeedstudio.


How to create large progmem arrays and not annoy the linker I have a rather complex project (PlatformIO, but I've also had this happen in the vanilla IDE) with several nested includes.
Let's say that there are three files and a main sketch.
The main sketch includes #2 and #3.
File #3 includes file #1 and file #2.

If file #2 is a .h file containing something like a font, of the format:

const char foo[] PROGMEM = {0xDE,0xAD,0xBE,0xEF};

Then I get linker errors of multiple definitions of 'foo' in both #3 and main.

Weirdly, the default fonts included in my OLED library are placed in a header file, EXACTLY like how I did it, and yet multiple files including that library (or files that themselves included it) do not cause this issue with the library's header file.

Yes, I do have a working include guard. For some reason it doesn't ever seem to help.

I have been using extern to solve this issue, but it's annoying and I'm not sure that it's proper behavior, either...

Could it have something to do with #include <font.h> vs #include "font.h"? What is the difference? My reference said they mean the same thing, but now I'm not so sure.

Include Guards only protect against inclusion of a header file multiple times within the same translation unit.  This is important.  If you include a header file (1) in a source file, then include another header file (2) in the same source file, said header file also including the previous header file (1), then the include guard will perform its function.

If you have two source files and you include the same header in both, then the include guard will do nothing.

If you have a variable or function defined in a header file and you include that header into two different source files, when you link those source files together you will get a multiple definition error, since you have two translation units that have the same thing in them, and the linker doesn't like that.

The only time you should ever define variables or functions in a header file are if they are simple constant types, like a const int or a const char - something where the compiler can replace it verbatim in the code and optimize out the symbol completely (arrays of any kind are not simple), or if the symbol is declared "static", where it will be forced to remain "within" the translation unit and not get exported for linking.

Normally you will only declare your complex constants in the header file, and define them once and once only in a single source file. That way there is only one instance of the symbol in one translation unit.

For example, in the header file you would declare your constant:

extern const char foo[] PROGMEM;

And in your source file define the constant:

#include "foo.h"
const char foo[] PROGMEM = {0xDE,0xAD,0xBE,0xEF};

And in answer to the question "what's the difference between #include <...> and #include "..." - when it comes to Arduino, nothing whatsoever.

Officially it denotes a separation between "system" and "local" headers. That is, headers that are installed in the OS as part of the compiler, and headers that are contained within the project.  However there isn't that distinction with Arduino, and the two mean the same thing - just a header.

And finally a note on terminology - a glossary if you will:

Translation unit - One compilable source file (and any included headers) that forms a single file of object code to be linked.
Declaration (Declare) - The indicating of a symbol's type and any attributes, but not the content of that symbol
Definition (Define) - Associating a symbol, whilst declaring it, with the content of that symbol.
Symbol - the name of any variable, function, class, etc.


Arduino two Ethernet shields Is it possible to connect two Ethernet shields to arduino? And if yes, how can I distinguish them in the code?

The ENC28J60 Shields have a Chip-Select-Pin (CS) so you could select between the two shields with this.

I'm using the EN28j60 with the Ethercard library and I'm not sure if this could handle two Ethernet shields because you have to set the CS pin at init on the first call in the function, and can't change it at runtime.


Run function concurrent to server.available() I have a Arduino UNO WiFi Rev2 board that runs WiFiServer serving as a web server. The server listens and accepts clients using server.available(). I also want a loop that controls a servo in concurrent of the server.
I looked at ArduinoThread and tried to implement my web server with it.
class WebServer : public Thread
{
private:
    // Some method definition omitted
    WiFiServer server;
    void accept_and_process();

public:
    void run() override;
}

void WebServer::accept_and_process()
{
    Serial.println("Waiting for client");
    // listen for incoming clients
    WiFiClient client = server.available();
    // Process client
}

void WebServer::run()
{
    this->accept_and_process();
    this->runned();
}

But the code does not run in parallel with code in void loop() it only ran code inside loop function and does not accept client as expected
This is the code I ran the server with
void setup()
{
    Serial.begin(9600);
    WebServer webserver = WebServer();;

    webserver.setInterval(100);
    webserver.run();
}

void loop()
{
    Serial.println("Hello");
    delay(1000);
}

How would I run the server concurrent to another function.

There is no “parallel” on a single core arduino. All you need to do is program both things in a non blocking fashion. Don’t use delay or while loops waiting on things and you can do both things so fast it seems like they are parallel. Put a call to server.available() in loop and then if it returns an invalid client object then the rest of the loop runs.  If it returns a valid client object then you can quickly do what you need with the server and then get back to everything else.
As noted in the comments, server.available is not blocking.  It doesn't wait for anything to come, it simply returns whether there is a connection available or not.


Upload with esptool fails with "espcomm_send_command: can't receive slip payload data" Uploading a sketch to an ESP8266 board fails with:

error: failed reading byte
warning: espcomm_send_command: can't receive slip payload data
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

...or:

espcomm cmd: receiving 2 bytes of data
warning: espcomm cmd: no final C0
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

This is on OS X with a PL2303HXD USB-to-Serial cable, using the latest official Prolific signed OS X El Capitan-compatible drivers.

This is a known issue with the included esptool, and for the Arduino IDE there are quite a few blog posts to be found on this problem. But most are outdated, and are not applicable when using PlatformIO with some other IDE. So, February 2016:

Install esptool.py

git clone https://github.com/themadinventor/esptool/ (or download the ZIP file)
cd esptool
sudo python setup.py install

When using Arduino IDE

Open ~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/platform.txt.
Find the line tools.esptool.upload.pattern and disable that by prefixing with a hash. Check that your version only mentions -ca 0x00000, not -ca 0x10000 as well (like in most outdated blog posts):

# tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"

Add the following, referring to the esptool.py you installed above and also using different command line parameters:

# Fix for espcomm_send_command: cant receive slip payload data
tools.esptool.upload.pattern="/path/to/new/esptool.py" --port "{serial.port}" --baud {upload.speed} write_flash 0x00000 "{build.path}/{build.project_name}.bin"

Restart the IDE.

(One might be tempted to just change tools.esptool.path and tools.esptool.cmd instead, but beware that the command line parameters need changing as well.)

When using PlatformIO

You will find the same platform.txt file somewhere in ~/.platformio/packages/framework-arduinoespressif/platform.txt, but that file is not used for the upload. Instead:

In platformio.ini add:

# ...or whatever your port is named
upload_port = /dev/cu.usbserial
extra_script = /path/to/platformio_extra_script.py

Create a new file /path/to/platformio_extra_script.py:

# Custom settings, as referred to as "extra_script" in platformio.ini
#
# See http://docs.platformio.org/en/latest/projectconf.html#extra-script
# See https://github.com/platformio/platformio/issues/426

from SCons.Script import DefaultEnvironment

env = DefaultEnvironment()

# Must be full path, or use
# https://docs.python.org/2/library/os.path.html#os.path.expanduser

env.Replace(
    LOCAL_UPLOADER="/Users/arjan/path/to/new/esptool.py",
    LOCAL_UPLOADERFLAGS=[
        "--port", "$UPLOAD_PORT",
        "--baud", "$UPLOAD_SPEED",
        "write_flash", "0x00000",
    ],
    UPLOADCMD='$LOCAL_UPLOADER $LOCAL_UPLOADERFLAGS $SOURCE'
)


Record a duration of time as data I have very little experience with the Arduino and am hoping that you may provide me with some helpful info.

I would like to build a device that records time spent on a project.  I envision the main Uno with a switch, microSD breakout, and an LED to indicate its tracking your time. When setup the user could simply press the switch/button (light up the LED to show you're "working") and while you plug away on your day job the Uno will track the time between switch on and switch off. Then at the time the switch is turned off, have the Uno write a simple data file containing the total time spent on that activity.

I have a basic idea of what I need hardware wise, but am hoping to find insight to the backbone of software programming to make something like this begin to take shape.

There are two ways of doing this:

Using a Real Time Clock (RTC) chip, which you connect to your Arduino.
Using the millis() function of the Arduino.

Needless to say, they aren't completely the same in efficiency. An RTC is a dedicated chip for measuring time and is incredibly accurate. The millis() is not as accurate, but still pretty accurate.

So, it really depends on how accurate you want it to be. You can make millis() more accurate through code, which isn't something difficult. But an RTC always works fine and is always more accurate, if only by milliseconds. In general: need to time long durations, an RCT is probably better.

Regardless of the method you will use, you can convert the data into the desired format so it can be read easily when looking at the files on the SD card. So, for example: you can write code that simply checks how many hours fit in the saved time data, and after that you can check the minutes and even after that you can check for the last seconds. For this you're going to need modulo.

Here are some resources you might want to check out:

An Arduino tutorial for an RTC chip: http://playground.arduino.cc/Main/DS1302
Official documentation on millis(): https://www.arduino.cc/en/Reference/Millis


Using the Arduino compiler, is it possible to use Atmega2560 interrupt pins that are unused by Mega? Looking into the schematics for the Arduino Mega I noticed that pins PE6 and PE7 are interrupt-enabled (INT6 and INT7 respectively); however, they remain unconnected to any Arduino I/O pin.

I'm designing a custom board based on the Atmega2560 and want to use the Arduino IDE/Compiler to upload my code to it, so I'm pretty much replicating a big part of the Arduino Mega schematic into my board.

However, I would really like to enable these two extra interrupt pins (having 8 interrupt pins in total) in my board, but I'm now sure how to proceed from the software side. How could I enable this new pins in order to use them from the Arduino compiler?

Thanks!

If you are not afraid of getting your hands dirty by touching hardware
registers, you can access those pins bare-metal style, using port
manipulation. You will have to read the datasheet,
specifically the section “External Interrupts” if that's what you are
after.

This works with the stock Arduino core (or even without core), which may
be interesting from a maintenance point of view, but it's not as easy to
use as the Arduino interrupt API.


When should I use a transistor, mosfet, and when should I use a relay? I am used to relays some, and they are useful, especially for large loads like a incandescent light bulb or other 120V AC device. However, it seems like overkill to use a relay for a bunch of LEDs linked together (parallel) that use 60 mA (too much for the Arduino). Also, it wouldn't work if you wanted to turn it on/off frequently or do PWM. I've heard some about transistors and MOSFETS and know a little about them. When should I use each one and how do I know what type to get? Also, it seems like relays can be more expensive than transistors/MOSFETS.

Edit: How can I use these with my Arduino?

Transistors (such as Bipolar Junction Transistors (BJT)) are solid state switchers, that is, they don't have any moving parts. Metal-Oxide-Semiconductor Field-Effect Transistors (MOSFET) are also transistors, but are voltage controlled, whereas classical BJTs are current-controlled. Relays are more expensive, but they have moving parts.
BJTs and MOSFETs produce a lot of heat (with high currents). They both have three pins (usually) called the base, collector and emitter (in the case of BJT) or gate, source, drain (in the case of MOSFET). More info here
Relays use a magnet to control the position of a metal switch. They generally take more power than an Arduino pin can deliver, and therefore they are often controlled by a transistor. Relays can usually switch more current than either a transistor or a MOSFET.
There are also Solid State Relays (SSR), which have a triac (a device similar to a transistor) in them. These can't switch as much as a normal relay, but they generally have better ratings than MOSFETs and BJT. example


Communication between Arduino and iOS device How can I get weight that has been measured by an Arduino device to show up on an iOS mobile or tablet device as a number?

Thanks.

Warmly,
N.

There are cables that let you plug in to the 30 pin connector and get a connection.

You could also use a BLE shield and write code for both platforms that communicate via BLE, or a WiFi shield.


4 Digit 7 segment display flickering I am attempting to make an Arduino counter using a 4 digit 7 segment display. The problem I am encountering is the display flickers. I am using an Arduino Uno and 5641AS digit display (so common cathode). Here is my program:
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
    Serial.println("The value of buttonPress is:  ");
    Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}

I suspect this issue has to do with sevseg.refreshDisplay(), I have tried moving it in the program with no avail. My wiring is correct, as the program displays the correct digits. Thank you!

With the help of Majenko and jsotola in the comments, I've got it fixed! It was the text I was displaying in the Serial Monitor that was slowing the display down. Here is the updated program that works:
#include "SevSeg.h"
SevSeg sevseg;

int buttonPress{}; // Variable used in Serial monitor, simulates button press to increment counter
void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true;

  bool updateWithDelays = false;
  byte hardwareConfig = COMMON_CATHODE;
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments);
  sevseg.setBrightness(90);
  Serial.begin(9600);
  sevseg.setNumber(0);
  sevseg.refreshDisplay();
}
void loop(){
  static int number = 0;

  if (Serial.available() > 0) { // Serial monitor input for buttonPress
    buttonPress = Serial.read();
  }
// THE NEXT TWO LINES HAVE BEEN COMMENTED OUT FOR IT TO WORK
   // Serial.println("The value of buttonPress is:  ");
   // Serial.println(buttonPress);
    if (buttonPress == 10){ // Increment counter if buttonPress Serial monitor input = 10
    number += 15;
    buttonPress = 0;
    sevseg.setNumber(number); // Display the number on 4 digit 7 segment display
    }

    sevseg.refreshDisplay(); // Refresh display
}

I'm leaving the program modifications here in case anyone else gets the same problem.


Error when using USART with Arduino Mega 2560 I use the Arduino IDE 1.6.9

What I want is a DMX Receiver which receives 1 channel and displays it on the serial monitor. When I try to compile the code, I get the following error:

C:\Users\Helyx\AppData\Local\Temp\build25a76891c667e0896ec10beb77bd0478.tmp/core\core.a(HardwareSerial0.cpp.o): In function `__vector_25':

D:\Programme\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial0.cpp:48: multiple definition of `__vector_25'

sketch\DmxReceive.ino.cpp.o:C:\Users\Helyx\Documents\Arduino\DmxReceive/DmxReceive.ino:26: first defined here

d:/programme/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1
Fehler beim Kompilieren.

Any ideas?
Here is my code:

#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000

#define DMX_BAUD 250000
#define DMX_LOST_TIMEOUT 8000

volatile unsigned char dmx_buffer[10];
volatile unsigned int dmx_lost = DMX_LOST_TIMEOUT;

volatile unsigned int dmx_adresse = 1;

ISR (USART0_RX_vect)

{
static unsigned int dmx_channel_rx_count = 0;
static unsigned char dmx_valid = 0;
unsigned char tmp = 0;

tmp =  UDR0;

if(UCSR0A&(1<<FE0))
{
 if(dmx_channel_rx_count > 1)
 {
   dmx_lost = 0;
 }
 dmx_channel_rx_count = 0;
 dmx_buffer[0] = tmp;
 if(dmx_buffer[0] == 0)
 {
   dmx_valid = 1;
   dmx_channel_rx_count++;
 }
 else
 {
   dmx_valid = 0;
 }
 return;
}

if(dmx_valid)
{
 dmx_buffer[dmx_channel_rx_count] = tmp;
 if(dmx_channel_rx_count < 514)
 {
   dmx_channel_rx_count++;
 }
 return;
}
}

ISR (TIMER2_COMPA_vect)

{
 if(dmx_lost<DMX_LOST_TIMEOUT)
 {
   dmx_lost++;
 }
}

void setup()
{

EICRA |= (1<<ISC11)|(1<<ISC10); //The rising edge of INT1 generates an interrupt request
EIMSK |= (1<<INT1); //External interrupt request 1 enable

//Init usart DMX-BUS
UBRR0   = (F_CPU / (DMX_BAUD * 16L) - 1);
UCSR0B|=(1 << RXEN0 | 1<< RXCIE0);
UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
sei();//Globale Interrupts Enable

TCCR2A |= (1<<WGM21);
TCCR2B |= (1<<CS22|1<<CS21|1<<CS20);
TIMSK2 |= (1<<OCIE2A);
OCR2A = F_CPU/1024/1000 - 1; //Tick 1ms
Serial.begin(57600);

DDRC = (1<<PE3);
PORTB |= 0x3F;
PORTC |= 0xFF;
PORTC &=~(1<<PE3);

}

void loop()
{

if(dmx_lost==DMX_LOST_TIMEOUT)
{
  dmx_buffer[dmx_adresse] = 0;

}
Serial.print(dmx_buffer[dmx_adresse]);
}

The compiler/linker is providing the answer. There are at least two definitions of the ISR for UART0 RX. One in your code and one in HardwareSerial.


Global variables use to much space in the dynamic memory I use two simple libraries (see 1, 2) I found online for my code on the Arduino Uno, unfortunately I also use ROS and all those libraries take away to much space, when I compile my code I get this error:

Global variables use 2,112 bytes (103%) of dynamic memory, leaving -64 bytes for local variables. Maximum is 2,048 bytes.

I shortened my Strings, but it was not enough. How can I change the code in the libraries to achieve less used memory?

I think I don't understand the concept of global variables completely. For example I changed all double variables in the libraries to float variables, but it did not change dynamic memory use at all. How can I use less memory?

When you write a program, some memory can be determined in compilation time, due to it's predefinition, (float and double in Arduino - not Due model - use 4 bytes each - in Due, double uses 8 bytes for 64 bit precision).

But there is some memory that only can be known at runtime; where we are talking about objects (or arrays determined by user input). In these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete. More info at: Dynamic memory.

You should control the creation of objects and arrays (those are created with new and then deleted with delete).

If your requirements are greater than the resources of any Arduino (except Arduino Due), you should change to the Due model, which has more memory space and computing power (but changes the 5 V to 3.3 V, be careful).


Light LED when 2 others are disconnected I need to make circuit in which orange LED will light only when yellow and red are disconnected. When one of buttons is pushed orange LED should turn off.

See my attempt at it below.

I am new to electronics so your help is very appreciated.

EDIT:

After many atemps I managed to build this circuit as on left side of schematic (tested on live breadboard)

but my primary goal is to make this work with RGB LED. I took Common Anode RGB LED for this and build circuit on right side of schematic. I do not have such RGB LED to test it live so I ask you to review if that schematic will work as it has few changes to one with 3 LED's. Thank you

SOLUTION:

Thanks to Bruce's help my circuit now works.

3 separate LEDs emulate common anode RGB LED (as I do not have one to test circuit)
Q2 is BC 560B transistor with CBE type pinout

CODE:

void setup() {
  pinMode(2,INPUT);
  pinMode(4,INPUT);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
  digitalWrite(4,HIGH);
}

void loop() {
  Serial.println(digitalRead(2));
  Serial.println(digitalRead(4));
}

You want the green LED to be on only when the red and blue LEDs are both off. In other words, you want the voltage on the green LED to be LOW only when the voltages on the red and blue LEDs are both HIGH. That is a logical NAND function.

Your right-hand circuit with the RGB LED won't work because the transistor's collector is connected to the wrong place - it's shorting out the battery! Another problem is that the Arduino can only switch to Ground or +5V, so it can't replace a 'floating' switch.

You need a configuration that produces a logical NAND function. Your left-hand circuit is doing it, but won't work with a common anode RGB LED. So swap the transistor to a PNP  type, and add a couple of resistors to switch it on when either input goes low, like this:-


Proto Shields wthout breadboard? I want to use a proto shield (brand is unimportant) and solder some components to it, to make something more premanent than using a breadboard.

My question is can the components be soldered directly to the middle area where there are a lot of small holes?

I would assume this is possible, but everywhere I look people add mini breadboards to their proto shields.

If it's possible, then I assume components and wires can't just be connected in a row like on a breadboard and would instead need some solder between 2 holes where for example a component and seperate wire are connected?

There are many different types of photo-shields, sometimes they have interconnected rows or they just have individual solder holes or even breadboards.  What you get all depends on what you are doing.  My personal favorite are the interlocked rows so I buy that and use a breadboard while I am developing my project then take off the breadboard and solder everything into place.

Example of non interlocked rows  and an My favorite proto-shield, it has a little of both kinds


Reading a car mass air flow, volumetric air flow meter I'm looking to build an air flow meter that will output in standard liters per minute. The cheapest sensors seems to be a car's Mass Air Flow sensor. I'm wondering if there is a way use  one of these MAF to measure air flow in liters per minute.

Essentially I need to measure a medical ventilator's air flow in order to calibrate it. The gas flow analyzers that are normally used are way too expensive and offer too many extra features that I don't need.

Thank You

There's no reason that an MAF couldn't be used with an Arduino.  It's likely that the sensor will run on 12v and output an analog voltage from 0 - 12, so you might need to use a voltage divider with the Arduino.

See this Sparkfun article on implementing a voltage divider to scale down the 0-12 volt signal to 0-5v for the Arduino.


Datasheet of arduino power jack Can we find out about the parts that the arduino uses?
I want to make a shield, and i bought the same power jacks.
And i thought that there would be two pins, one for power, one for GND.
However, it has three pins.
The supplier did not have a datasheet, and right now i do not have a continuity beeper either, so could i see its datasheet somewhere, or does anyone know why it has three pins?

This is an image from a typical power jack:

The specific ones you bought may differ.  The vendor should be able to supply you with a manufacturer and P/N or an actual data sheet.
Image copied from: https://www.we-online.de/katalog/datasheet/6941xx301002.pdf


Is there any easy way to change Arduino Wifi shield to ESP8266? As the title says, is there any easy way to replace WiFi shield with ESP8266, with as little as possible modification to code?

Here is my ESP:

Consider porting your sketch to esp8266 board like Wemos D1. The API of the ESP8266WiFi library is same as the API of the WiFi library.

To use esp8266 as network adapter, you have two wiring options.

If you have or buy an esp8266 module with SPI pins, you can connect the esp8266 over SPI like the WiFi shield is connected. Then you upload the WiFiSpiESP firmware to esp8266 and you include in your sketch WiFiSpi library instead of WiFi library.

Second option is to connect esp8266 over Serial or SoftwareSerial. The esp8266 should have AT firmware installed. The you can include WiFiEsp library in you sketch and initialize it with the Serial interface of your choice. You can find the WiFiEsp library in Library manager. Most new esp8266 modules have AT firmware installed at default.

There is one more option for Serial connection, if WiFiEsp wouldn't work for you. WiFiLink firmware and library

All mentioned libraries WiFiSpi, WiFiEsp and WiFiLink have the same API as the WiFi library so the rest of the code should work without changes.


Problem running WiFiWebClient example I'm running the WiFiWebClient example which comes preloaded with Arduino IDE 1.6.7. I'm using Arduino Uno board with WiFi Shield Model R3.

/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using a WiFi shield.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * WiFi shield attached

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */

#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>

char ssid[] = "Vanilla Sky"; //  your network SSID (name)
char pass[] = "mypass";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80) == 0) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: keep-alive");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

It gets my WiFi shield connected to Vanilla Sky but doesn't fetch the HTTP request (see image below). What is getting wrong here?

Let's break it down :)

  Please upgrade the firmware

Visit here to upgrade the firmware of your board. Your original post doesn't show the fw version, but could have outdated library references and has been noted many times that outdated fw will not work.

https://www.arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading

Also add this to your project to help us determine your firmware:

  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());

My guess is that it is less than 1.1.0. If the Arduino IDE is out of date, and the board is newer,  the NOT EQUAL TO(!=) may suggest that the firmware is newer than the library which could also be an issue.

Just b/c it connects to your router, doesn't mean that it can still communicate correctly.

One last side note, some versions of Arduino IDE have proven to be problematic with uploading a sketch to a wifi shield. A quick search with your Arduino version followed by the Wifi Shield not connecting could point you in the right direction. eg- Arduino x.xx wifi shield not connecting

Hope this helps!


I can't scroll Arduino IDE's example & scketch lists down I have Arduino IDE 1.0.5 in win7 x64. I have so many library units. A pity that I can't scroll down to my other options. Is it Arduino.exe's problem or something else? How can I add triangle to scroll down and scroll up to see whole Sketchbook and Examples list? Thanks.

Try using 1.5.+. It has scroll arrows to allow larger lists of menus, bigger than the screen.

I find that most, if not all, sketches work equally well, if not better.

Up to 1.5.6r2 uses the same version of compiler as 1.0.+'s. 1.5.7 and newer uses a new compiler, that is more sctrict. All stock libraries work. And well written 3rd parties work. I personally use 1.5 and test backwards to 1.0.

There is a fork of 1.0 called ERW that has the scrolling. But 8t is becoming obsolete.


Is it safe to use the same power source for Arduino and its Motor shield? Is it safe to use a unique 12V 5A DC power source to feed both Arduino and its connected Motor shield, provided that

the motor (connected to the shield) will eat 3A maximum
the Arduino Vin will get the power

Arduino and the shield exchange information, and use both the same power supply, is there some risk of "interference" of some kind?

edit

This is the motor controller shield I intend to use. In the manual, the connections show that

the Arduino and the shield have different power supplies
the Arduino power pins are not used by the shield

In my case, when I was running my DC motors at full load, I noticed a large voltage drop in the circuit. This could affect the signals or transmission of data on the Arduino.

It is definitely recommended to power the arduino and motor shield with separate power source. Make sure the the share a common GND.


Uploading a simple sketch takes forever I am trying to upload this simple sketch into my arduino with a shield I made. It takes forever (note I have the right COM port on)

  int sensorValue = 0;

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

  void loop(){
     sensorValue = analogRead(A4);
     delay(10000000);
     Serial.println(sensorValue);
     delay(10000000);
  }

Are you sure the problem is in the upload time? delay() takes the number of milliseconds you want to wait. In your code, it should take about 3 hours before the Arduino sends some data through the serial port.


Is an Arduino capable of running 24/7? I'm making a simple Arduino web server and I want to keep it turned on all the time. So it must endure to stay working continuously.

I'm using an Arduino Uno with a Ethernet Shield.
It's powered with a simple outlet power supply 5V @ 1A.

My Questions:

Will I have any problems leaving the Arduino turned on all the time?
Is there some other Arduino board better recommended for this?
Are there any precautions that I need to heed regarding this?

You shouldn't have any issues keeping it on all the time, however, some thing to consider is any counters you may have, like the use of millis().

From the Arduino docs on millis:

  This number will overflow (go back to zero), after approximately 50 days.

So for projects that are on for long periods of time, you may not see an issue immediately but something like this could pop up and cause errors down the road.


Can you use both 3.3v and 5v Can you use an Arduino EtherMega's 3.3v and 5v pins with two sensors, one requiring 3.3v and the other 5v and a sketch that combines both?

Yes. As long as you take into account that the outputs of the Arduino will be 5V so you may need to reduce that to 3.3V for the 3.3V sensor (if it has any connection to an output).


IR signal: different libs, different bit/byte ordering? For IR sender at Nano Every (ATMega4809-based) I am using infrared4arduino to send simple remote control codes. I am double-checking those with a Nano-based receiver with IRrecvDumpV2 example from IRremote library but I am receiving something else what I am sending (I think):

The sender has the following code using Infrared4Arduino:

   IrSignal* sig=Nec1Renderer::newIrSignal(0,0x906f); // cmd 0x90
   IrSenderPwm::getInstance(true)->sendIrSignal(*sig,1);

but the receiver dumps (besides some garbage like 0-bit JVC and SANYO frames):

Encoding  : NEC
Code      : FFF609 (32 bits)
unsigned int  data = 0xFFF609;

0x00 and 0xff (first 2 bytes of the "packet") are device and its logical complement, those are fine.

The command sent as 0x90 (followed by its logical complement 0x6f) is decoded as 0xF6 (plus its logical complement 0x09). Why? Is it an accident that 906f is f609 backwards?

What's going on here?

I will try to run both sender and receiver with the same lib (IRremote is not ported to Nano Every) but before I go ahead, better ask. Perhaps I am only doing some IR-beginner's mistake.

It is the receiver (IRremote-based) which is decoding bits in reverse order. IRremote and IRLib2 implement the NEC protocol incorrectly (both on sending and receiving sides). More details in the issue report https://github.com/bengtmartensson/Infrared4Arduino/issues/52 .


ADC value changing after changing Timer1 value in program I'm writing a code where analogRead() reads ADC value from load. After reading ADC value, if it is not in range, I need to manipulate Timer1 value. Which is also getting changed.
But, after changing the Timer value,  if the load value again gets restored, ADC doesn't show the same value again, but shows some other value.

Please refer below code:

#include <TimerOne.h>

int LED = 13;
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 8;
int OUT4 = 7;
//float A0;
//int OUT5 = 6;
const float refvolt = 5.0;
int volts = 0;
byte tempL_flag = 0;
float samples, loadval, avgacs, acsvaluef =0;
float refval = 2.0;
bool lflag=0;
unsigned long count = 0;

void setup()
{
    pinMode(IN0, INPUT);
    pinMode(IN1, INPUT);
    pinMode(OUT1, OUTPUT);
    pinMode(OUT2, OUTPUT);
    pinMode(OUT3, OUTPUT);
    pinMode(OUT4, OUTPUT);
    pinMode(LED, OUTPUT);
    pinMode(A0, INPUT);
    //digitalWrite(OUT3, LOW);
    Timer1.initialize(370000);
    Serial.begin(9600);
}

word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;
    word avrdata;
    word abcdata;
    byte i;

    for(i=0; i<sample; i++)
    {
        adcdata = 0;
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return(avrdata/sample);
}

void flash_L()
{
    digitalWrite(LED, !digitalRead(LED));
    digitalWrite(OUT4, !digitalRead(OUT4));

    if (digitalRead(OUT4)==1)
    {
        loadval = ADC_READ(10, 10, A5);
        Serial.println(loadval);

        if(loadval < refval)
        {
            Timer1.initialize(185000);
        }
        else
        {
            tempL_flag = 1;
        }
        return;
    }
}

void loop() {

    delay(2000);

    if(digitalRead(IN0)==1)
    {
        Timer1.attachInterrupt(flash_L);
    }
    else if(digitalRead(IN0)==0)
    {
        digitalWrite(LED, LOW);
        digitalWrite(OUT4, LOW);
    }
}

ADC doesn't show the same value again

You are not reading the ADC correctly, so ADC_READ() can return
anything. See the comments in the code:

word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;  // not needed
    word avrdata;  // not initialized
    word abcdata;  // not used
    byte i;
    for (i = 0; i < sample; i++)
    {
        adcdata = 0;  // useless
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return (avrdata/sample);
}

The big issue is avrdata not being initialized. Its initial value is
whatever was left there (in the stack or some CPU registers) by the code
that ran before. The value returned by the function is then hard to
predict and depends on what the rest of the program is doing.

The other remarks I left in the comments are not that problematic,
although they are revealing of some lack of attention to detail. Same
for some badly named variables. Here is how I would implement this
function:

word ADC_READ(byte samples, byte time, byte channel)
{
    word sum = 0;
    for (int i = 0; i < samples; i++)
    {
        sum += analogRead(channel);
        delay(time);
    }
    return sum/samples;
}


AMIS30543 | DataSheet Understanding CIRCULAR TRANSLATOR TABLE I was reading the data sheet of AMIS-30543 stepper motor and I didn't understand fully what does this Circular Translator Table means, I have a couple of doubts

What does Circular Translator table Stands for.? How to read it .? pg:13
What does the current pairs can be projected approximately on a circle in Ix, Iy plane means.? pg:25

In the data Sheet it is given that Changes on the NXT input will move the motor current one step up/down in the translator table (even when the motor is disabled:  = 0). So the changes happened in the table while the motor was disabled will reflect as soon as the motor become active.? Like if I give say 5 step input while the motor was disabled and when I make the motor enable , will the motor will move by itself to reach that position in the translator table.? pg:25

Link to datasheet

1. It describes the current going through the two coils of the stepper motor at each step.
2. I'm not quite sure, as I I would think the last two diagrams should actually be squares. But for example in the first image you can see that the current in the X coil will steadily increase, while the current in the Y coil will steadily decrease. This will make the stepper rotate more slowly.
In the second image you can see that only the Y coil driver at 100% in step 0. In step 1 both coils are at 100%. In step 2 coil Y is turned off. I think this is profile produces more torque, but is less smooth.
3. No. I you are, for example using full step mode, and the motor is in step 0. If you give it 3 steps forward  (while the motor is disabled) it would drive the coils (once you re-enable to motors) as describe in the lookup table for step 3. Which in practice would mean the motor would rotate backwards one step (instead of 3 steps forward).
In other cases it could result in undefined behavior. Going from step 0 to step 2 could mean if would rotate clockwise, anticlockwise, or even not rotate at all.
Though in practice I don't think this you would even be in issue, and disabling the motor, but still sending it step pulses is kind of silly.


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

What is my WAMP server's IP address?

I connect my laptop and Arduino with a router so:

My laptop is 192.168.1.2
My Arduino is 192.168.1.3

I think this is correct.

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

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

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

  INSTRUCTIONS FOR USE

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

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

  Created by: Dr. Charles A. Bell
*/

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

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

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

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

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

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

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

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

Change:

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

To:

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


Bizarre transistor behavior and voltage with DC motor in simple circuit I started a new motor related project recently with a new Arduino Uno, beginning with several tutorial circuits included in the Vilros Arduino guide. The circuit in question is #10, a simple DC motor circuit with a transistor switch (http://imgur.com/a/vaqUA). The Arduino is being powered for the moment via USB.

The circuit, completed according to the diagram/common sense, does not work. The voltage across the transistor base is clearly not sufficient to activate the switch with the motor in the circuit. 5V (more like 4.6V) from Pin 13 is running across a 330 ohm resistor to the transistor base, but there is no current between the collector and the base. Bypassing the collector/base gap with a piece of metal will complete the circuit and activate the motor.

For some reason, the transistor will switch properly when the motor is replaced by a simple LED. AND, switching the cable from Pin 13 to the +5V out is enough to activate the transistor switch. I was under the impression that the transistor should only require .7V above the common grounded element.

But, even more bizarrely, with a cable running from +5V to the transistor base (through a resistor), a voltmeter across the DC motor is reading a potential difference of anywhere from 9V to 1702V (see http://imgur.com/a/08I3W, yes, with 4 digits). The multimeter is otherwise working normally, so I don't see a good explanation. Is the Arduino pin just incapable of providing sufficient current/voltage to activate the transistor, or am I missing something obvious. And does anyone have some idea why the voltmeter is reading so high and fluctuating so wildly? It is curious that the Arduino disconnects from the PC whenever the circuit is completed with the motor in it, so the Arduino likely is overdrawing from the USB.

The transistor included was not the one listed, but a common MPS2222A.

Thanks

According to second image transistor seems to be connected in oposite direction (switched Collector with Emitter). It means common collector configuration is used instead common emitter and it's usually not enough to drive motor. And C-E can handle only about 10V Max (more or less, depends on transistor) even if it could handle much more in oposite direction.

See link for more details:

  Common Base Configuration   –   has Voltage Gain but no Current Gain.
  Common Emitter Configuration   –   has both Current and Voltage Gain.
  Common Collector Configuration   –   has Current Gain but no Voltage Gain.

I've just tested this circuit an it must be powered by power jack. USB is not strong enough.


Pin change interrupt does not work properly to wake up arduino from sleep mode I am building a timer circuit using Arduino Pro Mini Atmega168p 5v 16MHz (which later supposed to be become to adjustable one).

Here is the current breadboard view.

(I am supposed to use SS relay at place of that green thing. I am not sure if that item is correct SS relay in Fritzing)

Here is the program code I wrote.

#include <PinChangeInterrupt.h>
#include <PinChangeInterruptBoards.h>
#include <PinChangeInterruptPins.h>
#include <PinChangeInterruptSettings.h>

#include <avr/sleep.h>

// LED to indicate timer is active.
const int ON_LED = 5;
// It should be high when timer is active.
// Connect to relay.
const int PUMP_SWITCH = 6;

// Button to start timer running.
const int START_BUTTON = 8;
// Button to stop timer forcefully.
const int STOP_BUTTON = 9;

volatile boolean timer_running;
volatile int timer_start_time;

// TODO: Make it volatile once timer has mdified as configurable.
volatile unsigned long timer_time = 0;

void enter_sleep_mode() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sei();
  sleep_mode();
}

/**
 * Activate timer.
 */
void start_timer() {
  if (!timer_running) {
    // Time period in milliseconds.
    timer_time = 30000ul; // 30 seconds

    timer_running = true;
    timer_start_time = millis();
  }
}

/**
 * Stop timer.
 */
void stop_timer() {
  timer_running = false;
  timer_start_time = 0;
}

void setup() {
  timer_running = false;
  timer_start_time = 0;

  // Configure output pins.
  pinMode(ON_LED, OUTPUT);
  pinMode(PUMP_SWITCH, OUTPUT);

  // Configure pins for input push buttons.
  pinMode(START_BUTTON, INPUT_PULLUP);
  pinMode(STOP_BUTTON, INPUT_PULLUP);

  // Attach interrupt handlers
  // Buttons are with pull up resistors so listening for 'falling' (voltage).
  attachPCINT(digitalPinToPCINT(START_BUTTON), start_timer, FALLING);
  attachPCINT(digitalPinToPCINT(STOP_BUTTON), stop_timer, FALLING);
}

void loop() {
  if (timer_running) {
    digitalWrite(ON_LED, HIGH);
    digitalWrite(PUMP_SWITCH, HIGH);
    // TODO: Handle the case when return value of millis() goes back to start from zero
    if ( (millis() - timer_start_time) >= timer_time ) {
      // Timer elapsed the required time period.
      // So, stop the timer.
      stop_timer();
    }
  }
  else {
    digitalWrite(ON_LED, LOW);
    digitalWrite(PUMP_SWITCH, LOW);
    // Nothing to do If timer is not running.
    // Save power!!
    enter_sleep_mode();

    sleep_disable();
  }
}

The problem is timer does not work when pressing START button starting from third click. Two initial clicks works OK and timer functions as it should be. I think it does not wake up properly from sleep mode. However, wondering why it works for two initial clicks??

Please help me to identify the problem.
I don't have much experience in writing Arduino code.

Thanks

Start by checking your calculation of time limits. I see you are mixing signed and unsigned arithmetics - not a very good idea. Check the blink-without-delay example for how to do that.

The declaration of timer_start_time should be paid special attention.

Good luck with your project!


Connecting Arduino and Processing, how do I know what COM to read? I'm using Processing to read data from the serial port that the Arduino sends. When I go to device manager it shows that the Arduino is in COM 4, but in order for Processing to read from the Arduino the COM I need to type in is 2:

String portName = Serial.list()[2]

Why do the numbers not match?

Thanks!

Because the two numbers are completely different types of numbers.

The number 4 for COM4 means that it is the fourth serial communications port as defined by which I/O ports are used to communicate with the actual hardware. I.e. you'll have COM1, COM2, COM3 and so on. It doesn't matter if the hardware is actually there or anything is connected - the names are the same.

The number 2 in Serial.list()[2] means that you're selecting the third (!) element of the array returned by Serial.list(). I.e. in this case we're counting from 0 instead of 1.

In addition to that, Serial.list() only returns available ports. I.e. if the hardware for COM3 is not installed physically, it will not be returned by Serial.list(). Also the list is not guaranteed to be sorted in any specific order.

You'll want to print out the contents of the array returned by Serial.list() and let the user select which of the ports he wants to use.


Atmel atmega32u4 not recognized when connected by usb after attempting to flash new bootloader I am making a mechanical keyboard using Atmel's pro micro as the controller.  I decided I would try to replace it's bootloader, as the one it ships with doesn't seem compatible with QMK's RESET keycode (which is supposed to put the controller into DFU mode).

Clearly I didn't know what I was doing, as the controller no longer seems to be recognized when I plug it in via USB - MicroUSB.

If I recall correctly, this is the command I used to attempt to flash the bootloader:

"sudo avrdude -p atmega32u4 -P /dev/ttyACM0 -c avr109 -U flash:w:Caterina-promicro16.hex"

At this time, it seems likely to me that the issue is that I over-wrote the bootloader (or some portion of it) and failed to replace it with an appropriate alternative.  Is this correct?  Is there any way to correct my error through a USB-MicroUSB connection at this point, or will I need to buy some sort of programmer?  All the leds light up.

You cannot load the bootloader over USB, that job needs to be done with an in-serial-programmer (ISP).  You could have stopped the board working if you wrote the wrong fuses, e.g. different clock frequency.

Flashing the bootloader via ISP can be done with the Arduino IDE and there are lots of tutorials on the web.  Try it, will probably work for you.


How to Determine Fuse Settings I bought an arduino compatible board here: http://unsigned.io/projects/micromodem/
and am trying to flash new supported firmware onto it. The only instructions given to flash the board is to use the command avrdude -p m328p -c arduino -P /dev/ttyUSB0 -b 115200 -F -U flash:w:YourFirmwareFile.hex .

I'm trying to follow the tutorial here using an Uno as a programmer: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader#uploading-code---hard-way but I don't know what to use for the fuse settings. I've tried a few different fuse settings such as the one for the Uno, and default 328p ones using a fuse calculator but it seems like they all have unpredictable results. Some fuse settings make it so that I can't connect  to the COM port at all to monitor the traffic, and others let me connect, but send a message of . I'm expecting an introduction message from the firmware that is supposed to be built in.

Thanks for the help.

Normally you don't need to change the fuse settings, this configuration should be fine with the default arduino setting of

lowfuse=0xff

highfuse=0xde

extendedfuse=0x05

Serial should work fine.


Will bootloader communicate via TX0 / RX0 I'm fairly new to Arduino programming but have a good deal of experience with  low-level programming early processors, having originally cut my teeth on Z80, 8088, etc. I'm looking at developing a sizeable project using a Mega 2560. The project includes quite a lot of off-board logic, leds, and an RPi. Thus I don't want to overload the 2560 voltage regulator and really want to use common rail 5v power with a switch-mode supply. However, I also need debugging / console access, so this gives me the immediate problem of direct 5v driving whilst the board is being driven with 5v from the USB port, which is a no - no. The solution appeared to be fairly simple - use a CH340 - based USB to serial converter and connect it to RX0, TX0 and Reset (DTR output connected via a blocking capacitor) but with its 5v output disconnected. With this setup, the Arduino communicates quite happily with the IDE-based serial monitor (the sketch was downloaded via the on-board usb port), but on trying to download a new sketch via this route, AVRDude fails with a timeout. At the commencement of the download the processor is being reset, but the bootloader doesn't appear to hansdshake with AVRDude (properly). Is this a known feature or have I missed something?

Problem solved. The standalone CH340-based converter for whatever reason isn't man-enough to reliably pull down the RX0 line when connected to the Mega 2560 (also with a CH340 converter on board). I've seen suggestions posted in various places that this can be a problem with respect to DTR (though I don't have a problem with it). My solution is to insert a 7417 open-collector non-inverting buffer between the output of the stand-alone converter and the RX0 input on the 2560 board. I've not been able to find a schematic for the Mega 2560 board to determine its pull-up resistor size but imagine it must be relatively small. Thanks to those who made suggestions.


Relay + Arduino uses too much power for battery to handle. Which solution is best? You can see in my crumby schematic that I am using a Non-latching relay to turn on a 3A circuit (one of them arc lighters), which is powered by a 25C (supposedly) lipo battery. That same battery also powers an Arduino through a TP4056. This works fine when I first turn it all on, but once the relay is activated by the Arduino, the lighter + Relay only turn on for a split second before stopping (when the Arduino is powered via USB, it works fine). I am thinking that the Arduino+Relay+Lighter is too much for the battery, even though it claims to be 25C. It is just strange because the Arduino+Activated Relay consume what, like 200 mA?
Notes:
When I manually turn on the lighter, the light on the Arduino dims a fair bit, but stays on.
The Arduino is running at logic level of 3.3V so that I didn't need a booster.

As for fixes, I was thinking about trying to use a transistor or SSR instead of the chunky relay I have now (which would be good, I need this to be compact). Or maybe the TP4056 is failing to provide enough output despite a decent input?
I am FAR from an electrical engineer so if anyone has any pro tips for improving this it would be much appreciated.

The TP4056 is a battery charger, not a voltage regulator. It cannot be used to supply power to a device like an Arduino. It is designed for charging the Lithium Ion battery from a 5V (e.g., USB) source.
By trying to use it as a power supply you're asking for trouble. It thinks it's trying to charge a battery (from a 3.7V nominal source) and will be doing things like:

Running constant current making the voltage fluctuate wildly as current demands change
Running constant voltage with limited current causing starving of power
Shutting off when it thinks it sees the non-existent battery being fully charged.

The TP4056 should be connected to a 5V USB power source and to the battery for charging it. The battery should be then through a (very) low-dropout regulator (ideally a switching regulator with zero dropout bypass ability) to power the Arduino at 3.3V.
Alternatively, if you don't need a (reasonably) precise 3.3V then you can power the Arduino directly from the battery.


I am making heated socks with adjustments by Nano and want to extend batterty life? I want to set a temperature and have Nano turn on for 2 minutes then off for 2 minutes and repeat using the same temperature originally set and have the ability to change temperature settings and do the same.
The following sketch works along with displaying battery voltage using MIT Inventor 2 app via Bluetooth HC-05 to my Android phone (without the on/off sequence I am looking to do).
I hope to keep my feet warm but also extend the battery life.  Can you tell me what methods I should research to figure out how to do this? I have looked at millis(), blink without delay, and my own limited programming skills without success.  Thanks.
#define right 5
#define left 6

int leftval = 0;
int val=0;
int vg=0;

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

void loop() {
  int vg = analogRead(A0);
  Serial.println(vg / 82.049, 1);
  delay(200);
  if (Serial.available() >= 2) {
    unsigned int a = Serial.read();
    unsigned int b = Serial.read();
    unsigned int val = (b * 256) + a;

    if (val >= 0 && val <= 255) {
      analogWrite(right,val);
      delay(200);
    }

    if (val >= 1000 && val <= 1255) {
      leftval = val - 1000;
      analogWrite(left, leftval);
      delay(200);
    }
  }
}

With an electrical heating element powerful enough to warm your feet, the power to the heating element is hundreds or thousands of times greater than the power to your Arduino. Anything you do to reduce the power consumed by your Arduino will have no meaningful effect on your total power consumption. It's like trying to stop a drip in your faucet to save water while the main water pipe has water gushing out of a gaping hole.
Heating elements convert watts of power to calories of heat. The more watts you put in, the more heat you get.
Current • duty cycle • on-time = total power consumed AND total heat generated.
If you reduce the duty cycle to the heating element, you will reduce the power consumed, but you will also reduce the amount of heat generated.
Given that you already have the ability to vary the duty cycle to your heating element (via your analogWrite to right and left) the only meaningful way to reduce power consumption is to lower the heat setting. It looks like you already have that ability. Turn down the heat setting and have slightly colder feet, or use a higher capacity battery.
All that said, if you turn the heat setting down to 0, the heating element completely stops using power. At that point the Arudino will slowly drain your battery while your electric socks sit in your sock drawer. It would be worth putting your Arduino in ultra-low-power sleep mode (or even turning it off entirely) to avoid draining it while you're not using it.
Edit:
If you want to run the heating element on for 2 minutes, off for 2 minutes, that would give exactly the same power savings as running it at half the current power level, but constantly.
If you really want to implement the 2 minutes on, 2 minutes off approach, you will need to use millis() to keep track of the time when you last turned the elements on/off. I suggest refactoring your current code to remove delay and use millis as well.
Take a look at the "BlinkWithoutDelay" sketch (which I believe is included with the IDE, and is certainly available online) for an idea of how to handle timing things without using delay().


Elegant solution for refreshing TFT display content? I'm currently drawing black boxes over old content before displaying constantly refreshing content on my display, so for instance to display temperature:

if (sensorTemp != nowTemp){
    nowTemp = sensorTemp;
    tft.fillRect(0,52,88,21,ILI9341_BLACK);
    return nowTemp;
}

If I don't do this the display will just overlay content until it becomes a white blob.

However, this solution leaves me with a black flickering on the display and I can't control exactly what is refreshed where. So for instance when I want to display the current time or date it has to refresh the date all the time, even though nothing changed.

void loop() {
  tft.setTextSize(2);
  tft.setCursor(0,0);
  tft.print(rtc.getDateStr());
  tft.fillRect(144,0,199,15,ILI9341_BLACK); //Black box drawn over 'old' time data
  tft.setCursor(144,0);
  tft.print(rtc.getTimeStr());  //Draw new time
  tft.setCursor(0,52);
  tft.print(tempCall());  //call function to check on temperature and draw new data if necessary
}

Is there a more elegant solution to this problem?

If you look in the "Adafruit_GFX.cpp" you will see the following.

void Adafruit_GFX::setTextColor(uint16_t c) {
 // For 'transparent' background, we'll set the bg
 // to the same as fg instead of using a flag
 textcolor = textbgcolor = c;
}

void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) {
 textcolor   = c;
 textbgcolor = b;
}

If you only want to Draw the Character with a transparent background meaning you only write the character setTextColor in the prescribed pixels changing none of the surrounding pixels in the character block defined by x, y, setTextSize.

TFT.setTextColor(GREEN); //With Transparent Text Background not updating surrounding pixels.

If you want to Draw the Character with your background color, replace app pixels in the character block defined by x, y, setTextSize with your chosen text color and your background to be the same as your chosen background. This will overwrite all pixels with old character that are no longer used with the background color all at the same time preventing mess of pixels, and character flashing.

TFT.setTextColor(GREEN, BLACK); //With Text Background Color updating surrounding pixels.


EEPROM programmer works with serial monitor but not with pySerial I'm trying to modify Ben Eater's eeprom programmer to flash a 32K eeprom, since the arduino has 32K of program data total the data wouldn't fit in the program. So I wrote a python program using pySerial to send the data in chunks of 256 bytes over serial. The arduino program works correctly when I manually send the data over the serial monitor, and the python program works correctly when I print the values to a console as a test, but when I actually run the program over serial it seems to only write zeros to the eeprom. Additionally, the Rx led on the arduino seems to be lighting up with the correct data, but like I said only zeros are written.
Here's the relevant arduino code:
void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);
  digitalWrite(WRITE_EN, HIGH);
  pinMode(WRITE_EN, OUTPUT);

  Serial.begin(57600);
  dataArrPage = 0;

  //delay(1000);
  //Serial.println("Reading EEPROM");
  //printContents();

}

void loop() {
  if (Serial.available() > 0) {
    int len = Serial.readBytes(dataArr, 256);

    for (int i = 0; i < 256; i++) {
      writeEEPROM(dataArrPage + i, dataArr[i]); // writeEEPROM(address, data)
    }
    dataArrPage += 0x100;

    Serial.write('s'); //success, writing is done
  }
}

And the relevant python code:
import time
import serial
ser = serial.Serial('/dev/ttyUSB0', 57600)
time.sleep(4) # wait for arduino to initialize

filename = input("Enter file name: ")
f = open(filename, "rb")
data = f.read()

page = 0
for x in range(128): # 128 pages in 32K eeprom
    for i in range(256):
        #print(hex(data[(page * 256) + i])) # printing prints the correct values
        ser.write(data[(page * 256) + i])
    page += 1

    #wait until receive 's' from arduino
    while True:
        if ser.in_waiting > 0:
            suc = ser.read(size=1)
            if suc == b's':
                print("Success")
                break

print("Writing done")
f.close()
ser.close()

I'm a beginner so sorry if it's something obvious.

I figured out the problem. The for loop was writing one byte at a time, which probably wasn't fast enough and caused a timeout in the arudino. The code is now:
page = 0
for x in range(128): # 128 pages in 32K eeprom
    datalst = []
    for i in range(256):
        datalst.append(data[(page * 256) + i])

    ser.write(datalst)

    #wait until receive 's' from arduino
    while True:
        if ser.in_waiting > 0:
            suc = ser.read(size=1)
            if suc == b's':
                print("Success")
                break

    page += 1

I also changed the data types in the arduino sketch to use the ones in stdint.h which solved an unrelated bug. Let me know if I should post the full code for both.


Suggest me Arduino device with USB for Mass storage I want to make a temperature data logger by using Arduino.

I can read a data every 1sec and I want to store 30days data with date&Time.

In data logger, I want to write a temperature data with date&time in the .csv file and this file will be generated after I attaching USB.

So, Please suggest me Arduino board with USB compatible(working on 3V battery) and also suggest me EEPROM who able to store 30 days data.

60 samples per minute, 60 minutes per hour, 24 hours per day, 30 days - that's 2592000 samples. At 10 bytes per sample (a very generous allocation) that's less than 30MB of data.

You could fit that many many times over on even the smallest of today's SD cards, so why mess with the complexity of USB? Any Arduino can work with an SD card.

A bigger concern of yours should not be the storage medium, which is trivial - you should instead be thinking about how you will run the board off a 3V battery for 30 days.