Evaluating delay for Xbee I will explain my task in a simplified way. I'm communicating among 3 Xbee's.

The attached code is for the sender Xbee. This Xbee actually sends multiple values of value1 (here for simplification I assigned it to constant value 10). For finding the value1 it does some other calculations as well and then assigns it.

But I find that if I reduce or remove the delay(100) I end up receiving improper values. I guess delay gives a buffer time for data transmission but my question is how to do I calculate the minimum delay or how can justify that this is the delay needed ?

I hope you can understand my question. If not please comment I will give some more pertinent details.

  // Sender Xbee
    void setup()
    {
    Serial.begin(9600);
    }
    void loop()
    {
    int value1 = 10; // some hardcoded values to send
    Serial.print('H'); // unique header to identify start of message
    Serial.print(value1,DEC);
    Serial.print(","); // note that a comma is sent after the last field
    Serial.print('\n'); // send a cr/lf
    delay(100);
    }

Based on my experience with Xbee, I would say the limit is 50ms as Xbee can do the lowest sampling rate of 50ms.


LED Control through bluetooth I have an Android app that sends data to the arduino HC-06. It is however giving me colors i did not send to it. Eg. Red in place of green, white in place of red etc.
Here is a snippet of my android code that sends the data via bluetooth

 public void onColorChanged(int color) {
    BluetoothV2 bluetooth = new BluetoothV2();
    int r,g,b;
    r = Color.red(color);
    g = Color.green(color);
    b = Color.blue(color);
    bluetooth.Message(r+","+g+","+b);
 }

Here is a snippet of my arduino code

void loop() {

if(Serial.available()>0){

while(Serial.available()>0){
   char inChar = (char)Serial.read();
   inputString += inChar;
}
   int red = Serial.parseInt();
   int green = Serial.parseInt();
   int blue = Serial.parseInt();
   color(red,green,blue);
   inputString = "";
   Serial.println("R:"&& red &&"G:"&& green &&"B:"&& blue);
  }
}

void color (unsigned char red, unsigned char green, unsigned char blue){
   analogWrite(redPin, 255-red);
   analogWrite(greenPin, 255-green);
   analogWrite(bluePin, 255-blue);
}

Terminal data

               2,,,,,,,,,,,,,2,,5,,,,,,,,,,,,,,,,,,,,,,,,,02725,1,502725,,,,,,,,,02514,5,602515     ,5,3,,,,,025

Is the problem how i get the data though Serial.read()? Or what am i missing

int firstcomma = inputString.indexOf(',');
int secondcomma = inputString.indexOf(',',firstcomma+1);
String r = inputString.substring(0,firstcomma);
String g = inputString.substring(firstcomma+1,secondcomma);
String b =  inputString.substring(secondcomma+1);
red = r.toInt();
green = g.toInt();
blue = b.toInt();
Serial.print("R");
Serial.print(red);
Serial.print("G");
Serial.print(green);
Serial.print("B");
Serial.println(blue);

This solved my problems.


Am not able to call C++ function pointers from inline assembly Due to some curiosity, I was trying to use some assembly with my Arduino MEGA 2560.
I am not able to invoke a function from a c++ function pointer array.
When I uncomment the call function, func_a runs. However, when I almost reproduce the assembly, it doesnt work.
Example:
extern "C" void __attribute__ ((used, noinline, noreturn)) func_a();

typedef void (*volatile func_ptr)();

func_ptr tasks[MAX_TASKS] = {&func_a};

extern "C"
void __attribute__ ((used, noinline)) call(func_ptr *ptr) {
    (*ptr)();
}

void __attribute__ ((noreturn, used)) setup() {

    // call(tasks);

    asm volatile (
    "lds r26, (tasks)\n"
    "lds r27, (tasks + 1)\n"

    "ld r30, X+\n"
    "ld r31, X\n"

    "eijmp\n"
    );
}

Generated assembly recovered from avr-objdump
000001c6 <setup>:
 1c6:   a0 91 00 02     lds r26, 0x0200 ; 0x800200 <tasks>
 1ca:   b0 91 01 02     lds r27, 0x0201 ; 0x800201 <tasks+0x1>
 1ce:   ed 91           ld  r30, X+
 1d0:   fc 91           ld  r31, X
 1d2:   19 94           eijmp
 1d4:   08 95           ret

000001d6 <call>:
 1d6:   dc 01           movw    r26, r24
 1d8:   ed 91           ld  r30, X+
 1da:   fc 91           ld  r31, X
 1dc:   19 94           eijmp

An specific resources I should refer for things like this?
If it matters, I'm using platformio on a linux system for compilation.

It seems you got confused by the pointer indirections, which is
confounded by the implicit indirections made by the compiler.
Here:
extern "C"
void __attribute__ ((used, noinline)) call(func_ptr *ptr) {
    (*ptr)();
}

The parameter ptr is not a function pointer: it's a pointer to a
function pointer. You have to dereference it twice in order to get the
function: (**ptr)();. Note that the compiler implicitly dereferences a
function pointer if you call it like a function: that's why you get no
error by explicitly dereferencing the pointer only once. In the
generated assembly, the lines
ld  r30, X+
ld  r31, X

dereference ptr in order to get the address of the function to call.
You probably wanted to write
extern "C"
void __attribute__ ((used, noinline)) call(func_ptr ptr) {
    ptr();
}

And then use it as:
call(tasks[0]);

If you just call(tasks), the array identifier decays to pointer, and
the compiler handles this as a shortcut for call(&tasks[0]);, which
turns out to be compatible with your initial implementation of call().
Now, in your inline assembly you have
lds r26, (tasks)
lds r27, (tasks + 1)

The assembly treats tasks as a symbol representing the address of
the tasks array. The linker replaces those symbols by the actual
address (0x0200). Those instructions read the RAM at this and the
following address. These slots of RAM hold the first item of the array,
namely &func_a. So now you have this address in the X register pair.
No need to read RAM again: you can movw r30, r26 and do the indirect
jump. Or, better yet, load into Z to begin with:
lds r30, (tasks)
lds r31, (tasks + 1)
eijmp

See also Majenko's answer: here I am assuming EIND is somehow
correctly set up to begin with. On an Uno, you would just use ijmp
instead of eijmp and not worry about EIND.


Does Arduino sent output to TX pinout? I am beginner at Arduino,i tried to read as much as i can but i am not sure if i am doing good.I would like to send a specific code for a (non PC) device through the TX pinout when i push the button which is wired to the Pin 2.I have writtem this small code to check it:

int buttonUPpin = 2;
int UpinStatus=LOW;

void setup() {
  Serial.begin(9600);
  // put your setup code here, to run once:
pinMode(buttonUPpin, INPUT_PULLUP);
digitalWrite(buttonUPpin,HIGH);

}

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

UpinStatus=digitalRead(buttonUPpin);

if(LOW==UpinStatus)
{
Serial.print('A');
digitalWrite(1,LOW);

}

}

When i push the button i can see at serial monitor the 'A' character but i am not sure if this character was also sent out to the TX pinout since the TX led is not blinking only the RX led.

You haven't set pinMode for pin 1 and using pin 1 will interfere with the serial monitor (never use 0 and 1).

#define buttonUPpin = 2;
#define LedPin = 3;
int UpinStatus = LOW;

void setup()
{
    Serial.begin(9600);
    pinMode(buttonUPpin, INPUT_PULLUP);
    pinMode(LedPin, OUTPUT);
    // digitalWrite(buttonUPpin,HIGH);  // Don't think this is right

}

void loop()
{
    UpinStatus=digitalRead(buttonUPpin);
    if(LOW==UpinStatus)
    {
       Serial.print('A');
       digitalWrite(LedPin, LOW);  // Not sure if High or Low depends on you circuit
    }
}


Using Arduino to learn AVR programming I want to learn AVR C programming instead of arduino programming. I have an arduino UNO board and few Atmega328 chips that I bought, and Atmel studio for programming. Can I use Arduino Uno board as programmer to flash the chips from Atmel Studio? Or any other alternatives?

If your chips have a bootloader already installed in them, you can use any USB -> Serial cable (FTDI cable) to program them in-circuit on their Rx/Tx pins. If not, you can use the Uno to program a boot loader into them (one time) and program them with the cable from then on.

To use standard C, you can use the bare chips or the UNO. You'll want a different environment than the Arduino IDE, though. That can be anything from an editor, the the gnu compiler tools run from a command line, to almost any other IDE. A number of people, myself included, use the Eclipse IDE with an AVR plug-in and do almost everything from writing the code to programming the AVR from within it. (I say 'almost' only because I personally prefer a full-blown programming editor, run outside of the IDE, for initial creation of sizeable projects or major edits and rewrites. That isn't necessary, though).


Gravity fan does not work when powered by 3.3V ESP8266 The gravity fan has 3 pins. I connected one pin to the ground, one pin to the digital pin numbered 2 on ESP8266. I uploaded this code but the fan doesn't run at all. The fan supposedly uses a 5V power supply but the ESP8266 only supplies 3.3V. Could this be the problem?

void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, HIGH);
}

The ESP can only supply 12 milliamperes of current. The fan most likely uses a whole lot more. You could for example uses a transistor to turn on the fan.


