text:
Use timer0 without affecting millis() and micros()
I'm writing a library which needs an ISR to turn off an LED some time after it was turned on. Since it's all about turning an LED on and off it doesn't need to be very precise. On the other hand I would like to use this library in a program where timer1 and timer2 are given out to other (more important) tasks, and I also need the millis() and micros() functions. Last, I'm using an ATmega328P microcontroller, which only has 3 timers (and I can't easily replace it with another one).

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions, and – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...) and the disadvantages or side effects in using this timer in a non-Arduino library and the Arduino millis() and micros() functions.
Thanks in advance for any answer!

Why do you feel you need to use an interrupt for such a simplistic and not time-critical operation?

I fact I'm currently using a 'checkLed()' function, and it works fine. But 1) the program main loop is sometimes quite long (e.g. sometimes it has to execute other loops), and it were easier for me if I didn't need to care about turning off the LED (which is not time-critical but quite important), 2) now I'm quite curious about this question in general ;)

Fair enough. TBH I have just been writing a routine that does exactly that, but on a different MCU that has a different timer structure (it controls the TX and RX LEDs to indicate USB activity - RX interrupt and TX functions turn the LEDs on, timer turns them off 50ms later), so I can understand the need.

Related: Atmel / Arduino: ISR(TIMER0_OVF_vect) won't compile (“first defined” in __vector_16) (providing your own handler for Timer0 and still use the Arduino environment).

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions,

Yes. A few ways, depending on your level of comfort:

You can declare the stock Arduino Timer0 OVF "weak" and write your own where you can insert your ISR. But you have to handle the interaction between the millis() / micros() related variables.
You can modify the stock Arduino Timer0 OVF to insert your own ISR.
And – if that can be done – what would be the restrictions of such an ISR (e.g. I suppose I could not use all the timer/interrupt modes...)
The stock ISR would look like this:
ISR(TIM0_OVF_vect) {
    ...
    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

    //insert your isr here
    _mytmr0_isrptr();
}

Where _mytmr0_isrptr() is a function pointer to your own ISR handler.
The simplest is probably to use the output compare interrupts. You can get it to behave like a virtual timer and can do lots of other stuff.

Obviously, you can think of tons of other ways and this is just a starting point.

What are those interrupts? How can I use them? –

Timer0 has three interrupts associated with it: overflow and compare channel A and channel B. The overflow interrupt is already being used by the timing functions millis() and micros(), as shown earlier.
The compare channel A/B interrupts are unused. And this discussion is about using them for timing purposes.
The general ideal is demonstrated in blog post Using Spare Output Compare Channels as Timers – the Collection.
The task there is more complicated than what you are trying to do here, but the basic ideal is the same. To do what you wanted here it is much simpler than that.
If you still cannot figure it out, I can provide you with code pieces to get you started.

Sorry, i didn't understand the third option... What are those interrupts? How can I use them?

Thank you, now I got it! I've implemented it in my library and it works.

I'm glad you have a solution that works for you. The key here is to recognize that output compare is essentially a timer: it generates an interrupt on match, vs. Timers doing so on overflow or underlie.

Once you recognize that you can make a lot of virtual timers out of output compare channels . for most mcus that means 2x to 8x virtual timers per hardware timer.

I think the first solution suggested by dannyf's answer is wrong as ISR in AVR GCC can't be defined as weak function (why).
I think the best solution is to add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.
More about this trick in this article here.

An interrupt can only have one interrupt service routine. The only way you can do something else using an interrupt that is already handled elsewhere would be to modify that existing interrupt handler to also call your code. Not something that is practical for a library.
I can see no practical way of doing it short of modifying the entire millis() system in the main API to allow hooking of callback functions, which would be a really nice facility (chipKIT has a similar system with the Core Timer interrupt on the PIC32) and submitting it back to Arduino for inclusion in the main core - which would set a baseline version for compatibility of your library of course.

And there is no way to kind of override the ISR of the millis system without modifying the API files, right?

Correct. If you define a second ISR you will get vector conflicts. You will just have to decide on another interrupt to use. Some libraries provide #define macros etc to select which timer to run with.

So I was wondering if I could attach an ISR to timer0 without affecting the above Arduino functions ...

No, because those functions use an already-attached interrupt.

it doesn't need to be very precise ...

Just test for the current time (eg. using millis or micros) in your main loop.

the program main loop is sometimes quite long (e.g. sometimes it has to execute other loops) ...

Restructure so that it doesn't do that. You can use the state machine concept to do things from time to time, without getting stuck in inner loops for a long time.

It's not possible with TIMER0_OVF interrupt, but there are also TIMER0_COMPA/TIMER0_COMPB interrupts and these should be free to use. Only downside is that analogWrite on corresponding pins moves the time when the interrupt happens.

@KIIV So using timer0_compx I couldn't use analogWrite on the corresponding pin any more?

@noearchimede You can. Just the interval will move according to that. But if you don't need precise timing, it won't be a problem. Just for sure you can test all PWM values just to be sure it's working everytime.

@KIIV I've just written a new version of my library using TIMER0_COMPA and it works exactly as I wanted.May I ask you to write a complete answer with your suggestions, so that I can mark the question as answered?

@noearchimede It's already here in dannyf answer (third option)

@KIIV Yesterday I didn't understand his third option so I forgot it, but now it is clear to me. Thanks to you and all those who answered!


text:
Arduino, Serial and wrapper class
I am working on an Arduino project, that would use HardwareSerial object reference stored in a class and call methods on it. However, there is problem with writing output using the reference.
Minimal use case to demonstrate behavior is in following files:
main.ino
#include <Arduino.h>
#include "testclass.h"

TestClass testClassInstance(Serial);

void setup() {

}

void loop() {
    testClassInstance.print("Hi There\r\n");
    delay(1000);
}

testclass.h
#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <Arduino.h>

class TestClass {
public:
    TestClass(HardwareSerial &serial);
    void print(const char * text);

private:
    HardwareSerial _serial;
};

#endif

testclass.cpp
#include "testclass.h"

TestClass::TestClass(HardwareSerial &serial) : _serial(serial) {
    _serial.begin(9600);
    _serial.print("Initializing\r\n");
}

void TestClass::print(const char *text) {
    _serial.print(text);
}

After reset, there are only two characters sent: "In"
In the example above, initialization is done before setup() method and Serial's state is probably reset before calling it. Having changed that to dynamic allocation in setup method did not change this behavior as well.
modification of main.ino
TestClass *testClassInstance;

void setup() {
  testClassInstance = new TestClass(Serial);
}

There might be problem with passing the reference to Serial, but in that case I would expect to not have any output at all.
Any help is greatly appreciated.

You can't do complex tasks (or anything that relies on the Arduino API in any form) in your constructor. Simply because that all gets called before the Arduino API initializes, and in so doing the serial port gets disabled.
Instead you should do your complex operations and API-based operations in .begin(), which is why 99.99% of all libraries (including HardwareSerial) have a .begin() method.

This looks reasonable. Does begin() method exist in main file next to setup() and loop() functions? Or does it have to exist on my wrapper class and be manually called in setup()? Additionally, is there some manual that specifies how Arduino API is initialized and what happens then, so I could RTFM? :)

.begin() is a function you must write in your class. The user then calls it from setup(). No, I am not aware of any generic documentation - simply because it is different for every core. Just assume that nothing bar setting some variables / flags can be done in the constructor - that's the safest way.

I have debugged deeper and the problem was somehow passing HardwareSerial to constructor as parameter with HardwareSerial &serial.
When changing it to pointer HardwareSerial *serial and using access via pointer-type variable, everything works.
Many thanks for suggestions.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Arduino Mega, PWM analogWite doesn't work with Timer interrupt
Can anybody explain me, why the PWM doesn't work in such a simple example?
Generally, Timer interrupt is being called once per 100 ms and then in the interrupt function the bool flag (state ) is being set. Then in the main loop the flag is checked and when it is 1 (true) several instructions are being executed. Next, PWM is generated and measured via ADC and also displayed on the LCD.
The problem is that the PWM is generated as 0 or sligthly over the 0, even when the value put to the  analogWrite is 255 (max of 8 bit). Variable counter is incremented without problems and this value is being put to the analogWrite and despite it the PWM doesn't work.
I don't know, totally, what can be wrong.
Can anybody help me?
 #include<LiquidCrystal.h>
 #include<TimerOne.h>

  LiquidCrystal lcd(52, 50, 48, 46, 44, 42, 40);

  int out = 12;
  int in = A7;
  volatile bool state;

  int counter = 0;
  volatile int y;

  void setup()
  {
    lcd.begin(16, 2);
    lcd.clear();
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    analogReference(DEFAULT);
    Timer1.initialize(100000);
    Timer1.attachInterrupt(functionInterrupt);

     state = 0;
      y = 0;
   }

   void loop()
   {
     y = analogRead(in);
     y = y / 4;
     y = y - 128;

    if (state == 1)
    {
      state = 0;

      counter++;
      if (counter > 255)
      //counter = 0;
      counter = 200;

      //state = 0;
     }

      analogWrite(out,counter);

      lcd.home();
      lcd.setCursor(0, 1);
      lcd.print(counter);
      lcd.setCursor(12,1);
      lcd.print(y);
     }

    void functionInterrupt()
    {
      state = 1;

     }

