text:
Help with function template syntax
I am trying to understand the following code snippet from the Espressif OTABasic example for the ESP32 wireless/BT module (see this repository for the full code).
 ArduinoOTA
.onStart([]() {
  String type;
  if (ArduinoOTA.getCommand() == U_FLASH)
    type = "sketch";
  else // U_SPIFFS
    type = "filesystem";

  // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
  Serial.println("Start updating " + type);
})
.onEnd([]() {
  Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
  Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
  Serial.printf("Error[%u]: ", error);
  if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  else if (error == OTA_END_ERROR) Serial.println("End Failed");
});

The initial 'ArduinoOTA' looks kinda like an implied 'with ArduinoOTA' statement, but I can't find anything like that in the reference documents.  I know it has something to do with the way the function templates in 'ArduinoOTA.h', but it's beyond me to untangle the syntax.
May I buy a clue, please?
TIA,
Frank
Thanks to all for the clues; I'm an old-time c/c++ programmer, but must have slept through the 'lambda function' class ;-).
To help my somewhat calcified brain, is it functionally equivalent (if more clunky) to write the above snippet as shown below with the handler functions 'unchained'?
    ArduinoOTA.onStart
([]() //lambda function
    {
        String type;
        if (ArduinoOTA.getCommand() == U_FLASH)
            type = "sketch";
        else // U_SPIFFS
            type = "filesystem";

        // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
        Serial.println("Start updating " + type);
    }
);

ArduinoOTA.onEnd
([]() //lambda function
    {
        Serial.println("\nEnd");
    }
);

ArduinoOTA.onProgress
([](unsigned int progress, unsigned int total) //lambda func with arguments
    {
        Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
    }
);

ArduinoOTA.onError
([](ota_error_t error) //lambda func with arguments
    {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
        else if (error == OTA_END_ERROR) Serial.println("End Failed");
    }
);

TIA,
Frank

This is called (by me, anyway) "method chaining".
It's nothing special, really.  ArduinoOTA is just an instance of the class ArduinoOTAClass.
Each method of that class does what it needs to do, then returns a reference to the object that the method is within.  Which means that you can then call a method on that returned reference ... and so on.
All the rest of it is "lambda" functions - that is, functions that are embedded within the parameters of the functions being called.
The basic result is something like:
A.foo().bar().baz();

Where A.foo() returns A. A.bar() returns A. A.baz() returns A.
You can do the same with:
A.foo();
A.bar();
A.baz();

that snipet looks like a multiple event handler declaration or multiple event handler overloading

@jsotola It's just passing anonymous ("lambda") functions as parameters to simple methods which then store those functions as as pointers and return the object again. Nothing magic about it, and no overloading or anything like that.

i learn something new every day ... thank you


text:
Unsure if my NEMA 14 stepper motor wiring is correct
So I'm pretty brand new to Arduino's in general so I do apologize if its a simple mistake. But basically I'm trying to use the <Stepper.h> library to control my NEMA 14 motor on an arduino with a CNC shield and a A4988 driver. Specifically at this moment I am testing out this code:
/*
 Stepper Motor Control - one step at a time

 This program drives a unipolar or bipolar stepper motor.
 The motor is attached to digital pins 8 - 11 of the Arduino.

 The motor will step one step at a time, very slowly.  You can use this to
 test that you've got the four wires of your stepper wired to the correct
 pins. If wired correctly, all steps should be in the same direction.

 Use this also to count the number of steps per revolution of your motor,
 if you don't know it.  Then plug that number into the oneRevolution
 example to see if you got it right.

 Created 30 Nov. 2009
 by Tom Igoe

 */

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken

void setup() {
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:");
  Serial.println(stepCount);
  stepCount++;
  delay(500);
}

Now unfortunately when I run this code I can hear the motor whirring, but it doesn't revolve. I'm guessing that either I wired the motor incorrectly, or because I'm using a CNC shield the pins in the code should be different. Also, I've checked the voltage going into the driver in accordance with this website. I've also attached pictures below of my setup to just to make everything clear:

Picture of CNC shield atop Arduino board with wires connected as follows:

Picture of Stepper motor I'm using:

Specifications of the NEMA 14 motor I'm using:
Can be seen here

I'm sorry for the convoluted post but I am kind've stuck so any help would be greatly appreciated and if there's any more info needed to help clarify my problem I will update the post or reply to your comments. Thanks!

please, no pictures of text ... add the actual code to your post and delete the picture of the code

I didn't check your motor / driver, but you could check first if you are initialising myStepper correctly; also see here. What are the specs of your motor and shield?

Sorry, changed the picture to the provided code from the stepper library examples

The specs of the motor are outlined in the post at the very end, but to sum it up its a bipolar motor with 200 steps/rev. Also the code is provided code from the library so I don't think its incorrect, but I can try to change the initialization to what you linked and will update. Thanks.

Edit: It was not the initialization, so I think it has to do with wiring or pins addressed.

I would first check with a multimeter which pins from the the shield have voltage. Draw on a piece of paper the sequence of pin activated by the driver and check your motor connection. Probably you have just inverted two wires, this would also explain the whirring sound.

Interestingly enough, I think my wiring was correct, but the stepper library code that I was using didn't like the fact I was using a CNC shield because when I used code that needed no library and just hand-coded the pin steps it worked. Thanks for the reply though!

source: Stack Exchange

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

sort: votes


text:
How to connect a thermal printer to an ESP32?
I want to attach my GOOJPRT Thermal Printer (I believe model QR701, communication RS232) to my ESP32 but I cannot seem to get them working.
I tried all the Adafruit Thermal Printer library examples but get the same error each and every time:
"Error compiling for board ESP32 Dev Module."

I guess the libraries are not meant for the ESP32.
I also tried the "Thermal Printer Library" by Larry Bank (which should be compatible with the ESP32 according to its github docs) but there I cannot figure out how to connect the wires of thermal printer to the ESP32 correctly.
Of course, I do not ask for a specific solution, I am just looking for someone to point me in the right direction!

This is an image of the exact thermal printer I have
Full error message from Adafruit Thermal Printer examples:
C:\Users\Thomas\Documents\Arduino\libraries\SoftwareSerial-master\SoftwareSerial.cpp:41:27: fatal error: avr/interrupt.h: No such file or directory
compilation terminated.
Multiple libraries were found for "Adafruit_Thermal.h"
 Used: C:\Users\Thomas\Documents\Arduino\libraries\Adafruit_Thermal_Printer_Library
 Not used: C:\Users\Thomas\Documents\Arduino\libraries\Adafruit-Thermal-Printer-Library-master
Multiple libraries were found for "SoftwareSerial.h"
 Used: C:\Users\Thomas\Documents\Arduino\libraries\SoftwareSerial-master
 Not used: C:\Users\Thomas\Documents\Arduino\libraries\EspSoftwareSerial
exit status 1
Error compiling for board ESP32 Dev Module

Second error message from Adafruit Thermal Printer example after removing the manually installed SoftwareSerial.h:
A_printertest:21:28: fatal error: SoftwareSerial.h: No such file or directory
Multiple libraries were found for "Adafruit_Thermal.h"
compilation terminated.
 Used: C:\Users\Thomas\Documents\Arduino\libraries\Adafruit_Thermal_Printer_Library
 Not used: C:\Users\Thomas\Documents\Arduino\libraries\Adafruit-Thermal-Printer-Library-master
exit status 1
SoftwareSerial.h: No such file or directory

What is the error you are actually getting? The message you pasted us is the one telling you that an error occurred, not what the error was. Without the actual error we can't help you.

@Majenko♦ Please see the full error message above, which I copy pasted from the Arduino IDE

It looks like you have installed some other SoftwareSerial library manually. You should never ever need to do that since almost all cores bundle their own version that is specific to the core. Delete it. You don't want it. Ever.

@Majenko♦ Thanks for the info! I manually installed the SoftwreSerial because the IDE was giving the error "No such file or directory" error. It also gives me this error after I deleted the library which I installed manually.

Well, remove the library again, then try compiling, and post what you get then.

@Majenko I posted the other message on the bottom again. I am a tiny step further now, I managed to get output from my thermal printer through the Serial2 port on my ESP32 (tx/rx on pin16/17). Unfortunately the output is all gibberish but consistent (baudrate is correct). I posted a topic here on the Adafruit forum: https://forums.adafruit.com/viewtopic.php?f=22&t=174116

ÊSP32 has three hardware serial ports (UARTS), so no need for SoftwareSerial. To use Serial1 and Serial2, see e.g. https://github.com/espressif/arduino-esp32/issues/1838#issuecomment-418744153

@ridgy thanks for your reply, I have figured that out and I got the printer to output something. There still is a problem though, the text that comes out of the printer is not as it should even though my baudrate is correct. Please see the following link, maybe you know what goed wrong https://forums.adafruit.com/viewtopic.php?f=22&t=174116

What if you replace printer.println() by Serial2.printl()? You should not need the Thermalprinter library to just print out normal text - if that works, the error is in the library.

You need to use the <HardwareSerial. h> library. SoftwareSerial is for Arduino boards.
"Thermal Printer Library" by Larry Bank is for GOOJPRT PT-210 and uses Bluetooth. Won't work for QR-701.
Instead of using Adafruit Library, you can try with this: ThermalPrinter.
This May Help,
Peter

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


text:
Loading local libraries
I'm new to Arduino/C development (coming from a JavaScript/Ruby environment), but I was wondering if it was possible to include a library from a custom folder within a sketch?
So this is my situation;
project.ino
libs/
  MyNewLib/
    MyNewLib.h
    MyNewLib.ccp

Now my question is: how can I include my custom library? I've tried several variations on this;
# project.ino

#include <libs/MyNewLib/MyNewLib.h>
#include "libs/MyNewLib/MyNewLib.h"
#include <./libs/MyNewLib/MyNewLib.h>
#include "./libs/MyNewLib/MyNewLib.h"

But none of them works. Can anyone tell me if this is possible? I've looked into this question around the web, but I can't find any satisfying answer. Hopefully you guys can help.
Cheers.
UPDATE
I'm aware you can put your libraries in your global libraries folder, but I want them in my local project folder. I want to share them through git with my team.

Please read my question again @Tyson. I'm aware of the global libraries solution, but I want them inside my project.

You have to first tell the IDE where to find the library (see prior link) then within your sketch you call the library.  #include <LibraryName.h>  AFAIK you can not combine the two into a single include specifying the path/to/library/ which is what I guess you're asking.

Okay, so I can't include files from subfolders.. That's a pity..

Windows Symlinks

Yeah I guess symlinks are the only option. Or a custom Makefile, but I'm not sure about that. Thanks!

On windows you can use Visual Micro and Visual Studio. Supports local Arduino libraries. For an example sketch with a local library click "File>New>Project>Arduino Library"

You are stumbling on the fact that the Arduino tools are fundamentally incompatible with real, mature or professional software practices.  They'll probably also incessantly complain about that .git directory, though it won't actually break the build.

