Newbie Question with 4 pin button I suspect this is a very Naive question.
But the answer will teach me a lot.

Why does this circuit work when I connect the Digital Input (Digial Pin 2) to Pin 4 of the push button. But does not when I connect the push button to Pin 3. I missing something about how power flows when the button is pushed.

Ray K

Internally those little tactile switches look like this:

That means that the two pins on the same long side are connected together.  So you can use, when you hold the switch vertically as in the image on the page you link to the two left-hand pins are linked together, and the two right-hand pins are linked together.

So you can use either both the top pins, both the bottom pins, or the top left and bottom right or the top right and bottom left.

Using either both left hand pins or both right hand pins will be as if you were sat on the button and it was permanently pressed.


How much voltage and current can a Arduino uno digital input sink? I am having a digital output of 24VDC and 0.5A from ABB IRC5 controller. I need to feed this digital output to the digital input of Arduino uno. How can I do that?

You have 2 different questions here. First one can be answered by google search, it is literally the first result.

The Arduino Uno uses the atMEGA328 microcontroller, which has an absolute maximum rating of 40 mA source or sink per GPIO. Also, the total current through the supply or ground rails (i.e. the total of all current OP wants the GPIO pins to sink, or source) is rated to a maximum of 150 200 mA.

And you should not apply more than 5V.

Regarding second question, Google can help again.

Vin is your 24V from controller, Vout is your Arduino digital 5V input. With that established, use voltage divider formula to calculate R1 and R2 values. I hope you can do that?
That being said, I am disappointed, because I feel like you have put 0 effort into researching this.


Problem with reading series of bytes over serial port I'm writing a program to read bytes from serial channel, copy those into an array and then do some verification on those copied numbers.

I'm able to read and copy bytes into an array of bytes.
However, I'm facing an issue with the verification of those bytes.

Here's the code I've written:

#include <SoftwareSerial.h>

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

void loop()
{
    char charRead = 0x00u;
    byte byteArray[10];
    int i=0 , j=0;

    //Clear the array contents
    for(j = 0; j < 10u; j++)
    {
       byteArray[j] = 0x00u;
    }

    //Wait for data on serial channel
    while(Serial.available() > 0)
    {
       //Copy bytes received into array
       charRead      = Serial.read();
       byteArray[i] = (byte)charRead;
       i++;
    }

    //Just for the sake, print the array contents
    for(j = 0; j < i; j++)
    {
       Serial.print(byteArray[j],HEX);
    }

    //Check for first two bytes
    if( (byteArray[0] == 0x31) && (byteArray[1] == 0x32) )
    {
        Serial.println("Verified.");
    }
}

To test this program, I entered "12345" (without quotes) on the serial monitor which gave me an output as "3132333435" since I'm printing the contents of the array in HEX format.

What I'm not being able to understand is even if this output shows that the first two bytes in the array are 0x31 & 0x32 respectively, why not the verification logic of those two bytes is getting executed? If it would, then the string 'Verified' would get printed on the output.

Am I doing something wrong here with Serial.read() or some typecasting?

I'm running this on an Arduino Uno

So, as result of Edgar Bonet's good remark, change

int i=0 , j=0;

to

int j = 0;

and define

int i = 0;

Outside the loop (as a global variable).

Also it is quite dangerous to define the length of the array as 10, while not checking for writing over the boundary of the array. What if you receive more bytes? The application might crash or give unpredictable behavior.


PWM Every Other Pin Doesn't Read Scenario
I've plugged 6 pins from my RC receiver into my Arduino in order to read the incoming values.
Problem
I'm using Digital PWM~ pins 2-6. Oddly the Arduino only reads odd channels:
1480, 0, 1175, 0, 991, 0

I've that if I physically reverse the cables (2-7, 3-6, 4-5) going into the Arduino I get ALL values:
988, 983, 1511, 1174, 1490, 1487

I've found that if I go back to my initial pin setup and merely flip neighbors (2-3, 4-5, 6-7) that works as well.
Question
What could possibly be causing this?
Code
Here is the current code I've written

int ch1, ch2, ch3, ch4, ch5, ch6;
int ch1Pin = 2;
int ch2Pin = 3;
int ch3Pin = 4;
int ch4Pin = 5;
int ch5Pin = 6;
int ch6Pin = 7;

void setup() {
  pinMode(ch1Pin, INPUT);
  pinMode(ch2Pin, INPUT);
  pinMode(ch3Pin, INPUT);
  pinMode(ch4Pin, INPUT);
  pinMode(ch5Pin, INPUT);
  pinMode(ch6Pin, INPUT);

  Serial.begin(9600);
}

void loop() {
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);

  String p = (String)ch1;
  p += ", " + (String)ch2;
  p += ", " + (String)ch3;
  p += ", " + (String)ch4;
  p += ", " + (String)ch5;
  p += ", " + (String)ch6;
  Serial.println(p);

//  delay(100);
}

Photo

EDIT
Since posting this question I've found that reversing the chXpin values accomplishes the same effect as reversing the physical pins. This makes me thing it's a software issue so I'm digging in further.
TEMPORARY SOLUTION
I'm not sure why this works but flipping the neighbor order of pulseIn fixed the issue:
  /* OLD
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  */

  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);

Why did that work? It makes no sense to me.

pulseIn() is a blocking function: it waits until it gets a complete
pulse, or until it times out. While it's waiting, the Arduino cannot do
anything else, and it will miss pulses on other channels.

The RC receiver sends the pulses sequentially. Then, if you try to read
them in the right sequence, it may work. If you read them out of
sequence, you will miss some pulses, and the corresponding pulseIn()
calls can timeout, returning zeros.

For this kind of job I would use the pin change interrupt on pins 2 – 7.
This should allow reading the six pulses continuously without blocking
the whole program. But it's low-level (AVR-level) programming, probably
not doable with the standard Arduino libraries.

Edit: Here is what I had in mind when suggesting the use of the pin
change interrupt. Notice that the pin numbers are “hardwired” into the
code and cannot be changed easily. This is because:

Pins 2 – 7 share a single pin change interrupt request
(PCINT2_vect), thus a single ISR is needed to time the six channels.
They also share a port (port D), meaning they can all be read by the
ISR in a single instruction.

The other possible choices having these nice properties would be pins
8 – 13 (PCINT0_vect, port B) or A0 – A5
(PCINT1_vect, port C).

/*
 * Read 6 PWM signals from an RC receiver.
 *
 * Channels 0-5 are on digital pins 2-7 (i.e. PD2-PD7 = PCINT18-23).
 */

// This always contains the last length measured on each channel.
volatile uint16_t last_pulse_lengths[6];

// Interrupt triggered on every change in pins 2-7.
ISR(PCINT2_vect)
{
    static uint8_t last_pin_states;
    static uint16_t start_times[6];  // start time for each channel
    uint8_t pin_states = PIND >> 2;  // shifted to bits 0-5
    uint16_t now = micros();

    // Check every changed bit of the port.
    for (int i = 0; i < 6; i++) {
        uint8_t mask = _BV(i);

        // Record start time on rising edge.
        if ((pin_states & mask) && !(last_pin_states & mask))
            start_times[i] = now;

        // Record pulse length on falling edge.
        if (!(pin_states & mask) && (last_pin_states & mask))
            last_pulse_lengths[i] = now - start_times[i];
    }
    last_pin_states = pin_states;
}

// Return the pulse lengths avoiding race conditions.
static void get_pulse_lengths(uint16_t lengths[6])
{
    for (int i = 0; i < 6; i++) {
        noInterrupts();
        uint16_t tmp = last_pulse_lengths[i];
        interrupts();
        lengths[i] = tmp;
    }
}

void setup()
{
    // Setup the pin change interrupt.
    PCIFR  = _BV(PCIF2);  // clear pin change interrupt flag
    PCICR  = _BV(PCIE2);  // enable pin change interrupt
    PCMSK2 = 0xfc;        // sense changes on pins 2-7 (i.e. PD2-PD7)

    Serial.begin(9600);
}

void loop()
{
    // Report the pulse lengths on the serial console.
    uint16_t pulse_lengths[6];
    get_pulse_lengths(pulse_lengths);
    for (int i = 0; i < 6; i++) {
        Serial.print(pulse_lengths[i]);
        if (i < 5) Serial.print(", ");
        else Serial.println();
    }

    delay(1000);
}


Arduino Uno SD card storage I am interested in storing accelerometer data to an SD card. Since power consumption is the main consideration of my project, it is important to do as few writes to the SD as possible, because the SD requires much current, and also takes long to be written, keeping my MCU from sleeping.

The data to be stored are about 50 bits of data at 10Hz, so I need to store 500c bits per second, or around 63 bytes per second. The arduino uno EEPROM is 1024 bytes, which could give me around 16 seconds of data stored before having to access my SD card. However I have seen that the EEPROM has limited write cycles (100000). So each byte can be written 100000 times, which gives us a total of 1000*100000=100000000 bytes to be written.As a result, with writing there 63 bytes per second, that would give me 1587301 seconds=441hours=18days of EEPROM lifetime, which is unacceptable. Is this correct?
If (1) is correct and using internal eeprom is not a possible solution, what other recommendations do you have? Is there an alternative to SD storage, that requires less power and less writing time, so that it is cheaper power-wise? The total storage should be around 200MB.

Regarding 1, it's true that EEPROM has limited write cycles. Mostly it can be much more, but it's only guaranteed upto that number, so I can imagine you don't want taking the risk to be lucky.

Regarding 2, other solutions could be external SRAM, which can be much more than just 1 KB, but also adds some extra components, thus cost and more important power. When that SRAM is full (can be many KBs), you can transfer it to the SD card.

Another (added) improvement you might think of (if you did not already) is data compression (trying to store the 50 bits in less bits), but this will cost some 'computing' power.


Are global variables evil in Arduino? I'm relatively new at programming and many of the coding best practices I'm reading effectively state that there are very few good reasons to use a global variable (or that the best code has no globals at all).

I've done my best to keep this in mind, when writing software to make an Arduino interface with an SD card, talk to a computer and run a motor controller.

I currently have 46 globals for about 1100 lines of "beginner level," code (no line having more than one action). Is this a good ratio or should I look at reducing it more? Also what practices can I employ to reduce the number of globals further?

I'm asking this here because I'm specifically concerned with best practices for coding on Arduino products rather than computer programming in general.

They aren't evil per se, but they do tend to get overused where there is no good reason to use them.

There are plenty of times when global variables are advantageous. Especially since programming an Arduino is, under the hood, vastly different to programming a PC.