What are the better options to the basic Arduino Serial Plotter? Arduino Serial Plotter does not allow analysis or saving of data. What are the best serial data graphing software (preferably free, but i don't mind if it's paid as long as it's better than the bare-bones Arduino Serial Plotter)?

It should work well with Arduino
It should allow plotting several variables on the same graph
Allow exporting data to CSV so i can show it in Excel.

Custom devices require custom solutions.

I suggest using Python (don't be scared).

This tutorial shows us how to read data from serial and save it to .csv file. You don't have to use a file. For example you can modify it to use an in memory list, and save just values from last 30 seconds. You can also read several values, and not just one.

import serial
import time
import csv

ser = serial.Serial('/dev/ttyACM0')
ser.flushInput()

while True:
    try:
        ser_bytes = ser.readline()
        decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
        print(decoded_bytes)
        with open("test_data.csv","a") as f:
            writer = csv.writer(f,delimiter=",")
            writer.writerow([time.time(),decoded_bytes])
    except:
        print("Keyboard Interrupt")
        break

This tutorial (and this one) shows you how very quickly to show a sophisticated plot of the data you collected. You can even make a plot that shows several graphs and updates in real time.

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

Don't be scared it's not black magic. It just takes few days to understand how things work.


Why NRF24L01+ pipe has 5 byte address I am studying NRF24L01+ module. I see, that only 6 receivers can be connected with the transmitter, via their unique pipes. What I can’t get is why the pipe id (address) has 5 long bytes.

As to me,1 byte would be much more than enough.
What is the purpose in 5-byte address in 5 bidirectional communications?

5 bytes = more than 1 million million unique addresses, although not all addresses (as the nRF24L01 datasheet points out) are advised, for instance because they mimic the nRF's preamble packet.

So what is the purpose of addresses?
The purpose is to ensure that radio transmissions are received at the intended radio module.  Consider a radio network where you have 1 transmitter (TX) and 3 receivers (RXs) within range of one another, all using the same radio frequency (channel).  Now all receivers will detect a message sent by the transmitter, but only act upon it, such as raising an interrupt flag, it if the TX and RX addresses match.  To avoid chaotic communication, failed packets or on-air collisions you need each receiver to have a unique address.  Consider these like a postal address.  You should have an intuition of what would happen to your mail if both you and your neighbor had the exact same address.  Since the 2.4 GHz band can be extremely busy in public places with WiFi and Bluetooth traffic (which as an aside, Bluetooth is based on the nRF protocol), having 40 address bits seems quite sensible, as the probability of matching addresses by chance is almost zero.

So what are pipes?
If you read the nRF datasheet, you will see that in TX mode the radio can only send on using one address.  In RX mode, the radio will listen for messages on up to 6 different addresses.  Why 6?  This is likely arbitrary - a balance between register memory allocation, most probable number of nRF modules being used simultaneously and the likelihood of more efficient network topologies (such as star/tree networks) that do not require huge numbers of pipes.  A pipe represents one of these 6 addresses that a radio can receive the message and send and an ACK packet if requested.  That's all.

I hope this answer clears any confusion you had between nRF addresses and pipes.


Saving byte array in PROGMEM instead of SRAM For an ethernet project I do, I need to store the Ethernet Shield's MAC address.
I store it like that:

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

That works OK, but in my project I need all the SRAM available, so every byte of memory is important. I've used the F() macro and PROGMEM everywhere, but I couldn't manage to store the MAC byte array in the PROGMEM.

How can I store it in PROGMEM? Is it even possible?

See Putting constant data into program memory (PROGMEM) for tips about putting stuff into PROGMEM. However personally I wouldn't get too excited about saving 6 bytes.

Example code:

Declare data globally:

const byte mac [6] PROGMEM = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

Get a copy for use into a temporary variable:

  char foo [6];
  memcpy_P (foo, mac, sizeof foo);


How do I use a servo in an interrupt? I am working on a small circuit now where I increment the rotation of a servo motor and at the same time blink a LED.

I have used all methods I know to do it but still it does not work or it blinks and then the servo start working but never both at the same time.
This is what i am basically working with:

  for(position=0;position<=90;position=position+5){
    digitalWrite(led_pin,HIGH);
    delay(200);
    digitalWrite(led_pin,LOW);
    delay(200);
    servoBar.write(position);
    delay(15);
  }

But it blinks once and then it stops and the servo start working right after that.

I know I must not use delays in interrupts. I am using a function that I can but just to show you what I am working with.

The problem is that the delay routine is blocking. It stops operation and blocks other things from happening. Have a look at the Blink without delay example in the example tab. (also linked below)
https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

What you need to do is to not block. Call the time checker often and check if the time you want delayed has run out. The perform the action needed to be done at that time.

This is a more sophisticated way to deal with timed events. Also look at this
Demonstration code for several things at the same time.
https://forum.arduino.cc/index.php?topic=223286.0

Have fun learning. :)


Mass testing of Arduinos I am using Arduino for an IoT class (40 students).  I have set up a test program to check all sensors and actuators used in the class (we need to recycle for next semester). However, I would also like to check the Arduino's themselves (and also NodeMCU´s) in case some of the units have been broken.  I have an idea of testing input/output of each pin to make sure its working - using LEDs and buttons, but if anyone has some ideas to improve testing, it would be great to hear from you. I guess I am not the only one reusing IoT components from one semester to another.  It would be great to hear from other instructors in the IoT field.
Best regards,
Lasse Berntzen,
University of South-Eastern Norway,
lasse.berntzen@usn.no

A complete test would obviously be something fairly complex, and would
probably require building some sort of rig. You can, however, perform a
minimal test that checks for common failure modes, without connecting
any extra hardware.
I assume the pin I/O stages are the easiest thing to break. You can then
check that, when you read a pin that is set to OUTPUT, you get the
value that the pin is supposed to be outputting. You can leverage the
stray capacitances of floating pins to test them as inputs: the
capacitance should make the pin “remember” its previous output value for
some time, and that time should be really short if the internal pull-up
is enabled.
The following program tests pins 2–13 and A0–A5 of an Uno. It checks
that:

a pin set to OUPUT LOW reads LOW
a pin set to OUPUT HIGH reads HIGH
a pin switched from OUPUT HIGH to INPUT reads HIGH
a pin switched from OUPUT LOW to INPUT reads LOW
a pin switched from OUPUT LOW to INPUT_PULLUP reads LOW, then
switches to HIGH less than a microsecond later

Pins 0 and 1 are not tested, as they are connected to the serial port.
On the other hand, if you can upload a sketch, you know those pins work
at least as RX/TX.
Note that the program uses direct port access, as the Arduino functions
for accessing the pins are too slow for this kind of tests. If all
works, the program prints “All tests passed.”. Otherwise specific error
messages are printed, followed by “Some tests failed.”
#include <avr/cpufunc.h>
#include <util/delay.h>

int failures = 0;

static void log_failure(char port_name, const char * reason)
{
    failures++;
    Serial.print("FAIL: Port ");
    Serial.print(port_name);
    Serial.print(", read ");
    Serial.println(reason);
}

static inline __attribute__((always_inline))
void test_port(const char port_name, uint8_t mask,
    volatile uint8_t *pin, volatile uint8_t *ddr, volatile uint8_t *port)
{
    *port = 0;
    *ddr = mask;   // OUTPUT LOW
    _NOP();
    if ((*pin & mask) != 0)
        log_failure(port_name, "OUTPUT LOW");
    *port = mask;  // OUTPUT HIGH
    _NOP();
    if ((*pin & mask) != mask)
        log_failure(port_name, "OUTPUT HIGH");
    *ddr = 0;      // INPUT_PULLUP
    *port = 0;     // INPUT -> HIGH
    _NOP();
    if ((*pin & mask) != mask)
        log_failure(port_name, "INPUT HIGH");
    *ddr = mask;   // OUTPUT LOW
    *ddr = 0;      // INPUT -> LOW
    _NOP();
    if ((*pin & mask) != 0)
        log_failure(port_name, "INPUT LOW");
    *port = mask;  // INPUT_PULLUP
    _NOP();
    uint8_t r1 = *pin;
    _delay_us(1);
    uint8_t r2 = *pin;
    if ((r1 & mask) != 0 || (r2 & mask) != mask)
        log_failure(port_name, "INPUT_PULLUP");
}

void setup()
{
    Serial.begin(9600);
    TIMSK0 &= ~_BV(TOIE0);  // disable timer interrupt

    test_port('B', 0x3f, &PINB, &DDRB, &PORTB);  // PB0..PB5
    test_port('C', 0x3f, &PINC, &DDRC, &PORTC);  // PC0..PC5
    test_port('D', 0xfc, &PIND, &DDRD, &PORTD);  // PD2..PD7

    if (failures == 0)
        Serial.println("All tests passed.");
    else
        Serial.println("Some tests failed.");
}

void loop(){}

As an extension, analog inputs could be tested in a manner similar to
test 5: if the analog sampling is done at the right time, you can
get a reading that is somewhere mid-range.


Where can I find a better pinout diagram for "Arduino Ethernet" board? I'm looking for a complete pinout of the Arduino Ethernet R3.
I've found one here which is low quality, and seems not complete (where are the digital I/O pins?).

BTW, it was not a good idea for Arduino to name this board "Arduino Ethernet", as this is pretty useless for searching online :-(

The formal Arduino.cc website mentions, somewhat obscurely, that the Arduino Ethernet is pin compatible with Arduino Uno:

  The Revision 3 of the board introduces the standardized 1.0 pinout

Except for pins 10-13:

  Pins 10, 11, 12 and 13 are reserved for interfacing with the Ethernet
  module and should not be used otherwise. This reduces the number of
  available pins to 9, with 4 available as PWM outputs.

The other difference is the onboard LED is connected to pin 9 rather than the Uno's pin 13:

  On most other arduino boards, this LED is found on pin 13. It is on pin 9 on the Ethernet board because pin 13 is used as part of the SPI connection.

You can use any Arduino Uno pinout diagram as a reference, the one you have found seems to be pretty elaborated.


How to mimic soft-power button in inexpensive toys & flashlights? My kids have a few odd inexpensive toys with a soft push-button that will turn on the toy, and subsequent pushes change the toy's mode of operation in some fashon.  A flashlight comes to mind, where the button is pushed once and it turns on, push again and it blinks, and a 3rd time and the light turns off.

I've looked inside one of these flashlights, and there's a small blob covering some IC, what looks to be a diode, and the usual connections for the batteries and lights.

How do these circuits "work" without immediately draining the batteries?  I'm looking to mimic this behaviour on a battery powered arduino Uno (or possibly Pro Mini).

What comes to mind is that the button is on an interrupt line, which wakes the system up from some sleep state..  when the button cycles around to an "off" state, the system goes back to sleep.

I have a lengthy write-up about saving power at Power saving techniques for microprocessors.

One of the sample sketches on that page (Sketch J) does what you ask:

#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precaution while we are doing other things
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  digitalWrite (2, HIGH);  // enable pull-up
  }  // end of setup

void loop ()
{

  pinMode (LED, OUTPUT);
  digitalWrite (LED, HIGH);
  delay (50);
  digitalWrite (LED, LOW);
  delay (50);
  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes low
  attachInterrupt (0, wake, FALLING);

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

According to when I tested that, it used 0.116 µA when asleep (116 nA). That is well below the rate at which batteries self-discharge.

Basically that code does what you described. It sleeps, when pin D2 goes low it wakes and flashes an LED.

I should point out though that any "development board" Arduino with a voltage regulator, USB interface, and power LED on it will consume considerably more power because of the current drain they consume.

For low-power applications you need the bare chip (with appropriate supporting circuitry, like decoupling capacitors).


How can I use the NRF24L01 modules without a library? The datasheet is too intimidating for me, and I dont want to use the libraries available. Hence, I am looking for some clarity on this matter.

You can use the NRF24L01 by writing the functionality that is currently within a library yourself (and strip of parts you do not use).

However, for this, you need to understand the library, and therefore high likely the datasheet too.

You also can start without looking at a library, but your only documentation source is the datasheet itself.

A NRF24L01 has a lot of possibilities (that is why the datasheet is so extensive), so writing the functionality yourself might be causing more time.


Attiny85 not recognized at windows startup I'm using an Attiny85 to interact with a computer using an USB connection, and everything works fine except when I restart my computer and the Attiny85 is connected. When Windows end to boot up the Attiny85 isnt't recognized, and on Device Manager it's listed like this:

If I unplug the Attiny85 and then plug it back in, everything works just fine.

Is there any to make it detectable at boot time without having to always unplug/plug it?

EDIT:

More details:

I'm using this board

and libusb-win32 as the USB driver

I don't have enough reputations to make a comment so I will drop my 2 cents here.

There should be more elegant way to do this but as a fast solution I would recommend two things:

If it is possible, add a push button to your board to reset the MCU manually when the PC is booted up.
You can make a software reset after powering up the board by a certain time (e.g. 10 sec) by using watchdog timer.


Range of Offset Value in pH sensor module? In finding the pH value of a liquid/Soil, what is the range of Offset voltage value that I can use in my code?

Using / calibrating pH sensor module

I considered the above link as a reference. But I didn't come to know the range of Offset Value...

Here is the logic below to find the value of pH right...

avgValue = 0;
for (int i=2;i<8;i++)       // take the average value of 6 center sample
avgValue+=buf[i];

float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
phValue=3.5*phValue+Offset;

What is the range of Offset value can I use in the above/my code?

Thanks in Advance

When converting real world sensor measurements into usable data there are several issues to consider:

Noise from any number of sources such as (unavoidable?) long cables and power supplies to name two.  Consider using exponential averaging to minimize the effects of noise.  If the noise if predictable consider sampling only when the noise is absent.
Slope of the data is important when converting to known scales.  For example the slop of the resistance of a thermistor verses heat may not have the same slope as the temperature in Celsius verses heat.  Simply multiply by the appropriate constant to correct for slope error.
After you correct for slope the values may still not be correct.  When all values are equally less or more then the expected values an offset is required.  Simply add or subtract the appropriate constant to correct for offset error.
Linearity is often corrected using lookup tables.  Linearity is a measure of how closely the sensor tracks the physical value being measured.  For example, after slope and offset corrections, a thermistor measurement may appeared curved when compared to the actual temperature in Celsius.  For this final correction the sensor measured value is used to index into a lookup table which returns a correction value.  Interpolation is used to control the size of the lookup table when space is a consideration.


Problems reading I2C sensor when using a Xbee module I'm developing a project where I can control a RC boat with GPS and a magnetometer. How ever, I was developing everything connected to my computer and worked pretty well. When I was going to make some test with a battery and a couple of Xbee's (PC and "Arduino"), the magnetometer signal was not updating. So, I read the first value and continued to transmit the same value (thing that never happened on computer). Has someone had the same issue before? How can I solve this? Oh, one thing. The GPS and magnetometer comes in the same module, and I'm having no problems with GPS coordinates. And even if I power de MCU with my computer and transmitting with the Xbee's it doesn't work either. Seems like a communication problem.

Hardware used:

GPS Module + Compass

ATmega1284P

UPDATE:

I want to share also the code I'm using for the I2C reading.

#include <Wire.h> //I2C Arduino Library
#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  Wire.endTransmission();
}

 void loop(){

  int x,y,z; //triple axis data

  //Tell the HMC5883L where to begin reading data
  Wire.beginTransmission(address);
  Wire.send(0x03); //select register 3, X MSB register
  Wire.endTransmission();

 //Read data from each axis, 2 registers per axis
  Wire.requestFrom(address, 6);
  if(6<=Wire.available()){
    x = Wire.receive()<<8; //X msb
    x |= Wire.receive(); //X lsb
    z = Wire.receive()<<8; //Z msb
    z |= Wire.receive(); //Z lsb
    y = Wire.receive()<<8; //Y msb
    y |= Wire.receive(); //Y lsb
  }

  //Print out values of each axis
  Serial.print("x: ");
  Serial.print(x);
  Serial.print("  y: ");
  Serial.print(y);
  Serial.print("  z: ");
  Serial.println(z);

}

I have solved the problem by adding a delay just before I select the continuous measurement mode.

void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  delay(100);
  Wire.endTransmission();
}