Okay, here is how it works, and I checked it to make sure.
Sure you can use hard paths, but every programmer hates using hard paths. They are not portable at all, and they lock your program in place. You use soft or hard links to the files in the project (look up the man pages on "ln"). But,... talk about ugly! So the question is how to do it "correctly"? The key is learning with what parameters and in what path the C/C++ compiler runs.
You will find the conclusion is NOT intuitive at all. Cutting to the chase: relative paths don't work correctly. Now, why?
But first, let me explain why anyone would want to place program files outside the project directory. Programmers like writing program classes, structs, methods, functions, macros, etc., once. As soon as the programmer solidifies the program fragment, he/she wants to put the files in a common tree and move on. Every program thereafter could use that private library. Also, by having the files in a central place, you won't have multiple copies and versions of each. One private library for many private programs.
As of 1.6.13 (Teensy does not yet support 1.8.*), relative includes start from the library, not your directory. It appears that the ano-to-C filter (remember that Arduino does a "conversion" to the target then calls the C/C++ compiler) starts where you installed your Arduino tree. In my case, I installed in "~/bin/arduino". Teensy's home is "./hardware/teensy". The entire home path for the libraries is "~/bin/arduino/hardware/teensy/avr/libraries" where you will find all the support program trees.
In a source file, the '#include "test.hpp"' statement correctly picks the file from your current directory. HOWEVER, if you use '#include "../test.hpp",' the include path does not start in your project directory. Instead it starts in "./libraries"! So the resulting path is:
#include "../test.hpp" ==> ./arduino/hardware/teensy/avr/libraries/test.hpp
In conclusion there is no clean way of making your own tree of tools in  a nearby directory. The only course is to commit your work in the Arduino library and be aware of those rules as well.

I recently tested this local library structure. It works with:
#include "libs/MyNewLib/MyNewLib.h"

The Arduino IDE 1.6.7 build pre-processing will even pick up the source code for the library.
Cheers!

Must be new in 1.6.7

It seems that indeed the newer versions are more flexible and you can include libraries in relative paths. However I still ran into problems when the included files also include other files relative to their location.

Hmm the include problems I just wrote about are not related to paths. It appears that the Arduino IDE does not handle *.ipp files well. See this arduino forum thread

Doesn't work for me in 1.8.1 on Windows.

The Arduino plugin for Visual Studio supports local libraries you can find the plugin here

I am just back to using the arduino after some time away and am somewhat bewildered
by similar issues and confused by different info from different sites and for different
versions of the ide.
What I have found is that if you have a sketch in a directory, then shut down the Ide you can drop .h, .cpp... files in the directory and the ide, when restarted, will open them with the sketch.
Include them by using simple quotes on the file names, no path, no angle brackets.
I am sure this is only part of the full answer, but it has gotten me started.

As far as I know, you can include your libraries from a custom location by using their absolute path.
Since absolute paths could be boring from a code-portability point of view, you could define some macros to get the absolute path from a given relative one. In this way, you would just have to fix the 'project root' path when passing from a device to another.
Define your project's root folder :
    #define PROJECT_ROOT C:\path\to\your\project\folder

Define a relative-to-absolute macro 'transformation' :
    #define TO_STRING(s) #s
    #define ABSOLUTE_PATH(root, relative_path) TO_STRING(root\relative_path)
    #define RELATIVE_PATH(library) ABSOLUTE_PATH(PROJECT_ROOT, library)

Include your files using the relative path :
    #include RELATIVE_PATH(some\file\relative\path.h)
    #include RELATIVE_PATH(another\file\relative\path.h)

I hope it will be useful.

The simplest way I've found to do this is store the libraries in your local sketch directory and create a symbolic link in the [HOME]/Arduino/libraries directory.  Then you can check them in to Git easily with your sketch/project and Arduino's still happy because the libraries are accessible in the global folder.
Maybe even create an install script that creates these links automatically and check that into Git too.

Another really bad fix - create a file called libraries.cpp, which contains:
// force the linker to build the libraries
#include "libraries/LIB1/src/FILE1.cpp"
#include "libraries/LIB1/src/FILE2.cpp"
#include "libraries/LIB2/src/FILE1.cpp"

Of course, this only works if the library does not itself contain any includes...

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


text:
Good button debouncing/stateChange library
I need debouncing/stateChange for a push button configuration. Is there a good library for debouncing/stateChange buttons in Arduino (without delay)?

I usually check the button state every few milliseconds, and store the state in an array. Next I check if the stored values are all HIGH or all LOW.

"Best", especially without offerimg any (or enough) criteria, would elicit entirely subjective answers and so is not a good fit for stackexchange.com. If you can re-word your question make it more objective, it will get more useful results (not to mention, it will remain open!)

There is no such thing as debouncing without delay. Some small amount of delay by definition needs to be introduced for the input system to be sure that the event is not a false positive.

The Button library in the Arduino playground works perfectly.

This library is great! BUTTTT dosn't work with the ESP8266 because meanwhile the Arduino has an internal Pull-up resistor the ESP doesn't (in all pins)!!!

This link is now broken

I think what you need is an interrupt-based detection of the button. This way, your Arduino can do what it needs to do without stalling for the delay function.
// Example code usage

int pin = 13; // LED on board
int interrupt0pin = 2; // pin attached to int0 if you're using Uno
int buttonState;

void setup()
{
  pinMode(pin, OUTPUT);
  pinMode(interrupt0pin, INPUT);
  attachInterrupt(0, buttonUpdate, CHANGE); // calls buttonUpdate() when button input changes (you can also use high-to-low or low-to-high)
}

void loop()
{
    if (buttonState)
        digitalWrite(pin, HIGH);
    else
        digitalWrite(pin, LOW);
}

void buttonUpdate()
{
  buttonState = digitalRead(interrupt0pin);
  delay(50); // 50ms works for most switches - adjustable
}

Find out more here: http://arduino.cc/en/Reference/AttachInterrupt
Good luck!

I'm on this subject right now and I'll use this to note my findings.
I found many libs on this, and this is my wishlist:

support many buttons
support toggles or switches
support debouncing and maybe de-glitching
non-blocking functions
support long-press, double-click

Candidates:

Switch from avandalen: tutorial - github - lib ref@arduino - @platformio
EasyButton from Evert Arias: tutorial - github - lib ref@arduino - @platformio
JCButton from JChristensen: github - lib ref@arduino - @platformio
ezButton from ArduinoGetStarted: tutorial - github - lib ref@arduino - @platformio

Here are my findings for each lib:
Switch

it's really easy to use
you can use it as a switch or a button, same class handles both
supports callbacks
supports many buttons
supports debouncing and de-glitching
supports double click and long press
most configs have defaults, and you define them at the Button setup
as I use PlatformIO, some warnings from this lib are shown while compiling my project

EasyButton

it's really easy to use
very good docs
supports callbacks
supports many buttons
does not support toggles/switches, although you can simulate it by checking the wasPressed and wasReleased properties
supports debouncing
supports double click, triple click, or a given number of clicks
you may have a different action for single, double or triple click for the same button
supports multiple times of long press, if needed
most configs have defaults, and you define them at the Button setup

JC Button

easy to use, not as easy as Switch and EasyButton tough
you can use it as a Button or a switch (ToggleButton), different class for each
supports many buttons
does not support callbacks
supports debouncing
supports multiple times of long press, if needed
most configs have defaults, and you may define them at the Button setup, but long press time is something you define while querying it's status rather than defining it once at the button setup

ezButton

easy to use, not as easy as Switch and EasyButton tough
supports many buttons
does not support toggles/switches, although you can simulate it by checking the isPressed and isReleased events
does not support long press
does not support callbacks
supports debouncing, does not debounce by default (you must call setDebounceTime on setup)
supports an easy way to count button clicks

Veredict
I chose avdweb/Switch. Reasons:

in terms of debouncing AND de-glitching, it did better according to my tests
I need a solution for Buttons and Switches, and it provides them in the same class

You can use my library
https://github.com/anlgncr/Buttons
This library lets you use buttons as many as you wish with only one instance of class.
You can also call a function when button is pushed or released.

I put this together for a guy the other day. Its not a library but it achieves reading and debouncing all of your buttons and works very well maybe it could help you
const byte numbuttons = 15;                                                     // DEFINE HOW MAY DIGITAL INPUTS TO MONITOR(NUMBER OF BELOW PINS TO USE)
const byte digitalpin[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16 };   // DECLARE ALL DIGITAL INPUT PINS WHICH CAN BE USED IN THE ORDER IN WHICH THEY WILL BE PHYSICALLY USED(DONT INCLUDE ANY PINS USED FOR OTHER THINGS
const byte debouncetime = 50;                                                   // THIS VALUE IS THE TIME TO WAIT BEFORE RECHECKING (FOR DEBOUNCE
byte readstate[numbuttons];                                                     // READ ARRAY
byte laststate[numbuttons];                                                     // HOLDS THE BUTTON LAST STATE FOR STATE CHANGE DETECTION
byte NumBut;                                                                     // THIS IS THE VARIABLE FOR DIGITAL FORLOOP COUNTER
unsigned long checktime;                                            // RECORDS THE TIMES (IN MILLIS() TO RECHECK THE STATE FOR EACH BUTTON. FOR DEBOUCING

byte CURRENT_SETTING;
void setup() {

  // SET INITIAL STATES FOR DIGITALS
  for (NumBut = 0; NumBut < numbuttons; NumBut++) {
    pinMode(digitalpin[NumBut], INPUT_PULLUP);
    laststate[NumBut] = digitalRead (digitalpin[NumBut]);
    checktime = 0;
  }
}

void loop() {
  //call the read button method
  READBUTTONS();
  PROGRAM_OUTPUT();
}

void READBUTTONS() {
  for (NumBut = 0; NumBut < numbuttons; NumBut++) {

    readstate[NumBut] = (digitalRead (digitalpin[NumBut]));                                                                   // READ DIGITAL INPUTS INTO ARRAY

    if (readstate[NumBut] != laststate[NumBut] && millis() >= checktime )   {
      if (readstate[NumBut] == 0 && laststate[NumBut] == 1) {
        checktime = millis() + debouncetime;
        CURRENT_SETTING = NumBut;
      }
      laststate[NumBut] = readstate[NumBut];
    }
  }
}

void PROGRAM_OUTPUT(){
    switch ( CURRENT_SETTING ) {
    case 0:   //do something to turn off output break;
    case 1:   //do something with setting 1 break;
    case 2:   //do something with setting 2 break;
    case 3:   //do something with setting 3 break;
    default:    break;
}
}

I can receommend the following library:
http://log.liminastudio.com/itp/physical-computing/arduino-a-new-improved-button-library-with-some-handy-features
https://github.com/virgildisgr4ce/Button
On the website you will find some examples on how to use it. I have implemented this library already in several sketches and it works very reliably.

You can put a capacitor in parallel with the switch - 100nf should do the trick. Some capacitors have a minus on the packaging, next to one of the pins - if so, make sure that side is to negative (ground).

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


text:
Problem using Ino build for 8 MHz
I want to use the Ino command line toolkit to build and upload my HEXes. It works well for the regular Arduino, however when I try to upload code to a Mini Pro 3.3V at 8 MHz, the code has the timing wrong. The serial output is garbled (I tried at different baud rates and was garbled each time) and delay(1000); seems to take double the time. I have selected the correct board (pro328 in my boards.txt), but it didn't seem to make a difference in the generated code. Has anyone used this and encountered a similar problem?

