text:
Servo Speed Changer with Buttons
ok so yesterday i was in trouble with the buttons, with help from you i got over it and everything worked fine with the 1st speed of the servo, then i added the other 2 speeds and it looks like it all messed up... the buttons don`t respond as they should and the servo moves very weirdly.
Here is the code:
const int button1Pin = 2;
const int button2Pin = 3;
const int ledPin1 = 13;
const int ledPin2 = 12;
const int ledPin3 = 11;
#include <Servo.h>
Servo servo1;

int x = 0;
int button1State = 0;
int lastButton1State = 0;
int button2State = 0;
int lastButton2State = 0;

void setup() {
  servo1.attach(9);
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    int position;
    button1State = digitalRead(button1Pin);
    button2State = digitalRead(button2Pin);

      if (button1State != lastButton1State)
     {
        if (button1State == HIGH)
          {
            x++;
            Serial.println("on1");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off1");
          }
     }

    if (button2State != lastButton2State)
      {
        if (button2State == HIGH)
          {
            x--;
            Serial.println("on2");
            Serial.print("number of button Pushes:  ");
            Serial.println(x);
          }
        else
          {
            Serial.println("off2");
          }
       }
          delay(1000);

lastButton1State = button1State;
lastButton2State = button2State;

  if(x == 1)
    {
      digitalWrite(ledPin1, HIGH);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position < 360; position += 2)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else if (x == 2)
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);
        for(position = 0; position <360; position += 5)
          {
            servo1.write(position);
            delay(20);
          }
    }
   else
    {
      digitalWrite(ledPin1, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, HIGH);
        for(position = 0; position < 360; position += 10)
          {
            servo1.write(position);
            delay(20);
          }
    }
}

There may be better ways to mitigate button bounce. Check this link for a discussion on button bounce and example code to work around this problem. In your code, it appears you can not press your buttons faster than once a second.
Determine if the servos you are using are capable of the range you are demanding.  Some servos only travel from 0 degrees to 180 degrees.  Your code is asking the servo to travel from 0 degrees to 360 degrees.  Also, it is unlikely that any normal servo can travel this far.  Most servos use a potentiometer as a feed back sensor.  And most potentiometers can only be turned to something less than 1 full revolution.
It is likely you have not given the servos enough time to move to the zero degree position at the start of each of your 3 loops.  Understand that normal servos can not make complete revolutions.  They need to stay within their designed limit of rotation.  If you want to start over at 0 degrees you need to allow the servos time to rotate back in reverse to the 0 degree position.
Consider your last loop.  You are asking the servo to move from 0 degrees to 360 degrees in 10 degree steps.  You are allowing 20ms per step.  That means the servo will be demanded to move almost a complete revolution in (((360 / 10) * 0.020 = 0.72 seconds) less than a second.  Some but not all servos can move that fast.

so i should add more delay? another way to button bounce i don`t really know... can you tell me more?

If the code restricts you pressing the button no faster than once a second and you are fine with that, you can leave that part for later.  (Unless there is another problem with that bit of the code.) However you need to tell the servos to go to zero degrees & give the servos some time to do this before each of the 3 loops.  Finally, you need to determine how fast the servo can actually respond.  I might try increasing the 20ms delay for all loops equally until I noticed a speed difference for the 2 fastest loops.

that is actually a good idea, i just got home and i`m gonna try this out and tell you how it worked out

ok so trying this out still not a solution, i tried removing the servo part of the code and it looks just fine, the buttons work perfectly and the leds light up corespondingly. I think that the problem stands in making the servo rotate endesly. At the start x = 0 so nothing happens, i press the button once so it adds 1 to x, x = 1. After the x = 1 the code enters a loop from which it cant get out, it must move the servo continously so it doesnt allow any other functions to work out, like the buttons. Just an idea i don`t know if this is true.

The stack exchange format is not well suited for code debugging.  Unless there is a specific question about the code, it is difficult to adhere to the 1 specific question and 1 concise answer format.  That said, there may be problems with you code.  For instance, I would be annoyed that nothing happens after pressing a button for at least a second.  Second, you never control your "x" counter. It could get very large or it could also go negative.  And who knows what may happen if you told the servo library method to set the servo to a negative angle. Did you at least try to add the new delays?

i know it's not the best for that but it's my only solution. I don't know any other forum where i could find people that could help and i don't know irl people with programming experience. I'm willing to help and work a lot but i sometimes need some help :) I did everything that you said, adding the delays, lowering the servos speed and giving them time to go to 0 degrees. Although i think it would be pointless to tell the servo to go everytime to 0 when i actually want it to make it spin continously how it does for a fan for example. Thanks for taking your time and helping me man!

and for the X counter, this would be permanently controled by a human so i didn't want to make the code more complicate by adding some limits to x

Ah, I think I see the problem.  A normal servo can not rotate more than once!  There is a POT or potentiometer inside the servo and, as the volume control in an old amplifier, can only be rotated about 300 (maybe 330) degrees.  There is something called a Continuous Servo.  Instead of position, you control the forward and reverse speed.  That is to say, you will know how fast a Continuous Servo is rotating but you will not know its position at any given moment. For your code to work, you need to start thinking about moving your servo like the wipers move on your car's windscreen or windshield.

You should also be aware that some servos will not rotate more than 180 degrees.  If you have such servos they may act unexpectedly if asked to go beyond their physical limits.

Ah, I understand. I think i need to go get a Continuous Servo as you said. I hope i find one soon and buy it. When i do so i will redo the code and update you on the situation. And yes i think my servos go only to 180, i just tried a simple code to make it to 270 and it didn't work that far. Thank you very much for talking your time and helping me kind sir! Have a great day and I`ll update you if it works with the other Servo. (also sorry for my bad English, not my 1st language)

Just to be clear, normal servos are used to position things.  Like steering a robot.  Continuous servos are used to propel things.  Like pushing a robot.

yeah yeah I got the idea, this servo came in the box with the arduino as a starter pack. I thought I couldn't control a normal motor so I chose this one instead. Never thought i couldn't actually fully rotate it at different speeds and could only do it until a certain point. Thanks for clearing that out for me! :D


text:
arduino ethernet run php from sd card
I am just interested, but I would like to run a webpage with php on my arduino ethernet. I would like to be able to store my webpage on the sd card as well.
does anyone know of a library that would let me do this?

Please clarify, are you expecting to run PHP code from the Arduino too? Because that won't work.

I want to be able to have a php document on the sd card, and the arduino to run it.

Loading a file off an sdcard and displaying it on port 80 isn't hard. Just check out the 'Ethernet' library and the 'SD' library.
I don't want to discourage you too much about the PHP part, but you won't be able to load the official PHP interpreter onto the Arduino. Simply not enough memory available.
However, if you just want to have dynamic website such as display variables or output from sensors, then you could write your own code interpreter for dynamic web pages that would fit in the memory of an Arduino, just think a bit smaller in scope as far as what it can handle. Maybe you'll end up writing a new library for dynamic webpages for Arduino sensor data.
If you really need to run a PHP interpreter then you can try something like a Rapsberry Pi and hook it up to the Arduino for sensor input using the I2C protocol.

Thats not possible, only if you write yourself a PHP interpreter, which I suspect won't fit inside an Arduino.
You might be able to create your own interpreter for simple Get and POST requests, but bear in mind that HTTP, and even TCP are very sophisticated protocols to run on an AVR. You might want stick with simple things, preferentially with small messages as you also have very little RAM on those MCUs.

source: Stack Exchange

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

sort: votes