When you use a timer to generate an Interrupt Service Routine (as you do with the TimerOne library) you change the configuration of that timer (in your case timer1). The timer is used by the TimerOne library to provide an interrupt, but also by the microcontroller itself to produce a PWM signal on some pins depending on the timer: in your case (Arduino Mega, timer 1) on the 11 and 12. If you use one of these pins as "analog" output while controlling an ISR with the same timer you won't get the expected output, because the timer isn't any more configured as needed by the PWM generation mechanism but as needed by you (you changed the configuration of the timer in the Timer1.initialize(100000); function call).

So, either you use another PWM pin as output either you use a timer library which uses another timer (or you implement it by yourself).

I just edited my own answer because as I wrote it I didn't notice you (the OP) were using an Arduino Mega board (you only wrote it in the title, and I didn't pay much attention to it... sorry)

noearchimede, I'm really thank you. You're right. I didn't consider it and have wasted much time trying to solve it. Thanks.

if (state = 1)

This is setting state to 1, not testing if it is equal to 1. In other words, it will always be true.

Nick Gammom, you're right but this is not that. It was just my typo mistake when I was translating variable's names from my native language to english. In my real code I had "if(state == 1)". But anyway, thank you for your respond.

Can you correct your question then? As it is, it is misleading. It is also misleading to post code which is not the problem code in the first place.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
I bought ATmega328p with bootloader and I can't erase it
I bought an online deal which had 10x ATmega328p with bootloader installed. I thought I can erase the bootloader once I got the order (I want to write custom task without a bootloader) but my programmer does not seem to find the ATmega328p. I know it is the problem of the microcontroller because I have another ATmega328p which works fine and I can upload code to it. Is there a flag or switch I am missing when trying to overwrite the bootloader on the microcontroller?
Here are the components I am using:

ATmega328p with bootloader
SparkFun Pocket AVR Programmer (usbtiny)

Here are the commands I am using:

To compile: avr-gcc -std=c11 -mmcu=atmega328 -O -o main.o main.c
To generate hex: avr-objcopy -O ihex main.o main.hex
To upload: sudo avrdude -c usbtiny -p m328p -U flash:w:main.hex

Here is the output of the avrdude command:
avrdude: Using SCK period of 10 usec
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Anyone encountered similar situation before? How did youu managed to fix it? I appreciate any help :)
Thank you
Edit #1 I tried setting the -B flag to various values but nothing seems to solve the problem.
Edit #2 Here is the circuit I am using while programming the ATmega328p

2x Capacitors 22pf
1x Crystal oscillator 16Mhz
1x Resistor 10K ohm
1x ATmega328p
1x SparkFun Pocket AVR Programmer

Maybe you need to provide a specific clock input to the chip...

Thanks @Majenko for your comment, I should have mentioned that I tried using the -B flag with low, medium and high values but nothing did work

This is almost certainly not a bootloader problem but either a programmer, wiring, power, clock, or fuses one.  Or you could have switching power supply chips re-printed to look like ATmega328p's (though those were QFP, and I suspect yours are DIP).

Your post should include a schematic diagram of how your powered and clocked these.  Would also be good to include a photo of the chips themselves.  Have you tried this process/programmer with any chips from a reputable source yet?

@ChrisStratton thanks for your suggestions, I added an image showing the circuit I am using.

Your connections to the ATmega328p are incomplete.
You are missing the connection of ground to pin 22, and you must supply power to AVCC on pin 20.
You should also place the capacitors much closer to the crystal with a very direct route to ground, and try to place the crystal itself closer to the chip.
Additionally you should use supply bypass capacitors.
Please see the minimum wiring at Arduino on a Breadboard, however this document itself is erroneous as it neglects to show the high frequency 0.1 uF bypass capacitors you should have directly across each pair of power pins.
That's not to say that there may not be additional issues as well - but you need to fix the circuit problems first.

Thank you Chris for your answer, I will try your suggestions and will post an update

I adjusted my circuit as you mentioned and it worked! Thank you Chris +1


text:
Possible reason for broken Uno
Yesterday I wrote in a comment that I didn't break much, except a LED and a LED matrix. However, exactly yesterday I think my Uno gave up, since I cannot upload a sketch anymore (timeouts). For the rest the board seems to work still ok.
I have two possible reasons, and would like to know what I can do to prevent this in future. I connected a 415 MHz RF transmitter and receiver to it, which are working.

To get more power I attached an adapter (12V), TOGETHER with the USB ... I thought always adapter power would be used, but it seems it is not a good idea to have both connected. Is this true?
The Uno was inside a case (with holes near the output pins). I know this causes some extra heat, but I would guess that adding just an RF receiver/transmitter would not cause the Uno to heat up more than allowed.

Which of these reasons is the possible cause ... or are there any other reasons I didn't think off. Everything worked fine until I plugged in the 12V adapter and it still worked for some time (until I tried to upload a new sketch).

It is a mistaken belief that powering an Arduino from an external power source increases the power available. It doesn't. All it does is increase the amount of heat produced.
Unless you are powering your Arduino from an unpowered hub you will have around 500mA available from the USB power. The 5V regulator, which converts the incoming 12V to 5V, can supply at best between 800mA and 1A on a good day. However with 12V the amount of heat generated will cause thermal shutdown at those kind of currents due to lack of proper heatsinking. So you can't get anywhere near 800mA out of it - instead you are limited to around the same as (or even less than) the USB power source can provide.
All that excess heat (and at 12V you are throwing away about 58% of your power as heat) in an enclosed case will have caused nasty things to happen - at the very least your regulator should have gone into thermal shutdown. Worst case scenario your voltage regulator failed (especially if it's a cheap version) which would end with one of two scenarios:

No power getting through to the rest of the board
More than 5V getting through to the rest of the board

If it's (1) it'd be obvious - nothing works. No LEDs light, etc. However if it's (2) then more nasty things will ensue. One common one is that the ATMega16U2 chip (the USB interface chip) if it's a genuine Arduino will be fried. You may find it's getting excessively hot itself now. Of course, if it's a clone then the CH340G will no doubt have given up what little ghost it had.

So if I'm understanding right, 12V  is normally not a good choice unless the power is really 'used' externally (by LEDs or power hungry parts)?
I read that using more power could improve the RF range (which it did, but not that much).
Also if I understand right, it's not a good idea to power an Arduino with an adapter in an enclosed cage? I think that's not very comfortable.
Too bad probably the Mega chip itself is probably ruined, that would be the only useful part being salvaged, since it was an original DIP-socketed chip.

Your bog standard Arduino Uno / Mega is not really good with external power and enclosed spaces, unless you only draw small currents. RF tends to be quite power hungry, especially when transmitting, which will drive up your current use and thus your heat. You are better bypassing the on-board regulator with a 5V buck regulator (e.g., a model vehicle "UBEC") which produces far less heat and can provide about 10x the current.

Thanks for that info .. however, it disappoints me, I don't hope I need multiple power sources for my Arduino/RF when using RF. I was hoping I could handle everything with either a USB cable OR 12V adapter. How should I bypass it? By powering the buck regulator completely out of the Arduino with it's own power supply? I never used a buck or UBEC regulator.

Why not just a 5V USB power supply (phone charger) plugged in to USB?

Hmm maybe that's better, I would expect they sell typical Arduino adapters with 5V  ... going to search for them, that seems like a good way.Btw, I don't have to use buck regulators when I use a 5V adapter?

A buck regulator is a 5V adaptor. Just not necessarily in a fancy case ;)

Ah ok ... but I think I rather go for a dedicated adapter, otherwise I would need two power sources, one for the Arduino and one for the RF, and I like to have them both in the same case (preferably with one power plug)

You should be OK as long as you use a 9 to 12 volt supply since there is an FET that disconnects the 5 volt USB power from the rest of the Arduino circuitry if VIN is greater than approximately 6.6 volts.
But... if your external voltage is less than 6.6 volts you may have a problem since both supplies will be powering the Arduino circuitry and they probably will not be providing exactly the same voltage.  If you get below the dropout voltage of the voltage regulator then you may have a bigger problem since the USB voltage will be backfeeding the voltage regulator.
There is a diode between the PWRIN connector and VIN so if you feed the Arduino from that connector the voltage will have to be greater than approximately 7.3 volts to activate the FET and anything less than 7.3 volts may cause the problems mentioned above.

It was a normal 12V adapter, specifically for Arduino ... so I guess that should be ok. Seems the case was the problem. Which makes me more worried, since I wouldn't expect so much heat.

this link may be useful for you:                                                        http://www.technobyte.org/2016/08/core-subsystems-arduino-uno-power-supply/                                                                will update you if i found any other solution to your case.

Thanks for this link! I will have to go through it slowly

go through the  link :https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/


text:
Interfacing Logitech Joystick to Arduino and interrupt a while loop
I am working on a project of a robot arm. The joints are made of servo motor. The basic function can be describe as:

The robot arm (the servos) were moved manually by the Logitech joystick.
The user could press a certain button to remember a position. I made 6 buttons for 6 positions, in detail.
After the remembering, if an activating button was pressed, the robot arm would move repeatedly around those 6 positions until a stopping button was pressed.