You have to set the correct value for F_CPU (i.e. 8000000).

Where should I set that value? Is it a compiler define that's not taken into account by Ino?

Normally it's set in boards.txt.

Well it is set in boards.txt if you look at the pro328 settings that I mentioned. I'd like to find out where that is used in the arduino code and how can I make sure Ino will use it.

Per the Quick start guide, Ino assumes the board is an Arduino Uno unless otherwise specified on the command line:

All examples were done in assumption that you have Arduino Uno and it is available on default port. Now consider you have Arduino Mega 2560 and it is available on port /dev/ttyACM1. We have to specify this for our build steps as command-line switches.
Board model may be set with --board-model or -m switch. Port is set with --serial-port or -p switch. So lets do it:
$ ino build -m mega2560
$ ino upload -m mega2560 -p /dev/ttyACM1
$ ino serial -p /dev/ttyACM1

For the full list of board names refer to ino build --help.

So you might be able to do this by using
$ ino build -m pro328
$ ino upload -m pro328 ...

However I don't know what options Ino includes for boards (presumably it uses the boards file), so using ino build --help should give you the information you need to select a suitable board if pro328 doesn't work.
Once that's done, the frequency setting should be taken care of for you.

The think is I use that board. I tried both in command line and in the settings file and it didn't seem to work. In the meantime I found out about platformio which I'm evaluating and on which it works correctly.

@rslite - the pro comes in both 5v 16 MHz and 3.3v 8 MHz version, to get the correct clock for the latter you will have to specify that and not the 16 MHz version.  This is exists in the current boards.txt but it is unclear what the ino syntax for it would be.

So it seems the F_CPU should be set up at compile time and I'm not sure if Ino does that or not (probably, or I'm missing something else).
However after pulling my hair for a day or so I discovered PlatformIO which has a much better functionality - my code works correctly, the lib manager is intriguing, is platform independent and seems it doesn't even require the Arduino environment to be installed (it can pull the required files itself).

authors: سيد امجد الشرع


text:
HTTP GET request only works sometimes
I am sending a HTTP GET request to a server I deployed on digital ocean (Ubuntu/Node.js). On the web browser when I go to my URL 'http://Server_Ip_Address/event/astarttime' or 'http://Server_Ip_Address/event/aendtime' the application on the web successfully performs its transaction.
However, I tried doing the same on my D1 R2 ESP8266 with this code in Arduino IDE: Sometimes it works sometimes it doesn't...I can't figure out why it only works some times and other times it doesn't work at all. Any idea of what it could be? Thank you for your help in advance.
Using these libraries:
#include "ESP8266WiFi.h"
#include <ESP8266HTTPClient.h>

http.begin("http://Server_Ip_Address:80/event/astarttime");
int httpCode = http.GET(); //Send the request
http.end();  //Close connection
http.begin("http://Server_Ip_Address:80/event/aendtime");
int httpCode = http.GET(); //Send the request
http.end(); //Close connection

arduino core version? 2.4.1? which lwip? 2? try 1.4. and erase the flash with esptool

Does the web server see the requests in the failing case?

Using arduino 1.6.13 it acctually works sometimes but not all of the time — Mark Smith how would I see the log file of the web server & it’s failing requests?

Perhaps I should, somehow, have a confirmation response from server to arduino to confirm that the http get request was successful (& if it wasn’t then it would keep trying? Does that sound like something that could be possible to implement?)

I've no idea how to see the logs but I'll eat my hat if Google doesn't tell you. Generally you should handle failures cleanly and sensibly, but I would investigate and fix the cause rather than bodging it and pushing the problem elsewhere.

@JoeB, esp8266 arduino core packages version? https://github.com/esp8266/Arduino/releases


text:
Reading from a pin Arduino Uno (assembly)
I am creating a project in which an Arduino reads (gets) a value from
a DHT sensor. The DHT sensor returns two values:

Temperature
Humidity

My assembly code:
sbi ddrd,5
cbi ddrd,2
sbi portd,5

start:

in r16,Pind2
cpi r16,80
brne On

jmp start

On:
cbi portd ,5
jmp start

After the code, the light remains turned on, but if the sensor sends '80'
and I get it correctly it should be turned off.
Question: Am I Using the write way to read a pin?

I'm not sure any of your code makes sense. Firstly you've got the roles of pind and portd backwards (port is for writing, pin is for reading). Secondly you haven't defined in your code what half of the stuff is (what is ddrd, what is portd, what is Portd2). Thirdly you are reading in the portd register (not an input), and then comparing it directly to a number (decimal 80, hex 0x50) - even if we assume you mean to read the inputs (pind), you haven't connected most of the pins on that port so who knows what value will return.

in r16, PIND, assuming you are using avr-gcc. If you want just the bit 2, andi r16, 1<<2.

I'm voting to close this question as off-topic because it is about AVR assembly NOT ARDUINO and was properly asked on EESE, but IMPROPERLY MIGRATED.  The language is not Aduino, the pin specs are AVR NOT ARDUINO - the only thing "Arduino" about this is some soldermask masquerading as silkscreen on the board.

Yet another crap migration from @Nick Alexeev. Is there anything we can do about this?

Gentlemen, Nick Alexeev asked me if he could migrate this. Whilst the assembler question might be marginally off-topic, this is hardly an electronics question. The question specifically mentions an Arduino Uno. Personally I would be encouraging him to ditch assembler for such a simple task. It seems completely inappropriate.

You are simply reading the state of the input pin - this won't work.
Study the datasheet for the DHT22, available from Sparkfun or eslewhere.
To get data from the DTH22, you must first send a start signal, wait a specified time, then watch the level of the data line, measuring the time of each bit to determine whether it is a 1 or 0, and store the bits in five 8-bit variables.  You can then examine those variables to determine the temperature and humidity.

Instructions for writing to an individual output bit:-
 sbi portd,5 ; make Port D output bit 5 high (set)

 cbi portd,5 ; make Port D output bit 5 low (clear)

 sbi pind,5  ; toggle Port D output bit 5 (low -> high, high -> low)

Instructions for reading an individual I/O pin:-
 sbis pind,2 ; skip next instruction if Port D pin 2 is high

 sbic pind,2 ; skip next instruction if Port D pin 2 is low

Awsome, this answer is clear and answers the question really well.


text:
Problem uploading to ATMega using ArduinoIDE ("unbricking" "bricked" microcontroller?)
I've a SparkFun Pro Micro which is an Arduino Leonardo clone. Unfortunately my attempts to upload programs failed. I did some research in the internet and found you have to use SparkFun's configuration. There is a board manager's URL you have to use: https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json
So far so good. After trying to use this I attempted to do an upload and failed. I tried it with different settings but all failed. While earlier there was a serial port named /dev/ttyACM0 there now is no such port any more. Further research gave me the information that you might get the device running if you a) reset to boot loader mode where you should have an 8 seconds window to upload and b) actually perform the upload.
I can verify: If I pull RESET to ground I can switch into this 8 seconds mode. Then the device /dev/ttyACM0 appears after about 1 second for about 7 seconds. As instructed I immediately try to do an upload. This is strange: I immediately (!) get the following output:

Line 1: Sketch uses 4140 bytes (14%) of program storage space. Maximum is 28672 bytes.
Line 2: Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.
Line 3: avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
Line 4: Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

The TTY should be there as the 7 seconds have not been passed in that case. Furthermore my user account is in dialout which enables it to use the tty.
If I trust this error message that means the tty is gone as soon as avrdude tries to access it. Which shouldn't be that way, should it?
Has anyone encountered this situation before? How can I upload a program to the mikrocontroller? Has anyone has any experience with that situation here?
--
Additional information:

ArdunoIDE 1.8.5
Ubuntu (Mate) Linux 16.04

version of IDE?

ArdunoIDE 1.8.5

Did uploading work with an other board, for example the arduino uno, or is this your first board? Are you in the dialout group? Is the modemmanager installed? You have to remove it. The purpose of the modemmanager is to cause troubles with an arduino pro micro (and other boards). If you don't like the extras by sparkfun, then you can burn the bootloader of the official arduino micro on it, but you have to take care that it has less pins. Do you have anything related to arduino installed from the repositories? can you try to remove java? Be sure to remove the librxtx-java.

I first used a completely different µC which worked perfectly. This was not an ATMega but a ESP8266. I then switched to the other board, tried to change settings for that board.

Yes, the modemmanager is installed. I read about that. But I can't uninstall the modem manager: It would uninstall the complete Mate UI because of dependencies. I do not know if the modemmanager interfers: I have used this board before and uploaded programs a few times to test it. Now I wanted to really make use of it ...

Why should I remove Java? What would that help? Please provide more information: I can't see how that would interfere with this avrdude (whatever that is ...)

