Issue with PWM output pin I'm just starting off with using the Arduino and was learning about PWM
(http://arduino.cc/en/Tutorial/PWM).
Below is what my circuit looks like.

Below is the very simple code.

const int pinNine = 9;    // LED connected to digital pin 9

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
  // set the digital pins as outputs
  pinMode(pinNine,OUTPUT);
}

void loop() {
  analogWrite(pinNine, 0);
}

I was expecting my LED to not be lighted as its a 0% duty cycle. I even change the pinNine outputValue to (64, 127, etc) but for some reason the LED is always lighted. Any ideas?

Added at top:
Your code runs correctly on a $US3 Arduino Nano :-)
It seems extremely likely that you have a hardware problem of some sort.
If you have a voltmeter you can try these easy checks.
I carried these out to be sure that I got what was expected and the results are as you would expect them to me. Use a meter set to DC Volts - typical common meter circuitry averages the PWM well.

Remove LED etc connection to pin 9.
Measure the voltage from the 5V pin to ground. If powered from USB this will usually be slightly below 5V.

Run your code with the analogWrite set to 128 ie
analogWrite(pinNine, 128);

Measure the voltage on pin 9 relative to ground. It should be close tohalf the voltage on the 5V pin in 1. above. This is because the analogWrite value is controlled by PWM with values from 0 to 255. 128/255 ~= 50% so output is 50% of Vref = 5V by default. in a 5V system.

Set analogWrite to
 analogWrite(pinNine, 25);

The voltage on pin9 should be about 10% of the voltage on the 5V pin.

IF you get approximately the voltages shown in 3. and 5. your code is working OK and your hardware is OK.  If not then 'summat aglae'.
Try another analog pin.
Check that the red wire to the LED goes to UNO ground.
The voltmeter is a surer way of checking that the LED is as you can see actual numeric values that result.

OLDER:
It always helps greatly if you show PIN IDs on photos so people can be confident re what you have done.
If you view the whole UNO-R2-R3 connector with numbering it is obvious that the important pinouts are the same.
If however you view part of the connector with no numbering/ pin names shown,  then on the R3 there are additional pins on the ARef end of the connector which make comparisons'more difficult).
You APPEAR to have an Arduino UNO R3
It would help if you gave actual model and weblink in future "just in case it matters". .
You appear to have connected to pin 9  (as you intended to)
Pin 9 has PWM capability, as required.
It seems that your code should work.
Thusly

IF the red wire connects to ground the circuit seems electrically correct.
Does it?
Code LOOKS OK.
Try digital write on / off on pin 9 to see if LED changes and that the port behaves as expected. A bad port pin is possible.
What pin is serial on?
Try another pin with PWM capability to see if it changes.

ARDUINO UNO R3 from UNO home page
The connector pinouts vary widely between models of UNO.


Arduino Based Solid State Drive I've searched high and low for something to get me on the right track, it's making me think it might not be possible.

Basically, I want to create a cheap SSD using Arduino (or another microcontroller if it is too weak). I know I would have to implement the SATA protocol on the device and an OS driver for the disk drive. Assuming I could jump those two hurdles, what else would bar me from implementing a rudimentary SSD? I'm not even talking about full production quality, just a SATA wire coming from a mother board plugged into a socket on a breadboard. Do I need flash storage or would I need another kind of chip to handle the data needs?

The good news is that SATA drivers are fairly generic so you don't have to write the OS side. The bad news is everything else.

just a SATA wire coming from a mother board plugged into a socket on a breadboard

Let me stop you there. The minimum data rate for SATA is sufficiently high that you need a PCB. If you try and do this with wires or breadboards it will simply not get through; it will be lost to parasitic capacitance.

(Many years ago as a student I tried to do something vaguely similar with a wire-wrap board. At just 20MHz you could see a clean signal go in one side and a noisy unreadable mess come out the other side. Actually seeing it on a scope drove home the importance of shielding.)

Do I need flash storage or would I need another kind of chip to handle the data needs

Where would you put the data otherwise? It might be an entertaining first step to create a read-only drive with constant contents, but it's not very useful.

You need a chip with a SATA interface. This will almost certainly be an ARM and almost certainly not in DIP. I can't remember at the moment whether SATA master and slave "PHY" interfaces are different or whether it's all defined in software, someone else can answer that.


How to int variables with similar names without tons of code? I'm using int with 14 LEDs to specify pins, but I don't want to use int 14 times, like this:

int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 7;
int led7 = 8;
int led8 = 9;
int led9 = 10;
int led10 = 11;
int led11 = 12;
int led12 = 13;
int led13 = 45;
int led14 = 46;

is there any way to not do this?
Also, to define them as output, is there any way to avoid using pinMode(***, OUTPUT) 14 times as well?

The word you are looking for is array.

An array is like a list of values all of the same type.  For instance, your LED pins could be specified as:

int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

You can then access the LEDs by number.  Note that arrays start counting from zero not from one, so you would have:

leds[0]
leds[1]
leds[2]
... etc to ...
leds[12]
leds[13]

It's great for using them in an array:

for (int i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

If the values are never going to change, as in this case since they are pin numbers, the array should be declared const so it doesn't take up any of your precious RAM:

const int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

Also you should get into the habit of tailoring the data types to the expected values.  If the values are never going to exceed 255 then you should use "byte" not "int", or better still the C standard "uint8_t".

const uint8_t leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

for (uint8_t i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

An int takes two bytes, so using int when you can get away with uint8_t means you're wasting half the memory.


Does IDLE Mode not power down an ATtiny85? So I'm trying to power down my ATtiny85 to save power, but for some reason the ATtiny doesn't power down when I'm using the default IDLE mode, but when I start using the SLEEP_MODE_PWR_DOWN the ATtiny appears to go to sleep.

I'm testing it by calling a checkPower() method that blinks an LED after the sleepNow() method. In other words, if the ATtiny goes to sleep then the checkPower() method should not be reached and the LED should not blink. Here is the code:

void loop()
{
  doStuff();
  sleepNow();
  checkPower();
}

void sleepNow()
{
    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_IDLE);
    // Set sleep enable (SE) bit:
    sleep_enable();
    // Put the device to sleep:
    sleep_mode();
    // Upon waking up, sketch continues from this point.
    sleep_disable();
}

void checkArrays()
{
  for(i = 0; i < 15; i++)
  {
     digitalWrite(1, HIGH);
     delay(1000);
     digitalWrite(1, LOW);
     delay(1000);
  }
}

Any idea why my LED would continue to blink when using the IDLE mode but no the PWR_DOWN mode?

In IDLE mode the timers still run. Arduino uses timer0 for millis. So when timer0 overflows the ATTiny will wake up and call the ISR.

So the ATTiny will go to 'sleep' but wake up a number of microseconds later.


Why does my wired button always read HIGH? I have made a simple Arduino program that uses a potentiometer to dim a LED.

This program also makes a second LED blink.

Finally, I have added a button that controls a third LED; this part of my program does not work: the 3rd LED is always lit as the button always reads HIGH.

Here is the code:

//sensePin is wired up to the FSR
int sensePin = 2;

//this is wired up to an LED
int ledPin = 9;

//Wired up to a button
int inputPin = 1;

int val = 0;

//I was broed so added the default Blink
int ledPinX = 13;

//Wired up to a second LED
int ledPinY = 7;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode(ledPinX, OUTPUT);
  pinMode(ledPinY, OUTPUT);
  val = digitalRead(inputPin);
}

void loop() {
  if (val == HIGH){
    //This should ask "If your button is pressed, then do the code below
    digitalWrite(ledPinY, HIGH);
    //but for some reason the light is always on. I've tried it with more than one button
  }
  else if(val == LOW){
    digitalWrite(ledPinY, LOW);
  }
  int value;

  /*
 The rest of this stuff works. Well, it did before adding in the button. Now the FSR acts as a digital input. Please help.
   */
  value = analogRead(sensePin) / 4;
  analogWrite(ledPin, value);
  digitalWrite(ledPinX, HIGH);
  delay(500);
  digitalWrite(ledPinX, LOW);
  delay(500);
}

What did I do wrong in this code?

EDIT:: diagram and pic at: instagram.com/p/m3AmHWmp4e

You read the button once, in setup(). The function is not called every time the variable's value is read, only when the line is executed and the variable assigned to. Move the digitalRead() call and assignment into loop(), before you check the variable's value.


Whats the function of the resistor between MCU and its Resonator in Arduino Mega? I was looking Arduino Mega's schematic and I noticed a resistor between the MCU and its resonator. R3 in this image:

Why is it there and what is its function?

That resistor limits the drive through the crystal.  If the power applied to the crystal is too high then the slope and phase shift at the resonant frequency will not be optimal and at really high drive levels could cause mechanical damage to the crystal (like that shattered wine glass trick).

See good instruction PDF here, section 2.1.


Increase Serial Rx buffer I am working with an Arduino Due and I am having some issue with the serial Rx buffers size. I am using a GSM module and some of the replies to the Arduino exceed the number of bytes I can store in the buffer at once.

I have read about ways to increase the buffer size by modifying the Arduino default install files but I cannot take this route as my code may then be compiled on a machine with standard buffer sizes in the default install files and the module would not work correctly.

I am not sure if it is possible but I was hoping that someone might know how to increase the serial buffer size using the source code. If I can do it this way the buffer would always be the size I have specified.

Use timer interrupts to read and store the data from serial. Lets assume you are receiving data at baud rate of 115200 in default configuration (8data bits, 1 stop bit), 115200/9=12800 bytes per second, approximately 80 micro seconds for every byte, create a timer interrupt that is called once every 2 millisecond(Choose best time for your application making sure that receiver buffer does not overflow), In 2milli seconds 25bytes of data will be available in the buffer. So you can read data in batches of 25 each. From the interrupt read and store the available data from the buffer.


Partially clean a LCDScreen I have connected an 16x2 LCD to my Arduino. It shows my Room Temperature and Behind that variable is the string "Celcius". Everytime the temp is diffrent than shown on the screen it updates the screen by clearing the screen.
Is there a way I could clear just a part of the screen? or is this technically impossible. Or is it a waste of code? :D

Thanks in Advance!

Anton