The biggest benefit to global variables is static allocation. Especially with large and complex variables such as class instances. Dynamic allocation (the use of new etc) is frowned upon due to lack of resources.

Also you don't get a single call tree like you do in a normal C program (single main() function calling other functions) - instead you effectively get two separate trees (setup() calling functions, then loop() calling functions), which means that sometimes global variables are the only way to achieve your goal (i.e., if you want to use it in both setup() and loop()).

So no, they're not evil, and on an Arduino they have more and better uses than on a PC.


Multiple I2C sensors with the same address I am trying to find the simplest way to connect multiple (preferably around 10-20) IMU sensors to one controller. There are two constraints: sampling at 60Hz and reasonably simple wiring as I want to put it on clothes.

I am totally new to the Arduino world, please let me know what other details I should provide.

It seems that just having multiple IMUs on the I2C bus would work great, but they usually all come with the same address.

So, the solutions I found so far:

Using several different IMUs from different companies - hard to find 20 of them
Using a multiplexer - requires star-like wiring topology.
Using multiple controllers - inefficient and doesn't seem right.

For now, the solution with a multiplexer seems to me the most reasonable, but is there any other way I am missing? Can I somehow produce IMUs with, say, 16 different addresses and wire them all together to one I2C?

Thanks for your help!

If you're using MPU6050 IMUs, there's an easy trick: put them all on the I2C bus, and connect each IMU's AD0 pin to a separate digital pin on the Arduino[*]. When you want to read from a specific IMU, set all AD0s to HIGH, except the one you want to read to LOW. All the IMUs with AD0 set to HIGH with have an I2C address of 0x69, whereas the only one on LOW will have an address of 0x68.

If you want to read them all, you just go through a loop and set the one you want to LOW, the others to HIGH, and you're set.

[*] If you want 20 IMUs, you'd better get a Mega, or, even better, a Maple. Small form factor, quite a bit of oomph, lots of pins and flash, and some clones cost next to nothing; eg Itead sells Maple clones for 6 bucks. ElecFreaks sells them for 9 bucks. You could use the 16 pins at the bottom for the AD0s.

This trick works with any kind of I2C device that has a customizable address scheme through one or more pins. I do that with AT24Cxx EEPROMS, which have a 0x50-57 address range. When you want to have more than eight chips, setting all but one to 0x50 and one to 0x51 solves the problem pronto.

Reference: https://github.com/PaulStoffregen/FreeIMU_original/blob/master/documents/PS-MPU-6000A-00v3.4.pdf


Driving a servo with an ATTiny13A So, I managed to fry my cheap servo/ESC (electronic speed controller) and decided to make my own using an ATTiny13A on some perfboard. But, I have run into some issues getting the servo to respond.  I'm assuming the servo.h library is not compatible with the ATTiny13A because of incompatible internal clock speeds not creating the right PWM signals. And I haven't found a solution for this.
I have messed around with the Servo8Bit.h library, but this also doesn't seem to work (as its designed for the ATTiny45 and the ATTiny85 ). Is the ATTiny13A even able to produce the needed PWM signals?
Any help/links to documentation would be appreciated!
Thanks in advance.
Code:
#include <Servo.h>

Servo myservo;
int potpin = A3;
int val;    // variable
int Toggle = 2;

void setup() {
  Serial.begin(9600);
  pinMode(Toggle, INPUT);
  myservo.attach(1);  // Servo/ESC is attached to pb1
}

void loop() {
  int ToggleState = digitalRead(Toggle);
  Serial.println(ToggleState);
    val = analogRead(potpin);

  if (ToggleState == 0) {
  val = map(val, 0, 1023, 0, 180);  //Servo motor
   myservo.write(val);
  delay(15);
}
else {
  val= map(val, 0, 1023,1000,2000); //ESC
  myservo.write(val);
  delay(15);
 }
}

Servo8Bit and ATTiny13(A)
I had a look at the Servo8Bit and had pretty much the same thoughts on this as Edgar Bonet in his comment:

Servo8Bit relies on an 8-bit timer, and the ATtiny13A does have an
8-bit timer. It should not be too hard to port this library to that
micro. Study the source code, then study the datasheet of the tiny13A
(mostly the chapter dedicated to the timer). You should then be able
to easily see what changes are needed.

Ignoring the timing differences between the ATTinyx5 and ATTiny13(A), I just went ahead and saw if I could get it to compile.  And yeah, it's pretty easy to compile.  This mostly consists of adding 0 to some hardware register names.  The bad news is:

Sketch uses 1486 bytes (145%) of program storage space. Maximum is 1024 bytes.
Global variables use 31 bytes (48%) of dynamic memory, leaving 33 bytes for
local variables. Maximum is 64 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.
Error during build: text section exceeds available space in board

So, yeah, that was a bit much to hope for, I guess.  The library does use ISRs to support a number of servos kind of like the more common servo library that you'd use on an UNO.  I haven't looked into chopping it down to size; I expect that will be impractical.
PWM... sort of.
Prior to considering modifying Servo8Bit, I kind of thought it made sense to just use the timer counter directly to produce a waveform.  The problem is the conventional servo signal is 20ms long, and does all of its control in a 1ms window.  If you try to fit the whole 20ms frame into a single 8bit timing interval, what you end up with is pretty crappy angular control.  So, doing it is a bit painful without a 16-bit timer counter.  But, I guess that's the game.
So, the below is a crude and barely tested attempt at it.  The code that follows is state machine inside the OCR0B overflow vector that schedules the rising an falling edges is "normal" mode.  Just to warn you, I don't actually have an ATTiny13(A) on hand.  And in fact I don't happen to have a servo hand either.  But I do have an ancient storage scope and an ATTiny85 and the ability to compile for ATTiny13(A), and a calculator for working out the 8 MHz vs 9.6 MHz difference.
So here's what I came up with, which I think (but don't know) will work if you compile and upload using MCUDude MicroCore, ATTiny13(A) with the 9.6 MHz internal oscillator chosen.
It's only designed to operate 1 servo.  Extending it to two should be easily doable.  Going beyond that you're likely run into problems.
Code:
// +---------------------------------------------------------------------------------------+
// |                                                                                |
// |                                 +-------------+                                       |
// |                                 |             |                                       |
// |                                 |      A      |                                       |
// |  PCINT5 ADC0 dW  /RESET  PB5 *--|-1    T    8-|--* VCC                                |
// |                                 |      T      |                                       |
// |  PCINT3 ADC3      CLKI   PB3 *--|-2    I    7-|--* PB2  SCK   ADC1 T0         PCINT2  |
// |                                 |      N      |                                       |
// |  PCINT4 ADC2             PB4 *--|-3    Y    6-|--* PB1  MISO  AIN1 OC0B  INT0 PCINT1  |
// |                                 |      1      |                                       |
// |                          GND *--|-4    3    5-|--* PB0  MOSI  AIN0 OC0A       PCINT0  |
// |                                 |      A      |                                       |
// |                                 |             |                                       |
// |                                 +-------------+                                       |
// |                                                                                |
// +---------------------------------------------------------------------------------------+

#if !defined(__AVR_ATtiny13__) && !defined(__AVR_ATtiny13A__)
#error This code is written specifically for ATTiny13(A) devices.
#endif

#if F_CPU != 9600000
#error  This code is written specifically for 9.6 MHz
#endif

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

//
//
//
constexpr uint8_t TCCR0A_config(
  int com0b // two bits
) {
  return
      (    0 << COM0A1) // normal
    | (    0 << COM0A0) //   port operation
    | (com0b << COM0B0) // bits 5 AND 4
    | (    0 <<      3) // reserved
    | (    0 <<      2) // reserved
    | (    0 <<  WGM01) //  lower two bits
    | (    0 <<  WGM00);//     of Normal (mode 0);
}

//
//
//
constexpr uint8_t TCCR0A_config_for_go_low()  {return TCCR0A_config(0x2);}
constexpr uint8_t TCCR0A_config_for_go_high() {return TCCR0A_config(0x3);}

//
// 50 Hz (hobby servo frame frequency); period 20 ms
//
// In the below you'll see the numbers 150 and 300 and 3000.
// The reason for these numbers is that I've chosen to to use a /64
// timer prescaler.  At 9.6 MHz, with a /64 prescaler, 1 millisecond
// is 150 timer timer counts.  There's as fixed 1 MS high in the servo,
// followed by 0 to 1ms variable portion.  The number 150 helpfully
// fits within the 8-bit timer registers and also gives a reasonable
// number of increments to the servo control.  For 180 degrees, 150 increments
// is 1.2 degrees.
//
// The maximum high time is the fixed 1ms high time and the maximum
// variable high time, totalling 2 MS, or 300 timer ticks, that's what that
// number is about.
//
// 3000 is the number of timer ticks for a full 20ms signal frame,
// that is 20 * 150 = 3000.
//
//
// Deriving the 150 figure:
//
//  At 9.6 MHz and /64 prescaler
//
//        1 second         64 mcu_cycles   A_MS_DURATION timer_counts
//  -------------------- X ------------- X ---------------
//  9_600_000 mcu_cycles   1 timer_count    0.001 seconds
//
//
//       1      64    A_MS_DURATION
//  --------- X -- X  -----
//  9_600_000   1     0.001
//
//
//     64       A_MS_DURATION
//  --------- X -----------
//  9_600_000      0.001
//
//
//     64 x A_MS_DURATION
//  --------------------
//        9_600
//
//
//  A_MS_DURATION
//  -------------
//      150
//

static constexpr uint8_t  ONE_MS_WORTH_OF_TICKS    = 150;
static constexpr uint8_t  MAXIMUM_HIGH_PERIOD      = ONE_MS_WORTH_OF_TICKS * 2;
static constexpr uint16_t TWENTY_MS_WORTH_OF_TICKS = 3000;
static constexpr uint16_t MAX_WASTE_CYCLES         = 0x80;

static volatile uint8_t g_pulse_width = ONE_MS_WORTH_OF_TICKS / 2;  // default to mid-range.