The problem was the bold words.
In order to make the robot arm could move repeatedly with one pressing, I used a while loop.
However, when the program was in while loop, the joystick events stopped updating no matter how I pressed or pulled the joystick. Therefore, I couldn't program a stopping button.
I guessed that was because the joystick events were called outside the loop, but I don't know how to get it inside. My code was based on the example of the USB Host Shield library.
Here is the code. It contained 3 files. My robot also has some more function so I only quote the part that I had problem here.
.ino file:

#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include "le3dp_rptparser.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

//int waist_back, shoulder_back, wrist_back, gripper_back;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial);
#endif
  Serial.println("Start");

   if (Usb.Init() == -1)
       Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );

}

void loop()
{
    Usb.Task();
}

.cpp file: This was where I worked. Please look at the JoystickEvents::OnGamePadChanged
#include "le3dp_rptparser.h"

//Many parameters for robot here

JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
    joyEvents(evt)
{}

void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
    bool match = true;

    // Checking if there are changes in report since the method was last called
    for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
        if( buf[i] != oldPad[i] ) {
            match = false;
            break;
        }
  }
    // Calling Game Pad event handler
    if (!match && joyEvents) {
        joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

        for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
    }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
  Serial.print("X: ");
  Serial.print(evt->x);
  Serial.print(" Y: ");
  Serial.print(evt->y);
  Serial.print(" Hat Switch: ");
  Serial.print(evt->hat);
  Serial.print(" Twist: ");
  Serial.print(evt->twist);
  Serial.print(" Slider: ");
  Serial.print(evt->slider);
  Serial.print(" Buttons A: ");
  Serial.print(evt->buttons_a);
  Serial.print(" Buttons B: ");
  Serial.print(evt->buttons_b);
  Serial.println("");

  // Manual control program here. I didn't post because it was so long.

  //Activation

  if (evt->buttons_a == 32){
    while (evt->slider == 0){

    //Robot working here, also a long code that was out of limit for a block here.

    Serial.print(evt->slider);
    }
  }
}

.h file:
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__

#include <usbhid.h>

struct GamePadEventData
{
  union { //axes and hut switch
    uint32_t axes;
    struct {
      uint32_t x : 10;
      uint32_t y : 10;
      uint32_t hat : 4;
      uint32_t twist : 8;
    };
  };
  uint8_t buttons_a;
  uint8_t slider;
  uint8_t buttons_b;
};

class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
  static GamePadEventData mostRecentEvent;
};

#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

class JoystickReportParser : public HIDReportParser
{
    JoystickEvents      *joyEvents;

  uint8_t oldPad[RPT_GAMEPAD_LEN];

public:
    JoystickReportParser(JoystickEvents *evt);

    virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

#endif // __HIDJOYSTICKRPTPARSER_H__

After the //Activation under JoystickEvents::OnGamePadChanged, no matter how I pulled the slider of the joystick, the event was not updated, the evt->slider always returned zero and the robot arm couldn't be stopped.
Is there any method to update the joystick event inside the while loop?
Or another method other than while loop to make something move repeatedly after pressing one button, and can be stopped with another button?
Thank you so much for reading, and please help me!

As full code is not posted I cant suggest you correctly but you should add the two buttons, START & STOP.
When STOP button is pressed all events (your code is performing on) should stop working.
Just make sure when you program for a joystick control, the code for START & STOP buttons  should fall under the joystick control loop.
if (STOP PRESSED){

}else if(START PRESSED){

    //INVOKE THE FUNCTIONS FOR ACTIONS TO BE PERFORMED
}

Thank you. I planed to post the full code at the beginning, but the site told me that I was out of limit so I had no choice but to post the part I needed.

@JohnKeane. In that case, reduce you sketch to the minimum size that still show the problem. That will make easy for the rest of us to work on your question.

The trick is to never use a while loop to wait for something physical to happen.  Instead write code that doesn't block execution of the rest of the code.  Write your code so that instead of sitting in a while loop, the function relies on being called over and over from the loop function.  Let the loop function do the looping.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to load Image in Arduino?
In my recent project, I want to load Image in my Arduino. Is there any library available that can be used for loading Image in Arduino. Give some suggestion. Thank you!

A small 128x128 gif takes more than 2.5KB, Arduino have 2KB. What you want to do?

You mean a picture? Sure: convert it to C source code and #include it. Gimp will export in C source format, or there's plenty of websites around that will convert an image for you if you ask Google. However: what are you trying to achieve? An Arduino isn't good at image processing!

Yes there is a library to load the image to Arduino called as "TFTLibrary".
Loads an image file from the SD card into a named instance of PImage. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. Images can be smaller or larger than the screen resolution (160x128), but there is no method on the Arduino for image manipulation. The images should be sized before you put them on the SD card. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. It is possible to load 24 bit bmp image only.
Syntax:
screen.loadImage(name);

Details available on Arduino website:
https://www.arduino.cc/en/Reference/TFTLoadImage


text:
Can't Upload Sketch, Atmel SDM Chip Overheating
I have a chinese CH340 clone arduino. It was working fine until now. The L light stays always on. The sdm Atmel chip is overheating to the point that I can't even touch it. The card is listed under com ports however I can't upload anything due to:
avrdude: stk500_recv(): programmer is not responding

Should I just throw it away or is there a way to save it?

I had a similar question, maybe it helps: https://arduino.stackexchange.com/questions/41806/possible-reason-for-broken-uno

How was it being powered?

It's dead, Jim.

@SDsolar It was powered with a 12V adapter. It was also connected with a rfc522 module and a relay module. Apparently rfc522 also doesn't work anymore.

Remember the Software Engineer from this joke:  http://www.cs.uni.edu/~mccormic/humor.html

Here are some fun links about Arduinos on fire:  https://www.google.com/search?q=arduino+on+fire

SDM... Do you mean SMD (Surface Mount Device)?


text:
Include Adafruit_RGB LCD Shield library in class
I'm trying to make a class to expand on the functionality of the Adafruit-RGB-LCD-Shield-Library I'm creating this based on what I see from this post.
class LcdMenu
{
 #include <Adafruit_MCP23017.h>
 #include <Adafruit_RGBLCDShield.h>
 public:
 Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu *LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM->Setup();
  LcdM->lcd.setBacklight(VIOLET);
}

However, I'm getting the following error:

C:\Users\jschere2\AppData\Local\Temp\ccUzvCmX.ltrans0.ltrans.o: In function `main':
ccUzvCmX.ltrans0.o:(.text.startup+0xf0): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::begin(unsigned char, unsigned char, unsigned char)'
ccUzvCmX.ltrans0.o:(.text.startup+0xf8): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::setBacklight(unsigned char)'
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

Move your #include statements outside the class definition.
You declare a pointer, but never allocate space for it with new. I see no need for a pointer.
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu
{
 public:
     // default ctor will be called here.
     Adafruit_RGBLCDShield lcd;

     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.lcd.setBacklight(VIOLET);
}

Also note: you are not extending the Adafruit_RGBLCDShield class as in the example you linked. To do that:
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu : public Adafruit_RGBLCDShield
{
 public:
     void Setup()
     {
      begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.setBacklight(VIOLET);
}

Ok, in my larger program should I allocate space for the pointer? What is the advantage of having a pointer in a larger program?

The advantage to using pointers is to create objects on-the-fly. For example, create an object, use it, then free the memory associated with it. (There are other uses for pointer.  This is just one example). If the object exists for the life of the program, a pointer is not needed.

Ok, What metric should I use to determine if I should extend the class or keep it separate?

You could use the "has-a/is-a" concept. Is your class an LCD ("is a") or does it just use one ("has a")? Here's an SO question that discusses it: HAS-A, IS-A terminology in object oriented language

Ok and I should extend the class if LcdMenu is a(n) Adafruit_RGBLCDShield?

In this case, it looks like extending it would make sense.


text:
Saving EEPROM after programming on Arduino uno
I am using an Arduino Uno,  and I use the EEPROM to store some presets. It works fine. But, when I reprogram the Arduino, the EEPROM gets wiped out. Is there a way to prevent this, and have the EEPROM not change after the Arduino is programmed?
I am using a USBtinyISP programmer.
Thank you very much for your help, and advance.
Here is the verbose result of my programming:
Sketch uses 5,298 bytes (16%) of program storage space. Maximum is 32,256 bytes.
Global variables use 286 bytes (13%) of dynamic memory, leaving 1,762 bytes for local variables. Maximum is 2,048 bytes.
/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/bin/avrdude -C/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cusbtiny -Uflash:w:/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
        Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
        Copyright (c) 2007-2014 Joerg Wunsch

        System wide configuration file is "/Users/fed/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9/etc/avrdude.conf"
        User configuration file is "/Users/fed/.avrduderc"
        User configuration file does not exist or is not a regular file, skipping

        Using Port                    : usb
        Using Programmer              : usbtiny
avrdude: usbdev_open(): Found USBtinyISP, bus:device: 006:003
        AVR Part                      : ATmega328P
        Chip Erase delay              : 9000 us
        PAGEL                         : PD7
        BS2                           : PC2
        RESET disposition             : dedicated
        RETRY pulse                   : SCK
        serial program mode           : yes
        parallel program mode         : yes
        Timeout                       : 200
        StabDelay                     : 100
        CmdexeDelay                   : 25
        SyncLoops                     : 32
        ByteDelay                     : 0
        PollIndex                     : 3
        PollValue                     : 0x53
        Memory Detail                 :

                                 Block Poll               Page                       Polled
          Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
          ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
          eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
          flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
          lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
          calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
          signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

        Programmer Type : USBtiny
        Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
        To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file "/var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex"
avrdude: writing flash (5298 bytes):

Writing | ################################################## | 100% 7.80s

avrdude: 5298 bytes of flash written
avrdude: verifying flash memory against /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
avrdude: load data flash data from input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex:
avrdude: input file /var/folders/lb/5zdjdm6153jcx_5nq32tt7gw0000gn/T/buildb926e4430d002b65d0ca44bda9d693e2.tmp/LED_strip_08.ino.hex contains 5298 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 4.98s

avrdude: verifying ...
avrdude: 5298 bytes of flash verified

avrdude done.  Thank you.

I believe avrdude allows access to each type of memory independently, so this is probably an issue with the commands the IDE issues.  Another option is to use avrdude to backup the eeprom and then re-write it after.  Basically you need to become familiar with avrdude and figure out how you can change the way the IDE uses it.  Or else only have the IDE build your sketch, and use avrdude manually to load it.

I should clarify my previous comment was more about using avrdude for ISP; off the top of my head, I'm not sure what subset of this the bootloader supports.

You can change the fuses for Atmega328 to preserve EEPROM during chip erase (for ISP programming). Basically, if you are using USBTiny connected to the UNO by 3x2 pin header, you are using ISP programming. Which means chip erase erases also EEPROM if fuse EESAVE is 1 (unprogrammed).
Uploading over the Arduino bootloader (it means you have the UNO connected directly into the computer and there is no other device like USBTiny). The EEPROM should be preserved then.

So, are you saying that changing fuses (I have no idea how to do that) may or may not work.  But not using Arduino IDE, but rather using AVRdude in  command line should work?

@Fed EEPROM can be changed by avrdude but Arduino usually won't do anything with it (you can see whole command in the Arduino IDE if you enable verbose upload).

I updated the verbose output of Arduino IDE when I program the Arduino.  Any suggestions?

@fed The most important thing is USBTiny - it performs chip erase and without EESAVE fuse programmed to 0, it erases EEPROM too.


text:
Read and parse continuous serial stream
I'm trying to read in and parse a message in the form of X123987 continuously streaming into a serial port. There are no new lines or control characters other than the X which marks the beginning/end of the message. The message contains two, three-character components, ex: 123, and 987. I'm trying to copy bytes as their read into a char array, and then on the control character, return the result, but while this compiles, I don't get any output, and it crashes constantly.
#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11);

char _byte_received;
char _buffer[10];
char _value[10];

bool OnReceive()
{
  if (RS485Serial.available())
   {
    digitalWrite(13, HIGH);
      _byte_received = RS485Serial.read();
      if (_byte_received == 'X') {
        strcpy(_value, _buffer);
        memset(_buffer, 0, 10);
        return true;
      } else {
        strcat(_buffer, _byte_received);
        return false;
      }
    digitalWrite(13, LOW);
   } else {
    return false;
   }
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(13, OUTPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.write(_value);
    Serial.println("");
  }
}

Output:
Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:

I expect to see value: 123987

You wrote: “while this compiles [...]”. No. The code you posted does not compile.

I don't know what library are you using, but strcat take two strings, and you are passing a string a char, which is not what you want. concat may be?

I updated the code to make it complete so it now does actually compile. I'm very likely using the char array functions wrong, and that's probably my issue. Should I creating a one char string before using strcat? I think I just don't know how to ask my question properly.

Look at the prototype for strcat: char *strcat(char *dest, const char *src );. You are trying to pass a char where there should be a char * for the 2nd parameter.

How much data will be received ? What else is the sketch doing ? The SoftwareSerial takes over the Arduino, and there is not a lot that the Arduino can do any more. The words "continuously streaming" and "SoftwareSerial" rings an alarm bell. You might need an other Arduino board.

the software serial bit is just for testing on an arduino with only a single hardware port. I'll be using one with multiple hardware serial once it's set up. thanks for the warning.

In OnReceive, you are concatening a string with a char. This may be the cause of the resets.
As a side note, you don't really need to use strcat, strcpy and other str functions. You can make your sketch lean by accesing the arrays directly, like this:
char _buffer[10];
int index = 0;

bool OnReceive()
{
  bool status = false;
  if (RS485Serial.available())
  {
    digitalWrite(Pin13LED, HIGH);
    char _byte_received = RS485Serial.read();
    if (_byte_received == 'X') {
      _buffer[index] = 0; // Mark the end of string.
      index = 0;
      status = true;
    } else {
      _buffer[index++] = _byte_received;
      // ToDo: check for overflow;
    }
    digitalWrite(Pin13LED, LOW);
  }

  return status;
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Receive);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.print(_bufer);
    Serial.println("");
  }


text:
Writing serial data on a pin on Arduino
I want to write some data (GPS) to a digital port on Arduino.  As far as I understand sending data via a pin as if it were USB is possible. But I don't know what function to use. digital.Write doesn't expect any data or strings. How do I write serial data on to a digital pin

Digital.Write takes exactly two arguments, the pin number and 'high' or 'low' - so you look at your bit stream and write the port accordingly, or speed things up by using a built in protocol like I2C, SPI etc...
https://www.arduino.cc/en/Reference/DigitalWrite

USB is a complex protocol which is not supported by most of the simpler processors used in most of the simpler Arduino boards.  So you need to specify your exact hardware or answers to your questions will have to be generic and vague.  The USB port on an Arduino Uno is actually a separate chip from that which you run your Arduino sketches on.  What your Arduino Uno program can do is send out serial data to this separate chip.  Not USB protocol.  Also, as far as I know, the only USB protocol supported on an Arduino Uno is Serial Data over USB.  Hopefully that is what the GPS uses.

It would help if you edited your title so that people know that you are asking about connecting a Arduno to a USB Device.

You need to edit this to be clear what exact "serial" signalling scheme you need to use, and if you are able to choose the pin on which the chip can do that best, or if it has to be a particular pre-chosen and specified in the question pin even if that requirement makes the task far more difficult or impossible.

I am talking about an arduino uno the data from which I am connecting to some other device to read. Right now just to an oscilloscope. I am not sure about the pin. I'm talking about a digital pin on an arduino.
The GPS data can be transmitted using the serial protocol as far as I understand, I'm just not sure how exactly to do that in terms of software.

Also, no I'm not connecting the arduino to a USB device, I just used that as an analogy. The GPS module is connected to an arduino via pins, the data is processed by an arduino and I want to extract this data and send it to other device using a digital pin.

Using the arduino library "software Serial" (https://www.arduino.cc/en/Reference/SoftwareSerial) you can use any pin to write/read serial data.

The Aruduino Uno uses an ATmega328P which only has 1 hardware UART to help the software communicate serially with the outside world.  If you are already using this hardware resource (for example through the normal Arduino serial library), it is unavailable to talk to a 2nd external device.  In such a case you can emulate a UART in software using this Software Serial Library in exchange for some processor time (that is, using a software emulated serial port will slow down your program's execution).

This is likely not what the asker is trying to do - by appearances the data is GPS-like (probably NMEA or something) but they probably don't want to output it to a GPS.  Unless they mean some kind of moving map display for a GPS, but that probably won't want USB input, rather some suitable marine grade serial interface.

Yeah, I'm not trying to output it to a GPS. I am collecting some set of data, and trying to send it to some other device using a digital pin on my arduino. Most likely using serial connection.

Again, it pays to tell which Arduino / processor you are using.  If the processor only has 1 UART you will need to use a software implemented library to talk to a 2nd device over a serial port.  If the processor has 2 UARTs, then the serial communications will be more robust.  But you will have to figure out if the Arduino serial port library you are using will support the 2nd UART of the processor you are using.

Oh I see, thanks. The arduino I'm using is uno with ATMEGA32BP-PU. However, if I'm using a digital pin to communicate do I just configure it as a serial port and then use the serial library?

Please re-word (edit) your Title & Question.  Make it clear you are already using the serial port built into the Arduino Uno.  And you wish to create a 2nd serial port.  I will in turn make my answer fit the re-worded (edited) question.


text:
Comparison of Board Shape between Arduino MEGA and Arduino DUE
I'm using KiCAD to design boards, and while it has a lot of Arduino templates, it doesn't have one for the Arduino Due. Now, I've did some searching, and it looks like the Arduino MEGA is very similar to the Arduino DUE, not the specifications, but the number of I/O pins and the overall shape of the board. I couldn't find a straight answer, so I decided to ask here: Can the template of the Arduino MEGA be used as a template for the Arduino DUE when designing custom 'shields' and such based on the number of I/O pins and overall layout?

The Due has the same footprint as the Mega 2560.

source


text:
Run two Loops Simultaneously on Arduino
I am not able to combine the below two sketches. What I require is to either run both the loops together or find a way to run both the functions inside a single loop.
Sketch 1
#include <SevSeg.h>
#include <DS1307RTC.h>
#include <Time.h>
#include <TimeLib.h>
#include <Wire.h>

// Create an instance of the object
SevSeg sevseg;
bool militaryTime = false; // true for 24 hour clock

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default. Recommended
  bool leadingZeros = true; // Use 'true' if you'd like to keep the leading zeros

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros);
  sevseg.setBrightness(90);
}

void loop() {
  tmElements_t tm;
  int time;
  int dot;

  if (RTC.read(tm)) {
    time = tm.Hour * 100;
    if (time > 1200 && militaryTime == false) {
      time = time - 1200;
    }
    if (time == 0 && militaryTime == false) {
      time = 1200;
    }
    time += tm.Minute;
  }

  if ((tm.Second % 2) == 0) {
    dot = 4;
  } else {
    dot = 2;
  }

  //Produce an output on the display
  sevseg.refreshDisplay();
  sevseg.setNumber(time, dot);
}

Sketch 2
// Change this to the output pin you are using
#define TICK_PIN A0

void setup()
{
  pinMode(TICK_PIN,OUTPUT);
  while (1) {
    tone(TICK_PIN,1000,2);
    delay(1000);
  }
}

void loop()
{
}

The second loop is empty. You are already "running" it ...

@LookAlterno Actually, the 2nd loop never executes because of the while in setup.

The second loop can actually be in the loop function as well. Either way, I am unable to combine the two to make it work.

Basically you need to get rid of the delay and any other blocking loops. Here is a way to do it.
Define this variable globally.
unsigned long lastTime = 0;

Then in your first loop, add the following code either to the beginning or the end:
if (millis() - lastTime >= 1000 || !lastTime) {
    lastTime = millis();
    tone(TICK_PIN,1000,2);
}

What is the !lastTime for ?

@Jot. !lastTime is tested to run the tonein the first execution of loop. After that, is always false. A common trick to resolve the first execution problem.

This worked very well

That looks familiar....just like my answer that was posted 3 hours before yours.

@JohnnyMopp Well, this is a common trick to emulate multitasking on arduino. After looking at yours, it doesn't solve the first execution problem which is done above. You can find this answer almost everywhere, it's not a rocket science.

That's OK, even though I didn't read your answer beforehand but I can delete my answer if that will make you happy ;)

Let it go. I've moved on......and the right thing to do is remove your unjustified DV on my answer.

Not a problem. Waiting for the edit to be approved before I can upvote you again. Also, I couldn't delete this answer because it was accepted.

@LookAlterno, I never used !lastTime. Perhaps I never needed to run something in the first execution of loop. After 50 days it could cause a glitch.

@Jot. In the world I live in, 50 days without a black-out is quite a record. The longest period between blackouts this year was 17 days. Hours, even days without electricity, That's way I always forget about millis() rollover ... it's just a first world problem.

I fund the easiest way to work on this challenge when you have to deal with a long delay and think you need a second loop, is to make make a counter in the main loop using centiseconds (10 milliseconds) and then trigger your required response when the counter reaches your time like
void loop(void) {
counter=counter +1;
if (counter==100){
tone(TICK_PIN, 1000, 2);
counter =0;
}
....rest of code

One way is to use a timer callback.
// Include the timer1 library
#include "TimerOne.h"

// Other code here...

void setup()
{
    // Other setup code here....

    // Setup timer
    Timer1.initialize(1000000);          // 1 second
    Timer1.attachInterrupt(callback);    // Set callback
}

void callback()
{
    tone(TICK_PIN, 1000, 2);
}

void loop()
{
    // Code from 1st loop here...
}

If that doesn't work (if something else is using timer1) you could just keep track of the time between beeps:
uint32_t last_beep = 0;
const int beep_timeout = 1000;

void loop() {
    // Code from first loop here

    uint32_t now = millis();
    if (now - last_beep >= beep_timeout) {
        tone(TICK_PIN, 1000, 2);
        last_beep = now;
    }
}

Would the downvoters care to explain?

You actually read and understood my question better than the accepted answerer. The reason why I did not accept this was simply due to complexity. I upvoted your answer.

Run two Loops Simultaneously on Arduino

in general, the answer depends on your definition of "simultaneously".
But in this case, the answer is "definitively yes", as the other loop is empty.
a generic approach to this kind of questions is:
void setup(void) {
  setup1();  //run setup 1
  setup2();  //run setup 2
  ...
}

void loop(void) {
  loop1();  //run loop1
  loop2();  //run loop2
  ...
}

this approach would only fail if the original setup() and loop() are written poorly.

This might work in some cases, but not even closely for my case.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Buzzing on computer speakers when LEDs are on
I have an Arduino Nano connected via USB to a Mac Mini. When the LEDs come on, an external speaker connected to the Mini starts to hum/buzz quite loudly. If the LEDs are turned off, the buzz stops.
The speaker and the Mac mini are both powered independently, and are plugged into one wall socket, while the 5V power supply to the LEDs and the Nano is plugged into a different socket (of the same outlet).
What could be causing the buzz and what are the possible remedies?

WTH is a "fadecandy"?

Changed to Arduino

Post your sketch, please. What pin are you using for the LED? Are you using digitalWrite, analogWrite, tone ... ?

make sure you run a common ground between the amp and source

@LookAlterno I'm using FastLED, which I believe leverages PWM/analogWrite.

@dandavis This sounds reasonable, but possibly hard to do. Or maybe not. The source is the Mac mini, and both the mini and the amp/speaker are plugged into the same power outlet. Neither the Mac plug nor the speaker power plug have a ground prong. Not sure how I would create a common ground between them.

for a mac mini, you can use a chassis screw, for the 5v stuff you can use the negative rail. On a laptop to receiver setup i have going, I have an alligator clip biting a half-inserted USB plug's meta collar, the other jaw biting a lead from the FM antenna gnd on the back of the receiver. w/o, i get hum, occasional clicks, and pink noise, but as soon as the clip bites, near silence. Shielded cables helped a little, but the ground connection basically fixes the issue completely.

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

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

It's not the same project, and I would like to believe the issues are not related (the other one has to do with voltage changes probably due to common power source). However your tests are very helpful. I have significantly upped the LED power supply (from 8A -> 30A) and am pluggin both power supplies into a big old UPS with shielded power and the buzz seems to have gone away.


text:
ESP Wemos D1 upload fails
I try to upload simple code (e.g. blink.ino) to my ESP8266-12 (I have the WeMos D1 breakout board). Until now, that worked without a problem: I had to pull GPIO0 down and then I could upload the compiled sketch.
Since today that does not work any more - but I did not change anything.
I get:

error: espcomm_upload_mem failed

(I know that here are some questions / github issues out there that have the same error, but that was often because GPIO0 wasn't pulled down and the ESP was therefore not in FLASH mode.)
My config is: ESP8266, 80MHz, DIO, 115200, 512K (64K SPIFFS), ck, Serial
When I reset my board, having GPIO0 pulled down, the ESP sends this serial info:

ets Jan  8 2013,rst cause:2, boot mode:(1,7)

The whole debug output is:
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM6
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 228624 bytes from D:\Users\myusr\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037d10 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    read 0, requested 1
    setting serial port timeouts to 1000 ms
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
error: espcomm_upload_mem failed

As I found out, GPIO0 has to be LOW AND GPIO2 has to be HIGH. It is very important to use pin D3 as GPIO0 and pin D4 as GPIO2 at the WeMos D1 board, because this "routing" is different for other boards and therefore other digital pins are often described.

Very useful, upvoted.

@black What exactly did you do to solve the problem. Because I have almost exact problem. It was working fine. Suddenly It started to give this error. So I plugged every cable on wemos just as it is plain. Then using the Blink sketch even it is not uploaded without this problem. So what did you do?

I was facing the same problem, I simply updated CH34x driver for esp8266 to v1.4 from v1.3 after that I was able to see a new port option named usbserial 1420 & wchusbserial 1420. after selecting wchusbserial 1420 I was able to upload program successfully. As  my MacOs running on Mojave


text:
Arduino: Connect UNO to A7 AI Thinker
I just cannot connect or send AT command from my UNO to A7 AI Thinker module. This is the connection:
UNO    ->    A7
TX     ->    RX
RX     ->    TX
USB    ||    5V    -> External Power Supply
GND    ->    GND

Without any sketch, I tried to send AT command from serial monitor, and nothing happened.
Different case if I use USB TTL to A7
USB TTL   ->   A7
VCC (5v)  ->   5V
GND       ->   GND
TX        ->   RX
RX        ->   TX

Then it is OK, I can send all AT command, SMS, Call, etc from the serial monitor.
Just what is happening with UNO? Does my UNO RX TX Faulty? How to check it?

What pins on the Arduino are you calling TX and RX?  The normal ones are already in use for the USB-serial, so if you try to use those for something else at the same time, at least one of the two links will fail and you won't be able to tell what is going on.  The Uno is poorly suited to use with serial interfaced add-ons, you typically have to use a bitbanged "software serial".

The pins are 0 and 1 on Arduino. I do not try to use sketch, I just want to make sure that the A7 got the AT commands. If I use SoftwareSerial and connect the tx rx on pin 2 and 3, I should upload the sketch first right?

I think I am a I'll so facing similar issues with you.
I tried sending AT commands to my board and nothing is coming up
Could it be that I have done something wrong?

Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

The problem is with your connections to the Uno. Although it seems wrong, the correct connection when you're using the Uno as a USB-serial adapter to communicate with the A7 AI Thinker module from Serial Monitor is:
Uno                A7
TX (pin 1)   ->    TX
RX (pin 0)   ->    RX

The RX and TX markings on the Uno refer to the pins on the ATmega328P microcontroller. But you're not using that microcontroller, you're communicating between the USB-serial chip on the Uno and the A7. The RX line of the USB-serial chip is connected to the TX pin of the ATmega328P and thus to pin 1, the TX pin of the USB-serial chip is connected to the RX pin of the ATmega328P and thus to pin 0. For this reason the connection between the Uno and A7 shown above are actually an RX-TX, TX-RX connection between the USB-serial chip and the A7.
If you were communicating between the ATmega328P on your Uno and the A7 then the connections you used would have been correct.

This is make sense. I tried to connect TX->TX and RX->RX but this error came out: Invalid or no response from the device. Please check the modem port and the baud rate.Disconnecting port COM3.. I set the baud rate to 115200. What is happening here?

Are you communicating with your computer over Serial e.g. Serial Monitor) and also communicating with the A7 module over Serial at the same time? That is problematic. It may be better to communicate with the module via software serial and leave Serial to be used only for uploading and communicating with the computer. Keep in mind that software serial doesn't work reliably at 115200 baud.


text:
Adafruit nRF52 feather board [SOLVED]
I am working on a project (the scenario is depicted in the attachment) involving Bluetooth Low Energy (BLE). As a master (central device) I am using the Adafruit nRF52 feather board (https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/introduction) and as slaves (peripheral devices) a pair of Adafruit nRF8001 modules (https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/pinouts?view=all#introduction). Moreover, I have to wire the nRF52 up with an Arduino Uno rev3.
I am trying to set up the very initial communication between central and peripheral devices, but if I even try to upload the blinky sketch into the nRF52 board the compiling phase returns to me the following error:

exec: "nrfutil": executable file not found in $PATH

Does anyone have an idea what it means? I googled a lot but I am not able to figure it out on this problem.
Thanks in advance to anyone would be able to help me!
Filippo

[EDIT] Solved: just need to install the nfrutil first, as written in https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/arduino-bsp-setup#nrfutil-os-x-and-linux-only

mind sharing your code on github?

Would you mind sharing how you solved the problem in an answer (or edit monkSinha's answer)? That adafruit website may not exist at the same address in the future, so it would help to give a complete answer to future readers of your question.

Step 2 solves this problem:
https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/arduino-bsp-setup
Also, read up about how to add something to Path Variable on Windows.


text:
Arduino LilyPad and nRF8001 module wiring
I am trying to wire up a nRF8001 BLE module with the LilyPad board, as the title says.
The problem is that if I wire them up I am not more able to see the nRF8001 module during the scan phase with the nRF UART 2.0 app ( https://play.google.com/store/apps/details?id=com.nordicsemi.nrfUARTv2&hl=it for Android). INstead, if I wire the nRF8001 up with the Arduino Uno rev3 I can correctly exchanging messages from the serial monior to the app and viceversa.
Since the LilyPad is quite equals the the Arduino in terms of processor and pinout, I am wondering what I am doing wrong.
The wirings is the following:
LilyPad   <--->   nRF8001
  +                 Vin
  -                 GND
pin #2              RDY
pin #9              RST
pin #10             REQ
pin #11             MOSI
pin #12             MISO
pin #13             SCK

Does anyone have any suggestion? Thanks in advance!
Filippo

How are you powering the LilyPad? Check the current and voltage levels.

Lilypad is powered via the FTDI USB adapter, so should be 5V, isn't it?

Should I use the 6-pins header (2x3) in the cebnter of the board near the processor for the SPI connection?


text:
CH340 max serial speed
With an Arduino-like board using a CH340 USB Serial chip, I'd like to send text lines as fast as possible to a Raspberry Pi through USB using the Serial.println() function. The problem is that when I set the serial speed to values above 230 400 with the Serial.begin(speed) function, the Arduino console crashes and the C program on the Rapsberry Pi displays garbage in its console, even though I set the same serial speed.
Short examples :
Serial.begin(230400);
Serial.println("Test !"); // Works fine.

Serial.begin(250000);     // Or any speed above 250 000.
Serial.println("Test !"); // Doesn't work at all.

This answered question states that 2 Mbauds is possible, so I'm a bit lost.
The Arduino IDE console offers various speed from 300 to 2 000 000 bauds, so why don't speeds above 230 400 work ?

What type of Uno? Clone? Check what USB bridge is used on your board.

Cheap Chinese clone. The chip seems to be a CH340G.

CH340G does not support 250 Kbps. See page 5, https://www.insidegadgets.com/wp-content/uploads/2016/12/ch340g-datasheet.pdf

Thank you for the datasheet and this information. But according to the document, speeds like 460 800 bauds and 2 000 000 bauds should work, so why would this not be the case with my board ?

Add the line "while (!Serial); " after "Serial.begin()" or simply a delay. The USB handshake might take some time and the first character lost.

Please remember that the baudrate is not the USB transfer rate. It is between the MCU and the USB bridge. Also the max sustained baudrate is approx. 100-200 Kbps with the Arduino HardwareSerial implementation.

Thank you for your help and reminder. My print() are in a while loop, and it's not a problem if I miss a few characters at the beginning. What is the HarwareSerial implementation ? I see it's a custom version of Serial, but what is it for ?

The HardwareSerial class is an implementation of the Arduino Serial class that uses the MCU/AVR UART (hardware serial). The class (internals) are interrupt driven and uses ring-buffers to store incoming and outgoing characters.

CHG340 supports common baud rates: 50, 75, 100, 110, 134.5, 150, 300, 600, 900, 1200, 1800, 2400, 3600, 4800, 9600, 14400, 19200, 28800, 33600, 38400, 56000, 57600, 76800, 115200, 128000, 153600, 230400, 460800, 921600, 1500000, 2000000 baud.
250 000 baud isn't supported by that IC.
The Baud steps is either 200% or 150% of the previous value (There is exceptions).
Tested and working Baud rates.
I used putty as serial monitor since the built in monitor didn't have all baud rates preprogrammed.
SpeedTest.ino
// Serial port Baudrates:
// const int Speed = 115200;
// const int Speed = 128000;
// const int Speed = 153600;
// const int Speed = 230400;
// const int Speed = 460800;
// const int Speed = 921600;
// const int Speed = 1500000;
const int Speed = 2000000;

void setup() {
  // Initialize serial:
  Serial.begin(Speed);

  // Initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
  Serial.print("Speed :  ");
  Serial.println(Speed);
}

This helped me, thanks ! Actually, I've found that my problem is due to serial latency, but I still managed to communicate at 1 Mbaud.

I have tested 3000000, which worked for me. See also https://www.eevblog.com/forum/microcontrollers/ch340-usb-uart-speed-tests/

the windows driver only goes to 128000

I have seen commenst that speeds abowe 115200 is "unstable" in both windows and linux

There may just be a workaround to allow this adapter to operate at 250000 baud (at least in the Raspberry Pi). The author of this article:  http://dmxpi.blogspot.com/2014/04/dmx-on-raspberry-pi-start-here.html has modified the linux driver and claims it works. I hope this helps.

Please edit your answer to include the method/steps employed in the link. If the link dies then your answer will not be as useful as it could be.

i agree with @Greenonline


text:
analogRead() hangs
With this code I try to send a measurement over 443MHz using RadioHead. All parts work but when combined they fail. This chip used is an ATtiny85.
The function 'measure' torpedoes the entire program. If it is used, it will compile but it will never run Setup or Loop. I know this because I use a Logic Analyzer and Software Serial. I can see the Serial Port, PB1, hanging high.
I would like to know what is so wrong about function measure that it undermines all code..
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <RH_ASK.h>   // local libs at
#include <powernap.h> // /home/thijs/.platformio/lib

#define TICKLE_ID 192

#define SENSOR1_PIN 2
#define SENSOR1_PWR 4
#define SENSOR2_PIN -1
#define SENSOR2_PWR -1

#define SOFTWARE_SERIAL_TX_PIN 1
#define SOFTWARE_SERIAL_RX_PIN -1

#define RADIOHEAD_BAUD 2000
#define RADIOHEAD_TX_PIN 0
#define RADIOHEAD_RX_PIN -1

struct tickle {
  uint16_t id = TICKLE_ID;
  uint16_t value1;
  uint16_t value2;
};

Napper napper;
SoftwareSerial mySerial(SOFTWARE_SERIAL_RX_PIN, SOFTWARE_SERIAL_TX_PIN);
RH_ASK driver(RADIOHEAD_BAUD, RADIOHEAD_RX_PIN, RADIOHEAD_TX_PIN);

void senddata(int hygro) {
  mySerial.print("Senddata");
  struct tickle package; // make a Tickle package
  package.id = TICKLE_ID; // hard-coded device ID
  package.value1 = 0; // any positive int up to 2^16
  package.value2 = hygro; // any positive int up to 2^16
  driver.send((uint8_t *)&package, sizeof(package));
  driver.waitPacketSent(); // wait for it ~Barney
}

int measure() {
  mySerial.print("Measure");
  pinMode(SENSOR1_PWR, OUTPUT); // enable sensor
  pinMode(SENSOR1_PWR, HIGH); // turn on sensor
  delay(100); // wait for sensor to settle

  int i; // int for counter
  int data = 0; // data container

  for (i = 0; i < 5; i++){ // cumulate 5 measurements
    data = data + analogRead(SENSOR1_PIN);
  }

  data = data / 5; // avg of measurements
  pinMode(SENSOR1_PWR, LOW); // turn off sensor
  pinMode(SENSOR1_PWR, INPUT); // disable sensor
  mySerial.print(data);
  return data; // return avg measured value
}

void setup() {
  mySerial.begin(600); // 600 baud serial
  mySerial.print("Setup"); // logging the start
  driver.init(); // initialize the RadioHead library
  napper.setup_sleep(); // initialize the Napper library
}

void loop() {
  mySerial.print("Loop"); // start of loop
  int measurement = measure(); // measure data
  senddata(measurement); // send data
  napper.napminutes(1); // deep sleep for 1 minute
}

[EDIT]
I thought the problem to be this, and then to be that. This is how I debug, I start somewhere and work my way back. Currently it looks like my own library PowerNap is the culprit, I have tested with other Sleep code and it works. I can only be sure after more tests and isolated code running.

My guess is that whatever is attached to pin 4 causes the chip to overload?

thanks for the quick reply! I removed the sensor, should return floating analogue value now, still nothing, SoftwareSerial returns complete jibberish whenever I use the function.

@Majenko It might, if he'd actually turned it on. But there are just bunch of pinMode calls and no digitalWrite.

@KIIV So there is. I completely blanked those and just read the OUTPUT and HIGH parts ;) Brains are strange things...

With only 512B of SRAM you really really need to have all string constants in flash. Use the F() macro on all your strings.

DO you think it fails over my mistake of using pinMode where it should read digitalWrite?

I moved the Strings to Flash with the macro but I think there is some incompatibility somewhere because softwareserial now returns nothing. Changing the pinMode to digitalWrite starts the sensor now but it hangs during measurement..

The change you are seeing shows that memory certainly was an issue - maybe it still is. Reduce your program down to the bare minimum. I'd suggest removing the serial comms completely unless you really really really need them.

that did not help, now my code is not working AND I'm blind because of removing SoftwareSerial, which was also broken because I used the F() macro. Time to start over, again. I am uploading the Blink Example code now.

Let us continue this discussion in chat.

I'm voting to close this old abandoned question as incomplete and unanswerable because the asker has posted that their prime suspicion is now with code which is not included in the question but only linked at an external site, which is not in keeping with the rules of this site which require questions to stand on their own without relying on external references for the key parts.

Fine by me, it has been some time since I worked on this. I do not know what to do with my 'old' unanswered questions.

Interesting question but nothing seems wrong in the measure() function unless the mistake pinMode is used instead of digitalWrite. I suggest in the for loop keep a slight interval between the measurements. lets say about 50ms. if the problem still presets lets start the debugging. set a serial message in every critical point and pin point the exact location the code hangs.

analogRead() hangs

you started this journey thinking a particular routine (measure()) is the problem and you now are blaming analogRead() to be the source of your ills.
it will serve you much better for you to step back and ask yourself if your thought process is at fault here.
while you haven't provided much information on what it is that's not working, you have provided more than enough information to suggest that the issue is not measure() nor analogRead().
you may find this hard to understand now but debugging is far less about convincing yourself where the wrongs are. instead, it is about convincing yourself what you think right is wrong.

Offcourse my thought process is wrong, otherwise I would file a bug at ATMEL or Arduino :D I am not here to find a problem in the tech, I am here to identify the mistake I am making myself. Yes I am the weakest link. This is nice to know but it does not help regarding the question at hand.

Personally I think its a memory size issue, but the only real changes you need to make to measure is change pinMode to digitalWrite (as you have spotted) and personally I think you should remove the other pinMode statements and leave the pin setup the whole time, unless you are using it for something else.
int measure() {
  mySerial.println("Measure");
  pinMode(SENSOR1_PWR, OUTPUT); // enable sensor
  digitalWrite(SENSOR1_PWR, HIGH); // turn on sensor
  delay(100); // wait for sensor to settle

  int data = 0; // data container

  for (int i = 0; i < 5; i++){ // cumulate 5 measurements
    data = data + analogRead(SENSOR1_PIN);
  }

  data = data / 5; // avg of measurements
  digitalWrite(SENSOR1_PWR, LOW); // turn off sensor
  // pinMode(SENSOR1_PWR, INPUT); // disable sensor - If you do this the "sensor" floats.
  mySerial.println(data);
  return data; // return avg measured value
}

if I replace the function measure() by '17' it works. But the function still does not produce a valid repsonse. The int from analogRead goes to uint16_t for the 'tickle' struct and then goes over the air as uint8_t? Maybe it gets lost in this type jungle?

It really sounds like you are just over the maximum memory you can use.  Remove myserial and call and it should work.  There doesn't appear to be anything wrong with your code.

it hangs on analogRead(), I can see it not hitting the sleep routine by watching my multimeter. something must be in the way of analogRead()

Put a delay of 10ms after the analogRead() call.

Did not help, it still does not hit the sleep function. Maybe I made a mistake in my Deep Sleep code in this lib; https://github.com/Thijxx/PowerNap

Print a serial message right after going into the for loop. just to make sure it executed the for loop and hanged on the analogueRead itself. If so try declaring the i and data variables out of the function.

@danialweaber - I'm not disagreeing with you, but why would declaring the variables outside the function make any difference? (Just want to learn.)

@CodeGorilla Theres no thumb of rule to use global variables or local variables one over the other. Regardless of the language here we are writing to a device whose memory is limited(few kbits). In these cases more likely so many global variables when accessed from several routines may lead to unexpected side effects. I just suspected if it was a a such issue because I didn't check his napper library for memory leaks. OP makes sure it hangs in the particular routing, So it was just a suggestion from me for testing.


text:
Programming ATmega328p on external board with FT232R
I am making a 100W AC-DC linear power supply, for which I want to show output Voltage and Output current on LCD display. I already used shunt resistor and voltage resistor to bring both values to analog pins on my ATmega328P in DIP socket, which has an Arduino bootloader on it. I want to programm my ATmega328P on the board without taking it off everytime and putting it into Arduino UNO board to just programm it and put it back, so how can I integrate a programmer onto board?
I intend to use the FT232R ic, which I think would work more than fine for this application.
On finished product I want to have a USB connector on the case just to update/correct the software.

If you want an USB connector, an Arduino Nano or 32u4 based Arduino may be a better solution.

I suggest use ICSP(In circuit serial programming) feature of the Atmega 328 chip. Grab the .hex file from the arduino IDE and a USB ISP external programmer to write the program to the chip. Here you will have to use a 6 pin header on your custom board to take out the pins which are used to program the atmega.

External programmers are cool, but if you want your end-user to connect to the board, you'll most likely want USB. But I agree that it is useful to have the ICSP header available, so you can put on the bootloader if you're making more of these boards.

That's correct paul. But here the OP has said that she plug the chip into an UNO for programming and then remove it to the target board. And she want to avoid that. In that case this is the simplest solution rather than building an UNO in the application.

I use an FTDI cable with my home-builds. Then the board doesn't need the interface hardware (it's in the cable) and the MCU doesn't need to be removed.
I put a 6-pin male header on the board to match 6-pin female socket my cables come with. The header is direct-wired to the Tx, Rx, +5, & Gnd pins. If you have an auto-reset circuit on your board, connect the RTS pins to that. Then, reprogramming is as simple as connecting your board and clicking 'upload'. Without the auto-reset circuit, you just hold the reset button while you click upload, count 3, and release the reset.
Update:
You can do it with only 4 pins on the board. If I understand correctly, just wire Tx, Rx, +5 & Ground of the Arduino to the 4 pins and replace the Arduino-end socket on the FTDI cable with one wired to match however you wired the board. If you use L-shaped male pins, they'll lie parallel to the board and won't add any height (above what is already on it).

Hmm..that doesn't sound as a bad idea, but I'd like to make only 4 pins onto the PCB and from there connect the USB cable panel mount. In other words, I'm searching for a schematics for USB cable - ftdi - atmega connection.

Check the schematics of the Arduino Nano, they are basically exactly the circuit you describe.


text:
Using Capacitive Sensing Library with a 74HC4067 multiplexer
I'm trying to use the Capacitive Sensing Library by Paul Badger in conjunction with one or more 74HC4067 multiplexers to achieve a lot of capacitive touch inputs. I came across this youtube video where the poster seems to have accomplished what I'm trying but I can't seem to replicate this.
Here is the setup I'm using with an arduino nano, some 1MΩ resistors and a CD74HC4067 breakout :

Here is my Arduino code :
#include <CapacitiveSensor.h>

#define muxS0Pin 7
#define muxS1Pin 6
#define muxS2Pin 5
#define muxS3Pin 4
#define muxSignalPin 3
#define muxEnPin 8
#define capSenseSendPin 2
#define sampleRate 5

int touch[4] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

void setup() {
    digitalWrite( muxEnPin, LOW );
    Serial.begin( 115200 );
}

void loop(){
    byte touchIndex = 0;
    for ( byte channel = 0; channel < 4; ++channel ) {
        digitalWrite( muxS0Pin, ( channel & 1 ) >> 0 );
        digitalWrite( muxS1Pin, ( channel & 2 ) >> 1 );
        digitalWrite( muxS2Pin, ( channel & 4 ) >> 2 );
        digitalWrite( muxS3Pin, ( channel & 8 ) >> 3 );
        touch[touchIndex] = capSense.capacitiveSensor( sampleRate );
        ++touchIndex;
    }
    for ( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print("\t");
    }
    Serial.println();
}

This example attempts only four capacitive touch pads but eventually I plan to use all 16 and then another multiplexer, but right now I'm stuck on getting anything, I seem to be getting some readings on touching the last pad but it's not what I expect to see, and it affects all the reading.
I've successfully got a version of this running without a multiplexer just on ten IO pins and it worked great. I also got the multiplexer running fine in a separate example with 16 push buttons.
Could the problem be due to pad charge times or the send-recieve capsense signals getting stopped in the multiplexer?
Any and all help would be appreciated.

Here is the link to the library : http://playground.arduino.cc/Main/CapacitiveSensor

And here's a video of my example not working : https://www.youtube.com/watch?v=4bGJw1UrgOk. The setup in the video is slightly different than the illustration above; I have pads connected to C6 to C15 on the multiplexer and I loop through them backwards to display them in order on the serial monitor. But the point is, it seems to be only the last multiplexer pin that affects all the readings.

Might need to set the mux enable pin (muxEnPin) mode to output in setup().

This is way late, but for anyone who runs across this, here was my solution. The two main thing is explicitly using analog input pins (which could be quantized to digital values in the software, and making sure you have resitors on each channel being sensed. Also, ground the EN pin on the multiplexer
#include <CapacitiveSensor.h>

#define muxS0Pin 9  // I used these rather than 4-7
#define muxS1Pin 10
#define muxS2Pin 11
#define muxS3Pin 12

#define muxSignalPin A0      // explicitly set ro analog
#define capSenseSendPin A2   //

#define sampleRate 10
#define n_inputs 16

int touch[n_inputs] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

int readMux(int channel) {
  int controlPin[] = {muxS0Pin, muxS1Pin, muxS2Pin, muxS3Pin};

  int muxChannel[16][4] = {
    {0, 0, 0, 0}, //channel 0
    {1, 0, 0, 0}, //channel 1
    {0, 1, 0, 0}, //channel 2
    {1, 1, 0, 0}, //channel 3
    {0, 0, 1, 0}, //channel 4
    {1, 0, 1, 0}, //channel 5
    {0, 1, 1, 0}, //channel 6
    {1, 1, 1, 0}, //channel 7
    {0, 0, 0, 1}, //channel 8
    {1, 0, 0, 1}, //channel 9
    {0, 1, 0, 1}, //channel 10
    {1, 1, 0, 1}, //channel 11
    {0, 0, 1, 1}, //channel 12
    {1, 0, 1, 1}, //channel 13
    {0, 1, 1, 1}, //channel 14
    {1, 1, 1, 1} //channel 15
  };

  //loop through the 4 contol pins
  for (int k = 0; k < 4; k ++) {
    digitalWrite(controlPin[k], muxChannel[channel][k]);
  }
  //read the value at the SIG pin
  return capSense.capacitiveSensor( sampleRate );
}

void setup() {
  // Very important to set control pins to output mode
  pinMode(muxS0Pin, OUTPUT);
  pinMode(muxS1Pin, OUTPUT);
  pinMode(muxS2Pin, OUTPUT);
  pinMode(muxS3Pin, OUTPUT);

  digitalWrite(muxS0Pin, LOW);
  digitalWrite(muxS1Pin, LOW);
  digitalWrite(muxS2Pin, LOW);
  digitalWrite(muxS3Pin, LOW);
  Serial.begin( 9600 );
}

void loop() {
  byte touchIndex = 0;
  for ( byte channel = 0; channel < n_inputs; ++channel ) {
    Serial.print( readMux(channel));
    Serial.print("\t");
  }
  Serial.println();
}


text:
SPI Arduino communication
I want two Arduino cards to communicate with each other using SPI and move the servo motor with potentiometer as a result. I've done the pre-burning led or the led burning led on the SPI, I am waiting for your help. I will give the code below.
MASTER Arduino code
#include <SPI.h>
/* SPI haberleşmesinde Master olarak görev yapan Arduino kodu */
const int pot=A0;   // Servo kontrol potunu bağlayacağımız analog giriş.
int potdurum=0;
int pos = 0;
const int SSpini = 8;
/* Slave görevindeki Arduino'nun seçilmesi için 8 bumaralı pin SS olarak belirlendi */

void setup()
{
  Serial.begin(9600);
  pinMode(SSpini, OUTPUT);
  /* SS pini çıkış olarak ayarlandı */
  digitalWrite(SSpini, HIGH);
  /* Slave olan Arduino başlangıçta haberleşmeye geçmemesi için SS pini HIGH yapıldı */
  SPI.begin();
  /* SPI haberleşmesi başlatıldı */
}

void loop()
{
  potdurum=analogRead(pot);
  pos= map(potdurum,0,1023,0,180);//Pottan okunan değeri  180e oranlıyoruz.
  veriGonder(pos,SSpini);
}

/* SPI üzerinden veri göndermek için yazılmış fonksiyondur */
void veriGonder(int veri, int SSpini)
{
  digitalWrite(SSpini, LOW);
  /* Diğer Arduino'nun veri dinlemeye başlaması için SS hattını LOW düzeyine çekmeliyiz */
  delay(1);
  /* Kısa bir süre bekleyelim */
  Serial.print("Aci Degeri = ");
  Serial.println(veri);
  delay(15);
  SPI.transfer(veri);
  /* veri karakteri diğer Arduino'ya yollandı
  * Fonksiyon diğer arduino'dan gelen veriyi vermektedir
  * Geri gelen veri LEDDurumu değişkeninde tutulmuştur
  * Bu değişken Seri port üzerinden bilgisayardaki Serial monitöre yollanmıştır
  */
  digitalWrite(SSpini, HIGH);
  /* Haberleşmeyi bitirmek için pin LOW konumuna çekilmiştir */
}

SLAVE Arduino code
#include <Servo.h>
int i = 0;
Servo myservomotor;

void setup()
{
  Serial.begin(115200);
  myservomotor.attach(3);
  pinMode(MISO, OUTPUT);
  pinMode(SS , INPUT);
  /* MISO pini OUTPUT, SS pini INPUT olarak ayarlandı */

  SPCR  |= 0b11000000;
  SPSR  |= 0b00000000;
  /* Slave mod ve interrupt için ayarlamalar yapıldı */

  sei();
  /* Interruptlar çalıştırıldı */
}

void loop()
{
}

/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
  /* Interruptlar durdurulmuştur */
  while(!digitalRead(SS))
  {
      SPDR = i;
      i ++;
      if ( i > 255)
        i = 0;
      while(!(SPSR & (1 << SPIF)));
      /* SPI hattında veri aktarımı bitene kadar bekle */
      int gelenVeri;
      gelenVeri = SPDR;
      myservomotor.write(gelenVeri);
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);
      delay(15);

//      if(gelenVeri == 'a'){
//        digitalWrite(SERVO,HIGH);
//      }else if(gelenVeri == 'b'){
//        digitalWrite(SERVO,LOW);
//      }
      /* SPI üzerinden gelen verinin değerine göre LED'in konumu değiştirildi */
  }
  sei();
  /* Interruptlar başlatılmıştır */
}

What's your question?

The basic error is too much code in the SPI ISR. Focus on capturing the SPI value and then flag to the loop() function that a new value is available. Avoid delay and serial print in ISRs.

@LookAlterno - this site requires posts and comments to be in English, thanks.

I am waiting for your help. - for what, exactly?

/* SPI kesmesi olduğunda çalışacak fonksiyon */
ISR(SPI_STC_vect)
{
  cli();
 ...
      Serial.print("Aci Degeri Slave= ");
      Serial.println(gelenVeri);

Don't do serial prints inside an ISR.


text:
Millisecond timestamp (13 digits) in Arduino
How can I store a 13 digits int in Arduino?
For example, current timestamp is:
1500666822235
An uint32_t can only hold 10 digits max.
64 bits integer does not seem to be supported on RFduino.

Where they come from? As strings, sequence of bytes ...?

They're timestamps of sensor logging application (accel, gyro). It comes from combining millis (uptime) and RTC (absolute time).

18446744073709551615
That 20 digits. It is the maximum value of a uint64_t. Even the Arduino Uno can use the uint64_t. Perhaps the Serial.print does not support it, but the compiler supports it.
Which processor does your RFduino have ?
Where does the timestamp come from ? Perhaps you are asking the wrong question. Perhaps this is a xy-problem.

How can I store a 13 digits int in Arduino?

create a multi-byte type.
a 40-bit (32+8 bits), or a 96-bit (32+32+32) would hold a ton.
or BCD.