TLC5917 Electrical Characteristics I am using an Arduino Uno to communicate over SPI to 3 cascaded TLC5917 chips corresponding to the Red, Green and Blue rows of an RGB LED Matrix.
I am using direct output IO from the Arduino to power the columns.

Now I intend to use multiplexing to avoid drawing too much current at once, although it could still potentially be quite alot (3 x 8 x 20ma).

I have managed to display a full white screen using multiplexing with quite a high brightness, however this should not be possible to my knowledge.

Looking at the data sheet I found that at both at 3V and 5V the Output Voltage is rated at Vdd - 0.4 for Voh (Voltage High Level Output).
This means that at 5V the minimum output voltage should be 4.6V and at 3V it should be 2.6V.

Disabling multiplexing and simply writing to the registers and columns, and then measuring the voltage shows 2.5V, 2.8V and 1.8V for different colors.
This contradicts the data sheet.

The circuit contains no resistors except from GND to REXT using a 680Ohm Resistor.
The Arduino is powered over USB.

(http://www.ti.com/lit/ds/symlink/tlc5917.pdf)

Why is the Voltage so low, should it not be higher given the data sheet?
Am i reading the correct attribute?
How can my Arduino manage to drive so many LEDs (albeit through LED Drivers)?

What can I do to make this circuit more electronically safe and stable?

The concepts of HIGH and LOW, and thus the voltages associated with those concepts, apply only to logic signals.

LED drivers are not logic signals - they are constant current sinks. The voltages you are measuring are the forward voltages of the LEDs.


Checking a jumper between two pins on Arduino I'm in the process of making a tag scanner (which transfers the tag ID to the computer), and I figured I'd use an Arduino Micro for that and just use the keyboard function on it to save myself a whole lot of hassle. From what I've read, however, having the keyboard open all the time can make it tricky to program it.

I figured my solution would be to use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard. That way I should be able to put the jumper on if I need to program it, and leave it off if I just want it to run.

Unfortunately, I've never really done anything like this before, and I don't really want to just start plugging things around and run the risk of damaging my board. I've read around a bit, but I figured I wanted to bounce my ideas off of someone before I try it.

First, would you recommend a different approach? I did see a question that used the internal pullup resistor to check if a jumper connected it to ground, but since I only want to make this check once, is that a good route to go?

Secondly, if I connect it between two pins, am I correct in thinking I'd need a resistor between them (the Arduino website suggested 470ohm to 1kohm when connecting to other devices, so I'm guessing this would be a good number)? How would I set the pins up to make this work; should I put one pin as output and the other as input, and just read the input pin (after which I'd simply turn the output pin off), or would I need to add additional connections?

Thirdly, since this will use the USB port on the Arduino that is used to program it, is there a way to wipe the code from the Arduino in case of Serious Bugs, or is it possible to "brick" the board by tying up the USB permanently? I mean, I'll definitely make use of the Serial connection to test the output (and also to test the above jumper), so I think the odds are small enough to try it anyway, but... better safe than sorry?

First of all, welcome here. Usually questions should contain, well, only one question ;)

In any case the usual circuit with buttons (a jumper can be seen as a button) are these ones:

simulate this circuit – Schematic created using CircuitLab

In the left case, usually the arduino pin is "pulled down" by the resistor when the button is not pressed (or the jumper is not present), so it will read "LOW". When the button is pressed, the arduino will see a "HIGH" value, since the button is "stronger" than the resistor and is able to force its value. The resistor is called "pull-down".

