text:
nRF24l01+ Outputting Garbage Values
I just purchased a set of 10 nRF24l01+ modules with a breakout board that looks like this:

Note: This is the nRF24l01+ chip, not a clone Si24Ri. Also, I'm using an Arduino Mega.
I'm following the Sparkfun tutorial here:
https://learn.sparkfun.com/tutorials/nrf24l01-transceiver-hookup-guide
The wires are hooked up like so:

3.3V → VCC
GND → GND
PWM 8 → IRQ
PWM 9 → CE
PWM 10 → CSN
PWM 11 → MOSI
PWM 12 → MISO
PWM 13 → SCK

I've verified the two modules are hooked up as they should be. I'm using the GettingStarted example program for both units. Whenever I go into the serial monitor when connected to the transmitter, I get garbage values like <¯�SžRÖ being output. Whenever I try to transmit a message by entering t, nothing gets returned. The same problem is happening on the receiver end.
As for troubleshooting:

I've wiggled all of the jumper cables to verify a stable connection.
I've swapped out the modules I was using with others from the package (twice) so the modules probably aren't bad.
After reading that a capacitor is sometimes needed to provide a smoother voltage to the module, I upped the voltage from the 3.3V the Arduino was providing to a stable 3.5V from an external variable power supply to account for any small voltage dips. I don't have any capacitors available to me at the moment, so I figured this would be the next best option.

Unfortunately, my RF modules are still not correctly transmitting any data, and I don't know where to go from here.

Check the SPI pins. They are different on a Mega.

See http://blog.brunodemartino.com.ar/wp-content/uploads/2013/11/connections.png

No luck - garbage values are still being output even after changing the wire configuration. I don't see anything in the example sketch I would need to change either.

Ah, wait! Nevermind, it did work. I just needed to make sure I was on 115200 baud rate in my serial monitor.

Check these things first:

Is your power supply give a constant 3.3V and a minimum of 0.5A(500mA)?
Does your code work for others?
Are you on the right serial baud rate?
Is the path from the radio to the Arduino as short as possible?
Are your MISO and MOSI wires twined into each other?

If none of these things help then, please tell me what library you are using. I had a lot of issues with the RF24 library so maybe try using the NRFLite library.


text:
Firmata: how to set a particular pin to high on boot?
I'm working on a project that use J5, so is using the standard firmata, this project is using an opto 4 channel relay, when the board is booting the pins state are set to low, so as soon as I power the board my relay goes to a close state and make my motor run... this is a wrong behaviour for my purpose. How can I avoid that? By googleing around I stumble acros this:
A possible solution
but I can't uderstand if this is what I'm looking for.. plus I need only the PIN 7 to be set high on boot, any help please?
EDIT: SCHEMATICS
4 Channel 5V Relay Module

What makes you believe it boots with all pins LOW? They should be high impedance. Could you share the schematic of how you connect the Arduino to the optocoupler, to the the relays and to the motors?

@EdgarBonet added schematics in the question ;)

This is not a schematic. And it only shows how you are powering your relay module, not how you are driving it, nor how it works internally (reference please).

@EdgarBonet added the references link to the constructor wiki page

@EdgarBonet I forgot in the schema above to connect the pin 7 to the ch1, sorry

Why you don't put an inverter between pin 7 and the relay?

It would seem you are right. If I understood the source correctly,
Firmata initializes all digital pins as OUTPUT LOW. Hard to believe, as
this seems like a silly thing to do... My understanding is that:

setup() calls systemResetCallback() in order to set the initial
pin configuration (line 779)
systemResetCallback() loops over all pins and calls
setPinModeCallback(i, OUTPUT) for every pin i that is not an
analog pin (line 732)
setPinModeCallback() calls pinMode() to set the pin to OUTPUT
(line 325).

If my understanding is correct, then the simplest solution would seem to
patch systemResetCallback() and replace OUTPUT by INPUT on
line 732.

yep, my same conclusion but I think that setting all the pins to INPUT will cause the same but opposite problem for other components.. best would be set the desired pin number

Irrespective of how you patch Firmata, the pins will be set to INPUT when you power the Arduino, and during the time the bootloader runs. You should manage for you circuit to accommodate that initial state. A pullup or pulldown resistor may be suitable for the pins driving those other components.

how does it take to boot less than a second would be acceptable

Just put digitalWrite(anyPin,HIGH) in void setup() this will make that specific pin HIGH to reset. It works for me.
void setup()
{
  digitalWrite(8,HIGH);
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);

  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
  Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.attach(SYSTEM_RESET, systemResetCallback);

  // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega,
  // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this:
  // Serial1.begin(57600);
  // Firmata.begin(Serial1);
  // However do not do this if you are using SERIAL_MESSAGE

  Firmata.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101
  }

  systemResetCallback();  // reset to default config
}

source: Stack Exchange

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

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

sort: votes


text:
Problem regarding getting split data of JSON - Another issue
In my recent project, I'm working with Arduino and JSON. I've successfully split the JSON data I want. My JSON data length is fixed. So, I used the length() function and I'm getting the length of my data.
Now, my input JSON data is:
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

Using the length() function, its length is 39.
But when I use an if statement like if(len == 39) and put my logic inside this, I'm not getting the split data. Below is my whole code.
Here, I'm displaying my data on LCD.
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);
String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";
String response = "";
bool begin = false;
int counter = 0;
int len = 0;
char in;
float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop() {
  while(Serial.available() || !begin) {
    in = Serial.read();
    if (in == '{') {
      begin = true;
    }
    if(begin) {
      counter++;
      response += (in);
      len = response.length();
      if(len == 39) {
        if(counter >= 9 && counter <= 12) {
          data_TPS_Json += (in);
        }
        if(counter >= 22 && counter <= 25) {
          data_MAP_Json += (in);
        }
        if(counter >= 36 && counter <= 37) {
          data_LOAD_TM_Json += (in);
        }
      }
    }

    if(in == '}') {
      break;
    }
    delay(1);
  }
  TPS_Json = data_TPS_Json.toFloat();
  MAP_Json = data_MAP_Json.toFloat();
  LOAD_TM_Json = data_LOAD_TM_Json.toFloat();
  lcd.setCursor(0, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(8, 0);
  lcd.print(MAP_Json);
  lcd.setCursor(0, 1);
  lcd.print(LOAD_TM_Json);
}

Finally, I got the solution. Using substring() function, I can able to split my data.
Here, suppose I have two input data with fixed length.
{"TPS":"0.40","MAP":"0.95","LOAD":"14"}

{"LOAD":"2.40","RPM":"4200","INJECTION_TIME":"4.87"}

So, using length() function I got the length of both data. So, I can able to differentiate the different data. In my previous code, I use counter and according to counter index I split my data. But somehow it does not work. So, after using substring() function I got the same result even better.
And below is my whole arduino code:
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";

String data_LOAD_RI_Json = "";
String data_RPM_Json = "";
String data_INJECTION_TIME_Json = "";

String response = "";
bool begin = false;

char in;
int len = 0;

float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

float LOAD_RI_Json;
float RPM_Json;
float INJECTION_TIME_Json;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{
  while(Serial.available() || !begin)
  {
      in = Serial.read();

      if (in == '{')
      {
        begin = true;
      }

      if(begin)
      {
        response += (in);
      }

      if(in == '}')
      {
        break;
      }

      delay(1);
  }

  len = response.length();

  if(len == 39)
  {
    data_TPS_Json = response.substring(8, 12);
    data_MAP_Json = response.substring(21, 25);
    data_LOAD_TM_Json = response.substring(35, 37);

    jsonMapTps();
  }

  if(len == 52)
  {
    data_LOAD_RI_Json = response.substring(9, 13);
    data_RPM_Json = response.substring(22, 26);
    data_INJECTION_TIME_Json = response.substring(46, 50);

    jsonRpmLoad();
  }
}

void jsonMapTps()
{
    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    LOAD_TM_Json = data_LOAD_TM_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(TPS_Json);
    lcd.setCursor(8, 0);
    lcd.print(MAP_Json);
    lcd.setCursor(0, 1);
    lcd.print(LOAD_TM_Json);
}

void jsonRpmLoad()
{
    LOAD_RI_Json = data_LOAD_RI_Json.toFloat();
    RPM_Json = data_RPM_Json.toFloat();
    INJECTION_TIME_Json = data_INJECTION_TIME_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(LOAD_RI_Json);
    lcd.setCursor(8, 0);
    lcd.print(RPM_Json);
    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME_Json);
}

I don't think your loop handles the situation where the data comes in too slowly. Looking at your while condition:
while(Serial.available() || !begin)

Once you receive the start char, this becomes:
while(Serial.available())

Now, if there is a delay in the serial buffer, the loop exits before you have the entire message.
You should change the loop so it only ends when you have all 39 chars.
void loop() {
    while (39 != response.length()) {  // Keep going until full msg {
        // Check for data in serial buffer
        if (Serial.available()) {
            in = Serial.read();
            .....
        }
        // No data?
        else {
            delay(10);
        }
    }

    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    .....
}

Thank you for your efforts. I tried it out. But still not getting data. This looks logically correct, but If data length changed then what? By the way, I got the solution.

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


text:
Manchester.h message format
I'm sending some data by 433Mhz transmitter using manchester.h library from here https://github.com/mchr3k/arduino-libs-manchester and I'm trying to wrap my head around message format. In manchester.cpp it is described very poorly.
I'm sending number 1. Here is the code for that:

#include <Manchester.h>
/*
  Manchester Transmitter example
  Try different speeds using these constants, your maximum
  possible speed will depend on various factors like transmitter
  type, distance, microcontroller speed, ...
  MAN_300 0
  MAN_600 1
  MAN_1200 2
  MAN_2400 3
  MAN_4800 4
  MAN_9600 5
  MAN_19200 6
  MAN_38400 7
*/
  #define TX_PIN 4  //pin where your transmitter is connected

  uint8_t transmit_data = 1;
  void setup() {
  man.setupTransmit(TX_PIN, MAN_4800);
}
  void loop() {
  man.transmit(transmit_data);
  delay(200);
}

Here is the screenshot from oscilloscope:

And here is the message for sending 0:

In manchester.cpp you can find message format:
/*
    format of the message including checksum and ID

    [0][1][2][3][4][5][6][7][8][9][a][b][c][d][e][f]
    [    ID    ][ checksum ][         data         ]
                  checksum = ID xor data[7:4] xor data[3:0] xor 0b0011

*/