text:
Limiting motors to a specific position using while and if loops
I am currently building a prosthetic hand using an Arduino MEGA, an Advancer Tech Myoware sensor, and 3 TB6612FNG Dual H-bridge breakouts. I have the EMG sensor sending an analog value to the Arduino and want to use that value to open or close the hand.
The problem I have is that the motors cannot turn more than 1 second without tightening too much and breaking the hand, so I want to place a limit on the while loop telling them to move that will restrict their movement under the specified conditions to one second. Also, when the analog voltage is no longer present, I need the motors to reverse their movement so the hand releases.
Here is the code I have where move(motor #, speed, direction) is the function to move the hand (1 = forward, 2 = backward).
void loop(){

  int EMGv = analogRead(EMG);

  while(EMGv >= 900){
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left

  }

To reiterate. I need the motors to move while the EMG value is over 900, BUT not move more than 1 second, even if the value is 900 for 5 seconds. I then need the motors to move one second backwards when the value dips below 900.
Thanks!

You can use millis() feature
unsigned long starttime;

void loop(){

  int EMGv = analogRead(EMG);
  starttime=millis();
  while(EMGv >= 900){
    if (millis()-starttime < 1000) //limit on 1000ms
    {
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left
    } else {/*turn off motor here*/}
  }

Thank you! Can you explain what the millis funtion does?

Also is there a way to reverse this movement as soon as the value dipps below 900

Sorry for the questions. One more thing. This code only allows the motors to turn once. How do I reset the function after the value dips below 900 so it can be activated again when the value rises for a second time?

For short, millis is the time on your Arduino since it start. More information can be found on https://www.arduino.cc/en/Reference/Millis. As for reversing the movement, you can do some trial with the algorithm by yourself. The function will reset if the EMG value drops under 900, so it will break the while-loops

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


text:
2 digit number to 2x 1 digit
Suppose I have a number with 2 digits, 42.
It is an integer, received from my RTC
Now for my 7 segment displays, I will need 2 separate numbers:

4 on display 1.
2 on display 2.

How do I slice this number in 2?

What is the type of the number? Is it currently stored as a string (e.g. char* or String) or is it an integer (e.g. int or byte or char)?

The OP mentions it is an integer.

Numbers retrieved from an rtc are usually returned as a char or integer.
On this basis, you want
ones_column = bytefromrtc % 10;
tens_column = (bytefromrtc / 10) % 10;
hundreds_column = (bytefromrtc / 100) % 10;

the % operator returns the modulus - if you divide 42 by 10, the answer is 4, with a remainder of 2. % returns the remainder, in this example, 2.
To do the tens column, first get rid of the last digit by dividing by 10, then do the modulus as above. Since bytefromrtc is not a float, if you divide it, you lose the remainder - 42 / 10 = 4, not 4.2.
If the output is a word, or integer, or long integer, the method is exactly the same, except for the number of digits you can get out.

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


text:
Coding issue with Fast LED Multiple Colour Palettes in a State Machine
I am working on a project using the WSB2812B LED strip, with a ATmega644A using the MCUdude/MightyCore plug in (https://github.com/MCUdude/MightyCore).
I am using Fastled 3.3.3 with Ardunio 1.8.13 on Windows 10 and is using code based on "ColourWavesWithPalettes" (https://gist.github.com/kriegsman/8281905786e8b2632aeb).
This project as 2 button inputs  Solid & Palette and 2 outputs, LED DI & Mosfet gate. With the sequence being the following:

Power on and start running a set of colour palettes with fade (STANDARD_COLOUR_PALETTE). This could be anything from 5-15 colours, with transitioning colours from red to green to blue to purple to yellow... etc.

If Palette button is pressed, then change state to run 1 colour palette with fade (SINGLE_COLOUR_PALETTE) on repeat. E.G just purple with fade.

While in SINGLE_COLOUR_PALETTE state, if Palette button is pressed then change colour to another 1 colour palette e.g blue but still in the SINGLE_COLOUR_PALETTE state.

If in either "STANDARD_COLOUR_PALETTE" or "SINGLE_COLOUR_PALETTE" state and Solid button is pressed, then change state to run 1 solid colour (SOLID_COLOUR) e.g just blue with no fade.

While in "STANDARD_COLOUR_PALETTE" if Solid button is pressed, then change to another solid colour e.g Red with no fade.

While in "STANDARD_COLOUR_PALETTE" if Palette button is pressed then change state to colour palettes with fade (STANDARD_COLOUR_PALETTE).

In summary, the code is made up of 3 states with for loops and if statements. I have most of this sequence working but I am struggling a lot with step 2 & 3, as there is only 1 colour palette "Playlist" that I am trying to use as STANDARD_COLOUR_PALETTE but also trying to pull indivduial colour palettes from (SINGLE_COLOUR_PALETT).
One solution I thought of was to generate multiple separate a colour playlists one with the 5-15 colours that would fade to one another and many more that would just have the single colour palette.
How to code that into the exiting "ColourWavesWithPalettes" I used as a base?

#include "FastLED.h"
#if FASTLED_VERSION < 3001000
#error "Requires FastLED 3.1 or later; check github for latest code."
#endif

#define DATA_PIN    16
#define LED_TYPE    WS2812B
#define COLOR_ORDER GRB
#define NUM_LEDS    276
#define BRIGHTNESS  250
#define SECONDS_PER_PALETTE 10 // ten seconds per color palette makes a good demo but 20-120 is better for deployment
CRGB leds[NUM_LEDS];

enum State{STANDARD_COLOUR_PALETTE, SINGLE_COLOUR_PALETTE, SOLID_COLOUR};
uint8_t State = STANDARD_COLOUR_PALETTE;
int SOLID_COLOUR_POSITION;
int SOLID_COLOUR_COUNT;
int SINGLE_COLOUR_PALETTE_COUNT;

// ten seconds per color palette makes a good demo
// 20-120 is better for deployment
#define SECONDS_PER_PALETTE 10

void setup() {
  delay(1000); // 1 second delay for recovery
  pinMode(14, INPUT); // pin #14 Solid
  pinMode(13, INPUT); // pin #13 Palette Colour
  pinMode(17, OUTPUT); // Pin #17 MOSFET gate
  digitalWrite(17,HIGH);

  // tell FastLED about the LED strip configuration
  FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
    //.setCorrection(TypicalLEDStrip) // cpt-city palettes have different color balance //TEST THIS!!!!!!
    .setDither(BRIGHTNESS < 255);

  // set master brightness control
  FastLED.setBrightness(BRIGHTNESS);
}

// Forward declarations of an array of cpt-city gradient palettes, and
// a count of how many there are.  The actual color palette definitions
// are at the bottom of this file.
extern const TProgmemRGBGradientPalettePtr gGradientPalettes[];
extern const uint8_t gGradientPaletteCount;

// Current palette number from the 'playlist' of color palettes
uint8_t gCurrentPaletteNumber = 0;

CRGBPalette16 gCurrentPalette( CRGB::Black);
CRGBPalette16 gTargetPalette( gGradientPalettes[0] );
CRGBPalette16 gTargetPalette1( gGradientPalettes[0] );

void loop()
{

  switch (State)
  {
    case STANDARD_COLOUR_PALETTE:
        EVERY_N_SECONDS( SECONDS_PER_PALETTE ) {
        gCurrentPaletteNumber = addmod8( gCurrentPaletteNumber, 1, gGradientPaletteCount);
        gTargetPalette = gGradientPalettes[ gCurrentPaletteNumber ];
        }

        EVERY_N_MILLISECONDS(40) {
        nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 16);
        }

        colorwaves( leds, NUM_LEDS, gCurrentPalette);

        FastLED.show();
        FastLED.delay(20);

        if (digitalRead(13)==HIGH) // Colour palette pressed
        {
          delay(400);
          State = SINGLE_COLOUR_PALETTE; // Change state to single colour palettes

        }

        if (digitalRead(14)==HIGH) // Solid colour button pressed
        {
          delay(400);
          State = SOLID_COLOUR; // Change state to solid colours
          SINGLE_COLOUR_PALETTE_COUNT =++SINGLE_COLOUR_PALETTE_COUNT;
        }
    break; //End STANDARD_COLOUR_PALETTE

    case SINGLE_COLOUR_PALETTE:
//        if (SINGLE_COLOUR_PALETTE_COUNT==1)
//        {
//        EVERY_N_SECONDS( SECONDS_PER_PALETTE ) {
//        gCurrentPaletteNumber = addmod8( gCurrentPaletteNumber, 1, gGradientPaletteCount);
//        gTargetPalette1 = gGradientPalettes[ gCurrentPaletteNumber ];
//        }
//
//        EVERY_N_MILLISECONDS(40) {
//        nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette1, 16);
//        }
//
//        colorwaves( leds, NUM_LEDS, gCurrentPalette);
//
//        FastLED.show();
//        FastLED.delay(20);
//        }

        if (digitalRead(14)==HIGH) // Solid colour button pressed
        {
          delay(400);
          State = SOLID_COLOUR; // Change state to solid colours
          SINGLE_COLOUR_PALETTE_COUNT =++SINGLE_COLOUR_PALETTE_COUNT;
        }
//
//        if (SOLID_COLOUR_COUNT==1)
//        {
//          for (int i = 0; i < NUM_LEDS; i++)
//          {
//            leds[i].setRGB(255, 255, 0);
//          }
//        }
//
//        if(digitalRead(14)==HIGH)
//        {
//          delay(100);
//          SOLID_COLOUR_COUNT=++SOLID_COLOUR_COUNT;
//        }
//        FastLED.show();
//        FastLED.delay(20);
//    break; //End SINGLE_COLOUR_PALETTE

    case SOLID_COLOUR:
         if (SOLID_COLOUR_COUNT==1)
        {
          for (int i = 0; i < NUM_LEDS; i++)
          {
            leds[i].setRGB(255, 0, 0);
          }
        }

        if (SOLID_COLOUR_COUNT==2)
        {
          for (int i = 0; i < NUM_LEDS; i++)
          {
            leds[i].setRGB(0, 255, 0);
          }
        }
        FastLED.show();
        FastLED.delay(20);

        if(digitalRead(14)==HIGH)
        {
          delay(400);
          SOLID_COLOUR_COUNT=++SOLID_COLOUR_COUNT;
        }

        if(digitalRead(13)==HIGH)
        {
          delay(400);
          SOLID_COLOUR_COUNT=0;
          State = STANDARD_COLOUR_PALETTE;
        }

    break; // End SOLID_COLOUR
    }// switch end

} // Main end

// This function draws color waves with an ever-changing,
// widely-varying set of parameters, using a color palette.
void colorwaves( CRGB* ledarray, uint16_t numleds, CRGBPalette16& palette)
{
  static uint16_t sPseudotime = 0;
  static uint16_t sLastMillis = 0;
  static uint16_t sHue16 = 0;

  uint8_t sat8 = beatsin88( 87, 220, 250);
  uint8_t brightdepth = beatsin88( 341, 96, 224);
  uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
  uint8_t msmultiplier = beatsin88(147, 23, 60);

  uint16_t hue16 = sHue16;//gHue * 256;
  uint16_t hueinc16 = beatsin88(113, 300, 1500);

  uint16_t ms = millis();
  uint16_t deltams = ms - sLastMillis ;
  sLastMillis  = ms;
  sPseudotime += deltams * msmultiplier;
  sHue16 += deltams * beatsin88( 400, 5,9);
  uint16_t brightnesstheta16 = sPseudotime;

  for( uint16_t i = 0 ; i < numleds; i++) {
    hue16 += hueinc16;
    uint8_t hue8 = hue16 / 256;
    uint16_t h16_128 = hue16 >> 7;
    if( h16_128 & 0x100) {
      hue8 = 255 - (h16_128 >> 1);
    } else {
      hue8 = h16_128 >> 1;
    }

    brightnesstheta16  += brightnessthetainc16;
    uint16_t b16 = sin16( brightnesstheta16  ) + 32768;

    uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
    uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
    bri8 += (255 - brightdepth);

    uint8_t index = hue8;
    //index = triwave8( index);
    index = scale8( index, 240);

    CRGB newcolor = ColorFromPalette( palette, index, bri8);

    uint16_t pixelnumber = i;
    pixelnumber = (numleds-1) - pixelnumber;

    nblend( ledarray[pixelnumber], newcolor, 128);
  }
}

// Alternate rendering function just scrolls the current palette
// across the defined LED strip.
void palettetest( CRGB* ledarray, uint16_t numleds, const CRGBPalette16& gCurrentPalette)
{
  static uint8_t startindex = 0;
  startindex--;
  fill_palette( ledarray, numleds, startindex, (256 / NUM_LEDS) + 1, gCurrentPalette, 255, LINEARBLEND);
}

// Gradient palette "yellow_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/h5/tn/yellow.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 8 bytes of program space.

DEFINE_GRADIENT_PALETTE( yellow_gp ) {
    0, 255,255,255,
  255, 255,255,  0};

  // Gradient palette "RK_Yellow_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/lb/mp/tn/RK_Yellow.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( RK_Yellow_gp ) {
    0, 239,147,  0,
  155, 247,180,  1,
  255, 252,215,  1};

  // Gradient palette "blues_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/ocal/tn/blues.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 32 bytes of program space.

DEFINE_GRADIENT_PALETTE( blues_gp ) { //Blue
    0,   0,  0, 45,
   25,   0,  0,125,
   51,   0,  0,255,
   76,   7, 12,255,
  127,   7, 55,255,
  178,   0,138,255,
  242,   0,255,255,
  255, 255,255,255};

  // Gradient palette "bhw1_33_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/bhw/bhw1/tn/bhw1_33.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 16 bytes of program space.

DEFINE_GRADIENT_PALETTE( bhw1_33_gp ) { //Purple
    0,   2,  1,  8,
   94,  79,  2,212,
  140, 110, 11,197,
  255,   2,  1,  8};

// Gradient palette "Fuschia_8_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/ds/fuschia/tn/Fuschia-8.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Fuschia_8_gp ) {//Purple
    0,  44,  4,214,
  127, 123,  1,233,
  255, 255,  0,255};

// Gradient palette "Blue_Green_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/ggr/tn/Blue_Green.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 20 bytes of program space.

DEFINE_GRADIENT_PALETTE( Blue_Green_gp ) { //Light blue to green
    0,   0, 51,255,
   34,   1,111,255,
  144,   9,195,255,
  234,   1,225,153,
  255,   0,255, 80};

// Gradient palette "Green_3D_1_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/sd/tn/Green-3D_1.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 28 bytes of program space.

DEFINE_GRADIENT_PALETTE( Green_3D_1_gp ) {
    0, 103,186,106,
   42,  45,147, 48,
   84,  13,114, 14,
  127,   2, 87,  2,
  170,   0, 66,  0,
  212,   0, 23,  0,
  255,   0,  3,  0};

// Gradient palette "Mexican_flag_smooth_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/ggr/tn/Mexican_flag_smooth.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 20 bytes of program space.

DEFINE_GRADIENT_PALETTE( Mexican_flag_smooth_gp ) {
    0,   0,255,  0,
   63,  42,255, 45,
  127, 255,255,255,
  191, 255, 55, 45,
  255, 255,  0,  0};

 // Gradient palette "Fire_2_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/ds/icons/tn/Fire-2.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Fire_2_gp ) { //Red
    0, 255,255,  0,
  127, 255, 55,  0,
  255, 255,  0,  0};

  // Gradient palette "Orange_3D_1_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/sd/tn/Orange-3D_1.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Orange_3D_1_gp ) {// Orange
    0, 255,111, 11,
  127, 255, 92,  2,
  255, 255, 74,  1};

  // Gradient palette "bhw2_grrrrr_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/bhw/bhw2/tn/bhw2_grrrrr.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 32 bytes of program space.