In the right case, the voltages are inverted. You read a "HIGH" value when the button is not pressed, and a "LOW" value when it is. The resistor is called "pull-up" for obvious reasons.

The resistor is needed because you need to have a "weak" component that can pull the arduino pin to a voltage value; it needs to be weak, so the button can override it.

The arduino, however, as a very common feature, called "internal weak pull-up" on the digital pins. This means that internally there is already the possibility to enable a weak resistor pulling the voltage to +5V. For this reason, what you need is to just connect the jumper to ground and read it.

simulate this circuit

You will need, in your setup, to set the pin as INPUT_PULLUP, and then check the value you read:

const byte jumperPin = 2;

void setup() {
  pinMode(jumperPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(jumperPin) == LOW)
  {
    // Jumper is inserted
  }
  else
  {
    // Jumper is not inserted
  }
}

This is what the DigitalInputPullup example is for...

Regarding your other question, there is a connector on every board named ICSP (of if there isn't, you should have access to the ICSP pins from somewhere else). This connector is used to flash the bootloader again (or to flash a program with an external programmer). You will need a atmel programmer to restore the original bootloader and "unbrick" it.

Luckily any arduino board can be used for this task; you will just need to download on another board the sketch ArduinoISP (already included in Arduino IDE) and you can use it to flash. There is plenty of tutorials online to do it. So to "unbrick" it you will just need another arduino board


Two things:

You have a comma missing: 1260,12601635,1635,
You have an extra comma: 1180,1180,,1255,1255

If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.


What causes a "blip" in LED brightness with sequence of 254, 255, 0, 1 brightness values? I am seeing a "blip" in LED brightness when trying to fade a red LED on an Arduino UNO.

This code demonstrates the "blip" seen in brightness right after a 254, 255, 0 sequence.  When the brightness is then set to 1, the actual brightness is much higher for a short period of time.  The blip is not seen during the entire delay interval, just at the beginning.

I see the blip every time except for the very first cycle, before the 255 to 0 transition has ever happened.

My best guess is that there is a PWM "accumulation" that is not seen when the brightness is set to zero, but it is used when the brightness is set to a non-zero value.

/*
 FadeBlip
 Derived from Fade.ino.
 */

int led = 9;
int brightness = 0;
int fadeAmount = 1;
int skipBegin = 5;
int skipEnd = 254;

// If you try a shorter delay, you must make the skip range smaller
// to pick out the blip.  If you try a longer delay, the blip is not
// as bright.
int delayms = 1000;

void setup()  {
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  delay(1000);  // give us time to bring up serial monitor
}

void loop()  {
  Serial.println(brightness);
  analogWrite(led, brightness);

  brightness = brightness + fadeAmount;

  // skip the boring middle values
  if (skipBegin < brightness && brightness < skipEnd)
    brightness = skipEnd;

  if (brightness > 255)
    brightness = 0;

  delay(delayms);
}

The Why does an LED sometimes flash when increasing brightness? question does exactly describe my problem (except for the substitution of pin 11 for pin 9).  That question refers to this post at forum.arduino.cc which gives the beginnings of an answer.

The problem is caused by the fact that analogWrite(led, 0) does not use PWM, it just sets the pin to LOW.  So when you call analogWrite(led, 0), the value in the Output Compare Register (OCR) is left at 255.  When you call analogWrite(led, 1), the OCR value is changed to 1, but due to double-buffering this doesn't take effect until the next timer cycle begins.  So for a fraction of the current timer cycle the output pin is left at HIGH.

The solution is to either avoid calling analogWrite(led, 0) or to explicitly set the OCR value to 0 when analogWrite(led, 0) is called.  This will only work if another call to analogWrite() is not made in the current timer cycle.  Given that the default timer cycle takes 32 microseconds, this is unlikely to happen.  32 microseconds = 256 (ticks per timer cycle) / 16MHz (clock ticks per second) * 2 (default timer prescale factor).

For pin 9, the solution was to add these lines immediately after the analogWrite() call:

if (brightness == 0) {
    OCR1A = 0;
}

For other pins, use the correct Output Compare Register.  For the Arduino UNO they are:

+-------------+----------+-------+
| Arduino Pin | Chip Pin | OCR   |
+-------------+----------+-------+
|           3 |        5 | OCR2B |
|           5 |       11 | OCR0B |
|           6 |       12 | OCR0A |
|           9 |       15 | OCR1A |
|          10 |       16 | OCR1B |
|          11 |       17 | OCR2A |
+-------------+----------+-------+

Of course this solution will need to be modified if you have changed anything related to timers such as the PWM mode.

The solution given by the forum.arduino.cc post indicated that the Timer/Counter Control Register (TCCR) needed to be modified in addition to setting the OCR value.  This modification was to configure the PWM mode, but the PWM mode would have already been correctly configured by any previous call to analogWrite() for that pin.

Others have suggested that calling analogWrite(led, 1) before analogWrite(led, 0) would be a simpler solution, but that still results in a flash, albeit shorter.

Resources:

LED fade malfunction (random flash) (forum.arduino.cc/index.php?topic=360468.msg2486781)
hardware/arduino/cores/avr/arduino/wiring_analog.c
Secrets of Arduino PWM (www.righto.com/2009/07/secrets-of-arduino-pwm.html).  There is a more recent copy of this article at arduino.cc (www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM), but that copy has the useful graphics stripped out.
Arduino Timers and Interrupts (arduino-info.wikispaces.com/Timers-Arduino)


Burning the Bootloader on Adafruit Feather 32u4 So, the default bootloader in Arduino is oddly set to erase EEPROM with every reboot, rendering the EEPROM, well, useless.

I found where the fuses are set in the boards.txt file, but getting this configuration change into the chip requires burning an updated booloader.

In the Arduino IDE, there is an option to "Burn Bootloader", but that would be way too easy, and of course, doesn't seem to work.

I can't find any clue on the Internet about how to actually get the bootloader updated in these devices.

So, is it possible to reprogram the bootloader on the Adafruit Feather 32u4 devices?

If so, what's the trick to do it?

"Burn Bootloader" only works if you have a programmer connected to the device. The onboard bootloader in your Feather cannot change the fuses, even though the process may indicate it has done so.

You would have to connect an ICSP (In-Circuit Serial Programmer) to the correct pins (MOSI, MISO, SCK, RESET, VCC, GND). You can use another Arduino as a programmer by uploading a specific sketch to the Arduino to make it an Arduino as ISP.

The normal bootloader on an Arduino emulates this kind of device to allow programming by serial/USB port, but it has limitations. The ICSP process is the native way to get a program onto the AVR chip, and is the only way to set fuses.

EDIT:

This AVR USB Bootloader Datasheet states on page 3:

  • Boot Reset Fuse The Boot Reset Fuse (BOOTRST) can be programmed so
  that the Reset Vector points to the Boot Flash section start address
  after reset. Once the user code is loaded, a bootloader command
  (“start application”) can start executing the application code. Note
  that the fuses cannot be changed by the MCU itself. This means that
  once the Boot Reset Fuse is programmed, the Reset Vector will always
  point to the Bootloader Reset and the fuse can only be changed through
  the serial or parallel programming interface. The BOOTRST fuse is not
  active in the default factory configuration.

That document also references AVR282: “USB Firmware Upgrade for AT90USB” (Note, I could not find this on the Atmel website.) This document details the FLIP program, at Atmel tool for uploading firmware over the USB DFU interface and setting configuration settings, etc.

This doc has a FAQ section which states:

  Can I modify the fuse bits using Flip? • No, Flip cannot modify the fuse bits. To modify the fuse bit you can use either the JTAG ICE
  MKII, the AVRISP MKII, or parallel programming

So, while this may not be a definitive answer, it appears at this time that "burning fuses" cannot be done over USB on the 32u4. If that's not the case, I'm sure the site would welcome the new info.


Servo going up to the limit as soon as attached I have a Futaba S148 servo (https://servodatabase.com/servo/futaba/s148)
connected to an Arduino Uno.

As soon as the script attaches the servo, it rotates to its limit and gets stuck.

I've tried several scripts, and narrowed to the simplest:

#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  servo1.attach(10);
}
void loop()
{
}

Also connected the servo to the board with this:

#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  //servo1.attach(10); <--- notice this commented out
}
void loop()
{
}

and then the servo remains still.

I'm using a battery pack of 4.8 V which works fine with the servo and the RC radio, so the battery and the servo, works fine together with remote control.

I have another different SG90 servo running with its own power source and connected to the pin 9, and with a different sketch, it works perfectly.

https://www.arduino.cc/en/Reference/ServoAttach - This should answer it. The library you are using supports only 2 specific pins


Unable to program Arduino mega2560? I am using arduino mega for my application .  Board works well for a week , from yesterday it  is not programming at all , it shows me some error like timeout . What could be the problem kindly  help me to solve this.

avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM20
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM20": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

Com 20 is not configured with your arduino. Go to the arduino program and I think it is on the tools tab or the one next to it. There should be a port label and it says which com port to use. Then go to device manager, then ports. Then go to properties on the port that has arduino and change that to the port the arduino program said. It should work then. This topic has been solved many times.


Replacing Atmega8a pu 1440 arduino Ic with 1337 I have one Arduino uno, and one atmega8a 1337 ic. Can i replace the Arduino uno ic with 1337 to program the 1337 one?

If you have a bootloader installed on the 8A then yes, you can.  The two chips are pin and electrically compatible.


Newbie - What is the Difference Between Power Supply's GND and Arduino's GND? I am new to electronics and Arduino.