ISR(TIM0_COMPB_vect) {
  static uint8_t l_pulse_width; // this caches g_pulse_width
                                // and is updated from g_pulse_width
                                // only between frames

  //
  // The ISR is a state machine with four macro states.
  //
  enum class t_signal_generator_state : uint8_t {
    timing_to_variable_high_period,
    timing_to_set_pulse_width,
    calculate_time_to_start_of_next_pulse_and_waste_a_bit,
    timing_to_start_of_pulse
  };

  //
  // Macro state variable
  //
  static t_signal_generator_state g_signal_generator_state =
    t_signal_generator_state::timing_to_variable_high_period;

  // low_time_remaining is an extended state variable
  // for the timing_to_start_of_pulse state
  static uint16_t low_time_remaining;

  switch (g_signal_generator_state) {
    case t_signal_generator_state::timing_to_variable_high_period:
      // We just went high at the OCR0B value that triggered this interrupt
      // and we need to retrigger ((MAXIMUM_HIGH_PERIOD==300) - 256 == 44)
      // timing cycles later such that there are 256 timing cycles left of the
      // 2ms (maximum) high part of the frame.
      OCR0B += (MAXIMUM_HIGH_PERIOD - 256);  // 2ms worth of timer nicks minus the resolution of our timer

      // We're remaining HIGH as we head into the variable portion of the HIGH period.
      g_signal_generator_state = t_signal_generator_state::timing_to_set_pulse_width;
      break;
    case t_signal_generator_state::timing_to_set_pulse_width:
      // We're retrieving the global variable which holds a (potentially new) value from 0 to 150
      // representing a span of 0ms to  1ms (the full range of the servo), but
      // we're starting out the variable pulse a head of time, part way through the always-on first ms.
      // There are (150 - 44) timer cycles, that's 1 ms worth of timer cycles
      // where the timer remains high to finish out first millisecond of HIGH.
      // So we add this to the requested variale pulse width time.
      l_pulse_width = g_pulse_width + (ONE_MS_WORTH_OF_TICKS - 44);

      // Set adjust pulse width
      OCR0B += l_pulse_width;

      // We'll be going low and the end of the variable high period.
      TCCR0A = TCCR0A_config_for_go_low();

      g_signal_generator_state = t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit;
      break;

    case t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit:
      // We just went low at the OCR0B value.

      // Calculate remaining timer cycles to the beginning of the next pulse
      // accounting for the MAX_WASTE_CYCLES we're about to waste in this state.
      low_time_remaining = (TWENTY_MS_WORTH_OF_TICKS - 44 - MAX_WASTE_CYCLES) - l_pulse_width;
      OCR0B += MAX_WASTE_CYCLES;

      // We will remain LOW since the pulse is done and we've not finished out the 20ms period
      g_signal_generator_state = t_signal_generator_state::timing_to_start_of_pulse;
      break;

  case t_signal_generator_state::timing_to_start_of_pulse:
      // Continue retriggering the timer until we've used up 20ms total,
      // in increments of not more than MAX_WASTE_CYCLES.

      if (low_time_remaining > MAX_WASTE_CYCLES) {
        low_time_remaining -= MAX_WASTE_CYCLES;
        OCR0B += MAX_WASTE_CYCLES;
        // We'll need to wast more, so we're remaining LOW.
      } else {
        OCR0B += low_time_remaining;
        low_time_remaining = 0;

        // This is out last round through this state to finish out the 20ms
        // window, so we'll be returning to HIGH.
        TCCR0A = TCCR0A_config_for_go_high();

        g_signal_generator_state = t_signal_generator_state::timing_to_variable_high_period;
      }
      break;
  }
}

//
//
//
void servo_init() {
  const auto SREG_saved = SREG; cli();

  DDRB |= 1U << 1;  // Servo data pin attached on Attiny PB1 aka (OCR0B)

  // select no clock source / stop counter
  TCCR0B &= ~(
      (1U << CS02)
    | (1U << CS01)
    | (1U << CS00)
  );

  // reset counter
  TCNT0 = 0x00;
  OCR0B = 0x80;

  TIMSK0 =
      (0 <<      7) // reserved
    | (0 <<      6) // reserved
    | (0 <<      5) // reserved
    | (0 <<      4) // reserved
    | (1 << OCIE0B) // we *ARE*  using output-compare B interrupt
    | (0 << OCIE0A) // we aren't using output compare A interrupt
    | (0 <<  TOIE0) //             nor overflow interrupt
    | (0 <<      0);// reserved

  TIFR0 = 1U << OCF0A;

  TCCR0A = TCCR0A_config_for_go_high();

  TCCR0B =
      (0 << FOC0A) // We're not doing any
    | (0 << FOC0B) //   output compare forcing.
    | (0 <<     5) // Reserved.
    | (0 <<     4) // Reserved.
    | (0 << WGM02) // High order bit of Normal mode (0)
    | (0 <<  CS02) // Clock source
    | (1 <<  CS01) //    prescaled
    | (1 <<  CS00);//      by 64.

  SREG = SREG_saved;
}

//
//
//
void setup() {
  servo_init();
}

//
//
//
void loop() {
  for (g_pulse_width = 0; g_pulse_width < 150; ++g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
  for (; g_pulse_width > 0; --g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:

On the scope, this produces servo signal that should sweep a servo on pin OCR0B (PB1).  Something like 4 to 5 seconds going one way and same going back.
If I put an ATTiny13A on an order sometime and manage to dig out a servo myself, I'll actually test it.  It may be a very long time before I can do that though.  But the results on the scope look good.  Admittedly everything is scaled by 9.6/8.0.  It should be accurate on a ATTiny13(A).  I verified that it compiles for it.  The workings of the thing are explained in the code as I can.
For comparison:

Sketch uses 490 bytes (47%) of program storage space. Maximum is 1024 bytes.
Global variables use 10 bytes (15%) of dynamic memory, leaving 54 bytes for local variables. Maximum is 64 bytes.

That's still a good chunk of what little code space you have, but it should be enough to read a switch and potentiometer.  This is using the timer the device has, so millis()/delay() usage are kind of out-the-window, I think, I didn't try to see what happen when you call them or study their code in MicroCore.  You could recreate your own millis() by making a timer overflow interrupt and it would overflow at about 1.7 ms intervals.  As you can see, I just used __builtin_avr_delay_cycles to keep things simple.
If you, or anyone else, gets it working on at ATTiny13 before I try it myself, I'm curious to know that it worked (or didn't).


bootloader uploading into Atmega328 Here is mine circuit. Intially i used arduino UNO directly for programming. Now i am Using atmega 328 IC for programming. I am trying to connect 32 hall sensor via Mux circut. I wanted to How to upload boot loader or HExfile Here. Will avr pocket programmer satisfy above circuit or i need to add addtional circuit here
AVr pocket programmer

The AVR pocket programmer should work fine. Sparkfun has a good guide for doing this.

Here's the pinout of the Atmega328:

You'll want to connect your programmer as follows (note, these are the pins for the bare Atmega328 chip only. The pin numbers on an Arduino board are different.):

Programmer Pin		Atmega328 Pin
5V			Vcc (7)
GND			GND (8)
MOSI			Digital 11 / Physical 17
MISO			Digital 12 / Physical 18
SCK			Digital 13 / Physical 19
Reset			Reset (1)

Note that the physical pins on the chip are numbered differently than the logical pins. In the table above the "Digital" pin numbers are those colored yellow in the figure, while the "Physical" pins correspond to the black-on-white numbers around the edge.

If you already have the ICSP header connected to those pins (it's not completely clear in the schematic if that is the case), you can connect the programmer to those pins instead. This can be easy if you have a 6-pin ICSP cable with your programmer.

Also, if you are already powering your Atmega328 from some other 5V power supply you can omit the 5V-Vcc pin. However, the programmer and the Atmega328 must share a common ground, so be sure the GND pins are connected.

Connect your programmer to the computer using USB, open the Arduino IDE, select the correct serial port of the programmer, and pick "Arduino Uno" in the "Board" menu. You can program the bootloader by selecting "Burn bootloader" in the Tools menu, or you can simply write your program by selecting "Uploading using programmer" in the File menu.


DIY CNC Machine Power Requirements I want to make a CNC machine that uses 5 NEMA 17 rated for 2A and a RAMPS 1.4 to control it all. I have a power supply that can deliver 1.5A at 12V. Is it enough? I am worried that when all 5 motors are under load, the amperage will get distributed and there will be very low amperage per motor.

Figuring out your current needs is simply a matter of adding everything up. If you have 5 2 amp motors, you'll need 5 x 2, or 10 amps just to drive the motors.
You should probably have at least 20% extra capacity, so I'd suggest having a 12V power supply that can put out at least 12A.
15A would be better.
The stiffer your power supply the less it will "bobble" as the load varies.


Arduino serial port reset in Serial monitor & Python So am I using an Arduino with a shield to gain some voltage values for an ECG. I am then plotting that data in Python. However whenever I "observe" the serial port, be that through the Arduino serial monitor or in attempting to plot the values of time (using millis()) against ECG (voltage) the values reset, so millis() resets the zero, which is fine, except that some of the older values still show up. Now this is especially a problem in Python because it means the plot is malfunctioning at the start of the script, because it is plotting some of the older values and then after a couple of seconds it resets and the plot looks normal again.

To demonstrate this I have recorded it on video and put it on YouTube, here it is:

https://www.youtube.com/watch?v=dNpUakcRPec

Now initially I thought the problem was with Python or the Pyserial module so I labelled the video as such, but since it occurs in the serial monitor I realised the solution would be in the Arduino sketch. I have tried flushing, didn't work, I have tried even to not start the data till I send a start byte, but this didn't work on Python.

Ideally I could start the Python plotting script and it would skip, or ignore those initial values from the serial port before beginning again.

Here is the Arduino sketch I am using:

#include <eHealth.h>

unsigned long time;
// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);

}

// The loop routine runs over and over again forever:
void loop() {

  float ECG = eHealth.getECG();
  time = millis();
  Serial.print(time);
  Serial.print(" ");
  Serial.print(ECG, 3);
  Serial.println("");

  delay(50);    // wait for 50 millisecond
}

The Arduino is designed to reset when a Serial monitor or script connects to it. The best way to mitigate this would be to send the Arduino some kind of "start sending" signal when you connect to the serial port. It would then send the data when your script was ready.


Detect how long a push button is being pressed? I would like to detect how long the state on/off is going on for. Is there a way to do that? I would like to do that for two reasons:

I would be able to make a very simple toggle button. (I know about the other way with the old value and new value).
I can make the button being pressed for a long time be like a return button.

Anyone got any ideas?

This needs a combination of patterns.

First, the button pin needs to be debounced. This can be done with the "blink-without-delay"-pattern where the button pin is sampled with a low period (40 ms in the example code below).

Second, a simple state-machine is needed to keep track of the button state but also if the return button action function, doReturnButton(), has already been called.

The button is assumed to be connected from GND to pin4. The button action function, doButton(), is called when the button is pushed (goes LOW).

const int buttonPin = 4;
const unsigned long debounceInterval = 40;
const unsigned long returnInverval = 400;
bool buttonState = true;
bool returnButtonState = false;
unsigned long buttonDownMillis = 0L;

void doButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doButton"));
}

void doReturnButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doReturnButton"));
}