DEFINE_GRADIENT_PALETTE( bhw2_grrrrr_gp ) {
    0, 184, 15,155,
   35,  78, 46,168,
   84,  65,169,230,
  130,   9,127,186,
  163,  77,182,109,
  191, 242,246, 55,
  216, 142,128,103,
  255,  72, 50,168};

// Gradient palette "es_skywalker_12_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/es/skywalker/tn/es_skywalker_12.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 16 bytes of program space.

DEFINE_GRADIENT_PALETTE( es_skywalker_12_gp ) { // Blue
    0,  92,175,255,
   61,  20,100,255,
  153,   1, 10,170,
  255,   0,  1, 29};

// Gradient palette "es_candide_26_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/es/candide/tn/es_candide_26.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 24 bytes of program space.

DEFINE_GRADIENT_PALETTE( es_candide_26_gp ) { //Purple
    0, 104, 10,245,
   89, 155,  0,245,
  165, 249,  2,242,
  208, 249, 51,247,
  249, 247,180,250,
  255, 247,180,250};

// Gradient palette "cool_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/h5/tn/cool.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 8 bytes of program space.

DEFINE_GRADIENT_PALETTE( cool_gp ) { // Blue to purple
    0,   0,255,255,
  255, 255,  0,255};

// Gradient palette "green_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/h5/tn/green.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 8 bytes of program space.

DEFINE_GRADIENT_PALETTE( green_gp ) {
    0, 255,255,255,
  255,   0,255,  0};

// Gradient palette "Pink_3D_2_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/sd/tn/Pink-3D_2.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Pink_3D_2_gp ) { //Pink
    0, 244, 58,242,
  127, 222, 29,226,
  255, 201, 10,210};

// Gradient palette "GoldSunset_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/atmospheric/tn/GoldSunset.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 36 bytes of program space.

DEFINE_GRADIENT_PALETTE( GoldSunset_gp ) { //Yellow and Orange
    0, 229,118,  0,
   41, 227,101,  0,
   82, 224, 86,  0,
  118, 163, 42,  0,
  124, 113, 15,  0,
  129, 167, 68,  2,
  138, 237,164, 16,
  191, 232,139,  2,
  255, 229,118,  0};

// Gradient palette "Sunset_Real_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/atmospheric/tn/Sunset_Real.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 28 bytes of program space.

DEFINE_GRADIENT_PALETTE( Sunset_Real_gp ) { //Orange and blue
    0, 120,  0,  0,
   22, 179, 22,  0,
   51, 255,104,  0,
   85, 167, 22, 18,
  135, 100,  0,103,
  198,  16,  0,130,
  255,   0,  0,160};

// Gradient palette "Blue_Magenta_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/basic/tn/Blue_Magenta.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Blue_Magenta_gp ) { //Blue purple
    0,   0,  0,255,
  127,  42,  0,255,
  255, 255,  0,255};

// Gradient palette "Red_Yellow_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/basic/tn/Red_Yellow.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Red_Yellow_gp ) { //Red to yellow
    0, 255,  0,  0,
  127, 255, 55,  0,
  255, 255,255,  0};

// Gradient palette "Yellow_White_Magenta_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/basic/tn/Yellow_White_Magenta.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 20 bytes of program space.

DEFINE_GRADIENT_PALETTE( Yellow_White_Magenta_gp ) { //Yellow to white
    0, 255,255,  0,
   63, 255,255, 45,
  127, 255,255,255,
  191, 255, 55,255,
  255, 255,  0,255};

// Gradient palette "White_Cyan_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/basic/tn/White_Cyan.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( White_Cyan_gp ) { //White to light blue
    0, 255,255,255,
  127,  42,255,255,
  255,   0,255,255};

// Gradient palette "Magenta_White_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/basic/tn/Magenta_White.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Magenta_White_gp ) { //Purple to white
    0, 255,  0,255,
  127, 255, 55,255,
  255, 255,255,255};

// Gradient palette "Magenta_Cyan_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/basic/tn/Magenta_Cyan.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 12 bytes of program space.

DEFINE_GRADIENT_PALETTE( Magenta_Cyan_gp ) { //purple to light blue
    0, 255,  0,255,
  127,  42, 55,255,
  255,   0,255,255};

  // Gradient palette "Green_Cyan_Blue_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/nd/basic/tn/Green_Cyan_Blue.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 20 bytes of program space.

DEFINE_GRADIENT_PALETTE( Green_Cyan_Blue_gp ) { //Greent to light blue
    0,   0,255,  0,
   63,   0,255, 45,
  127,   0,255,255,
  191,   0, 55,255,
  255,   0,  0,255};

// Gradient palette "rhubarb_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/ocal/tn/rhubarb.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 20 bytes of program space.

DEFINE_GRADIENT_PALETTE( rhubarb_gp ) { //purple to red
    0, 255, 55, 45,
   76, 255,  0,  0,
  127, 188, 12, 45,
  191, 255,  0,  0,
  255, 188, 12, 45};

// Gradient palette "YlGnBu_09_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/cb/seq/tn/YlGnBu_09.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 72 bytes of program space.

DEFINE_GRADIENT_PALETTE( YlGnBu_09_gp ) { //Blue
    0, 255,255,170,
   28, 255,255,170,
   28, 210,239,102,
   56, 210,239,102,
   56, 133,209,106,
   84, 133,209,106,
   84,  41,157,117,
  113,  41,157,117,
  113,   7,121,132,
  141,   7,121,132,
  141,   1, 73,125,
  170,   1, 73,125,
  170,   1, 28, 89,
  198,   1, 28, 89,
  198,   1,  7, 65,
  226,   1,  7, 65,
  226,   1,  2, 17,
  255,   1,  2, 17};

  // Gradient palette "Oranges_09_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/cb/seq/tn/Oranges_09.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 72 bytes of program space.

DEFINE_GRADIENT_PALETTE( Oranges_09_gp ) { //Orange
    0, 255,233,207,
   28, 255,233,207,
   28, 252,203,149,
   56, 252,203,149,
   56, 249,162, 82,
   84, 249,162, 82,
   84, 249,109, 29,
  113, 249,109, 29,
  113, 249, 69,  6,
  141, 249, 69,  6,
  141, 220, 36,  1,
  170, 220, 36,  1,
  170, 167, 15,  1,
  198, 167, 15,  1,
  198,  83,  8,  1,
  226,  83,  8,  1,
  226,  41,  4,  1,
  255,  41,  4,  1};

// Gradient palette "bhw1_28_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/bhw/bhw1/tn/bhw1_28.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 32 bytes of program space.

DEFINE_GRADIENT_PALETTE( bhw1_28_gp ) {// Purple blue purple
    0,  75,  1,221,
   30, 252, 73,255,
   48, 169,  0,242,
  119,   0,149,242,
  170,  43,  0,242,
  206, 252, 73,255,
  232,  78, 12,214,
  255,   0,149,242};

  // Gradient palette "bhw2_10_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/bhw/bhw2/tn/bhw2_10.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 28 bytes of program space.

DEFINE_GRADIENT_PALETTE( bhw2_10_gp ) { //Dark green to light green
    0,   0, 12,  0,
   61, 153,239,112,
  127,   0, 12,  0,
  165, 106,239,  2,
  196, 167,229, 71,
  229, 106,239,  2,
  255,   0, 12,  0};
// Gradient palette "bhw2_11_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/bhw/bhw2/tn/bhw2_11.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 20 bytes of program space.

DEFINE_GRADIENT_PALETTE( bhw2_11_gp ) { //Dark grren and blue mixed
    0,   0, 12,  8,
   79,   0, 55, 45,
  130,   0,136,125,
  183,   0, 55, 45,
  255,   0, 12,  8};

// Gradient palette "bhw3_01_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/bhw/bhw3/tn/bhw3_01.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 52 bytes of program space.

DEFINE_GRADIENT_PALETTE( bhw3_01_gp ) { //Pink, to blue, to red, to yellow
    0, 255,146,228,
   25, 152, 43, 65,
   48,  36, 17, 22,
   72,   8, 34, 75,
   81,   1, 58,170,
  104,  42, 49,245,
  124,  15, 15, 95,
  150,   1,  8, 39,
  175,  98, 32, 35,
  204, 123,  9,  2,
  219, 220, 15,  2,
  237, 255, 93,  6,
  255, 244,244,  0};

   // Gradient palette "Deep_Sea_gp", originally from
// http://soliton.vm.bytemark.co.uk/pub/cpt-city/ggr/tn/Deep_Sea.png.index.html
// converted for FastLED with gammas (2.6, 2.2, 2.5)
// Size: 20 bytes of program space.

DEFINE_GRADIENT_PALETTE( Deep_Sea_gp ) { //Dark blue
    0,   0,  1,  2,
  148,   1,  7, 24,
  194,   2, 31, 77,
  226,   1,108,144,
  255,   0,237,235};