But when you look at the actual oscilloscope readings it does not fit at all! Maybe I'm missing something? I'll be very grateful for any help in understanding this topic:)

Looks correct according to the code. The format above is not used for transmit. It is 4-bit sync, 16-bit data, and trailing 3-bit sync. Total 23 bits.

@MikaelPatel But if I'm sending 0, then all 16 bits of data should be 0, which is not the case, Or maybe I'm not seeing something?

The data is xor'ed with a decoupling mask (0b11001010 in this library). https://github.com/mchr3k/arduino-libs-manchester/blob/master/Manchester.cpp#L162 explained here https://github.com/mchr3k/arduino-libs-manchester/blob/master/Manchester.h#L114

The data is sent MSB first with least significant bit first per byte.

@MikaelPatel Ahhhh.... thanks a lot!!!! Do you understand why it is so? It would be far less complex if data was sent just straight bit by bit

An explanation for this design is available in the header file; "it's common to zero terminate a string or to transmit small numbers involving a lot of zeroes those zeroes may be mistaken for training pattern, confusing the receiver and resulting high packet lost, therefore we xor the data with random decoupling mask". This can be avoided by a start symbol in the preamble. Please example in https://github.com/mikaelpatel/Cosa/blob/master/libraries/ManchesterCodec/ManchesterCodec.hh. This is the Ethernet preamble. https://en.wikipedia.org/wiki/Ethernet_frame#Preamble_and_start_frame_delimiter

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


text:
Advanced I/O shifting bits
I wanted to tinker around more with the 8-bit shift register (74HC595) so I tried to make a simple LED display and after reading about some shift commands I got lost and didn't understand much...
Let's start simple...
from what I read -- you can send out Binary data 1s and 0s --- does the shift regsiter read it as on and off? the shift register I'm using which is probably the same thing with others but it has 8 pins that can be used as output --- how does it output the data? --- does it output (example) 10100110 which shifts to the right as if 00000000 -> 10000000 -> 11000000 -> 01100000 -> 00110000 -> 10011000 -> 0100110 -> 10100110 through the pins one by one? like pin 1 would get 0 first then 0 will move to pin 2 and pin 1 will get a 1? (still using 10100110 by example above ^ )
Also what would the code look like? how does shiftOut() and shiftIn() work exactly? does all of this have something to do with pulseIn()? what do the bitwise operators like >> and << or ~ to name a few exactly do?
let's say I made 8 leds hooked up to one of each output pin of the shift-register --- how do I give data to the register? what commands should I use to give data? --- from what I understood I can output 01011011 right? if so, how does the shift-register output it? and if (Assumingly) it does output it like on and off would it eventually turn out as if LED1 = OFF LED2 = ON LED3 = OFF LED4 = ON LED5 = ON LED6 = OFF LED7 = ON LED8 = ON as if I entered in 01011011?
tl;dr
how do 8-bit shift registers work and how do you make codes work with them xP

Voting to close as too broad. You should do some research yourself first. Start by reading a tutorial on the 74HC595 shift register: it should answer most of your questions. Then look at the source code of shiftOut(). If you still have doubts then, come back here with more specific questions.

I bolded out the questions I'd like answered most although I'd understand if you still find it too broad

Did you read the tutorial?

I read another thing about it but it doesn't address above questions or at least I didn't understand those

For the 74HC595 in combination with the Arduino, the best way to check is to use the default example by Arduino:
ShiftOut
With the ShiftOut you can shift the bits into the IC which will make the correct LEDs light up (or not).
Probably you can lit up a LED when passing a HIGH, but you will know very easily by trying the example and check some values/for loops to make them dynamically lighting.
Probably after playing with the example, it will give you much more insight than describing the details here.
Update:

Try first with 00000000 and 11111111 and 8 leds, so you know if 0 will be OFF and 1 will be ON.
Than try with eg 10101010 and 8 leds ... than you know if the first or the last will be on or off.
pulseIn is unrelated
The operators >> and << are so called bit shift operators. Like 1 << 3 gives 8, the binary value 0000001 is shifted 3 bits left resulting in 00001000 which has value 8.
~ is the not operator -> which reverses bits.
The shiftOut function can be used to send data to the 74HC595N.
And to be honest, how does it work ... does it really matter for now? First see what the result is, how to use it. Later you can get into details. Start simple first.

how do I give out 11111111? do I need to make a variable that has 255 to make all bits become 1? or is there another way? --- also the shiftOut works like this "shiftOut(-dataPin-, -clockPin-, MSBFIRST, -variable-)" right? is the dataPin the pin connected to the arduino?

Yes, 255 is 11111111 binary. You can also use a for loop and set each bit with << operator. Data and clock pin are explained in the example (just connect it to the correct pins of the 74HC595, LSBFIRST/MSBFIRST decide the order, the variable is the 255 number above). The data pin you have to connect to the Arduino, otherwise the 74HC595N cannot receive the value.

I see, I see --- I will test this out when I get home thanks for the answer :)


text:
Arduino + L9637 K-Line reader - 10400 baud on SoftwareSerial?
I know this question has been asked many times before in different flavours, but all of the previous questions I have found seem to pre-date the current SoftwareSerial library, which afaik now (unlike when the previous questions were asked) allows any baud rate to be set as it calculates the values for the timings.
So I currently have the L9637 monolithic bus driver connected to pins D0 and D1 of my Arduino Uno. I am trying to create an ECU reader to communicate with my car over the KW1281 protocol, and from testing I have discovered I need to do the 5 baud init and then communicate at 10,400 baud.
First off I want to say I have successfully managed to run the 5 baud init. Now, I realise the pins (D0 & D1) are capable of hardware serial, however when trying to use the hardware serial I couldn't get any connection to the car. I think it's because the hardware serial doesn't like the pin modes to be changed after setup - however this is required to perform the 5 baud init. So I have decided to use the SoftwareSerial library for the following 10,400 baud communication.
With this library I successfully receive three (incorrect) response bytes from the ECU when setting a baud rate of 9600, however the response bytes - despite being correct in the number of them (3) - are wrong in terms of their value and seem to just be zero values.
Now as my car requires 10,400 baud communication, I instead setup the serial port to 10,400 baud. I know from experience that using 9600 baud will give incorrect response bytes and 10400 baud solves this. So I expected this would work and solve my problem, however it didn't. I still get 3 bytes containing 0. Just to be clear the three correct values should be: 55 01 8A
So I was wondering:

Am I right in assuming the SoftwareSerial library will work for any baud rate, even 10,400?
If yes to point 1, can anyone suggest why I might be getting data bytes containing 0 instead of the correct values?

As the full code is too long to post, the code for setting up the UART at 10,400, and then receiving the bytes is as follows:
#include <Wire.h>
#include <SoftwareSerial.h>

SoftwareSerial obd(pinKLineRX, pinKLineTX, false); // RX, TX, inverse logic
obd.begin(baudrate);

uint8_t data = 0;
int recvcount = 0;
char s[3];

while (obd.available())
{
   uint8_t data = obd.read();
   s[recvcount] = data;
   recvcount++;
}

And then to print the data I do the following:
#include <Adafruit_GFX.h>
#include <UTFTGLUE.h>

UTFTGLUE lcd(0x9488,A2,A1,A3,A4,A0);

char textout[30];
int xVal = 50;
cursorY = 10;
for (int i=0; i < size; i++)
{
  uint8_t data = s[i];

  sprintf(textout, "%i ", data);
  lcd.print(textout, xVal, cursorY);
  xVal += 10;
}

cursorY += 10;

The output on the LCD is

0 0 0

When it should be

55 01 8A

I don't have experience with your specific case... I tried to use MIDI over SoftwareSerial (31250 baud). And I missed some messages, especially when there are more messages sent in a shorter period. There are other SoftwareSerial libraries, but had similar problems. So I try to stay away from SoftwareSerial.

Thanks for your reply. Well I believe I cannot use hardware serial so I have no choice really... Although I did see that when using a lower baud and also receiving less messages then there should be less missed messages in the serial connection. Can you by any chance tell me if you had to edit the software serial library to calculate the correct timings for the custom baud rate? Or did you use the latest libraries where the library calculates the timings?

I used the midi library which I passed the baudrate to that library (MIDI library from 47effects). So I did not had to change the library. I will add some more in an answer (gives me some possibility to add bullets).

I've found 9600 baud to be the receive limit among standard baud rates (transmission can go faster). You're proposing an 8% increase over 9600 which sounds like it has a good chance of working but you'll need to experiment to find out.
You also asked why might your data (on the LCD) be wrong.
You'll do your sanity a big favor and do two separate experiments:

First, get known data (literal strings or terminal input) to display correctly on your LCD, before you try to use the LCD to confirm or debug your communications.
Second, get SoftwareSerial running (or find out that it doesn't...) at 10400 baud. In fact try to get up to, say, 12000 baud, or at least push the rate to find out where it starts to fail so you know how much head-room you'll have at 10,400. The simplest way would be to use two Arduinos if you have access to another one. Again, use your terminal or some literal strings on MCU 'A' to send to MCU 'B', MCU 'B' should receive a line and echo it back to 'A', who prints it on its terminal. Printing it on 'B's terminal wouldn't be a bad idea either.

You'll be in a lot better position to combine the two techniques once you have confidence that each one works; especially if you copy-and-paste known-working code segments.

Thanks for your answer, I think I may have not explained the situation very clearly in my original post though. I know for sure my LCD is displaying the correct data so there is no issue there. As for the SoftwareSerial running at 10,400 baud, I know that others have had it running on an Arduino Uno before but that was with the old library which used hardcoded timings. So I guess the take home for now is to as you say try and communicate with a PC running at 10,400 baud in order to reduce the unknowns and very that serial instance.begin(10400) works out of the box (or not if thats the case).

Also the Arduino library specifies the Uno can handle up to 57600 baud, so there shouldn't be a technical issue running 10,400.

Great! When I last tested it, I didn't find it to receive reliably at above 9600 baud. I guess it's time I check my library version & test again. I could sure use that 5x speedup!

I tried using MIDI data with the software library. However, I also got problems with missing and/or corrupted messages. MIDI has a fixed baudrate of 31,250 baud. As long as I did not sent too much, everything was ok, but sending continuous messages (within the 31,250 baud rate spec) I got into problems. It seems that the input buffer was too full and/or no time to process them.
The default buffer for the serial (software serial) buffer was 64 bytes. I increased it to 128, but saw no difference. Making the buffer higher probably just would delay the time until messages are corrupted.
What you can do is:

Use a non Arduino device with multiple UARTs (no experience with that)
There seems to exists a 328PB version of the Uno which has two UARTs (but it maybe a kind of niche device, possibly with support problems)
What I did was using a Mega, it has 4 UARTs.
Using multiple Uno's and/or Mega's connected to eachother, giving 1 resp. 4 UARTs


text:
Servomotor and music shield
I’m trying to make an art sculpture, with an Arduino-uno, a servomotor and a seeduino musicshield v2.0.
I’m making the servo motor moving a stick with the attached fans of the servo, and I want to  synchronize the servo motor with the music shield  and when the motor is stopped(about one minute), the music(about one minute of music) will play and when de motor is moving the music will be stopped.
I'm super noobie with the code. I tried something like this
but, is not moving at all, neither my servo or my musicshield  when I write this:
#include <SD.h>
#include <SPI.h>
#include <arduino.h>
#include <MusicPlayer.h>

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
  Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
}
void loop() {
  mover();
  if ( val == 90) {
    music();
  }
}