The easiest is to clear the entire screen (I'm sure there is a function for that).

What you also can do:

Create lines which are 16 characters wide and print them, so the old text is overwritten
More complicated: store the text that is written in two strings (one per line) and check where are not spaces, to overwrite it with spaces to clear.

You would have to do a performance/time check to see what works best.

If performance is not an issue (which I doubt), keep it simple and just overwrite the two lines (without a clear, assuming you call the clear function yourself).

Another solution is to keep the word Celcius always on the same location... this means you might have to change formatting:

_28.6 Celcius
__3.8 Celcius
_-12.3 Celcius

Where _ are spaces (so the word Celcius is always on the same location)


How to make sure Arduino's PWM pulses are phase shifted? I'd like illuminate my room solely with several RGB LED strips using Arduino's PWM (together with LED amplifier and few transistors).

I want the Arduino to control 2 independent chains of LED strips, and I want to make sure, that the LEDs would not blink simultaneously, creating a very strong stroboscopic effect in my room.

How to delay three Arduino's PWM pins half a phase relative to the other three?

This (short) code below will achieve what I think you are asking for, on the Atmega328 (eg. the Uno, Duemilanove, etc.).

byte dutyCycle = 80;

void setup()
 {
  pinMode (3, OUTPUT);    // Timer 2 "B" output: OC2B
  pinMode (11, OUTPUT);   // Timer 2 "A" output: OC2A

  // Set OC2A on Compare Match when up-counting.
  // Clear OC2B on Compare Match when up-counting.
  TCCR2A = bit (WGM20) | bit (COM2B1) | bit (COM2A1) | bit (COM2A0);
  TCCR2B = bit (CS21);         // phase correct PWM, prescaler of 8
  OCR2A = dutyCycle;           // duty cycle out of 255
  OCR2B = 255 - dutyCycle;     // duty cycle out of 255
  }  // end of setup

void loop() { }

How it works

The code uses Timer 2 (an 8-bit timer) to count up to 255 in phase-correct PWM mode. Outputs are to OC2A (the "A" output - pin D11) and OC2B (the "B" output - pin D3). The duty cycle is in variable dutyCycle which must be in the range 0 to 255. The timer counts up to 255 and sets OC2A on compare-equal to the dutyCycle number, and it also clears OC2B on compare-equal, when counting up. The second half of the phase-correct cycle does the reverse. Thus the two cycles are of opposite phase.

Frequency

The frequency of the timer is 3.9 kHz. This is because the timer has a prescaler of 8, then it counts up to 255, then it takes two cycles per period (one up, one down):

16000000 / 8 / 255 / 2 = 3921.56 Hz

As Edgar Bonet pointed out in the comments, phase-correct PWM counts are not zero-relative, unlike other counting modes. Thus you divide by 255 to work out the frequency, not 256.

You could select other frequencies by choosing different prescalers.

Proof of operation

The oscilloscope screen here shows the two outputs, out of phase with each other by 50%.

You can see from the circled cursor measurement that the OC2B pin is off for exactly the requested duty cycle (80 µs).

 1/ 16000000 * 80 * 8 * 2 = 8e-005 (0.00008)  --> 80 µs


Can you charge and use a LiPo battery at the same time? I have a system that uses an Arduino Uno board as a "brain". All the elements in the system are powered by a single LiPo battery (3cell, 11.1V, 1800mAh). I made a circuit so the arduino can check the battery voltage and decide when it needs to recharge. I also have a circuit that controls the battery charge sequence and interrupts the power when the battery is charged, sending a signal to the arduino interrupting it's power saving mode. The arduino enters the power saving mode when the charging sequence is initiated. The charging circuit uses 12V and 450mA which I plan to supply with a 12V 6W solar panel.

My question is: can I charge the battery while the arduino is still on, but on power savig mode?

If not, how can I make this system self charging while keeping the arduino continuously on?

can I charge the battery while the arduino is still on, but on power savig mode?

You can draw power from a Li-Ion battery whilst charging it, but it isn't recommended. This is because the load on the battery affects the ability to detect the different phases of charging, and determine the end-of-charge condition.

Instead you should provide a bypass facility so that if external power is applied the external power is routed to the Arduino to power it, but when the power is removed the battery provides the power to the Arduino.

The circuit I usually use is:

simulate this circuit – Schematic created using CircuitLab

When 5V is applied the battery charges up. Q1 is held off. The 3.3V regulator is then powered through D1. When the 5V is removed Q1 is turned on by R1 pulling the gate low and the battery powers the 3.3V regulator.


Passing VAL(0-179) to OLED I´m using Spark Fun Micro Pro board 5V: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

and to that i´ve hooked a true color OLED from digole: http://www.digole.com/index.php?productID=859

I manage to get my VAL from my potentiometer on screen. But when I exceeds val "10", and then go back to lets say "9", the zero from "10" is still there. It looks like:  "90" instead of "9". The problem is of course that the second (and third) number don't go away.. Im sure there is a simple way of doing this but I can't get my head around it..
I´ve tried using clearScreen but that function makes the OLED blink in a unpleasant way every time it clears... Hope you get my question, english isn't my native language, as u maybe can tell =)
Thanks

void loop()
{
  val = analogRead(potpin);        // reads the value of the     potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 179);  // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val)  sets the servo position according to the scaled     value
  mydisp.clearScreen();
  mydisp.setPrintPos(9, 6);
  mydisp.print(val);

  delay(200);  // waits for the servo to get there
 // mydisp.clearScreen();

}

Instead of printing "10" or "9" etc, print "10 " or "9 ".  Add an extra space at the end of what you print which overwrites the character that was there before.

mydisp.print(val);
mydisp.print("  ");

I used 2 spaces there, in case you go from 3 digits straight to 1.

Another method is to "format" the number using sprintf:

char temp[4];
sprintf(temp, "%3d", val);
mydisp.print(temp);


AMIS30543 | Data-Sheet understanding Status register I was reading the data Sheet of AMIS-30543 stepper motor driver and I was not able to understand how to combine the result of the Micro step position status register MSP[8:0]. I know that its a 9 bit value . Help me understand how to get the value.
In the data sheet it is given like

in SR3 -> MSP[8:2], and in SR4 -> MSP[6:0]. How I am I suppose to get the 9 bit out of these.

In the library I have seen that , (sr3<<2) | (sr4 & 3)  . I don't understand why they are doing and & here.
Please explain . also If there was no library how am I suppose to know how to combine these registers from the dataSheet .
Link to DataSheet

Most of the data is duplicated between the registers. Both registers contain MSP[6:2].
If MSP contains 111001001 the registers (ignoring the MSB "PAR" bit) would look like:
SR3: 1110010
SR4: 1001001

If we line those up it's then like:
SR3: 1110010
SR4    1001001

You can now see the overlap.
So taking SR3 and shifting it left two places (sr3 << 2) gives you:
SR3:   1110010
<<2: 111001000

Taking the lowest two bits of SR4 with & 3 gives you:
SR4:   1001001
& 3:   0000001

Then ORing the two results together:
SR3<<2: 111001000
SR4 &3: 000000001
-----------------
MSP   : 111001001


How do interrupts work on the Arduino Uno and similar boards? Please explain how interrupts work on the Arduino Uno and related boards using the ATmega328P processor. Boards such as the:

Uno
Mini
Nano
Pro Mini
Lilypad

In particular please discuss:

What to use interrupts for
How to write an Interrupt Service Routine (ISR)
Timing issues
Critical sections
Atomic access to data

Note: this is a reference question.

TL;DR :

When writing an Interrupt Service Routine (ISR):

Keep it short
Don't use delay ()
Don't do serial prints
Make variables shared with the main code volatile
Variables shared with main code may need to be protected by "critical sections" (see below)
Don't try to turn interrupts off or on

What are interrupts?

Most processors have interrupts. Interrupts let you respond to "external" events while doing something else. For example, if you are cooking dinner you may put the potatoes on to cook for 20 minutes. Rather than staring at the clock for 20 minutes you might set a timer, and then go watch TV. When the timer rings you "interrupt" your TV viewing to do something with the potatoes.

Example of interrupts

const byte LED = 13;
const byte SWITCH = 2;

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  if (digitalRead (SWITCH) == HIGH)
    digitalWrite (LED, HIGH);
  else
    digitalWrite (LED, LOW);
}  // end of switchPressed

void setup ()
{
  pinMode (LED, OUTPUT);  // so we can update the LED
  pinMode (SWITCH, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (SWITCH), switchPressed, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  // loop doing nothing
}

This example shows how, even though the main loop is doing nothing, you can turn the LED on pin 13 on or off, if the switch on pin D2 is pressed.

To test this, just connect a wire (or switch) between D2 and Ground. The internal pullup (enabled in setup) forces the pin HIGH normally. When grounded, it becomes LOW. The change in the pin is detected by a CHANGE interrupt, which causes the Interrupt Service Routine (ISR) to be called.

In a more complicated example, the main loop might be doing something useful, like taking temperature readings, and allow the interrupt handler to detect a button being pushed.

Converting pin numbers to interrupt numbers

To simplify converting interrupt vector numbers to pin numbers you can call the function digitalPinToInterrupt(), passing a pin number. It returns the appropriate interrupt number, or NOT_AN_INTERRUPT (-1).

For example, on the Uno, pin D2 on the board is interrupt 0 (INT0_vect from the table below).

Thus these two lines have the same effect:

  attachInterrupt (0, switchPressed, CHANGE);    // that is, for pin D2
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);

However the second one is easier to read and more portable to different Arduino types.

Available interrupts

Below is a list of interrupts, in priority order, for the Atmega328:

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

Internal names (which you can use to set up ISR callbacks) are in brackets.

Warning: If you misspell the interrupt vector name, even by just getting the capitalization wrong (an easy thing to do) the interrupt routine will not be called, and you will not get a compiler error.

Reasons to use interrupts

The main reasons you might use interrupts are:

To detect pin changes (eg. rotary encoders, button presses)
Watchdog timer (eg. if nothing happens after 8 seconds, interrupt me)
Timer interrupts - used for comparing/overflowing timers
SPI data transfers
I2C data transfers
USART data transfers
ADC conversions (analog to digital)
EEPROM ready for use
Flash memory ready

The "data transfers" can be used to let a program do something else while data is being sent or received on the serial port, SPI port, or I2C port.

Wake the processor

External interrupts, pin-change interrupts, and the watchdog timer interrupt, can also be used to wake the processor up. This can be very handy, as in sleep mode the processor can be configured to use a lot less power (eg. around 10 microamps). A rising, falling, or low-level interrupt can be used to wake up a gadget (eg. if you press a button on it), or a "watchdog timer" interrupt might wake it up periodically (eg. to check the time or temperature).