What is the difference between power supply ground and Arduino's ground. If I connect my LED cathode to power ground, it doesn't work. But if I connect it to Arduino ground, it works. Aren't all ground the same?

Please see picture below.

I would expect there to be no difference between the grounds in your circuit, and after looking over the schematic for the board, it appears that all of the grounds are common.

I think the most likely explanation for what you're seeing is a quirk in the breadboard. It may be that the side busses are split at the middle of the board, or perhaps there was just a bad connection somewhere on the ground bus on that side of the board.

One way you could troubleshoot it further would be by jumping the ground side of the LED to the power supply ground. Start with the ground on the regulator and then work out until you find the spot where you loose continuity.


Going from arduino & sketch to production I've got a little proof of concept thing going here with an arduino & Ethernet shield. The basic idea is for it to ping out much like a heartbeat monitor every so often so I can see if my house still has internet connectivity.

The arduino works nicely and does exactly what I want. I've ordered a board to be made with just the basic components needed and now want to put the code on to it. They gave me an option to load the code (Dragon AVR) during checkout and I'd love to try that out. So, the question is - how on earth do I package up code for something like that? I've seen a number of people ask the same thing for large manufacturing scales / similar setup where they don't fancy using the arduino & IDE as a programmer.

I've asked around on IRC and various other places but nobody seems to be able to give me specific and clear advice on whether it's possible and how to go about doing it.

"Intel Hex" is pretty much an industry standard and I'm quite certain the .hex files produced by the GNU AVR tools is Intel Hex format. Your vendor is almost certainly prepared to load your sketch from the .hex file.


Replacing the IC (atmega328) if lifespan has been arrive Consider if the lifespan of atmega328 has been wear out.
It said on datasheet of atmega how many times we can upload sketch about 10.000times (cmiiw), should i change the arduino or only the microcontroller after 10.000 times have been arrive? what if that times has been arrive? What happened with that IC? If it will starting problem, can we change only the microcontroller (atmega328PU)?? Or any there's thing or stuff we must change too?
Should i burn the bootloader to that IC after replace it?

You only need to change the IC, not the entire board. The microcontroller IS the IC.
Also, you will not see any degradation, it will just 'suddenly' fail, or starting to fail sometimes, without any warning or counter that counts up/down to 10,000.
Also keep in mind that this number is the MINIMUM guaranteed value, most ICs will go much further.
The best way to prevent getting into problems related with this issue is:

When you have a finished project and it works, just keep that IC for that project.
In case you fear getting into this problem during development, only change it if you are sure you have problems (i.e. you cannot upload your sketch anymore).
Think before uploading 100 times per day a sketch for debugging purposes (add Serial.print lines, or even better, use a PC to debug all non Arduino related code.


How to assign a string-variable to a StackString based on the StackString-library? I'm trying to use the StackString-library which offers not to eat up RAM over time by re-assigning values to strings. I started from scratch and wrote a very basic democode which works.
Then I added an assignment to a STackString-variable from a normal string or a function with return-value string
See code below
If I try to compile
I get a compiler-error saying
no matching function for call to 'Stack::StackString<50>::append(String&)'

here is the code

#include <StackString.hpp>
using namespace Stack;  // it is very important to have this line of code. Otherwise the code won't compile

StackString<50> myString = StackString<50>("Hello, World!");

String NormalString = "1234Test";

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.println(myString.c_str());

  myString.prepend("Everybody say: ");
  Serial.println(myString.c_str());

  myString.append(" How are you doing?");
  Serial.println(myString.c_str());
  Serial.println();

  //myString = NormalString;
  myString.append(NormalString);

}

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

}

Do I have to do some typecasting? and if yes how does it look like?
WHat I want to do is assigning a StackString a new value. This means the STackString is on the left side of the "="  assigning operator. I have tried different variants to no avail.

Could this be a problem of the special construction as a "namespace" ?
No idea no clue

you find the STackString-library here:
https://gitlab.com/arduino-libraries/stackstring

best regards

Stefan

StackString doesn't know what a String is.  The append function only accepts a const char *, a const char or an int:

void append(const char* string);
void append(const char character);
void append(int number);

You can get a const char * from a String easily enough with .c_str(), so use that in the append:

myString.append(NormalString.c_str());

There is also no simple assignment (or complete content replacement) with StackString - you have to "clear" the string first.  So to replace the content with what is in NormalString you would:

myString.clear();
myString.append(NormalString.c_str());


Valid options for output port on Mega 2560 I would like to adopt this library on an Arduino Mega2560:
https://github.com/gueei/DShot-Arduino
However, the macro DSHOT_PORT needs defined for the Mega2560 here:
https://github.com/gueei/DShot-Arduino/blob/master/src/DShot.h
So I need to add a #if defined(__AVR_ATmega2560__) macro to that DShot.h header, however, it is not clear to me where to lookup the port mapping on a 2560 mega.  I'm looking directly at the schematic itself here:
https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
And understand that the 'ports' are groupings of IO where the pins are described as P?#, ? being the port letter and # being 0-7.
So what are my valid options?  It appears that some ports (A,C,L) aren't pinned at all, some (D,J) only a few pins, and just about none of them (except K/F) have all port pins utilized.  Also, I can see most of these pins are reserved for some type of functionality (analog, SPI, etc).  I'm assuming I'm looking for a port with available pins reserved for PWM, such as Port B (pins 10-13 are PWM).  Would this be correct?

It would seem this library needs a single pin to communicate. So it
doesn't really matter whether the port you choose has only a few pins
available. Also, you do not care that some pins can have extra
functionality, like SPI, I2C, etc, unless you do plan to use that
functionality.
There is one think you should be aware of: the library uses the in and
out assembly instructions to access the port. These instructions can
only access the ports that are mapped in the regular I/O space of the
microcontroller, not those that are in the “extended I/O” space. In the
case of the ATmega2560, this means you can use any of the ports A
through G, but you cannot use H, J, K nor L.


can we use Software serial and timer one at the same time or this software use also timer one? i am using timer1 and software serial for gps data i need to see if we have a problem with connection .
So i made a timer1 that's start before the loop that will wait the gps sending and after 3s if we didn't receive data we will exit the loop of waiting and going to make diffrent thing .

According to Answer software serial only you pinchange interrupt and CPU  delay loop. which means it not effect any timer but it might freeze system while transmission.


Simultaneous input output in arduino mega I need to read 5 analog pins simultaneously , is it possible?

note that:
analogRead(1);
analogRead(2);
analogRead(3);
will not work this case

No, it is not. The ADC in the MCU is only capable of sampling a single analog channel at a time.

If you require sampling more than one channel at a time then you will need to use one or more external ADCs that are capable of sampling multiple channels, or multiple ADCs each dedicated to a single channel.


Why does the pin 2 of arduino Mega stay always HIGH? Without declaring the pin 2 as INPUT or OUTPUT, it remains constantly HIGH. Can anyone explain why is it so?

Pin 2 connects to the controller's PE4, which is a GPIO pin, which can also be used for PWM. You should be able to use it either as input or output, and both high and low. It could be that setup initializes it as output high, while you would usually have uninitialized pins as input.

Have you tried to make it low, or make it input?

digitalWrite(2, LOW);

should make it low, while

pinMode(2, INPUT);
int pin2Status = digitalRead(2);
digitalWrite(13, pin2Status);

will copy the status of pin 2 to the on-board LED.


Use LoLin V3 pins starting with 'S' in Arduino I have this LoLin NodeMcu V3 board:

What are the pins S3, S2, S1, SC, S0, SK?
Can I use them as GPIO in Arduino?

Thank you for your help!

These pins have 2 functions: They are the connections to an SD card and/or to its internal flash chip. The ESP8266 has the feature of when you set GPIO15 HIGH during bootup, it will load the program from SD card and execute it. See here for reference. On the normal board, these pins are however connected to an internal flash chip.

Signal name meanings:

SK: Serial Clock
SC: SPI Chip Select
S0 to S3: Data lines (Quad-I/O mode).

This picture found here explains the pins:

But as @Majenko already said, only the chip documentation matters, which is here:

Now to answer the actual question: Can you use these pins for arbitrary purposes? That depends. On the board they are all internally connected to a Quad-SPI flash chip. If you re-assign these pins to GPIO pins during normal operation in Quad-SPI mode, the chip hang up as the you just cut off one of the important lines to flash chip. However, if you really want you can modify your chip and cut two connections from the flash chip. Quad-SPI uses 4 data lines, but you can also operate the chip in Dual-SPI with 2 data lines (refer to here).

That means that you are able to cut 2 of the 4 data lines, GPIO9 (SPI_HD, S2 on the board) and GPIO10 (SPI_WP, S3 on the board) on the PCB from the ESP8266 to the flash chip and then use these two GPIO pins arbitrarily. This is to avoid interference with the flash chip when you are driving random signals to it while the lines are still physically conencted to the flash chip. You will ofcourse need to tell your flash tool (esptool.py) to use Dual-SPI mode for all subsequent firmwares. See here for that.

All other Flash GPIO pins can not be re-purposed, these conenctions (such as SCLK, MISO, MOSI, CS) are always needed for the flash chip.

GPIO15, which is D8 on the board, is easier to repurpose: You just need to make sure it's LOW during startup as to not trigger the SD card bootup by using a pulldown resistor. After flash bootup you can re-purpose it for input and output. This is already done on the board for you and you just need to use pinMode to set it as INPUT or OUTPUT. This is also described in here.