void mover () {
  val = 0;// start point
  myservo.write(val);
  delay(800);

  val = 90;
  myservo.write(val);
  delay(60000);//wait for 1 min
}

void music () {

  player.play();
}

when I write this my servo moves, but obviously my music wouldn't play
#include <SD.h>
#include <SPI.h>
#include <arduino.h>
#include <MusicPlayer.h>

#include <Servo.h>
Servo myservo;

int val;//for the servo

void setup() {
  //setup for the music shield
 Serial.begin(9600);
  player.begin();  //will initialize the hardware and set default mode to be normal.
  player.addToPlaylist("a.mp3");
  //setup for the servo
   myservo.attach( 9 );
 }

void loop() {
mover();

 }

 void mover () {
val = 0;// start point
myservo.write(val);
delay(800);

val = 90;//
myservo.write(val);
delay(60000);//wait for 1 min
}

void music () {

  player.play();  //do some leisurely job
}

And the music will play when I write this, obviously the servomotor don't move, so I'm  think I have a problem mixing my servomotor and the musicshield(seeeduino music shield v2.0, and I want the music start when my servo motor is in this point of val=90 delay(60000)
 #include <SD.h>
    #include <SPI.h>
    #include <arduino.h>
    #include <MusicPlayer.h>

    #include <Servo.h>
    Servo myservo;

    int val;//for the servo

    void setup() {
      //setup for the music shield
     Serial.begin(9600);
      player.begin();  //will initialize the hardware and set default mode to be normal.
      player.addToPlaylist("a.mp3");
      //setup for the servo
       myservo.attach( 9 );
      }

    void loop() {

   player.play();
     }

    void mover () {
    val = 0;// start point
    myservo.write(val);
    delay(800);

    val = 90;//
    myservo.write(val);
    delay(60000);//wait for 1 min
    }

with is not working I mean is not moving at all, neither my servo or the music, but when I compile I don't have any mistakes messages

Break the problem down into pieces. First get the servo working without the distraction of the music. Then get the music working without the distraction of the servo. Then combine them. Does the servo work when you write a simple program to move it?

yes, the servo is moving without the musicshield, and the musicshield is working without the servo, I'm having trouble combining both of them

That is very useful information. Could you edit it into your question please?

yes, of course, thank you for helping me, I'm noobie at making questions too

If you use two shields (libraries and such) and each single one is working and together they are not, the most common problem is, that they share something (usually some pin for shields or interrupt for libraries) and do fight over that.

so, I have to search for that something that they're sharing and change it? or is more like they are not going to work together and I need to find another way?(and thank you it was very useful information)

When you say the music wouldn't play in the first case, you did wait the full 1 minute for it to start right?

Is this the MusicPlayer.h that you have?  https://github.com/Seeed-Studio/Music_Shield
From the description it says:

The music player reads data from SD card and then feed into the VS1053 chip via SPI bus. This is done in TIMER1's ISR with a interval of 2ms. This job has a high priority and uses the cpu exclusively. In the spare cpu time, player does some process control, like play/pause.

That's the same timer that Servo.h uses.  So the two libraries are not compatible.  You could try using ServoTimer2 library or rewriting this library to get the 2ms timer with Timer 2.

thank you, yes that's my musicshield, I think I will try the ServoTimer2


text:
What is the purpose of the I/O pin capacitor on the AVR microcontroller?
What is the purpose of the capacitor on the I/O pins on the ATmega328 (I imagine it's on other AVR microcontrollers as well)? Is it to reduce noise from other parts of the microcontroller?

To make explicit the implicit parasitic capacitance on the pin.

So, it's not actually a capacitor, but just drawn in to the schematic to demonstrate that the pin has capacitance?

Correct. The input is actually the gate of a MOSFET. That gate acts like a capacitor. So they show it as one in the simplified block diagram.

The pin does not have a capacitor added to the integrated circuit (IC). Rather this capacitor is drawn to show that the input has capacitance that you need to be aware of.
The input drives a MOSFET - and as we know, MOSFETs have some parasitic capacitance.
For more information on parasitic capacitance of MOSFETs see these pages:

MOS Transistor parasitic capacitances - OnMyPHD.com
MOSFET Parasitic Capacitance and Its Temperature Characteristic - ROHM


text:
Can i create a function inside of void setup()?
Can i create a function inside of void setup()
to recall in loop() function

No. You do not create functions within functions.
You can create a function, and then call it both from setup() and loop() if you so wish.

Defining a function within a function is not supported in C or C++. If it were supported in a way consistent with the rest of the language, the inner function would be local to the outer function, just as local variables are, so not callable or even visible from outside the outer function.
Your loop() function (or any other function) could, however, call the setup() function as long as you want to execute setup() again in its entirety. That means that any initialization you perform in setup() would be repeated each time you call it.

You can create functions within a function if the particular c compiler supports it - gcc, the compiler used by arduino,  does. But not all c compilers support that.
Whether you can create a function within a function that recalls loop() depends on your meaning of "recall".

Can you cite a source or show an example? Local functions aren't part of the C or C++ languages (excepting private member-functions of a class). They would be very useful in a few situations.

@JRobert: https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

You have asked two questions here.  In the title, can you define a function inside of setup():  Yes.
But that is the "scope" of where it can be used.
In Loop() it won't exist, ("xxx undefined in this scope") so the answer to what you ask in the text is No.


text:
Problem with coding
Recently I got this code from a friend which is unfortunately unavailable right now.
When button is pressed two halfbridges are supposed to change directions with increasing  frequency of direction change until button is pressed again and than that frequency remains same.
Potentiometar is there to regulate that incriese of frequency.
For some reason one output is always on other one gets one when I press the button.
This is mentioned double halfbridge board:
http://www.ebay.de/itm/272620735999?_trksid=p2060353.m2749.l2649&var=571741857121&ssPageName=STRK%3AMEBIDX%3AIT
It is working, I checked button and potentiometer too,
Here is the code:
#include "options.h"

float ratio = CHANGE_FREQUENCY_MAX_SEC / 1023.0;

void setup() {
  pinMode(PIN_PWM_COIL_1, OUTPUT);
  pinMode(PIN_PWM_COIL_2, OUTPUT);
  pinMode(PIN_DIR_MOTOR, OUTPUT);
  pinMode(PIN_START_STOP, INPUT_PULLUP);

  digitalWrite(PIN_DIR_MOTOR, HIGH);
  digitalWrite(PIN_PWM_COIL_1, HIGH);
  digitalWrite(PIN_PWM_COIL_2, LOW);
}

void loop() {
  float voltage = 0;
  long steps;
  long pwm_half_period;
  unsigned long change_freq_time = 0;
  unsigned long value_steps = 0;
  unsigned int stop_freq = 0;

  if (digitalRead(PIN_START_STOP)) {
    return;
  }

  steps = (FREQUENCY_STOP_HZ - FREQUENCY_START_HZ) / FREQUENCY_STEP_HZ;

  if (FREQUENCY_STOP_HZ < FREQUENCY_START_HZ ) {
     return;
  }

  // If max number is reached we do nothing error in seetings
  if (steps > FREQUENCY_MAX_CHANGES) {
    return;
  }

  value_steps =  analogRead(PIN_POTENTIONMETER_IN) * ratio + CHANGE_FREQUENCY_MIN_SEC;
  value_steps *= 1000000;

  pwm_half_period  = 500000 / FREQUENCY_START_HZ ;

  change_freq_time = 0;

  while(!digitalRead(PIN_START_STOP)) {

    digitalWrite(PIN_PWM_COIL_1, LOW);
    digitalWrite(PIN_PWM_COIL_2, HIGH);
    delayMicroseconds(pwm_half_period);

    digitalWrite(PIN_PWM_COIL_1, HIGH);
    digitalWrite(PIN_PWM_COIL_2, LOW);
    delayMicroseconds(pwm_half_period);

    change_freq_time++;

    if(value_steps == change_freq_time) {
      change_freq_time = 0;
      pwm_half_period += 500000 / FREQUENCY_STEP_HZ;
      stop_freq = 1000000 / FREQUENCY_STOP_HZ;

      if(FREQUENCY_STOP_HZ == (2 * pwm_half_period)) {
         break;
      }
    }
  }
}

and here is options.h
#ifndef __OPTIONS_H__
#define __OPTIONS_H__

#define PIN_PWM_COIL_1    5
#define PIN_PWM_COIL_2    6

#define PIN_DIR_MOTOR     4

#define PIN_START_STOP    7

#define PIN_POTENTIONMETER_IN A0

#define FREQUENCY_START_HZ    5
#define FREQUENCY_STOP_HZ     1000

#define FREQUENCY_STEP_HZ     10
#define FREQUENCY_MAX_CHANGES 120

#define CHANGE_FREQUENCY_MIN_SEC  1.0
#define CHANGE_FREQUENCY_MAX_SEC  30.0

#endif

and here is the circuit:

It makes little sense to drive both PWM pins but only one DIR pin. Could you post your schematic please?

There is not that much to a curcuit, Just poti and push button.
_PWM_COIL_1 is on 5
_PWM_COIL_2 is on 6
and DIR_motor 2 is on 4 (this one I do not get at all)


text:
Arduino Uno doesn't work as Manchester code receiver
I'm sending some data from ATTINY85 to Arduino UNO using 433Mhz modules. Coding is Manchester using Manchester.h library from here.
Transmitting data works perfectly, 433 receiver gets data alright.
But Arduino UNO does not seem to receive data! Here is the code of the receiver:
/*
  Manchester Receiver example

  In this example receiver will receive one byte of payload and 4 bit sender id per transmission
  message also contains a checksum and receiver can check if the data has been transmitted correctly
  try different speeds using this constants, your maximum possible speed will
  depend on various factors like transmitter type, distance, microcontroller speed, ...
  MAN_300 0
  MAN_600 1
  MAN_1200 2
  MAN_2400 3
  MAN_4800 4
  MAN_9600 5
  MAN_19200 6
  MAN_38400 7
*/
#include <Manchester.h>

#define RX_PIN  4  //pin where your receiver is connected

uint8_t moo = 1;
uint8_t data;
uint8_t id;

void setup() {

//  pinMode( RX_PIN, INPUT );
  man.setupReceive(RX_PIN, MAN_600);
  man.beginReceive();
  Serial.begin(9600);
}

void loop() {
  if (man.receiveComplete()) { //received something
    uint16_t m = man.getMessage();

    Serial.write(m);
    man.beginReceive(); //start listening for next message right after you retrieve the message
  }

}

Transmitter code:
/*
  Manchester Transmitter example

  In this example transmitter will send one byte of data and 4bit sender ID per transmission
  message also contains a checksum and receiver can check if the data has been transmitted correctly
  try different speeds using this constants, your maximum possible speed will
  depend on various factors like transmitter type, distance, microcontroller speed, ...
  MAN_300 0
  MAN_600 1
  MAN_1200 2
  MAN_2400 3
  MAN_4800 4
  MAN_9600 5
  MAN_19200 6
  MAN_38400 7
*/
#include <Manchester.h>

#define TX_PIN  4  //pin where your transmitter is connected
#define SENDER_ID 5

uint8_t transmit_data = 0;

void setup() {
  man.setupTransmit(TX_PIN, MAN_600);
}

void loop() {
  //SENDER_ID can be ID of the sender if you have multiple transmitters so receiver knows who sent it
  //OR it can be receiver ID if you have multiple receivers so receiver knows it's for him
  //OR it can by just any arbitrary 4 bit number
  man.transmit(man.encodeMessage(SENDER_ID, transmit_data));
  transmit_data++;
  delay(200);
}

Anyone got idea what's the problem?

Might want to use Serial.println(m) instead of Serial.write(m) in the receiver sketch.

What clock is used on the ATtiny85? Did you burn the fuses correctly? I.e. is the timing correct?

@MikaelPatel I use 8MHz internal timer. By "burning fuses" you mean settings that I use while uploading program to microcontroller? For example Tools/B.O.D or Tools/Clock?

See "Configuring the ATtiny to run at 8 MHz" in http://highlowtech.org/?p=1695

check that the chip is receiving data at all, and if it works THEN add the manchester code.

Does it work from an Arduino Uno to another Arduino Uno? Does it work when you wire link them together?


text:
Connecting an Arduino Nano, Mega and LCD via I2C works but fails when shutting down Mega
I have connected an Arduino Nano, Mega and a LCD via I2C/TWI (SDA/SCL).
The Nano is playing the master while Arduino Mega and LCD are slaves. This works well till I power off the Arduino Mega. Of cause I don't expect the Mega to answer.
In particular the SCL line seems to pull-down the connection. Disconnecting SCL from the Mega will reestablish the connection to the LCD. I added two pull-up resistors 4.7k to both SDA SCL but no improvement from that.
Is there no way than physically disconnecting the lines?

See
How to setup an I2C bus which stays valid if a slave is powered down or fails?
Basically I2C uses pull-ups to have all lines HIGH until any device bring it LOW. Arduino uses INPUT_PULLUP / OUTPUT+LOW states for this. But if you switch Arduino off (turn off Vcc), internal diodes cut the power on pins to Vcc (which is zero) +diode voltage (which is small), effectively to logical LOW. And I2C see that as the device is activelly sending LOW all the time - so communication is blocked.
If you just add pullup resistors, you either have them high enought so it not prevent this state or you have them low enought to draw the lines HIGH even when there is LOW on device, which prevents other devices to draw them LOW for communication. You need "cut off" such incactive lines - either physically disconnect (pull wires from connector - such as if you just get the Mega out of socket, or use some relays powered from Mega Vcc, which disconnet them when the power goes out) or electrically disconnect - using some circuits designed for it. There are some already sold or you can create your own to the same efect (if you are skilled in this area - otherwise it is much easier and faster to pay for some already made solution)

Or... don't power off the Arduino Mega. Use the same power supply for everything that is connected to the same I2C bus.

Well it would work too :) But I think, there is a reason, why the user wants to power off one of its arduinos, otherwise he would not get in the problem at all.

BTW: I use setup, where I2C network uses 4 wires -SDA,SCK, GND and PWR - so I just power up the I2C bus with pullups and anything connected via I2C is powered from the same source (the I2C bus serves also as Power grid - and can be powered from real power source, not just Arduino). So either it is connected to I2C and powered, or it is not powerd, but also not connected to I2C at all.

that is what we are here for: recognizing what could be a xy-problem: http://xyproblem.info/  My main Arduino Mega project has two of 5 wires. A 5V I2C bus with 5V power plus a interrupt signal and a 3.3V I2C bus with 3.3V power and interrupt signal. The interrupt signal is to detect when a Slave needs attention, for example alarm signals from motion sensors.

There are I2C Multiplexers/Switches that you can use to disconnect automatically such as the PCA9540. I do not know if they are available on breakout boards.


text:
Switch setting 'running' state boolean doesn't hold
I have a rotary encoder and I want to use the switch to stop the rest of my code running, essentially switching off what I have going on.
I have this
boolean running = true;

void setup() {
  pinMode(swPin, INPUT);
  digitalWrite(swPin, HIGH);;
}

void loop() {

  if(digitalRead(swPin) == LOW) {
    running = !running;
  }

  if(running) {
    ...
  }
}

When I enter the if statement catching the switch press running does become false and the rest of the code is stopped. However, once released; running is becoming true again and the rest starts again.
I guess it is because the rotary encoder isn't fixed in the LOW state but I expected the running variable to be set to false and remain since it is declared outside of the loop().
Any guidance would be much appreciated!!

You are constantly toggling it over and over again all the time you are holding the button down. Every iteration of loop() you change the variable to the opposite if you happen to still be holding the button down.

@Manjenko, that makes sense! Thanks :) I have added a switch previous state variable to check and allow the if to only run when I want it. I'll post it up as an answer.