Pin-change interrupts could be used to wake the processor if a key is pressed on a keypad, or similar.

The processor can also be awoken by a timer interrupt (eg. a timer reaching a certain value, or overflowing) and certain other events, such as an incoming I2C message.

Enabling / disabling interrupts

The "reset" interrupt cannot be disabled. However the other interrupts can be temporarily disabled by clearing the global interrupt flag.

Enable interrupts

You can enable interrupts with the function call "interrupts" or "sei" like this:

interrupts ();  // or ...
sei ();         // set interrupts flag

Disable interrupts

If you need to disable interrupts you can "clear" the global interrupt flag like this:

noInterrupts ();  // or ...
cli ();           // clear interrupts flag

Either method has the same effect, using interrupts / noInterrupts is a bit easier to remember which way around they are.

The default in the Arduino is for interrupts to be enabled. Don't disable them for long periods or things like timers won't work properly.

Why disable interrupts?

There may be time-critical pieces of code that you don't want interrupted, for example by a timer interrupt.

Also if multi-byte fields are being updated by an ISR then you may need to disable interrupts so that you get the data "atomically". Otherwise one byte may be updated by the ISR while you are reading the other one.

For example:

noInterrupts ();
long myCounter = isrCounter;  // get value set by ISR
interrupts ();

Temporarily turning off interrupts ensures that isrCounter (a counter set inside an ISR) does not change while we are obtaining its value.

Warning: if you are not sure if interrupts are already on or not, then you need to save the current state and restore it afterwards. For example, the code from the millis() function does this:

unsigned long millis()
{
  unsigned long m;
  uint8_t oldSREG = SREG;    // <--------- save status register

  // disable interrupts while we read timer0_millis or we might get an
  // inconsistent value (e.g. in the middle of a write to timer0_millis)
  cli();
  m = timer0_millis;
  SREG = oldSREG;            // <---------- restore status register including interrupt flag

  return m;
}

Note the indicated lines save the current SREG (status register) which includes the interrupt flag. After we have obtained the timer value (which is 4 bytes long) we put the status register back how it was.

Tips

Function names

The functions cli / sei and the register SREG are specific to the AVR processors. If you are using other processors such as the ARM ones the functions may be slightly different.

Disabling globally vs disabling one interrupt

If you use cli() you disable all interrupts (including timer interrupts, serial interrupts, etc.).

However if you just want to disable a particular interrupt then you should clear the interrupt-enable flag for that particular interrupt source. For example, for external interrupts, call detachInterrupt().

What is interrupt priority?

Since there are 25 interrupts (other than reset) it is possible that more than one interrupt event might occur at once, or at least, occur before the previous one is processed. Also an interrupt event might occur while interrupts are disabled.

The priority order is the sequence in which the processor checks for interrupt events. The higher up the list, the higher the priority. So, for example, an External Interrupt Request 0 (pin D2) would be serviced before External Interrupt Request 1 (pin D3).

Can interrupts occur while interrupts are disabled?

Interrupts events (that is, noticing the event) can occur at any time, and most are remembered by setting an "interrupt event" flag inside the processor. If interrupts are disabled, then that interrupt will be handled when they are enabled again, in priority order.

How do you use interrupts?

You write an ISR (interrupt service routine). This is called when the interrupt occurs.
You tell the processor when you want the interrupt to fire.

Writing an ISR

Interrupt Service Routines are functions with no arguments. Some Arduino libraries are designed to call your own functions, so you just supply an ordinary function (as in the examples above), eg.

// Interrupt Service Routine (ISR)
void switchPressed ()
{
 flag = true;
}  // end of switchPressed

However if a library has not already provided a "hook" to an ISR you can make your own, like this:

volatile char buf [100];
volatile byte pos;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;
    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

In this case you use the "ISR" macro, and supply the name of the relevant interrupt vector (from the table earlier on). In this case the ISR is handling an SPI transfer completing. (Note, some old code uses SIGNAL instead of ISR, however SIGNAL is deprecated).

Connecting an ISR to an interrupt

For interrupts already handled by libraries, you just use the documented interface. For example:

void receiveEvent (int howMany)
 {
  while (Wire.available () > 0)
    {
    char c = Wire.receive ();
    // do something with the incoming byte
    }
}  // end of receiveEvent

void setup ()
  {
  Wire.onReceive(receiveEvent);
  }

In this case the I2C library is designed to handle incoming I2C bytes internally, and then call your supplied function at the end of the incoming data stream. In this case receiveEvent is not strictly an ISR (it has an argument) but it is called by an inbuilt ISR.

Another example is the "external pin" interrupt.

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
}  // end of switchPressed

void setup ()
{
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);  // attach interrupt handler for D2
}  // end of setup

In this case the attachInterrupt function adds the function switchPressed to an internal table, and in addition configures the appropriate interrupt flags in the processor.

Configuring the processor to handle an interrupt

The next step, once you have an ISR, is to tell the processor that you want this particular condition to raise an interrupt.

As an example, for External Interrupt 0 (the D2 interrupt) you could do something like this:

EICRA &= ~3;  // clear existing flags
EICRA |= 2;   // set wanted flags (falling level interrupt)
EIMSK |= 1;   // enable it

More readable would be to use the defined names, like this:

EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
EICRA |= bit (ISC01);    // set wanted flags (falling level interrupt)
EIMSK |= bit (INT0);     // enable it

EICRA (External Interrupt Control Register A) would be set according to this table from the Atmega328 datasheet.
That defines the exact type of interrupt you want:

0: The low level of INT0 generates an interrupt request (LOW interrupt).
1: Any logical change on INT0 generates an interrupt request (CHANGE interrupt).
2: The falling edge of INT0 generates an interrupt request (FALLING interrupt).
3: The rising edge of INT0 generates an interrupt request (RISING interrupt).

EIMSK (External Interrupt Mask Register) actually enables the interrupt.

Fortunately you don't need to remember those numbers because attachInterrupt does that for you. However that is what is actually happening, and for other interrupts you may have to "manually" set interrupt flags.

Low-level ISRs vs. library ISRs

To simplify your life some common interrupt handlers are actually inside library code (for example INT0_vect and INT1_vect) and then a more user-friendly interface is provided (eg. attachInterrupt). What attachInterrupt actually does is save the address of your wanted interrupt handler into a variable, and then call that from INT0_vect / INT1_vect when needed. It also sets the appropriate register flags to call the handler when required.

Can ISRs be interrupted?

In short, no, not unless you want them to be.

When an ISR is entered, interrupts are disabled. Naturally they must have been enabled in the first place, otherwise the ISR would not be entered. However to avoid having an ISR itself be interrupted, the processor turns interrupts off.

When an ISR exits, then interrupts are enabled again. The compiler also generates code inside an ISR to save registers and status flags, so that whatever you were doing when the interrupt occurred will not be affected.

However you can turn interrupts on inside an ISR if you absolutely must, eg.

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
  interrupts ();  // allow more interrupts

}  // end of switchPressed

Normally you would need a pretty good reason to do this, as another interrupt now could result in a recursive call to pinChange, with quite possibly undesirable results.

How long does it take to execute an ISR?

According to the datasheet, the minimal amount of time to service an interrupt is 4 clock cycles (to push the current program counter onto the stack) followed by the code now executing at the interrupt vector location. This normally contains a jump to where the interrupt routine really is, which is another 3 cycles. Examination of the code produced by the compiler shows that an ISR made with the "ISR" declaration can take around 2.625 µs to execute, plus whatever the code itself does. The exact amount depends on how many registers need to be saved and restored. The minimum amount would be 1.1875 µs.

The external interrupts (where you use attachInterrupt) do a bit more and take around 5.125 µs in total (running with a 16 MHz clock).

How long before the processor starts entering an ISR?

This varies somewhat. The figures quoted above are the ideal ones where the interrupt is immediately processed. A few factors may delay that:

If the processor is asleep, there are designated "wake-up" times, which could be quite a few milliseconds, while the clock is spooled back up to speed. This time would depend on fuse settings, and how deep the sleep is.
If an interrupt service routine is already executing, then further interrupts cannot be entered until it either finishes, or enables interrupts itself. This is why you should keep each interrupt service routine short, as every microsecond you spend in one, you are potentially delaying the execution of another one.
Some code turns interrupts off. For example, calling millis() briefly turns interrupts off. Therefore the time for an interrupt to be serviced would be extended by the length of time interrupts were turned off.
Interrupts can only be serviced at the end of an instruction, so if a particular instruction takes three clock cycles, and has just started, then the interrupt will be delayed at least a couple of clock cycles.
An event that turns interrupts back on (eg. returning from an interrupt service routine) is guaranteed to execute at least one more instruction. So even if an ISR ends, and your interrupt is pending, it still has to wait for one more instruction before it is serviced.
Since interrupts have a priority, a higher-priority interrupt might be serviced before the interrupt you are interested in.

Performance considerations

Interrupts can increase performance in many situations because you can get on with the "main work" of your program without having to constantly be testing to see if switches have been pressed. Having said that, the overhead of servicing an interrupt, as discussed above, would actually be more than doing a "tight loop" polling a single input port. You can barely respond to an event within, say, a microsecond. In that case you might disable interrupts (eg. timers) and just loop looking for the pin to change.

How are interrupts queued?

There are two sorts of interrupts:

Some set a flag and they are handled in priority order, even if the event that caused them has stopped. For example, a rising, falling, or changing level interrupt on pin D2.
Others are only tested if they are happening "right now". For example, a low-level interrupt on pin D2.

The ones that set a flag could be regarded as being queued, as the interrupt flag remains set until such time as the interrupt routine is entered, at which time the processor clears the flag. Of course, since there is only one flag, if the same interrupt condition occurs again before the first one is processed, it won't be serviced twice.

Something to be aware of is that these flags can be set before you attach the interrupt handler. For example, it is possible for a rising or falling level interrupt on pin D2 to be "flagged", and then as soon as you do an attachInterrupt the interrupt immediately fires, even if the event occurred an hour ago. To avoid this you can manually clear the flag. For example:

EIFR = bit (INTF0);  // clear flag for interrupt 0
EIFR = bit (INTF1);  // clear flag for interrupt 1

However the "low level" interrupts are continuously checked, so if you are not careful they will keep firing, even after the interrupt has been called. That is, the ISR will exit, and then the interrupt will immediately fire again. To avoid this, you should do a detachInterrupt immediately after you know that the interrupt fired.