I read a tutorial provided by SparkFun stating that you should switch the µC in this 8-seconds-Bootloader mode. It then should accept any upload (which it doesn't ...)

We use these a lot, and it's very easy to accidentally program the boards with the incorrect settings - particularly as the Sparkfun Pro Micro library defaults to the 3.3V/8 MHz variant instead of the more common 5V/16MHz.
I have recovered the boards with the bootloader reset method, but it is hard - you have to get the timing just right. What we do now is to simply reinstall the bootloader using an ISP programmer (instructions: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader). It works first time, and ends up being much quicker than repeated tries to get the reset timing right. Just make sure that you have the right board selected when you burn the bootloader. We use a USBASP, and it only takes a couple of minutes to set up.

I think I got the timing right. I was way within the 8 seconds. Nevertheless I'll have a look to the details you provided, thank you! I'll be on a business this week but will return to this topic next week. Please have a bit of patience! Thanks!


text:
Compiling SRAM intensive code from Raspberry Pi 3
I am using an Arduino Uno R3 to control my Christmas lights (a strand of 665 WS2812B LEDs).
I am using the Pololu library that can be found here:
https://github.com/pololu/pololu-led-strip-arduino
This library has been the most memory efficient one of its kind that I have found. It is the only one with which I could run my entire strand. I have been able to run it with up to 670 LEDs when compiling the code from my Windows PC.
The Arduino, while driving the LEDs, is not accessible from my PC, so I am attempting to use a Raspberry Pi with VNC installed to control it remotely, and update the Arduino code on demand. However, when compiling the exact same code (the LedStripXmas example from the Pololu library) on the Raspberry Pi, I am only able to get 650 LEDs working. If I try upload a code with more than that, the program will not run. The Raspberry Pi Arduino software also does not show the message:
"Global variables use 2,012 bytes (98%) of dynamic memory, leaving 36 bytes for local variables. Maximum is 2,048 bytes."
Is there a way to display this information from the Raspberry Pi?
Is there a difference in the PC and Raspberry Pi compilers?
Edit:
I uninstalled the IDE from the standard repository and installed the ARM version from the website. Now with the exact same code as from my PC, I am getting a ton of Narrowing warnings and the code does not run with any number of LEDs.

Let me guess: you installed the Arduino IDE from the default repository? Delete it. Uninstall it. It's very very very ancient. Download the latest version from the Arduino website.

I did indeed install it from the repo. Ill try downloading the version from the website later today.

You can build on your desktop, find the hex output in the tmp directory or wherever, and use avrdude on the pi to flash this result of building on your PC, rather than that of building on the pi.  Doing a dry run of all these operations with verbose output enabled will help you find the applicable commands.


text:
how to write a program in Arduino that pairs a single Rx to multiple Tx modules? i want to learn implementing this protocol
I have two Attiny85 communicating over 433mhz radio (Rx & Tx on either ends) using virtual wire library, how will the programming be to pair them by the press of a button on either module ?
i have so far been able to pair them both through the program (exclude any external devices by giving a node ID to listen to in my Rx) or think of adding DIP switches (but i run out of pins & combinations sooner). I am expecting  something similar to a commercial product where i can connect/pair multiple Tx modules to a single Rx base station in a press of a button on the Tx side. so i am seeking some technical expertise on the idea to understand such programming technique/methods.
Regardless of using 433mhz or a NRF24L01 module or anything else, i want to know how this feature of pairing module together is made.
------
Edit 22 July 2021:
This is added here in response from Crisl's comment
you have correctly understood my question, yes i want to learn how such a pairing protocol is implemented, i am not too concerned about the device for the communication gateway.
this question is regarding the protocol, and not about a specific circuit
------
I am a mechanical engineer by profession, with a hobby towards programming & electronics, so kindly spare some patience/detail in explaining this concept/technique.

please add a diagram of the system that you are trying to build

If you are talking about these simple 433MHz modules, which are also used for example in garage openers, then there is normally no pairing. The sender just sends some data (a static code, rolling code or other security measurement) and the receiver receives that data and acts accordingly. They normally don't have a sense of which device send the data. That would be an overlying protocol. Can you please describe, what you want to achieve? Current it is rather broad, so that we cannot really give advice on what would be the best option.

@chrisl.....yes i want to learn the protocol implementation, i am clueless on how to learn such a protocol, maybe give me some reference to learn that will also help

If it is sufficient to distinguish between the two (or several) transmitters and you don't need to exclude intrusions, accidental or otherwise, a "protocol" can be as simple as:
XMTRID BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]
, where each of the above represents a single byte. Does the library include message integrity checking, such as a checksum? If not, and the physical conditions warrant, you might add that to your protocol as well, and include an expectation by the transmitter that it receives an acknowledgement or rejection of correct reception (ACK or NAK) within a short time and will re-transmits the same message if it hasn't received an ACK. Then you'll want a message ID byte that increments for each new message (but not for retramsmission), so the receiver can reject a retransmission (if, say, its attempt to acknowledge had been lost).
Then your protocol could look something like this:
XMTRID MSGID CHKSUM BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]
. and it just keeps getting better from there as you add features for robustness, security, and whatever else you might need it to accomplish. But I'm guessing this is already sufficient.
Update:
To clarify:
XMTRID    - ID of sending 433MHz radio (any value you like, as long as each device has its own).
MSGID     - An incrementing number (rollover allowed), a new one for each *new* message
            (enables the receiver to distinguish new messages from resent ones).
CHKSUM    - A sum of bytes in the message to let the receiver check the message integrity.
BYTECOUNT - The number of message bytes to follow.
BYTE[0] ... BYTE[BYTECOUNT-1] - The actual message data.

Thanks, i understand your logic. this has sparked some new thinking for new topics to learn and experiment on. and i suppose you mean the Tx ID as "XMTRID" ?, and what is the difference between CHKSUM BYTECOUNT BYTE[0] BYTE[1] ... BYTE[COUNT-1]


text:
Serial monitor window opens frozen
My serial monitor window opens frozen, without any output or possibility to input, or even activate the window.
Sketch is very simple, but behavior is same even with empty sketch, so I assume problem is not in sketch. I also checked if sketch is uploaded correctly by uploading simple sketch with blinking diode, which worked.
Same behavior with Arduino Nano and Uno.
I tried to reinstall IDE, uninstalled, removed and reinstalled serial driver (ch340) with no success.
I can see Serial monitor window only on windows taskbar, it won't activate after click.
Until now I haven't had any significant problems with IDE or serial monitor for years.

Is it uploading at all?

Yes, sketch is correctly uploaded, I tried to upload another simple sketch with blinking LED, which worked.

IDE version? Did you get it through the website or the windows store? If you get it from the website, which file did you use?

I got it from windows store, version is 1.8.13 (Windows Store 1.8.42.0)

Do you anything plugged in or connected to the Arduino besides the USB cable to the PC?

No, but I tried it both, with connected MH sensor series flying fish and without on Nano, and with and without 2.4"TFT LCD shield on Uno with same result, meanwhile I tried both arduinos on another PC, where they work normally

Unfortunaltely, nothing worked, and after hours of trying and googling I reinstalled windows, and now Serial Monitor works correctly.

Try updating the java. Also check whether the device manager shows the USB serial port without any yellow warning sign on it.
If there is a current short in the usb port that specific port will be off for safety, restarting the computer should resolve that problem.

Until now I haven't had Java installed, no change in behavior after installation. I restarted computer many times in the process. Driver is correctly installed, and device in device manager is working correctly both with old and new driver.

The IDE runs on a JVM bundled with the IDE.


text:
HMC5883L Magnetometer X, Z values constant, only Y value Changes
I have a HMC5883L module connected to an Arduino Mega 2560 via +5, GND, SCL, SDA.  The Arduino code is from the MagMaster-master example, as follows:
#include "Wire.h"
#include "HMC5883L.h"

HMC5883L compass; //Copy the folder "HMC5883L" in the folder "C:\Program Files\Arduino\libraries" and restart the arduino IDE.

float xv, yv, zv;

void setup()
{
  Serial.begin(9600);
  Wire.begin();
  compass = HMC5883L();
  setupHMC5883L();
}

void loop()
{
  getHeading();

  Serial.flush();
  Serial.print(xv);
  Serial.print(",");
  Serial.print(yv);
  Serial.print(",");
  Serial.print(zv);
  Serial.println();

  delay(100);
}

void setupHMC5883L()
{
  compass.SetScale(0.88);
  compass.SetMeasurementMode(Measurement_Continuous);
}

void getHeading()
{
  MagnetometerRaw raw = compass.ReadRawAxis();
  xv = (float)raw.XAxis;
  yv = (float)raw.YAxis;
  zv = (float)raw.ZAxis;
}

When I run the code, I get the following output on the serial monitor
-15872.00,-27601.00,1.00
-15872.00,3264.00,1.00
-15872.00,19536.00,1.00
-15872.00,-18208.00,1.00
-15872.00,12401.00,1.00
-15872.00,-27647.00,1.00
-15872.00,1170.00,1.00
-15872.00,17442.00,1.00
-15872.00,-21326.00,1.00
-15872.00,7235.00,1.00
-15872.00,21715.00,1.00
-15872.00,-15261.00,1.00
-15872.00,15604.00,1.00
-15872.00,-22396.00,1.00
-15872.00,7189.00,1.00
-15872.00,23717.00,1.00
-15872.00,-13259.00,1.00
-15872.00,14534.00,1.00
-15872.00,-24490.00,1.00
-15872.00,3303.00,1.00
-15872.00,17527.00,1.00
-15872.00,-20473.00,1.00
-15872.00,9368.00,1.00
-15872.00,26664.00,1.00
-15872.00,-8008.00,1.00
-15872.00,8265.00,1.00
-15872.00,23769.00,1.00
-15872.00,-14231.00,1.00
-15872.00,13562.00,1.00
-15872.00,-24438.00,1.00
-15872.00,3099.00,1.00
-15872.00,17579.00,1.00
-15872.00,-19397.00,1.00
-15872.00,11468.00,1.00

As can be seen from the above, only the Y (middle column) values change when I move the sensor around.  If I plot these values in Excel, I get a plot that looks like this:

I have looked through the code, and the HMC5883L library code (below) and nothing seems amiss.  I tried a different HMC5883L module and got the same (bad) result.  I know I must be doing something wrong, but I can't for the life of me figure it out. Any hints would be appreciated! ;-)
HMC5883L.cpp:
/*
HMC5883L.cpp - Class file for the HMC5883L Triple Axis Magnetometer Arduino Library.
Copyright (C) 2011 Love Electronics (loveelectronics.co.uk)/ 2012 bildr.org (Arduino 1.0 compatible)

This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

 WARNING: THE HMC5883L IS NOT IDENTICAL TO THE HMC5883!
 Datasheet for HMC5883L:
 http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Compass_IC.pdf

*/

#include <Arduino.h>
#include "HMC5883L.h"

HMC5883L::HMC5883L()
{
  m_Scale = 1;
}

MagnetometerRaw HMC5883L::ReadRawAxis()
{
  uint8_t* buffer = Read(DataRegisterBegin, 6);
  MagnetometerRaw raw = MagnetometerRaw();
  raw.XAxis = (buffer[0] << 8) | buffer[1];
  raw.ZAxis = (buffer[2] << 8) | buffer[3];
  raw.YAxis = (buffer[4] << 8) | buffer[5];
  return raw;
}

MagnetometerScaled HMC5883L::ReadScaledAxis()
{
  MagnetometerRaw raw = ReadRawAxis();
  MagnetometerScaled scaled = MagnetometerScaled();
  scaled.XAxis = raw.XAxis * m_Scale;
  scaled.ZAxis = raw.ZAxis * m_Scale;
  scaled.YAxis = raw.YAxis * m_Scale;
  return scaled;
}

int HMC5883L::SetScale(float gauss)
{
    uint8_t regValue = 0x00;
    if(gauss == 0.88)
    {
        regValue = 0x00;
        m_Scale = 0.73;
    }
    else if(gauss == 1.3)
    {
        regValue = 0x01;
        m_Scale = 0.92;
    }
    else if(gauss == 1.9)
    {
        regValue = 0x02;
        m_Scale = 1.22;
    }
    else if(gauss == 2.5)
    {
        regValue = 0x03;
        m_Scale = 1.52;
    }
    else if(gauss == 4.0)
    {
        regValue = 0x04;
        m_Scale = 2.27;
    }
    else if(gauss == 4.7)
    {
        regValue = 0x05;
        m_Scale = 2.56;
    }
    else if(gauss == 5.6)
    {
        regValue = 0x06;
        m_Scale = 3.03;
    }
    else if(gauss == 8.1)
    {
        regValue = 0x07;
        m_Scale = 4.35;
    }
    else
        return ErrorCode_1_Num;

    // Setting is in the top 3 bits of the register.
    regValue = regValue << 5;
    Write(ConfigurationRegisterB, regValue);
}

int HMC5883L::SetMeasurementMode(uint8_t mode)
{
    Write(ModeRegister, mode);
}

void HMC5883L::Write(int address, int data)
{
  Wire.beginTransmission(HMC5883L_Address);
  Wire.write(address);
  Wire.write(data);
  Wire.endTransmission();
}

