text:
Can't flash ESP8266 anymore (NodeMCU)
So I've been happily making away with these nodeMCU boards now for a while but I came across a strange issue when updating some code on my board.The problem was that I couldn't flash anymore with Arduino's IDE (OR the NodeFlasher tool)
The error I was getting in Arduino's IDE was:
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

I tried flashing over all the memory with the flash tool but that didn't work, I also tried connecting D3 to 3.3v output, that did nothing. I've also tried holding the flash button down while flashing without any effect.

the flash button should be held down at power-up or reset to go into flashing mode at boot. it connects io 0 to ground (D3 is io 0). NodeMCU has circuit to control reset and reset to bootloader by the esptool. The esptool in IDE is different from the esptool.py (until 2.5.0 esp8266 arduino).

Thanks @Juraj , I tried to figure out the right way to "press" the flash button but a lot of things I read were misleading and said to hold until flash was complete.

I am afraid your answer to this question is misleading too. NodeMcu has pull-up resistor on io 0. The bootloader checks io 0 for LOW to start in flashing mode. I don't see a difference in plain wire to ground and a 220 Ohm resistor to ground.

It's entirely possible there isn't one but I hadn't seen anything telling me to do that, this is simply what worked and since it's not broken anymore, I can't test it. But with how many of these I'm running I'm sure it will happen again. I'll update the answer though since not everyone has a 220ohm resistor to try.

The fix ended up being to use a 220ohm resistor between D3 and GND (It has been pointed out, though I haven't tested it, that just wiring D3 to ground on startup should have the same effect). Then unplugging the USB cable, plugging it back in, then flashing the blink program to test. That got it going. I tried a 10kohm resistor too per some documentation I read but that didn't end up working. Wanted to post in case someone else stumbled on this issue.
Source
GitHub Issue
Helpful Articles:
ESP8266 bootloader modes
NodeMCU Pinout

NodeMcu has pull-up resistor on io 0. The bootloader checks io 0 for LOW to start in flashing mode. I don't see a difference in plain wire to ground and a 220 Ohm resistor to ground

Yep, 220ohm worked pretty well for me, thank you :)


text:
Getting different values inside vs. outside a function while using global array
function splitter is designed to get a string of parameters and create a an array of parameters. If only part of parameters were given, the rest of them will get default values.
for example : input string 1,2,3,4 would fill parameters array with values {"1","2","3","4"}, but  if input string is 1,2, parameters={"1","2","20","0"} while parameters[3] and parameters[2] were given its default values.
BUT
when assigning default values, inside splitter the correct values are stored in parameters but when using print_output function to show parameters values - different values are shown.
in output supplied, when input is 1,2,  default values should be pasted, to parameters[2], and parameters[3] , while input is 1,2,3,4 no need to use defaults.
OUTPUT:
Running string 1,2
param_2 was set to default value:20
param_3 was set to default value:0
output:
1
2
0
0
Running string 1,2,3,4
output:
1
2
3
4

CODE:
#define PARAM_AMOUNT 4
#define COLOR 1
#define LED_DELAY 20
#define BRIGHTNESS  50
#define LED_DIRECTION 0

char *parameters[PARAM_AMOUNT] = {"0", "0", "0", "0"};
int param_def[] = {COLOR, BRIGHTNESS, LED_DELAY, LED_DIRECTION};

void setup() {
  Serial.begin(9600);
  Serial.println("Running string 1,2");
  splitter("1,2");
  print_output();

  Serial.println("Running string 1,2,3,4");
  splitter("1,2,3,4");
  print_output();
}

void splitter(char *inputstr) {
  char * pch;
  int i = 0;

  pch = strtok (inputstr, " ,.-");
  while (pch != NULL)
  {
    parameters[i] = pch;
    pch = strtok (NULL, " ,.-");
    i++;
  }

  //  update default values
  for (int n = i ; n <= PARAM_AMOUNT - 1; n++) {
    sprintf(parameters[n], "%d", param_def[n]);
    Serial.print("param_");
    Serial.print(n);
    Serial.print(" was set to default value:");
    Serial.println(parameters[n]);
    delay(50);
  }
}

void print_output() {
  Serial.println("output:");
  for (int n = 0 ; n <= PARAM_AMOUNT - 1; n++) {
    Serial.println(parameters[n]);
  }
}

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

not an error, but strange n <= PARAM_AMOUNT - 1. write n < PARAM_AMOUNT

Create a 2-dimensional array that has enough bytes or use an array with pointers so you can set the pointers to default strings. You have now a mix of those two and it is not well defined. At least write in comments what the maximum values are (how many decimal digits).

@jot - you are write for not commenting, but each parameter in range [0,100]. integer only

It is not a good practice to reserve memory for a string with a constant string. Allocate an array of char arrays with:
char parameters[PARAM_AMOUNT][PARAM_LEN];

Now with "0" you allocate 2 bytes for each string. The '0' and a terminating 0.
Then in splitter function you write 3 bytes into one of the parameters with value "20". This writes outside of the 2 bytes of memory reserved for the string.
strcpy(parameters[i], pch); will copy the token returned by strtok into your array. pch points into inputstr and the delimiters in inputstr are replaced by 'strtok' with zeros

Thank you. But but when parameters is not a pointer array, it can't get pch value... ( I guess I'm still newbie here :( )

paramaters[i]=pch; was changed to sprintf(parameters[i],"%s",pch); now all is OK

source: Stack Exchange

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

sort: votes


text:
Dual power supply using Arduino uno and nano
I had a very vague thought. I was wondering if I could I create a dual power supply using an Arduino uno and a nano. Can the  ground terminals of both the boards be shorted and the 5 volt terminals be used as +5v and -5v . Is this possible? Would it damage the board??

No, because both 5V terminals are +5V.
If both boards are powered by completely isolated power supplies then you could connect the +5V of one to GND on the other. One will then have all its signals and logic negative to your ground level, but normal compared to its own ground level. Managing it though and keeping things separate (no shared ground between two sets of peripherals, etc), would be tricky. And the moment you plug one into your computer the whole lot could go up in smoke.

I didn't quite understand. So are you saying that it is possible  for me to get negative signals if I  have  somehow connect both the Arduino boards on different  power supply and then connect the 5v pin of one board onto the ground pin of the other board and vice versa??

Kind of. The ground of one will be 5v lower than the ground of the other. And the power supplies must be isolated. That is vitally important.

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


text:
Using pointer to a Global function
I am trying to store and use a pointer to a global function.
The function global_f returns a String and takes an object as parameter:
String global_f(Request r){
    // ...
    return "This is it";
}

I have also declared a type:
typedef String (*f_type)(Request);

And this is the class that stores the function:
class T {
    f_type f;

    void setF(f_type fFunc){ // called as: setF(&global_f)
        f = fFunc;
        f(Request());        // This Works
    }

    void callF(){
        f(Request());       // This Freezes the arduino
    }
}

So I can call f in the instructor, but it freezes the Arduino in other methods.
Follow-up: It runs in all methods, that the function is being passed as a parameter and stored in the object.
This is where this functions is called in the actual code: GitHub

//called as: T(&global_f)? it should be T(global_f)

how do you know it is freezing the Arduino? or even working in the first case? You don't do anything with the return value in either case!; can you make a complete, minimal sketch that shows the problem?

@Juraj I tried both of them and they give the same results, also PlatformIO compiles both

@esoterik I am using Serial.print to know how it runs. This is just the most important part of the code for this problem. I can provide a link to github if it is needed.

the snippets are OK. the problem is in the code you didn't show

@Juraj This is the actual code I'm using https://github.com/kachatzis/ArduinoWebServer/blob/758ba6eae7ab1a9fccdbdb3606bdfbfa980be742/lib/EthernetWeb/src/ApiEndpoint.cpp#L47


text:
Stop led from blinking when running
I don't get it. I'm new to Arduino, but not to programming. I don't understand why led pin 13 keeps blinking.
here is my code..
#include <Servo.h>

// X servo angle will stay in [min_x, max_x] range
// Y servo angle will stay in [min_y, max_y] range
// to be adjusted to the size of your living room

float min_x = 5;
float max_x = 50;
float min_y = 5;
float max_y = 35;
int min_freeze = 200;
int max_freeze = 3000;
float minimal_movement = 5;

// finding center of square for starting point
int random_delay;
float x_position = min_x + (max_x - min_x)/2;
float y_position = min_y + (max_y - min_y)/2;
float x_old_position = x_position;
float y_old_position = y_position;
float x_new_position;
float y_new_position;
float x_speed;
float y_speed;
int movement_time;

// Instantiating two servos
Servo x_servo;
Servo y_servo;
int pos = 0;

void setup() {
  y_servo.attach(6);  // attaches the y servo on pin 6 to the servo object
  x_servo.attach(9);  // attaches the x servo on pin 9 to the servo object
  pinMode (13, OUTPUT);
  digitalWrite (13, HIGH);  // switch on  the laser

  //Place the servos in the center at the beginning
  y_servo.write(y_position);
  x_servo.write(x_position);

}