Hints for writing ISRs

In brief, keep them short! While an ISR is executing other interrupts cannot be processed. So you could easily miss button presses, or incoming serial communications, if you try to do too much. In particular, you should not try to do debugging "prints" inside an ISR. The time taken to do those is likely to cause more problems than they solve.

A reasonable thing to do is set a single-byte flag, and then test that flag in the main loop function. Or, store an incoming byte from a serial port into a buffer. The inbuilt timer interrupts keep track of elapsed time by firing every time the internal timer overflows, and thus you can work out elapsed time by knowing how many times the timer overflowed.

Remember, inside an ISR interrupts are disabled. Thus hoping that the time returned by millis() function calls will change, will lead to disappointment. It is valid to obtain the time that way, just be aware that the timer is not incrementing. And if you spend too long in the ISR then the timer may miss an overflow event, leading to the time returned by millis() becoming incorrect.

A test shows that, on a 16 MHz Atmega328 processor, a call to micros() takes 3.5625 µs. A call to millis() takes 1.9375 µs. Recording (saving) the current timer value is a reasonable thing to do in an ISR. Finding the elapsed milliseconds is faster than the elapsed microseconds (the millisecond count is just retrieved from a variable). However the microsecond count is obtained by adding the current value of the Timer 0 timer (which will keep incrementing) to a saved "Timer 0 overflow count".

Warning: Since interrupts are disabled inside an ISR, and since the latest version of the Arduino IDE uses interrupts for Serial reading and writing, and also for incrementing the counter used by "millis" and "delay" you should not attempt to use those functions inside an ISR. To put it another way:

Don't attempt to delay, eg: delay (100);
You can get the time from a call to millis, however it won't increment, so don't attempt to delay by waiting for it to increase.
Don't do serial prints (eg. Serial.println ("ISR entered"); )
Don't try to do serial reading.

Pin change interrupts

There are two ways you can detect external events on pins. The first is the special "external interrupt" pins, D2 and D3. These general discrete interrupt events, one per pin. You can get to those by using attachInterrupt for each pin. You can specify a rising, falling, changing or low-level condition for the interrupt.

However there are also "pin change" interrupts for all pins (on the Atmega328, not necessarily all pins on other processors). These act on groups of pins (D0 to D7, D8 to D13, and A0 to A5). They are also lower priority than the external event interrupts. However they are a bit more fiddly to use than the external interrupts because they are grouped into batches. So if the interrupt fires you have to work out in your own code exactly which pin caused the interrupt.

Example code:

ISR (PCINT0_vect)
 {
 // handle pin change interrupt for D8 to D13 here
 }  // end of PCINT0_vect

ISR (PCINT1_vect)
 {
 // handle pin change interrupt for A0 to A5 here
 }  // end of PCINT1_vect

ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D9)
  PCMSK0 |= bit (PCINT1);  // want pin 9
  PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13
  }

To handle a pin change interrupt you need to:

Specify which pin in the group. This is the PCMSKn variable (where n is 0, 1 or 2 from the table below). You can have interrupts on more than one pin.
Enable the appropriate group of interrupts (0, 1 or 2)
Supply an interrupt handler as shown above

Table of pins -> pin change names / masks

D0    PCINT16 (PCMSK2 / PCIF2 / PCIE2)
D1    PCINT17 (PCMSK2 / PCIF2 / PCIE2)
D2    PCINT18 (PCMSK2 / PCIF2 / PCIE2)
D3    PCINT19 (PCMSK2 / PCIF2 / PCIE2)
D4    PCINT20 (PCMSK2 / PCIF2 / PCIE2)
D5    PCINT21 (PCMSK2 / PCIF2 / PCIE2)
D6    PCINT22 (PCMSK2 / PCIF2 / PCIE2)
D7    PCINT23 (PCMSK2 / PCIF2 / PCIE2)
D8    PCINT0  (PCMSK0 / PCIF0 / PCIE0)
D9    PCINT1  (PCMSK0 / PCIF0 / PCIE0)
D10   PCINT2  (PCMSK0 / PCIF0 / PCIE0)
D11   PCINT3  (PCMSK0 / PCIF0 / PCIE0)
D12   PCINT4  (PCMSK0 / PCIF0 / PCIE0)
D13   PCINT5  (PCMSK0 / PCIF0 / PCIE0)
A0    PCINT8  (PCMSK1 / PCIF1 / PCIE1)
A1    PCINT9  (PCMSK1 / PCIF1 / PCIE1)
A2    PCINT10 (PCMSK1 / PCIF1 / PCIE1)
A3    PCINT11 (PCMSK1 / PCIF1 / PCIE1)
A4    PCINT12 (PCMSK1 / PCIF1 / PCIE1)
A5    PCINT13 (PCMSK1 / PCIF1 / PCIE1)

Interrupt handler processing

The interrupt handler would need to work out which pin caused the interrupt if the mask specifies more than one (eg. if you wanted interrupts on D8/D9/D10). To do this you would need to store the previous state of that pin, and work out (by doing a digitalRead or similar) if this particular pin had changed.

You are probably using interrupts anyway ...

A "normal" Arduino environment already is using interrupts, even if you don't personally attempt to. The millis() and micros() function calls make use of the "timer overflow" feature. One of the internal timers (timer 0) is set up to interrupt roughly 1000 times a second, and increment an internal counter which effectively becomes the millis() counter. There is a bit more to it than that, as adjustment is made for the exact clock speed.

Also the hardware serial library uses interrupts to handle incoming and outgoing serial data. This is very useful as your program can be doing other things while the interrupts are firing, and filling up an internal buffer. Then when you check Serial.available() you can find out what, if anything, has been placed in that buffer.

Executing the next instruction after enabling interrupts

After a bit of discussion and research on the Arduino forum, we have clarified exactly what happens after you enable interrupts. There are three main ways I can think of that you can enable interrupts, which were previously not enabled:

  sei ();  // set interrupt enable flag
  SREG |= 0x80;  // set the high-order bit in the status register
  reti  ;   // assembler instruction "return from interrupt"

In all cases, the processor guarantees that the next instruction after interrupts are enabled (if they were previously disabled) will always be executed, even if an interrupt event is pending. (By "next" I mean the next one in program sequence, not necessarily the one physically following. For example, a RETI instruction jumps back to where the interrupt occurred, and then executes one more instruction).

This lets you write code like this:

sei ();
sleep_cpu ();

If not for this guarantee, the interrupt might occur before the processor slept, and then it might never be awoken.

Empty interrupts

If you merely want an interrupt to wake the processor, but not do anything in particular, you can use the EMPTY_INTERRUPT define, eg.

EMPTY_INTERRUPT (PCINT1_vect);

This simply generates a "reti" (return from interrupt) instruction. Since it doesn't try to save or restore registers this would be the fastest way to get an interrupt to wake it up.

Critical sections (atomic variable access)

There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).

Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

First ... when do you use "volatile" variables?

A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.

volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variables contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

Turn interrupts off while accessing a volatile variable

For example, to compare count to some number, turn interrupts off during the compare in case one byte of count has been updated by the ISR and not the other byte.

volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  noInterrupts ();    // <------ critical section
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();      // <------ end critical section
  } // end of loop

Read the data sheet!

More information about interrupts, timers, etc. can be obtained from the data sheet for the processor.

http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

Further examples

Space considerations (post size limit) prevent my listing more example code. For more example code see my page about interrupts.


Attiny85 and 433Mhz RF I have this cheap RF link that I had working with the Arduni UNO, but I wanted to make it smaller and ATTiny85 should do the trick. The RF module is connected (data pin) to PB3 on the ATTiny.

But I am having some problems. It does not work, and I don't know why. My code:

#include <SoftwareSerial.h>

// PINS
#define SERIAL_TX PB3

SoftwareSerial mySerial(-1, SERIAL_TX);

void setup() {
  pinMode(SERIAL_TX, OUTPUT);
  mySerial.begin( 1200 );
}

void loop() {

  mySerial.write(0xAA);
  mySerial.write(0xAA);
  mySerial.write(0xAA);

  delay(1000);
}

The code you presented does not fit for working with the RF 433Mhz. I'm not sure what you think this code should do, but this is not the way to go with a 433Mhz transmitter.

I would suggest using a dedicated library for transmitting information using the 433. There are many libraries out there for doing that; two popular libraries would be the ManchesterRF and the VirtualWire, both includes code samples.

For example, sending data with ManchesterRF:

#include "ManchesterRF.h" //https://github.com/cano64/ManchesterRF

#define TX_PIN 3 //any pin can transmit
#define LED_PIN 13

ManchesterRF rf(MAN_4800); //link speed, try also MAN_300, MAN_600, MAN_1200, MAN_2400, MAN_4800, MAN_9600, MAN_19200, MAN_38400

uint8_t data = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  rf.TXInit(TX_PIN);
}

void loop() {

  rf.transmitByte(++data, data*data);
  digitalWrite(LED_PIN, digitalRead(LED_PIN)); //blink the LED on receive
  delay(100);
}

In addition, there are many other blogs around going step-by-step how to use 433Mhz Tx/Rx with ATtiny85, google is your friend :)


Arduino Mega with nRF24L01+ module I am having trouble getting this module to work using the tmrh20 lib. I am using these modules with two arduino mega and a 3.3V external power supply. I also placed 10 uF in parallel with the modules power pin. I would really appreciate any comments or suggustions.

In the code below all I am trying to do is turn on a led.
Here are my pin assignment for both arduinos
CE -> 7
CSN -> 8
SCK -> 52
MOSI -> 51
MISO -> 50
IRQ -> unconnected

Transmitter

//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg = 375983;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Transmitter");
    pinMode(9, INPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openWritingPipe(pipe);
    radio.startListening();
    radio.printDetails();
}

void loop() {
  radio.stopListening();
  if (digitalRead(9) == HIGH)
  {
    while (!radio.write(&msg, sizeof(msg))){
      radio.write(&msg, sizeof(msg));
}
  Serial.println("Sending.....");
  }
  else {
    Serial.println("Awaiting Input....");
  }
  delay(500);

}

print detail report

STATUS = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1 = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5 = 0x7f 0xff 0x7f 0xff
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0xff 0x7f 0xff 0x7f 0xff 0xff
EN_AA = 0xff
EN_RXADDR = 0xff
RF_CH = 0xff
RF_SETUP = 0xff
CONFIG = 0xff
DYNPD/FEATURE = 0x7f 0xff
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MAX