uint8_t* HMC5883L::Read(int address, int length)
{
  Wire.beginTransmission(HMC5883L_Address);
  Wire.write(address);
  Wire.endTransmission();

  Wire.beginTransmission(HMC5883L_Address);
  Wire.requestFrom(HMC5883L_Address, length);

  uint8_t buffer[length];
  if(Wire.available() == length)
  {
      for(uint8_t i = 0; i < length; i++)
      {
          buffer[i] = Wire.read();
      }
  }
  Wire.endTransmission();

  return buffer;
}

char* HMC5883L::GetErrorText(int errorCode)
{
    if(ErrorCode_1_Num == 1)
        return ErrorCode_1;

    return "Error not defined.";
}

HMC5883L.h:
/*
HMC5883L.h - Header file for the HMC5883L Triple Axis Magnetometer Arduino Library.
Copyright (C) 2011 Love Electronics (loveelectronics.co.uk) / 2012 bildr.org (Arduino 1.0 compatible)

This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

 WARNING: THE HMC5883L IS NOT IDENTICAL TO THE HMC5883!
 Datasheet for HMC5883L:
 http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Compass_IC.pdf

*/

#ifndef HMC5883L_h
#define HMC5883L_h

#include <Arduino.h>
#include <Wire.h>

#define HMC5883L_Address 0x1E
#define ConfigurationRegisterA 0x00
#define ConfigurationRegisterB 0x01
#define ModeRegister 0x02
#define DataRegisterBegin 0x03

#define Measurement_Continuous 0x00
#define Measurement_SingleShot 0x01
#define Measurement_Idle 0x03

#define ErrorCode_1 "Entered scale was not valid, valid gauss values are: 0.88, 1.3, 1.9, 2.5, 4.0, 4.7, 5.6, 8.1"
#define ErrorCode_1_Num 1

struct MagnetometerScaled
{
    float XAxis;
    float YAxis;
    float ZAxis;
};

struct MagnetometerRaw
{
    int XAxis;
    int YAxis;
    int ZAxis;
};

class HMC5883L
{
    public:
      HMC5883L();

      MagnetometerRaw ReadRawAxis();
      MagnetometerScaled ReadScaledAxis();

      int SetMeasurementMode(uint8_t mode);
      int SetScale(float gauss);

      char* GetErrorText(int errorCode);

    protected:
      void Write(int address, int byte);
      uint8_t* Read(int address, int length);

    private:
      float m_Scale;
};
#endif

Is this the Adafruit module? If so I would follow their tutorial step by step before breaking out on your own. Also, know that magnetometers are more difficult to align and use then, say, an accelerometer or gyroscope.

No, it's not - just a typical GY-273 clone.  I did  look at the Adafruit tutorial, but it just covers the same ground.

If it is not too big of an investment, I would buy the HW so as to be able to use the Adafruit tutorial exactly. Or, if you can, look for a working example that fits your HW situation. I've only worked w/the STMicro magnetometers & IMUs.  Their magnetometers are very sensitive and need to be aligned either by setting registers inside the chip or externally in the SW.  Regardless, there are usually many registers needing configuration before meaningful data is read out.  Meanwhile, in the short term, perhaps someone will spot something missing in your code preventing your HMC5883L from working.

Oh, do make sure that all your libraries are up to date.  I know you may have heard this many times.  But more often than not, code created for the Arduino by other hackers is only truly vetted after many others have tested and improved the code.


text:
Class private variable values not accessible in public function
I'm experimenting with classes in Arduino code. I have the following small code snippet:
#include "Motor.h"
#include "Arduino.h"

Motor::Motor()
{

}

void Motor::Configure(uint16_t inA_pin, uint16_t inB_pin, uint16_t speed_pin, Stream* SerPort)
{
    uint16_t _inA_pin = inA_pin;
    uint16_t _inB_pin = inB_pin;
    uint16_t _speed_pin = speed_pin;
  gl_pSerPort = SerPort;

    gl_pSerPort->printf("...._inA_pin set to %d\n", _inA_pin);
    gl_pSerPort->printf("...._inB_pin set to %d\n", _inB_pin);
    gl_pSerPort->printf("...._speed_pin set to %d\n", _speed_pin);

    pinMode(_inA_pin, OUTPUT);
    pinMode(_inB_pin, OUTPUT);
    pinMode(_speed_pin, OUTPUT);

}

void Motor::RunMsec(bool bisFwd, uint16_t onMsec, uint16_t speed)
{
  gl_pSerPort->printf("RunMsec(%d, %d, %d\n", bisFwd, onMsec, speed);
  gl_pSerPort->printf("RunMsec: _inB_pin = %d\n", _inB_pin);
  gl_pSerPort->printf("RunMsec: _speed_pin = %d\n", _speed_pin);
  gl_pSerPort->printf("%lu: Calling Run(%d, %d)\n",millis(), bisFwd,speed);
    Run(bisFwd, speed);

    //Step 2: Delay timsec seconds
    delay(onMsec);

    //Step3: Stop motors added 04/12/21
  gl_pSerPort->printf("%lu: Calling Stop()\n",millis());
    Stop();
}

The Motor.h file is:
#pragma once
#include "Arduino.h"

const uint16_t MOTOR_SPEED_FULL = 200; //range is 0-255
const uint16_t MOTOR_SPEED_MAX = 255; //range is 0-255
const uint16_t MOTOR_SPEED_HALF = 127; //range is 0-255
const uint16_t MOTOR_SPEED_QTR = 75; //added 09/25/20
const uint16_t MOTOR_SPEED_LOW = 50; //added 01/22/15
const uint16_t MOTOR_SPEED_MIN = 15; //added 12/24/23 for 'mirrored sfc' detection
const uint16_t MOTOR_SPEED_OFF = 0; //range is 0-255
const uint16_t MOTOR_SPEED_CAPTURE_OFFSET = 75; //added 06/21/20 for offset capture
const uint16_t TURN_START_SPEED = MOTOR_SPEED_QTR; //added 11/14/21

class Motor
{
public:
    Motor();
    void Configure(uint16_t inA_pin, uint16_t inB_pin, uint16_t speed_pin, Stream* gl_pSerPort);
    void RunMsec(bool bIsFwd = true, uint16_t onMsec = 1000, uint16_t speed = MOTOR_SPEED_HALF);
    void Run(bool bIsFwd = true, uint16_t speed = MOTOR_SPEED_HALF);
    void Stop();

private:
    uint16_t _inA_pin;
    uint16_t _inB_pin;
    uint16_t _speed_pin;
    Stream* gl_pSerPort;

    void SetDirAndSpeed(bool bIsFwd, uint16_t speed);
};

The code in the corresponding .ino file is:
#include "Motor.h"
#include <Wire.h>
#include "FlashTxx.h"       // TLC/T3x/T4x flash primitives

#pragma region MOTOR PINS
//11/04/21 Now using Pololu VNH5019 drivers for all 4 motors
const uint16_t InA_Left = 22;
const uint16_t InB_Left = 21;
const uint16_t Spd_Left = 23;

const uint16_t InA_Right = 34;
const uint16_t InB_Right = 33;
const uint16_t Spd_Right = 35;
#pragma endregion MOTOR PINS

Motor LeftMotor;
Motor RightMotor;

  Stream* gl_pSerPort = 0; //09/26/22 made global so can use everywhere.

void setup()
{
#pragma region SERIAL_PORTS
  Serial.begin(115200);
  delay(2000); //10/06/21 - just use fixed delay instead

  Serial1.begin(115200);
  delay(2000); //11/20/21 use fixed delay instead of waiting

  if (Serial)
  {
    Serial.printf("Serial port active\n");
    gl_pSerPort = (Stream*)&Serial;
  }
  else if (Serial1)
  {
    Serial.printf("Serial1 port active\n");
    gl_pSerPort = (Stream*)&Serial1;
  }

  gl_pSerPort->printf("gl_pSerPort now points to active Serial (USB or Wixel)\n");

  //02/25/23 added for Garmin LIDAR-Lite V4/LED use
  Serial2.begin(115200);
  delay(2000); //11/20/21 use fixed delay instead of waiting

  LeftMotor.Configure(InA_Left, InB_Left, Spd_Left, gl_pSerPort);
  RightMotor.Configure(InA_Right, InB_Right, Spd_Right, gl_pSerPort);

#pragma endregion SERIAL_PORTS
}

void loop()
{
  //redLED.Blink(2000);
  //delay(200);

  //yelLED.Blink(2000);
  //delay(1000);

  gl_pSerPort->printf("%lu: LeftMotor.RunMsec()\n", millis());
  LeftMotor.RunMsec(5000); //fwd for 1sec
  delay(500);

  gl_pSerPort->printf("%lu: RightMotor.RunMsec()\n", millis());
  RightMotor.RunMsec(5000); //fwd for 1sec
  delay(500);
}