// Single array of defined cpt-city color palettes.
// This will let us programmatically choose one based on
// a number, rather than having to activate each explicitly
// by name every time.
// Since it is const, this array could also be moved
// into PROGMEM to save SRAM, but for simplicity of illustration
// we'll keep it in a regular SRAM array.
//
// This list of color palettes acts as a "playlist"; you can
// add or delete, or re-arrange as you wish.
const TProgmemRGBGradientPalettePtr gGradientPalettes[] = {
  GoldSunset_gp,
  //Green_3D_1_gp,
  //GoldSunset_gp,
  //bhw1_33_gp,
  //bhw1_33_gp,
  //bhw1_33_gp,
  //bhw1_33_gp,
  //Green_3D_1_gp,
  //Fire_2_gp,
  yellow_gp,
  RK_Yellow_gp,
  //yellow_gp,
  //yellow_gp,
  //blues_gp,
  //blues_gp,
  //bhw1_33_gp,
  //bhw1_33_gp,
  //bhw1_33_gp,
 Fuschia_8_gp,
  //Blue_Green_gp,
  //Blue_Green_gp,
  //Fire_2_gp,
  //Green_Cyan_Blue_gp,
  //Green_Cyan_Blue_gp,
 //Green_Cyan_Blue_gp,
  //Green_Cyan_Blue_gp,
  //Green_Cyan_Blue_gp,
  //Green_Cyan_Blue_gp,
  //Green_3D_1_gp,
  //Green_3D_1_gp,
  //Mexican_flag_smooth_gp,
  //Mexican_flag_smooth_gp,
  //Fire_2_gp,
  //Fire_2_gp,
  //bhw1_33_gp,
  //es_skywalker_12_gp,
  //Fire_2_gp,
  //es_skywalker_12_gp,
  //es_skywalker_12_gp,
  //Orange_3D_1_gp,
  //Orange_3D_1_gp,
  //bhw2_grrrrr_gp,
  //es_candide_26_gp,
  //cool_gp,
  //cool_gp,
  //green_gp,
  //green_gp,
  //Pink_3D_2_gp,
  //Pink_3D_2_gp,
  //GoldSunset_gp,
  //Green_Cyan_Blue_gp,
  //Sunset_Real_gp,
  //Blue_Magenta_gp,
  //Blue_Magenta_gp,
  //Red_Yellow_gp,
  //Red_Yellow_gp,
  //Yellow_White_Magenta_gp,
  //White_Cyan_gp,
  //White_Cyan_gp,
  //Magenta_White_gp,
  //Magenta_White_gp,
  //Magenta_Cyan_gp,
  //Magenta_Cyan_gp,
  //Green_Cyan_Blue_gp,
  //Green_Cyan_Blue_gp,
  //rhubarb_gp,
  //YlGnBu_09_gp,
  //Oranges_09_gp,
  //bhw1_28_gp,
  //bhw2_10_gp,
  //bhw2_11_gp,
  //bhw3_01_gp,
  //Sunset_Real_gp,
  Sunset_Real_gp,
 };
//
// const TProgmemRGBGradientPalettePtr gGradientPalettes[] = {
// Fuschia_8_gp,
// };

// Count of how many cpt-city gradients are defined:
const uint8_t gGradientPaletteCount =
  sizeof( gGradientPalettes) / sizeof( TProgmemRGBGradientPalettePtr );

separate the state transition and the resulting LED mode selection ... for example, at reset, go to state 0 ... in state 0, if solid pressed, goto state 1, if palette pressed, goto state 5 ... in state 1, if solid pressed, goto state 2 ... in state 2, if solid pressed, goto state 1 ... etc. etc. .............. then light LEDs according to existing state ... if state 2, light random solid color and go to state 1 ... etc. etc. ...... basically, keep the state selection by button self contained ... the LED lighting is done only on basis of the state number

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


text:
Uploading sketch to multiple Arduinos connected in series
I'm currently working on a project where you essentially will have multiple Arduinos (1 Uno, multiple Nanos) daisy-chained, only connected through 2 digital pins and one wire for Serial communication (RX Pin -> TX Pin). (The first one is connected via USB to the PC.)
I figured the serial communication between the first Arduino and PC would also be forwarded through the RX and TX pins, but that doesn't seem to be the case.
As it's fairly tedious to update one at a time, is there a way of updating all of them at once, using only the one-way serial communication wire?
EDIT: Yeh so like imma just add a USB Port to every single component to the chain to update separately, and update every single one of them separately.

Serial communication between the first arduino and PC would also be forwarded through the RX and TX pins ... that would happen only if the bootloader sends back what it receives from avrdude ... you could modify the bootloader to do that ... I think that the avrdude expects some handshaking though

Might be better off making a program to feed nanos instead of a modified bootloader

Try connecting only the RX and reset pins. Serial programming is done by the bootloader, but it needs to be switched into programming mode first, which is done by resetting the chip and then sending a special code to the RX pin within a certain time period. When you program through the serial port (as you are doing with the Uno) the FTDI chip drives this pin for you, but you'll need to cascade that reset signal through to the other chips as well. This still isn't guarenteed to work 100%, because it depends on a number of other factors as well, but at least you'll have a chance.
When I've done stuff like this commercially I've programmed via the ICSP connector instead and made programming rigs out of spring-loaded pin connectors that the target boards simply clip onto. If you're planning on doing this with any degree of frequency then I'd recommend investing a bit of time into doing this yourself.
UPDATE: ok, I can see now why this isn't working. The Nano's CH340 usb-to-serial chip is pulling RX low, preventing the data stream from being read. Would work fine with standalone chips, obviously doesn't on the Nano.
I think your best option is to use ICSP. It's an extra pin, but if you breadboard then it shouldn't make any difference. Plus there are a number of advantages to doing so, including faster programming, the ability to upload/replace the bootloader and the ability to change fuses (e.g. to protect your firmware or disable the bootloader altogether to give you app more Flash space etc).
If you don't already know how to do this then the layout is:

Connect Uno SCLK(D13)/MOSI(D11)/GND pins to all the corresponding Nano pins.
Connect Uno D10 to all the Nano's RESET pins.
Connect Uno MISO(D12) to only the first Nano's MISO pin.
Connect Uno VIN to all the Nano VINs (you don't want all the Nanos being driven from the Uno's regulator)

Should wind up looking something like this:

Prepare the Uno for programming:

Set your IDE board type to Uno
Set IDE programmer type to "AVR ISP"
Upload IDE ArduinoISP sketch to the Uno

And now you're ready to program the Nanos:

Set your IDE board type to Nano
Set IDE programmer type to "Arduino as ISP"
Upload your Nano sketch using "Upload Using Programmer"

Just tried it now with the two Nanos in the photo, worked fine.

What I've also heard so far is, that avrdude also expects handshakes/responses from the programmed board, and if the serial is simply forwarded, out of sync aka timing issues are likely to occur while uploading, but I'll definitely try this later!

@Mikoyan yes, that's true, although I would expect the pauses in between programming chunks to be long enough to accommodate that. But if it doesn't work then writing your own uploader is extremely easy, the Flash function in Device.cs in my Windows Arduino emulator has all the code to do this, and you could just add additional delays as needed.

Connecting only the RX and Reset pins does not work, it appears like the Reset pin is not actually (un)firing (although it might've just been too fast to notice, still: no program on the nano) :/

@Mikoyan gimme a day or so to try it out, I'll reply here with an answer if I can get it working myself.

@Mikoyan answer updated.

As only one Nano has its MISO connected, the programmer can't get feedback from all the others. I wouldn't have dared such a setup, but it's really cool that it works! Note though that, in the “verify” phase of the upload, only the first Nano is effectively verified.

I kinda feel dumb at this point: avrdude: Yikes!  Invalid device signature., I did just as you said buuut yea, it spits this error. I only used one nano to try this, but I don't think that matters.

@Mikoyan first thing to do then is check the command being sent to avrdude. If you're doing it through the IDE then enable verbose output during upload in preferences and see what command it dumps out when you program, should be something like C:\arduino-1.8.19-windows\arduino-1.8.19\hardware\tools\avr/bin/avrdude -CC:\arduino-1.8.19-windows\arduino-1.8.19\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM9 -Uflash:w:C:\Users\your_user_name\AppData\Local\Temp\arduino_build_213021/your_sketch.ino.hex:i

If that checks out then it's probably just a wiring issue. Start by replacing that VIN connection with a connection to their 5V pins (fine if it's just one board) and wire directly to the Arduino pins (as shown in this image) to rule out any problem with its ICSP header.

There is a two-way protocol used by the bootloader which I describe here.
You could conceivably connect all the Rx wires together, and use the Tx wire from the first one (so it responds appropriately), and discard the responses from the other units. If they program at exactly the same rate, and reset at exactly the same moment, that might work.
You might be better off just uploading using a device designed to do that, as I describe on my forum. The Atmega328P programmed using that method can be reprogrammed in about one second (so the time to hook up the wires is the long part). Using the ICSP interface on the chips, and a suitable plug, could make that very quick, and easy.
There are also stand-alone devices, for example the Crossroads standalone programmer which uses the techniques described in my forum post. You can use that in the field because it doesn't require a monitor or PC. You just hook it up via the ICSP port, select what file you want to upload, and hit the "program" button.

"You could conceivably connect all the Rx wires together" -
Actually no, as discussed in another reply, connecting just the RX pins (and reset to bring it into programming mode) does not work as:
"The Nano's CH340 usb-to-serial chip is pulling RX low, preventing the data stream from being read. Would work fine with standalone chips, obviously doesn't on the Nano"

Hmm, OK. You could make up your own boards without a USB to serial chip, since that doesn't seem required in this setup. Or just desolder it from the boards.


text:
creating HTTP persistent connection, to create 'smooth' data over GSM sending
Project goals

Send data over GSM to firebase
Fast sampling - need to send 16 bytes every half second to firebase
Send data using GET or POST to server with PHP script, that redirect data to firebase

Problems --
Extremely low data rate!

Using standard GET or POST request from client(arduino) side, is impossible to achieve second (2) project goal.
To send data correctly I need to close connection with server, so next data package unfortunately waits(2-6 seconds) for establishing a new connection.
Is this quite nonsense? I'm using ArduinoHttpClient library.

My actual Nonsense Connection and fully useless, but works

while(1){

http.post("/test.php","application/x-www-form-urlencoded","data=0");
http.stop(); //closing connection with server

//next instruction take over 5 second to establish new connection :(

http.post("/test.php","application/x-www-form-urlencoded","data=0");
http.stop(); //closing connection with server, whyyy?
}

Data are send once per 2 - 6 seconds, this is not even funny. NEED to send data every 0.5 seconds!
So I decided to create super solution, which not works :C
while(1){
    http.post("/test.php","application/x-www-form-urlencoded","data=0");
    delay(xxx);
//no connection closing, no wasting time for establishing new one :)
}

Just tell my why this connection is not "Keep-Alive", also used with

http.sendHeader("Connection: Keep-Alive"); or
  http.connectionKeepAlive();

//First run
http.post(blabla);// returns value: 0 & data are logged into firebase
//Second run
http.post(blabla);// returns value: -2 & data are not logged in firebase

my test.php file
<?php
require_once 'firebaseLib.php';
$url = 'https://czujniki-aa5ca.firebaseio.com/';
// --- Use your token from Firebase here
$token = ':-CCCCCCCCCCCCCCCCCCCCCCC';

$arduino_data_post = $_POST['data'];
$firebasePath = '/';

$fb = new fireBase($url, $token);
$response = $fb->push($firebasePath, $arduino_data_post);
sleep(2);

does the 'modem' disconnect from network with no active connection? search for a setting to keep the GPRS connection connected

@Juraj i think modem doesn't turn off networking itself, I will check the code and post back. If it will not work, i will test it on pure AT commands.

try in the library in HttpClient.h make resetState() public (by moving 'protected:') and then in sketch call resetState() before post()