Receiver

//#include <DigitalIO.h>
#include <SPI.h>
#include "RF24.h"
#include <printf.h>
RF24 radio(7,8);
const uint64_t pipe = 0xE8E8F0F0E1LL;
unsigned long msg;

void setup() {
    Serial.begin(115200);
    printf_begin();
    Serial.println("Receiver");
    pinMode(9, OUTPUT);
    radio.begin();
    radio.setChannel(108);
    radio.openReadingPipe(0,pipe);
    radio.printDetails();

}

void loop() {
   radio.startListening();
   digitalWrite(9, LOW);
  if(radio.available()){
    while(radio.available())
    {
    radio.read(&msg, sizeof(msg));
    Serial.println("Incoming...");
    delay(500);
    Serial.println(msg);
    }
  }
  else{
    Serial.println("No Msg");
  }
  radio.stopListening();
  Serial.println(msg);
  if (msg == 375983){
    digitalWrite(9, HIGH);
    Serial.println(msg);
  }
  delay(500);
}

print detail report

STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1 = 0x0000000000 0x0000000000
RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA = 0x00
EN_RXADDR = 0x00
RF_CH = 0x00
RF_SETUP = 0x00
CONFIG = 0x00
DYNPD/FEATURE = 0x00 0x00
Data Rate = 1MBPS
Model = nRF24L01
CRC Length = Disabled
PA Power = PA_MIN

UPDATE:
Transmitter PrintDetail

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

Results form tmrh20 Getting Started Example

First Arduino

Sent 8340224, Got response 0, Round-trip delay 547172 microseconds
Now sending
Sent 9889124, Got response 0, Round-trip delay 511072 microseconds
Now sending
Sent 11401920, Got response 0, Round-trip delay 43348 microseconds
Now sending
Sent 12446992, Got response 0, Round-trip delay 635580 microseconds
Now sending
Sent 14084352, Got response 0, Round-trip delay 1620788 microseconds
Now sending
Sent 16706968, Got response 0, Round-trip delay 1227548 microseconds
Now sending
Sent 18936340, Got response 0, Round-trip delay 145372 microseconds

Second Arduino

*** PRESS 'T' to begin transmitting to the other node

The second arduino is not printing anything on the serial monitor, no matter what I enter.