Obviously that's a lot of trouble to get 2 GPIO pins. If you just want more GPIO, you will find an I²C GPIO port expander such as the MCP23017 much more suitable for that -- 16 more GPIOs at the cost of 2 GPIO pins (the I2C bus). If you're already using the I2C bus in a project then you don't even loose additional GPIOs, it's just one more device on the bus.


light detection system: Response different from power bank and computer system Hello friends

I'm working on a light detection system for the higher secondary summer term project, for which I'm using a simple Arduino board, Adafruit 16-Bit ADC, an LDR with some resisters, a 5V USB power source either the computer USB 2.0 port or a mobile power bank 5V-500mA/1A/2.1A, a USB mobile charging cable (not the data cable) and a Bluetooth module to communicate with Arduino system, an android or a computer (different from Arduino power source) to record the data.

The difference in maximum and minimum response is very poor when replacing the power source from the computer USB to power bank USB. With the same environmental and experimental conditions, the response goes from 50000 to 45000 counts (the changes in response are 5000 counts) with the power bank. For the same situations, the response goes from 50000 to 5000 counts (the changes are 45000) with the computer power source which is more suitable but it's better to use a small power supply.

How can I get the better and stable response? Kindly help me to solve out this issue. Thank you.

Based on limited knowledge of the design and limited knowledge of the requirements here are 3 possible reasons.  More may exist.

The USB 2.0 definition stats such a port provide 0.5A of current.  Some devices limit the current as a precaution.  Therefor the battery may provide more current then the USB source.  The type of USB source was not specified and no voltage measurement data was provided.
How fast does the device need to react to a change in light level?  A light-dependent resistor or LDR can have a latency of as much as a second with respect to light level changes.
With regards to the 16 bit ADC.  What precautions have been made with regards to precisely controlling the ADC's voltage reference?  Any fluctuation can cause large errors.  What precautions have been made with regards to filtering out the ADC's random noise?  For example, many ADCs only have a fraction of their resolution if averaging is not used.


What options are available for connecting to a CDMA network? I am looking specifically to connect to a CDMA carrier from an Arduino. In doing research, I came across a CDMA shield option (requires getting a CDMA module that you drop into a shield), but that ends up being quite expensive - the CDMA module alone is $140, as opposed to a GSM shield which runs $30-$60. I've also tried looking for other CDMA modules, but haven't been able to find much.

Even if it's not sold as a proper Arduino shield, does anyone know of a CDMA module for hobby projects?

There are no CDMA (more correctly known as CDMA2000) modules for hobby projects. There are a lot of reasons for this, which I won't get into, but suffice it to say, it is the way it is.

EDIT

Okay, I'll bite (just a little).

I think the most important reason is CDMA is actually kind of USA-centric technology. While there are now a few other countries that have CDMA networks deployed, it pales in comparison to the number GSM networks globally.
So in the cellular services world there is a service offering called machine to machine (M2M). What this is is a service to allow various machines (think parking meters, vending machines, ATMs, etc.) to have a data connection for control and status messages. These services are usually bought in bulk at rates much lower than equivalent consumer services would cost.
The rest from here on out is just economies of scale. If I am making an ATM machine, would I rather be limited to a handful of countries, or be able to sell in almost all countries. The obvious choice is the latter, so these manufacturers use GSM.
The reason a hobbyist can get anything cheap is because some other industry is using a lot of them. For example accelerometers used to be crazy expensive, that was until millions of cell phones started shipping with them every year, and now you can get them for pretty cheap. GSM modules are relatively cheap because there are lot of devices being made with them for the above mentioned reasons. CDMA modules are not so cheap because there are not a lot of devices using them.


Is there an alternative to soldering to connect boards? I know that shields are usually soldered to headers so they can be attached to the board with the Arduino. I have a tremor, which makes soldering impossible. Are there ways of connecting PCBs without soldering?

If a concrete example would be helpful, I would like to connect the Adafruit WINC1500 WiFi Shield to a SparkFun RedBoard.

Yes, there are ways. There is a system called "Press Fit" where the pins have a bulge in one end of them. This grips the inside of the holes in place of soldering.

A number of companies make them, such as TE Connectivity and Positronic.

Of course, these depend on the holes being just the right size, and finding the right connectors could be tricky... so... your mileage may vary.

But nothing is better than getting someone to solder the pins for you. You could teach one of your younger relatives to solder, for example...


How to connect an Elegoo Nano to a Raspberry Pi and program it? I own an several Elegoo Nanos and a Raspberry Pi. I would like to connect an Elegoo Nano to the Pi and upload nanpy onto the board and control it's GPIO pins.

I have plugged the nano into the Pi and it is not recognised by the pi. I believe it is something to do with the drivers required for the nano to work. I feel this is similar to this post Arduino Nano not visible in Serial Ports (Mac OS) as I have tried and failed at connecting it to my Mac.

Any help at getting the Elegoo Nano read by the Arduino IDE on my Raspberry Pi so I can program onto it would be greatly appreciated.

The Elegoo website has a downloads page which contains the drivers.

Using the Raspberry Pi, download the zip file containing the drivers.
Unzip the contents to a location of your choice. (Also see here)
Change to the directory containing the Linux driver source files (ie CH341SER_LINUX).
In the terminal type make. Let it compile the driver.
In the terminal type make load.

Done


How to draw a bitmap on a tft display? I'd like to print a bitmap on my TFT.

I setup my screen with this library: http://forum.arduino.cc/index.php?topic=292777.0

It is like the Adafruit_GFX library (only a little bit changed). Everything works.

With the tool Img2Code I converted my image into a bitmap.

void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                               const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

How to include this code and print the bitmap on the tft?

As the function prototype you have show suggests, the data needs to be in a uint8_t array format.

void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
            const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

So your array data would look like:

const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff,
    0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef,
    .... etc ....
    0xff, 0xff, 0xff, 0xff, 0xff
};

You then call the function with the needed parameters:

tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF);

That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size.  It will draw it in white (0xFFFF).


Sets of Ultrasonic frequencies using arduino uno Is it possible to create a set of ultrasonics frequencies using only the Arduino? What code to be used? And how am I going to do for it to work? For this project I need to focus in  the emitter side; all resources on Google are only on sensor and distance detector. I just want to use ultrasonic on other field just like for example on repelling rats. Thanks!

There are three parts to this project, one of which you asked:

I need to generate a frequency greater than 40 khz using arduino uno?

This one is easy: Yes. You can use the tone() library call. You can specify a frequency up to 8mhz. You can call this in the void setup{} part of your code, and (if you don't want to do anything else), leave the void loop() {} empty. You might want to generate an audible tone for a short period first, to show that it is working.

You need something to actually make the sound.

Depending on the frequency, most speakers won't do the trick, or will do it at a very low volume. Speakers are made to work with audible frequencies. Even then, some speakers (larger ones) are better at low frequencies; others (smaller ones) are better at higher audible frequencies. I think piezoelectric buzzers would give you a better response at higher frequencies. In any case, whatever you buy find out the frequency response for the specific part, find the frequency you intend to use along the bottom, then see what the volume (db) is for that frequency - this will give you an indication of how loud it will be. Remember that you won't be able to hear it.

The circuit is pretty trivial. Google piezo arduino

Efficacy:

From https://en.wikipedia.org/wiki/Electronic_pest_control#Effects_on_rodents

  Rodents adjust to the ultrasound (or any new sound) and eventually ignore it. At best, ultrasonic waves have only a partial or temporary effect on rodents. Numerous studies have rejected ultrasonic sound as a practical means of rodent control.Tests of commercial ultrasonic devices have indicated that rodents may be repelled from the immediate area of the ultrasound device for a few minutes to a few days, but they will nearly always return and resume normal activities. Other tests have shown that the degree of repellance depends on the frequency, intensity, and pre-existing condition of the rodent infestation. The intensity of such sounds must be so great that damage to humans or domestic animals would also be likely; commercial ultrasonic pest control devices do not produce sounds of such intensity.


How can a DC motor (toy) be run with only an Arduino and transistor without an external power source? I'm trying to understand this circuit found here.

I understand that the Arduino cannot directly run a DC motor because it can only supply 40mA of current and also due to the back EMF which can damage it. I can also understand this circuit if they used an external power supply and used the transistor as a switch to drive the DC motor. But, I do not understand this configuration shown in the pic where the power supply is the arduino itself.

Your confusion lies in what can "supply" power.
Your assumptions are all correct for an IO pin. However the Arduino has more than just IO pins. It has power pins.
These power pins are not controlled in any way by the microcontroller - they are merely connections into the power supply circuit that also powers the microcontroller.
So in that circuit the Arduino's power supply is shared between the Arduino (the MCU) and the motor.
The 5V pin of the Arduino can supply up to 450mA (when powered from USB - 500mA less about 50mA for the MCU) or up to 800mA when supplied with about 6.5V into the barrel jack (any more than that will cause excess heat to be dissipated which will reduce the maximum current the 5V regulator can handle before shutting down).


Can Arduino control 8 solenoids? I know very little about Arduino and even less about programming one. Before I purchase a board, and learn how to program it, I was wondering if my idea is feasible.

I want to program the Arduino to sequentially open one after another irrigation valve. There would be approximately eight 24 volt solenoid valves. Each one would need to be open for approximately 15 minutes, then open the next valve in sequence and finally close the previous valve. Similar to a multi-zone irrigation controller.

I see that I may need to use a transistor in the power circuit of the solenoid. But it is not clear to me if the Arduino can control eight solenoids and if so, does each solenoid require its own transistor?

An Arduino can control (at least) 8 devices. Instead of a transistor, it might be much easier to use an 8 way relay controller, something like this:

8 relay module

Just connect all 8 valves to the relays, you power the relay with a separate source for the valves, and connect the pins to the Arduino.

These ones have opto couplers, which give an extra security between the valves and the Arduino.

8 relay module with opto couplers
(note I just put the first entry I found, you might find better/cheaper similar items, e.g. at AliExpress for $4).

As Andre said in a comment below, you can use an Arduino Mega if you need more outputs. Or if you want a challenge you can use use a multiplexer IC like 74HC595 (plenty of examples to be found with Arduino).

For controlling one relay with an Arduino enough examples can be found, for 8 it's similar (just use 8 GPIOs), or a multiplexer IC.


How do I set a continuous servo to turn on until a switch is flicked? I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.

Here is the schematic:

Here is my code:

#include <Servo.h>
Servo servo1;

int button = 2; //Assigning pin 2 for the momentary button
int buttonval = 0; //Creating a variable for the buttons value
int green = 12;
int red = 13; //Assigning the green and red LED to pin 12 and pin 13
int red = 13;
int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
int Open = 7;
int Closedval = 0; //Creating two blank variables for the states of the switch
int Openval = 0;

void setup() {
  servo1.attach(4); //Assigning the data pin for the servo
  servo1.write(1); // Giving a starting speed to the servo
  pinMode(button, INPUT); // Setting up the input pin for the momentary button
  digitalWrite(button, HIGH); //  turn on pull up resistors
  pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
  pinMode(Open, INPUT);
  pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);
  digitalWrite(Closed, HIGH);
  //Turning on pull up resistors for the two inputs from the toggle switch
  digitalWrite(Open, HIGH);
}