When this is run, I get the following output from the embedded print statements:
Opening port
Port open
Serial port active
gl_pSerPort now points to active Serial (USB or Wixel)
...._inA_pin set to 22
...._inB_pin set to 21
...._speed_pin set to 23
...._inA_pin set to 34
...._inB_pin set to 33
...._speed_pin set to 35
6300: LeftMotor.RunMsec()
RunMsec(1, 1000, 127
RunMsec: _inB_pin = 0
RunMsec: _speed_pin = 0
6300: Calling Run(1, 127)
In SetDirAndSpeed(true, 127)
In TRUE block of SetRighttMotorDirAndSpeed(true, 127)
....Pin 0 set to 1
....Pin 0 set to 1
7300: Calling Stop()
In SetDirAndSpeed(true, 0)
In TRUE block of SetRighttMotorDirAndSpeed(true, 0)
....Pin 0 set to 0
....Pin 0 set to 0
7800: RightMotor.RunMsec()

From the printouts, I can see that Motor::Configure() properly initializes the private member variables, but Motor::RunMsec() reports that _inB_pin = 0, and _speed_pin = 0, so something is preventing RunMsec from seeing the values set by Configure().
Can anyone see what I'm doing wrong here?
TIA,
Frank

I tried making changing the private variables to 'public' (by commenting out the 'private:' line), but this had no effect - the variable values were still shown as '0' in the RunMsec() function

why are you commenting on your own question?  ... if you have anything to add, then please edit the question instead

duplicate of https://arduino.stackexchange.com/questions/57515/global-variable-does-not-change-when-value-is-set-within-boolean-function/57516?r=SearchResults&s=14%7C0.0000#57516

In your configure function:
void Motor::Configure(uint16_t inA_pin, uint16_t inB_pin, uint16_t speed_pin, Stream* SerPort)
{
    uint16_t _inA_pin = inA_pin;
    uint16_t _inB_pin = inB_pin;
    uint16_t _speed_pin = speed_pin;
  gl_pSerPort = SerPort;

You are creating new local variables named _inA_pin and _inB_pin and _speed_pin.  These new local variables shadow the member variables.  You have multiple variables with the same name, and the more local scope is the one that will be used.
I don't think you want to have the uint16_t there.  I think you want to put those values into the member variables in the class.
void Motor::Configure(uint16_t inA_pin, uint16_t inB_pin, uint16_t speed_pin, Stream* SerPort)
{
    _inA_pin = inA_pin;
    _inB_pin = inB_pin;
    _speed_pin = speed_pin;
  gl_pSerPort = SerPort;

DUH!!  Thanks for pointing out the obvious (to everyone but me!) error.


text:
esp32-pico-4d not working
My power supply is feeding the esp32-pico with 5v tho it says that there is 0 amps power drain, already there I know something isn't working since the power drain should be around 0.080amps, (it can be all the way up to 0.250amps if wifi on)
when I measure the vdda pin where the power goes into the chip it reads 3.3v which is perfect, but any of the other vdda power pins reads 0v, is the chip turned of cause I'm not powering the EN pin directly from the power supply?
in other words, do the other power pins turn off with the chip?
I have now tried pulling 3v straight from the power supply to the EN pin, and it then goes up to using around 0.160amps, but I still get nothing in the com port
a bit clueless for what is wrong?
other information:
I have a powerbumb turning the 5v into 3.3v
if EN = low: module is turned off if EN = high module is on
(don't leave EN floating)
https://www.espressif.com/sites/default/files/documentation/esp32-pico-d4_datasheet_en.pdf
(I know the antenna doesn't work)

Please show your schematic and PCB design.

i have added them now

You must connect all of the VDD pins of all types to the appropriate power supplies. These aren't like development boards. They are chips. And you must treat them as such.

Especially the CPU one - or nothing will ever be able to work.

so every single vdd pin also those named vdda3p3 needs to be connected to power supply?

(ofc only the amount of v they need)

DVVA3P3, VDDA, VDDA3p3_RTC, VDD3P3_CPU, VDD_SDIO - they all need connecting.


text:
Soil moisture sensor, weird readings
I'm  having a small problem with my soil moisture sensor
it gives me weird readings, in the second the smallest connection is made between the legs it just gives me 4096 (which is max possible value), its either about 0 or 4095
I can't really seem to see the problem, any help is appreciated
(the output voltage is read on an ESP32, almost visible in the bottom of the image)

And what is your soil monitor?

not sure what your question is, but I'm reading the output voltage on an ESP32

The output voltage of what? How is it wired? What is your schematic?

the output of the sensor, one leg has 3.3v going in, the other leg is wired to a GPIO pin

do you want the full schematic?

Yes please. Without that we're just stabbing in the dark.

how is the ground lead connected to the arduino?

its not an arduino, its an ESP32, but through the pcb

now I've added the full schematic

Is the soil probe component just two metal prongs?

yes, just 2 metals "prongs"

It looks like you're trying to measure the resistance of soil by connecting an ADC input through the soil to VCC.  That is not the way to to it.
At the moment you effectively have this schematic for that portion:

simulate this circuit – Schematic created using CircuitLab
The voltage dropped across the soil is proportional to the current flowing through it. And there is no current flowing through it1 because there's no path to ground, only the very high impedance of the ADC.
So you never see anything except VCC (or a floating input when the probe is not in the ground).
To measure a resistance like that you have to have it as one half of a potential divider, just like you would for an LDR.

simulate this circuit
What actual value R2 should have depends entirely on the resistance range detected by your probe. It can be good to experiment with different values until you find one that works for you.

1: Actually there is some small leakage current through the ADC to ground, but that is so tiny we can ignore it.


text:
esp32, brownout on 3.3v?
I'm using a powerbump, input: 3.7v-6v Outputs: 3.3v, to provide the power I'm using 2 CR2025 coin cell batteries(3v each), meaning the powerbump gets 6v, the esp gets the exact 3.27v(I've measured with a multimeter),
But the chip still keeps on brownouting, when I start BLE on the chip

The ESP32 is quite power hungry when using the bluetooth or WiFi. Read this: https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/ - button cells provide very little current. You may find it's not enough. Add one more button cell and see if that improves things. Maybe replace one CR2032 with a pair of CR2016's to use the same space but double the voltage (with reduced capacity for reduced runtime of course).

@Majenko The third cell adds another 3 V to the supply voltage. The regulator is specified with 6V and now gets 9V. I think that's not a good idea. The third cell has the same inner resistance than the other ones. So if the current goes above a certain amount the voltages breaks down. So I do not think this would help. One could use two or three pairs in parallel. But the best solution would be to replace the cells by a more powerful source.

If it's the powerbump I designed then it's 16v max input, not 6v, and it's a buck regulator, so the higher the voltage in the higher the current you can get out.

@Majenko If you have two cells you double the voltage and also the inner resistance of both cells together. The current where the inner voltage drop gets so high that the voltage breaks down and can not feed the converter, stays the same. The converter is not the problem, the cells are. Event if you have more voltage on then bug converter and so it needs less current to draw, I doubt that would be enough to avoid the effect. And the cells also discharge very quickly. If the converter is specified with 16V max then my warning is obsolete. Sorry, I didn't know about that.

@PeterPaulKiefer There comes a point where the current being required from the batteries needed to provide the desired output current is low enough that the internal resistance of the batteries doesn't provide enough voltage drop to cause a brownout any more. What input that voltage is at though is the main unknown at the moment. As for battery drain, sleep modes can mitigate most of that. But I certainly agree that button cells are a poor choice unless you are specifically using circuitry designed to run at very low currents. The ESP32 isn't really that.

well, the most important for my batteries, is to be small, coins cells are very small, and the best solution I could find was them, btw the chip will be in deep_sleep most of the time

and yes, it is @Majenko powerbump, thought you said it was 6v in a earlier post

just realized I wrote the wrong number, its cr2025

@Majenko I fully agree with you.  I wanted to say something about the possibility the two cells will work, but due too my bad English I failed obviously.  I know the e.g. CR2025 has a capacity of about 170 mAh and serve a typical current of ~ -0.2 mA, I think there is a significant drop, if one draws e.g. -50 mA from the cells. The cell quickly looses the stored energy and after a short time the voltage of the cell sinks because of that. The buck converter gets less voltage and needs more current. So as you wrote too, cell coins are a poor solution.

Marius, there are other solutions that may fit your needs. Cell coins may work or not, but if they work, then not for along time. And the mentioned types are not re-loadable. I don't know how often the ESP wakes up and activates bluetooth. But do you really want to change batteries every 2 hours of operation? Perhaps accus fit better with your needs. There are LiPo Packs that provide 3.7V. There are small packs available:  e.g.  6mmx35mmx37mm (2 CR2025 need 2.5mmx40mmx25mm w/o the holder).

is the lipo rechargeable?


text:
STM32 Nucleo-L432KC can't send data to Arduino Uno via nRF24L01 module
Hello everyone.
First of all, I know you're going to tell me to send my question on the stm32duino forum. But I tried to enter the stm32duino forum and I didn't succeed (I think their forum is closed). So I'll be happy if you could try to help me here.
So, I want to use the nRF24L01 module to communicate between the STM32 Nucleo-L432KC and the Arduino Uno. such that both the STM32 Nucleo-L432KC and the Arduino Uno will be transceivers.
My nRF24L01 module pin connections are:
For the nRF24L01 module to the Arduino Uno:

CE => D7
CSN => D8
MOSI => D11
MISO => D12
SCLK => D13

For the nRF24L01 module to the STM32 Nucleo-L432KC:

CE => PB0
CSN => PB1
MOSI => D11 (Other names: PB5, SPI3_MOSI)
MISO => D12 (Other names: PB4, SPI3_MISO)
SCLK => D13 (Other names: PB3, SPI3_SCLK)

I tried to send data from the Arduino Uno to the STM32 Nucleo-L432KC, and I got the data and everything was OK.
But when I tried to send the data from the STM32 Nucleo-L432KC to the Arduino Uno board, I didn't receive the data in the Arduino Uno (I use the Serial monitor in-order to print the data I receive).
My code:
For the Slave (STM32 Nucleo-L432KC) who send the data to the Arduino Uno:
#include <nRF24L01_STM32.h>
#include <RF24_config_STM32.h>
#include <RF24_STM32.h>
#include <SPI.h>

RF24 myRadio(PB0, PB1); //CE Pin, CSN Pin
//----------------------------------
//Rest of connections to the Nucleo-L432KC:
//   nRF    Nucleo-L432KC
//  MISO      D12 (Other names: PB4, SPI3_MISO)
//  MOSI      D11 (Other names: PB5, SPI3_MOSI)
//  SCLK      D13 (Other names: PB3, SPI3_SCLK)

//My Slave (Nucleo-L432KC) and Master (Arduino Uno) addresses:
const uint64_t pipes[2] = {0xF0F0F0F0AA , 0xF0F0F0F066}; // {Master (Arduino Uno) address , Slave (Nucleo-L432KC) address}

const char test[] = "test"; // junk string to send between the slave and the master in-order to check the communication between them

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600); //Start Serial communication
  delay(1000);
  //Init SPI config:
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  //---------------------------

  //Init my nRF radio:
  myRadio.begin();                      //Starting the Wireless communication
  myRadio.setRetries(15, 15);
  myRadio.setChannel(0x4c);             // Set the communication channel
  myRadio.setPALevel(RF24_PA_MAX);      // Set the nRF power level. RF24_PA_MAX => maximum power
  myRadio.openWritingPipe(pipes[0]);    // Set the address of the Master (in-order to send back the requested data). Master address is: pipes[0]
  myRadio.openReadingPipe(1, pipes[1]); // Set the address of the Slave (in-order to receive the commands from the master). Slave address is: pipes[1]

  myRadio.stopListening();              // Set myRadio to transmitter mode (in-order to test the data communication: Slave send requested data to master)
  //---------------------------

}

// Send the data to the master (Arduino Uno) infinitely:
void loop() {
  delay(500);
  myRadio.write(&test, sizeof(test));
}

For the Master (Arduino Uno) who receive the data from the STM32 Nucleo-L432KC:
    // nRF24L01 libraries for Arduino platform:
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
//--------------------------
#include <SPI.h>

RF24 radio(7, 8); // CE Pin (D7), CSN Pin (D8)
//----------------------------------
//Rest of connections to the Arduino Uno:
//   nRF    Arduino Uno:
//  MISO      D12
//  MOSI      D11
//  SCLK      D13

//My Slave (Nucleo-L432KC) and Master (Arduino Uno) addresses:
const uint64_t pipes[2] = {0xF0F0F0F0AA , 0xF0F0F0F066}; // {Master (Arduino Uno) address , Slave (Nucleo-L432KC) address}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600); //Start Serial communication
  delay(1000);

  //Init my nRF radio:
  radio.begin();                       //Starting the Wireless communication
  radio.setRetries(15, 15);
  radio.setChannel(0x4c);              // Set the communication channel
  radio.setPALevel(RF24_PA_MAX);       // Set the nRF power level. RF24_PA_MAX => maximum power
  radio.openReadingPipe(1, pipes[0]);  // Set the address of the Master (in-order to receive back the requested data from the slave). Master (Arduino Uno) address is: pipes[0]
  radio.openWritingPipe(pipes[1]);     // Set the address of the Slave (in-order to send the commands to it from the master). Slave(Nucleo-L432KC) address is: pipes[1]

  radio.startListening();              // Set radio to receiver mode (in-order to test the data communication: Slave send data data to master)
}

// Receive the data from the slave (Nucleo-L432KC) infinitely:
void loop() {
    if (radio.available())              // Looking for the data.
  {
    char text[32] = "";
    radio.read(&text, sizeof(text));    // Saving the incoming data
    Serial.println(text);               // Printing the received data on the Serial monitor
  }
}

Both the Arduino Uno and the STM32 Nucleo-L432KC codes were compiled successfully.
Can you please help me and tell me what I'm doing wrong here and how to fix this?
Note: I use for the master and the slave a code that I found from the web (in multiple web pages).
Thank you for your help,
Reshef

I'd suggest using the bold format for really things that you need to draw attention to and NOT use it for whole sentences. It just makes the post hard to parse through. p.s. a ~picture~ (schematic) is worth a thousand words. Instead of writing down what pin is used for what, a better picture could be conveyed if the schematic of your circuit could be included here instead.

Also I would remove the header files that you listed in your post. We can see those header files in the code? Right? Then why list them again separately? p.s. you made a nice effort in formatting your post. :) !

I'm sorry to dig up a 2-years old post, but did you succeed to send data from the STM32 to the Arduino ?


text:
How to receive data via Bluetooth on an Arduino 101?
The Arduino 101 came out recently, and it has built-in "Bluetooth Low Energy" capabilities. The tutorials and code examples that can be found for the 101 all seem to be about transmitting data, but I can't find anything about receiving data. I've tried to go through the source code of the CurieBle library to find some hints, but I feel a little overwhelmed/lost. Could someone point me to a code example which demonstrates how to do this?
Context: I was previously using an HC-05 module paired with an Arduino Nano in order to receive data. In this case it is quite easy to connect the HC-05 to the Nano's digital pins and receive data like so:
#define RxD 7 // This is the pin that the Bluetooth (BT_TX)
              // will transmit to the Arduino (RxD)
#define TxD 8 // This is the pin that the Bluetooth (BT_RX)
              // will receive from the Arduino (TxD)

SoftwareSerial blueToothSerial(RxD,TxD);

void setup() {
  blueToothSerial.begin(9600);
  Serial.begin(9600);
  // Allow Serial communication via USB cable to computer
  pinMode(RxD, INPUT);
  // Set up the Arduino to receive INPUT from the HC-05 on Digital Pin 7
  pinMode(TxD, OUTPUT);
  // Set up the Arduino to send OUTPUT to the HC-05 on Digital Pin 8
}

void loop() {
  char recvChar;
  while(1) {
    if(blueToothSerial.available()) {
      recvChar = blueToothSerial.read();
      Serial.print("Read character: ");
      Serial.println(recvChar);
      // Print the character received to the Serial Monitor
    }
  }
}

Is there equivalent, and equally simple, code available, which would do the same thing via the BLE built into the Arduino 101?

According to the Arduino Callback LED tutorial, you can use the dedicated library to access the BLE features of the board. All the Curie Libraries are covering the new Arduino/Genuino 101 embedded characteristics .
In your case you must incluse the CurieBLE.h and configure the bluetooth service with Read/Write access.
Have a look to this page for a complete sample.

It's possible to using HC-05 with Intel 101.
I worked on the pin 0, 1, as the Serial1 class.

I don't understand what you are trying to say. Can you please elaborate.

It seems the 101 only supports Bluetooth LE stack and not the full Bluetooth stack including RFCOMM, virtual com port. This means there is no proper supported way, but it seems people are working on workarounds.
https://forum.arduino.cc/index.php?topic=370123.0


text:
Four Fast PWM outputs, in parallel
I need four Fast PWM signals for four different transistors.
I want to use timers 1+2 (pins 3, 11, 9, 10) so it wouldn't interfere with delay(...).
I tried setting the timers to Fast PWM mode, and applied different OCRnA/OCRnB values, but nothing really worked - at most, I managed to get two good PWM signals, one from each timer.
How should I deal with TCCRnA/TCCRnB, OCRnA/OCRnB to achieve 4 parallel PWM signals?
My latest attempt:
// Timer 1 Fast PWM setup: TOP=0x00FF, Update of OCRx at BOTTOM (0), TOV Flag Set on TOP
pinMode(9, OUTPUT); pinMode(10, OUTPUT);
TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10); // Divisor 64
// Timer 2 Fast PWM setup: TOP=0xFF, Update of OCRx at BOTTOM (0), TOV Flag Set on MAX (0xFF)
pinMode(3, OUTPUT); pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22); // Divisor 64
// ...
int val = 200; // Desired PWM output
OCR1A = val;
OCR1B = val;
OCR2A = val;
OCR2B = val;