(not enough point to comment, so here's a potential answer)
I had enormous troubles getting these things to work reliably.  I tried all kinds of caps over the power supply. In the end I went for a 1$ piggy back board that takes 5v input and regulates to 3.3V. It also has the right pin female header to fit the nfr nicely. Since then I've had no issues. I also did a bit of experimentation and found that the RX side was the side giving problems.


Reduce speed on DC motor The Arduino starter kit came with a DC motor. I want to have it rotate at a slow speed so it can be on a reel and automatically dispense and wind wire, however, I don't know how I can slow it down.

Giving it an analog value of 1 is still way too fast.

Is there any way to control or reduce the speed. Like a 360 degree turn in a second rather than milliseconds?

Thanks

Remember if you are using a UNO or similar there is no Analog Output, the output is PWM (Look that up).
If its DC motor then it needs to work from a DC (constant voltage) and will spin at a fixed speed.
Motors usually have a RPM (speed) specification.
Speed can be reduced with gears and rotation detected with rotary encoders and or sensors like Infra Red Switches or Reed Switches.
You can also get Motor Controllers like...
https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
AC Motors can be speed controlled by changing drive frequency, this is usually called an inverter.
NOTE reducing DC voltage will result in less torque and higher current.
Hope this helps.


Thermistor doesn't work Connecting all like shows the image, thermistor shows, that I'm going to be burnt:

The code is simple:

#define analogPin  A0 //the thermistor attach to
#define beta 4090
#define resistance 10

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

void loop()
{
  //read thermistor value
  long a =analogRead(analogPin);
  //the calculating formula of temperature
  float tempC = beta /(log((1025.0 * 10 / a - 10) / 10) + beta / 298.0) - 273.0;
  float tempF = 1.8*tempC + 32.0;
  Serial.print("Temp: ");

  Serial.print(tempC);

  Serial.print("  C");

  Serial.print("Fahr: ");
  Serial.print(tempF);
  Serial.print(" F");
  delay(200); //wait for 100 milliseconds
}

Do I have a wrong thermistor or wrong code?

The series resistance is 220 Ohms (Red, Red, Brown).

You also need to take into account the thermistor resistance at 25C. Assuming its 10K. Hence choosing a 10K series resistance will make the calculations easier.

     int THERMISTORNOMINAL =  10000;
     int SERIESRESISTOR = 10000;
     int TEMPERATURENOMINAL = 25;

     a = 1023 / a - 1;
     a = SERIESRESISTOR / a;
     tempC = a / THERMISTORNOMINAL;     // (R/Ro)
     tempC = log(tempC);                  // ln(R/Ro)
     tempC /= Beta;                   // 1/B * ln(R/Ro)
     tempC += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
     tempC = 1.0 / steinhart;                 // Invert
     tempC -= 273.15;                         // convert to C


Raspberry Pi with Arduino, Serial connection stops working This is the hardware set-up at home,

Raspberry Pi GPIO -> Logic Level Converter -> Arduino -> Multiple Relays

I am running Raspbian and NodeJS on the Pi while the Arduino is loaded with StandardFirmata.
I connect NodeJS to the Arduino with the johnny-five package and it works well after it's started. But after extended periods, a few hours? The Arduino stops responding. Whatever command that I send to the Arduino won't be acted on. It's as though as the Arduino hung.
Both the Raspberry Pi and Arduino are being powered indenpendently with a 1A Nokia USB Adapter.

Does anyone know why this is happening?

johnny-five
StandardFirmata
NodeJS Server Code

If none of the code is yours, and all code from the Firmata library, then the most possible cause that comes to mind after reviewing the library code is memory leak, which makes the next allocation to fail and by thus breaking the code.

The Firmata library does perform dynamic memory allocation, checkout Firmata.c, so it is realistic - I would suggest to take it with the Library's author.


POST request on Arduino MKR1400 GSM not working Im trying to send a POST request from the Arduino MKR1400 GSM board to a server with a database.

I've tested the server using Postman (https://www.getpostman.com/) and it handles the POST request correctly, the json data gets uploaded to database fine.

The problem is that the same POST request from the Arduino MKR GSM 1400 does nothing. I've tried using client.print and I get the same result.

I'm not sure what I'm doing wrong or how to debug this issue, any ideas?

Arduino code:

#include <MKRGSM.h>
#include "Credentials.h"

// Definiciones para el GPRS
const char PINNUMBER[]     = SECRET_PINNUMBER;
const char GPRS_APN[]      = SECRET_GPRS_APN;
const char GPRS_LOGIN[]    = SECRET_GPRS_LOGIN;
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD;

GSMClient client;
GPRS gprs;
GSM gsmAccess;
GSMScanner scanner;

char ip[4] = {xxx,xxx,xxx,xxx};
char ipstring[14];
char path[] = "/atcapp.php";
int port = 80; // port 80 is the default for HTTP

char respName[30] = "Arduino MKR GSM 1400";
char toolName[30] = "Herramienta martillo";
char location[30] = "Mave Aeronautica S.L.";
char tlState[4] = "OUT";
unsigned long int user_id = 4294967295;
unsigned long int tool_id = 1234567899;
unsigned long int tmeStmp = 1532684104;
char notes[100] = "";

char postData[200];
char packetData[500];

void setup() {

  Serial.begin(9600);
  while(!Serial);
  sprintf(ipstring,"%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3]);
  post(respName,user_id,location,toolName,tool_id,tlState,tmeStmp,notes);

}

char post(char* resp,unsigned long int userid,char* location, char* toolName,unsigned long int toolid,char* toolState,unsigned long int timeStamp,char* notes)
{
  Serial.println("Connecting to GPRS Network...");
  boolean connected = false;

  while (!connected) {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("GPRS connection failed");
      delay(1000);
      return -1;
    }
  }

  if (client.connect(ip, port)) {
    sprintf(packetData,"POST %s HTTP/1.1\nHost: %s\nUser-Agent: Arduino/1.0\nConnection: close\nContent-Length: %d\nContent-Type: application/json\nCache-Control: no-cache\n\n{\n\"responsable\":\"%s\",\n\"user_id\":%lu,\n\"loc\":\"%s\",\n\"tool\":\"%s\",\n\"tool_id\":%lu,\n\"tool_state\":\"%s\",\n\"timestamp\":%lu,\n\"note\":\"%s\"\n}\n",path,ipstring,sizeof(postData),resp,userid,location,toolName,toolid,toolState,timeStamp,notes);
    client.beginWrite();
    for(int i=0;i<sizeof(packetData);i++){
        Serial.write(packetData[i]);
        client.write(packetData[i]);
    }
    client.endWrite();

    while(client.connected()){
      Serial.println("Client still connected.");
      while(client.available()){
        Serial.println("Client still available.");
        char c = client.read();
        Serial.print(c);
      }
    }

    Serial.println("disconnecting.");
    client.stop();

    Serial.println();
    Serial.println("Done.");
    return 1;
  }else{
    Serial.println("Cannot connect to server.");
    return 0;
  }

}

void loop() {}

Serial port output:

It's my first time ever asking a question here, any contructive criticism is more than valuable to me. Thank you in advance,

The problem most likely stems from your Content-Length header.  You are using sizeof(postData) as the length of your content - however postData is a 200 byte array which is not used for anything. sizeof() will always return 200 for that regardless of what the rest of your program is doing.

Content-Length must be equal to the number of bytes after the second of the two \n separating the header from the body.  The best way to calculate that is up add up the length of all the strings that get inserted into the body formatting (using strlen() not sizeof()), and then add to that a constant value which is equal to the number of static characters (including \n) in the body (I make that 108 possibly?).

int dataLen = 108;
dataLen += strlen(resp);
dataLen += strlen(userid);
dataLen += strlen(location);
dataLen += strlen(toolName);
dataLen += strlen(toolid);
dataLen += strlen(toolState);
dataLen += strlen(timeStamp);
dataLen += strlen(notes);

Alternatively you pre-format the body into a separate string and use strlen() on that to get the length before starting to send data.  Of course, you don't need to store all the header in the string, since you can just send that line-by-line...

sprintf(packetData,"{\n\"responsable\":\"%s\",\n\"user_id\":%lu,\n\"loc\":\"%s\",\n\"tool\":\"%s\",\n\"tool_id\":%lu,\n\"tool_state\":\"%s\",\n\"timestamp\":%lu,\n\"note\":\"%s\"\n}\n",resp,userid,location,toolName,toolid,toolState,timeStamp,notes);
client.beginWrite();
client.print(F("POST "));
client.print(path);
client.println(F(" HTTP/1.1"));

client.print(F("Host: "));
client.println(ipstring);

client.println(F("User-Agent: Arduino/1.0"));
client.println(F("Connection: close"));
client.print(F("Content-Length: "));
client.println(strlen(packetData));
client.println(F("Content-Type: application/json"));
client.println(F("Cache-Control: no-cache"));
client.println();

client.print(packetData);

client.endWrite();

Note the use of F() around your static text to save copious amounts of RAM on AVR-based boards. Not really necessary on an ARM-based board, but a good thing to get into the habit of to keep things portable.

If you want to debug what is being sent I would suggest making a "debug" wrapper class that comprises both client and Serial:

class TwinPrint : public Print {
    private:
        Print *_ch1;
        Print *_ch2;

    public:
        TwinPrint(Print &ch1, Print &ch2) : _ch1(&ch1), _ch2(&ch2) {}
        size_t write(uint8_t c) {
            _ch1->write(c);
            _ch2->write(c);
            return 1;
        }
};

You can then construct a new object:

TwinPrint debug(client, Serial);

and do your writing to that and it will come out on both client and Serial at once:

debug.print(F("POST "));
debug.print(path);
debug.println(F(" HTTP/1.1"));

debug.print(F("Host: "));
debug.println(ipstring);

debug.println(F("User-Agent: Arduino/1.0"));
debug.println(F("Connection: close"));
debug.print(F("Content-Length: "));
debug.println(strlen(packetData));
debug.println(F("Content-Type: application/json"));
debug.println(F("Cache-Control: no-cache"));
debug.println();

debug.print(packetData);


On a motor after a continuous input of a certain amount of time I would like to produce an output after a constant input is detected for a certain amount of time. Below is a simple code of what I am trying to do minus the time factor. Can someone help me on how to code out the duration of an input occurrence?  i.e.

if (sensorValue > threshold);
    //if this occurs for more than 4 hours, then
    digitalWrite (3, HIGH);

You must store the state of the last readings and do something like this:

    //Off-loop:
    bool state_changed = false;
    unsigned long time_in_state = 0;
    unsigned long last_reading = 0;

    //On-loop:
    if (sensorValue > treshold && !state_changed) {
        time_in_state += millis() - last_reading;
        last_reading = millis();
    }
    else {
        state_changed = true;
        time_in_state = 0;
    }

    if (time_in_state > TIME_REQUIRED) {
      digitalWrite (3, HIGH);
    }


Create a device to detect object and voice alert what kind of object it is Here is what I want to do (since I'm not a embedded guy)

create a prototype with an Arduino to detect objects using camera(object classification?)
that prototype will detect objects and alert that object's name

My questions are....

Is it possible? :)
What things should I use to create a prototype?
What camera should I use?
Is it related to image processing?
Connection between object detection and voice alert?

The Arduino is not the ideal platform for you since it is more "lightweight" and can't really meet the demand that your application is expecting.

A platform like for example Raspberry Pi that has a full-blown operating system and a lot of tools that fulfils your application needs.


Can an Arduino Pro Mini interface with a full-sized WiFi shield? We have an Arduino Pro Mini on a breadboard connected to a 9V battery and a sensor, reading data. We also have a full-sized Adafruit WINC1500 WiFi Shield with PCB Antenna. I would like to know if they can be connected and, if so, how.

I understand that a shield is usually stacked on a similarly sized board, but can we place the shield on the breadboard with the Mini and use jumper wire to connect the necessary pins so the Mini can use the WiFi (actually, we want to write to the SD card on the WiFi shield)? If so, how would we know which pins are used, and would we need to provide additional power? Or is connecting a Mini to a full-sized shield a ridiculous idea?

I would like to know if they can be connected and, if so, how.

Yes.

  but can we place the shield on the breadboard

No, the pins are misaligned and won't plug in.

  and use jumper wire to connect the necessary pins so the Mini can use the WiFi

Yes - connect the jumper wires directly to the WiFi shield pins.

  If so, how would we know which pins are used,

Read the manual or schematic for your WiFi shield. It probably uses the SPI pins plus a few more.

  and would we need to provide additional power?

It will need a power connection, yes - though "extra" power? Not sure what you mean.


Which board to use for wireless communication of small packages? I was hoping to get your advice on what Arduino boards to look at for a project I'm working on. The project involves two separate boxes in different rooms of my apartment (~ 5-10 feet away from each other) and needs to allow wireless communication of very small amounts of information (think like 5 bytes). However, this transfer needs to be very rapid (within 200 milliseconds).

While I have worked a good bit with the Arduino Uno, I haven't worked with boards with Wifi capabilities.

The boards I know of are: Esp32, Esp8266, Arduino MKR 1010, Arduino Mega RobotDyn.

What would be the best board for a project like this / are there other boards that are well-suited for a project like this?

Thanks!

WiFi round trip time is about 2-50 ms (50 is the worst case), so, you can use the ESP's and the UDP/TCP.

On the other hand, you can use the NRF433 module, but in this case, you have to develop your own channel level protocol, with error detection/correction and so on.

Also, there are ZigBee module. They developed for home automation specially.


Updating firmware on Adafruit Huzzah ESP8266 tldr: I'm trying to re-flash a previously working Adafruit Huzzah ESP8266 breakout module to use the latest AT firmware. The re-flash doesn't seem to be working and I'm getting rather confused. This is the first time I've re-flashed one of these modules.

What I did:

I installed the latest version of esptool.py using pip, and downloaded the latest Espressif AT firmware from github. With the Huzzah on a breadboard I grounded GPIO0 and connected the serial port header to my PC using a FTDI cable. VC on the cable is 5v. The red power light lit. I then ran the following commands:

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x00000 boot_v1.1.bin

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x01000 user1.bin

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7C000 esp_init_data_default.bin

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7E000 blank.bin

Each upload seemed to complete ok, but I found that I couldn't upload the next until I pressed the reset button on the module first, otherwise I got the error:

  A fatal error occurred: Failed to connect to Espressif device: Timed
  out waiting for packet header

This doesn't seem right to me.

After uploading all 4 components as above I disconnected GPIO0 and cycled the power on the module. I then tried connecting using putty at 115200 baud but I get no echo back from the module, and it doesn't respond to commands.

Observations:

The module previously worked and I could connect to it with putty.
If I reset it while connected to putty at 115200, I get a consistent pattern of garbage characters, so my guess is its alive but confused somehow.
I've tried connecting at various baud rates: 9600, 14400, 19200, 38400, 57600, as well as 115200. Same result.
I've found walkthroughs that show firmware like node.mcu being uploaded as a single binary. Should I be somehow merging the four bin files into one before uploading the the Huzzah?

What am I doing wrong here?

I'm confident that I've resolved this now. I'll leave the question here in case it is useful to anyone in the future.

The problem was they way I was downloading the individual bin files from the github repo, using right click -> Save As in Chrome. This downloads a file with the correct name, but it is actually the content of the file's html page, not the binary itself. Downloading the repo as a zip file, extracting the bin files,  and then uploading them to the Huzzah using a single command gave me a properly flashed device.

What happened was I noticed that esptool can upload multiple files in one go so, with the original bin files, I tried the command:

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m 0x00000 boot_v1.1.bin 0x01000 user1.bin 0x7C000 esp_init_data_default.bin 0x7E000 blank.bin

and got the following error

  esptool write_flash: error: argument  : Detected overlap at address: 0x1000 for file: user1.bin

Thats when I noticed that boot_v1.1.bin was way to big to fit in the space between 0x00000 and 0x01000. Examining it in notepad++ revealed that it was html.

A learning experience...


ESP8266 timer to trigger actions (logic issue) so I have an application in which there are 2 specific times (eg 9AM, 6PM) where a variable curPos is updated. Everything is converted in ms since 00:00 (9AM = 32400000, 6PM = 64800000). Now, the actions (curPos updates) should be triggered every day at these times. To retrieve the current real time (always in ms) I'm sending a http request to a website. This is done only once in the setup().

The idea is that I have to access somehow (http request) the current real time in order to determine when are 9AM and 6PM in my ESP8266, since the start of the sketch. The current real time is needed only once at the beginning (in case there's an issue and the sketch restarts).
Then I can calculate the difference between the current real time and the timers.

The next step would be to translate the values into a 24hour cycle starting at the startup/reset time, so that it can repeat itself without need to request again the real time.

I'm lost in the logic on how to deal with this and with millis() to check when it's time to trigger one of the actions.

This is what I'm doing now with the HTPP GET payload in the setup() (I can successfully retrieve the 3 values in ms from the GET response)

      String payload = http.getString();

      int commaIndex = payload.indexOf(',');
      int secondCommaIndex = payload.indexOf(',', commaIndex + 1); //Search for the next comma just after the first

      mainTime = payload.substring(0, commaIndex).toInt(); //current real time in ms
      timers[0] = payload.substring(commaIndex + 1, secondCommaIndex).toInt(); //9AM in ms
      timers[1] = payload.substring(secondCommaIndex + 1).toInt()); //6PM in ms

      timers[0] = abs(mainTime - timers[0]); //the time difference before reaching the first timer (in ms)
      timers[1] = abs(mainTime - timers[1]); //the time difference before reaching the second timer (in ms)

      // my attempt to turn the time differences into a 24hrs "local" (in the sketch) time
      //dayMs is 24hrs in ms (86400000)
      if(timers[0] < 0)
        timers[0] = dayMs - timers[0];

      if(timers[1] < 0)
        timers[1] = dayMs - timers[1];

and in the loop I'd need a comparison (I think) but I'm just really lost on this

//I think millis need to be reset after 24hrs since the start of the sketch?

if(millis() == timers[0]){
      curPos = 1; //first timer expired then trigger
  }else if(millis() == timers[1]){
      curPos = 7; //second timer expired then trigger
  }

thanks!

For time-keeping on a long-term basis, you are going to run up against clock drift and offsets from tick-tracking. You may be better off using a real-time-clock (RTC) such as the DS1307. This and RTCs like it are often available in breakout boards with a coin-cell battery holder built in.

You would still get the time from your HTTP or NTP source, but the RTC will be much better at keeping the "right" time as you would expect a wristwatch or desk clock to do, versus using the MCU for counting milliseconds.

You can use Ticks or millis() to set up a periodic read of the RTC every second or every 10 seconds, etc. Avoid using the MCU clock for long-term real-world time keeping.


Where can I find a central repository of all available Arduino libraries? Currently; when I start a new Arduino project with some new hardware, the first thing I do is to look for 3rd-party libraries that bring Arduino support for this hardware.

The first places I look are:

The Arduino Playground
GitHub
Google

Generally I find either no support library or several different libraries (it's quite rare to find only one) in different locations with different levels of documentation, different levels of testing...

Once I have found the library I need (sometimes I need to try several), I download it to my Arduino libraries folder, I use it and I forget it.

I find this process cumbersome:

manual search with different possible options, not always well documented
manual download and install to Arduino libraries
no version control in the process (all versions of a library have the same name and thus cannot coexist in the Arduino library folder).

I wish there was a central repository with all available libraries for arduino, with:

description (supported hardware, supported boards)
source code
documentation
versions

And a tool (Arduino IDE or external) to access this repository at project build time.

A kind of maven for Arduino in fact.

I have seen several discussions once took place on Arduino forum, but it seems they led nowhere:

Arduino Libraries Census and Repository
Arduino Library downloader
Arduino Library downloader (2)

Are there other options, that are made it to something usable (from the community or individuals, why not)?

Since this question was first asked, there is now the Arduino Library Manager, built into the Arduino IDE. There you can search for and install libraries.

There is information about how the library manager works here:
https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ

There isn't however an official website listing the libraries, so I recently created this unofficial site, based on the same data in the Arduino Library Manager:

http://www.arduinolibraries.info/


Issues programming Arduino Uno with Sparkfun's MAX3232 breakout board I'm having an issue programming the Arduino Uno with Sparkfun's MAX3232 breakout board attached.  Sometimes the Arduino IDE won't see the Uno plugged in.  I'm thinking of  connecting a switch to the GND or the 3V - 5.5V pin so I don't have to disconnect the breakout board when programming.  Are there any better solutions?

Sparkfun link: https://www.sparkfun.com/products/11189

Switching the power off to the MAX3232 appears to be okay.
There are no components connected to the Rx and Tx lines on the breakout board to complicate it.

Unfortunately the break out does not give access to pin 1, EN which is "Enable Control", or pin 18 SHDN "Shutdown Control". AFAICT they could have been used to turn off the receiver and transmitters of the MAX3232. That would have been ideal. Maybe contact Sparkfun and suggest the improvement to put them on pads for folks to use, and offer to beta test it :-)

The datasheet for the MAX3232 says that it is able to withstand a continuous short on the Tx line, so it sounds pretty tolerant to minor abuse. Also, the diagrams dont show any pull-ups on the MOS/TTL Tx line. So I would expect it t be okay if you shut the power off, but continued to wiggle the Tx Rx pins.

An alternative would be to disconnect the Tx pin from the Arduino, so that the MAX3232 wouldn't interfere with the host PC's USB comms. It sounds like the thing on the RS232 connection will ignore data it receive while the Arduino is being programmed. If that is not true, then it would need to be disconnected too.

At the moment, switching off power looks like a reasonable approach.
Disconnecting Tx and Rx also looks reasonable, and slightly better than powering the MAX3232 off.

Do you know how you want to do that?

NB: The MAX232 datasheet shows that part should not be driven by a high when the chip is unpowered. However the MAX3232 datasheet does not carry that warning. My preference would be to use the MAX3232 signals 'EN' and 'SHDN'. However those are not available on the breakout. I'd recommend having the part powered, and disconnecting Tx and Rx from the Arduino.


Change RF Receiver Frequency by Antenna Length This may be a very stupid question, but I have got me one of those cheap 433 MHz RF modules for the Arduino.
I'm wondering if I can vary the receiver's frequency by simply changing the length of the antenna? Or does the circuit limit the frequency band to 433 MHz?

Thanks in advance.

No, changing the antenna length will only change the resonant frequency of the antenna circuit. That is, it will affect the sensitivity of the receiver, but won't actually change the frequency that the receiver "listens" to.


Power supply change change gps readings? I was powering a GPS Sensor from the 3v3 pin of a raspberry pi and my reading for my GPS sensor had some strange symbols in the mix, but when i switched to the 3v3 on the arduino, my reading came back to normal. This wasted several hours of my time.

Any idea why i would get weird readings when using a different power source?? (even though it is the same voltage)

Note: Both the raspberry pi and the arduino are getting their power form the USB that is connected to my PC.

The Pi can only supply ~50mA from 3.3V. This is unlikely to be enough to run GPS.

In addition USB can only supply 500mA. This is marginal at best, and below the recommended minimum for Pi.


GSM 900A modem not responding to AT commands I am using GSM 900A modem which requires 5V Supply. I am connecting it to Arduino UNO. I am giving supply to modem by arduino 5V and GND pin. I am connecting RXD pin to TX(pin 1) of arduino TXD pin to RX(pin 0) of arduino and GND to GND of arduino i.e. pin 14. I am running the basic example codes but GSM is not responding. I have also tried other softwares like Putty but I am unable to write any AT command Please help me. When I tested the modem using this code:
/*

 This example tests to see if the modem of the
 GSM shield is working correctly. You do not need
 a SIM card for this example.

 Circuit:
 * GSM shield attached

 Created 12 Jun 2012
 by David del Peral
 modified 21 Nov 2012
 by Tom Igoe

 http://www.arduino.cc/en/Tutorial/GSMToolsTestModem

 This sample code is part of the public domain

 */

// libraries
#include <GSM.h>

// modem verification object
GSMModem modem;

// IMEI variable
String IMEI = "";

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

  // start modem test (reset and check response)
  Serial.print("Starting modem test...");
  if (modem.begin()) {
    Serial.println("modem.begin() succeeded");
  } else {
    Serial.println("ERROR, no modem answer.");
  }
}