void setup()
{
  Serial.begin(57600);
  while (!Serial);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
  unsigned long currentMillis = millis();
  static unsigned long previousMillis = 0L;

  // Check if it is time to sample the button pin
  if (currentMillis - previousMillis >= debounceInterval) {
    previousMillis = currentMillis;

    // Did the button change
    if (digitalRead(buttonPin) != buttonState) {
      buttonState = !buttonState;

      // Was the button released
      if (buttonState) {
        returnButtonState = false;
      }

      // Was the button pushed
      else {
        buttonDownMillis = currentMillis;
        returnButtonState = true;
        doButton();
      }
    }

    // Check if button was pushed and time for return action
    else if (returnButtonState) {
      if (currentMillis - buttonDownMillis >= returnInverval) {
        returnButtonState = false;
        doReturnButton();
      }
    }
  }
}

What does the code do?

It samples the button pin with a debounce interval.
If the button state changes:
a. High to Low it calls the doButton() function and captures a timestamp. It also allows detect of return time interval.
b. Low to High. Return time interval is not allowed any more.
It checks if the return time interval has elapsed and if so calls the doReturnButton() function. The detect is then not allowed any more.

The doButton() function is called when the button is pushed (transition high to low), only once. The doReturnButton() function is called if the return time limit exceeds and the button is still low. Both are only called once per push (transition high to low).

To avoid the multiple transitions that occur when a button is pushed a debounce time period is used. The can also be done in hardware with a RC-circuit.

With some abstraction it could be rewritten as:

#include <Timemark.h>

Timemark debounce(40);
Timemark buttonHold(400);

const int buttonPin = 4;
bool buttonState;

void doButton()
{
  Serial.println(F("doButton"));
}

void doReturnButton()
{
  Serial.println(F("doReturnButton"));
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("started"));
  pinMode(buttonPin, INPUT_PULLUP);
  buttonState = digitalRead(buttonPin);
  debounce.start();
}

void loop()
{
  if (debounce.expired()) {
    bool currentState = digitalRead(buttonPin);
    if (currentState != buttonState) {
      buttonState = currentState;
      if (buttonState) {
        if (buttonHold.expired())
          doReturnButton();
        else
          doButton();
        buttonHold.stop();
      }
      else {
        buttonHold.start();
      }
    }
  }
}

This also demonstrates the callback on the release of the button. The Timemark class hides all the time intervals, expire calculations, etc.

Cheers!


Windows 10 does not recognize Arduino Leonardo Using Arduino Leonardo, IDE 1.8.9, Windows 10.

For a short time, when I first got the Leonardo, Windows 10 would recognize the board; I could see it in devices, Windows 10 would make a sound when plugged in, it would show listed in the ports of the IDE, and I could upload my code to the board (confirmed with blinking light sketch). It no longer does.

The error I get in the IDE avrdude: butterfly_recv(): programmer is not responding.

I believe the main issues stems from I had selected Arduino UNO (I have a couple of those as well) in the IDE and Uploaded my sketch.

Ever since I did this, Windows 10 no longer recognizes the board when plugged in. It doesn't even show in "other devices" under device manager.

I have tried the following:

The on-board reset trick that seems to be most of what other users experience and solves their issue. All variations. Holding the reset button, uploading, releasing, etc.
Swapping cables. Confirmed with another device it was a data cable and working.
Uninstalling and reinstalling the IDE
Restarting numerous times
Burning boot loader - since Windows 10 won't recognize the device, this fails immediately can't even communicate to the board.

I have seen similar questions about this, but none of them seem to specifically cover what I am encountering.

Sounds like you've bricked it.  Your broken sketch (wrong MCU selected) means that it's not presenting a CDC/ACM port.

Your best bet is to use a hardware programmer (eg USBASP or another Arduino) to erase the chip and reload the bootloader.


Getting FFT arduino code to run over 9+ hours, utilizing micros() I am a beginner in Arduino, coding, and electrical engineering (learning on my own time) and am working on creating an EEG. I've got the hardware down and have managed to get numerical data output from the analog (A0) of Arduino. The next step is transforming these numbers to outputting dominant frequency and I have managed to find a code that uses FFT to find the dominant frequency from the input of A0. The following is the code:

#include "arduinoFFT.h"

#define SAMPLES 128             //Must be a power of 2
#define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

arduinoFFT FFT = arduinoFFT();

unsigned int sampling_period_us;
unsigned long microseconds;

double vReal[SAMPLES];
double vImag[SAMPLES];

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

sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
}

void loop() {

/*SAMPLING*/
for(int i=0; i<SAMPLES; i++)
{
    microseconds = micros();    //Overflows after around 70 minutes!

    vReal[i] = analogRead(0);
    vImag[i] = 0;

    while(micros() < (microseconds + sampling_period_us)){
    }
}

/*FFT*/
FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

/*PRINT RESULTS*/
Serial.println(peak);     //Print out what frequency is the most dominant.

for(int i=0; i<(SAMPLES/2); i++)
{
    /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

    //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
    //Serial.print(" ");
    //Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
}

delay(1000);  //Repeat the process every second OR:
//while(1);       //Run code once

}

The problem I have is with the line microseconds = micros(). The comment state that this will overflow after 70 minutes and after some days of research, I sorta understand what is meant by this. However, I need this program to run over 9 hours, so I can log the dominant frequency of the brainwave throughout the night. Is that possible?

Chris Do, there is indeed a rollover problem when micros is used that way. When that happens, the samples are taken at full speed without interval. That will create bad data for the FFT.
The solution is in the Blink Without Delay example. The magic to avoid a rollover problem is the substraction with two unsigned long values.

The arduinoFFT library is in the Library Manager of the Arduino IDE.
The example "FFT_03.ino" uses micros in the wrong way.

The next sketch shows how to avoid the rollover problem:

// Use micros() without rollover problem for a fixed sample rate
// for a certain amount of samples.

#define SAMPLES 128

unsigned long previousMicros;
const unsigned long intervalMicros = 1000UL;   // 1000 Hz is 1000 us

float vReal[SAMPLES];
float vImag[SAMPLES];

void setup() {
}

void loop() {

  previousMicros = micros();  // set the previousMicros just before entering the for-statement
  for(int i=0; i<SAMPLES; i++) {

    // A while-statement to wait.
    // Note that the ';' at the end means 'do nothing'.
    while( micros() - previousMicros < intervalMicros);

    // The 'previousMicros' is increased with a fixed number, for a fixed sample rate.
    previousMicros += intervalMicros;  // for next interval

    vReal[i] = float(analogRead(0));
    vImag[i] = 0.0;
  }

  delay(1000);
}

Take the current value of micros and substract the previous value of micros. The result of that substraction is a valid number, even during a rollover. It is the only way that always works.

The line to calculate the sample period has too many things in it that can go wrong. These lines:

unsigned int sampling_period_us;
sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));

In my example, I set the intervalMicros to a certain number. Could you do that as well? When everything works, you can try to calculate it.

Added: The answer by Edgar Bonet is exactly the same. That is no surprise because there is no other way.


Can arduino interrupts occur in a middle of if statement? I got an issues from few days, got some code which reset millis time on successful i2c communication, if not it restart an relay after specified period of time. Here is part of the code:

 if ((unsigned long)(i2c1Millis1 - i2cpreviousMillis1) >= i2cset1 )  // check if not restarted soon
        {

i2c1Millis1 are updated every run of the loop and on successful i2c communication.

i2cpreviousMillis1 is updated on successful i2c request (coming from interrupt)

I manage to debug when false restart occur and looks like i2c1Millis1 is lower than i2cpreviousMillis1

So question is: can an interrupt occur while those two millis are compared when value of i2c1Millis1 is taken for compare and then come interrupt where i2cpreviousMillis1 is updated to current millis and it become greater and trigger the condition?

(I already modified my code i2cpreviousMillis1 is updated with i2c1Millis1  value on successful communication to prevent that, but it is not working, from time to time it made false restarts).

Yes, an interrupt can occur at any time and can change the values during a calculation. And since you work with unsigned long variables (which are 4 bytes as I remember), it is also possible, that the calculation uses the old value for the first bytes and the new value for the other bytes, meaning that the used value for calcuation is totally garbage.

To prevent that your checks must either be atomic (meaning consisting only of 1 base instruction, which cannot be interrupted, e.g. handling only 1 byte) (that is not possible here), or you must prevent the calculation from being interrupted. For this you can turn off all or only the corresponding interrupt. To turn off all interrupts you can use noInterrupts() and interrupts() to turn them on again.

But it is questionable, why you need to update this time directly in the ISR. Instead you could only set an atomic flag (1 byte) and check this flag in the loop. If the flag was set, reset it and save the millis value. If you loop runs fast enough (which seems the case, since you already use it to set a millis timestamp) that should be sufficient

Both ways can be used and it depends on you, if it's ok to turn of interrupts for a short time, since you might miss an I2C interrupt this way.


How can I read this digital pin for Nano by using AVR's Atmel Studo? How can I read digital pin 6 in AVR?

I set the pin as input as follows:

DDRD = B0100000; //this will set pin 6 as input

But how can I now digital read this pin?:

Another way of putting it: how can I convert this Arduino code to be used in Atmel Studio?:

digitalRead(DATA_PIN);

Edit:

while (1) {

        unsigned long data = 0;//32 bit variable to store encoder data

        for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
        data <<= 1;//shift all read data left one bit
        PORTD &= ~(1 << 5);//clock pin goes low
        _delay_us(2);
        PORTD |= (1 << 5);//clock pin goes high
        _delay_us(2);

        data |= digitalRead(DATA_PIN);//cat the new read bit to the whole read data
        }

I want to use usual C code for AVR instead of using digitalRead above. data is an 32 bit array storing 25 bit encoder data. It is bit by bit filled by digitalRaed.

I think I found it:

while (1) {

        unsigned long data = 0;//32 bit variable to store encoder data
        uint8_t val;

        for (int i=0; i<25; i++) {//25 bit encoder data, first 12 bit is CCW count data and the rest 13 bit is the position angle data
        data <<= 1;//shift all read data left one bit
        PORTD &= ~(1 << 5);//clock pin goes low
        _delay_us(2);
        PORTD |= (1 << 5);//clock pin goes high
        _delay_us(2);

        if ( (PIND & (1 << PIND6)) == (1 << PIND6) ) {
            val = 1;
            } else {
            val = 0;
        }

        data |= val;//cat the new read bit to the whole read data
        }

Read the port state with PIND
Isolate the bit you want with &
Profit

if (PIND & 0b0100000) {
    val |= 1;
}

Or, as a ternary:

val |= ((PIND & 0b01000000) ? 1 : 0);


Weird formatting behavior with sprintf function I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.

But that line:

sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));