void loop() {
  Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
  Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

  if (Closedval == HIGH) {
    servo1.write(180);
    // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
  }

  if (Openval == HIGH) {
    servo1.write(86);
    // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
  }

  digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
  digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
}

Any help would be appreciated.

Your are not debouncing your input buttons, which means that digitalRead(Closed) (and Open) will be HIGH in one execution of loop and in the next pass, 3 millis later, it will be LOW.

The servo probably need over 50ms to complete the action (you don't said what servo are you using).

You need to wait for the action to be completed before trying to move it in another direction.

You didn't post your schematic, so may be you wired things wrong. How can we know?

Usually the first step when you find a problem is add Serial.print to know what is working and what not, and then correct the problem.


Burn Arduino Bootloader - Atmega8L I am making an RGB LED project right now using the Arduino UNO board.

At this point everything is working fine so I would like to transfer this onto a small microcontroller circuit to be put inside the enclosure. Since the enclosure is small, I cannot fit the UNO board inside it, hence I want to make a small circuit on perfboard with minimal components.

I read that you can burn the arduino bootloader on a standalone AVR (hooked up to power, filter caps and 16Mhz crystal) which can then execute Arduino code.

Any idea how can I do this? Also can I do this on an ATmega8l AVR, since my code is small enough to fit in one? No point wasting a 328 if 8L can do the job.

Thanks!

The Bootlader
If you want to burn the bootloader to the standalone AVR that you will be using, you can do so using a programmer like the USBasp. Or, you can simply use the Arduino  itself to do this.

Open the ArduinoISP sketch from File > Examples.
Upload it.
Push reset on the Arduino.

Wire it up
Next, wire up the AVR on a breadboard as shown here: Arduino ISP

If you are using a variant/derivative, use a crystal that matches the crystal on your board. You might have not_in_sync() trouble if you don't.
Add a 10uF capacitor between RESET and GROUND on the Arduino, if you are using Uno, or something similar.

Burning the Bootloader
Then select Arduino as ISP as the programmer.

Goto Tools > Programmer.
Select Arduino as ISP.

Now click on Tools > Burn Bootloader.
Verifying it all works
Once that is done, open the Blink LED example and try uploading it to the AVR. You have to use the Upload using Programmer option from File > Upload using Programmer. You can verify if it is successful, by connecting an LED to pin 19 of the AVR, and checking if it blinks.
Notes:

Remember that the pins on an AVR don't map to the corresponding pins on the Arduino, even if they are both the same chips. Search for "AVR to Arduino pin mapping" for your chip on Google. Here's the ATMega8 to Arduino pin mapping.

Don't forget to connect the ground lines of the AVR and the Arduino.

This worked for me using an ATMega8A-PU. It should work with the 8L too.

Post here if you have any problems. Glad to help :)


Mapping PPM Signals to Servo Values This question is an extension of this question.

Accessing Values From Array Within a Library

The answer provided by Mark showed me how to read and print a single value from a particular array by using the index number to print to the serial console.

The second part of this question is how to get these values from the array to map to 0-180 for values that are useful to the servo.

The below code is my attempt that is not working. I used the servo sweep example from the Arduino examples which worked fine with a potentiometer but not with the ppm input. What am I doing wrong here? This won't compile. (I am using TinyServo.h library since this is for an attiny85. Works with with the pot mapping just fine.)

#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          //Doesnt work// reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}

For some background, the ppm library outputs like this to the serial monitor:

Ch4=1560 us

These values move from ~1000 - 2000 depending on the ppm signal input. (The input is from a RC remote control receiver)

This example below prints only channel 4 (Ch4=1560 us)from  a total of 8 channels. Now, I want to map this to the values of 0-180:

#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
  TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
}

void loop()
{

Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us"));

 display results */
  delay(500);
}

What am I doing wrong?

int PPM_INPUT_PIN = TinyPpmReader.width_us(3);

will save the result into variable PPM_INPUT_PIN, while

val0 = analogRead(PPM_INPUT_PIN);

will save an analog reading results from PPM_INPUT_PIN channel into variable val0. This is (one of) your problem.
To map the PPM value, you can do:

#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int val0,                     // integer to store value
    mappedval0;               // integer to store mapped value;

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

const int PPM_max_value = xxxxx; //put the max value of PPM reading result
const int PPM_min_value = yyyyy; //put the min value of PPM reading result

void setup()
{
  setupServos();
}

void loop()
{
  val0 = TinyPpmReader.width_us(4);   //get PPM reading result from index 4
  mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)

  moveServo(PANSERVO, mappedval0);
  delay(5);                           // waits for the servo to get there
}


LED on Arduino does not blink I successful installed arduino, added me to uucp and lock and loaded cdc_acm module.

I use Arduino Uno R3, so I also installed arduino-avr-core.

I have Arduino on /dev/ttyUSB0.

I configured with:

stty -F /dev/ttyUSB0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

I have this folder with these files:
~/Documents/Arduino

build.options.json
------------------------------------------------------------
{
    "fqbn": "archlinux-arduino:avr:uno",
    "hardwareFolders": "/usr/share/arduino/hardware",
    "toolsFolders": "/usr/bin"
}

sketch.ino
------------------------------------------------------------
void setup() {
    pinMode(13, OUTPUT);
}

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

After this commands I got output:

arduino-builder -build-options-file build.options.json sketch.ino

Sketch uses 914 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

But nothing happened on my Arduino, what's my problem?

Thanks.

P.S. I don't have external LED, I try to use bultin LED.

You invoked the builder, but not an upload to the board. The builder created a hex file.You should use avrdude for upload.

Or use Arduino IDE which does it with a click on a button


Action while button is pressed My issue is that I can't rotate the motors continuously. If I press any button, motor.step will be executed and then it stops, even though I didn't release the button.
This is my project so far.
Code:

#include <AFMotor.h>

//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

char data;

void setup()
{

  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm
  Serial.begin(9600);
}

void loop()
{
  Serial.println(data);
  if (Serial.available())
  {
    data = Serial.read();
    if (data == 'A')
    {
      motor1.step(200, FORWARD, DOUBLE);
    }
    if (data == 'B')
    {
      motor1.step(200, BACKWARD, DOUBLE);
    }
    if (data == 'C')
    {
      motor2.step(200, FORWARD, SINGLE);
    }
    if (data == 'D')
    {
      motor2.step(200, BACKWARD, SINGLE);
    }
    if (data == 'E')
    {
    delay(50);
    }
  }
}

App Inventor blocks:

Serial isn't a keyboard. When you send 'A' you send 'A'. Whatever that source is - if you send a single A you send a single A, and you receive a single A.

You will have to come up with some other protocol and write some special software on your computer that monitors the keys directly, and sends something along the lines of "I Pressed A" and "I Released A".


Achieving nanosecond accuracy with MKR Vidor 4000 Can I achieve nanosecond accuracy with Arduino Vidor MKR 4000? Has anyone experience? Obviously by using the FPGA it has on it. I do not find much support on this module on google search...

No. You can't.
To achieve 1ns precision you need a 1GHz clock. That can't happen.  The MKR Vidor 4000 uses an FPGA with an "A7" speed grade. That means that (according to Table 20 here) you can't run at any more than 402Mhz internally (200MHz is all Arduino are rating it for).
Not even half.
Around 5ns precision would be the absolute maximum precision you could get if you stick to the Arduino clock specs.


Arduino Burn the code programmatically Is it possible to burn arduino code programmatically?

I was thinking of one way and that is to download hex file from my online server. Store contents of the hex file in a string, and write that string to arduino flash, restart arduino and it should run new code in flash.

Can this be done? If not than please suggest me any other way to burn the code using C++ instructions.

First, the Arduino Uno has 32 KB of flash, but only 1 KB of RAM. So, to be able to store the new program in a string means your new program can only be, at most, 1kb.

Secondly, only the bootloader can write to flash. So you could write a new bootloader that downloads the new program (in parts) and writes it to the flash. You would however need quite a big bootloader, leaving less space for actual code. Also the main program still needs to access the server to see if it needs to "reboot" so the bootloader can run the update process.