void loop() {
  // get modem IMEI
  Serial.print("Checking IMEI...");
  IMEI = modem.getIMEI();

  // check IMEI response
  if (IMEI != NULL) {
    // show IMEI in serial monitor
    Serial.println("Modem's IMEI: " + IMEI);
    // reset modem to check booting:
    Serial.print("Resetting modem...");
    modem.begin();
    // get and check IMEI one more time
    if (modem.getIMEI() != NULL) {
      Serial.println("Modem is functoning properly");
    } else {
      Serial.println("Error: getIMEI() failed after modem.begin()");
    }
  } else {
    Serial.println("Error: Could not get IMEI");
  }
  // do nothing:
  while (true);
}

I am getting this output on Serial Monitor for 9600 baud rate:

Starting modem test...ERROR, no modem answer.
Checking IMEI...Modem's IMEI: 0
Resetting modem...Modem is functioning properly

The modem library does not communicate on pins 0 and 1. Check the reference library and tutorial. It should be pins 2 (RX) and 3 (TX). Reset is pin 7. The configuration may be found in GSM3IO.h. https://github.com/arduino/Arduino/blob/master/libraries/GSM/src/GSM3IO.h. See also https://www.arduino.cc/en/Main/ArduinoGSMShield


Turn on a light when there is an input I am using the pin 4 as an OUTPUT and pin 8 as an INPUT to turn on/off the light, but for some reason it is not working. Light is on all the time, but when I try to input something it gets brighter and doesn't turn off when I don't give anything to pin 8.

LED is connected to pin 4 with a 220 R, and the other side to GND. When pin 8 is connected to 5V pin then the light should come on, and off when I disconnect them.

Here is the code:

void setup()
{
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(8, INPUT);
}

void loop()
{
   bool on = digitalRead(8);
   if(on)
   {
     digitalWrite(4, HIGH);
   }
   else
   {
     digitalWrite(4, LOW);
   }
}

What am I doing wrong?

Use input with pullup on pin 8 and a button to ground (GND). See below:

const int ledPin = 4;
const int buttonPin = 8;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
   digitalWrite(ledPin, digitalRead(buttonPin));
}

Using the pin as input and disconnecting is not the same as GND. The pin is floating. By using the internal pullup resistor the pin is HIGH when the button is not connected to GND.


Arduino and Raspberry Pi - 5V/3.3V I2C This topic have been covered in various places, but I still think it hasn't been thoroughly explained anywhere. Doing google search on connecting Arduino to Raspberry Pi via i2c gives for example, this page.

While apparently this should work, there is a factual error there: on arduino side, pins used for i2c do have internal pull ups, and they are activated by Wire library.

Digging further, I've found following information:

  However, it turns out that these are weak (high-resistance) pull-ups;
  the Pi has strong pull-ups which dominate those on the Arduino, making
  direct connection safe.

What does safe mean? And how weaker are those pullups compared to raspberry pi ones?

Let's check:

rpi i2c pullup: 1K8
arduino i2c pullup: 20K-50K from datasheet (if I'm looking correctly, I'm using ATmega8), though the above page states 10K.

What can I make of those values? My (intuition rather than) basic knowledge hints me something along the lines:

If the i2c is floating, it means the 5V is connected with 3.3V and there are only those pullups along the way, so:

calculate voltage drop between 5 and 3.3: 1.7V.
calculate voltage drop across rpi pullup proportionally to voltage drop across arduino pullup:
1800 / 30000 = 0.06, meaning 0.102V across rpi pullup and 1.598 across arduino pullup, so the actual pulled up voltage is gonna be 3.3V + 0.102V = 5V - 1.598V = 3.402V?

Though I'm pretty sure I'm doing some terrible math here and someone is gonna have good laugh:)

So, my question is not whether it's safe (as it's been proved), but rather why is it safe considering the internet resources are inaccurate on this matter.

If you are sure to disable pull up on arduino side you are safe, as i2c works in open-drain mode, but the logic level "high" of arduino is about 3.2v, so it would be unstable.

Otherwise i2c pin of rasp are NOT 5v tolerant, so you must be sure the voltage on the bus does not exceed operative limit; as you calculated ~3.5v should be good on raspi, but please check on datasheet.

Also, you should check the total current on the bus, but as atmega resistor as so high,it should not pose a problem with raspi (but may give problem with passive i2c, that you can solve with a external pull up)


How to make I2C work on RS485? I'm trying to optimize the communication (minimize wires) on a project where I can control a motor and toggle some 230V devices by using RS485 and I2C.