@Juraj [link] (https://ibb.co/7rc2Yt8) look at the screenshot. resetState() is working fine, and now we dont need to use stop(), but essentially it works like .stop(); Look at the timestamp, delay between data uploading is still awful. 0 means 0 error code, so data are send successfully

The ArduinoHttpCliemt library's HttpClient.stop() method does two things. It resets the state of the HttpClient object and stops the underlying Client connection (TCP connection). If HttpClient.stop() is not called, the internal state is not good to call get() or post() again.
The method resetState() is called in HttpClient.stop() to reset the internal state of the HttpClient object. But resetState() is protected. To call it we must modify the library header file.
In HttpClient.h make resetState() public (by moving 'protected:') and then in sketch call resetState() before post(). It will put the HttpClient object into initial state without disconnecting the underlying TCP connection.

Yes that's work, but time between POST's is still huge. [link] (ibb.co/7rc2Yt8) screenshot

add #define LOGGING at the beginning of HttpClient.cpp, to see if it uses the connection or reconnects

[link] (https://ibb.co/k88TXXm) logging returns: connection already open, connected. Look at time, delay increases while new posts are sended. Is it opening new connections, instead of using first one?

no it always prints Connected. so it is reusing the connection. that was your question. the request takes time, not the connection.

try to read the response with int statusCode = client.responseStatusCode();

[link] (https://ibb.co/Q9ZHxJN), with responseStatusCode(); arduino client do nothing

so it doesn't get a response. check the server

[link] (https://ibb.co/gJxQSfw) now i setted it to make reconnect every POST. And it seems to be paradox, because we got smaller delays, if you look at the timestamp. Quite frustrating, keep-alive should lower time between requests, but it's working in the opposite direction

because not the new connection is the problem as you can see on the output times


text:
Arduino components
I’m teaching and learning coding with MicroBit and was wondering if these components are compatible with MicroBit. The specific kits labeled for MicroBit are twice the price but the components look similar. Just trying to save a few bucks. Would this kit work with my MicroBit?

That is a whole collection of components, most of them simple electronic components not specific for Arduino. Some components are more complex, but they also should work with the microbit. This is seen from the first glance, I didn't looked into everything in detail. What can be done simultaneously on the microbit depends more on what you try to build. What components did you see, that where marked compatible with Microbit? It might be easier to point out devices, that are microbit specific instead of the one which are not.

It looks like the MicroBit runs on 3.3V versus 5V for most Arduino boards. You'd need to use 3.3V components.
It looks like the kit you linked to is built for (and includes) a 5V Arduino, so those accessories would not work with your MicroBit.
There are other Arduino boards that run on 3.3V. Look for 3.3v accessories. Those should work.
EDIT:

I assume that the MicroBit is capable of I2C interfacing. If so, you should look at the SparkFun Qwiic system. It's a setup with 3.3V I2C serial interface in a 4-wire ribbon cable with a standard connector. You can easily daisy-chain Qwiic devices by just plugging Qwiic cables between them, and they are reasonably priced. I bought some of them thinking I could use them with my Arduino projects, only to discover that they use 3.3V, so I can't use them without I2C voltage translation interfaces, which makes them much less appealing.

Thanks. For speedy response

See the edit to my answer, talking about SparkFun Qwicc devices.


text:
Help Troubleshooting L298n connected to dc motor
I am relatively new to Arduino, and I am trying to power a DC motor with the L298N dual H-Bridge. I have done as follows:
I am powering everything with the Arduino that is connected to the PC. (I know this isn't ideal, but I don't have a better power supply yet)
I connected the 5V output from Arduino to the 12V terminal of the L298N, and connected it to the Arduino ground. The red light from the L298N shines brightly.
Then, I connected the IN3 and IN4 pins to the Arduino digital pins 7 and 8, respectively.
Finally, I connected the Out 3 and Out 4 to my DC motor, but it doesn't turn at all. I use the following code:

int In3=7;
int In4=8; //idem para In2

void setup() {
  pinMode(In3,OUTPUT); //avisa que nuestros pines son todos outputs
  pinMode(In4,OUTPUT);

  digitalWrite(In3,HIGH);
  digitalWrite(In4,LOW);
}

void loop() {

}

For the time being I decided to not use the PWM, so that I can start simple. I tried changing all cables and even the motor, but it just won't rotate. The L298N is brand new, so it's unlikely that it is damaged. What could I try next?

Welcome to Arduino! Please take the tour and visit the helpcenter to see how things work here. Note that (SOLVED) tags should not be edited into the question's title, please "accept" the correct answer instead.

I realized that I had the jumper disconnected from the ENB pins, which immediately solved the problem when I reconnected it, so it is now fixed!

It's OK to accept your own answer as the solution to the problem. I think you get 15 rep for it.


text:
CircuitPython - how to connect Adafruit esp32 AirLift with Adafuit HttpServer? Incompatible socket object
I am building a CircuitPython weather station based on Adafruit M4 board stacked with Adafruit ESP32 AirLift module.
Both work fine together when it comes to making http calls (via the Adafruit_requests library). However I would like to build am HTTP server serving weather measures instead.
And here is a problem: all Adafuit examples are based on ESP32 or Raspberry Pico boards natively fitted with Wifi. The Adafuit M4 board doesn't have the same core Python packages since it doesn't support Wifi.
So an example written for Pico doesn't work on the M4 with ESP AirLift, as there are a number of packages missing to do so (like wifi and socket), adafuit_esp package has to be used instead.
This package however seems to be incompatible with Adafuit HTTPServer:
https://docs.circuitpython.org/projects/httpserver/en/stable/index.html
HttpServer requires a socket object as a parameter to be initialized:
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
socket.set_interface(esp)
server = HTTPServer(socket)

This code fails when I'm trying to start the server:
try:
    server.start(esp.pretty_ip(esp.ip_address))
    print("Listening on http://%s:80" % esp.pretty_ip(esp.ip_address))
#  if the server fails to begin, restart the pico w
except OSError:
    time.sleep(5)
    print("restarting..")
    microcontroller.reset()

And the error is:
>>> %Run -c $EDITOR_CONTENT
Creating display
Creating server socket
ESP32 found and in idle mode
Firmware vers. bytearray(b'1.2.2\x00')
MAC addr: ...
...
Connecting to AP...
Connected to jama   RSSI: -27
My IP address is 192.168.0.24
Creating HTTP Server...
starting server..
Traceback (most recent call last):
  File "<stdin>", line 175, in <module>
  File "adafruit_httpserver/server.py", line 91, in start
AttributeError: 'socket' object has no attribute 'bind'
>>>

So it looks like that's not the right socket. It works for ESP and Requests libs but not for HTTPServer.
Here are imports:
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_esp32spi.adafruit_esp32spi_socket as socket

My question then (or two) is does anyone know a workaround for this issue  and/or a different socket or server packages I can use instead?
Here is the full code for the reference, it is not finished and contains more stuff than described here but unrelated to the issue:
import os
import time
import busio
import board
import microcontroller
from digitalio import DigitalInOut, Direction
import adafruit_bh1750
# import adafruit_requests as requests
from adafruit_bme280 import basic as adafruit_bme280
from adafruit_httpserver.server import HTTPServer
from adafruit_httpserver.request import HTTPRequest
from adafruit_httpserver.response import HTTPResponse
from adafruit_httpserver.methods import HTTPMethod
from adafruit_httpserver.mime_type import MIMEType
from adafruit_epd.epd import Adafruit_EPD
from adafruit_epd.il0373 import Adafruit_IL0373
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_esp32spi.adafruit_esp32spi_socket as socket

try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

#  onboard LED setup
# led = DigitalInOut(board.LED)
# led.direction = Direction.OUTPUT
# led.value = False

i2c = board.I2C()  # uses board.SCL and board.SDA
bh1750 = adafruit_bh1750.BH1750(i2c)
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, 0x76)
bme280.sea_level_pressure = 1012.50

spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
ecs = DigitalInOut(board.D9)
dc = DigitalInOut(board.D10)
srcs = DigitalInOut(board.D6)  # can be None to use internal memory
rst = None #DigitalInOut(board.D1)  # can be None to not use this pin
busy = None #DigitalInOut(board.D5)  # can be None to not use this pin

esp32_cs = DigitalInOut(board.D13)
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)

print("Creating display")
display = Adafruit_IL0373(
    128,
    296,  # 2.9" Tri-color display
    spi,
    cs_pin=ecs,
    dc_pin=dc,
    sramcs_pin=srcs,
    rst_pin=rst,
    busy_pin=busy,
)

display.set_black_buffer(1, True)
display.set_color_buffer(1, True)
display.rotation = 1
display.fill(Adafruit_EPD.WHITE)
# display.display()
# display.text(splash, 12, 12, Adafruit_EPD.BLACK, size=1)

#  connect to network
print("Creating server socket")
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
socket.set_interface(esp)

if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
    print("ESP32 found and in idle mode")
print("Firmware vers.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address])

for ap in esp.scan_networks():
    print("\t%s\t\tRSSI: %d" % (str(ap["ssid"], "utf-8"), ap["rssi"]))

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(secrets["ssid"], secrets["password"])
    except OSError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))

print("Creating HTTP Server...")
server = HTTPServer(socket)

#  font for HTML
font_family = "monospace"

#  the HTML script
#  setup as an f string
#  this way, can insert string variables from code.py directly
#  of note, use {{ and }} if something from html *actually* needs to be in brackets
#  i.e. CSS style formatting
def webpage():
    html = f"""
    <!DOCTYPE html>

    <meta http-equiv="Content-type" content="text/html;charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Pico W HTTP Server</title>

Pico W HTTP Server

This is a Pico W running an HTTP server with CircuitPython.

The current ambient temperature near the Pico W is
    {temp_test}°{unit}

Control the LED on the Pico W with these buttons:

    <form accept-charset="utf-8" method="POST">
    <button class="button" name="LED ON" value="ON" type="submit">LED ON</button>
</form>

<form accept-charset="utf-8" method="POST">
    <button class="button" name="LED OFF" value="OFF" type="submit">LED OFF</button>
</form>

Party?</h>

<form accept-charset="utf-8" method="POST">
    <button class="button" name="party" value="party" type="submit">PARTY!</button>
</form>

    """
    return html

#  route default static IP
@server.route("/")
def base(request: HTTPRequest):  # pylint: disable=unused-argument
    #  serve the HTML f string
    #  with content type text/html
    with HTTPResponse(request, content_type=MIMEType.TYPE_HTML) as response:
        response.send(f"{webpage()}")

#  if a button is pressed on the site
@server.route("/", method=HTTPMethod.POST)
def buttonpress(request: HTTPRequest):
    #  get the raw text
    raw_text = request.raw_request.decode("utf8")
    print(raw_text)
    #  if the led on button was pressed
    if "ON" in raw_text:
        #  turn on the onboard LED
        led.value = True
    #  if the led off button was pressed
    if "OFF" in raw_text:
        #  turn the onboard LED off
        led.value = False

    #  reload site
    with HTTPResponse(request, content_type=MIMEType.TYPE_HTML) as response:
        response.send(f"{webpage()}")

print("starting server..")
# startup the server
try:
    server.start(esp.pretty_ip(esp.ip_address))
    print("Listening on http://%s:80" % esp.pretty_ip(esp.ip_address))
#  if the server fails to begin, restart the pico w
except OSError:
    time.sleep(5)
    print("restarting..")
    microcontroller.reset()

#  text objects for screen
#  connected to SSID text
connect_text_area.text = "Connected to:"
ssid_text = "%s" % secrets('ssid')
# ssid_text_area = label.Label(terminalio.FONT, text=ssid_text, color=0xFFFFFF, x=0, y=offset_y+15)
#splash.append(ssid_text_area)
#  display ip address
ip_text = "IP: %s" % wifi.radio.ipv4_address
# ip_text_area = label.Label(terminalio.FONT, text=ip_text, color=0xFFFFFF, x=0, y=offset_y+30)
#splash.append(ip_text_area)
#  display temp reading
temp_text = "Temperature: %.02f F" % float(temp_test)
# temp_text_area = label.Label(terminalio.FONT, text=temp_text, color=0xFFFFFF, x=0, y=offset_y+45)
#splash.append(temp_text_area)

def get_weather_conditions():
    temp = bme280.temperature
    print("\nTemperature: %0.1f C" % temp)
    hum = bme280.relative_humidity
    print("Humidity: %0.1f %%" % hum)
    pres = bme280.pressure
    print("Pressure: %0.1f hPa" % pres)
    alt = bme280.altitude
    print("Altitude: %0.2f meters" % alt)
    light = bh1750.lux
    print("Light: %.2f Lux" % light)
    return [temp, hum, pres, alt, light]

clock = time.monotonic() #  time.monotonic() holder for server ping

while True:
    try:
        #  every 30 seconds, ping server & update temp reading
        if (clock + 30) < time.monotonic():
            if wifi.radio.ping(ping_address) is None:
                connect_text_area.text = "Disconnected!"
                ssid_text_area.text = None
                print("lost connection")
            else:
                connect_text_area.text = "Connected to:"
                ssid_text_area.text = "%s" % secrets('ssid')
                print("connected")
            clock = time.monotonic()
            #  comment/uncomment for desired units
            #  temp_test = str(ds18.temperature)
            temp_test = str(c_to_f(19.45))
            temp_text_area.text = "Temperature: %s F" % temp_test

#         display.show(splash)
        #  poll the server for incoming/outgoing requests
        server.poll()
    # pylint: disable=broad-except
    except Exception as e:
        print(e)
        continue

The official answer from Adafuit for this question is that the HTTPServer lib is created for Raspeberry PICO and does not work on other boards like Feather M4 express indeed. A different set of libraries needs to be used instead, here is the relevant example:
https://github.com/adafruit/Adafruit_CircuitPython_WSGI


text:
How can I improve the power supply for my Arduino-based sensor system?
I am working on an Arduino-based sensor system that includes a temperature sensor, a humidity sensor, and an LCD display. Everything works fine, but I am facing issues with power stability when I run the system for extended periods.
The sensors sometimes stop responding, and the LCD display flickers occasionally. I am currently powering the system using a 9V battery, but I suspect that the power supply might not be sufficient or stable enough for continuous operation.
I was considering switching to a regulated power supply, but I’m not sure which type would be best suited for this setup. Should I go with a linear regulator or a switching regulator? Are there any specific products that are recommended for Arduino-based systems?
Additionally, I found this DC-DC Convertor which seems like a good option. Has anyone used something similar in their projects? Any feedback or alternative recommendations would be greatly appreciated.
Thank you!

May you link the board you are using?

9V batteries may seem convenient but are generally not recommended for systems that run for a long time. An exception might obviously be smoke alarms, but they are specifically designed to have low current draws.
If you are using something like a Uno, and plugging in a 9V battery, then the voltage regulator immediately converts that to 5V, throwing away the rest as heat.
You are much better off using, say, 3 AA batteries in a battery holder (giving a nominal total of 4.5V) and connecting that directly to the 5V pin of your Arduino.
Then I would set it up to sleep, consuming much less power when it is not actually taking readings.
I did a temperature and humidity sensor, described here which runs for a couple of years before needing battery replacement.
I also have some tips for low power usage.
Related post on this site: Arduino minimal power usage

Assuming you want your system to work as long as possible with the battery, you should consider changing your elements:

Do NOT use Arduino Uno or similar, but go for a Pro Mini (3V3/8MHz) with no LED.
Select a low consumption display. e-ink are best, as they do not consume anything as long as you don't change the display.
Look at "sleeping" capabilities of your system. There are a few libraries or articles explaining how you can put your system to sleep and only wake up every x minutes.
Consider using a 1.5V battery and a boost DC-DC converted.

One AA battery will last weeks if you are following the above recommendations. I have one such system running since 10 years at home, and I change my battery roughly every year.

You can always tie multiple batteries in parallel for more current, use a bigger 9v battery, or go with any 9v power supply. If your sensors are analog, you may need to use a linear power supply because they make less noise. If the sensors are digital, switching should work fine. I think all of the sensors would be 5v, if so, a 5v power supply would work as long as it has enough current to run all the sensors, and Arduino. DC-DC converters aren't really want you are looking for unless your power supplies are too high of a voltage or if you need two separate voltages. With Arduino, I usually connect a 12V power supply to VIN so that I have 12V, and 5v 3.3v from the Arduino. When you connect your sensors, try not to draw too much from the Arduino. The pins can only supply so much.


text:
Using I2S MEMS microphone breakout (SPH0645) as frequency detector
Good day. I would like to ask for help regarding the code for my project. I am using an I2S MEMS microphone breakout (SPH0645) to my Arduino Nano 33 IoT. Here are my pin configurations LRCL to A2 of the Arduino Nano 33 IoT, DOUT to D4, BCLK to A3. The code that I am using is:
#include <I2S.h>
void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ;
  }
  if (!I2S.begin(I2S_PHILIPS_MODE, 8000, 32)) {
    Serial.println("Failed to initialize I2S!");
    while (1); // do nothing
  }
}
void loop() {
  int sample = I2S.read();
  if (sample) {
    Serial.println(sample);
  }
}