An example of an OTA bootloader can be found at https://www.rotwang.co.uk/projects/bootloader.html which might be a good starting point. Similar idea https://ncrmnt.org/2014/02/27/rf24boot-a-universal-over-the-air-bootloader-for-all-those-ucs/

Another option is to write the new firmware to an external EEPROM. Then your modified bootloader only has to read the new firmware from EEPROM, making it a lot simpler and smaller. There is some useful info in the question OTA updates for Arduino using nRF24L01+

MySensors.org already made such a bootloader: https://www.mysensors.org/about/bootloader

I know there exists another bootloader that does just that, but I can't seem to find it.


Arduino and SIM900 unavailable all the time I have the a problem with my arduino MEGA 2560 and the SIM900 module.
I want to save the outputs of the AT commands, but I never get a chance. If I print mySerial.available() I only get 0.
Sending SMS works fine on the other hand.

Initializing...
AT+CMGF=1
AT+CNMI=2,2,0,0,0

OK
Done
AT+CMGL="REC UNREAD"

OK
0
0
0
0
0
0
0
0
0
0
0

This is the sketch I use:

#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(11, 10); //SIM900 Tx & Rx is connected to Arduino #7 & #8
String incoming="";
String incoming2="";
String messages="Test";
String auth_num="+49xxxxxxxxx";
char incoming_char=0;

String response = "";

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

int period = 6000;
unsigned long time_now = 0;

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT+CMGF=1");
  mySerial.println("AT+CNMI=2,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  //mySerial.println("ATE0");
  updateSerial();
  Serial.println("Done");

  //sms_versenden("xxxxxxxx", "text");
}

void loop()
{
  updateSerial();
  Serial.println(mySerial.available());
  if(millis() - time_now > period){
    time_now = millis();
    if(sms_erhalten()){
      sms_autorisiert();
    }
  }
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void sms_versenden(String rufnummer,String text)
{
  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  if(rufnummer.startsWith("0")){
    rufnummer.remove(0,1);
    mySerial.print("AT+CMGS=\"+49");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else if(rufnummer.startsWith("+49")){
    mySerial.print("AT+CMGS=\"");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else{
    return;
  }
  updateSerial();
  mySerial.print(text); //text content
  updateSerial();
  mySerial.write(26);
}

boolean sms_erhalten()
{
  mySerial.print("AT+CMGL=\"REC UNREAD\"\r");
  //recvWithEndMarker();
  Serial.println(mySerial.available());
  delay(30);
  while (mySerial.available()){
    String inData = mySerial.readStringUntil('\n');
    Serial.println("Got reponse from SIM900: " + inData);
  }
  /*if(mySerial.available()>0){

    incoming = mySerial.readString();
    Serial.print(incoming);
    delay(10);
  }*/
  updateSerial();
  if(incoming.startsWith("+CMGL:"))
  {
    return true;
  }
  else{
    return false;
  }
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (mySerial.available() != 0 && newData == false) {
        rc = mySerial.read();
        updateSerial();
        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}
String getResponse() {
    while(mySerial.available()>0){
        response += mySerial.read();
    }
    return response;
}

Thanks in advance for every idea.
Bravodelta

Rather than creating your own function used SerialEvent function in arduino. It acts as a serial interrupt in arduino. For example:

String inputString;
void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          Serial.Println(inputString);
        }
      }
    }


How do I get an accurate time? I've made a clock using an Arduino, but the time seems to drift.  I am aware of the rollover issue; the clock seems to drift by about 15 minutes over the course of a week.

I'm using a custom PCB with this resonator from Digi-key.  The code reads the millis() function at the beginning of each loop, and works from that value.

My question is:  How can I measure time with an Arduino, accurately enough to make a passable desk clock?

You do not need an RTC to build a clock: the ATmega chip has all the
hardware needed to perform the duties of the RTC itself. Here is how:

Get a 32768 Hz watch crystal: either buy it or disassemble an
old clock. These crystals, specifically designed for time keeping,
have an extremely small temperature drift. You would also need one
of those if you wanted to use an RTC chip.
Configure the fuses of your ATmega to run off the 8 MHz RC
oscillator. This will make your millis() function horribly
inaccurate, and also free the XTAL1 and XTAL2 pins.
Connect the watch crystal to the TOSC1 and TOSC2 pins. These are the
same pins as XTAL1 and XTAL2 (9 and 10 on the 328P). The different
names are used to mean different functions.
Configure the Timer/Counter 2 for asynchronous operation, normal
counting mode, prescaler set to 128, and enable the timer overflow
interrupt.

Now you will get a TIMER2_OVF interrupt at a very steady rate of once
per second. You only need to advance the clock display by one second in
the ISR. In between the interrupts, you can put the MCU in very deep
sleep (power-save sleep mode: nothing runs but Timer/Counter 2) and run
for years on a couple of AA cells. Unless the display is power-hungry,
obviously.

I did exactly this to build my 24-hour one handed wall
clock.
This link points now to the English translation of the original
documentation in French.

Quartz calibration

If you do not calibrate your quartz, you can expect a significant drift,
typically a few seconds per week. The drift rate depends on the
stray capacitance of the traces that connect the crystal to the MCU. In
principle, it could be removed by adding some extra, finely tuned
capacitance. It is worth noting that you would have the same drift
problem with an RTC.

If you are satisfied with this kind of accuracy, then live with it and
be happy. However, if you care to measure the drift, you will notice
that it is very stable. You can then easily compensate for it in
software, and achieve an accuracy of a few seconds per year.

The algorithm for correcting the drift is very simple. From the measured
drift, you figure out the precise delay between the interrupts, which
should be very close to 109 nanoseconds, then:

#define ONE_SECOND    1000000000  // in nanoseconds
#define ONE_INTERRUPT  999993482  // for example

ISR(TIMER2_OVF_vect)
{
    static uint32_t unaccounted_time;

    unaccounted_time += ONE_INTERRUPT;
    while (unaccounted_time >= ONE_SECOND) {
        advance_display_by_one_second();
        unaccounted_time -= ONE_SECOND;
    }
}

In the above example, the quartz is slightly too fast, and the software
compensates by “missing” a tick every few days. If the quartz was too
slow, the same code would instead double-tick once every few days.

This kind of calibration could also be done for an RTC, but it would be
significantly more complex because the RTC reports the time in a
broken-down form that does not naturally lend itself to arithmetic
operations.


Unable to upload sketch using Platformio (but Arduino IDE works) I am using an Arduino Nano (Clone) which I was programming with the Arduino IDE (Version 1.8.5 on Mac OS X 10.10.5).

Using the Arduino IDE I need to re-plug the Nano before uploading, but after doing this everything works as expected and the sketch is being uploaded successfully.

I then tried to use Platformio core (CLI) and get the well-known not in sync error:

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

As said, this error is well-known, esp. in relation to Arduino clones, and reported several times around the Internet with different solutions.

I just wonder how Arduino IDE is able to upload the code successfully, but Platformio is not since both Arduino IDE and Platformio CLI are just calling avrdude to upload the code.

Remark: Uploading the same code to an Arduino Uno works like a charm with both using Arduino IDE and Platformio.

Updates due to further investigation:

I enabled verbose output for both Arduino IDE and Platformio showing the exact avrdude command executed to upload the built hex-file. I adopted the call to avrdude from Arduino IDE with the path of the compiled Platformio code. This works as expected:

avrdude -v -p atmega328p -c arduino -b 57600 -D -P /dev/cu.usbserial-00000000 -U flash:w:.pioenvs/nano/firmware.hex:i

I then had a look at the command used by Platformio which is quite similar but provides an additional -C for a config-file:

avrdude -v -p atmega328p -C /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf -c arduino -b 57600 -D -P "/dev/cu.usbserial-00000000" -U flash:w:.pioenvs/nano/firmware.hex:i

Unfortunately, I am not able to run this command from the Terminal due to an error:

avrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf"
avrdude: syntax error at /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf:1080

Please use board = nanoatmega328new in your platformio.ini


How to switch 12V water pump I found this pump:

https://www.aliexpress.com/item/Free-Shipping-Ultra-quiet-DC-12V-3M-240L-H-Brushless-Submersible-Water-Pump-High-Qualtiy-mini/32472119699.html

Now, I want to control it from an Arduino.

Is this a good relay to use?

https://www.pololu.com/product/2480?

I want to use a 12v battery for the pump.

I see people are recommending mosfets (which is the best option). Keep reading this if you still want to use relay. There are two kind of relays, mechanical and solid state. Mechanicals are cheap but they can be noisy (they make sound) also they have low life expectancy compared to solid state relays. On the other hand solid state relays are faster with everything else but they are expensive. Also you need to check voltage and max current rates before buying.


TWI Wire.setClock() on non arduino AVR MCU issue Using an Atmega168P - programmed by means of avrdude with the .hex file generated by Arduino IDE.

The following code sets the 8 MHz Atmega's TWI interface to just 15.625 kHz:

  Wire.begin(); // Initiate the Wire library
  Wire.setClock(100* 1000);
  delay(10);

While this one doubles it to 31.25 kHz:

  Wire.begin(); // Initiate the Wire library
  TWBR = (F_CPU/(100*1000) - 16)/2;
  TWSR &= 0b11111100;
  delay(10);

Looking to get 100 kHz clock. What am I missing ?

Looking to get 100 kHz clock. What am I missing?

Calculations are int (16-bits) by default in AVR GCC. Try 100*1000L. Or even better:

#define F_TWI 100000L

and use:

TWBR = ((F_CPU/F_TWI)-16)/2;

or:

Wire.setClock(F_TWI);

Cheers!