On this project, I'm using an Arduino (Mega) for the control panel (buttons, potmeters, LED segment display (I2C) etc.).

I'm using the RS485 protocol (Modbus RTU) to control an inverter by using a MAX485 TTL converter. Now I also have a relay board (8 channel) to be able to toggle some lightning and sound devices. Both the inverter and the relay board, as well as the power supply, are located in another box, which I call the power box. Between the control panel and the power box will be a cable.

[Control Panel (with arduino mega)] <--cable--> [power box (with inverter, 8 channel relay board and 230V devices)]

I've got the following requirements:

The cable should have a minimum amount of wires (5V, Ground, 485+(A) and 485-(B) for sure)
The total length of the cable varies from 1 to 3 meters.
The signal should be reliable.

Now the relay board uses 8 channels. I've bought an I2C expander (PCF8574) to minimize that to 2 wires (SDA, SCL).

I'm thinking of using the existing 485 lines to control the inverter AND the relay board. So no additional wires are required. But theoretically I can't get it to work. So before I try to invent it.

Can I do I2C communication over the RS485 as well somehow by putting another converter?
If you recommand to just go with 6 wires (power, RS485 and I2C), how reliable is my I2C line going to be on 3 meters? What pull-up values do you recommand? (24AWG wire in mind, but also using a close-by LED segment display, so 2 I2C devices on different distances). I've read posts saying:

  The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz I2C bus.

Or can I use some other protocol/trick? Either minimalize wires, or boost signal by a I2C buffer? (recommendations?)

I2C and RS485 are such vastly different protocols with such vastly different signalling needs that they cannot share the same cables.

Further, I2C is not designed for connecting with long cables - it's meant for use between chips on a PCB.

The simplest "Arduino" solution would be to create a new RS485 device on your RS485 bus using another MAX485 and a small Arduino (micro, nano, etc) that responds to MODBUS RTU instructions and controls the relay board for you.


Arduino Interface with Serial device and LCD display I want to connect my Arduino UNO to a serial device that once powered displays signature numbers. I want to then display those numbers on an LCD display. I have my 16x2 LCD wired correctly and it works fine even when I use the SerialDisplay example code from the library.

My questions are:

Can I use a USB to TTL serial cable to connect the RX/TX pins of the serial device to the TX/RX pins of the arduino?
The two numbers are more than 16 characters. How can I cut the numbers down and then display the two numbers on two seperate lines of the LCD display?

Let me know if I should provide further details.

If the device is serial and you want to connect it to the Arduino serial port, why would you use a usb-to-serial converter?
For a serial to serial connection, you have to connect TX, RX and GND.
This is the bare minimum for bidirectional communication, if your device is really read only, you can use just the TX and GND.
it depends how you receive data from your "serial device" - btw, what is it? If the data comes as either ascii or individual characters, then it's easy: treat them as strings and display them separately. If the numbers arrive in binary format, you have to perform the conversion to string.

Questions like this should have attached at least a snippet, if not all, of code.


How to connect capacitive touch sensor to Arduino? The capacitive touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my Arduino Micro, correct?

Also, I need to power 2 of these capacitive touch sensors along with an IMU. How do you power multiple sensors on the Arduino Micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

The capacitative touch sensor has 3 pinouts: Vin, GND, and OUT and emits an active high signal when the pad is touched. I should be routing the OUT pin to any one of the digital input pins on my arduino micro, correct?

Probably, yes. Without more details about what the sensor is we can't really comment.

  Also, I need to power 2 of these capacitative touch sensors along with an IMU. How do you power multiple sensors on the arduino micro? There is only one GND pin and one 5 V pin. I would prefer if it could be done without a breadboard as this entire setup will be placed in a stylus.

You can plug as many (within reason) items into the +5V and GND pins as you like. You can twist wires together, use screw terminal blocks, breadboard, solder, whatever you like, to connect the wires together to a single wire that goes to the pin.


Creating Arduino library file I need to create a library file for Arduino. While surfing the Internet, it shows me to use C, C++. Is a C++/C compiler mandatory to create library files in Arduino? Or we can use the Arduino IDE to create library files?

The Arduino IDE has a compiler, and will in the end compile the library with whatever .ino script you'll write. But you don't need any compiler to write a library. All you need is a text editor, and produce .cpp and .h files.

However when you test the library, you'll have to use the Arduino IDE to compile it.


Show images on a monitor using Arduino via Wifi Consider a computer monitor hanging on a wall. Next to it is an Arduino Uno with a wifi. Is it possible to create something like this? Using wifi it should be possible to send data (images) to Arduino. This will be output to a monitor, like an image gallery. Images can be any type (videos included).

Is it possible? Where does one start?

Thank you.

I have somewhere in my stash a shield that enables an Arduino to overlay graphics on the screen. But it is kinda crude and low-res. What you're trying to achieve is definitely not for Arduino, it is way underpowered.

You'd better look into doing this with something like a Raspberry Pi.


Code runs different on USB vs Battery I have two Arduino, one is to handle the Bluetooth communication and send a signal to the other Arduino, and the other to interpret the signal and display or hide an image on the E-ink display.

It work just fine when they both are connected through the USB. But when I connect a 9V battery to the Arduino running the E-ink, instead of the USB, the image is displayed and cleared (looping), as if the IF ELSE conditions are not there.

I have tested if it actually runs the method by adding delay to the showImg()-method, and that seems to work.

I have also tested with connecting the USB cable to the E-ink Arduino to a 5V charger, and the case is the same.

Image:

Bluetooth code:

int ledPin = 13;
int state = 0;
int flag = 0;

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

 Serial.begin(9600);
}

void loop() {

 if(Serial.available() > 0){
 state = Serial.read();
 flag=0;
 }

 if (state == '2') {
 digitalWrite(ledPin, LOW);
 if(flag == 0){
 Serial.println("Screen: off");
 flag = 1;
 }
 }

 else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 if(flag == 0){
 Serial.println("Screen: on");
 flag = 1;
 }
 }
}

E-ink code:

#include <epd.h>

int displayed = 0;
int val = 0;

void showImg(void)
{
  Serial.print("showImg");
  displayed = 1;
  //epd_clear();
  epd_disp_bitmap("PIC9.bmp", 0, 100);

  epd_udpate();
  //delay(10000);
}

void clearImg(void){
  Serial.print("clearImg");
  displayed = 0;
  epd_clear();
  epd_udpate();

}

void setup(void)
{
  //Serial.begin(9600);
  epd_init();
  epd_wakeup();
  epd_set_memory(MEM_TF);
  pinMode(7, INPUT);

}

void loop(void)
{
  val = digitalRead(7);

  if(val == 1){

    if(displayed == 0){
      showImg();
    }

  }else {

    if(displayed == 1){
      clearImg();
    }
  }
  //Serial.println(val);
  //delay(3000);
}

I am a beginner when it comes to Arduino, So I hope someone can give me some hints to what may be wrong.

Thanks!

The USB provides the one thing that is missing from your diagram there: the common ground.

The GND pins of the two boards must be connected together. By using USB the USB becomes that connection. As soon as you use batteries there is no connection, so no communication happens.


Where does arduino IDE store the latest board selection? I'm building a tool to help me automate my uploading process. How do I know where Arduino stores the current preferences - which board, which com port, what serial speed?

If devs are familiar with using multiple boards in the same system ithey'd know it would be really handy to be able to change that

It is stored in preferences.txt in your Arduino data folder.

You can find more about that file, including where to find it, here.

Some of the keys you may be interested in are:

board=uno
serial.port=COM3
serial.debug_rate=115200

However maybe for your workflow the Arduino IDE isn't the best tool for the job.  You may consider arduino-builder, which is the back-end that the Arduino IDE uses to do the actual compiling, or maybe another IDE entirely, such as PlatformIO or UECIDE.


Merging of two functions This is my Arduino code that checks the water Level of two different water reservoirs via 2 water Level Sensors A and B:

#define Water_Level_A 5;
#define Water_Level_B 6;

boolean Water_Level_Check_A(){
boolean Result = digitalRead(Water_Level_A);
return Result;
}
boolean Water_Level_Check_B(){
boolean Result = digitalRead(Water_Level_B);
return Result;
}

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

void loop() {
if (Water_Level_Check_A() == LOW){
--> Water Pump A
}
if Water_Level_Check_B() == LOW{
--> Water Pump B
}

What's the best way to simplify this code so that I only need one Water_Level_Check function so that the distinction between A and B and Water_Level_A and Water_Level_B is made within the function and the loop part looks like this:

void loop() {
if (Water_Level_Check_(A) == LOW){
--> Water Pump A
}
if Water_Level_Check_(B) == LOW{
--> Water Pump B
}

Functions like

boolean Water_Level_Check_A(){
   boolean Result = digitalRead(Water_Level_A);
   return Result;
}

Are really overcomplicated. You're just calling one function and returning that value, so it can be simplified to

boolean Water_Level_Check_A(){
   return digitalRead(Water_Level_A);
}

Or just the expression

digitalRead(Water_Level_A)

whenever you need it.

So all you're doing is calling digitalRead() on a pin number and check if the result is low. If you really want to move this to a different function then you could give it the pin number argument and directly invert the result so that a true from this function means that some action needs to be done.

boolean Water_Level_Check(int sensorPin){
   return !digitalRead(sensorPin);
}

And then call it as

void loop() {
   if (Water_Level_Check(Water_Level_A)){
       //--> Water Pump A
   }
   if (Water_Level_Check(Water_Level_B )){
       //--> Water Pump B
   }
}


Connect Arduino with fischertechnik TX Controller Is it possible to cinnect the Arduino with a fischertechnik TX Controller? Maybe with I²C, but i want to use I²C for something else on the arduino. So are there multiple I²C Ports on the Arduino (I haven't got one yet)?

As described in the Wire library that brings supports I²C support to Arduino, except for the DUE that has 2 pairs of pins for 2 I²C buses, other Arduino boards support one I²C connection.

However, this is when you want to use hardware facilities of ATMEL chips that these limitations apply; there is a software I²C library exists that allows using other pins for I²C. One major drawback, though, is that it is very slow; not sure if this is a problem in your situation.

One important thing though: the principle of I²C is to be able to plug several slave devices (more than 100) to one master device. In general, Arduino is the master device, but the Wire library can be used as master or slave. Wouldn't that fit your requirements?

In this situation, you could just use the same I²C bus for everything, including connection to Fischertechnik TX controller.