returns something like this:

3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)

It's suppose to return something like this:

3000;110;291;263;230;0;0;245

Here is my sketch:

int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;

volatile boolean interruptFlag = 0;
char read[45];
char signal[2048];
volatile int count = 0;
volatile long x = 0;

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

  noInterrupts(); // Stop interrupts.

  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.

  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)

  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);

  interrupts(); // Allow interrupts.
}

ISR(TIMER1_COMPA_vect){
  if (!interruptFlag){
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag){
    writeAnalogSignals();
    count++;
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  if (strlen(read) == 0) {
    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  } else {
    sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  }
  strcat(signal, read);

  x += 2;

  if (count >= 50) {
    Serial.print(signal);
    signal[0] = 0;
    count = 0;
  }
}

Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.

When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.

For a data rate of 50Hz, I suggest to raise the baudrate to 115200.

Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt.
See the BlinkWithouDelay example and use 20ms as an interval.


Why won't the slide switches control the motor in this 123d simulation? int guard = 7;
int switchPin = 6;
int motorPin = 9;

void setup(){
  pinMode(guard,INPUT);
  pinMode(switchPin,INPUT);
  pinMode(motorPin,OUTPUT);
}

  void loop(){
   if (digitalRead(guard==HIGH)&&digitalRead(switchPin==HIGH))              //&&

   {

     digitalWrite(motorPin,HIGH);
    delay(500);
    digitalWrite(motorPin,LOW);
    delay(1000);
   }
        else {

     digitalWrite(motorPin,LOW);
   }

  }

This should be written like this:

if ( digitalRead(guard)==HIGH && digitalRead(switchPin)==HIGH ) {

// Rest of the code..

}


CAN-Bus shield, SD-card module & LED_BUILTIN use D13; possible collision? To my knowledge the SeeedStudio CAN-Bus shield utilizes D13, and so does the SD-card module I use. And also Arduino Uno's LED_BUILTIN is 13. Am I in danger of some sort of collision here?

I have read this question, but that one describes situation where both modules are on a single shield.

Why I am alerted: I can perform following sequence: turn the LED on, open file, write, close file, turn the LED off, no apparent problem here. But when I connect my CAN-Bus shield to merely read messages (i.e. no sending data to the shield, not on purpose) my car behaves funny as if I still somehow managed to send some rogue bytes to the shield. (Right side windows and mirror are dead, infotainment display shows dead splash screen, dashboard complains about "engine malfunction" and airbags...)

I wonder if by writing to the SD-card and possibly turning the LED on I didn't send some bytes to the shield. Do I need to somehow Select Slave?

Yes you are in danger of a collision, how much danger I can't say, but the potential is there.

You could stop using the LED on D13?
Could you move the pins of your SD card reader, or get a different one that allows I2C or SPI interfacing?

I guess there is nothing that can be done to the CAN bus device, but if there is it might be a good idea to move its pins.


Problems creating 10Hz pulse wave I'm trying to make a 10Hz pulse wave output at Arduino's pin 9 by using the following code I wrote:

#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1); //Does this set port B pin 1 and is this pin 9 in UNO board?
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB |= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

I use Atmel Studio to uplaad the code and it works fine with other codes. But for some reason this code doesn't work. What can be the problem here?

Still doesnt work
edit:

#define F_CPU 16000000UL
#include <avr/io.h> //Defines pins, ports, etc.
#include <util/delay.h>

int main(void)
{

    DDRB |= (1<<DDD1);
    PORTB |= (1<<PORTB1);

    while(1){

        PORTB &= ~(1<<PORTB1);
        _delay_ms(100);
        PORTB |= (1<<PORTB1);

    }

}

You have your whole 100ms wait time while the pin is low.
You need half of it while low, half while high.

while(1){

    PORTB &= ~(1<<PORTB1);
    _delay_ms(50);
    PORTB |= (1<<PORTB1);
    _delay_ms(50); // You need a delay here too.
}


3.95 MCU Friend Arduino TFT LCD flickering I got the 3.95" LCD from aliexpress which uses IL9488. I used the MCUFRIEND_kbv library. I am using an Arduino Mega as I need other GPIO to be used for other purposes. I can't use the Uno because of this limitation.

I have other modules like the DS3231, and ESP8266 connected to the Mega and this 3.95" LCD connected as well. ESP8266 is powered separately using a 12-5V converted supply. The Mega is powered using another source. The normal graphics test is working in the LCD. I am able to make it work with the Nano, Uno and Mega. Even for the Mega I am able to write customized messages.

What I intend to do is to update the time in the LCD which is received from the DS3231. It updates the LCD but I see a flickering issue here.

Every update (LCD display function is from the loop which sets the text when there is a second/time/hour difference in the time) seems like it draining more current as the one of the LED connected to Mega dims, the Rx/Tx LEDs also dim.

I am able to get the LCD refreshed but it shows a flickering. I powered the LCD 3.3V and 5V using another separate source but still the small flickering continues.

Moreover all these time I was connected to the Mega through the USB from the laptop. Once I unplug the USB, LCD starts and shows some update and again become white. This continues and an not able to see anything on LCD there after.

I am not sure why only when the Mega is connected to USB this LCD works and that too flickering but once the USB is removed the LCD is not working at all.

Can someone please do help me in this ?

I think something is wrong with this LCD board. This is because in my case the display works sometimes perfectly with the ILI9481 driver but sometimes something hangs and the display starts to flicker. It looks like a chip charging problem. Anyway I solved the flickering problem by tuning the ILI9488 registers. Simply you have to change the initlcd.h for ILI9481 driver in UTFT library.

enter code here

case ILI9481:

LCD_Write_COM(0x11);
delay(70);

LCD_Write_COM(0x38);//Idle Mode OFF
LCD_Write_COM(0x13);//Normal mode

LCD_Write_COM(0x36); // Memory Access Control  crucial
LCD_Write_DATA(0x0A);

LCD_Write_COM(0x55);
LCD_Write_DATA(0x22);//High enhancment of CE ratio

LCD_Write_COM(0xB1);
LCD_Write_DATA(0x70);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB4);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB5);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x12);

LCD_Write_COM(0xB6);        // Display Function Control
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x21);       // 0x42 = Rotate display 180 deg.
LCD_Write_DATA(0x3B);

LCD_Write_COM(0xC0);
LCD_Write_DATA(0x1F);//0X1F
LCD_Write_DATA(0x01);//0X10

LCD_Write_COM(0xC1);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xC2);
LCD_Write_DATA(0x00);//0X44 lower better
LCD_Write_COM(0xC4);
LCD_Write_DATA(0x00);//0X10

LCD_Write_COM(0xC5);
LCD_Write_DATA(0x00);//0X10
LCD_Write_DATA(0x80);//optimum
LCD_Write_DATA(0x80);//0X10

LCD_Write_COM(0x3A);//Interface Pixel Format
LCD_Write_DATA(0x55);

LCD_Write_COM(0x2A);//Column Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0xDF);//320

LCD_Write_COM(0x2B);//Page Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0x3F);//480

delay(60);

LCD_Write_COM(0x29);//Display ON
delay(30);

LCD_Write_COM(0x2C);//Memory Write
delay(30);
break;


Using Arduino fix_fft or arduinoFFT library to filter some specific sound? I would like to know if there is a way to filter some specific sound using FFT on arduino. For instance, there is wind sound frequency in my analysis and I want to take it off. I searched for that a lot, but I didn't find something useful to solve this problem.

FFT is a tool for analyzing sound. It is not very appropriate for
filtering, unless you have loads of computing power to spare. And it is
even less appropriate for real-time filtering, if that is what you are
after.

Attempting to filter-out a noise based on its frequency is a reasonable
strategy for narrow-band noise, i.e. noise that lies in a narrow band of
frequencies. You can hope that, with some luck, removing this narrow
band doesn't affect too much the interesting part of the signal.

Alas, wind noise is very broad band, although it has more weight at low
frequencies:

(image source).

If the frequencies that interest you are above ≈ 2 – 4 kHz, you could
try a simple high-pass filter. Something like this should work even on
an Arduino if the sample rate is not too high:

static uint16_t filter(uint16_t input)
{
    static uint16_t sum;
    uint16_t delta = input - (sum >> SCALE);
    sum += delta;
    return delta
}

where SCALE is a small constant that determines the cut-off frequency.

Edit: The Z-domain transfer function of this filter is

H = (z − 1) / (z − u)

where u = 1 − 2−SCALE. Its cut-off frequency is then
approximately fsamp ÷ (2 π 2SCALE).


Can I set pin 13 to output 5v, then put arduino mini pro to sleep? Can I set pin 13 to output 5v, then put arduino pro mini to sleep and it maintains 5v going through pin 13 while in sleep mode?

I know there are various "levels" of sleep - can a voltage be maintained on a pin for all/any of the sleep modes?

Given the absence of clarity on the driving state of pins during sleep, consider connecting Pin 13 to an SR Latch or the gate of a MOSFET.

An SR Latch will hold it's output high or low until a high is presented on the Set or Reset inputs, so connect Pin 13 to the Set input, with a pull-down resistor -- even if the MCU in sleep mode allows the voltage output to drain away to 0v, the SR Latch will maintain it's output.

A MOSFET gate has a non-trivial capacitance which can hold a charge if the gate's driver goes high-impedance, thus holding the gate open after the driver is disconnected.


How to deal with this array correctly? I am using a led strip WS2812b, an ESP8266 (NodeMCU 1.0) and a gesture sensor APDS9960.
I want that when I move my hand from left to right and from right to left I change the colors of the strip of leds, previously saved in an array of strings:

const char * colors [11] = {"CRGB :: White",
"CRGB :: WhiteSmoke",
"CRGB :: CadetBlue",
"CRGB :: SteelBlue",
"CRGB :: Teal",
"CRGB :: SlateGray" ,
"CRGB :: MediumPurple",
"CRGB :: Purple",
"CRGB :: PapayaWhip",
"CRGB :: LightPink",
"CRGB :: Crimson"};

But when I'm going to turn on the colors using the functions of the FastLed library in this way:

for (int i = 0; i <NUM_LEDS; i = i + 1) {
       leds [i] = colors [2];
       FastLED.show ();
       delay (10);}

All I get is this error:

  invalid conversion from 'const char *' to 'uint32_t {aka unsigned
  int}' [-fpermissive]

I guess the problem is me when declaring the array, could someone help me?

You don't want an array of strings containing the (badly formatted) names of variables. Instead you want an array of 32-bit integers containing the values held within those variables.

const uint32_t colors[] = {
    CRGB::White,
    CRGB::WhiteSmoke,
    CRGB::CadetBlue,
    CRGB::SteelBlue,
    CRGB::Teal,
    CRGB::SlateGray,
    CRGB::MediumPurple,
    CRGB::Purple,
    CRGB::PapayaWhip,
    CRGB::LightPink,
    CRGB::Crimson
};

Since colours are just numbers, in the (hexadecimal) form of 0xRRGGBB you just store them as 32-bit unsigned integers.  The names you have there are just such (constant) variables used for easy reference (CRGB::White is 0xFFFFFF).


Arduino based small LCD screen with camera video capturing i have a idea to create a small screen which displays video recorded from arduino with camera. so camera will be back side of human and screen will be at near to eye. human can see the pictures from back side.

i have found https://electronics.stackexchange.com/questions/29139/processing-ntsc-video-feed-for-spi-display

but its not give me a clear idea. is there any one who can advice me for that kind project?

An Arduino doesn't have anywhere near the processing ability to transcode video from a camera unless you had an abysmal frame rate and very low quality. Even then, you would have to add extra storage because the Arduino would be over capacity in a heartbeat.

I recommend converting this project to a higher powered board like the Udoo. I have the Udoo Quad and it's beastly considering its form factor. You're going to need something a lot bigger than an Arduino!


Digispark ATtiny 85 - not recognised as HID device I am trying to create auto-username-writer with Digispark ATtiny 85. I have a pretty simple sketch:

#include <DigiKeyboard.h>
void setup() {
}
void loop() {
    DigiKeyboard.sendKeyStroke(0);
    DigiKeyboard.delay(100);
    DigiKeyboard.sendKeyStroke(76, MOD_ALT_RIGHT | MOD_CONTROL_LEFT); //ctrl+alt+del
    DigiKeyboard.delay(2000);
    DigiKeyboard.print("username");
    DigiKeyboard.sendKeyStroke(0x2B); //tab

    for (;;) {}
}

When I upload the code via Arduino IDE into the device (Board: Digispark (Default - 16.5MHz), it finishes successfully, it is recognised as a HID device and immediately performs all the tasks. But when I disconnect it and connect it again (to my PC or any other PC) it is recognised as Digispark Bootloader and does not do anything.

I have tried it in Arduino IDE 1.8.8 and in Arduino IDE 1.6.5 and I have no idea why it is only recognised right after upload. I have two ATtinys and both do the same behaviour.

Can someone help me, please?

EDIT:
I tried adding digitalWrite(1, HIGH); to detect, whether the sketch even runs and it turned out it does not even run (except after the upload)...

After five seconds, which is when the bootloader should switch to running your code, how does it show up in the list of usb devices (lsusb in Linux, Device Manager in Windows, etc.)

The original Digispark was a bit temperamental when plugged into USB 3 ports. If you are plugging it into one, try using a usb2 hub and plugging it into the hub instead.

Also, did you get this from Digistump, or is it a knock-off?


Arduino UNO reprogram the MEGA8u2 using external programmer As they say in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 you need to solder a 10k resistor in order to reprogram/reset the MEGA8u2 chip on Arduino UNO but sometimes you may lack the needed tools.

Is there a way to reprogram the MEGA8u2 using an external programmer or an another arduino as a programmer?

My idea behind this is to use the ISP LAYOUT for ATMEGA8U2 in order to load the correct bootloader:

Sure you can. Solder in a 6 pin header and you can program the ATMega8U2 using any Atmel hardware programmer. It's just a standard MCU, after all.  I'm not sure how the DFU side of things works - whether it's built into the chip in ROM or not1, but if it's just a bootloader in flash your programming may wipe it out stopping DFU from working in future. Not a problem if you can't get into DFU mode anyway.

1: The DFU is firmware stored in the "boot" region of the flash. As long as you don't erase or overwrite that region of the flash DFU will still function in future. Of course, you can also re-install the DFU firmware at any time you like.


Can I use these cheap GSM module with arduino? I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not.
Will you help me please?

Here are the link-

http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8

http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D70128bc79b60410d862b64d36cc479b3%26pid%3D100033%26rk%3D1%26rkt%3D4%26sd%3D281517486292

The SIM900A won't work in the UK, it's dual band.
The SIM800L is cheap as there is no power regulation on board. IIRC it requires 3.4V - 4.5V, min 2 amp supply. Check the data sheet to be sure.


No ttyACM0 with Pro Micro on Ubuntu 18.04 I am trying to determine the dev path of a USB keyboard running an Arduino Pro Micro on my Ubuntu 18.04 system. The files /dev/ttyACM0 and /dev/ttyUSB0 do not exist.

When I run dmesg I get:

[  410.770931] usb 3-3: new full-speed USB device number 3 using xhci_hcd
[  410.962180] usb 3-3: New USB device found, idVendor=feed, idProduct=3060, bcdDevice= 0.01
[  410.962184] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  410.962187] usb 3-3: Product: Dactyl-Manuform (5x6)
[  410.962189] usb 3-3: Manufacturer: tshort
[  410.962191] usb 3-3: SerialNumber: 0
[  411.006440] input: tshort Dactyl-Manuform (5x6) as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.0/0003:FEED:3060.0008/input/input27
[  411.063192] hid-generic 0003:FEED:3060.0008: input,hidraw0: USB HID v1.11 Keyboard [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input0
[  411.089097] input: tshort Dactyl-Manuform (5x6) Mouse as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input28
[  411.147172] input: tshort Dactyl-Manuform (5x6) System Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input29
[  411.147297] input: tshort Dactyl-Manuform (5x6) Consumer Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input30
[  411.147395] hid-generic 0003:FEED:3060.0009: input,hidraw1: USB HID v1.11 Mouse [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input1

Dactyl-Manuform is the keyboard so it seems to recognize the device. The command lsusb returns several usb devices. The entry with no title is the keyboard (based on doing watch lsusb):

Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID feed:3060
Bus 003 Device 002: ID 045e:02d1 Microsoft Corp. XBOX One Controller for Windows
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 1e7d:2c2e ROCCAT
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I have installed arduino and arduino-core from the official repos.

However, I still cannot get a ttyACM0 or ttyUSB0 to appear, and in the Arduino IDE the "Serial Port" option is greyed out (even when using sudo).

What can I check for to either 1) get the ttyACM0 file to exist for my Arduino device or 2) find some other dev port to use as the serial port?

A Pro Micro will only give a /dev/ttyACMx device node if the firmware installed on it creates a CDC/ACM interface.  That device obviously is running custom firmware which only provides the interfaces that the manufacturer wants to provide - in this case keyboard and mouse interfaces.

To use it as an Arduino you will first have to install the Arduino bootloader. That will then remove the existing manufacturer firmware, and you will have to write your own to make it act as a keyboard again.


I2C RTC returning bad times - sometimes I have a TinyRTC I2C clock in one of my Arduino projects, and it works most of the time. But occasionally, it will report the time as 165 hours, 85 minutes and 25 seconds (165:85:25) for a couple of seconds, then go back to the correct time.

I think this has got something to do with a fairly complicated I2C bus that I'm running: it has 12 devices connected to it (the clock, an LCD and 10 BlinkM LED programmable lights).

Here's what I've tried to debug, to no avail:

Replaced the RTC and battery
Replaced I2C pullup resistors
Redid the I2C wiring
Checked current draw of my project (.2A) and made sure the power
supply can handle that (it can)
Used 3 different power supplies in case I was getting noise

I think this is something to do with the I2C bus... the clock works fine when nothing much else is happening on the bus, but as soon as there's lots of activity (LEDs being sent messages, or perhaps other things) it starts reporting the time as 165:85:25).

Any idea how I could (a) isolate the cause of this problem; (b) get right to implementing a solution?

Such intermittent issue looks to me a hardware signal integrity problem, specifically around the I2C bus RTC chip. Did you experience any problem from any other device on the same I2C bus (e.g. when all the LEDs are on)? If not, then check on the noise level on RTC chip power and GND. Also, the I2C spec has limit on the bus capacitance load as max as 400 pF. When there are too many I2C device loads on the same bus, the bus may become vulnerable to the system noise.

Debug Suggestion: To narrow down if it is I2C load issue, add an I2C bus driver chip between the main Arduino board and your peripheral. For example, P82B96 from TI. See the spec here. http://www.ti.com/lit/ds/symlink/p82b96.pdf


Problem loading sketch to Leonardo Today I got Arduino Leonardo to replace my Uno. I've tried running one of sketches I use on the Uno, but with no luck. When I start the upload, RX LED on the Leonardo flashes few times, and after several seconds, L LED pulsates and I get this message:

avrdude: ser_open(): can't open device "\\.\COM9": The system cannot find the file specified.

avrdude: ser_send(): write error: sorry no info avail

I've checked in Device Manager, where it says that Arduino Leonardo is on COM3, and COM3 is also set in Arduino IDE.

However, when I change COM port to 9 in Device Manager and also in Arduino IDE and then try to upload the sketch, things start to roll out like above, but this time IDE freezes for 5-10 mins on "Uploading..." part, and finally unfreezes with this message:

Found programmer: Id = "B¨J"; type =
    Software Version =
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

Several more infos:

- OS: Win7 64-bit
- Arduino IDE: 1.0.5-r2
- Other serial devices: Only Bluetooth that I've manually assigned to COM200, to avoid possible conflicts.

Per imjosh's suggestion, I've installed IDE version 1.5.7 BETA and that solved my problem.
Thanks!


Not able to send SMS to Mobile using GSM900A and Arduino Uno I tried the code shown below (found here)

void setup()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+919449835011\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Test SMS -Jay\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}
void loop()
{
}

I interfaced my GSM SIM900A module to the Arduino UNO (connections - GSM Tx to Arduino Rx, GSM Rx to Arduino Tx, GSM provided with supply (12V) using external adapter, GSM gnd to Arduino gnd).

I dumped the code into Arduino and then opened the Arduino IDE serial terminal. In the serial terminal, I get AT+CMGF=1AT+CMGS="+919449835011"Test SMS -Jay\r being displayed and I am not receiving any sms to my phone. I am not sure if its a problem with the code or connections.