Thanks to @Manjenko's comment I was able to see my error.
Here is my solution:
boolean running = true;
int swReading;
int swPrevious = LOW;

void setup() {
  pinMode(swPin, INPUT);
  digitalWrite(swPin, HIGH);;
}

void loop() {

  swReading = digitalRead(swPin);

  if(swReading == LOW && swPrevious == HIGH) {
    running = !running;
  }
  swPrevious = swReading;

  if(running) {
    ...
  }
}

This is still unlikely to reliably do what you want, due to contact bounce.  To protect against that, add a fraction of a second of time where you ignore the input after deciding it has changed.


text:
Can I include a header file into a new header file?
Can I include a header file into a new header file that I created? I put #include <MCP23S17.h>. I want to create a another header file.

Can I include a header file into a new header file that I created? Yeah. That's what they are meant to be used.

Just remember to put Include guards to avoid problems... And remember to accept the most useful answer to avoid being bumped to the homepage uselessly...

Why not just include both in the final program?
Happens all the time.
DHT.h needs AdaFruit_Sensor.h, for instance, so you just include both.
First AdaFruit
then DHT

Yes, a header can include another header.  But if you are using the Arduino IDE and the headers aren't in the same folder, then you'll also need an #include line for it in the .ino file.

Wouldn't it have been easier to just try it to begin with instead of asking and waiting?

i want to llink MCP23S17.h file to my own created header file

can you give some suggestion to it

Suggestion to what?

Since Arduino IDE 1.6.6 it's no longer necessary to add includes to the sketch for library-library dependencies.


text:
How to use variables and functions across multiple .ino files
I have 2 .ino files (2 tabs) for one Arduino project/sketch: MySketch_File1.ino and MySketch_File2.ino.
I declared in MySketch_File2 variables and functions which I want to use in MySketch_File1, but I get this error massage:

error: 'a' was not declared in this scope

//MySketch_File1.ino
void setup(){
Serial.begin(9600);
Serial.println(String(a));
}

void loop(){

}

Second file:
//MySketch_File2.ino
int a;

How can I declare variables and functions one time in one .ino file and use it across multiple .ino files?

Do you mean multiple .INO files within the same sketch, or each in a completely separate sketch?

Within the same sketch, see edit.

It still raise the question - WHY? (why you want two sketch files and why share variables between them) as maybe you are trying to emulate something, which is already present and in much better and more usable form.

When you compile multiple files in the Arduno IDE the files first get concatenated together.
It happens in alphabetical order, except the main INO file (the one named the same as the folder it's in) is placed first.
In C the order in which things appear in the file matters. Basically you have to make sure that things (like variables, functions, etc) are defined before they are used.
This gets more complex when you have a hidden thing like file concatenation messing things up.
The Arduino IDE tries to hide some of it from you too by making function prototypes, so it doesn't matter what order you define functions in - however that "helpfulness" means you don't learn about the proper structure of a C program.
So what can you do? Well, simply make sure that all your global variables are defined in the main file, unless you know they are only going to be used within the file they are defined in.

What happens if you try to do what a C programmer should do? I mean, in one of the source (e.g. .ino) files you define the variable int a;, then in the other you declare it again with extern int a;. Will this work if 1) the variable is defined in the main ino and 2) if it is defined somewhere else but is declared in the main? I do not have the IDE installed here to test it myself ;)

Not sure. It may complain about multiple definitions of the same symbol, but may not. I'll test it.

It compiles, so yes you can do that, but why exactly would you, when you are then effectively defining it in both files anyway? Just define it in the first. If you want to make something portable between sketches then make it a library.