You should keep the timers running to max. Not make them reset when the timer value is reached. This way it will reach both values.

It would help if you posted the code. Note that there are two fast-pwm options. One that overflow at MAX and one that overflows at OCRnA.

Added example code. I tried many combinations, this is one of them.

That's a snippet - Please post a Minimal, Complete, and Verifiable example. Then we can try to help you.

That's all there is to it. The code was simply copied from my setup() function.
Regardless - I think the question is clear enough even without code examples - How should I deal with TCCRnA/TCCRnB, OCRnA/OCRnB to acheive 4 parallel PWM signals?

Double check the fast PWM selection. Does this actually use OCRnA/OCRnB?

What do you mean by "parallel"? Same frequency? Same duty cycle? Can you clarify why you don't just use one timer and route it to 4 transistors?

My latest attempt: - what does that attempt do? What do you want it to do, that it does not do?

You've put a bounty on the question, but don't seem interested in clarifying what the question is, exactly. No-one has attempted to answer, which maybe tells you that the question is vague. Even if you sketch on paper (and scan) or do a simple line-art drawing, that would help to clarify what "4 parallel PWM signals" means.

I want to drive four separate motors on a quadcopter, and thus the need for four separate and identical signals.

Basically, your question comes down to this:
"How to generate two PWM signals with only one timer."
(Once you've got that figured out, you could set up 6 PWM channels)
Keep in mind that there also are PWM generator IC's, if you don't want to use up all your timers, which can be usefull for other things.
IF you really want to set all outputs to toggle at the same time (based on your code example) why won't you just use one PWM signal, and drive all the 4 devices with the same signal? (Given you're not going to change it)
IF you're going to drive motors, why would you need 4 different PWM signals? It's often enough to only use one PWM signal for the right tires/tracks and one PWM signal for the left tires/tracks.

Setting the max
Since we want to generate different PWM signals from one timer, we can't just make the timer overrun (and generate a pulse or switch polarity at that point).
We want to let the timer run to completion over and over, and only change the signal when it reaches a set value.
The datasheet tells us this:

The TOP value can be assigned to be the fixed value 0xFF
  (MAX) or the value stored in the OCR0A Register. (328P datasheet 15.2.1 Definitions)

Setting a limit per pin
We want to set 2 limits on one timer, each timer has an output compare register (OCR), the action will be generated when the timer hits this value.

The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt
  request (abbreviated to Int.Req. in the figure) signals are all visible in the Timer Interrupt Flag Register (TIFR0).
  All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK0). (328P datasheet 15.2.2 Registers)

Extra info on compare
Below you can read some extra info on the signaling.
What actually will happen, depends on how the WGM

15.5 Output Compare Unit
  The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and
  OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the
  Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is
  enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is
  automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing
  a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output
  according to operating mode set by the WGM02:0 bits and Compare Output mode (COM0x1:0) bits. The max
  and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in
  some modes of operation (”Modes of Operation” on page 98).

Fast PWM
The actual settings are different per mode/modus, but for fast PWM we have:
Table 15-3. Compare Output Mode, Fast PWM Mode(1)
COM0A1 COM0A0 Description
0      0      Normal port operation, OC0A disconnected.
0      1      WGM02 = 0: Normal Port Operation, OC0A Disconnected.
              WGM02 = 1: Toggle OC0A on Compare Match.
1      0      Clear OC0A on Compare Match, set OC0A at BOTTOM, (non-inverting mode).
1      1      Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

The table tells us we need to set COM0A1 and COM0A0 to 1.
COM0B1 COM0B0 Description
0      0      Normal port operation, OC0B disconnected.
0      1      Reserved
1      0      Clear OC0B on Compare Match, set OC0B at BOTTOM, (non-inverting mode)

This table tells us we need to set COM0B1 and COM0B0 to 1.
WGM mode
If it's all set up, we only need to put the PWM in the right mode.
Mode WGM02 WGM01 WGM00 Timer/Counter TOP  Update-OCRx TOV-on
0    0     0     0     Normal        0xFF Immediate   MAX
1    0     0     1     PWM,P-Correct 0xFF TOP         BOTTOM
2    0     1     0     CTC           OCRA Immediate   MAX
3    0     1     1     Fast PWM      0xFF BOTTOM      MAX

So we'll need to set WGM02 to 0 and WGM01 and WGM00 to 1, to use fast PWM.F
Succes?
You should now be able to change the PWM's of these pins by setting the output compare registers of these.
Getting the double PWM of the other timer ready, shouldn't be much more different.
Be sure to set the right prescaler. Though it depends on a lot of external things.


text:
Problem sending colors from an audio visualizer to Arduino
Sorry in advance for the length of my question; I want to provide proper context. I wrote an audio visualization program in Java that (in addition to making "pretty pictures" based off of the amplitudes of different frequencies being sent from the computer) sends a color to an Arduino Uno based off the sound it is "hearing."
I know the algorithm for generating this color is functional (in addition to sending that color to the Arduino, it also changes the color of an item on the DrawingCanvas). When the color is sent to the Arduino (as 3 bytes representing red, green, and blue), though, the physical LEDs don't respond correctly (they become a random color for a few seconds then switch to another random color for a bit – the behavior is hard to describe, but certainly not desired!).
I have been able to send colors to the Arduino using the same client program, but when the audio visualizer sends colors by the same method, this odd behavior occurs. My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?
Here are the relevant pieces of code from the client, the audio visualizer, and the Arduino:
Client:
public class Client extends WindowController{
  //USB is a class I wrote that extends PApplet. Unless baud rates are the issue, I don't think we need to worry about this.
  static USB port = new USB("COM3", 9600);
  byte[] code = new byte[LENGTH];
  static byte killTerm = -100;
  private AudioVisualizer vis;

public void begin() {
  resize(1500,900);
  for (int k=0;k<LENGTH;k++){
    code[k]=killTerm;
  }
  vis = new AudioVisualizer(10,30,1200,300,canvas);
}

public void onMouseClick(Location point) {
  runVis = !runVis;
  if(runVis) {
    vis.start();
    code[0]=-22;
    sendCodeUSB(code);
  } else
    vis.stop();
}

public static void sendCodeUSB(byte[] code) {
  for (int k=0; k<code.length; k++) {
    port.writeProfile(code[k]);
  }
}

AudioVisualizer
public class AudioVisualizer implements Runnable {
  Thread thread = null;
  DrawingCanvas canvas;
  byte[] code = new byte[3];
  private int xPos;
  private int yPos;
  private int width;
  private int height;
  private int scale;
  private Location topLeft;
  private Location bottomRight;
  private FilledRect background;
  private int brightness=0;
  private boolean needOff = false;