looks like you should be using Serial.begin(2400);

also, I'm assuming your sms phone number isn't actually 919449835011 and that that's not actually the number you used in your code


Servo Program Questions Hi programming in arduino, I am trying to get a nested for loop inside a for loop with industrial servo which used PUL +- DIR+- (bought motor off amazon).

My goal is to get the puls delay to increase. I have a sensor attached that I want the servo to turn on when triggered.

So the sensor will get triggered and the the servo will start off fast and get slower up to 255 micros second delay.

example:

int sensor = 26;
int PUL = 23; //define Pulse pin
int DIR = 25; //define Direction pin

void setup() {
  pinMode(sensor, INPUT);
  Serial.begin(115200);
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
}

void loop() {
  int sen = digitalRead(sensor);
  if (sen == HIGH) {
    Serial.println("HIGH");
    delay(1000);
     for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}
  } else if (sen == LOW) {
    Serial.println("LOW");
    delay(1000);
    } else {
    Serial.println("ERROR");
  }
}

EDIT

I am trying to nest a FOR loop inside a FOR loop What I want to do is get x to increase with i until x is 255 then I will continue unit i reaches 500. Right now x goes 0-255 and then i increase by 1. I need the value of x to increase along side with i until 255

for (int i=0; i<500; i++) {
  for( int x=0; x<255; x++){
  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }
}

Do you want i and x to increment at the same rate 0-255 then x to remain 255 while i increases to 500?

this should do what you want. i and x increase together until x reaches 255 then it wont increment.

int x=0;
for (int i=0; i<500; i++) {

  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }

   if(x<=255){
        x++;
   }

}


Why do I need to include libraries used in other libraries? I have a simple library which uses another library.

Here is the header:

#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <HardwareSerial.h>

class DerivedClass
{
private:
    HardwareSerial* serial;

public:
    DerivedClass();
};
#endif

And the CPP:

#include "DerivedClass.h"

DerivedClass::DerivedClass()
{

}

And the sketch:

#include <DerivedClass.h>

void setup()
{
}

void loop()
{
}

This works fine.

However, if I change the library header to this:

#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <SoftwareSerial.h>

class DerivedClass
{
private:
    SoftwareSerial* serial;

public:
    DerivedClass();
};
#endif

The sketch fails to compile:

  /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
  error: ISO C++ forbids declaration of 'SoftwareSerial' with no type
  /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
  error: expected ';' before '*' token

If I change the sketch to:

#include <DerivedClass.h>
#include <SoftwareSerial.h>

void setup()
{
}

void loop()
{
}

i.e. including the SoftwareSerial library in the top level sketch, it compiles fine.

If I expand the library out so it actually performs actions, then if it compiles, it works.

Why is this? HardwareSerial is a built-in part of the Arduino, located in hardware/arduino/cores/arduino and SoftwareSerial is in libraries, but why would the build process differentiate between the two.

If I remember correctly this is in fact a limitation of the Arduino IDE.

If you use a better IDE (personally I use Eclipse with the Arduino plugin) it works as it should, i.e. if you include a library A that includes another library B, then in the end you won't get compile-time errors and both B and A will be included in the final binary.


7 Segment Display SET UP I am new to Arduino.
I have been trying to connect a 7 segment display (3 digits) to my Arduino and I was successful, but I am not doing any connection to ground. I do not find the data sheet so I am not sure if this connection is well done.
My doubt is: Is the connection to ground necessary? Or how do Arduino pins work? I am using 12 pins of the Uno to do the set up.

Thanks

My set up is the following:

I don't know exactly how your display is wired exactly, but it is certain that some sort of multiplexing is going on, since A: there is no wired ground, and B, you are controlling more LED's than you have pins going to the display.

Multiplexing manages this by using some trickery and persistence of vision. The pins for each part of the segment are all wired together. For example, the top segment on each of the three segments are all connected to one arduino pin. The common anode/cathode (depending on your specific display) for each of your three displays are wired separately however. Turning only one of the common pins on will cause only one display to function when the other pins set which segments are on. The micro controller then changes which common is active and what segments are on to illuminate the next character very quickly. It pulses between segments so quickly you cannot tell they are only on one third of the time each.

The wiring inside the display will likely look similar to this:
http://www.modd3d.com/articles/wp-content/uploads/normal-multiplexing-s.gif


Sending Multiple Information from BNO055 IMU to BridgeClient on Yun I have an Arduino Yun which is interfaces via I2C to a Adafruit BNO055 breakout board.

My Aim is to use Python Flask in conjunction with BridgeServer and BridgeClient to obtain the Sensor Information from the ATmega32u4 microcontroller to the Microprocessor and use HTML5 Server Side Event (SSE) to display live sensor information on Network interfaces.

I would like to show the Euler angles and Linear Acceleration values:

heading
pitch
roll
linear_accerlation_x
linear_acceleration_y
linear_acceleration_z

An Example of similar concept can be obtained from Smart Measuring Cup by Adafruit. However, in the code sketch the user sends only one value :

BridgeClient client;
....
client.println(volume, 5);

And at the Python Flask end the code opens up a socket and uses makefile() method to read value

def yunserver_sse():
    try:
        # Connect to YunServer instance that's listening on localhost.
        soc = socket.create_connection(('localhost', 5678))
        socfile = soc.makefile()
        while True:
            # Get data from server.
            line = socfile.readline()
            # Stop if the server closed the connection.
            if not line:
                raise StopIteration
            # Send the data to the web page in the server sent event format.
            yield 'data: {0}\n\n'.format(line)
            # Sleep so the CPU isn't consumed by this thread.
            time.sleep(0)
    except socket.error:
        # Error connecting to socket. Raise StopIteration to quit.
raise StopIteration

Instead of sending just one measured parameter how can I send all above mentioned 6 at the same time?

note

I tried using ArduinoJson library but I find it difficult to parse the JSON on the Python Flask end as readline() expects a \n at the end of the string.

Apparently the solution to my problem was a simple client.println() after my JSON was ready to be printed to the BridgeClient.

Snippet:

root.printTo(client); client.println();

where root is DynamicJsonBuffer from the ArduinoJson library. The client.println() would immediately print \n and this would be read by the readline() python code.


What's wrong with my codes/ My teacher gave us a performance output about doing a dancing christmas lights in tinkercad. But I don't know what to do about the codes. He left  an instruction to us about what to do. I follow it but the tinkercad keep telling that...
Sorry, it seems like your code has some errors.
Close
 In function 'void setup()':
13:5: error: a function-definition is not allowed here before '{' token
21:7: error: a function-definition is not allowed here before '{' token
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
 exit status 1