void loop() {
  movement_time = random(10,40);
  random_delay = random(min_freeze, max_freeze);
  x_new_position = random(min_x+minimal_movement, max_x-minimal_movement);
  y_new_position = random(min_y+minimal_movement, max_y-minimal_movement);

  if( (y_new_position > y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position + minimal_movement;
  }  else if ( (y_new_position < y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
    y_new_position = y_new_position - minimal_movement;
  }

  if( (x_new_position > x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position + minimal_movement;
  }  else if ( (x_new_position < x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
    x_new_position = x_new_position - minimal_movement;
  }

  x_speed = (x_new_position - x_old_position)/movement_time;
  y_speed = (y_new_position - y_old_position)/movement_time;
  for (pos = 0; pos < movement_time; pos += 1) {
      x_position = x_position + x_speed;
      y_position = y_position + y_speed;
      x_servo.write(x_position);
      y_servo.write(y_position);
    delay(10);
  }
  x_old_position = x_new_position;
  y_old_position = y_new_position;
  delay(random_delay);

}

Nowhere in this sketch, the line "digitalWrite (13, LOW);" is contained, yet I am unable to keep the LED on solid without blinking when the Arduino is looping. I've other people do it, with this code, I don't get what I'm missing!
Windows 7 64bit, Arduino Uno board, Arduino 1.8.9 program

Welcome to the Arduino SO site. You should select your code and tap the code formatting button (It looks like open and close curly braces ({}). (I edited your question and did it already.)

You did not upload that code. That's still the initial blink sketch, coming together with the bootloader. My guess.  :)

Or maybe your sketch causes a reset (not sure what happens during an exception). Change the initial code to see what happens (like a small pattern of the LED to play, than you also know that your sketch is loaded like DataFiddler assumes (which is even more likely than mine).

Use the serial monitor. Send a message from the setup function so you know that the setup function is executed. Then send a message from the loop.

If you're running a motor you need to have a separate power supply for the motor. There's no way you can drive a servo motor from the Arduino 5V line.  You are much better off using a completely different power supply for your servo motor (just connect the ground lines.)

I did upload my code. I did correction in the program, and that is when I was getting my problem, trying to unload over the first code. When the Arduino is connected to my USB and running what ever program I upload, my computer USB became unstable. Every time the led blink, the computer would unrecognized and re-recognize, which in return made me unable to overwrite the code on the Arduino. Are you guy's getting this too, my computer always beeps when I plug and unplug something, and it was continuously doing that. Re-uploading is a nightmare. I don't know how you guy's do it so easily!

I tried your sketch on an Arduino Uno, with no servos connected, and the LED on pin 13 did not blink.
DataFiddler makes a good point in their comment. To be sure you are actually uploading the sketch, try uploading the Blink sketch that comes with the IDE. Change the delays from 1000ms to 200ms then upload it. The difference in flash rates should confirm or deny the ability to successful upload sketches.
You don't say which servos you are using, so I'll assume they are SG90. I'm not sure if the data sheet for every SG90 servo is the same, but if you look at this one, SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA, each. If you are powering them from the Uno, it can't supply that much current. Another limiting factor is the computer's USB maximum current output, (if you are powering the Uno with a USB port). FWIW, my computer can only provide 500mA per USB.
I would suggest powering the servos with a separate power supply, then see what happens.

If you power your Arduino from the USB port the Arduino current-limits the draw from the USB to 500mA even if the computer's USB port is capable of more.

That is exactly what I found out. I was like why is it not working like it does in the video, then I decided to plug it in the outlet to see how bad it was, and that is when I notice that it was performing just like the video. Thanks for your help.


text:
Why Smart Plugs don't require setting port forwarding on router and how to accomplish this with NodeMCU (ESP8266)
I have a NodeMCU (ESP8266) board that I use to control some devices over the internet. To be able to access it I have to enable port forwarding on my router and set the port manually like in the image below:

But with Smart Plugs (that use a cloud based app) I don't have to set up anything on my router. I am only required to type my Wi-Fi password. So my question is how Smart Plugs are accessed over the router (why they don't need manual port forwarding setting), and how to apply this to my NodeMCU so I don't have to set port forwarding manually.

Port forwarding is required to allow a device outside your router to access a device inside a router that performs NAT (Network Address Translation).
When a NodeMCU is acting as a simple server to respond to requests, it is inside your network, and so the port-forwarding is required so that your phone or computer on the Outside can access it.
However, for the cloud-based "smart" devices, it is different. The smart device opens a connection from itself to a server (the cloud) outside your network. In this case, the router understands that a new two-way connection is created between the cloud server and your smart device.
The only communication to your smart device is from the cloud server to the smart device. If you have an app on your mobile device or computer, that app or website only accesses the cloud server, when then passes the instruction on to your smart device. Reverse direction for status info from the smart device to your app, etc.
These smart devices rely on the infrastructure of their creators to continue to work. There are no LAN-to-LAN connections from the client to the device. Everything goes through the Internet to the remote cloud server, and back.
Many home routers support a protocol called uPNP, that allows a device inside the network to request port forwarding to itself. Some routers require this to be explicitly enabled, because it's a security risk to allow any device to be able to open holes in your firewall/router.
To have your NodeMCU device do this, look for libraries for ESP8266 that implement uPNP. I did a quick search and found https://github.com/ofekp/TinyUPnP though I cannot vouch for it's effectiveness or safety.

Great answer, thanks for the quick response.

MQTT is another protocol worth looking at. It's commonly used in IoT devices (and supported cloud platforms such as the Amazon/Azure IoT offerings) to solve the same problem.

Another question, To avoid port forwarding I made a website where the user sets the device status to ON and OFF. The device status is then stored in a MySQL database. The devices then makes a GET request to the database and retrieves the device status and sets the device ON or OFF. The database is queried every 10 seconds for one device. In your opinion is this approach practically and how many devices can work on one database. Sorry for bothering you.

Whether it's practical is up to the available resources: Your database and server, the bandwidth required, etc.


text:
How can I put this display SSD1306 to sleep?
I have built a kitchen timer and it is supposed to spend most of its life in sleep mode in order to save power. I am using the SSD1306Ascii library (SPI) by William Greiman.
In this library I have found hints to power on and off commands but I don't know how to use them:
/** Set Display off. */
#define SSD1306_DISPLAYOFF 0xAE
/** Set Display on. */
#define SSD1306_DISPLAYON 0xAF

From what I could gather from the web, I need to re-initialize the display after turning it off and on again. But before I take care of that (which should be simple as it is done in setup anyway) I need to find out how to use these commands.
Would you help out a rookie?

So doing oled.ssd1306WriteCmd(0xAE); had no effect?

Can you post a link to the data sheet/instructions for the display?

@MaximilianGerhardt It does have aneffect. Even the desirred one. But until you mentioned it I did not know how to use it. I did not stumble upon ssd1306WriteCmd in the documentation - or upon example to be precise. Thank you!


text:
Wire doesn't work between Uno & ESP32S & ESP8266
I think i've reached my limit. I can't get Wire to work between an Uno or ESP8266 or ESP32S. On the Uno I had them connected like SDA via Uno SDA -> ESP32 GPIO21 SCL via Uno SCL -> ESP32 GPIO22.
I also tried flipping them like this:

SDA via Uno SDA -> ESP32 GPIO22
SCL via Uno SCL -> ESP32 GPIO21

Connections are as follows:

SDA via ESP32 GPIO21 -> ESP8266 GPIO4
SCL via ESP32 GPIO22 -> ESP8266 GPIO5

I also tried flipping them, as follows:

SDA via ESP32 GPIO21 -> ESP8266 GPIO5
SCL via ESP32 GPIO22 -> ESP8266 GPIO4

I have present a 4.7 kOhm pull-up resistor from SDA and SCL to +3.3 V.
All these combinations led to nil result on I2C bus scanners. I tried 5 scanners and 3 Wire libs. I tried having the ESP32 as slave because I heard the ESP8266 won't work as slave. I know I'm doing something wrong but can't figure it out, I've been at it all day.

the esp8266 and the esp32 Wire library supports only master. so you can't make them communicate

That is unforturnate. I believe stickman is working on a lib that supports slave.

sorry, the esp Wire libraries support slave mode, but it is experimental and doesn't work in most cases

In https://github.com/espressif/arduino-esp32/tree/master/libraries/Wire/examples they provide examples of master, slave, and scan.


text:
Unstable analog results
I have a rock solid voltage on my analog input with ADC values jumping around by about 15% on the Serial monitor and LCD display
Never had anything like this before
Seeeduino V4.2
pinMode(A1, INPUT_PULLUP);
volt = analogRead(A1)
Am I the proud owner of a faulty board? ( wish I had a spare one to test )
regards
Wilfried

INPUT_PULLUP? explain. and how do you measure "rock solid"?

I think INPUT_PULLUP doesn't do anything here. Analogread does all necessary pin configuration. Have you measured the input voltage with an oscilloscope?

Probably not related but you should probably not use INPUT_PULLUP mode when you want to read an analog input. Just use INPUT mode. `INPUT_PULLUP mode internally connects the pin to +5V through a resistor, which is going to throw off your voltage readings.

I have seen this many times in the past on many different families/brands of microcontrollers.  A/D systems are extremely sensitive to electrical noise especially on the AREF pin.  Check the loading on your 5V supply, that, I believe is the source for AREF. Inductive loads are notorious for injection of electrical noise into an analog sub system. If you are powering any loads from the 5V supply eliminate them one by one and see if you get a solution. I have seen LEDs cause this problem especially with PWM.


text:
RGBs and Potentiometers
I think my if statement can't be read here in my program. The RGBs should light up and change color when the potentiometer is turned but instead the RGBs just light up immediately and change color simultaneously. How do I fix this?
int POT1=A0;
int POT2=A1;
int POT3=A2;
int Red1=9;
int Green1=10;
int Blue1=11;
int Red2=3;
int Green2=5;
int Blue2=6;
int sValue1=0;
int sValue2=0;
int sValue3=0;
int oValue1=0;
int oValue2=0;
int oValue3=0;
int value1=0;
int value2=0;
int value3=0;
int timer(250);

void setup() {
 Serial.begin(9600);
 pinMode(Red1,OUTPUT);
 pinMode(Green1,OUTPUT);
 pinMode(Blue1,OUTPUT);
 pinMode(Red2,OUTPUT);
 pinMode(Green2,OUTPUT);
 pinMode(Blue2,OUTPUT);

}

void loop() {

sValue1=analogRead(POT1);
sValue2=analogRead(POT2);
sValue3=analogRead(POT3);

oValue1=map(sValue1,0,1023,0,255);
oValue2=map(sValue2,0,1023,0,255);
oValue3=map(sValue3,0,1023,0,255);

if ((sValue1<=127)&&(sValue2<=127)&&(sValue3<=127));
{
  setColor1(0,255,255); //red
  setColor2(255,255,0); //blue
  delay(timer);
  value1=0;
  value2=0;
  value3=0;

}

if ((sValue1<=127)&&(sValue2<=127)&&(sValue3>127));
{
  setColor1(255,255,0); //blue
  delay(timer);
  setColor2(255,0,255); //green
  delay(timer);
  value1=0;
  value2=0;
  value3=1;
}

if ((sValue1<=127)&&(sValue2>127)&&(sValue3<=127));
{
  setColor1(255,0,255); //green
  delay(timer);
  setColor2(0,255,255); //red
  delay(timer);
  value1=0;
  value2=1;
  value3=0;
}

if ((sValue1<=127)&&(sValue2>127)&&(sValue3>127));
{
  setColor1(0,255,255); //red
  delay(timer);
  setColor2(255,0,255); //green
  delay(timer);
  value1=0;
  value2=1;
  value3=1;
}

Serial.print("POT 1=");
Serial.print(value1);
Serial.print("\t POT 2=");
Serial.print(value2);
Serial.print("\t POT 3=");
Serial.print(value3);

if ((value1==0)&&(value2==0)&&(value3==0))
{
 Serial.print("\t RGB1=");
 Serial.print("RED");
 Serial.print("\t RGB2=");
 Serial.print("BLUE");
}

else if ((value1==0)&&(value2==0)&&(value3==1))
{
  Serial.print("\t RGB1=");
  Serial.print("BLUE");
  Serial.print("\t RGB2=");
  Serial.println("GREEN");
  Serial.println(" ");
}

else if ((value1==0)&&(value2==1)&&(value3==0))
{
  Serial.print("\t RGB1=");
  Serial.print("GREEN");
  Serial.print("\t RGB2=");
  Serial.println("RED");
  Serial.println(" ");
}

else if ((value1==0)&&(value2==1)&&(value3==1))
{
  Serial.print("\t RGB1=");
  Serial.print("RED");
  Serial.print("\t RGB2=");
  Serial.println("GREEN");
  Serial.println(" ");
}

}

void setColor1(int red1, int green1, int blue1){
  {
    analogWrite(Red1,red1);
    analogWrite(Green1,green1);
    analogWrite(Blue1,blue1);
  }
}

void setColor2(int red2, int green2, int blue2){
  {
    analogWrite(Red2,red2);
    analogWrite(Green2,green2);
    analogWrite(Blue2,blue2);

  }
}

The code you posted is more complex than your description.  Assuming you copied and pasted it, try simplifying it.  You only need a few lines to change the color of the LEDs based on the position of a potentiometer.  Include either a description of your hardware connections, a schematic or a clear picture of your wiring. Then edit this question.

By the way, why not just use your pot values (scaled to 0-255) to set the red, green, and blue channels of your LEDs directly?

How do I do that?????

I haven't traced through your if statement logic in detail to see what you are trying to do, BECAUSE I found that you have statements like this:
//            Get rid of this semicolon in every if statement.
//            |
//            V
if (condition); {
    //        ^
    //        |

    //Code that will always be executed
}

You should NOT have a semicolon after an if statement like that. That says "if (condition) then do nothing" (A semicolon creates a blank "do-nothing" statement that becomes the code that is executed if the if statement is true. Then the code in the braces gets executed every time.)
It is parsed as:
if (condition) <empty_statement;>

{
    code that always executes
}

That is one of the hidden "nasties" of C and it's close cousins like C++, Java, and Objective-C. Another nasty is typing:
if (a=b)

...when you mean if (a==b). (The first version puts the value of b into a, and then evaluates b as a boolean. If it's 0, the if statement is treated as false. If it's non-zero, the if statement is evaluated as true.
Another one is the fall-through cases in C switch statements. If you forget to add a break statement at the end of each case it falls through to the next case.


text:
Problems with serial communication from Arduino to ESP8266
I've been trying to get an Arduino and ESP8266 to communicate with each other over serial. The ESP8266 uses the Serial class for communications, while the Arduino uses SoftwareSerial.
The problem is that when I try to send data from the Arduino to the ESP8266,  only the first character of the string sent gets received by the ESP8266. For example, if I send a string "leather", the ESP8266 only receives an 'l'. Both devices are operating at 38400 baud, although I have tried 9600 baud with similar results (apparently SoftwareSerial is more reliable at lower baud rates).
Here is the relevant code that's running on both devices:
Arduino code:
#include <stdlib.h>
#include <SoftwareSerial.h>

#define COMMAND_TILT                'c'
#define SOFTWARE_SERIAL_BAUD_RATE   38400
#define ESP_RX                      8
#define ESP_TX                      9

SoftwareSerial esp(ESP_RX, ESP_TX);

void setup()
{
    ...
    esp.begin(SOFTWARE_SERIAL_BAUD_RATE);
    ...
}

void loop()
{
   if (esp.available() > 0) {
        String data;
        while (esp.available() > 0) {
            data += (char) esp.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);
        int value = data.toInt();
        char buf[STR_BUF_LEN];

        switch (command) {
             case COMMAND_TILT:
                 ...
                 sprintf(buf, "%c%d", COMMAND_TILT, value);
                 esp.write(buf);
                 break;
             ...
        }
    }

    delay(100);
}

...

ESP8266 code:
#define SERIAL_BAUD_RATE 38400

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

void loop()
{
    ...

    if (Serial.available() > 0) {
        String data;
        while (Serial.available() > 0) {
            data += (char) Serial.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);

        // problem: now, data.c_str() is blank when it should contain an integer in string format

        ...

        delay(100);
    }
}

...

If it helps to know, I'm running an MQTT client on the ESP8266 and controlling some steppers and relays on the Arduino.

use SoftwareSerial at 9600 baud. not more

@Juraj if you read the bottom of my questions it says I tried 9600 baud. Unfortunately no difference.

why do you thing that data will be available without a gap?

Strangely I am able to send data from the ESP to the Arduino in two separate write() calls and still get it in one piece on the Arduino side. But even if I send the data in one buffer the other way around, the ESP only gets the first character. For any gaps in data, shouldn't the Serial.available() calls take care of things? Or do you mean something else entirely?

Serial.available() returns the count of bytes in RX buffer. but at 9600 baud the bytes are coming very slow

you can use the blocking functions readString or readBytes, but it would be better to know the terminator char. https://www.arduino.cc/reference/en/language/functions/communication/serial/

The cause of the issue was that the ESP was reading chars too quickly, meaning that it would give up before the next char could be sent from the Arduino. To fix the issue I simply added a 10 ms delay between each Serial.read() call on the ESP.


text:
arduino is skipping the if statement
Hi guys I am new to this language and i just tested the code to control a servo motor
Can anybody help me please ? here is the code
void setup() {

  servo_test.attach(3);
  pinMode(9, INPUT);

}

void loop() {

 if ( digitalRead (9 == HIGH)) {

   for(angle = 0; angle < 180; angle += 5)    to 180 degrees
  {
    servo_test.write(angle);
    delay(5);
  }

  delay(4000);
  for(angle = 180; angle>=1; angle-=5)      to 0 degrees
  {
    servo_test.write(angle);               specified angle
    delay(5);
  }

    delay(4000);
}

}

It is just like the arduino completely ignore the if statement and start the loop wheter pin 9 is in high or low state  even if  i wire it directly to gnd

Try digitalRead(9)==HIGH

In your code this line:
 if ( digitalRead (9 == HIGH)) {

...is likely passing the function "digitalRead()" the value zero as "9 == HIGH" is likely false.
Likely what you want to do is check if the value returned by the function "digitalRead()" is high.  Try:
 if ( digitalRead (9) == HIGH) {

...instead.

Yeah, that line is wrong. That code evaluates as if (digitalRead(0)), which returns the value of pin 0. Not sure how LOW is defined in the Arduino IDE. If it's 0 then you'll get false if pin 0 is ==LOW and true if the pin is ==HIGH.

so Arduino SE becomes a typo correction site. this answer is not useful

@Juraj I don't think it's a typo. It's a newbie's syntax error that compiles. I'm sure the answer was quite useful to the OP.


text:
I2C potentiometer mess
I bought a few MCP4651 dual 8 bit I2C pots for a project. After browsing the arduino libraries and finding nothing,"No big deal" I thought to myself ... I've already written I2C libraries for other parts that were much more complicated! (e.g: ADS1219 24 bit ADC)! so just load up the datasheet and watch the memory maps and commands! ok, there are some stuff on page 49 which seem useful! oh boy was I ever wrong! this data sheet looks like nightmare! the worst documentation for any I2C device I've seen so far. The commands I wrote based on that did absolutely nothing!
I found a code for controlling an I2C pot in one of the arduino examples which is something like this:
#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte val = 0;

void loop() {
  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
  // device address is specified in datasheet
  Wire.write(byte(0x00));            // sends instruction byte
  Wire.write(val);             // sends potentiometer value byte
  Wire.endTransmission();     // stop transmitting

  val++;        // increment value
  if (val == 64) { // if reached 64th position (max)
    val = 0;    // start over from lowest value
  }
  delay(500);
}

I decided to just try it and see what happens (changed the address to the correct value) and crazy enough it actually worked! so I hacked this piece of code to get the first pot to work!
void setPot0(int n){
  if (n>256) n=256;
  if (n<0) n=0;
  Wire.beginTransmission(address);
  if (n<256){
    Wire.write(0x00);
    Wire.write(n);
  } else{
    Wire.write(0x01);
    Wire.write(0);
  }
  Wire.endTransmission();
}

and somehow this works! I still can't find this pattern in any of the pages on datasheet, but hey! it works so I'm not gonna complain about that?
I still haven't managed to make the pot1 to work, only pot0 ... if you can make sense of how the commands and data bytes should be like, please help me. It's so much more clear in T.I datasheets; you just use the command to write to the register you want and they detail what each register does:

Edit: here is a link to the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/22096b.pdf

what is your actual question? ....  the only question in your post is asking something about complaining

my question is how on earth should I send the I2C commands to use the pot. as I mentioned the code I wrote works but matches non of the I2C address and data patterns that they mentioned in their data sheet. I'm not sure what the control bytes should be and what's a general call vs a normal call? they just say general calls can change multiple pots (if present)?

general call and normal call are actually part of the I2C specification, it has to do with addressing single or multiple I2C devices

Does chapter 4 of the datasheet not give you all the information you need? Including the details of the THREE registers (yes, only THREE) for controlling the device?

I still can't find this pattern in any of the pages on datasheet -- Not even in Chapter 4, table 4-1 where it lists the registers? Register 0 is pot 0, and register 1 is pot 1. Clearly stated.

The registers are listed in table 4-1. Clearly enough.
The command byte format is shown in chapter 6. That command byte includes the operation and the register number, as well as upper bits for registers that expect more than 8 bits of data.
Two bytes are needed to set a register.  The first 4 bits are the register number (0000 for wiper 0, 0001 for wiper 1, and 0100 for the TCON register).  The next two bits are the operation as shown in figure 7-1. 00 for a simple write. The next two bits are the upper 2 bits of the data.  Following that are the lower 8 bits of data.
So to write a pot 0 value of 0x23 you would write:
0x00 0x23

To write a pot 1 value of 0x65 you would write:
0x10 0x65

To write a pot 1 value of 0x13D you would write:
0x11 0x3D

You can make a simpler function to wrap it for you:
void writePot(uint8_t address, uint8_t pot, uint16_t val) {
    Wire.beginTransmission(address);
    Wire.write((pot & 3) << 4 | ((val >> 8) & 3));
    Wire.write(val & 0xFF);
    Wire.endTransmission();
}


text:
Quadcopter oscillation using PID
I am building an Arduino based flight controller for a quadcopter and have got it flying but it is not performing how I want it to. The drone is flying but when I release the sticks the drone does  not stay perfectly still. There is some random and small oscillations that occur when it is just hovering.
Right now I am using a single PID controller for each axis though functions like this.
dt=0.005;
error = *in - *set;

P = (error * kp);
I = I + (error * ki)*dt;
D_M = ((*in - in1)*kd)/dt;
D_E = ((error - error1)*kd)/dt;
D=D_M*(1-jerk) + D_E*(jerk);

I = constrain(I, LOWER_BOUND*0.75, UPPER_BOUND*0.75);
in1 = *in;
error1 = error;
pid = P + I + D;

pid = constrain(pid, LOWER_BOUND, UPPER_BOUND);
*out = pid;

The error is the Euler angle and the setpoint is the angle I want it to go to.
I then output the PID controller values to the motors using the Arudino Servo library.
  motor1 = throttle;
  motor2 = throttle;
  motor3 = throttle;
  motor4 = throttle;

  motor1 += rollOUT;
  motor2 += rollOUT;
  motor3 -= rollOUT;
  motor4 -= rollOUT;

  motor1 -= pitchOUT;
  motor2 += pitchOUT;
  motor3 -= pitchOUT;
  motor4 += pitchOUT;

  motor1 += yawOUT;
  motor2 -= yawOUT;
  motor3 -= yawOUT;
  motor4 += yawOUT;

Is there something I am missing about quadcopter PID controllers? Thank you for the help!

Are the disturbances due to external effects (wind and turbulence)? Do they occur in still air, such as in a quiet indoor environment? In other words, can you tell whether the PID controller is the source of the problem or is just less-than-perfect at overcoming external forces? A feedback controller depends on the error-signal as its source of information, so by definition, it can never do a perfect job. If it could, its source of information would go to zero, i.e., it would "blind" itself.

@JRobert I am flying indoor with no outside disturbance. The quad flys and stays extremely steady for about 2 seconds and then these small but random "bumps" make itnwobble before it steadies out again. I've read that some people use angular rates instead of angles? Is that common? And if so how do I know the angular rate to set it at with a certain error?

I'm beyond my knowledge here (no drone experience), but I have to wonder about the "steady - wobble - steady again" cycles, especially if they are regular. Something seems to be disturbing it - software, electronic, atmospheric - especially since it seems very capable of holding steady, even if its only for short periods. It might be interesting (but challenging ): to log some raw sensor data and look for corresponding noise or other displacements.

Check kd relative to the measurement error.  Maybe the measurement error noise is significant enough that multiplying its derivative by your 200*kd factor is enough to bump the system.

I'd suggest setting Kd to zero, Kp to a minimal value and letting the integral alone function as the controller. Any response to an error might be slow but the integrator alone will control a process with zero error. After observing the response of the integral for a period of time, hopefully without the problem you referenced, gradually introduce proportional control and watch for the periodic instability. If increasing the proportional gain results in oscillation, reduce the proportional back to a stable value and gradually introduce more derivative gain. I have worked with PID throughout my career and the instability you described sounds like something I'd expect to see originating from the derivative control action. No sensor is perfectly noise free and even if the noise is low amplitude, the rate of change may still be fairly large which will result in a very obvious periodic instability in the flight of your drone.
If this is the case, finding the source of the induced noise may not be easy. Perhaps reducing the derivative gain and using mostly proportional and integral control will effectively filter and attenuate the instability you're noticing. Good luck.

"Good luck." It's difficult to say, being four years later, whether or not they'll get that. I'll vote it up for the effort and that someone may find it useful.

I saw it was dated 2019 but thought the reply might benefit others struggling with debugging PID control and tuning issues. Isolating PID related operational perturbations is a fairly common event in a number of industries well outside of drones. - JL


text:
How do I grab data from my Arduino device using a Python program?
We are currently creating a system which can log student attendance using RFIDs. Currently, we have the RFID Scanner set up (MFRC522 reader and Arduino UNO microcontroller). The database for the student's info and time-logging is also already set up. We are; however, having problems with accessing the data the Arduino is sending. We want the Arduino device to send us the Tag IDs via a USB Connection and have set it up to send the relevant data through the Serial Port. However, we cannot access this data using a Python program with this code.
import serial

x = 1
while(x == 1 ):
    ser = serial.Serial("COM3", baudrate = 9600, timeout = 0)
    if(ser.is_open):
       print("Serial Port in Use")
    else:
       print("Card ID: " + ser.read)

We are attempting to read from Port COM3 (the SP the Arduino uses). If the serial port is in use, the program outputs the "Serial Port in Use" (for testing purposes only, to be removed in final code) and if not, it will output the Card ID. However, through this, we run into the problem of being unable to use the same serial port with the Arduino (we are running on Windows). We tried using a serial port splitter but replacing the "COM3" with the name of the virtual port does not work.
We would prefer not to use Processing and would be open to simply avoiding the use of a serial port completely.

How do I grab data from my Arduino device using a Python program? ...... use the serial port to transport the data ..... i think that you answered your own question

use the serial monitor in the Arduino IDE to verify the presence of valid data before you proceed with python code development

It isn't a good idea to open serial in a loop. It can be opened once at the start (or you can retry once per few seconds, if it fails).
Also the method is_open should return true if the serial was successfully opened so you can use it.
Maybe some working example would be a good way to start.

We are completely sure the Arduino is working properly, as checking the Serial Monitor reveals the device is reading properly. The real problem arises whenever we run the above code while the Arduino is plugged in and on. On running the code, an error occurs at Line 5 (opening the Serial Port). The error says, among other things "Cannot Open Port: Access Denied"

@o0V0o I'm not questioning Arduino side. I'm just pointing on condition that seems to be wrong, and port opening logic in python code.


text:
analogWrite is not working - while trying to control DC motor speed
I'm trying to control the speed of DC Motor using

Arduino R3
NPN Transistor (2N2222A331)
10k potentiometer
2M ohm resistor
Diode

I'm not using L298N and I'm also not using L293D.
DC motor is running, but the speed of DC motor doesn't seem to change with changes in potentiometer.
Circuit seems to be alright as DC motor is running.
The code is as follows
int potPin = A0;
int motorPin = 9;
int potValue = 0;
int motorValue = 0;

void setup()
{
 Serial.begin(9600);
 pinMode(motorPin,OUTPUT);
}

void loop()
{
 potValue = analogRead(potPin);
 motorValue = map(potValue, 0, 1023, 0, 255);
 analogWrite(motorPin, motorValue);
 delay(2);
 Serial.print("potentiometer = " );
 Serial.print(potValue);
 Serial.print("t motor = ");
 Serial.println(motorValue);
}

Whenever I tweak the Potentiometer, I can see the relative changes from Arduino  "Serial Monitor" (both Potentiometer values and Motor values), but the speed doesnt seem to change physically.
Things that I tried

tried different combinations of resistors(100,1k,10k,1M,2M ohm) so as to vary voltage that goes to DC Motor
tried to check with different Output pins like 3,5,9

Nothing works, DC motor speed isn't changing.
this leads me - to believe that, my analogwrite isn't working.
please help me understand as to what i'm i doing wrong?
The Circuit is as follows

set the value with analogWrite only if it changed. now you restart PWM in every loop

Two things to test:

Have you tried to put an LED (and resistor to protect it) in the motor's place? If the brightness changes, your setup (Arduino+transistor) is working. If not, maybe you've killed your 2N2222 by giving it a wrong diode or something else is wrong.
Have you tried reducing the PWM frequency? An LED can follow a fast change, but a motor can't. Also, by turning on-off the motor less frequently you dissipate less power on your transistor and diode. A quick search gave me this: this.

Referring to this datasheet you have connected the transistor the wrong way around. Also, 1M resistor at the base is way too high. Bipolar transistors are current amplifiers (amplification at about 50-100 in your case) and with 1MOhm at the base there will be no current through the base at all. I would try with 2k for a beginning.
I hope you have another transistor because this one seems to be broken and I'm pretty sure that it's not a fault in the analog output. If the output stage of the uC was broke there would be no reaction (at least in a correct circuit)

Well, 2M resistor to the base? If the motor is running with that, the transistor must be broken (shorted). Just try to check if the motor is running with disconnected base.
You can also check PWM output by connecting LED with resistor (no, not 2M ohms, just about 330 ohms). For the transistor 1k should be sufficient maybe little less (depends on motor current and h21e amplification coeficient).
Also there are some versions 2N2222 with emitter and collector swapped. And reversed transistor has much lower current amplification coeficient.
And I hope you are using external power supply, USB is not a good idea. Starting power is usually way too much for the overcurrent protections.
Anyways, this works for me:
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  analogWrite(9, map(analogRead(A0), 0, 1023, 0, 255));
  delay(100);
}

2N2222A + 1k + PC FAN + 12V Fan Power supply.
Connections: E -> Gnd, C -> FAN-, FAN+ -> 12V, 12V GND -> Arduino GND, Pin 9 -> 1k -> B
On the Arduino side 47k trimmer and the USB

Thanks for the reply !! ....but issue remains !!
Motor is not running with disconnected base !!
i checked PWM output with LED and resistor (dimming brightness of LED) ....it seems to work as per expectation
Tried swapping the connections of emitter and collector .....DC motor ran but no speed control
adriuno dint powerup with 9v battery for the DC motor circuit....so im using USB as power supply !!
im running out of options , please do help me !!

@SharathChandra Works for me perfectly with PC FAN and external 12V PSU. Even with 2ms delays.

And also DC motor + antiparallel shottky is working (with own PSU)

Can you vary the speed of a plain DC motor using PWM?  I would think pulsed DC would play havoc with it, giving strange results. I'd expect to need an RC filter to convert the pulsed output into a fairly constant DC output. I know some servos are made to run on DC, but a normal DC motor?

@DuncanC Sure I can, but it's without the load. It's a small dc motor from some old walkman. However as it's DC motor with commutator, I don's see why it should be so bad, maybe bigger EMI. And the power peaks gives some extra torque at low RPMs.


text:
Can I connect a DS3231 and an MPU6050?
Can I connect a DS3231 and an MPU6050 by an Arduino Mega 2560? I have connect it:
MPU 6050               Arduino Mega 2560
SDA           =        SDA
SCL           =        SCL
GND           =        GND
VCC           =        5V

And I have connected DS3231 to SDA and SCL beside AREF pin:
DS3231               Arduino Mega 2560
SDA           =        SDA
SCL           =        SCL
GND           =        GND
VCC           =        5V

The problem is when I connect both of them MPU6050 prints nan, after opening the DS3231 pin from the arduino, MPU6050 prints the correct angles.
Can someone please help me?
Code:
#include "MPU6050.h"
#include "Wire.h"
#include <DS3231.h>
MPU6050 accelgyro;
int16_t ax, ay, az, gx, gy, gz;

DS3231 rtc(SDA, SCL);

double timeStep, time, timePrev;
double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

int i;
double gyroScale = 131;

void setup() {
  Wire.begin();
  accelgyro.initialize();
  Serial.begin(9600);
  rtc.begin();
}

void loop() {
  timePrev = time;
  time = millis();
  timeStep = (time - timePrev) / 1000;
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;
  arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
  arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);
  if (i == 1) {
    grx = arx;
    gry = ary;
    grz = arz;
  }
  else{
    grx = grx + (timeStep * gsx);
    gry = gry + (timeStep * gsy);
    grz = grz + (timeStep * gsz);
  }
  rx = (0.1 * arx) + (0.9 * grx);
  ry = (0.1 * ary) + (0.9 * gry);
  rz = (0.1 * arz) + (0.9 * grz);
  Serial.print("X axis == ");
  Serial.println(arx);
  Serial.print("Y axis == ");
  Serial.println(ary);
  Serial.print("Z axis == ");
  Serial.println(arz);
  Serial.println(rtc.getTimeStr());
  i = i + 1;
  delay(1000);
}

run I2C scanner sketch

What DS3231.h library are you using, and why are you specifying the pins to use? That probably puts it into software I2C mode and breaks hardware I2C.

I am using this DS3231, Link = http://www.rinkydinkelectronics.com/library.php?id=73...

And how to run I2C scanner, what is it?

The DS3231 library you are using works (for some bizarre reason) exclusively with its own internal bit-bang implementation of I2C. This cannot be used on the same pins as the hardware Wire library which the MPU6050 uses.
Either move the DS3231 to a different pair of pins, or find a better DS3231 library that uses the Wire library for communication.

Yes. Using i2c, you need to change the address of the MPU6050 because the default is (0x68) which is also the default and only address the DS3231 can use.
Example of changing the address from a personal sketch:
MPU6050 mpu(0x69);
So try:
MPU6050 accelgyro(0x69);


text:
digitalWrite on Trace SWO pin
I'm using STM32(generic board) and I want to control bi-color LED(common anode). STM32 pin layout and scheme is below, so please see it.
Now, in theory scheme Works, but in practice it Works halfway. Red LED is connected with PB8 pin and green LED is connected with PB3 pin.
Code is simple so I think that problem is not in the code. Red LED Works, but green doesn't work. If I connect green cathode with GND manually, then it Works, otherwise(with STM32) it doesn't.
Later I found that pin PB3 has Trace SWO mark(see pin layout below). I'm not completly sure what Trace SWO means, just found that it some kind of debugigng protocol(I guess) but I can't find info can it be used for digitalWrite purposes. Is there any way to habilitate PB3 pin for digitalWrite? All other pins are in use.
Code:
// DOWN
digitalWrite(PB3, HIGH);
digitalWrite(PB8, LOW);
delay(750);

// UP
digitalWrite(PB8, HIGH);
digitalWrite(PB3, LOW);
delay(750);

STM32 pin layout

R4 doesn't exist, it's mistake in scheme

did you solder the headers?

Don't understand you?

usually the Blue Pill is sold without pin headers soldered

@Juraj really? I didn't know that. Thanks for info! ♂

how can you don't know that? did you get it with pin headers soldered or without pin headers? https://cdn.instructables.com/F46/4FA4/JM8A987M/F464FA4JM8A987M.LARGE.jpg

Are you troll or? Of course I soldered pins. STM32 is on breadboard. How could I use STM32 without headers and breadboard?! Btw. I fixed the problem. Just deleted line in boards.txt file.

I didn't ask if you SOLDERED the headers.  I asked if YOU soldered the headers. :-) If I solder the headers then I test the pins and sometimes I must fix the soldering. I always first ask basic things, because many times they are the problem.

like here https://arduino.stackexchange.com/questions/57370/sd-card-failed-to-initialize/57387#57387


text:
How to interface MPU9250 and NodeMcu?
I am trying to send MPU sensor data to Pubnub IOT platform but not able to do it since there is some unknown problem. There is no error in code but following issue pops up in com port:-

It looks like sensor reading needs to be in JSON Format but no sure how to do it. I Just need it in raw imu sensor reading for now so how do i get it.
Here is the code:
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
#include "MPU9250.h"

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

const char * pubkey = "my key";
const char * subkey = "my key";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

MPU9250 IMU(Wire,0x68);
int status;

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(115200);

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);

    while(!Serial) {}

  // start communication with IMU
  status = IMU.begin();
  if (status < 0) {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while(1) {}
  }
}

void loop() {
    // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

What do you guys think?

I hope your pubkey and subkey aren't sensitive data

no, its just demo key. but will change it just in case.

The error you're reporting is coming from your call to PubNub.publish(). You could have diagnosed the problem by taking outputting and inspecting what you were passing to it.
Your line:
PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");

is not going to work. You're sending the string "String(IMU.getAccelX_mss())" to PubNub rather than the value of IMU.getAccelX_mss() as a String. Take the quotes off it:
PubNonSubClient *pclient = PubNub.publish(pubchannel, String(IMU.getAccelX_mss()));

If for some reason the number has to be returned as a string, the code would look like:
PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"" + String(IMU.getAccelX_mss()) + "\"");

I tried but it doesn't work. In Pubnub documentation its written to send that data in JSON format. eg - ""message"" . I know about uploading string but don't know about uploading data as a variable. You know how to upload variable as JSON.

You'll need ArduinoJson to make JSON easier - but if the data you are sending is very simple, then there's probably no need for ArduinoJson library - please add to the question the expected format of the data you are sending

I just need raw sensor reading for now

The answer I gave you sends the raw sensor reading to the server. You keep saying you need to send JSON. What should the JSON look like?

Expected format should be ""IMU.getAccelX_mss()"" .Just that imu.get needs to show an actual reading.

It's odd that a number should be returned as a string. I've updated the answer to publish a string instead of a number.


text:
Uploading bootloader to ATMEGA328 P
I have a duemilanove which originally had a 168.  I have some ATMEGA328 P chips and I've put one into the duemilanove.  I am using a Uno as a programmer for the duemilanove.  I am running Arduino 1.8.2 on a PC which I understand doesn't need a capacitor installed on the Uno.  I've uploaded the sketch which makes the Uno an ISP, I have edited the avrdude.conf file, have wired up in accordance with http://www.crash-bang.com/resource/bootload-atmega328/ and the tutorial on this site.  When I run burn bootloader using the preferences set to verbose, the returned signature is correct for the P version of the chip I believe (0x95 0x14) and this is the value I have put into the avrdude.conf file.  However, avrdude is still insisting it is expecting to receive 0x95 0x0F and will not burn the bootloader.  I have no idea where it is getting this value from (I've even tried editing the iom328p.h file...). Any ideas?

Why do you want to use a duemilanove?  Why not use UNO which has better spec and is actually still supported?

What board did you select, to "burn bootloader"? From what I know, putting an ATMega328 in a duemilanove board, will make it (more or less) identical to an UNO. So select the UNO from the boards, and press "burn bootloader", should work.

I've had the same issue with some standalone 328P project.
If you enable "Show verbose output during: upload" in the preferences menu, you can see the command which the Arduino IDE uses to flash your device - avrdude.
Copy it from the terminal window into a command prompt, and add "-F" to that to disable the device signature check.

@TobiasWeiß disabling the device check is not a good practice when you want to write to the chip and besides is not elegant. There must be a simple misconfiguration which has to be found and fixed

The signature bytes are:
ATmega328 0x1E 0x95 0x14
ATmega328P 0x1E 0x95 0x0F
So it looks you have the wrong bytes for the 328P.


text:
Connecting multiple MAX30100/30102 via I2C
I want to connect multiple (up to 4) MAX30100 or MAX30102 oximeter sensors to an Arduino via I2c. But I could not find a solution to change/assign the I2C address.
implementing-pulse-oximeter-using-max30100
datasheet MAX30100

it appears that the slave address is fixed, as per page 24 of the linked document ...... there is a typo in the document that refers to Table 18 ..... it probably should say Table 17

maybe the address register is undocumented ..... try reading all 128 registers ..... see if one of them contains the value AE

LTC4316 is what you need. I haven't used it yet, but I know it from a project that did: mocap. It is an I2C translator IC.
Of course, if you need those ICs to be far away from each other, use a uC (or a separate Arduino) with all of those, and connect them with a different protocol!

Good suggestion. (voted). I did not know that such chips existed. (Note that the data sheet I found online (https://www.analog.com/en/products/ltc4316.html#product-overview) says "At least one model within this product family is in production and available for purchase. The product is appropriate for new designs but newer alternatives may exist." Thus there might be newer chips that serve the same purpose and are likely to be available longer-term.

And that chip appears to be surface-mounted. I'm not equipped to do surface-mount soldering. I did find this option on SparkFun: https://www.adafruit.com/product/2717?gclid=EAIaIQobChMIk7S1-PLm4AIViZ-fCh39PQWEEAQYBSABEgJZ1PD_BwE

@Duncan C: MAX30100 is surface-mounted as well, so that's hardly a problem for OP. But thanks for the suggestion anyway! I haven't used it yet, I'm only familiar with this chip because I've read the above project. (I had to look for that mocap site to get the precise IC type.)

Is there any other way of solving this issue?
I do not want to increase Hardware dependency.
I found out this article - which lets you use multiple i2c devices with the same address by employing different data lines: https://bitbanksoftware.blogspot.com/2019/01/controlling-lots-of-oled-displays-with.html
The Github source: https://github.com/bitbank2/Multi_BitBang
To my knowledge, I, either have to implement this library my own way or us the TCA9548APW chip as described by @Duncan C in the above answer

Welcome to Arduino:SE This doesn't appear to provide an answer to the question. To ask another question, just click Ask Question above. If you wish, include a link to this question to help provide context.

Nyos's suggestion of an I2C address translator is the ticket. I hadn't heard of these chips before, so I started searching. I found that the one they recommended may be being phased out. It also looks like it's surface-mounted. I found a TI data sheet that lists a DIP package chip TCA9548APW that lets you map up to 8 I2C devices to different addresses. You might want to check those out as an alternative.


text:
Servo doesn't move with fingerprint
I've a project which i need to make a door open and close using the fingerprint.
I've successfully made fingerprint works just fine it reads and confirm the fingerprints stored in it but the servo doesn't act at all to my confirmed finger print.
    #include <Servo.h>
    #include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
Servo myservo;

int getFingerprintIDez();
int pos = 0;
int id ();
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino (WHITE wire)
SoftwareSerial mySerial(A12, A13);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
//Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial1);

void setup()
{
myservo.attach(10);
while (!Serial); // For Yun/Leo/Micro/Zero/...

Serial.begin(9600);
Serial.println("Adafruit finger detect test");

// set the data rate for the sensor serial port
finger.begin(57600);

if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :(");
while (1);
}
Serial.println("Waiting for valid finger...");
}

void loop() // run over and over again
{
getFingerprintIDez();
delay(50); //don't ned to run this at full speed.

}

uint8_t getFingerprintID() {
uint8_t p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println("No finger detected");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
return p;
default:
Serial.println("Unknown error");
return p;
}

// OK success!

p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}

// OK converted!
p = finger.fingerFastSearch();
if (p == FINGERPRINT_OK) {
sweep();
Serial.println("Found a print match!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else {
Serial.println("Unknown error");
return p;
}

// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
uint8_t p = finger.getImage();
if (p != FINGERPRINT_OK) return -1;

p = finger.image2Tz();
if (p != FINGERPRINT_OK) return -1;

p = finger.fingerFastSearch();
if (p != FINGERPRINT_OK) return -1;

// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;

}

void sweep()
{
 for(int pos = 0; pos < 180; pos += 25)  // goes from 0 degrees to 180 degrees
 {                                  // in steps of 1 degree
   myservo.write(pos);              // tell servo to go to position in variable 'pos'
   delay(122);                       // waits 122ms for the servo to reach the position
 }

 for(int pos = 180; pos>=1; pos-=25)     // goes from 180 degrees to 0 degrees
 {
   myservo.write(pos);              // tell servo to go to position in variable 'pos'
   delay(122);                       // waits 122ms for the servo to reach the position
 }
}

please use the {} button to format your code

you said that you verified the operation of the fingerprint reader .....  did you also verify the operation of the servo? ..... what kind of a servo are you using?


text:
Powering 150 WS2812B LED strips
I just bought an Elegoo Uno R3 today and delved into programming Arduinos. For my first project I'd like to power a 5m LED strip (30 LED/m). I've learned that an individual neopixel needs around 60 mA, and i'm gonna assume this means that to power all 150, I need 9A. I'm extremely new to all this (and electrical stuff in general) and not exactly sure how to go on about giving 9A worth of power to the strips and the Arduino. Any help to get me on the right track would be appreciated.

Step one: buy a power supply that gives at least 9A. Step two: connect it.

The neopixel uberguide should give all info required to get started. https://www.google.com/url?sa=t&source=web&rct=j&url=https://cdn-learn.adafruit.com/downloads/pdf/adafruit-neopixel-uberguide.pdf&ved=2ahUKEwjQss2n6-bgAhUBIVAKHQtlAFUQFjAAegQIBBAB&usg=AOvVaw1-UNr6xUSFV5fscJPYqsFR

"Any help to get me on the right track would be appreciated." Is not really a question. Notable is that this only counts if you put R/G/B all on 100%, you're right, but you may settle for less

Your math looks right to me. You need a 9A power supply if you're going to drive all 150 LEDs at %100 brightness on all 3 channels.
I'd suggest using a separate 500mA 5V regulated power supply for the Arduino. Switching 9A of load on and off on the LED power supply is going to cause quite a bit of variation in the voltage on that 9A supply, and the simplest way to keep the power supply to the Arduino clean is to make the 2 power supplies completely different.

Connect the power supply in multiple places to the LED strip. The two ends and the middle at least. That will keep all the current from having to flow thru all of the strip.  If try to power it from just one end, the power traces in the strip might act as a fuse and blow open. Or it might survive, but act like a low-ohm resistor and the chips farther down the string will see less voltage (because voltage down the trace = current x resistance) and may appear dim, or act weirdly, or not turn on at all.

I would hope that an off-the-shelf LED strip is built with heavy-duty enough traces to handle it's maximum current load. If not is a pretty shoddy product, an would likely fail UL or CE test certification.

Do you see any UL or CE test certification marking on your strip?

Fair question, but even if they aren't UL/CE certified, they shouldn't melt if you turn everything on.

Yes, "shouldn't". But very hot is not melting, yet can still have lots of voltage loss down the length. Measure the voltage down the string if you see odd things.


text:
Help decrypting AES string from arduino rf module in python
Please excuse any glaring errors in my code, I'm new to both C and python.
I'm trying to send an encrypted message from my arduino uno via a DHT22 sensor and an rf module using the radiohead ask and AESlib libraries to a raspberry pi with a usb RTL-SDR using the rtl_433 library and a python script.
I think (but I could very well be wrong) I have the Arduino side working properly and it feels as though I'm pretty close on the python side, however I don't seem to be decrypting the message properly.
An example of the string before being encrypted might be:
"55.55,24.99,0001"
Here is the code on the Arduino side:
#include <AESLib.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "DHT.h"
#include <RH_ASK.h>
#include <Base64.h>

#define DHTPIN 2

#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
RH_ASK driver;

bool takeSensorReading = true;
float h;
float t;
String str_humid;
String str_temp;
String str_out;
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
char data[32];
char endChar[1] = "Ʊ";

void setup() {
  driver.init();
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(5000);

  int messagelength = sizeof(str_out);
  byte plain[messagelength];

  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();

  // Convert Humidity to string
  str_humid = String(h, 2);

  // Convert Temperature to string
  str_temp = String(t, 2);

  // Combine Humidity and Temperature
  str_out = str_humid + "," + str_temp + ",0001";

  str_out.toCharArray(data, 32);
  aes256_enc_single(key, data);

  /*aes256_dec_single(key, data);*/
  Serial.println(data);
  int encryptedStringLength = sizeof(data);

  int encodedLength = Base64.encodedLength(encryptedStringLength);
  char encodedString[encodedLength];
  Base64.encode(encodedString, data, encryptedStringLength);
  Serial.print("Encoded string is:\t");
  Serial.println(encodedString);

  driver.send(strcat( (uint8_t *)encodedString, endChar ), 33);
  driver.waitPacketSent();

  takeSensorReading = !takeSensorReading;
}

and here is the python code:
import subprocess
import json
import base64
from Crypto.Cipher import AES

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

def decrypt(enc):
    private_key = str(bytearray([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]))
    iv = enc[:16]
    cipher = AES.new(private_key, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(enc[16:]))

p = subprocess.Popen(['rtl_433', '-f', '433720000', '-F', 'json'],stdout=subprocess.PIPE,bufsize=1)
# rtl_433 -f 433720000 -F json
try:
    for line in iter(p.stdout.readline, ""):
        lineStripped = str(line).strip()
        try:
            jsondata = json.loads(lineStripped)
            time = jsondata["time"]
            payload = jsondata["payload"]
            if len(payload) == 33:
                payloadstring = ''
                for a in range(len(payload)):
                    payloadstring += chr(payload[a])
                payloadstring += "AAAAAAAAAA="
                print payloadstring
                encrypted = base64.b64decode(payloadstring)
                print encrypted
                decrypted = decrypt(encrypted)
                print decrypted
        except Exception as err:
            print "oh no, something went wrong"
            print("error: {0}".format(err))
except KeyboardInterrupt:
    p.kill()

p.wait()
p.stdout.close()
Here is an example of the erroneous output of the decrypt function:
"@g�އ�6S���25zD"
Any help you could give me in decoding the message from the Arduino in the python script would be really appreciated.
Thanks
Richard
*EDIT
I thought if it helps I could provide a bit more context around the transmission stages that the message goes through:
After the initial data string is constructed from the temperature and humidity sensor eg "55.55,24.99,0001" that 16 byte message is added to a 32 byte char array and encrypted using the aes128_enc_single method. The encrypted message is then base63 encoded The encrypted char array is then combined with an extra unencrypted character "Ʊ" (which I thought I could use to crudely validate the message) and sent via the radiohead ask send method:
driver.send(strcat( (uint8_t *)encodedString, endChar ), 33);
On the pyhton/reciever end I run a sub process rtl_433 -f 433720000 -F json
and listen for the output line by line. A example of the output of the rtl_433 command would look something like this:
{"time": "2019-03-05 00:00:00", "model": "RadioHead ASK", "len": 33, "to": 255, "from": 255, "id": 0, "flags": 0, "payload": [111, 110, 109, 57, 120, 86, 52, 79, 121, 78, 71, 52, 48, 122, 117, 88, 67, 52, 77, 118, 85, 81, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65], "mic": "CRC"}
rtl_433 converts the message into an array of ASCII or Unicode characters.
I have then tried to convert the characters in the recieved array back into standard characters:
payloadstring += chr(payload[a])
added padding to the message:
payloadstring += "AAAAAAAAAA="
then base64 decoded the result:
encrypted = base64.b64decode(payloadstring)
and then finally decrypt that:
decrypted = decrypt(encrypted)
Hopefully that info might be helpful in flagging up where I have gone wrong.

payloadstring += "AAAAAAAAAA=" that looks rather arbitrary

First error: int messagelength = sizeof(str_out); no that is not the length of the String. It is the number of bytes for a String instance. The correct way to retrieve the string length is to use the member function, int messagelength = str_out.length();https://www.arduino.cc/en/Tutorial/StringLength

By inspection only:
You are using an Initialization Vector and CBC mode in your Python code, but no IV and single block encryption in your Arduino code.
I think if you use MODE_ECB in your Python it will ignore the IV and match the Arduino code.
From a look at the AESLib github it appears your key should be exactly 16 bytes - yours is 32. I haven't looked at the code to see whether it will just ignore the rest, but the Python code definitely won't, so you should probably do what it says and use 16, and adjust your Python code to match.
Since the above wasn't enough to get it working, I would suggest divide-and-conquer: Use an online AES-128 encyrptor/decryptor such as aesencryption.net or encode-decode.com or infoencrypt.com to validate and cross-check your Arduino encryption and Python decryption functions. With a bit of luck you can at least fix them one-by-one, against a known-good reference.  Perhaps with a bit of fiddling you may be able to work out where it's going wrong.
I presume the humidity value may not change much, and I have a feeling that sending several messages with the same start can substantially weaken the encryption but I'm no crypto expert and perhaps it's still adequate for your purposes.

Hi Mark, Thanks very much for taking the time to help out. I've had a go at implementing your suggestions by changing the uint8_t key to have only 16 values and called aes128_enc_single instead of aes_256_enc_single. On the python side I removed the iv, reduced the private_key length to 16 and changed the AES mode to AES.MODE_ECB.
Unfortunatley I'm still not able to decrypt the message correctly.
I have edited my original post to include some context around the stages the message goes through in transit, I hope that helps shed some light into where I am going wrong.
Thanks again

Hey, thanks very much for the links ... encode-decode.com did throw up something interesting.
If I use the string HelloIamamessage and the secret abcdefghijklmnop and set up the corresponding values in the Arduino script uint8_t string_key[] = {97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112}; and String test_message = "HelloIamamessage";
I get the following output from the site:
k7yooB6Mj6bgxJ2ywaZj0rRDy5XLQ8VcZMRo2jfU2Ok=
and the following from the Arduino IDE:
k7yooB6Mj6bgxJ2ywaZj0gAAAAAAAAAAAAAAAAAAAAA=

The output starts the same but then diverges. Could this be a padding issue (or lack of it on the Arduino side) and if so would you have any idea how to solve this?

I might have worked out what's going wrong. Change your message to "HelloIamamessag" (i.e. 15 chars) and see if it matches.  If so, I'll edit the answer and explain why.

Hey Mark, thanks for taking another look. I changed the message to HelloIamamessag unfortunately I still can't get the encrypted string to match that on encode-decode.
Perhaps I have made a simple error. Here is a pastebin with my latest attempt (If this ever works I'll edit the question and post the working code there).
The Arduino IDE is returning:
0P3iW9FSrni+evrhrWaiMQ==
and encode-decode is returning:
bs3Uzmhox9ARIPliQRxawQ==
Both using the string HelloIamamessag


text:
SerializeJson not working when using softserial
IDE:1.8.8
Board:Arduino UNO
When I use the code below, I get result of print like this.
{ "result": [ { "ID": "01", "Value": [ "2", "1", "13" ] } ] }

But when I use SoftwareSerial and in the setup to being that the serializeJson result like this:
{}

I don't know what happens in the softserial with using json library, can someone tell me why?
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
int dir[3];
char  json[] ="{\"ID\":\"01\",\"Value\":[\"%d\",\"%d\",\"%d\"]}";
//SoftwareSerial Left(8,9);//左
/SoftwareSerial Right(6,7); //右
//SoftwareSerial Up(10,11);//上
//SoftwareSerial Down(14,15);//下
//SoftwareSerial Global(8,9);  //建立軟體串列埠腳位 (RX, TX)左
void setup() {

  Serial.begin(9600);        //設定硬體串列埠速率
 // Up.begin(9600);
 // Right.begin(9600);
  //Global.begin(9600);   //設定軟體串列埠速率
  }

void loop() {

 dir[0]=2;
 dir[1]=1;
 dir[2]=13;
  if(Serial.read()=='j')
{
 StaticJsonDocument<256> docc;
  char b[35];
  sprintf(b, json, dir[0], dir[1],dir[2]);
  deserializeJson(docc, b);
  JsonObject object = docc.as<JsonObject>();

  DynamicJsonDocument doc(1024);
 JsonArray result = doc.createNestedArray("result");
  result.add(object);
  result.add(object);
  serializeJsonPretty(doc,Serial);
   }
  }

These are error code
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
int dir[3];
char  json[] ="{\"ID\":\"01\",\"Value\":[\"%d\",\"%d\",\"%d\"]}";
//SoftwareSerial Left(8,9);//左
SoftwareSerial Right(6,7); //右
SoftwareSerial Up(10,11);//上
//SoftwareSerial Down(14,15);//下
SoftwareSerial Global(8,9);  //建立軟體串列埠腳位 (RX, TX)左
void setup() {

  Serial.begin(9600);        //設定硬體串列埠速率
  Up.begin(9600);
  Right.begin(9600);
  Global.begin(9600);   //設定軟體串列埠速率
  }
void loop() {
     Global.listen();
      while (!Serial.available()) {}  //等到PC傳送字元才到下一步
     Global.write(2);  //傳送給左邊的板子子id
      while (!Global.available()) {}  //等到左方板傳送字元才到下一步
        dir[0]=Global.read();
        Serial.println( dir[0]);  //左方板向PC傳送字串

       Up.listen();
      while (Serial.read()!='Y') {}  //等到PC傳送字元才到下一步
      Up.write(3);  //傳送給左邊的板子子id
      while (!Up.available()) {}  //等到左方板傳送字元才到下一步
      dir[1]=Up.read();
        Serial.println(dir[1]);  //左方板向PC傳送字串
       // }

     Right.listen();
     while (Serial.read()!='Y') {}  //等到PC傳送字元才到下一步
      Right.write(4);  //傳送給左邊的板子子id
      while (!Right.available()) {}  //等到左方板傳送字元才到下一步
       dir[2]=Right.read();
        Serial.println(dir[2]);  //左方板向PC傳送字串
 if(Serial.read()=='j')
{
 StaticJsonDocument<256> docc;
  char b[35];
  sprintf(b, json, dir[0], dir[1],dir[2]);
  deserializeJson(docc, b);
  JsonObject object = docc.as<JsonObject>();

  DynamicJsonDocument doc(1024);
 JsonArray result = doc.createNestedArray("result");
  result.add(object);
  result.add(object);
  serializeJsonPretty(doc,Serial);
   }
}

the code you posted doesn't even use SoftwareSerial

Sorry, i edited.

Your code still isn't even trying to output json to any software serial

And what does "These are error code" mean. There are no errors in the question

Sorry, i didn't make myself clear, the error code is just mean test in software serial begin case return this '{}' result, then when comment out //Right.begin(9600); that can give me fine json print, i don't know what happen between these two library.

yes, but there is still no code that uses SoftwareSerial to ouput JSON

Oh, i tried to change
StaticJsonDocument<256> docc; -> StaticJsonDocument<50> docc;
then result is good, i think this is a memory problem?

yes, but there is still no code that uses SoftwareSerial to ouput JSON

OK, i  show my complete code to use SoftwareSerial , i just use that to collect number to join json string.


text:
How can I fix my HRLV-MaxSonar-EZ ultrasonic sensor so it does not give gibberish feedback?
I have hooked up my ultrasonic sensor to my Arduino correctly, I know this because I am getting feedback from it, but when I run this code:
int mode = 2;
double distance;
double calibration;
void setup()
{
  Serial.begin(9600);
  pinMode(12, INPUT);
}
void loop()
{
  if(mode == 1)
  {
  //Read duration in microSeconds
  long duration = pulseIn(12, HIGH);
  //58 uS per cm for MB1240 XL-MaxSonar
  //Operation Range: 20 cm min (50 cm for accurate)
  distance = duration / 58.0;
  calibration = -20;
  }
  else if (mode == 2)
  {
  //Analog In .49 mV per unit
  double voltage = analogRead(5)*.0049;
 //.49 mV per cm;
  distance = voltage/.0049;
  calibration = 0.0;
  }
  double cmToInch = 0.393701;
  //Analog Seems to be More Accurate due to PWM timing
  Serial.print((distance+calibration)*cmToInch);
  Serial.println(" in");
  delay(100);
}
I get sporadic results when it is just sitting there without anything moving in front of, let alone around it at all:

What is wrong here? Is it my code, is the sensor just very sensitive, or is it something else?
Thanks in advance.

so, what is at 148 or so inches from the sensor?

That's exactly it, nothing is.

so absolutely nothing for 12 feet, not even a wall?

Nope, and it changes without anything around it moving; it was in the middle of an empty room. Also, it doesn't change much when I move my hand in front of it.

voltage = analogRead(5)*.0049; distance = voltage/.0049 is just a long winded way of doing distance = analogRead(5) - I think your logic is messed up


text:
Sketch for 5 randomly fading leds not working as expected; what could be wrong?
I'm working on a project with a starry sky, based on fiberoptics and 5 leds.
The code should work this way:
Start on average brightness, then go up or down according to a set of randomly chosen preset values. (min, max, wait time etc) and switch direction after the wait period on either its min/max is completed. When it reaches the average again, a new set of preset values should be assigned.
The updating of the leds should be done every set interval, so the change speed can be adjusted.
The leds go on, but nothing seems to change after that. Have I done something wrong? No errors given in the Arduino IDE.
(it's my first coding project, there will probably be some beginner mistakes or workarounds)

// Declare pins
int LED01           = 3;
int LED02           = 5;
int LED03           = 6;
int LED04           = 9;
int LED05           = 11;

// Time variables
unsigned long currentTime;
unsigned long waitingTime[5];
unsigned long lastRound;

// LED Variables
int brightMin [5]   =       { 0,    0,    0,    0,      0     };    // Minimum brightness
int brightAvg [5]   =       { 200,  230,  210,  210,    235   };    // Average brightness
int brightMax[5]    =       { 0,    0,    0,    0,      0     };    // Maximum brightness
int timeWaitLow[5]  =       { 0,    0,    0,    0,      0     };    // Waiting time
int timeWaitAvg[5]  =       { 0,    0,    0,    0,      0     };    // Waiting time
int timeWaitMax[5]  =       { 0,    0,    0,    0,      0     };    // Waiting time
int increment[5]    =       { 0,    0,    0,    0,      0     };    // Increment in brightness
int currentBright[5]=       { 200,  230,  210,  210,    235   };    // Current brightness

// LED Variables Possibilities
int brightMinPos[5] =       { 0,   20,    40,   0,      20    };    // Minimum brightness possibilities
int brightMaxPos[5] =       { 240,  250,  230,  225,    250   };    // Maximum brightness possibilities
int timeLowPos[5]   =       { 3000, 5000, 4000, 40000,  20000 };    // Waiting time on low brightness possibilities
int timeHighPos[5]  =       { 3000, 1000, 500,  2000,   4000  };    // Waiting time on high brightness possibilities
int timeAvgPos[5]   =       { 3000, 5000, 4000, 40000,  20000 };    // Waiting time on average brightness possibilities
int incrementPos[5] =       { 10,    20,    30,    40,      20     };    // increment in brightness possibilities

// Variables
bool needsUpdate[5]  =       { true, true, true, true,   true    };  // Does the led need a settings update?
bool reachedAvg[5]   =       { true, true, true, true,   true    };  // Has it reached the middle brightness?
bool reachedLow[5]   =       { false, false, false, false,  false};  // Has it reached the Lowest brightness?
bool reachedMax[5]   =       { false, false, false, false,  false};  // Has it reached the Highest brightness?
bool waitingAvg[5]   =       { false, false, false, false,  false};  // Is it waiting at the middle brightness?
bool waitingLow[5]   =       { false, false, false, false,  false};  // Is it waiting at the lowest brightness?
bool waitingMax[5]   =       { false, false, false, false,  false};  // Is it waiting at the Highest brightness?

// Directional variables
bool directionLED[5];

// Random variables
long randomNumber;                                                  //  Long to store random number

// counters
int i=0;

void setup() {
  Serial.begin (9600);                                              //  Start serial
  randomSeed(analogRead(A0));                                       //  Set randomseed
  lastRound = millis();

// Declare outputs
  pinMode (LED01, OUTPUT);
  pinMode (LED02, OUTPUT);
  pinMode (LED03, OUTPUT);
  pinMode (LED04, OUTPUT);
  pinMode (LED05, OUTPUT);
}

// Check if it should stop at bottom, middle or top
void checkStopPoint(){
  for (i=0;i<5;i++){
    if (currentBright[i] <= brightMin[i] && reachedLow == false) {                         // is it at the lowest brightness?
      reachedLow[i] = true;
      waitingTime[i] = millis();
    }else if (currentBright[i] == brightAvg[i] && reachedAvg == false) {                   // is it at the average brightness?
      reachedAvg[i] = true;
      waitingTime[i] = millis();
    }else if (currentBright[i] >= brightMax[i] && reachedMax == false) {                   // is it at the highest brightness?
      reachedMax[i] = true;
      waitingTime[i] = millis();
    }
  }
  i=0;
}

void checkResetPoint(){
  for (i=0;i<5;i++){
    if (reachedLow[i] == true && currentTime-waitingTime[i] >= timeWaitLow){
      reachedLow[i] = false;
      directionLED[i] = true;
    }else if( reachedMax[i] == true && currentTime-waitingTime[i] >= timeWaitMax){
      reachedMax[i] = false;
      directionLED[i] = false;
    }else if ( reachedAvg[i] == true && currentTime-waitingTime[i] >= timeWaitAvg){
      reachedAvg[i] = false;
      needsUpdate[i] = true;
    }
  }
  i=0;
}

// update LED variables
void updateLEDVariables(){
  for (i=0; i>=5; i++){
    if (needsUpdate[i] == true){
      randomNumber      = random(5);
      brightMin[i]      = brightMinPos[randomNumber];                   // Set random value for minimum brightness
      randomNumber      = random(5);
      brightMax[i]      = brightMaxPos[randomNumber];                   // Set random value for maximum brightness
      randomNumber      = random(5);
      timeWaitLow[i]    = timeLowPos[randomNumber];                     // Set random value for low waiting time
      randomNumber      = random(5);
      timeWaitMax[i]    = timeHighPos[randomNumber];                    // Set random value for high waiting time
      randomNumber      = random(5);
      timeWaitAvg[i]    = timeAvgPos[randomNumber];                     // Set random value for average waiting time
      randomNumber      = random(5);
      increment[i]      = incrementPos[randomNumber];                   // Set random value for increment value
      randomNumber      = random(2);
      if (randomNumber == 1){
        directionLED[i] = true;
      }else{
        directionLED[i] = false;
      }
      needsUpdate[i]    = false;
      reachedAvg[i]     = false;
    }
  }
  i=0;
}

void writeToLED(){
  analogWrite(LED01, currentBright[0]);
  analogWrite(LED02, currentBright[1]);
  analogWrite(LED03, currentBright[2]);
  analogWrite(LED04, currentBright[3]);
  analogWrite(LED05, currentBright[4]);
}

void loop() {
  currentTime = millis();
  updateLEDVariables();
  checkStopPoint();
  checkResetPoint();

  if (currentTime - lastRound >= 1){

    for (i=0;i<5;i++){
      if (directionLED[i] == true && !reachedLow && !reachedAvg[i] && !reachedMax[i] && !needsUpdate[i]){
        currentBright[i] = currentBright[i]+increment[i];                         // Go 1 value up
      }else if (directionLED[i] == false && !reachedLow[i] && !reachedAvg[i] && !reachedMax[i] && !needsUpdate[i]){
        currentBright[i] = currentBright[i]-increment[i];                         // Go 1 value down
      }
    }
  i=0;
  writeToLED();
  lastRound = millis();
  }
}

Add print statements in  your code, to know where the program is, and what values certain variables are. (you can increase times to easier see what is happening).

to make it easier, start with ONE LED - since you'll be outputting debug statements very quickly

You have three of these: "currentTime-waitingTime[i] >= timeWaitLow", but "timeWaitLow" and the others are an array. You use "!reachedLow", but again, that is an array. After fixing those, the problem remains. In the settings, enable more compiler output and set the level of compiler warnings higher. Compile the sketch, and scroll up to see a few problems. Which arduino board do you use? A value of 40000 does not fit in a integer for an arduino uno. I would update the leds between 20 and 50Hz (a fixed value), and the rest is math. Can you show a schematic or tell how the leds are connected?

upvote for properly formatted code

tip: if( reachedMax[i] == true) is the same as if( true == true) .................. so all you need is if( reachedMax[i]) ..... the converse is if( !reachedMax[i])


text:
How to use the ESP32 WROOM GPIOS above #18 with arudino ide?
I am using the Arduino IDE version 1.8.8 I am trying to control an ESP32-wroom. The gpios for pins 16 and 17 are working. I have some relays on GPIO's 18 and 19 that I'd also like to be able to control. I also have no control over GPIO's that are over 17 I've tried 18 through 27 and I can't toggle them.
#define relayPin3 18
#define relayPin4 19

int relayflag = 0;
void loop() {
  delay(1000);
  if (relayflag == 0){
    digitalWrite(relayPin3, LOW);
    digitalWrite(relayPin4, HIGH);
    relayflag =1;
  }
  else
  {
    digitalWrite(relayPin3, HIGH);
    digitalWrite(relayPin4, LOW);
    relayflag = 0;
  }

}

I noticed that GPIO's 18 and 19 are also shared with spi ports.
Does the digitalWrite command work for any GPIO or is it in use by another library? Is there some other command to get access to the GPIO's I need to use? Some library I need to modify.

Found the answer, albeit a simple one. This is my first go around with arudino so it will look ridiculous to those who program microprocessors (including myself)
You need to declare the pin to be an output before use. The inconsistent thing is, this only happens sometimes. For some of the pins you don't need to use pinMode for them to work.
  pinMode(relayPin1, OUTPUT);

We all have to start somewhere in learning new things. Well done posting your solution.

If you don’t set a pin’s mode, the results are undefined. It might already be in the mode you want, and might not.


text:
Problem: char string not working with SoftwareSerial.h
I am creating a program to display text on an OLED display and then have it sent to a thermal printer.
The issue is my second char string: word_buffer
When I try to use word_buffer for any reason it crashes the program and nothing will work (the OLED display will not refresh upon uploading the sketch and typing on the keyboard will not update the display).
The program works fine when you omit the code needed for the thermal printer (Adafruit_Thermal.h, SoftwareSerial.h, and other setup).
The sample code is below, I've commented out the section where I try and utilize word_buffer.
If I remove the thermal printer setup code and uncomment that section, the program will run just fine.
Let me know what you think, I've been stuck on this for a while now :/
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <Adafruit_Thermal.h>
#include <PS2Keyboard.h>
#include <MemoryFree.h>

#include <SPI.h>
#include <Wire.h>

#define LED_PIN 13

// OLED display
#define OLED_MOSI  A4
#define OLED_CLK   A3
#define OLED_DC    A2
#define OLED_CS    A0
#define OLED_RESET A1
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// printer
#include "SoftwareSerial.h"
#define GND_PIN 7
Adafruit_Thermal printer(&Serial, 4);

// keyboard
const int DataPin = 8;
const int IRQpin =  3;
PS2Keyboard keyboard;

#define HIDDEN_BUF 21
#define VIS_BUF 168
#define WRD_BUF 32

char line_buffer[HIDDEN_BUF + VIS_BUF + 1];
int line_start = HIDDEN_BUF;
int line_len = 0;
int word_len = 0;
char word_buffer[WRD_BUF + 1];

void setup() {
  keyboard.begin(DataPin, IRQpin);

  pinMode(GND_PIN, OUTPUT);
  digitalWrite(GND_PIN, LOW);

  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  for (int i = 0; i < HIDDEN_BUF + VIS_BUF; i++)
    line_buffer[i] = ' ';

  line_buffer[HIDDEN_BUF + VIS_BUF] = 0;

  for (int i = 0; i < WRD_BUF; i++)
    word_buffer[i] = ' ';

  word_buffer[WRD_BUF] = 0;

  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.println(line_buffer + HIDDEN_BUF);
  display.display();

  Serial.begin(9600);
  printer.begin();
}

void loop() {

  if (!keyboard.available()) return;

  char c = keyboard.read();

  boolean newline = false;

 if (c == PS2_DELETE) {
    if (line_len > 0) {
      line_len--;
      line_buffer[line_start + line_len] = ' ';
      if (word_len > 0)
      word_len--;
    }
  }

//  if (word_len > 0)
//  line_buffer[188] = word_buffer[1];

  if (c >= 33 && c <= 126) {
    word_len++;
    line_buffer[line_start + line_len] = c;
    word_buffer[word_len] = c;
    line_len++;
     }

  if (c == 32) {
    line_buffer[line_start + line_len] = c;
    line_len++;
    for (int i = 0; i <= 32; i++)
      word_buffer[i] = ' ';
    word_len = 0;
  }

  display.clearDisplay();
  display.setCursor(0, 0);
  display.println(line_buffer + HIDDEN_BUF);
  display.display();
}

char word_buffer[WRD_BUF + 1] = {' '}; will init the array with spaces

Thanks Juraj, that makes sense and would save some code but I'm still not sure how to get the code to run with word_buffer

My guess is you are running out of memory and can't allocate the oled display buffer.

Thanks @Majenko do you have any suggestions? Note that using multiple char arrays works fine without the thermal printer code, so I'm not sure why that affects it so much?


text:
Using two leds with one push button
How can I make the code of this project where I will press one time a button,  to turn on the first led (and turn off second led) and when other one press to turn on second led (and turn off the first led).

Your question is barely answerable and shows no effort of trying it yourself. You could try starting out with Arduino Tutorials instead of a project directly.

This is a poor quality lazy question. You need to exert some effort.

From the question it appears that person's first language is not english, it looks like it was possible processed through some translator.

You can do this by keeping the 'state' saved in a variable.
Depending on it's state, the button will have a different effect.
After this effect, the state is updated, so that next iteration it will behave according to the other state.
state = led1
if(buttonpressed){
   if(state == led2){
     led1On();
     led2Off();
     state = led1;
   }else{
     led1Off();
     led2On();
     state = led2;
   }
}

Also check the Arduino example about debouncing buttons.

You do the OP a disservice by giving them functioning code. This allows "copy/paste programming" without learning.

This code isn't completely functional and only to illustrate how using state works. I somewhat agree that I could have used a different example as the case for which this person was asking.


text:
Can I program an ATtiny87 with Arduino
I have a project, and I want to use an ATtiny167(ATtiny87), I know that an Arduino can progam ATtiny84 (84/44/24), ATtiny85 (85/45/25), and ATtiny2313 (4313). but I don't know if it can program an ATtiny87?
thank you for your help.

There is a json for ATtiny 167 at https://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips
So add that json to your preferenses.

Having same issue. Installed https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json already. Trying to program the Roshamglo with virtual USB 1.1 via Micronucleus but even when the device is in and in Bootloader mode, I can not see it with lsusb or in micronucleus. Any suggestions?


text:
How to fix this error?
Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"
libraries\TimerOne\TimerOne.cpp.o (symbol from plugin): In function `TimerOne::isrDefaultUnused()':

(.text+0x0): multiple definition of `__vector_13'

libraries\Timer1Fast\Timer1Fast.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

Multiple libraries were found for "Timer1Fast.h"
 Used: D:\apps\Arduino\libraries\Timer1Fast
 Not used: C:\Users\biril\Documents\Arduino\libraries\pwmTest
Multiple libraries were found for "TimerOne.h"
 Used: D:\apps\Arduino\libraries\TimerOne
 Not used: C:\Users\biril\Documents\Arduino\libraries\TimerOne-master
Multiple libraries were found for "LiquidCrystal_I2C.h"
 Used: C:\Users\biril\Documents\Arduino\libraries\LiquidCrystal_I2C
 Not used: C:\Users\biril\Documents\Arduino\libraries\NewliquidCrystal
 Not used: C:\Users\biril\Documents\Arduino\libraries\Arduino-LiquidCrystal-I2C-library-master
 Not used: D:\apps\Arduino\libraries\LiquidCrystal
Multiple libraries were found for "Wire.h"
 Used: D:\apps\Arduino\hardware\arduino\avr\libraries\Wire
 Not used: D:\apps\Arduino\libraries\Wire
exit status 1
Error compiling for board Arduino Nano.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

What code causes this error? I think you have two libraries that both use the hardware "timer1".

Don't use both the TimerOne and Timer1Fast libraries together. Why you would want to, though, is anyone's guess...

thanks, i'll rearrange my libraries again.