However, I still cannot see in the serial monitor if the microphone can detect sound. Also, every time I upload this to my Arduino, I encounter this problem:

appdata/local/arduino15/packages/arduino/tools/arm-none-eabi-gcc/7-2017q4/bin/../lib/gcc/arm-none-eabi/7.2.1/../../../../arm-none-eabi/bin/ld.exe: warning: changing start of section .bss by 8 bytes

I followed the steps here. Thank you for your help.


text:
How to output two PWM signals, one of 50% duty cycle, the other 25% duty cycle, from an Arduino Uno?
I need to output two PWM signals, one of 50% duty cycle, the other 25% duty cycle, from an Arduino. Feed both signals into the 2 channels of a PicoScope and measure:
a) the time difference between the rising pulse of the traces and
b) the time it takes for the signal to settle for the 50% trace.
I understand that I may not get help with the Picoscope part of the question, however I do need help with the other part.
I'm very new to Arduino and don't really know what I'm doing. Any help will be appreciated!

examine the blinkWithoutDelay example sketch in the Arduimo IDE ... use that for timing the rising and falling edges of the two signals

The function analogWrite generates PWM signals. See its documentation for details.
You use analogWrite(pin_for_25_percent, 64); for 25% and analogWrite(pin_for_50_percent, 128); for 50%.
const int pin_for_25_percent = /* your choice */;
const int pin_for_50_percent = /* your choice */;

void setup() {
    analogWrite(pin_for_25_percent, 64);
    analogWrite(pin_for_50_percent, 128);
}

void loop() {
}

On an AVR-Arduino, each hardware timer controls two PWM pins. Results regarding timing/synchronization of the PWM signals may vary depending on the chosen pins.

@DataFiddler There are no requirements in the question concerning synchronous signals. ;-) I assume this is just an introductory experiment of a homework or laboratory assignment. But granted, with more and clear requirements, you could have a point.

@busybee I understand the time difference between the rising pulse of the traces as a question about the synchronization  of the two PWM signals. But you're right, the task rather seems to aim at manual triggering of digital pins.


text:
With reference to Arduino Keyboard library, it does not have a keymap for UK keyboard, has anyone created a KeyboardLayout_en_UK.cpp file for this?
With reference to the Arduino Keyboard library, it does not have a keymap for the UK keyboard. I have tried to find a keyboard map that shows the hex value for the UK keyboard but I didn't have any luck.
If you look in the Arduino Keyboard library: Arduino\libraries\Keyboard\scr\KeyboardLayout_en_US.cpp
it has some other languages but no keyboard layout for a UK keyboard.
It does say somewhere I think on GitHub that a keyboard layout file can be added, but where can I get that file or how can I create that file?
Has anyone already created a KeyboardLayout_en_UK.cpp file I could use, please?

Edgar Bonet, a regular contributor here, has some additional layouts at https://github.com/arduino-libraries/Keyboard/tree/master/src - however the UK keyboard doesn't seem to be present. He can probably help you, no doubt he will see this post shortly.

Thanks for useful info

As an example of what you might do ...
First copy the file KeyboardLayout_en_US.cpp and rename it as KeyboardLayout_en_UK.cpp.
Most of the entries will be the same. Now looking at the layout in https://github.com/arduino-libraries/Keyboard/blob/1.0.4/src/KeyboardLayout.h we see this:
  +---+---+---+---+---+---+---+---+---+---+---+---+---+-------+
  |35 |1e |1f |20 |21 |22 |23 |24 |25 |26 |27 |2d |2e |BackSp |
  +---+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-----+
  | Tab |14 |1a |08 |15 |17 |1c |18 |0c |12 |13 |2f |30 | Ret |
  +-----++--++--++--++--++--++--++--++--++--++--++--++--++    |
  |CapsL |04 |16 |07 |09 |0a |0b |0d |0e |0f |33 |34 |31 |    |
  +----+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+---+----+
  |Shi.|32 |1d |1b |06 |19 |05 |11 |10 |36 |37 |38 |  Shift   |
  +----+---++--+-+-+---+---+---+---+---+--++---+---++----+----+
  |Ctrl|Win |Alt |                        |AlGr|Win |Menu|Ctrl|
  +----+----+----+------------------------+----+----+----+----+

The third key along the top row of my (US) keyboard (below the function keys) has @ on top and 2 on the bottom. It has the code 1f in the chart.
In the US layout file we see, in part:
0x2c,          // ' '        0x20
0x1e|SHIFT,    // !          0x21
0x34|SHIFT,    // "          0x22
0x20|SHIFT,    // #          0x23
0x21|SHIFT,    // $          0x24
0x22|SHIFT,    // %          0x25
0x24|SHIFT,    // &          0x26
0x34,          // '          0x27
0x26|SHIFT,    // (          0x28
0x27|SHIFT,    // )          0x29
0x25|SHIFT,    // *          0x2a
0x2e|SHIFT,    // +          0x2b
0x36,          // ,          0x2c
0x2d,          // -          0x2d
0x37,          // .          0x2e
0x38,          // /          0x2f
0x27,          // 0          0x30
0x1e,          // 1          0x31
0x1f,          // 2          0x32
0x20,          // 3          0x33
0x21,          // 4          0x34
0x22,          // 5          0x35
0x23,          // 6          0x36
0x24,          // 7          0x37
0x25,          // 8          0x38
0x26,          // 9          0x39
0x33|SHIFT,    // :          0x3a
0x33,          // ;          0x3b
0x36|SHIFT,    // <          0x3c
0x2e,          // =          0x3d
0x37|SHIFT,    // >          0x3e
0x38|SHIFT,    // ?          0x3f
0x1f|SHIFT,    // @          0x40