And here's the code that I've entered...
int ledPins[]={3,4,5,6,7,8,9,10,11,12};
void setup()
{
  for(int i =0; i <11; i++)
  {
    pinMode(ledPins[i],OUTPUT);
}
  {
  void setup()
    {
     for (int i=0; i <11; i++)
     {
       pinMode(ledPins[i],OUTPUT);
     }
  }
    {
      void loop()
      {
        int i = 0;
        while (i<10)

        {
          {
            digitalWrite(ledPins{i],HIGH);
            delay(100);
            digitalWrite(ledPins[i],LOW);
            i++;
                                }
                         }
                         i = 10;
                         while (i >0
                                {
                                  digitalWrite(ledPins[i],HIGH;
                                               delay(100);
                                               digitalWrite(ledPins[i],LOW;
                                                            i--;
                                                            }
                                                            }

And here's the instruction of my teaher for the codes...
6. Initialize variables
Use array to initialize variables.
Set ledPin as the name of the variable and initialize the Arduino pins that you’re going to use.
Never forget to end each statement with semicolon
7. Set all pin to output
Use function void setup ()
Create a for () loop for array manipulation.
Initialize the for loop with i=0; since we will start the dancing lights with all LEDs turned off.
Initialize the condition i<11; since we need to turn on the 10 LEDs.
Set the increment to i++ because we need to iterate until it reaches the last LED.
Configure pin using pinMode().
Place a curly bracket before and after the for loop and pinMode().
8. Create a loop
Use function void loop().
Create a variable, i = 0.
Use while() for continuous looping
First while() is used to run your light from right to left.
Second while() is used to run your light from left to right.
Place a curly bracket before and after your statement block
Never forget to end each statement with semicolon

I changed it, so it at least compiles.
int ledPins[]={3,4,5,6,7,8,9,10,11,12};
void setup()
{
  for(int i=0; i < 11; i++)
  {
    pinMode(ledPins[i],OUTPUT);
  }
}

void loop()
{
  int i = 0;
  while (i < 10)
  {
    digitalWrite(ledPins[i],HIGH);
    delay(100);
    digitalWrite(ledPins[i],LOW);
    i++;
  }
  i = 10;
  while (i > 0)
  {
    digitalWrite(ledPins[i],HIGH);
    delay(100);
    digitalWrite(ledPins[i],LOW);
    i--;
  }
}


Not able to upload any code to Arduino Uno NOTE: Using the Arduino Uno

I am WORKING on a project that I have to submit in a few days. My arduino was all set up and was working fine.

Project:Arduino controls a 9v motor depending on the command given. As the arduino only provides 5v , i added a 9v battery to it through a transistor

I decided to add new code into the arduino but when I tried it failed. I have uploaded code thousands of times before (successfully) all of a sudden the IDE keeps giving the following message

  avrdude: ser_open(): can't open device "\.\COM3": Access is denied.

I have looked up for a lot of solutions on this forum and elsewhere. Here are the things I have tried so far:

Changing the COM port
Disabling all the other devices CONNECTED to COM
Tightening the CONNECTIONS
Re installing all the drivers and the IDE
Rebooting the system
Using another laptop to upload code

All the above have given me the same output for some reason. The built in LED light and the power LED switch on when the board is CONNECTED to a power source (my laptop). Could the board have been damaged by any chance ? How can I check if the board is spoilt ? Should I buy a new board ?

I have a post Have I bricked my Arduino Uno? Problems with uploading to board - that describes various tests you can carry out to isolate where the problem is.


Can I program a 20MHz Attiny85 with the 8MHz Internal Clock option in the Arduino Software? I'm looking at using the ATTiny85 for a project, but have run into a snag. After following the tutorial found at https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide, I've installed the necessary files to be able to program an ATTiny85; however, the options given under "Clock" are 1MHz and 8MHz internal, as well as 8, 10, and 20MHz external.

Normally this wouldn't be a problem, except Digikey has no in-stock 8MHz flavored devices in the package I need (SOIC-8, don't have a reflow setup to use the QFN package).

If I buy the 20MHz version, will I be able to program them with the Arduino IDE set to the "8MHz Internal" clock option?

I think you have the wrong end of the stick here. The Attiny85 is not a chip that comes in different speed versions. The datasheet mentions that it can run at 20 MHz. That doesn't mean you can buy a "20 MHz version". By selecting the appropriate clock option in fuses you can run at 20 MHz (or higher). From the datasheet:

  High Frequency PLL Clock

  There is an internal PLL that provides nominally 64 MHz clock rate locked to the RC Oscillator for the use of the Peripheral Timer/Counter1 and for the system clock source.

  I believe these to be pre-set from the factory for the various clock options - but will it matter when I try to program them with the Arduino software?

That list is weird, it doesn't specifically say they are pre-set to any speed. Personally I would regard that list as meaning that the higher speed ones are manufactured to better tolerances, if indeed it means anything at all.

Maybe when they manufacture them they do a quick test at various speeds, and ones that don't run at 20 MHz are put into a different batch.

The datasheet specifies the default clock settings, it would be weird if Atmel made them with different settings unless you placed a massive order.

As for programming them, by default they don't come with a bootloader, so you would need to use ICSP programming anyway. You would need (in any case) something like the AVRISP device (which connects via USB to your computer, and the other end goes to your chip to be programmed). Or you can make up something like my AVR hex programmer which lets you put a hex file from the IDE onto a MicroSD card, and then use that to program the ATtiny85.

In all of these cases you can change the fuses to do what you want, including the clock options you prefer.

There is a board you can buy which is a pre-made gadget using the code I mention above, where you just press a button and the chip is programmed, which would be helpful if you are doing a lot of them.


Using ALL the analog pins on Mega for Servo I wish to use ALL the Analog pins on a Mega2560 R3 to control Servo's, all is well up to and including A9, but from there on nothing. {sound familiar} this is apparently not a new problem. I have tried Servo.h and MegaServo.h but still no luck, does anyone have info on a library that will do this or a method to get around it........all the pins on the end buss are used for other purposes and are not available. I can post the code, but first just asking the general questions. Thanks Doug

OK..Solved...tried a library I had previously discarded for another project but it works with this situation..SoftwareServo ....(had also tried versions of Servo and MegaServo with no luck) I have attached a proven sketch that shows the method using arrays (as i have 16 servos to control) hope this is of use to others.

    /*This sketch will enable you to use ALL of the Analog pins on a Mega2560 to control a Servo
 * it uses the Arrays and the Softwareservo.h as the other Servo libraries do not support
 * Mega Analog above A9
 * this is the only method i have found that works
 * hope this is of use to others.
 */
#include <SoftwareServo.h>

SoftwareServo servos[16];  // create servo object to control a servo

int pos=0;
int servoPins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,A14,A15};                    //servo pin numbers
int servoPosMin[] = {80,80,80,80,80,80,80,80,80,89,80,81,80,70,80,45};                        //servo lower setting to suit individual servo
int servoPosMax[] = {100,100,100,100,100,100,100,100,100,100,100,100,100,110,100,160};        //servo upper setting to suit individual servo
boolean refresh = false;  // toggle refresh on/off
int m = 0;
int p = 0;
void setup()
{
  Serial.begin(115200);
  for (m=0;m < 16;m++) {
      // attaches the servo on pin to the servo object
    servos[m].attach(servoPins[m]);
      // init angle of servo inbetween two limitations
    servos[m].write(((servoPosMax[m]+servoPosMin[m])/2));
    Serial.println(m);
    delay(10);
      SoftwareServo::refresh();
  }
}
void loop()
{
  for (p=0;p < 16;p++) {

    for (pos = servoPosMin[p]; pos <= servoPosMax[p]; pos += 1) { // goes from 0 degrees to 180 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
  }
    for (pos = servoPosMax[p]; pos >= servoPosMin[p]; pos -= 1) { // goes from 180 degrees to 0 degrees
      servos[p].write(pos);                                       // tell servo to go to position in variable 'pos'
      delay(15);                                                  // waits 15ms for the servo to reach the position
      Refresh();
    }
  }
}
void Refresh() {
  refresh = refresh ? false : true;                             // set refresh one time / 2
  if (refresh) SoftwareServo::refresh();
  Serial.print("Servo Number = ");
  Serial.println(p);
  Serial.print("  Angle =  ");
  Serial.println(pos);
}


How to connect HC-06 BT module without pins? So, from one popular Chinese  store I ordered a HC-06 module that I received... and due to some mistake from a store, I received a HC-06 without connecting pins. So usually HC-06 looks like this (with blue plate underneath where 4 pins are available to solder or connect):

I just received the one without this blue plate and pins:

How do I connect it to Arduino if there are no pins? Where are usual GND, TX, RX pins (is this schematics correct?)? Is it okay if I just solder a wire to some of them without this blue under-plate?
Also do I need to add some resistors or other components if I connect wires directly to these half-circle pins?
Thank you!

The small green PCB is the real HC-06 board. The blue board has 2 functions:

It breaks out the contact pads of the HC-06 to the bigger pins.
It has a voltage regulator on it so that you can provide it with 5V power, which then get's converted to 3.3V for the HC-06 (which is a 3.3V device).

The next steps depend on what Arduino board you have:

If you have a 3.3V Arduino Board, you can directly connect the pads on the HC-06 (by soldering pins or wires to them) to the corresponding Arduino pins:

Arduino <--> HC-06
  3.3V  <--> 3.3V
  GND   <--> GND
  TX    <--> RX
  RX    <--> TX

Also you can connect a fitting LED to the LED pin. I spontaneously cannot find data about the max current of this pin. But I guess it is in the range of 10 to 20 mA. Use a corresponding combination of an LED and a resistor.
If you have a 5V Arduino, you need to consider the voltage difference. On the Uno and Nano you have a 3.3V regulator on board. The regulator itself is rated for 150mA, but since it is not cooled, the limit is more like 50mA (see this forum thread). This datasheet of the HC-06 states, that it draws at max 30-40mA, so you can get away without an extra 3.3V regulator, just by connecting the both 3.3V pins on Arduino and HC-06. If the voltage regulator overheats despite being under 50mA, you need to buy an extra 3.3V voltage regulator, that can handle the current.

Don't forget to use a voltage divider on the Arduino-TX --> HC-06 RX line to divide the Arduinos 5V down to 3.3V. This line isn't even regulated by the blue breakout board, so you would need this voltage divider either way.

Ground connection and the LED are the same as in the first case.

So all in all you can still use the HC-06, just with a little bit less ease than with the blue breakout board.


Arduino-like boards with other microcontrollers Are there any Arduino-like board designs that are NOT using an AVR chip, but perhaps a chip like the Z80 or the 6502?

You have to define what you mean by "Arduino-like" beyond just not using an AVR.

There's the Arduino Galileo using an Intel chip and supports the Arduino development tools, as well as the Arduino Due which is an Arm-based chip.

There's the Netduino which uses ARM chips (STMicro's) and is pin compatible with Arduino shields, but I don't know what the development framework is (other than it being in .NET), though this doesn't necessarily say much because not even all Arduino boards have the same pin compatibility (Nano boards are much smaller, LilyPad Arduinos which are round and semi-flexible, etc.)

Then there are related boards, but don't support the Arduino environment or any pin compatibility (TI Launchpad springs immediately to mind, but pretty much every manufacturer has some sort of demo board or development board for their MCU's).

There's a huge list of Arduino-like boards here (split into levels of compatibility, includes the official Arduino boards).


Establishing wireless comm. between PC and arduino pro micro to exchange speech and gyro data I have a client project to make a wireless head-mounted mouse. What wireless module should I use so that I can exchange data between my laptop and the arduino pro micro through the USB port like a wireless mouse? I am using an MPU6050 accelero+gyroscope sensor for cursor movement and Electrohouse Voice Recognition module V3.1 for speech recognition. To exchange such data between PC and arduino, I found a lot of options. Hence, I am confused. Please help me decide what to use so that cost efficiency and effectiveness can be acheived. Should I use bluetooth, RF shield , XBEE or any other module?

The wireless medium you choose is largely irrelevant.  The important thing to realise is that it's not (in most cases) the wireless medium that is communicating with the computer.

Most wireless mice use the nRF24L01+ (or rather the integrated SoC equivalent) to communicate. They use a USB dongle plugged into the computer for that communication. The computer has no clue what an nRF24L01+ is, but it does know what a USB mouse is. So there is a microcontroller in the dongle which receives data from the nRF24L01+ and interprets it, and sends the right instructions over USB to make the computer think it's a USB mouse.

What the data is that's sent over the wireless, and exactly what form that wireless connection takes, is completely irrelevant as far as the computer is concerned.  In general one if the SoC equivalent to the nRF24L01+ (such as the nRF52810) is chosen because it's a single chip solution with a simple to use wireless protocol, which makes for cheap and easy development and implementation.

The only exception to this general rule (and there is always an exception to every rule) is Bluetooth. This is because there is the concept (as far as the computer is concerned) of a Bluetooth mouse. So it is possible, using the right Bluetooth adaptor on your Arduino, for the computer itself to see the Arduino as a Bluetooth mouse. This can be harder to implement using small microcontrollers, but results in a potentially lower cost solution with fewer components.

The simplest solution for you, though, is probably:

One Arduino that has a native USB connection (Pro Micro, Leonardo, etc - anything ATMega32U4 based)

This will be connected directly to the computer and programmed to emulate a USB mouse

One Arduino that best suits your sensors (probably doesn't really matter what for this. Mini? Micro? Nano? Uno? They would probably all do fine).

To this you attach your sensors, your voice recognition, etc.

A pair of wireless connectivity modules of some form

I'd recommend the nRF24L01+ - simple to use, has a very convenient packet-based protocol, cheap, and there's plenty of examples and libraries out there.  These are connected to both Arduinos and are used to communicate between them.

Then it's up to you to decide what information gets sent between the Arduinos to make the one connected directly to the PC send the right mouse movements.


Sketch is not being received by Arduino even though Arduino Editor acts like it is finished? In my attached screen capture the Arduino Editor appears to be performing the upload, however it never finishes. Completes three steps, the last being the sketch up-load and then states that it is busy.  Sorry that I can't submit a short video. Please suggest ideas to solve this issue.  Maybe this is related to my first question?

Thank you to all who have suggested corrective action for my posted communication problem. After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor. Next I installed the Arduino Create Editor as a fresh/new install. Magically, all of my communication issues with the Arduino Uno have been corrected. Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.