I think that the extern should be "ignored" (in fact you usually use the extern in the header file which is then included also in the c file defining it)

Yes, I agree that the global variables should be put in the first file so that everyone can access it. Or make a class... This was just the most classical solution (C/C++ compilers do not append source files)

In Arduino the sketch.ino is the main (and only) program, which runs on the processor.
If you upload another sketch to HW, then the previous one is overwritten and does not longer exist on the HW. So there is no way, they can share variables, as they never are run at the same time.
(You can store some values to EEPROM or to external devices, but it is other thing).
What you probabely want to do is use the second file as a library, which is collection of variables and functions, that more then one program can use. Anyway what is used is the text of the library, not the values assigned to variables in one sketch.ino - so other sketch.ino using the same library would have the functions and variables of the same name accessible, but as it is compiled to othe program, the values assigned in one sketch would not be visible in other sketch.
Can you specify, why you want to use variables and functions accross multiple .ino files?
If it is just to not have type it again and again and fix found bugs in each aned every copy separately, then you are looking for libraries.
If you want to share also values (like read and compute value in one .ino then upload another .ino and use the result) you are looking for persistent storages (EEPROM on the chip, SD card via some reader or something like that.
If you want have more Arduinos running at the same time and sharing some values, you are looking for networks, like I2C, Serial communication, Ethernet and such.
If you want run mor programs on one arduino at the same time, you are looking for multitasking where each program is interrupted repeatedly and other one is continued, fast enought to user not notice, or for creatinig more functions and call them from loop() one after one to eg. read sensors, then light LEDs then run motors. State automats can make your way here easier.

Now that the OP clarified the question, this is not the correct answer. He has two "tabs" open, meaning he has two source files for the same program

Ok, this shifted it somewhere else, but still I think it may be relevant to his intent - why he wants to separate the two files - using secondary files to be merged together by some IDE hack while he wants emulate how library do function is not the best approach, if he can use libraries as well

Of course.. Even if I usually tend to split (bigger) programs in smaller chunks (for instance, one file for the main loop, one for one of the peripherals, one for the interface, ...)

Yes, I think, that if I cannot see all relevant code on one (max two) screens, then something is probably wrong. The question is, what is wrong - and so the answers differs. If there are repeated parts, the answer is probably function. If there are lot of functions for one periferial/protocol, the answer is library for this. If the problem is just complicated, so if have a lot of code and functions, there is folding each function and then folding each group of folded functions. So my usual program includes lot of libraries and all functions are folded and main loop/ifs too.

And anything longer then few lines means better editor than Arduino IDE. (I use VIM for example.)

It is simplest to put only one .ino file in a directory with the filename. Why does an `.ino` file have to be in a folder of the same name?
Option 1 (cleanest option): Create a user library.
Option 2  (workaround): Relative paths for #include aren't supported but you can use a symlink to make it appear that there is the same header file in every directory:
sketch1/
  sketch1.ino
  mylib.h
sketch2/
  sketch2.ino
  mylib.h (this is a symlink to sketch1/mylib.h)

Option 3: Avoid Arduino IDE entirely and build using avr-gcc. Example: http://thinkingonthinking.com/an-arduino-sketch-from-scratch/ and Will a .ino Arduino Sketch compile directly on GCC-AVR? This is much more complicated, but supports bigger projects using Makefiles.

Arduino ide has terrible project mgmt capabilities. So two solutions.

Switch to a real ide.
Use an extern atteibute.

You can make this easier by naming only the main sketch file '.ino', and naming all other code files as '.cpp'. The compiler has to know about 'a' before you use it, so declare 'a' in the .ino file as `extern int a;' before its first use, to tell it what 'a' is. Not having that is the reason for the error message.


text:
Programming Arduino via ICSP
I'm trying to programming Arduino Nano with another Arduino Nano via ICSP. I have a 6-pin cable directly connected to the ICSP's pin of the second board:
ICSP NANO ISP 1
pin1 pin2 pin3
pin4 pin5 pin6

ICSP NANO 2 (to be programmed)
pin1 pin2 pin3
pin4 pin5 pin6

I have correspondingly wired pin 1 (ICSP) of nano1 to pin 1 (ICSP) Nano 2, pin 2 (ICSP) of nano 1 to pin 2 (ICSP) Nano 2, etc.
I make this step before flashing: getting the Arduino ISP with example sketch ArduinoISP, plug off the Arduino ISP and attach the 6-pin cable to the ICSP port of the second board, plug Arduino ISP to the USB port, in the Tools menu select Arduino as ISP, load with external programmer, and fail...
This is the log:
avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM12
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         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 : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Errore durante il caricamento dello sketch
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Get yourself a cheap $2 USBASP off eBay. Save yourself the hassle.

You shouldn't connect the two reset pins of both nanos. Connect the reset of the target to pin 10 of the programmer. Also, you need to prevent the programming nano from being reset when the serial connection is opened.

I suggest you to try and read the Arduino page about ArduinoISP.
Particularly, you will notice that pins 11, 12, 13 and Vcc and GND are all common, BUT the reset pin is not common to both boards. So I suggest you to detach the pin 5 of ICSP from the ArduinoISP board and connect it to its pin 10. Or, if you prefer, connect
ISP - Target
+5V - +5V
GND - GND
11  - 11
12  - 12
13  - 13
10  - RST

Then try again

thanks, now im getting that `avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x02
avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
Hardware Version: 4728160
Firmware Version: 0.4598883
Topcard         : STK502
Vtarget         : 1.8 V
Varef           : 0.0 V
Oscillator      : Off
SCK period      : 0.1 us
avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01`

Did you try to flash the ArduinoISP again, then connect the "slave" nano (remember, the pin RST on the slave should be connected to pin 10 on the master) without connecting the slave to the USB and then try to flash with external? If so, try to flash the bootloader (there should be a command in the menus like "flash bootloader", but I don't remember where

i miss the PIN 10 to connect to the RST pin , thanks again

@FrancescoValla Glad this fixed the issue


text:
Read only selected Packet SoftwareSerial
I am reading data from RS485 which is in the following format:
void sendkwh()
{
  RS485Serial.write((byte)0x01); // Meter Address
  RS485Serial.write((byte)0x03); // Read Function Code
  RS485Serial.write((byte)0x40); // Register Address Variable (Start address high bit)
  RS485Serial.write((byte)0x34); // Register Address Variable (Start address low bit)
  RS485Serial.write((byte)0x00); // Register Quantity (High Bit)
  RS485Serial.write((byte)0x02); // Register Quantity (Low Bit)
  RS485Serial.write((byte)0x90); // CRC check code (CRC code Low bit)
  RS485Serial.write((byte)0x05); // CRC check code (CRC code High bit)
}

and I need to read only the 4th and 5th frame of the packet. I am doing it the following way:
RS485Serial.listen();
  if (RS485Serial.available() > 0)
   {

    if(RS485Serial.read() == 0x01)
    {
    for(int i=0; i<4; i++) {

   byte discard = RS485Serial.read();

   }
    byteReceived = RS485Serial.read(); // 4th frame
    byteReceived2 = RS485Serial.read(); // 5th frame

which is working fine. I wanted to know if there is a method to discard the packets without loop?
As in I have changed the sendkwh() as below:
byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };
RS485Serial.write(SendKWh, sizeof(SendKWh));

But don't know how to proceed with tapping the 4th and the 5th frame. Your help is appreciated.

What are the significance of the other bytes in the packet?

But the 4th and 5th frame actually needs to be sent to a server later in the code

If there was no significance they wouldn't exist. What do they all mean? As in - is there a packet header? A checksum? A packet length? What?

In a nutshell: your current reading methodology is seriously flawed and you're lucky it works at all.

Ok, sorry I didn't get your question at first. The other bytes have significance, as in Meter Address, Function Code, CRC code , etc

Can you suggest me how to improve it, or a reading that I may go through. Request your help on this!

That much is obvious. But you still haven't answered me. For me to help you I need to know precisely what the meaning of each individual byte is within the packet. Not just an "oh, it's such and such and such and such", but a list of "The first byte is... The second byte is... The third byte is..." etc, including how they are calculated (in the case of a CRC) or statically defined.

I am updating the question @Majenko

Your reading methodology is flawed from the start and you need to completely change how you do things.  First off, you wait until there is at least one byte in the incoming buffer, then if that byte is 0x01 you then try and read 5 more bytes - even if there is only (say) 2 bytes in the buffer.
Instead you need to set up a sliding window for receiving the data. A sliding window is basically an array that is the same size as the data you are receiving, and as bytes become available they work their way down from the "top" to the "bottom" of the array. When the contents of the array match a certain pattern you know it is a "good" packet and you can use the data form it.
For example, you may have something like:
uint8_t window[8];

void loop() {
    if (RS485Serial.available()) {
        uint8_t b = RS485Serial.read();
        // Slide the contents of the array down
        for (uint8_t i = 0; i < 7; i++) {
            window[i] = window[i+1];
        }
        // Insert at the top
        window[7] = b;

        // If the array starts with 0x01,0x03,0x40,0x34...
        if ((window[0] == 0x01) && (window[1] == 0x03) &&
            (window[2] == 0x40) && (window[3] == 0x34)) {
            // Do something with window[4] and window[5]
        }
    }
}

You could also add checking the CRC to that by comparing the calculated CRC for the incoming packet (however that is done in this protocol) with the last two bytes of the array.

Just one quick question, What is the need to slide the contents of the array down ?

To make room for the new incoming byte. Yes, you could wrap around instead, using a circular buffer, but that gets more complicated to both code and understand. Think of the data as socks on a washing line. You are only interested in the 8 socks that begin with the sequence red, blue, green, yellow. The "window" is the gap between your hands held out in front of you (fingers up, palms away from you, thumb tips touching). You move the "window" (slide it) along the socks until you see just 8 starting with the right sequence.

If I give the condition as (window[0] == 0x01) && (window[1] == 0x03) &&  (window[2] == 0x40) && (window[3] == 0x34) to (window[0] == 0x01) && (window[7] == 0x05) to confirm the window is covering the complete frame, then will I go wrong?

Yes, because window[6] and window[7] are the CRC and will change from packet to packet. You should, as I say in the last line of my answer, calculate the CRC and compare that to windows 6 and 7.


text:
Pass changing analog value from void loop to library .h file
How would I go about passing a void loop analog read value to a library .h file?
I've tried it but it only reads the pot position as soon as I plug the arduino in and does not change once booted up.
arduino main sketch file code;
#include "Arduino.h"
#include "common.h"
#include "synth.h"
#include "serial-in.h"
#include "audio-out.h"

void setup() {
  Synth<0>::initialize();
  SerialIn<0>::open();
  AudioOut<0>::open();
}

void loop() {
  int val = analogRead(A0);
  int val1 = analogRead(A1);
  int val2 = analogRead(A2);
  int val3 = analogRead(A3);
  int val4 = analogRead(A4);
  while (true) {
    if (SerialIn<0>::available()) {
      uint8_t b = SerialIn<0>::read();
      Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
  }
}

.h file code
#pragma once

// #define private public  // for tests

#include "common.h"

// associations of units
#define IOsc        Osc
#define IFilter     Filter
#define IAmp        Amp
#define IEG         EG
#define IVoice      Voice
#define ISynthCore  SynthCore

#include "osc.h"
#include "filter.h"
#include "amp.h"
#include "eg.h"
#include "voice.h"
#include "synth-core.h"

template <uint8_t T>
class Synth {
public:
  INLINE static void initialize() {
    ISynthCore<0>::initialize();
    int val = analogRead(A0);
    int val1 = analogRead(A1);
    int val2 = analogRead(A2);
    int val3 = analogRead(A3);
    int val4 = analogRead(A4);
    // Preset
    ISynthCore<0>::control_change(OSC_MODE      , 0  );
    ISynthCore<0>::control_change(OSC_COLOR     , val);
    ISynthCore<0>::control_change(MOD_RATE      , 8  );
    ISynthCore<0>::control_change(MOD_DEPTH     , val1);
    ISynthCore<0>::control_change(LPF_CUTOFF_ENV, val2);
    ISynthCore<0>::control_change(LPF_RESONANCE , val3);
    ISynthCore<0>::control_change(ENV_A         , val4 );
    ISynthCore<0>::control_change(ENV_D_R       , 1 );
  }

  INLINE static void receive_midi_byte(uint8_t b) {
    ISynthCore<0>::receive_midi_byte(b);
  }

  INLINE static int8_t clock() {
    return ISynthCore<0>::clock();
  }
};

I think it's going to be hard for anyone to answer the question the way you want. Your code has two sets of variables called val, val1 etc: one in your Synth class, one in the loop().  They are different, separate.  Writing to one will not change the other.
Both sets are changed only at startup - first setup() calls Synth::initialize() which does a load of analogRead calls and sets its val variables.   Then in loop() you do more analogRead calls, and set the local val variables.
Synth only does anything with those values when you call initialize(). Does that help?

First of all, the while(true) loop in the loop function is wrong. You will need to put in the loop only the code which needs to be repeatedly called. So
void loop() {
  if (SerialIn<0>::available()) {
    uint8_t b = SerialIn<0>::read();
    Synth<0>::receive_midi_byte(b);
  }

  int8_t level = Synth<0>::clock();
  AudioOut<0>::write(level);
}

Then, I haven't understood where the analog read values are used. Moreover the fact that in the initialization you read the analog values and in the loop you expect them to be passed is inconsistent. From what I read, the values should be passed to control_change; you can do one of these things, in my opinion:
1) manage the analog reading from the main:
void setup() {
    Synth<0>::initialize(analogRead(A0), analogRead(A1), analogRead(A2), analogRead(A3), analogRead(A4));
    SerialIn<0>::open();
    AudioOut<0>::open();
}

void loop() {
    Synth<0>::change_OSC_COLOR(analogRead(A0));
    Synth<0>::change_MOD_DEPTH(analogRead(A1));
    ...

    if (SerialIn<0>::available()) {
        uint8_t b = SerialIn<0>::read();
        Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
}

// in h file

INLINE static void initialize(int val, int val1, int val2, int val3, int val4) {
    ISynthCore<0>::initialize();

    change_OSC_MODE(0);
    change_OSC_COLOR(val);
    change_MOD_RATE(8);
    change_MOD_DEPTH(val1);
    change_LPF_CUTOFF_ENV(val2);
    change_LPF_RESONANCE(val3);
    change_ENV_A(val4);
    change_ENV_D_R(1);
}

INLINE static void change_OSC_MODE(int value) {
    ISynthCore<0>::control_change(OSC_MODE, value);
}

INLINE static void change_OSC_COLOR(int value) {
    ISynthCore<0>::control_change(OSC_COLOR, value);
}

INLINE static void change_MOD_RATE(int value) {
    ISynthCore<0>::control_change(MOD_RATE, value);
}

...

or, alternatively,
...
void loop() {
    Synth<0>::change_param(OSC_COLOR, analogRead(A0));
    Synth<0>::change_param(MOD_DEPTH, analogRead(A1));
    ...

}

// in h file

INLINE static void initialize(int val, int val1, int val2, int val3, int val4) {
    ISynthCore<0>::initialize();

    change_param(OSC_MODE, 0);
    change_param(OSC_COLOR, val);
    ...
}

INLINE static void change_param(uint8_t param, int value) {
    ISynthCore<0>::control_change(param, value);
}

(I prefer the firsti since you can prevent the user from using some parameters)
2) manage the analog reading from the library:
void setup() {
    Synth<0>::initialize();
    SerialIn<0>::open();
    AudioOut<0>::open();
}

void loop() {
    Synth<0>::updateAnalog();

    if (SerialIn<0>::available()) {
        uint8_t b = SerialIn<0>::read();
        Synth<0>::receive_midi_byte(b);
    }

    int8_t level = Synth<0>::clock();
    AudioOut<0>::write(level);
}

// in h file
INLINE static void initialize() {
    ISynthCore<0>::initialize();
    updateAnalog();
}

INLINE static void updateAnalog() {
    int val = analogRead(A0);
    int val1 = analogRead(A1);
    int val2 = analogRead(A2);
    int val3 = analogRead(A3);
    int val4 = analogRead(A4);
    ISynthCore<0>::control_change(OSC_MODE      , 0  );
    ISynthCore<0>::control_change(OSC_COLOR     , val);
    ISynthCore<0>::control_change(MOD_RATE      , 8  );
    ISynthCore<0>::control_change(MOD_DEPTH     , val1);
    ISynthCore<0>::control_change(LPF_CUTOFF_ENV, val2);
    ISynthCore<0>::control_change(LPF_RESONANCE , val3);
    ISynthCore<0>::control_change(ENV_A         , val4 );
    ISynthCore<0>::control_change(ENV_D_R       , 1 );
}

Each method has advantages or disadvantages... You should pick the one more suitable for you

On the first method I get this error:
Expected primary-expression before 'int'
ISynthCore<0>::initialize(int val, int val1, int val2, int val3, int val4);

Sorry, that was a typo. The list of the parameters should have gone in the other initialize line... Now I should have fixed it (int val, int val1, int val2, int val3, int val4 goes in the line above the one where you saw it)

Tried that, another error again I'm afraid. Changed the code as you said
'change_MOD_DEPTH' is not a member of 'Synth<0u>'

@CasperRound the ... at the end means "do this for all the other members you need", so just add the remaining ones ;)

I've already done that. Haha

So is it ok now?

How would I go about passing a void loop analog read value to a library .h file?

What you wanted to do makes little sense. But it is certainly doable. The simplest would be to use an "extern" variable as a bridge.


text:
Decoupling cap for self-powered LED matrix and LED strip
Should I add a decoupling capacitor to my RGB 16x32 LED matrix powered directly via the 5V pin?
When I display a spectrogram, the current load is fluctuating quickly in the 100-250 mA range (on average, the full range is 50-300 mA).
If yes, which capacitor should I pick for this purpose?
I have 0.01 μF, 0.1 μF ceramic and 1 μF, 2.2 μF, 4.7 μF, 10 μF, 100 μF electrolytic caps.
EDIT: I'm also interested to know about this WS2812B LED strip i've connected to the 5 V pin to another Arduino.
After reducing the brightness it has similar current consumption and fluctuation of the LED matrix.
In this tutorial they suggest to add a 1000 μF cap, but in my case the currents are much smaller.

No, there is no need. The matrix already has plenty of decoupling on it, including a large electrolytic for the incoming power and a small ceramic on each of the chips.

Possibly. The LEDs are "active" in that they have drive circuits in them. They should have decoupling with the LEDs in the strips. It can be good to provide a large reservoir capacitor for that though (the equivalent of the electrolytic on your matrix).

i've checked the led strip and indeed it has small caps near each WS2812B chip.


text:
After update via ICSP can't use usb for Serial Reading and Usb for programming board
after update software on my arduino Nano board via ICSP i can't use USB for serial monitor and update software, why?

Update the software that runs on the PC?  Update the Arduino boot loader?  Update some driver or library you are using?  Or, did you just reprogram the Atmel processor directly and erased the Arduino boot loader?

If you did the last, you no longer have an Arduino.  You just have an Atmel processor with some hardware around it.

As stated, it is very difficult for someone to answer this question.  Could you clarify what you have uploaded through ICSP? Mentioning the avrdude command line would already be better (we want to see if you changed fuses, for instances). Showing the output of avrdude might help as well. Also what program did you upload?

Assuming you have reprogrammed the Arduino Nano's Atmel processor (an ATmega328) directly using the processor's ICSP pins, you may have erased the Arduino boot loader from the processor.  In such a case you no longer have an Arduino.  Rather you have an ATmega328 processor surrounded by some hardware.
To recover you need to reprogram the ATmega328 processor with the Arduino boot loader.

I'd agree...
Bootloader has been overwritten by your 'update'..

Not "may" - but "have" - because the ATmega family ISP only supports full chip erase, the only way there is still a bootloader in there is if the ISP operation did no erasing, or if the ISP process happened to re-write a functional bootloader in the proper place alongside any application program it wrote.


text:
Problem with measuring vibrations (Arduino UNO + step motor + accelerometer)
I'm trying to measure vibrations of the motor's shaft that is oscillating due to an eccentric load. For that, I am using the MPU 6050 6 axis accelerometer. The motor is a NEMA 17 stepper, connected to Arduino UNO via EasyDriver v4.4.
I first uploaded my code for the stepper, where I have 2 buttons to control the rotation direction (if you press the left, it goes clockwise and if you press the right button it goes counter clockwise). This code works fine.
Later I uploaded the code only for the accelerometer and it worked fine, however when I'm trying to combine both so that the vibrations could be measured while the motor is running, apparently, I'm losing steps of the motor. Here is the code:
#include<Wire.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;

#define RPMS                300.0
#define STEP_PIN                9
#define DIRECTION_PIN           8
#define GO_PIN_L                3
#define GO_PIN_R                4

#define STEPS_PER_REV         200
#define MICROSTEPS_PER_STEP     8
#define MICROSECONDS_PER_MICROSTEP   (1000000/(STEPS_PER_REV *
MICROSTEPS_PER_STEP)/(RPMS / 60))

uint32_t LastStepTime = 0;
uint32_t CurrentTime = 0;

int Distance = 0;

void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);

  pinMode(STEP_PIN, OUTPUT);
  pinMode(DIRECTION_PIN, OUTPUT);
  digitalWrite(STEP_PIN, LOW);
  digitalWrite(DIRECTION_PIN, LOW);
  pinMode(GO_PIN_L, INPUT);
  pinMode(GO_PIN_R, INPUT);
}

void loop() {
  Distance = Distance + 1;   // record this step
  if (digitalRead(GO_PIN_L) == LOW)
  {
    CurrentTime = micros();
    digitalWrite(8, LOW);
    if ((CurrentTime - LastStepTime) > MICROSECONDS_PER_MICROSTEP)
    {
      LastStepTime = CurrentTime;
      digitalWrite(STEP_PIN, HIGH);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
      digitalWrite(STEP_PIN, LOW);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
    }
  }
  if (digitalRead(GO_PIN_R) == LOW)
  {
    CurrentTime = micros();
    digitalWrite(8, HIGH);
    if ((CurrentTime - LastStepTime) > MICROSECONDS_PER_MICROSTEP)
    {
       LastStepTime = CurrentTime;
      digitalWrite(STEP_PIN, HIGH);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
      digitalWrite(STEP_PIN, LOW);
      delayMicroseconds((MICROSECONDS_PER_MICROSTEP * 0.9) / 2);
    }
  }
//  Wire.beginTransmission(MPU_addr);
//  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
//  Wire.endTransmission(false);
//  Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
//  float AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
//  float AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
//  float AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
//  Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
//  // GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
//  // GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
//  // GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
//  Serial.print("AcX = "); Serial.println(AcX / 16384);
//  Serial.print(" AcY = "); Serial.println(AcY / 16384);
//  Serial.print(" AcZ = "); Serial.println(AcZ / 16384);
//  Serial.print(" Tmp = "); Serial.print(Tmp / 340.00 + 36.53);
//  Serial.println("");
//  // Serial.print(" | GyX = "); Serial.print(GyX);
//  // Serial.print(" | GyY = "); Serial.print(GyY);
//  // Serial.print(" | GyZ = "); Serial.println(GyZ);
//  delay(333);
}

So the commented portion of the code is used to read and print accelerations. Since this is in the same loop as the code for the motor, I'm sure that the delay(333) has a negative effect, but also when I tried step-by-step to include lines of code for accelerometer, the motor slowly started to losing speed and steps...
Does anyone of you have a clue how this could be done so that both devices (the motor with EasyDriver v 4.4 and the accelerometer) could run simultaneously since there can't be 2 void loops? I don't know how I could timewise separate their individual codes since I need to monitor the motor with the accelerometer...
Kind regards,
Luka

Thank you gilhad and Jot for your time, I really appreciate it. However, my best friend who happens to be an electric guru as far as I am concerned, proposed an ever more elegant solution to this multi-tasking problem.
He proposed to use timer settings in the void setup, like this:
#include<Wire.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;

#define RPMS                300.0
#define STEP_PIN                9
#define DIRECTION_PIN           8
#define GO_PIN_L                3
#define GO_PIN_R                4

#define STEPS_PER_REV         200
#define MICROSTEPS_PER_STEP     8
#define MICROSECONDS_PER_MICROSTEP   (1000000/(STEPS_PER_REV * MICROSTEPS_PER_STEP)/(RPMS / 60))

uint32_t LastStepTime = 0;
uint32_t CurrentTime = 0;

int Distance = 0;

void setup() {
  bitClear(SREG, 7);
  pinMode(10, OUTPUT);

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
  TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
  OCR1A = 2423; //timer šteje do 444, tako dobim PWM frekvenco 36,363kHz
  OCR1B = int(OCR1A / 2); //prilagajam duty cyle, naj bo kar 50%

  bitSet(SREG, 7); //global interrupt enable

  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);

  pinMode(DIRECTION_PIN, OUTPUT);
  digitalWrite(DIRECTION_PIN, LOW);
  pinMode(GO_PIN_L, INPUT);
  pinMode(GO_PIN_R, INPUT);
}

void loop() {
  Distance = Distance + 1;   // record this step
  if (digitalRead(GO_PIN_L) == LOW)
  { TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0;
    delay(100);
    TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
    OCR1A = 2423; //timer šteje do 444, tako dobim PWM frekvenco 36,363kHz
    OCR1B = int(OCR1A / 2); //prilagajam duty cyle, naj bo kar 50%

    digitalWrite(8, LOW);
  }
  if (digitalRead(GO_PIN_R) == LOW)
  {
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0;
    delay(100);
    TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
    OCR1A = 2423; //timer šteje do 444, tako dobim PWM frekvenco 36,363kHz
    OCR1B = int(OCR1A / 2); //prilagajam duty cyle, naj bo kar 50%

    digitalWrite(8, HIGH);
  }
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
  float AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  float AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  float AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  // GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  // GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  // GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.println(AcX / 16384);
  Serial.print(" AcY = "); Serial.println(AcY / 16384);
  Serial.print(" AcZ = "); Serial.println(AcZ / 16384);
  Serial.print(" Tmp = "); Serial.print(Tmp / 340.00 + 36.53);
  Serial.println("");
  // Serial.print(" | GyX = "); Serial.print(GyX);
  // Serial.print(" | GyY = "); Serial.print(GyY);
  // Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}

So the portion in void setup:
  bitClear(SREG, 7);
  pinMode(10, OUTPUT);

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1A = _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
  TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10); //prescaler 1, fast PWM, OCR1A as TOP
  OCR1A = 2423; //timer counts to 444, PWM frequency is thereby 36,363kHz
  OCR1B = int(OCR1A / 2); //duty cyle is 50%

  bitSet(SREG, 7); //global interrupt enable

rotates the step motor WITHOUT any code in the void loop, void loop is only used to change the rotation direction of the motor by using the buttons that I incorporated (GO_PIN_L and GO_PIN_R) and to measure the acceleration with the accelerometer.
I hope this helps to anyone that might have similar problems.
Kind regards,
Luka

Accept your own answer to close this question.

This is common problem, how to do two (and more) things with waiting, without blocking delay (the simplest way is in example BlinkWithoutDelay)

You wait for motor microsteps (with delayMicroseconds)
You wait between reading MCU (with delay(333))
You spend time sending Transmission over Wire (that is relatively slow) and getting answer requestFrom (also slow)
You spend time sending prints over Serial

Each of this is blocking delay of some kind under Arduino (and writing the transmission in non-blocking way is not an easy task)
You should use some kind of state automaton (google that) for that (or more such automats - each for one task), to overcome the blocking nature of the steps.
basically you can have lot of loops running together in this manner:
long state1_micros,state2_micros,state3_micros; // last time it happened
long state1_delay,state2_delay,state3_delay; // how long wait for next step
#define LOOP1_STEP1 1
#define LOOP1_STEP2 2
#define LOOP1_STEP3 3
#define LOOP2_STEP1 1
#define LOOP2_STEP2 2
#define LOOP2_STEP3 3
#define LOOP2_STEP4 4
#define LOOP2_STEP5 5
#define LOOP2_STEP6 6
#define LOOP2_STEP7 7
void setup(){
...
 long current_micros=micros() ; or millis, if less precision needed
 state1=LOOP1_STEP1;
 state1_micros=current_micros;
 state1_delay=0;
 state2=LOOP2_STEP1;
 state2_micros=current_micros;
 state2_delay=0;
 // state3=LOOP3_STEP1;
 // state3_micros=current_micros;
 // state3_delay=0;
}

void loop(){
 long current_micros=micros() ; or millis, if less precision needed
 if (state1==LOOP1_STEP1 && current_micros-state1_micros>=state1_delay) {
   //state1 paused for at least state1_delay
   if (/*some condition for leave state1 step1  like (digitalRead(GO_PIN_L) == LOW)*/) {
     state1=LOOP1_STEP2;// next step
     state1_micros+=/*some delay like MICROSECONDS_PER_MICROSTEP */;
     /* do action for STEP1, like  digitalWrite(8, LOW); */
    }
  }
 if (state1==LOOP1_STEP2 && current_micros-state1_micros>=state1_delay) {
   //state1 paused for at least state1_delay
   if (/*some condition for leave state1 step2  like (True)*/) {
     state1=LOOP1_STEP3;//next step
     state1_micros =/*some delay like(MICROSECONDS_PER_MICROSTEP * 0.9) / 2) */;
     /* do action for STEP2, like  digitalWrite(STEP_PIN, HIGH); */
    }
  }
 if (state1==LOOP1_STEP3 && current_micros-state1_micros>=state1_delay) {
   //state1 paused for at least state1_delay
   if (/*some condition for leave state1 step3  like (True)*/) {
     state1=LOOP1_STEP1;//next step
     state1_micros =/*some delay like(MICROSECONDS_PER_MICROSTEP * 0.9) / 2) */;
     /* do action for STEP2, like  digitalWrite(STEP_PIN, LOW); */
    }
  }
////////
 if (state2==LOOP2_STEP1 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step1  like (digitalRead(GO_PIN_L) == LOW)*/) {
     state1=LOOP2_STEP2;// next step
     state1_micros+=/*some delay like 100*1000 (333/3) */;
     /* do action for STEP1, like
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
  float AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  float AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  float AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  // GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  // GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  // GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
 */
    }
  }
 if (state2==LOOP2_STEP2 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state1 step2  like (True)*/) {
     state2=LOOP2_STEP3;//next step
     state2_micros +=/*some delay like 10*1000 (10ms) */;
     /* do action for STEP2, like  Serial.print("AcX = "); Serial.println(AcX / 16384);  */
    }
  }
 if (state2==LOOP2_STEP3 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step3  like (True)*/) {
     state2=LOOP2_STEP4;//next step
     state2_micros +=/*some delay like 10*1000 (10ms) */;
     /* do action for STEP3, like Serial.print(" AcY = "); Serial.println(AcY / 16384); */
    }
  }
 if (state2==LOOP2_STEP4 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step4  like (True)*/) {
     state2=LOOP2_STEP5;//next step
     state2_micros +=/*some delay 10*1000 (10ms) */;
     /* do action for STEP4, like  Serial.print(" AcZ = "); Serial.println(AcZ / 16384); */
    }
  }
 if (state2==LOOP2_STEP5 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step5  like (True)*/) {
     state2=LOOP2_STEP6;//next step
     state2_micros +=/*some delay 10*1000 (10ms) */;
     /* do action for STEP5, like  Serial.print(" AcZ = "); Serial.println(AcZ / 16384); */
    }
  }
 if (state2==LOOP2_STEP6 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step6  like (True)*/) {
     state2=LOOP2_STEP7;//next step
     state2_micros +=/*some delay 10*1000 (10ms) */;
     /* do action for STEP6, like  Serial.println(""); */
    }
  }

 if (state2==LOOP2_STEP7 && current_micros-state2_micros>=state2_delay) {
   //state2 paused for at least state2_delay
   if (/*some condition for leave state2 step7  like (True)*/) {
     state2=LOOP2_STEP1;//start over
     state2_micros +=/*some delay (333-100-4*10)*1000 (rest to 333ms) */;
     /* do action for STEP7, like  nothing*/
    }
  }
/////
/* if we have more automatons, like stat3, stat4 and so on, put it her */
} // end loop()

I associate a state machine with a switch-case statement. The name 'STEP' for the state machine is confusing because a stepper motor is involved. The name 'STATE' might be better. Whatever you do, you MUST make the timing variables "unsigned long" to avoid the rollover problem. mcluka, gilhad is making two seperate state machines in the loop function. Using a state machine together with the millis function is indeed the ideal solution.

Yes, unsingned long of course, my bad, wrote it from head before first cofee. switch-case is also sometimes more descriptive, in my last project I needed one machine "preferred", so I used if series (with returnin each part), where the more critical parts was solved first, then the less critical and the machines was reordered and interchanged heavily. So I first mentioned the google, then ofered one exapmle approach. There is much more ways hoe to do it.


text:
Issue with Speck cipher on Arduino UNO
I found a library for the Speck cipher here: https://github.com/Chien-Ning/ArduinoCrypto
And I'm trying to use but haven't had much luck. My code is the following:
#include <SPECK_AVR.h>
#include <SPECK_spec.h>

#include "SPECK_AVR.h"

void setup() {
  // put your setup code here, to run once:

  SpeckTxtLen = 32;
  SpeckKeyLen = 64;
  speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

  speckKey();
  speckEnc();

  Serial.println("");
  for (int i = 0; i < SpeckTxtLen/8; i++){
  Serial.print(speckTxtKey[i], HEX);
  Serial.print(", ");
  }
}

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

}

And I'm getting this error:
error: lvalue required as left operand of assignment

and
error: expected primary-expression before ']' token

Do you think I'm missing something in the usage of this library?
Thanks in advance

speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

That's not how you assign an array.
And you never defined a type for the array.
It sould be:
byte speckTxtKey[] = {0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00};

EDIT:
I checked the source of the library to figure out how to use it, but it doesn't seem the library is meant for actual use.
SpeckTxtLen and SpeckKeyLen are macros inside SPECK_AVR.h, which are supposed to be changed there, not in your code.
The library also defines speckTxtKey inside SPECKenc_AVR.cpp with predefined test data based on the chosen length.
This library looks like a test implementation of the speck cipher, which was just dumped onto GitHub.

Thanks, I got rid of my error with this, but now I'm getting others, but I think it's related to the library. Should I post another question with respect to them?

False alarm, I'm still getting the "error: lvalue required as left operand of assignment". The other error is gone, but still with the one I mentioned.

@LuzA I now checked the source code of the library and it doesn't look like it's meant to be used for arbitrary data without modifications.

so I need to change the key and everything directly into the .h and .cpp files?


text:
Loop code without manually pressing the button
In a piece off code I am modifying I have a button connected to start the code and then it resets its self afterwards. Is they a way to make the arduino loop that code without manually pressing the button again?
This is a section off the code:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
#define PIN 6
#define BUTTON_PIN 9

Adafruit_NeoPixel strip = Adafruit_NeoPixel(120, PIN, NEO_GRB + NEO_KHZ800);

bool oldState = HIGH;
int showType = 0;

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  // Get current button state.
  bool newState = digitalRead(BUTTON_PIN);

  // Check if state changed from high to low (button press).
  if (newState == LOW && oldState == HIGH) {
    // Short delay to debounce button.
    delay(20);
    // Check if button is still low after debounce.
    newState = digitalRead(BUTTON_PIN);
    if (newState == LOW) {
      showType++;
      if (showType > 9)
        showType=0;
      startShow(showType);
    }
  }

  // Set the last button state to the old state.
  oldState = newState;
}

void startShow(int i) {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
  resetFunc();  //call reset
}

Thanks Reece

https://pastebin.com/BULf5CfQ

Remove the loop() function, and rename void startShow(int i) as void loop().

Move startShow(showType); to just above   oldState = newState;. That way it get called al the time, and the button still changes the showType.

Could you describe more clearly what you want to happen please? Do you want to wait for the button to be pressed then do the LED stuff forever?

Yeah that is correct I want to wait for the button press then for the led's loop forever.

If you want the led stuff to loop forever, why are you resetting the board at the end of that function?  Why not just let loop call it again?

As pointed out by Delta_G, there is no point in resetting your program.
What you should do is think your program in terms of the Arduino logic:

You put in setup() the code you want to run when your program
starts.
You put in loop() the code you want to run over and over again.

In this case loop() is fairly simple, as the stuff you want to run
over and over again is the animation, thus:
void loop() {
  colorWipe(strip.Color(75, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 75, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 75), 50); // Blue
  theaterChase(strip.Color(75, 75, 75), 50); // White
  theaterChase(strip.Color(75, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 75), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
}

Note that I removed the call to resetFunc().
The stuff you want to do at startup is the initialization. Oh, wait. In
a comment you wrote “I want to wait for the button press”. So this also
has to be done before the program starts looping. Hence your setup()
should initialize stuff, then wait for the button press:
void setup() {
  // Initialize the strip to all piwels off.
  strip.begin();
  strip.show();

  // Wait until the button is pressed.
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  while (digitalRead(BUTTON_PIN) == HIGH)
      ; // do nothing
}


text:
MH-Z19 with Arduino null output
I want to get CO2 value by using MH-Z19. I tried this code with Arduino uno R3 but I always get this result (CRC 0/0). I didn't understand where is the problem.
I linked A0 with TX of sensor and A1 with RX, I powered the card with 3.3V/Vin to visualize the result on PC via USB port.
 #include <SoftwareSerial.h>;

 SoftwareSerial mySerial(A0, A1); // A0 - к TX сенсора, A1 - к RX

 byte cmd[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
  unsigned char response[9];

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

 void loop()
{
mySerial.write(cmd, 9);
 memset(response, 0, 9);
 mySerial.readBytes(response, 9);

  int i;
byte crc = 0;
 for (i = 1; i < 8; i++) crc+=response[i];
 crc = 255 - crc;
 crc++;

  if ( !(response[0] == 0xFF && response[1] == 0x86 && response[8] == crc) )
 {
Serial.println("CRC error: " + String(crc) + " / "+ String(response[8]));
  } else {
unsigned int responseHigh = (unsigned int) response[2];
unsigned int responseLow = (unsigned int) response[3];
unsigned int ppm = (256*responseHigh) + responseLow;
Serial.println(ppm);
}

Start by modifying your sketch to print out the return value of readBytes() and the actual byte values in the receive buffer.  If you have a scope or logic analyzer you might try monitoring the command and response directly.  If SoftwareSerial has the same 1 second default timeout as hardware serial, it is probably never getting a response and timing out with an empty buffer still at the initialized zeroes.  Perhaps you should check that the return value of readBytes() indicates the expected number of characters have been received.

@ChrisStratton thank you for your response. I changed the softwareSerial pins to Digital one ( pin 0 Arduino (RX) linked to TX of sensor and pin 1 Arduino (TX) linked to RX of sensor), I get this as output: 32 - 30 - 20 - 2D - 20 - 33 - 33 - 20 - 2D - END                           I think it is not correct since according to the datasheet the first byte should always be 0xFF

From the datasheet, working voltage for MH-Z19 is 3.6V to 5.5V, so 3.3V is not enough. (Although the interface runs at 3.3V).

Also, the Uno might not run reliably at 16MHz and 3.3V.

Edited image from datasheet page 303.

thank you for your response. I have the same result (CRC 0/0) even with Wemos D1 powered with 5V.

@user3921905 -- You should probably add the details of all you have tested to the question. Also please post a pic of your setup with wiring, etc.

I updated my question.


text:
Arduino Yun V2.0.1 can't configure WiFi
I can't configure at 192.168.240.1. It's giving me this message multiple times:
1- AJAX/HAR Error:0 has not allowed Arduino Configuration Wizard to complete.
Details of my board:
Arduino Yun V2.0.1 anders evinrud

Comments on a non-answer (since deleted) have been moved to chat.

I have this error too when I typed a wrong password to connect to the green 'osjs' interface.
have you changed the password of your board ?
have you tried the 2 possible passwords ( "arduino" or "doghunter" ) depends on the image installed ?
hacve you cleared your browser cache / test with another browser ?

I managed to pass through it...n my project had completed☺

@hydrogen.uranium235 then why don't you answer your question to help out anyone else who may have this issue?

First, u can just ignore the error and check back is ur IP add changed after several times of configuring.

Second, if it is still not working, and u cant enter the site with the new IP address, u just need to hard reset the arduino...mayb cz u did it so many times.

@hydrogen.uranium235 please submit your answer by clicking on the "Answer Your Question" button at the bottom of the page. Once submitted, then accept the answer by clicking on the green tick under the vote area. Please don't post the answer as a comment.