  public AudioVisualizer(int x, int y, int w, int h, DrawingCanvas myCanvas) {
    canvas=myCanvas;
    xPos=x;
    yPos=y;
    topLeft = new Location (xPos,yPos);
    bottomRight = new Location (xPos+width, yPos+height);
    width=w;
    height=h;
    background = new FilledRect(topLeft,width,height,canvas);
    background.setColor(Color.BLACK);
    initiateMonitor();
    scale = height/30;
  }

  public void start() {
    if (thread == null) {
      thread = new Thread(this);
      thread.start();
    }
  }

  public void stop() {
    thread=null;
  }

  public void run() {
    while (thread != null) {
      try {
        Thread.sleep(40);
      } catch (InterruptedException e) {
      }
      graphAmps();
    }
    thread = null;
  }

  public void graphAmps() {
    //there is a whole bunch of stuff here that is unrelated that I removed.
    //basically, just know that graphAmps() calls avgColors()
    avgColors();
  }

  public void avgColors(){
    //there is stuff here that generates avgRed,avgGreen,and avgBlue (known to be working)
    Color c = new Color (avgRed,avgGreen,avgBlue);
    background.setColor(c);
    //so we don't spam the Arduino more than we need to
    if(avgRed>10 || avgGreen>10 || avgBlue>10) {
      sendArduinoColor(c);
      needOff = true;
    } else if (!(avgRed>10 || avgGreen>10 || avgBlue>10) && needOff) {
      sendArduinoColor(c);
    }
  }

  public void sendArduinoColor(Color c) {
    //takes the color and sets code = an array of 3 bytes with values from 0-100 (100 is the highest brightness I ever want the LEDs to be)
    //I am sure this is done correctly so I've left it out.
    constrainArduinoColor(c);
    //calls the static method from the client and passes in the byte array with the rgb values
    Client.sendCodeUSB(code);
  }
}

Arduino
#include <EEPROM.h>

int redPin = 11;
int bluePin = 10;
int greenPin = 9;
//declared here for debugging ease of access
int r;
int g;
int b;
//are we going through the Spectrum Cycle loop for the first time?
boolean sclFirstTime = true;
//temporary initialization
boolean waiting = true;
int index = 0;
const int LENGTH = 20;
byte profile[LENGTH];
byte avProfile[3];
byte killTerm = -100;
byte audioVisualizationCode = -22;

void setup() {
  //start the serial communication
  Serial.begin(9600);
  //initialize the profile to all -1 values
  clearProfile();
}

void loop() {
  //if there is nothing over serial and nothing is in the EPROM, we are waiting
  if (!eepromProfileAvailable() && Serial.available()==0){
    waiting = true;
  } else if (eepromProfileAvailable() && Serial.available()==0) {
    //if there is something in EEPROM and nothing over Serial, we aren't waiting and load the EEPROM profile
    waiting = false;
    loadEEPROMProfile();
    //load the EPROM color profile into the array
  } else if (Serial.available()>0) {
    //if something enters over Serial, we aren't waiting, clear the profile, and load the new profile with the serial info
    waiting = false;
    clearProfile();
    while (Serial.available()<LENGTH) {}
    // Wait until there are LENGTH number of Bytes waiting
    for(int n=0; n<LENGTH; n++) {
      profile[n] = Serial.read(); // place them in the profile.
    }
    Serial.flush();
    //clear out the serial to prep for next time
  }
  //if we have a profile (either from EEPROM or Serial), save it, check for special codes (if found, apply the effect),
  //and if there are no special codes, the profile is a static color profile, and set LEDS to that.
  if(!waiting) {
    saveEEPROMProfile(); //omitted but working
    if (profile[0]==101) {
      while (Serial.available()==0)
        spectrumCycle(); //omitted but working
    } else if (profile[0]==-22) {
      audioVis();
    } else {
      anodeSafteyOut(redPin,profile[0]);
      anodeSafteyOut(greenPin,profile[1]);
      anodeSafteyOut(bluePin,profile[2]);
    }
  }
}

//a bunch of preset color effects omitted
//we are using a common Anode LED, so low value is 255 instead of 0
void anodeSafteyOut(int pin, int c) {
  if(c>=0) {
    c = 255 - c;
    //as a safety measure because there are no resistors (yes, I know im breaking an intergalactic law by not using any), make sure we aren't writing something too bright
    if (c>=155) {
      analogWrite(pin,c);
    }
  }
}

//wait for 3 bytes to come in, assign them to the avProfile, set the colors to that, do it again
//THIS IS PROBABLY WHERE THE PROBLEM IS
void audioVis() {
  while (Serial.available()<3);
  for (int k=0;k<3;k++)
    avProfile[k]=Serial.read();
  anodeSafteyOut(redPin,avProfile[0]);
  anodeSafteyOut(greenPin,avProfile[1]);
  anodeSafteyOut(bluePin,avProfile[2]);
  audioVis();
}

So that's a lot, and I've left a lot out that I didn't think was necessary, though I'm happy to provide the full programs if needed. Thanks for your help!
Here is constrainColorArduino:
public void constrainArduinoColor(Color c) {
  int r = c.getRed();
  int b = c.getBlue();
  int g = c.getGreen();
  int r1 = (int)(r*0.4);
  int b1 = (int)(b*0.4);
  int g1 = (int)(g*0.4);
  byte r2=0;
  byte b2=0;
  byte g2=0;
  for (int k=0; k<r1; k++)
    r2++;
  for (int k=0; k<b1; k++)
    b2++;
  for (int k=0; k<g1; k++)
    g2++;
  System.out.println(r+" "+g+" "+b);
  System.out.println(r1+" "+g1+" "+b1);
  if (r2>100) r2=100;
  if (b2>100) b2=100;
  if (g2>100) g2=100;
  if (r2<0) r2=0;
  if (b2<0) b2=0;
  if (g2<0) g2=0;
  System.out.println(r2+" "+g2+" "+b2);
  code[0]=r2;
  code[1]=g2;
  code[2]=b2;
}

constrainArduinoColor(c)?

takes a color, finds the red green and blue ints, creates bytes based off of those numbers, applies them to the array code.

but where is the mapping from color c to the code[]?

added the method to the bottom of my post

true but im sending a byte. for example, if i code was {r,g,b} and that is sent over where rgb are each bytes and r is initialized to 100 and g and b are 0, the LEDs become all red.

have you traced the stream?

I've called println when I was first debuging to ensure that the rgb components of c were being properly translated to the array. i've also done separate tests where ive "manually" created the array and sent it over, and the color was correct. I'm starting to think that the issue here is synchronization. I'll try sending a start code each time before the color profile

My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?

Close, but the source of the problem is probably this line
  Serial.flush(); //clear out the serial to prep for next time

Because your audio visualizer keeps sending data, it's quite likely that by the time you get around to claiming a record, at least some part of another one (or more) has also arrived.   When you discard that with flush(), you are probably most of the time not going to be discarding exactly a record's worth of bytes, but rather some arbitrary number more or less.  This introduces a synchronization problem.
You've already had some advice on solving synchronization problems.  There are a variety of workable methods, binary and otherwise.  One simple one that works in a lot of situations is to encode bytes textually in hex and terminate the record with a newline.  It does have just over a factor of two overhead, but it has the debug/test advantage of being human readable, and you can basically cover the overhead by switching from 9600 to 19200 baud.

Your idea that there's a synchronization issue seems plausible.  Whenever any byte gets skipped, color assignments shift from RGB to GBR or BRG, etc.
While sending a start code before the color profile is a possible approach to fixing the problem, it may be that occasionally one of the RGB values matches the start code, which could result in temporary desynchronization.
For an alternative method that doesn't require a start code, consider encoding the data into four bytes.  In the first byte, send the high two bits for RGB; in the second, the next two bits of each color; etc.  Set the low two bits of each byte to 11, 10, 01, 00 for first, second, third, fourth.
That is, each byte you send would be encoded BBGGRRdd where the capital letters are appropriate bits from RGB brightness levels and dd indicates which pairs of bits are being sent.
Here's some (untested) code that implements the decode:
byte code = Serial.read();
byte shif = 2*(code & 3);
byte mask = ~(3<<shif);
code >>= 2;
for (byte i=0; i<3; ++i) {
  profile[i] = (profile[i] & mask) | ((code & 3)<<shif);
  code >>= 2;
}

The following shows a function sendData3() that encodes three bytes from an array of RGB data into four bytes to be sent to the Arduino.  It also shows a convenience function sendDataRGB().  A call like sendDataRGB(100, 0, 42); puts three R, G, B values into a three-byte array and calls sendData3() to send it off.  [Substitute as appropriate in place of Serial.write]
void sendData3 (byte *dataIn) { // dataIn[] has R,G,B levels
  byte code;
  byte mask=3;          // mask for low 2 bits of a byte
  for (int b=4; b; ) {
    --b;
    byte shif = 2*b;    // For moving bits to align with mask
    code = 0;
    for (int k=3; k; ) { // Loop to handle dIn[2], dIn[1], dIn[0]
      --k;
      code |= (dataIn[k]>>shif) & 3; // Pick off 2 color bits
      code <<= 2;            // Roll up
    }
    Serial.write (code | b);    // Send encoded bits
  }
}

void sendDataRGB (byte R, byte G, byte B) {
  byte dataEg[] = { R, G, B };
  sendData3(dataEg);
}

I'll first try sending an extra sentinel byte outside of the range of any of the rgb bytes (like -7, for example), and if that doesn't work out, I'll try this. Hopefully, this will resolve the issue, but I also wonder if this will only fix the color mutation problem and not the latency one. Thanks for the detailed explanation. I look forward to getting back to you.

Just finished trying my method of ending each color transmission with an end term, and there was no improvement in behavior so I would like to attempt your method. Could you explain how I would encode the rgb values into 4 byes? I've never done something like that so some additional detail/example would be very much appreciated. If I wanted to send the byte color (100, 0, 42) how would that work, for example?

@KentAshfield, I added a C++ example of encoding the data.  Call routine sendData3  or sendDataRGB to encode and write an RGB triplet in four bytes.   ¶ I haven't looked very closely at most of your host-computer code; there, it might make sense to substitute some simple code that cycles through five or six simple colors at about 2 seconds each, and at the Arduino end, have a simpler program without EEPROM stuff, just for testing communications

*jwpat7 thanks for the guidance. Before I jump into the encoding, I might try raising the minimum threshold for sending a color profile from the audio visualizer to something that would correspond to a more prominent call in the music (like a beat, kick, snare, or hat). Doing so would reduce the amount of data being sent to something much more reasonable without sacrificing much of the effect after some tweaks to my equalizer. I'll keep you posted.

Ok great news. When I set up the "simplest scenario" with all excess code removed and a higher minimum threshold, the program worked mostly as desired (equalizers need more fine tuning and my color generator favors blue too much but those are somewhat trivial issues for now). I guess now I just need to go step by step adding in the other code segments again and seeing where the visualizer runs into trouble.