I've put the positions of each entry on the right (the offset from the start of the array).
So looking at that table, when the scan code 1f arrives, and SHIFT is pressed, we get 0x40 which is indeed @ in the ASCII table.
Similarly, 1f without SHIFT gives us 0x32 which is 2 in the ASCII table.
Now in your case I believe that key gives " when SHIFT is pressed, so the third line from the top in my example changes from:
0x34|SHIFT,    // "          0x22

to:
0x1f|SHIFT,    // "          0x22

And likewise for the other keys. So, the @ symbol moves to where the quote is in the US keyboard. So change the last line in my example from:
0x1f|SHIFT,    // @          0x40

to:
0x34|SHIFT,    // "          0x40

Those two changes "swap" the locations of the " and the @ symbols.

As noted in the comments, keys marked ¬ and £ do not have a 7-bit ASCII representation so you will not be able to put them in the table (there is no entry for them).

Thanks for this, I'm just getting down to figuring this out myself and this info is really helpful.

I am not aware of a UK layout file for the Arduino Keyboard library. The
library itself does not have such a layout, and a Web search returned
nothing. You may consider creating this layout yourself. The
documentation of Keyboard.begin() states:

Custom layouts can be created by copying and modifying an existing
layout. See the instructions in the Keyboard library’s
KeyboardLayout.h file.

The file KeyboardLayout.h does indeed have detailed
instructions for this. Are they clear enough? If not, please tell me: I
wrote those instructions, and I may try to update them if something in
them is confusing.
Do you feel like trying to create this layout yourself? If so, it would
be nice if you could submit it to the official library as a pull
request. This way other users of the library may benefit from your work.
If you don't feel like doing it, I may give it a try (I have already
created a few of them). In this case, I would appreciate if you could
submit an issue, just to show the maintainers that there is some
interest in having the library provide this layout.

Thanks for your help, I guess I will have a go at creating a KeyboardLayout_en_UK.cpp file

I'd suggest that the one addition which could usefully be made to those instructions is the explicit statement that this only supports 7-bit ASCII. So while a UK keyboard has keys marked ¬ and £, there are not corresponding ASCII codepoints.

@MarkMorganLloyd: “7-bit ASCII” is a pleonasm. Would the sentence “Non-ACSII characters are not supported.”, added to the end of the first paragraph, be suitable? Or should I add “anything outside the range NUL..DEL” in parentheses to explain “Non-ACSII characters”?

@EdgarBonet Either of those forms should do, but remember that a lot of people don't really understand that various codepages etc. based on "extended ASCII" are well outside the original ASCII specification. My experience is that the terms "7-bit ASCII" and "8-bit Extended ASCII" are well-understood, even though I know at least as well as you do that neither is strictly correct.

@MarkMorganLloyd: OK. I submitted the clarification in a pull request

@EdgarBonet I have created a KeyboardLayout_en_UK.cpp file and added to my Arduino keyboard library also I changed Keyboard.h to include the line: extern const uint8_t KeyboardLayout_en_UK[];  I am not very familiar with GitHub and not confident about making a pull request at this time.


text:
How to set ESP32 RTC clock source
According to the manufacturer's link below, the default RTC timekeeping in the ESP32 is supposedly based on Internal 150 kHz RC oscillator.
Apparently, there is another option called Internal 8.5 MHz oscillator, divided by 256 (~33 kHz) that has better stability without needing an external crystal. That link goes on to say that

To modify the RTC clock source, set CONFIG_RTC_CLK_SRC in the project configuration.

All good information but NO EXAMPLES given. Can anyone point me to an example showing

how I can prove what the current clock source is, and
how to set actually it?

https://docs.espressif.com/.../system/system_time.html

The default is 150kHz RC, see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html#rtc-timer-clock-sources

@hcheung Please don't answer questions with links that you have not read. I know all about the defaults and other options. The document does not show how to go about changing it.

Please don't assumed that I didn't read the document just because you don't understand it. The document is clearly said that "To modify the RTC clock source, set CONFIG_RTC_CLK_SRC in project configuration", it further provide the link to CONFIG_RTC_CLK_SRC page which again clearly indicated that the configuration is part of Component config > Hardware Settings > RTC Clock Config which you can find it here.

In summary, you are presuming that it can be dynamically change via programming, but it is not, you need to Edit sdkconfig.defaults file, set CONFIG_ESP32_RTC_CLK_SRC_INT_8MD256=y and run idf.py to build it.

@hcheung my apologies then. Too many people post a link assuming it answer the OP question. The is no "sdkconfig.defaults" on my system,. There plenty of sdkconfig.h for each board, and there is one file "sdkconfig" file with no extender. The .h files indeed have macros defining those options.
I did make the change you suggested in that file, also commenting out the default one. But I do not have an idf.py file, and would not know how to run it. Is there a document that offers all the steps and where to get the needed tools?
Thanks in advance.

idf.py is part of esp-idf tools.


text:
How to arrange my code block to make it work smooth and correct
I currently working on my system that automatically water the plant based on the water requirement of the plant for one day . I have a java application that let the user input the water requirement of the plant and then the java application send it to arduino the arduino will receive the data and put it inside the variable and it will be use .. I use the following sensor/module ..

SOIL MOISTURE 2 PCS.
WATER FLOW SENSOR 2 PCS.
SOLENOID VALVE 2PS
WATER LEVEL SENSOR 1 PCS.
HUMIDITY SENSOR 1 PCS.
REAL TIME CLOCK DS3231

The data that the java app will send is the water requirements for 1 day for example 400ml , the 400ml will be used by the water flow sensor if the sensor reads that its already 400ml has pass in the tube the solenoid will close the pipe . And my system has a water tank the water sensor is attach to it and will check if the water in the tank is not low if low the arduino will send that data into the java app .. All the sensors reading will be save into database using the java application ..
Here is My Whole code for arduino , its not finish yet because i'm stuck thinking on how to arrange my code blocks . Sorry for my English please bear with me ..
#include <DS3231.h>

//PINS
#define MOISTURE1 A15
#define MOISTURE2 A14
#define WATERFLOW1 A13
#define WATERFLOW2 A12
#define HUMIDITY A11
#define RELAY1 9
#define RELAY2 8
#define ALARM 2

DS3231  rtc(SDA, SCL);
int DELAYNI = 1000;
void setup() {
  // put your setup code here, to run once:
pinMode(MOISTURE1, INPUT);
pinMode(MOISTURE2, INPUT);
pinMode(WATERFLOW1, INPUT);
pinMode(WATERFLOW2, INPUT);
pinMode(HUMIDITY, INPUT);
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);

rtc.begin();

Serial.begin(9600);
}

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

  //Some Code here to get the data send by java app and then assign it to each variable

  readMoistureStatus();
  readWaterLevel();
}
void readWaterLevel(){
  ///Some code here
}

void readMoistureStatus(){

 int  moistureOneSensorValue = analogRead(MOISTURE1);
 int  moistureTwoSensorValue = analogRead(MOISTURE2);

   // checking the moisture range for the first soil moisture
  if(moistureOneSensorValue >= 700){
    // in case of dry soil:
    RelayOne();

     delay(DELAYNI);
  }
  if((moistureOneSensorValue < 700) && (moistureOneSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureOneSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }
   //
   //
   // Checking the moisture range for the second soil moisture

  if(moistureTwoSensorValue >= 700){
    // in case of dry soil:
    RelayTwo();

     delay(DELAYNI);
  }
  if((moistureTwoSensorValue < 700) && (moistureTwoSensorValue >= 300)){
    // in case of moist soil:

    delay(DELAYNI);
  }
  if(moistureTwoSensorValue < 300){
    // in case of soggy soil:

    delay(DELAYNI);
  }

}

void RelayOne(){
  //Close or Open the Solenoid

  //Read the water flow if the set point is reach it will close the solenoid using the relay
}

void RelayTwo(){
  //Close or Open the Solenoid

 //Read the water flow if the set point is reach it will close the solenoid using the relay
}

And also how often the arduino read the sensors value ? Or I just let the user decide the interval of reading the sensor and then save to database

I think that overall your code looks good but I don't understand why you need to log data every 1 seconds (DELAYNI = 1000; is approx 1 sec).
Although there's nothing wrong in placing the
if(moistureOneSensorValue >= ...)
...
...

codeblock in your readstatus(), it's best to separate this out into a dosomething function. Alternatively, you can read the moisture status in the void loop() itself and then place a switch case in the doSomething() function.
You can also use the data from the RTC to check moisture and do something:
void setup(){
...
time = DS3231.time(); //Time at the beginning
}

void loop(){

timeElapsed = now() - DS3231.time();//seconds elapsed

if (timeElapsed >= DELAYNI){
    moisture1 = analogRead(MOISTURE1); // Read ADC value
    moisture2 = analogRead(MOISTURE2); // Read ADC value
    updateDatabase(time, moisture1, moisture2, relay1, relay2); //update the moisture values and statuses of the relays to the database
    switchRelays(moisture1,moisture2); // switch relay1 and relay2 depending on vals
time = DS3231.time(); // Update the time

    }

}

authors: พงศ์พิช แก้วแพรก


text:
Controlling 5 DC motors with Arduino
I am looking to purchase the correct hardware to be able to control 5 DC Motors from an Arduino (UNO preferred, MEGA if necessary).
The Specs of the Motors are as follows: 12 V nominal, 3 → 12 V dc, 794 gcm, 100 rpm, 0.394 W
What would be your recommendations for how to set this up? As I am fairly new to circuitry a circuit diagram would be helpful along with the recommendation of what shield or drivers to use. Thank You

Do you need constant speeds or variable?  Do you need to sense the speeds?  Do you need reverse as well as forward rotation?

Constant speeds. I do need reverse and forward

Since youre new to circuitry - you should know an  actual  circuit for this is not hard to make. Its not something I'd buy a shield  for.

There are currently no expansion boards (shields) for the Arduino platform that are designed to do what you're asking of it. At most you'll find shields that can support up to 2 maybe 3 motors. My recommendation for a beginner would be to experiment with a breakout board like this one: https://www.sparkfun.com/products/9457 It's compact and can easily control 2 of the motors you need, three together and you could control up to 6.

would I need any other components to work with these?

No, nothing beyond a little soldering equipment, this blidr tutorial may help you, http://bildr.org/2012/04/tb6612fng-arduino/ . Note that for the motor direction pins on this breakout, if all your motors are spinning in a fixed direction, you could connect the proper pins to +5v and Ground without having to sacrifice more digital pins for it.

I would suggest to use the shield that is directly attachable to the Uno, for example: http://playground.arduino.cc/Main/AdafruitMotorShield. So everything you need is Uno, this shield and motors. No soldering.


text:
Connecting multiple TFT panels to Arduino Uno via SPI?
Is it possible to connect more than one TFT screen (like this one or similar: https://www.adafruit.com/products/1651) to an Arduino Uno?
I'm wanting to connect and control two color screens at once; note the touch functionality of the one linked above isn't really necessary, I just like the size and overall build. They have a version that works like a shield and sits on top of the Arduino, which would work I suppose if I bought another unit for the other screen. The breakout board version is more flexible but I don't know of a way to control two screens that require that many pins.
Any suggestions?
Thanks

Yes, you can. All the SPI pins (MISO, MOSI and SCK) are all shared between the panels. You can even share the D/C and RST signals. The only signal that needs to be separate is the CS pin since this is the pin that identifies which panel is actively receiving commands and data at any one time. Also you don't need to connect up the MISO pin at all, since that is only connected to the SD card slot, not the TFT screen.
So each screen that you add just requires one more pin to be used. One screen uses 5 pins. Two screens use 6 pins. Three screens use 7 pins, etc.
And yes, for this the breakout version would be easier to work with than the shield version.

Similarly, would communicating in 8-bit mode be possible? If draw speed was a concern that is

Sure. The data lines are shared and wr and Rd are unique.

Actually for 8 bit parallel you can share RD and WR as well. It's the CS pin on there that is unique. I couldn't remember if there was a CS or not, and certainly on the 8-bit parallel TFT I just grabbed from my box there is a CS pin.


text:
Arduino - RF 433 Mhz transmitting string and but receiving ASCII values of those characters
When I am using RF 433 MHz module with ARDUINO MEGA then it is transmitting any text or anything in ASCII values. Now how to decode those ASCII values to alphabets? If I use ASCII conversion programme then what if I send a number and that conversion program converts that number also to text or related ASCII character? please suggest any way.

Nothing gets "converted" - ASCII values and text are one and the same thing. It's all down to how you print it.

Lokesh, to expand on what Majenko said when you transmit something over this sort of link you are transmitting either a 1 or a 0.  When 8 ones or zeros arrive you have a byte.  A byte has a value of between 0 and 255 and what this means is entirely up to the 'protocol' you are using.
In your case your sending program is sending a letter, lets say A.  Now the A that you are sending is held in memory as a byte with the value of 65, 65 is the ASCII [code] for A. So 65 is sent as 8 different transmissions to the other end of the link and is received, built back into a byte and your program receives a byte with the value of 65.  Your receiver program is using the same protocol as your transmitter program, so it 'knows' you don't meant the number 65, the colour green or an elephant riding a bicycle, you mean the character A.
To show that A you might need to cast the data you receive to a character i.e.
unsigned char rxData = 0;
Radio.ReceiveData (&rxData, 1);
Serial.println((char)rxData);

An elephant riding a bicycle is 64, not 65.


text:
Control LED strip IR controller using Arduino
Is it possible to connect to one of these, which run at 12v, to turn on the LED strip using an ESP8266? It doesn't matter if it's an Arduino or the ESP8266, both should be able to do this. The board looks like this:

If I turn on the red light, the "R" gets grounded and therefore applies 12v to the rail. The 3 MOSFETs on the images are P0903BDG MOSFETs.
Alternatively, I can hook into the IR signal and send an IR signal using the ESP8266. That would be really awesome, as it only requires 3 wires. How that is possible, I'm not really sure, though.
I know it's possible to make your own circuit using IRLZ44N MOSFETs, which I have done before, but I want to try and use as much as this circuit as possible.

@LookAlterno It does not, unfortunately. It's just a simple controller like these: https://www.google.com/search?q=led+strip+ir+controller&tbm=isch

@LookAlterno Yeah exactly.

Desolder the IC's connected to the MOSFETs and use your Arduino to drive the MOSFETs.

I tried to do the same thing with hooking up an IR LED on a Raspberry Pi. It worked pretty well but the chip on the receiver board could not take fast switchings. I ended up doing my own PCB.
The problem is that the chips run at voltages higher than you would use for an ESP8266 or Arduino. This will be the biggest problem if you want to supply it with the voltages available on the board.
I think the safest thing is to see if you can simulate IR input by just connecting to GND and OUT of the IR receiver port.

Yeah I did the IR LED as well on my ESP8266 actually. I could both send NEC commands and receive them, meaning I could send commands to the LED strip or another ESP8266 using IR. Worked fine but I don't like IR. What do you think it would take to send the IR commands without the actual IR? Is it just a matter of taking some "IR receiver" code, then plugging that into the IR OUT "connector"? That might work.


text:
Powering an Arduino Mini Pro using a CR2032 battery as a remote control
I'm looking into making my own remote control using an Arduino Mini Pro and some RF transceivers. The receiving end won't be a problem, but the remote will. I want to make it as small as possible and consume as little energy as possible.
Is it possible to turn on the Arduino Mini Pro at the push of a button, while also using that same button to trigger a piece of code? That way I can cut the power when it's not being pressed.
I will make sure to code it, so I have to hold the button down for 1-1.5 seconds, so it has time to "boot up" and send the RF signal, but should power off immediately when I let go of the button.
What kind of power should I expect from a single CR2032 battery? I have a couple of NRF24L01 RF transceivers laying around together with an Arduino Mini Pro.
If we assume this, while looking at this sheet:
NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 0.19 mA @ 2V = 2100+ hours

Even if we just say 600 hours and it takes 2 seconds to turn something on, I should be able to run it  600H*60M*60S = 2.160.000 seconds = 1.080.000 times. If my calculation isn't completely wrong, it means I could literally turn it on a million times in the worst case scenario.
I hope that calculation is wrong, because that seems crazy.
EDIT: I could desolder the LED and regular as well, if that won't damage it too much. Just to consume power. I've read I can basically run it for free then.

You should take a look at ATmega328P datasheet

On page 2, it says: Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby, and Extended Standby

These are the modes which can be used to put Arduino Pro Mini in stand-by. You can search for them at datasheet and choose the only that better applies to you. To learn more about sleep mode and other methods to save battery, you can take a look at this source: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery
On the datasheet of battery, you should pay attention at its charge:

Typical Capacity: 240 mAh (to 2.0 volts)

This means that from 3 to 2 Volts, it relases 240 mAh. This is the charge you can expect to use. Using the consumptions rates you posted above
NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 240 mAh
Time: 240mAh/(10mA + 5mA) = 16 hours

Which is not so much. To increase this autonomy, the link I posted above is quite useful because it will show you alternatives like removing the voltage regulator that will reduce drastically your consumption. Now, if you feel really adventurous, you may take a look at how to underclock your board: Arduino pro mini @ 1MHz - 1.8V. This is a very efficient way to save power where clock frequency is not a must.

EDIT after comments:
The 16 hours were computed using 5mA for the Arduino (which is a value for power consumption that can be expected on active mode) and 10mA for the NRF24L01. You have to estimate a sleep mode consumption for both and a percentage of time in sleep mode if you want to estimate an autonomy. At the link I sent you about sleep mode there are some tables with power consumption in different configurations.
ATmega328P can run with a minumum of 1.8 Volts, while nRF24L01+ can while with a minimum of 1.9V - see datasheet. So probably you are going to have a little bit more than 240mAh to work with. Your battery won't have 3v all the time. It is going to start with 3V (maybe a litte bit more) and gradually reduces it voltage as the charge is provided to the circuit. Once the voltage goes bellow 1.9V, nRF24L01+ won't be guaranteed to work properly.
Definitely, to sleep the Pro Mini, just waking it up when using, is the right way to design this circuit. According to this reference I posted above, power consumption for Arduino should be 0.90 mA. At the item 5.1 of nRF24L01+ datasheet, it is described that it consumes 0.32mA at standby mode II. If you sleep the Pro Mini for, let's say, 90% of the time, without removing leds or voltage regulators, you can estimate that
t = 240mAh * (0.1/(5mA+10mA) + (0.9/(0.9mA+0.32mA)) = 178.65 hours

If you use strategies to reduce Arduino power consumption, like the ones I send you above, you can increase this time. You will also save power if you change nRF24L01+ from standby mode 2 to standby mode 1. Check the database to see which one fit your needs.

Thanks for your reply! The 16 hours would mean when it's actually bursting RF signals out into the air, right? So I could power the ATmega328P Arduino Mini Pro and the RF signal for 16 hours before the battery is completely drained (if we assume it stays at 3v all the time)? Would it be efficient enough to simply sleep the ATmega328P, then wake up with the push of a button? Would that keep the CR2032 battery running long enough, so I can use this for months?

I uptated the answer.

If you have a single button, it is useless to use the button to trigger the piece of code. The fact that you are powered on means that the button is pressed.

simulate this circuit – Schematic created using CircuitLab
Of course you need a 3.3V Arduino PRO Mini...
If you have multiple buttons, you can have different circuits to detect this.
Solution 1
Use a set of diodes to power the board, then another to detect the digital pins.

simulate this circuit
The second set of diodes is needed because you should not show to the atmega pins a voltage greater than Vcc+0.5V. Since a pull-down resistor is needed, if you want you can replace the second set of diodes with 2k2 resistors.
Solution 2
Again use a set of diodes to power the board, but then decode the value through an analog reading

simulate this circuit
You will need to experiment a bit to figure out the thresholds. For instance, with the values I wrote, you can expect to read from the ADC a value around 1000 for the button 1, a value around 600 for the button 2, and 300 for the button 3; for this reason, you write
int buttonRawValue = analogRead(A1);
if (buttonRawValue > 800) {
    // Button 1 was pressed
}
else if (buttonRawValue > 450) {
    // Button 2 was pressed
}
else {
    // Button 3 was pressed
}

This will require some tuning, but I think it can work.
Solution 3
You can power the board through a transistor (I usually prefer small MOSFETs)

simulate this circuit
You will need to find a MOS with a very low Vgs-th, sinceit should fully turn on with 1.5V. This solution has the advantage of not wasting the small voltage you have (while the other ones waste around 0.3V for Schottky diodes and 0.6V for PN diodes).
Personally I'd go with solution 3, since it is also easy to let the atmega control the power (simply attach one of the digital outputs to the cathodes of the diodes, and the ATMEGA will be able to force power on until it has finished the operations).
As a side note, I would recommend you not to use a pre-made board, but use a bare ATMEGA328P in this project. You can experiment with another arduino board, but then use the arduino board to flash a bare ATMEGA; you will get rid of all the useless things. You can avoid using a crystal and a voltage regulator, so your circuit will consist only of the components I used in the schematics and a 100nF capacitor between the VCC and GND pins of the microcontroller.
And... Don't flash a bootloader. Use another arduino board to flash the microcontroller, not a serial peripheral. This is because the bootloader is useful, but at boot it wastes some seconds (and you need to be as quick as possible)