text:
Strage delay needed after Serial.read()
I'm using a RedBear Duo to read the Serial writes from a RedBear Nano v2. Basically, I use a digital pin of the Duo to raise an interrupt on the Nano. Once, the nano catches the interrupt it writes on its Serial.
You can find a minimum working example below:
RedBear Duo
#include <Wire.h>

/*BLE and WiFi setup*/
#if defined(ARDUINO)
SYSTEM_MODE(MANUAL);
#endif

char incomingByte;   // for incoming serial data

void setup() {
    Serial1.begin(115200);     // opens serial port, sets data rate to 9600 bps
    delay(500);
    Serial1.println("Begin!");
    Serial2.begin(115200);

    pinMode(D5, OUTPUT);
}

void readSerial() {
    while (Serial2.available() > 0) {
        incomingByte = Serial2.read();
        Serial1.print(incomingByte);
    }
    Serial1.println(" ");

}

void loop() {
    digitalWrite(D5, HIGH);
    readSerial();
    delay(2);     // Here's the delay I'm talking about
    digitalWrite(D5, LOW);
    delay(1000);
}

RedBear Nano
uint8_t fire;
void task_handle(void) {
    fire = 1;
}

void setup() {
    Serial.begin(115200);
    fire = 0;
    pinMode(D4, INPUT);
    attachInterrupt(D4, task_handle, RISING);
}

void loop() {
    if (fire == 1) {
        fire = 0;
        Serial.write("hello ");
        // Serial.println("fire");
        digitalWrite(D13, HIGH);
    }
    delay(150);
}

I found this question (https://electronics.stackexchange.com/questions/28739/arduino-delay-of-1ms-necessary-between-serial-read-and-serial-write), and I understood that the problem might be the fact that it takes a while to empty the Serial buffer.
However, I tried to bring the baudrate at 500000 (more than 3x) and still if I change the delay to delay(1), the code is not printing what it has received on the Serial.
I'm trying to understand what is really going on and why I need this delay(2).
Thanks a lot in advance!

declare the variable fire as volatile

Try this code: first delay produces 1ms pulse on pin D5. Without this delay the pulse could be too short for the nano to catch it (you can use delayUs and try finding the shortest interval that produces reliable result). We know that after this pulse, nano sends some data. So wait 100ms to collect it. If you call readSerial right after the pulse was sent, you won't get anything, because you need to wait at least for single byte transmission
void loop() {
    digitalWrite(D5, HIGH);
    delay(1);
    digitalWrite(D5, LOW);

    delay(100);
    readSerial();

    delay(1000);
}

This line is wrong:
attachInterrupt(D4, task_handle, RISING);

It should be:
attachInterrupt (digitalPinToInterrupt (4), task_handle, RISING);

In any case, attachInterrupt does not apply to D4, it is for D2 and D3 on the Atmega328P.
Note that the pin number is 4, not D4.


text:
Using an Arduino as a Human Interface Device that sends analog inputs
I would like to have an arduino board act as a human interface device that can send analog inputs like joysticks.
As it currently stands I see two aproaches to this issue:

Use the arduino hid library and program all the reports in myself. This should be fairly simple but I can't seem to find any recourses that I actually understand. I get the idea of reports but I dont get how the report format is described to the OS. I also dont understand how drivers on the pc side of things play into this whole equation.
Write some software that makes a serial connection with the arduino and uses java's robot functionality (or similar) to controll a joystick, if even possible. This method would be much easier but would feel overall less polished.

Thank you for your help in advance!

Option 3: Use a different board that supports hid joysticks out of the box.

https://github.com/MHeironimus/ArduinoJoystickLibrary does my first aproach. The limitations one what board it can be will not be an issue because I have an extra 32u4 board.

source: Stack Exchange

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

sort: votes


text:
sensor detection is too slow when another feature is added
Can anyone figure it out for me? I am new to arduino and 1sheeld, Completely beginner. In my project(Smart Cane For Blind) has currently two part. One is object’s distance detection by using ultrasonic sensor and another feature is Emergency feature. When the blind people lost his way he can press the push button to sent his location to his family member for help.
My problem is that when I integrate that two feature, The sensor part, the detection is too slow and weak.
#define CUSTOM_SETTINGS
#define INCLUDE_GPS_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_VIBRATION_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD
#define INCLUDE_TERMINAL_SHIELD
#define INCLUDE_MIC_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>

// Define Pins for Sensor 1
#define trigPin1 4
#define echoPin1 5

//Define Pins for Sensor 2
#define trigPin2 6
#define echoPin2 7

// Define Pin for VibMotor 1
#define motorPin1 12

// Define Pin for VibMotor 2
#define motorPin2 13

/* Define a boolean flag. */
long duration, distance, UltraSensor, UltraSensorTwo;
boolean isMessageSent = false;
float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();
//  PushButton.setOnButtonStatusChange(&Emergency);

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
}

void SensorHandler() {

  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;

  SonarSensor(trigPin2, echoPin2);
  UltraSensorTwo = distance;

  if (UltraSensor <= 60 && UltraSensor >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  }
  else if(UltraSensor < 45 && UltraSensor >=30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  }
  else if(UltraSensor < 30)
  {
   digitalWrite(motorPin1, HIGH);
   delay(50);
   digitalWrite(motorPin1, LOW);
   delay(50);
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }

  Terminal.print("SensorOne: ");
  Terminal.println(UltraSensor);

    // For VibMotor Two

  if (UltraSensorTwo <= 60 && UltraSensorTwo >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin2, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin2, LOW); // motor off
    delay(200);
  }
  else if(UltraSensorTwo < 45 && UltraSensorTwo >=30)
  {
    digitalWrite(motorPin2, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin2, LOW);
    delay(100);
  }
  else if(UltraSensorTwo < 30)
  {
   digitalWrite(motorPin2, HIGH);
   delay(50);
   digitalWrite(motorPin2, LOW);
   delay(50);
  }
  else
  {
    digitalWrite(motorPin2, LOW);
  }

  Terminal.print("SensorTwo: ");
  Terminal.println(UltraSensorTwo);
}

void loop()
{
//    Terminal.println("Test");
//    Emergency();

    SensorHandler();
    //delay(10);
    if (PushButton.isPressed())
  {
    Terminal.println("Button Pressed");
    //delay(100);
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Terminal.print("Message Sent");

//        SMS.send("0819033655",Message);
    delay(3000);
  }
  delay(1000);
}

The following code is after I fixed by learning BlinkWithoutDelay example but the vibration rate according to the distance seems not right. (When the object is closer, the vibration motor vibrate rate should be faster).
#define CUSTOM_SETTINGS
#define INCLUDE_GPS_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_VIBRATION_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD
#define INCLUDE_TERMINAL_SHIELD
#define INCLUDE_MIC_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>

// Define Pins for Sensor 1
#define trigPin1 4
#define echoPin1 5

//Define Pins for Sensor 2
#define trigPin2 6
#define echoPin2 7

// Define Pin for VibMotor 1
#define motorPin1 12

// Define Pin for VibMotor 2
#define motorPin2 13

/* Define a boolean flag. */
long duration, distance, UltraSensor, UltraSensorTwo;
//boolean isMessageSent = false;
unsigned long previousMillis = 0;
unsigned long interval = 1000;
float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();
  //  PushButton.setOnButtonStatusChange(&Emergency);

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
}

void SensorHandler() {

  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;

  SonarSensor(trigPin2, echoPin2);
  UltraSensorTwo = distance;

  if (UltraSensor <= 60 && UltraSensor >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  }
  else if (UltraSensor < 45 && UltraSensor >= 30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  }
  else if (UltraSensor < 30)
  {
    digitalWrite(motorPin1, HIGH);
    delay(50);
    digitalWrite(motorPin1, LOW);
    delay(50);
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }

  Terminal.print("SensorOne: ");
  Terminal.println(UltraSensor);

  // For VibMotor Two

  if (UltraSensorTwo <= 60 && UltraSensorTwo >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin2, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin2, LOW); // motor off
    delay(200);
  }
  else if (UltraSensorTwo < 45 && UltraSensorTwo >= 30)
  {
    digitalWrite(motorPin2, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin2, LOW);
    delay(100);
  }
  else if (UltraSensorTwo < 30)
  {
    digitalWrite(motorPin2, HIGH);
    delay(50);
    digitalWrite(motorPin2, LOW);
    delay(50);
  }
  else
  {
    digitalWrite(motorPin2, LOW);
  }

  Terminal.print("SensorTwo: ");
  Terminal.println(UltraSensorTwo);
}

void loop()
{
  //    Terminal.println("Test");
  //    Emergency();
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval)
  {
    previousMillis = currentMillis;
    SensorHandler();
  }
  if (PushButton.isPressed())
  {
    Terminal.println("Button Pressed");
    lat = GPS.getLatitude();
    lon = GPS.getLongitude();
    Message1 = String(lat, 8);
    Message2 = String(lon, 8);

    Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
    Terminal.print("Message Sent");

    //SMS.send("0819033655",Message);
    //delay(3000);
  }
  //delay(1000);
}

study the example sketch called BlinkWithoutDelay .... it will give you information on how to remove the delay() functions from your code

@jsotola , Thanks sir. I will try to learn it now!

it seems a bit faster but the vibration rate according to the distance is not seems right. here's my code after I added. can you please check for me mr.@jsotola. I will edit in my question code.

You should replace ALL delays with non-blocking code like in BlinkWithoutDelay. This will only work good, if you ditch all the delays

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


text:
Serial.read(); and state machine for AT commands
I have a strange type of issue: the index of the array doesn't increment and when I print the value from the serialdata[pointingfinger] it just gives me an empty space.
This is a state machine (I guess) that should check what is the current char that's being written into the array and its position to avoid searching it later. When we have a finished line it changes the bigger state machine to another mode (that checks if four chars further is the command) when the processing is done it should get back getting the next line.
This is Arduino Leonardo and Serial is the USB and Serial1 is where I send and receive AT commands.
const long interval = 1000;
static long currentMillis;

char plussignpoint = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256] = ""; //Array to store the chars before parsing

int rdpos = 0;

int pointingfinger = 0;

char timeen = 0;
byte stat0 = 0;
char futstat0 = 0;
char searchcharpos = 0;

char enabled = 0;

char searchchartype = 0;

char smsvalid = 0;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write("ATE0\r");
}

void loop() {
    if (millis() - currentMillis >= interval)
    {
      Serial1.print("AT+CCLK?\r"); //ask for the time

      enabled = 1;

      currentMillis = millis();
    }

    if (enabled == 1) {
      if (stat0 == 0) {
        if (Serial1.available () > 0) {
          pointingfinger++;
          serialdata[pointingfinger] = Serial1.read();
          if (serialdata[pointingfinger] == '+') {

            searchcharpos = pointingfinger;
            searchchartype = 1;
            futstat0 = 1;
          }
          else if (serialdata[pointingfinger] == '$') {
            if (smsvalid = 1) {
              searchcharpos = pointingfinger;
              searchchartype = 2;
              futstat0 = 2;
            }
            if (smsvalid = 0) {
              stat0 = futstat0;
              pointingfinger = 0;
            }
          }
          else if (serialdata[pointingfinger] == '\n') {
            stat0 = futstat0;
            pointingfinger = 0;
            enabled = 0;
          }
          else if (serialdata[pointingfinger] == '\r') {
            stat0 = futstat0;
            pointingfinger = 0;
            enabled = 0;
          }
          else {
            stat0 = 0;
            pointingfinger = 0;
          }
        }

        if (pointingfinger == 255) {
          pointingfinger = 0;
          enabled = 0;
        }

      }
    }
}

EDIT: I forgot to include what AT commands it should parse:
Arduino: AT+CCLK?

SIM800H: +CCLK: "04/01/01,01:35:31+00"

         OK

What data do you get from Serial? Your problem heavily depends in that data, so please include it.

When checking value of smsvalid you use assignment operator = instead of comparison operator ==.
            else if (serialdata[pointingfinger] == '$') {
                if (smsvalid == 1) {
                    searchcharpos = pointingfinger;
                    searchchartype = 2;
                    futstat0 = 2;
                }
                if (smsvalid == 0) {
                    stat0 = futstat0;
                    pointingfinger = 0;
                }
            }

And also you increment pointingfinget prior writing to serialdata buffer. This means that the first character will be written at index 1. So the first character serialdata will be zero, which means empty string.
      pointingfinger++;
      serialdata[pointingfinger] = Serial1.read();

There are many issues with your code, I pasted your code to online gdb c++ compiler, so you can play with it and see what is going on.
Those AT state machines aren't easy to finetune on Arduino. I spent a lot of time debugging similar code and found out that the best way is to unit test all possible situations in visual studio or xcode. Arduino is just C++ and if you copy/paste some portions of your code to C++ IDE, after implementing few functions or classes it should work. For example, to make your code working in XCode, I had to implement some dummy Serial1 class and simplify the loop code:
class _Serial1
{
    std::string buffer{"OK\r\n"};
public:
    int available()
    {
        return (int)buffer.size();
    }

    char read()
    {
        char c = buffer[0];
        buffer.erase(0, 1);
        return c;
    }
} Serial1;

void loop() {
    if (enabled == 1) {
        if (stat0 == 0) {
            if (Serial1.available () > 0) {
                pointingfinger++;
                serialdata[pointingfinger] = Serial1.read();
                if (serialdata[pointingfinger] == '+') {

                    searchcharpos = pointingfinger;
                    searchchartype = 1;
                    futstat0 = 1;
                }
                else if (serialdata[pointingfinger] == '$') {
                    if (smsvalid == 1) {  // ==
                        searchcharpos = pointingfinger;
                        searchchartype = 2;
                        futstat0 = 2;
                    }
                    if (smsvalid == 0) { // ==
                        stat0 = futstat0;
                        pointingfinger = 0;
                    }
                }
                else if (serialdata[pointingfinger] == '\n') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else if (serialdata[pointingfinger] == '\r') {
                    stat0 = futstat0;
                    pointingfinger = 0;
                    enabled = 0;
                }
                else {
                    stat0 = 0;
                    pointingfinger = 0;
                }
            }

            if (pointingfinger == 255) {
                pointingfinger = 0;
                enabled = 0;
            }

        }
    }
}

And the compiler immediatelly pointed me at the incorrect assignments and also I was able to debug the code step by step and see what is happening inside.
In my situation I was interfacing SIMCOM900 gprs module and I made a state machine that allows me to write code like this:
virtual void Program()
{
    switch (Pc())
    {
        case 0: _ASSERT(strlen(mApn)>0);
                Stream() << "AT+CSTT=\"" << mApn << "\",\"\",\"\"\r\n";
                break;
        case 1: Expect("OK\r\n");
                if (Expect("+CME ERROR")) { Error("CME Error when attaching apn"); Return(false);}
                if (Timeout(25000)) Return(false);
            break;
        case 2: Stream() << "AT+CIICR\r\n"; break;
        case 3: Expect("OK\r\n");
                if (Timeout(15000)) Next(); break;
        case 4: Stream() << "AT+CIFSR\r\n"; break;
        case 5: if (ReadIpAddress()) Next();
                if (Timeout(2000)) Return(false); break; // longer?
        default: Return(true);
    }
}

Here is a bit older version of it:
https://gist.github.com/gabonator/88b80d9c6b16d699d6f4234ebc3a2587

wow I didn't know of such way to debug Arduino programs! Thanks! In the online compiler is cout printing chars one by one and not the whole array or I am writing them to the same index?


text:
samd21 linking, change the base addresse from the default
I'm working on creating a safe firmware upgrade for my adafruit feather m0.
I understand from my CTO that wrote the previous upgrade that for either samd21 or all arm m0 (not sure which) the compiler compiles non relative addresses, meaning bx 0x3000 will jump to address 0x3000 and not 0x3000 bytes from my location.
My goal is to split the flash into 4 banks:

bootloader (2k)
user data
firmware #1
firmware #2
which firmware will be booted is up to a flag in the flash do decide.
i understand from my predecessor this is an issue since firmware#2 when loaded to ram might not run.
I disagree and do believe simple changes in the .ld script should accomplish the task.

My only question to  you guys is changing the .ld script .text address is enough ? i know the bootloader jumps to an address that was defined in the  .ld script if it's not 0xFFFFFF (if the flash was written to).
do i ned to change the .ld script to include two .text sections ? do i need to also define how they reside in the RAM as well ?
any examples ? hint ?
Thanks.

Have you looked at the Samd21 datasheet?

The data sheet explained in detail how the samd21 memory is laid out including the boot loader section. I have no idea what you mean about .id script what ide are you using? Also search google for samd21 application note AT07175. A good tutorial on how to program the bootloader

the basic ld script shows me the basic memory layout and defines the variables that later on the bootloader uses, i don't need the datasheet for that. ld script and not id script is a GNU script for the ld  (linker) that defines the layout in the binary and later on in the flash and memory layout.

A typical LD script consists of two sections - one that defines memory ("MEMORY") regions, and another that defines what to put in those memory regions ("SECTIONS").
To carve holes in an existing memory layout it is usually enough to just change the first section - the part that defines the layout of the memoy. Shrink and move existing blocks of memory and insert new ones.
For example you may have this at the moment:
MEMORY
{
  FLASH (rx) : ORIGIN = 0x00000000+0x2000, LENGTH = 0x00040000-0x2000 /* First 8KB used by bootloader */
  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

There is a hole already defined of size 0x2000 at the start of flash, and the sketch is loaded from 0x2000 onwards.
You may want to shrink and move that, and add a "user data" chunk. It's enough to just go:
MEMORY
{
  USERDATA (rx) : ORIGIN = 0x2000, LENGTH = 0x1000
  FLASH (rx) : ORIGIN = 0x3000, LENGTH = 0x00040000-0x3000
  RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000
}

(I collapsed some of the maths cus it's pointless).  Now the flash area (where the sketch goes) has been shrunk by 0x1000 and moved an extra 0x1000 up the memory map. A USERDATA chunk has been inserted which you can then use later on if you so wish.
To make things get put in there by the linker script (you don't need to change anything else to move the sketch data...) you can define a new section in the later part of the linker script:
.userdata :
{
    KEEP(*(.userdata))
    KEEP(*(.userdata.*))
} > USERDATA

That should then place anything that you put in a .userdata section (or a subsection within that) within your sketch into the USERDATA chunk of flash - separate from your sketch.
(sketch)
const uint8_t __attribute__((section(".userdata"), used)) data[] = { 10, 100, 123, 177, 221, 49 };

However, if you plan to use it like EEPROM and only write to it using code in your sketch then you don't need to worry about anything like that - just carve out the hole.  You can also provide some globals to help with your code, though:
(linker script)
PROVIDE(userdata_start = ORIGIN(USERDATA))
PROVIDE(userdata_length = LENGTH(USERDATA))

Then you can use those in your program to know where the USERDATA chunk is and how big it is (ideal if you ever choose to change it - no need to change your code, only the linker script).

tn the basic ld script at least the one i have the bootloader is not "holed" from the script it's part of it, it cannot be written to due to the use of fure 4 register i think that protects the first X bytes i think 16K in arduino's default.
In any case  the ld script also defines a .text region that is later on referred to from the bootloader and uses volatile __asm("bx ...") to jump  to that address if the parallel flash address meant for the sketch has code and is not 0xffff (which means it was erased).
how does the script "links" between the .text on the flash and the ram area ?

what i need is to compile my sketch once when it's base ram area is defined as X and flash X' and once when it's base is Y on the flash and Y' in the RAM. again as i understand all memory addresses are not relative.

Good point. The existing bootloader doesn't have a clue. The bootloader and the linker script both have to agree on what they are doing. If you change the linker script to start executing from a different area then you must also change the bootloader to jump to that area. There is no way for the bootloader to know anything unless you tell it.

that goes without saying :) i need to mark the beginning, just like it's marked today and get the bootloader to have both addresses or update the address somehow during the firmware upgrade. i'll think of that later on, the real question i guess is lets say i move the .Text segment 0x4000 bytes up the flash memory do i need to relocate it in the script in RAM as well ?  your answer says nothing much about the RAM just FLASH so i'm not sure.

What is there to "relocate" in RAM? RAM is separate to flash. Moving stuff in flash has no connection to RAM at all. If you want to slice up RAM you can. But that has no relevance to moving stuff in Flash.

Some bootloaders use a dedicated "jump" location that is separate from your sketch. The linker script then "loads" that area with a jump instruction that sends it to the real start of the code. That way the linker script dictates where the program goes in flash - as long as that dedicated jump area is always the same.

But... would it just not be simpler to keep the sketch where it is and place your user data at the end of flash?

no, because user data area is needed but not the worst of my problems, i want two firmwares on one flash, for that i need  to either be able to boot from a different address then the default and to be able to compile a matching program for this region OR download a firmware to bank1 and have the bootloader itself copy it to bank 0, but if the write fails, i'm done, chip is toast, it's aproblem.

Then you need to split the flash 50/50 with a little left over for configuration. Two separate linker scripts, one for bank A and one for bank B. Upload bank A, verify bank A is correct, change boot flag to boot from bank A. Then upload bank B, verify bank B is correct, and flip the boot flag for bank B. The bootloader can do that flipping of banks for you once the upload is verified I guess. Custom bootloader required, of course. And some off-line method of remembering what bank is currently in use so you compile the right version.


text:
Cannot connect Mega to COM 9 but okay with other COM ports
I previously had issue updating code to Arduino Mega (clone). This is a continuation of this issue, but I think it should be made as separate thread.
After some time spending with it. Turns out if I change my USB port and connect it another USB port, the Mega is detected in port COM 6. I can upload code to the Mega using this COM port (COM6), although it shows an error sometimes. But if I change it back to the previous USB port (here the Mega detected as connected in COM9), I can't upload anything. You can see the error message in the above link.
I also have a Uno and tried uploading code to it through the same USB port (here it is detected as COM8), I can upload code.
I used the working COM (COM6) to upload Marlin FW to the Mega and I can connect my printer through the same COM port, but if I try it through COM9 I can't connect.
So why can't I use COM 9?
PS: I've been COM9 being used to communicate with the same Mega.

disconnect the arduino from your computer .... go to device manager in windows ... click view ... show hidden devices ... find COM9 and delete it .... plug the arduino back in and test the upload

Did that, i even uninstalled COM9. Still can't work with COM9

this is not an Arduino issue ..... i would say that it is some weird windows issue .... possibly something to do with the USB controller ... the two USB ports may be on different controllers .... you may also have an invalid device install file that windows is using to set up COM9 on that particular USB port

Is there anything I can do about this?

Install Unix on your PC?

This isn't really an Arduino question, it's more of a Windows question.

Check to see if you have !!! In your code. This will fail the upload.
More details here:  http://net-forces.blogspot.ca/2017/08/arduino-upload-timeout-and-in-string.html?m=1

It happens with whatever code I use (I tried arduino example codes). Like I said in the post, If I change COM port same code can be uploaded. but not with COM9.


text:
How do you convert a formatted print statement into a string variable?
I'm using the following routine to print the current time on the com port. I would like to capture this as a string so I can display it using ePaper.
    void printLocalTime()
    {
      time_t rawtime;
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo))
      {
        Serial.println("Failed to obtain time");
       return;
      }
     Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
    }

produces -

Saturday, May 12 2018 12:18:27

That's clever. How are you getting Serial.println to respond to that format?

try CStringBuilder from StreamLib

@Majenko, it is ESP32 Arduino core package

Oh, so nothing to do with Arduino then. It's non-standard functionality.

Personally I'd use sprintf() to place things into a char array - though you'd have to do the textual formatting (day names, etc) yourself.  Or the standard C library functions may work for you (or they may not).

It probably overloads to call strftime (http://www.cplusplus.com/reference/ctime/strftime/)

To achieve what you want you probably want to use the "string format time" function strftime (docs). You would write the result in a character buffer, which you can also print directly without having to convert it to String object.
So, the following code should work:
void printLocalTime()
{
  time_t rawtime;
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo))
  {
    Serial.println("Failed to obtain time");
   return;
  }
  char timeStringBuff[50]; //50 chars should be enough
  strftime(timeStringBuff, sizeof(timeStringBuff), "%A, %B %d %Y %H:%M:%S", &timeinfo);
  //print like "const char*"
  Serial.println(timeStringBuff);

  //Optional: Construct String object
  String asString(timeStringBuff);
}

The overload for Serial.print also does this exact same thing:
size_t Print::print(struct tm * timeinfo, const char * format)
{
    const char * f = format;
    if(!f){
        f = "%c";
    }
    char buf[64];
    size_t written = strftime(buf, 64, f, timeinfo);
    print(buf);
    return written;
}

Perfect, except  '&time_info);' should be &timeinfo);, Just what I was aiming for and missing.

@SimonMarkham corrected, thanks for spotting.


text:
Capacitors, Arduinos and Saving Data
In short, I have programmed and wired a speed/odometer and all is working well. However, I need to save data from the components/sensors once a power button is pressed, which has led me down the road of capacitors which seem to be the solution to my problem. Reading online about capacitors has dropped me in the deep end where I would like some help to see if I am thinking right.
I have attached a clearly very crude circuit which I need someone to confirm if I have it correct. If it's important, the whole system ran on 5v, powered by a 9v battery. Is a 5v Capacitor even the right one to use, considering that most components will not be active at the point of powering down?
OLD IMAGE: https://i.stack.imgur.com/aXhRi.jpg
NEW IMAGE: https://imgur.com/a/aHRpzE4
Just tried to download the app and it's not happening for some reason, so the link(edited) will have to do, I'm sorry.

Err.... no. That is wrong. Very wrong.

This will not work. You have the capacitor in series with the battery, so only an alternating voltage would reach the Arduino. The battery provides a DC voltage, which cannot pass the capacitor. Are you trying to provide power to the Arduino with the capacitor, when the battery is disconnected (so that you have some time to save your precious data)? Then the capacitor has to be in parallel to the Arduino power supply pins. Also you have to sense, if the battery is disconnected, so that the Arduino can sense this and save the data in EEPROM.

Also the capacitance of the capacitor is the important characteristic. You will have to use one with a big capacitance, to provide enough current for the Arduino and your other components.

Hmmm, hold on two secs, just gonna upload another image to confirm we are thinking alike. Thanks btw.

I wouldn’t do it this way. This would make sense if it was mains powered, but not when running of batteries. Use a push button. Then when the Arduino sees that the button is pressed, save the data and turn off the power to the Arduino using a transistor (one example). (On other Arduinos you could even put them to sleep, instead of using a transistor. But on an UNO that won’t work.)

Updated circuit uploaded.

Please don't provide links to images. Upload the images directly (using the image button above the editor).

The onsite image loader doesn't display properly using my mobile, it's just out of site to press the button.

So install the app?

I accept your point about the app, but with all due respect, it's everyone else that is being constructive in relation to the question. The image link is there now, but appologise if causes inconvenience to anyone.

@user4163554 Your "NEW IMAGE" link doesn't work. If a mod tells you to improve the question, you should do so. This isn't just about helping you, it's about the usefulness for future readers, and dead links don't help anyone.

Your "NEW IMAGE" is a link to some site "incur.com" that I have never heard of. My fellow moderator and I would like you to follow posting guidelines and actually post the circuit, not some broken link. Please read How do I ask a good question?.

once a power button is pressed - is it possible to make this power button just be an input to the Arduino, which then writes to the SD card and closes itself down?

Just slapping a random capacitor across your supply is not going to work. It's far more complex than that.
Yes, a capacitor is used to store a charge, but you have to manage that charge properly or you won't get much of a chance to do anything with it.
You need to:

Ensure that the discharge voltage remains high enough to run the chip for long enough to save your data (Note: writing to EEPROM causes an increase in current)
Isolate the capacitor from the rest of the circuit so it only powers the main chip
Monitor the incoming power to know when to do the saving.

A block-diagram of your setup may look something like this:

simulate this circuit – Schematic created using CircuitLab
In that diagram R1 and R2 form a voltage divider so you can monitor the battery voltage. C1 is a big capacitor. We're talking super-cap teritory here. Rated at 9V minimum. The regulator on the Arduino is ignored. You don't want to use it.  Two external regulators are now used to power your project - one direct from the battery to run the breadboard and other external components (which will lose power immediately the battery power is removed) and the other to run the main MCU and nothing else.  The second regulator is isolated from the rest of the circuit by D1, and the capacitor's charge then can only go through that regulator to power the main MCU.
That regulator for the MCU should be a switching regulator (DC-DC, "buck" regulator).  If you use a linear ("LDO") regulator you will waste power and your capacitor will have to be two or three times bigger than otherwise.  Even better would be to have a "buck-boost" regulator that will boost the voltage up to 5V when the input voltage drops below 5V, thus giving you even more life from the capacitor.
An alternative to all this is to use the 47C16 chip (5V) or 47L16 chip (3.3V) to store your data. This is an "EERAM" chip - an EEPROM with RAM buffer and automatic saving to EEPROM at power failure. It works through I2C and needs a capacitor connected to it directly to provide the backup power while it stores the data to EEPROM.

Thanks Majenko. Wow, I take back my comment, lol. It's gonna take a while for me to absorb this but will be right back.

One thing I will say now that you have mentioned EPROM, one of the components is an SD card where the data is being saved...I will just mull over your post though a no.

@user4163554 I have just added a paragraph about using EERAM instead.

@user4163554 SD cards don't play well with capacitor backup. They are far too power hungry and slow.

Thanks Majenko, I appologise for  the delay. I have rewritten my code, got rid of the SD part, now sending it to EPROM instead as mentioned by yourself. All is working good. Thanks again.


text:
How can I loop my code? For example after 30 minutes?
So I have this code which records the temperature and humidity using a DHT22 sensor. After it get's the values it then sends it to a webpage using PHP $_GET method, where that gets imported into a DB and emails (using PHP). But this only happens when I upload the code to my ESP8266; how can I know build in a loop function that it sends it every 30 mins or given time?
#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid     = "bbox2";      // SSID of local network
const char* password = "azerty";   // Password on network

WiFiClient client;
char servername[]="lucasdebelder.be";  // remote server we will connect to
String result;

float temperature;
float humidity;

#define DHTPIN 14

#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

void loop() {

}

void sendDataToServer(String temperature, String humidity)
{
  if (client.connect(servername, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /send_temperature.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
    client.println("Host: lucasdebelder.be");
    client.println("Connection: close");  //close 1.1 persistent connection
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

 while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
      result = result+c;
    }

  client.stop(); //stop client
  Serial.println(result);

}

void readSensor()
{

  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  Serial.println("Temperature:");
  Serial.println(temperature);
  Serial.println("Humidity:");
  Serial.println(humidity);

}

see BlinkWithoutDelay example

@Juraj Thanks for the answer, can you explain it a bit further? What code should I look at?

this tutorial and code ... https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

As stated in the previous answer. Code that needs to run more than one time should be called in the loop. But in this case the following solution will work as well.
You can end your setup with a call to the deepsleep(time_us) function which can be found in the ESP library. This will shutdown everything except for the on board RTC(Real Time Clock). So the circuit only draws a very little current (20 uA). This can be very useful if the circuit is powered by a battery.
The RTC has a signal on GPIO 16 (D0 on NodeMcu) which will be held HIGH while the given time is not reached. If the given time is reached the signal will be LOW.
If you connect GPIO 16 to the RST(reset) pin, this will make the ESP8266 start-up again. And thus the setup() will be executed again.

You execute the corresponding function only in the setup() function, which is called once on startup of the ESP. After that the loop() function is called repeatedly. The setup() function is meant to "setup" your code for it's functionality, which is then executed in the loop() function. For example you are begin the Wifi connection and connect to a network in there, because you need the network for your main functionality.
So you have to put the code from readSensor() until (and including) sendDataToServer() into the loop() function. This will execute this code repeatedly.
Then you have to introduce some concept of time, else your code will be executed very fast, effectively flooding your webserver. The easiest way would be to add a call to delay(30000), which would delay the code for 30s. But using delay is not considered good coding style, since it is basically busy waiting and you cannot do anything else during that time.
So to be able to add other functionalities in the future you can implement the time concept with non-blocking code. Take the BlinkWithoutDelay example from the Arduino IDE as reference. It uses the millis() function, which counts the milliseconds since the startup. You save a timestamp of the last execution of your code and wait until the difference between the current time (given by millis()) and your timestamp is greater than 30s. In this time the ESP can do other things, since it still goes through the loop() function undisrupted. Then after the timespan you execute the code and reset the timestamp to the current time.

Thanks a lot for this answer @chrisl but how can I implement something like this in my code? I can read and understand the code, but writing is something different for me. Could you try to have a look at my code? Thanks

Do you really understand, what the code does? The first part I mentioned is just cut and paste the measurement and send code from setup() to loop(). The second part is just the BlinkWithoutDelay example. You have to put the code you now have in loop() into an if(millis() - timestamp > interval) clause. This is described in the Arduino Documentation.

You really have to understand both concepts I tried to explain, or you will not be able to write your own code. Read the documentation. Do some starter tutorial for Arduino, where the setup() and loop() functions are explained. We cannot write your code for you. If something about my explanation isn't clear, I will try to explain it further.


text:
Setting 10 RGB Strips Independently from Single Arduino
I want to control 10 different 12V RGB LED strips independently from a single Arduino.
As a clarification - I've setup a bunch of NeoPixels and understand how to wire and control them independently. So now I'm looking to do something similar but rather than set color of individual LED's, I'm looking to set color of LED strips.
I've already done all the research to understand how to use a MOSFET to control a single strip - but that requires 3 PWM outputs on the Arduino board and I don't see any boards that have 3 * 10 = 30 PWM outputs.
Are there existing controllers that can abstract the power conversion and voltage control, so I can just send a color and brightness setting from the Arduino to each strip?

How many leds per strip (i.e. how much current per strip)?

How about using an extra chip as driver. Something like this. Or, if you haven't bought the strips yet, you can by the individually addressable strips. They don't need PWM, but only one pin for shifting out the data

@chrisl - thanks for the reply. The chip as a driver looks interesting. To then control the color on an RGB strip would I need to connect a Mosfet to each R/G/B output of the chip?
I want to avoid the neopixel strips as it's overkill for this project. I.E. I don't need to address individual LED's, but do want to control several separate strips.

@Gerben - I'm hoping to connect many strips together to form larger strips. So probably 10 strips with each strip being 60-300 LED's

Yes, surely you need a MOSFET for each PWM line, since LED strips with this many LEDs can easily draw multiple amps. I mentioned the Neopixels, because despite the individual addressing might be an overkill you don't need further components (besides a capacitor and a resistor). So this might be the cheaper solution, depending on the strips.

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLED library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".
Wiring:

Example code:
#include <FastLED.h>

#define NUM_LEDS 10
#define DATA_PIN 3
#define CLOCK_PIN 2

CRGB leds[NUM_LEDS];

void setup() {
    FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

int hue = 0;
void loop(){
    for(int i = 0; i < NUM_LEDS; i++) {
        leds[i] = CHSV(hue + i*255/NUM_LEDS , 255, 255);
    }
    FastLED.show();
    delay(20);
    hue += 2;
}

You'll need external circuitry to control the actual LEDs.
There is the WS2811 chip which can control 3 channels of 12V LED strips controlled though a single wire and you can daisy chain them controlling each strip individually. The protocol is the exact same as you'll find in individually addressable RGB LEDS. In fact it's the same IC that is embedded in those LEDs.


text:
LCD display weird characters
Im a newbie. I have a problem with displaying text in LCD (16x2). It shows incorrect message in the lcd. Here is the code and the picture that gives the wrong output : Kindly help Thank you.
#include "SIM900.h"
#include <SoftwareSerial.h>

#include "sms.h"
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

//gsm
SMSGSM sms;

int numdata;
boolean started  = false;
char smsbuffer[160]; //message
String newsms;
char n[20];
unsigned char i;
//lcd
int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
int outputValue = 0;   // value output to the %
int outputValue1 = 0;   // value output to cursor

void setup()
{
  //Serial connection.
  //gsm
    lcd.begin(16, 2);

  Serial.begin(9600);

//  lcd.setCursor(0, 1);
//  lcd.clear();
//  lcd.print("   Wireless Public       via GSM"); //55 chars
//  lcd.setCursor(0, 2);
//  lcd.print("    Notice Board "); //55 chars
   Serial.println("GSM Shield testing.");
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    started = true;
  }
  else Serial.println("\nstatus=IDLE");

  //lcd
  // set up the LCD's number of columns and rows:

};

void loop()
{

  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  // map it to the range of the analog out:
  outputValue = map(sensorValue, 0, 1023, 0, 100);
  outputValue1 = map(sensorValue, 0, 1023, 0, 200);

  //scroll = lcd.scrollDisplayLeft();
  if (started) {
    //Read if there are messages on SIM card and print them.
    if (gsm.readSMS(smsbuffer, 160, n, 20))
    {
      //lcd
      lcd.clear();
      lcd.setCursor(0, 2);
      lcd.print("SMS Received!");
      delay(2000);
      lcd.clear();
      lcd.setCursor(0,1);
      Serial.println(n);
      Serial.println(smsbuffer);
      lcd.print(smsbuffer);
      delay(1000);
//      lcd.clear();
    }
    delay(1000);
  }
}

What characters does Serial.println(smsbuffer); print to the serial monitor?

Yes In Serial Monitor it display the correct message that being send by the sender but when i print it in lcd it did not display the same output as what serial monitor display It only display the image that i upload.

Please edit your question to show the wireup of the LCD to your Arduino. Are you sure you didn't exchange one of the data line wires? (https://www.arduino.cc/en/Tutorial/HelloWorld) Is every message displayed wrong or just the contents of smsbuffer? Have you tried running a minimal sketch to just test the LCD with a 'hello world'?

I did print the smsbuffer in serial so that i can see the content of the message that being receive. Well in Serial it gives the correct output/content that the sender message. but when i print it in lcd it shows incorrect content.

@Megumichan, when i print it in lcd it shows incorrect content .... you are misunderstanding the problem ... the LCD is displaying exactly the correct content .... it is displaying what you are telling it to display ..... you have to figure out why your program is sending content that you do not want to see .... start by running the "helloWorld" demo

we start running the hello world demo in the lcd and yeah it runs perfectly in lcd. but when it comes to this code it didnt. it display only that in the picture that i upload

I print the smsbuffer content when its already receive a message and when i print the smsbuffer in the serial monitor the content is right and correct. but why when it comes to the lcd it isnt?]

Can you give an example of the string contained smsbuffer? What exact characters are those? The LCD library probably can only handly ASCII only, for the rest you would need to define custom character sets.

The first thing to try is replacing lcd.begin(16, 2) with lcd.begin(20, 4). The image of your LCD looks like a 20 char by 4 line display. Based on your comments, it seems that the SMS part of your code is working because it's outputting the correct characters to the serial monitor. I would focus on the LCD code and connections to your Arduino.

Yeah in serial it shows the correct content of the message but in lcd it shows degree symbol(extended ascii code) Is it possible to convert this ascii code to string?  or how can i remove this degree ascii code and change it to text? Thank you

What would you like to replace the degree symbol with?

can i possibly replace the degree symbol to string ??

I'm not sure what you mean, "to string". An empty string? A space character?

I arrived a little late; however I'm leaving some further information to Debug similar problems for those who arrive here in the Future.
Regarding the Question
As already answered above:
 - You are specifying your LCD as a 16 Column with 2 Rows (1602); and in your picture you clearly have a 20 Column with 4 Rows.
Change:
lcd.begin(16, 2);

To:
lcd.begin(20, 4);

How LCD Works
Take into consideration that LCD works as a Matrix and both Columns and Rows are Zero Based Index.
That is; when you set the LCD Cursor Columns or Rows; you start counting with 0.
See Example Bellow:
lcd.setCursor(0, 2);

The 1st Parameter (Zero) Represents Columns.
The 2nd (Two) Represents Rows.
Therefore on the 1st Parameter: "0" (Column); (Considering you're reading from Left to Right and Top to Bottom); You Set the Cursor on the very 1 Column on the LCD.
The 2nd Parameter (2): you’l be Setting char on the 3rd Row (Line).
Note: 3rd and not 2nd; because both Columns and Rows are "Zero Based" Indexed.
Debugging LCD Issues

Check If your LCD is Properly Wired. You may have switched a wire; wire not properly plugged or broken.
Specially if you’re not using a I2C back module). Wiring without I2C (“I Squared C”) module can be confusing in certain occasions.

Check your Library and Hardware.
Make sure you’re using the correct library (I2C library: if your LCD has the module: use a compatible I2C Library; and specify the LCD parameters accordingly).
In case you don’t have a I2C module; then use a library to with a workaround for that situation. (You specify all the Pins).

Check you Code:
Check the way you initialize your LCD.
i.e: lcd.begin(16,2); or lcd.begin(20, 4);

Make sure you print inside LCD Index.
Setting the cursor outside its bounds can also cause “weird” chars.

There can be other situations related with improper wiring or some sort of short circuit with other components connected to your project that can also produce weird characters.

In certain circumstances; pressing Reset; Cutting the Power for a little while or Re-Uploading the project fixes the issue.

Not clearing the LCD whenever there is New data can simulate the effect of weird characters; but actually they are old data characters that remained there.

Writing Custom Characters to LCD
As you've Probably Noticed you are Unable to print the a Custom Character (i.e: Degree Symbol) on your LCD.
That can be solved by Creating your own (Custom) char and Declare it on your Code.
I won't explain every detail, in order to avoid going off topic and to avoid providing an extensive and hard-to-read answer.
Instead will leave an example, that is easy to understand and 2 Links bellow with further information regarding Custom Characters.
Links:

More Information and Examples for Custom Characters.
LCD Character Generator

Example for Degree Character
/* LCD Custom Characters
*******************************************/
// This is your Char Definition in Bytes:
byte DegreeDef[8] = { B01100, B10010, B10010, B01100, B00000, B00000, B00000, B00000 };

// This is the byte Char to be used to write to LCD.
const byte Degree = 0x2;

void LCDInitialization()
{
  // LCD Initialiation Code Here
  // ...

  // Initialize Custom Characters.
  lcd.createChar(2, DegreeDef);

  // Do Something Else...
}

void PrintToLCD()
{
  // Note:
  // "lcd.write" is Different from "lcd.print".
  // Use "write" to Print your Custom LCD Characters.
  lcd.setCursor(0, 1);
  lcd.write(Degree);
}

I hope this helps debugging your issue.

Hello I had the same problem and noticed that if you setup the lcd screen in this order:
LiquidCrystal lcd (d7, d6, d5, d4, , en, rs) ;

you get some weird character showing up...
but if you do this way:
LiquidCrystal lcd (rs, en, d4, d5, d6, d7) ;

you don't get any weird character.


text:
Servo speed in a Toggle Code
I am new to Arduino and am trying to figure out servos. Right now I have a toggle button code for the servos. Although I want to know how to speed them up. Is there a way to do this?
Currently, this is my code:
#include <Servo.h>
int button = 5; //button pin, connect to ground to move servo
int press = 0;
Servo servo_7;
Servo servo_8;
Servo servo_9;
Servo servo_10;
boolean toggle = true;

void setup()
{

  pinMode(button, INPUT); //arduino monitor pin state
  servo_7.attach(7); //pin for servo control signal
  servo_8.attach(8);
  servo_9.attach(9);
  servo_10.attach(10);
  digitalWrite(5, HIGH); //enable pullups to make pin high
}

void loop()
{
  press = digitalRead(button);
  if (press == LOW)
  {
    if(toggle)
    {

      servo_7.write(180);
      servo_8.write(180);
      servo_9.write(180);
      servo_10.write(180);
      toggle = !toggle;
    }
    else
    {

      servo_7.write(0);
      servo_8.write(0);
      servo_9.write(0);
      servo_10.write(0);

      toggle = !toggle;
    }
  }
  delay(100);  //delay for debounce
}

Please add your code, since we cannot help you without it. Edit your question accordingly and format the code correctly (There is also a shortcut for it: Strg + K)

Stop changing the whole question. It is frustrating, that you solved the problem yourself during me writing an answer, and then just changing the question to a complete other problem. If you can solve your problem in this short time, you should not ask a question here. It is not in the scope of this site, to answer questions, that can be easily answered by googling or thinking about it.

You cannot change the servos speed with the Servo library. It just outputs the value you give as a PWM wave. It is up to your servo to follow it as fast as it can.

why do you have the servo_7.write(), servo_8.write(), etc code twice ... you only need to have it once

Normal servos have a speed. It's their speed, and you can't change it. You can make it appear slower by moving in small increments, but you can't actually change the speed it moves.
With constant rotation servos the "angle" dictates the rotation speed, but even with those there is nothing you can do to change the relationship between "angle" and rotational speed.
Other than buying a different servo with a different degrees-per-second rating.


text:
clear serial buffer not working
Also asked in forum.arduino.cc
bool receive_command(char answer[]);
void serial_flush(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  for(byte i=0;i<3;i++){
if(receive_command("OK")) Serial.println("OK found");
 serial_flush();
  }
}

void loop() {}

void serial_flush(void) {
  while (Serial.available()) Serial.read();
}

bool receive_command(char answer[]) {
 unsigned long _time = 0;
  const int max_time = 10000;
  bool flag = 0;

Serial.print("in Serial buffer=");
  Serial.println(Serial.available());
  if(Serial.available()){
  Serial.write(Serial.read());
  Serial.println(" left in serial buffer");}

  while (Serial.available() < 2) {
if ((millis() - _time) > max_time) {
      Serial.println("waited too long nothing received");
  return flag;
    }
    }
  do {
    if (Serial.findUntil(answer, '\n')) return flag = 1;
  } while (Serial.available());

return flag;

}

via serial monitor with CR+LF line ending I`m sending this string:
abcdefghijklmnopqrstuvwxyzOKabcdefghijklmnopqrstuvwxyz
26chars+OK+26chars+CR+LF=56 chars
Output:
in Serial buffer=0
OK found
in Serial buffer=1
b left in serial buffer
in Serial buffer=0
waited too long nothing received

after OK is found serial_flush() is executed but after second run there serial.available() shows there is something in serial buffer. right at that moment it was char 'b' but it also can show char 'd'  and 'c' depending how long it will run.
why serial_flush() is not clearing the buffer?
Thanks.

your serial_flush() code does not wait for CRLF .... once the "OK found" is printed, the input buffer is probably receiving the b or c or d ...  serial_flush() exits before e is received, since the buffer is empty ( e has not yet arrived) ................ imagine that you are the Arduino and you receive one character every hour ... what do you do after you have received the O K ?

The processor is somewhat faster than serial input. If you really want to wait for nothing more to arrive you should probably add a short delay (although jsotola's suggestion of looking for a newline is sensible). Something like:
void serial_flush(void) {
 while (true)
   {
   delay (20);  // give data a chance to arrive
   if (Serial.available ())
     {
     // we received something, get all of it and discard it
     while (Serial.available ())
       Serial.read ();
     continue;  // stay in the main loop
     }
  else
    break;  // nothing arrived for 20 ms
   }
}

the second parameter of findUntil(target, terminator) is of type char* not char
your Serial.findUntil(answer, '\n') doesn't work and you patched it with do while.
use Serial.findUntil(answer, "\n")
'a' is read by readUntil, then it returns  because  of wrong parameter. serial_flush sees no new character. and next you read 'b' from buffer. the sketch runs fast compared to Serial speed. it sees always no or one new character in buffer if the previous was removed


text:
Send readings to PC using HC-05
My project, briefly explained is a weather station that will send data periodically from an Arduino UNO (later an attiny85) to my PC for processing. I'm using a HC-05 bluetooth module to establish a serial connection to my (Linux Mint) Laptop. That all works with blueman-manager and rfcomm using gui tools manually.
So here comes the twist. Since the bluetooth module draws significant current, I will shut it down when it's not used by simply disconnecting the power to it and the sensors. Then I would like the module to wake up when the power comes on again and send the readings to the PC, automatically.
From what I read a bluetooth module can only initiate a connection in master mode. I have tried setting this with an AT command and that part works, but I don't know how to go about creating the persistent connection to my PC that will connect up again after a power loss so that I can send the next reading.
Another part of this is of course that the Laptop running Linux Mint must be able to create the serial port (or ideally use the same port) when the bluetooth module wants to send data.
I realize this question is a bit broad, but any pointers are welcome and I'm curious first of all if this is the right way of accomplishing this task.
Thank you!

I can't answer your question on BL but here's a suggestion: Why not use a Bluetooth Low-Energy module (like the HM-10)? These modules should be well-designed for continious low-power consumption and deepsleep capabilities. You could also use the ESP32 with onboard BLE and put that chip into deepsleep, or any other kind of ultra-low-power BLE beacon.

You might also find this interesting: https://www.youtube.com/watch?v=1i-6cz4KHXE

That is very interesting, thank you! Do you have any experience using the HM-10? I'm a little confused on how to use the AT commands on them that would initiate the sleep mode. On the EC-05 I set it by holding the button and it enters a separate mode. On the EM-10 it seems to be able to accept AT commands in "normal" mode? That would actually be much better since the Arduino could then send that command whenever it wanted without having to set it to AT mode. Can't seem to find any information on that :-/


text:
AT command parsing and listening for incoming SMS Arduino Leonardo SIM800H
I am trying to make a program that receives commands contained in SMS. The commands can be $CMD1 and $CMD2. Of course I need to verify the phone number of the sender by its last 6 digits. Other than this I have to ask and receive rtc clock information from the modem. AT commands format:
+CCLK: "YY/MM/DD,HH:MM:SS+TT" (works properly)
+CMTI: "SM",N (where N is the index number of the sms in the phone mem)
+CMGR: "REC READ","+1234567890","","04/01/01,00:00:00+00" (it reaches only the 15th char and hangs)
My code:
const long interval = 1000;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

char esemesemes[3];

byte pointingfinger = 0;

char enabledtime = 0;

char cclkenabl = 0;

char foundchar[6];

byte cmtienabl = 0;

byte witdqt = 0;

byte acceptsms = 0;

byte ocpos = 0;

byte occurence = 0;

byte cmgrenabl = 0;

byte esemindex[3];

char phone1[6] = {'5', '6', '7', '8', '9', '0'};

char phone2[6];

byte enableclock = 1;

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    if (enableclock == 1) {
      Serial1.print("AT+CCLK?\r");
    }
    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    if (enableclock == 1) {
      Serial.println("YEAR: ");
      Serial.print(rtcy1[0]);
      Serial.println(rtcy1[1]);
      Serial.println("MONTH: ");
      Serial.print(rtcm1[0]);
      Serial.println(rtcm1[1]);
      Serial.println("DAY: ");
      Serial.print(rtcd1[0]);
      Serial.println(rtcd1[1]);
      Serial.println("HOUR: ");
      Serial.print(rtch1[0]);
      Serial.println(rtch1[1]);
      Serial.println("MINUTE: ");
      Serial.print(rtcmm1[0]);
      Serial.println(rtcmm1[1]);
      Serial.println("SECOND: ");
      Serial.print(rtcs1[0]);
      Serial.println(rtcs1[1]);
    }
    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
    if (Serial1.available () > 0) {
      foundchar[0] = foundchar[1];
      foundchar[1] = foundchar[2];
      foundchar[2] = foundchar[3];
      foundchar[3] = foundchar[4];
      foundchar[4] = foundchar[5];
      foundchar[5] = Serial1.read();

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K' && foundchar[5] == ':' && enableclock == 1) {
        cclkenabl = 1;
        pointingfinger = 0;
      }

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'T' && foundchar[4] == 'I' && foundchar[5] == ':') {
        cmtienabl = 1;
        pointingfinger = 0;
        enableclock = 0;
      }

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'G' && foundchar[4] == 'R' && foundchar[5] == ':') {
        cmgrenabl = 1;
        pointingfinger = 0;
      }

      if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '1') {
        if (acceptsms == 1) {
          while (true) {
            Serial.println("CMD1");
          }
        }
      }

      if (foundchar[0] == '$' && foundchar[1] == 'C' && foundchar[2] == 'M' && foundchar[3] == 'D' && foundchar[4] == '2') {
        if (acceptsms == 1) {
          Serial.println("CMD2");
        }
      }

      if (cclkenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        cmgrenabl = 0;
        cclkenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
      }

      if (cmtienabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        cmtienabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        enableclock = 0;
        esemesemes[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        esemesemes[1] = serialdata[searchcharpos + 9];
        esemesemes[2] = '\0';
        esemindex[0] = serialdata[searchcharpos + 12];
        esemindex[1] = '\0';
        Serial.println("CMTI");
        Serial.println(esemesemes[0]);
        Serial.println(esemesemes[1]);
        Serial.println(esemindex[1]);
        if (esemesemes[0] == 'S' && esemesemes[1] == 'M') {
          Serial1.println("AT+CMGF=1");
          Serial.println("AT+CMGF=1");
          delay(100);
          Serial1.println("AT+CMGR=1");
          Serial.println("AT+CMGR=1");
        }
        if (esemesemes[0] != 'S' || esemesemes[1] != 'M') {
          Serial1.println("AT+CMGD=4,1");
          Serial.println("Deleted");
        }
      }

      if (cmgrenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read(); //                       I THINK HERE WE HAVE SOME PROBLEM
            Serial.println("Searching");
            Serial.println(serialdata[pointingfinger]);
            Serial.println(pointingfinger);
            Serial.print(serialdata[searchcharpos]);
            Serial.print(serialdata[searchcharpos + 1]);
            Serial.print(serialdata[searchcharpos + 2]);
            Serial.print(serialdata[searchcharpos + 3]);
            Serial.print(serialdata[searchcharpos + 4]);
            Serial.print(serialdata[searchcharpos + 5]);
            Serial.print(serialdata[searchcharpos + 6]);
            Serial.print(serialdata[searchcharpos + 7]);
            Serial.print(serialdata[searchcharpos + 8]);
            Serial.print(serialdata[searchcharpos + 9]);
            Serial.print(serialdata[searchcharpos + 10]);
            Serial.print(serialdata[searchcharpos + 11]);
            Serial.print(serialdata[searchcharpos + 12]);
            Serial.print(serialdata[searchcharpos + 13]);
            Serial.print(serialdata[searchcharpos + 14]);
            Serial.print(serialdata[searchcharpos + 15]);
            Serial.print(serialdata[searchcharpos + 16]);
            Serial.print(serialdata[searchcharpos + 17]);
            Serial.print(serialdata[searchcharpos + 18]);
            Serial.print(serialdata[searchcharpos + 19]);
            Serial.print(serialdata[searchcharpos + 20]);
            Serial.print(serialdata[searchcharpos + 21]);
            Serial.print(serialdata[searchcharpos + 22]);
            Serial.print(serialdata[searchcharpos + 23]);
            Serial.print(serialdata[searchcharpos + 24]);
            Serial.print(serialdata[searchcharpos + 25]);
            Serial.print(serialdata[searchcharpos + 26]);
            Serial.print(serialdata[searchcharpos + 27]);
            Serial.print(serialdata[searchcharpos + 28]);
            Serial.print(serialdata[searchcharpos + 29]);
            Serial.print(serialdata[searchcharpos + 30]);
          }
        }
        //pointingfinger = 0;
        enabledtime = 1;
        occurence = 0;
        ocpos = 0;
        Serial.println("mode1");
        while (occurence < 7) {
          Serial.println("mode2");
          if (serialdata[ocpos] == '\"') {
            Serial.println("mode3");
            occurence++;
            Serial.println(occurence);
          }
          Serial.println("mode4");
          ocpos++;
          Serial.println(ocpos);
        }
        witdqt = ocpos;
        Serial.println("PHONE1: ");
        Serial.print(serialdata[witdqt - 1]);
        Serial.print(serialdata[witdqt - 2]);
        Serial.print(serialdata[witdqt - 3]);
        Serial.print(serialdata[witdqt - 4]);
        Serial.print(serialdata[witdqt - 5]);
        Serial.print(serialdata[witdqt - 6]);
        Serial.println("");
      }
      acceptsms = 0;

      if (serialdata[witdqt - 1] == phone1[5] && serialdata[witdqt - 2] == phone1[4] && serialdata[witdqt - 3] == phone1[3] && serialdata[witdqt - 4] == phone1[2] && serialdata[witdqt - 5] == phone1[1] && serialdata[witdqt - 6] == phone1[0])
      {
        acceptsms = 1;
        Serial.println("Accepted");
      }

      if (serialdata[witdqt - 1] == phone2[5] && serialdata[witdqt - 2] == phone2[4] && serialdata[witdqt - 3] == phone2[3] && serialdata[witdqt - 4] == phone2[2] && serialdata[witdqt - 5] == phone2[1] && serialdata[witdqt - 6] == phone2[0])
      {
        acceptsms = 1;
        Serial.println("Accepted");
      }

      /*Serial.println("");
        Serial.print(foundchar[0]);
        Serial.print(foundchar[1]);
        Serial.print(foundchar[2]);
        Serial.print(foundchar[3]);
        Serial.print(foundchar[4]);
        Serial.print(foundchar[5]);
        Serial.println("");*/

    }
  }
}

This is the Serial Monitor:

What is the exact question? You presented your project and your code. You want code for general AT command parsing?

I have some error that doen't allow me to see and parse the whole char array and get the phone number to compare. I cannot see what's wrong with my code.

That is the most bizarre serial parsing code I have ever seen. You're not making life easy on yourself with that stuff...

This might help you to write better parsing code: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ and https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/

I also cannot comprehend that parsing code. You might want to start working on a general ATCmdParser like mbed-os has or look at the parsing code from other libraries which receive AT commands (example)

Or, in short: Read an entire line into the buffer, and only once the line is complete do you analyse it and decide what to do with it. A sliding window is not what you want for line-based ASCII communication.

how to detect what command I have? I did this with shifting values, but is there a better way?

You could write a unified "send command and parse response", which will send a command, read the entire response in a buffer until a delimiter is reached, then use custom parsing functions or simple sscanf to parse the data out of it, according to the sent command.

strncmp() on a properly formatted line (c string) buffer is what you want.

Thank you both, I will see what I can do with the new info and write here.

@Majenko why there isn't a break; in the switch statement in your line by line reading example?

For '\r' there is a return, so you don't need a break (it would never get there). For default it's the last entry, so you don't need a break (though you could put one there if you like).  I should really swap over the \r and \n entries - the \n is really the proper one to detect for a line ending.

There - I've updated it. It was such a long time ago I wrote that snippet...

Argh! I hate Wordpress! It just trashed my post!  C  * N * S! I hope I just got it back in there right again.

I am really sorry, hope your site is ok

You should throw away all your own code and read the serial data in a line at a time. Only once a complete line has been received should you then examine it to see what you have.
For example, here's something I just threw together based around a snippet I posted here:
int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
            buffer[pos++] = readch;
            buffer[pos] = 0;
        }
        break;
    }
  }
  return 0;
}

// ... later, in your loop:

if (Serial1.available()) {
    // Read one character and send it to the readline function.
    if (readline(Serial1.read(), serialdata, 512)) { // do you really need 512 bytes of buffer?!?!

        // readline() told us we got a valid string. Let's
        // parse it.

        // If the string starts with '+CCLK: "'
        if (strncmp(serialdata, "+CCLK: \"", 8) == 0) {
            // Slice it up by the different delimiters
            // starting at the 9th character:
            char *cyear = strtok(serialdata + 8, "/");
            char *cmonth = strtok(NULL, "/");
            char *cday = strtok(NULL, ",");
            char *chour = strtok(NULL, ":");
            char *cmin = strtok(NULL, ":");
            char *csec = strtok(NULL, "+");

            // Check the last slicing worked
            if (sec != NULL) { // It parsed OK
                // And convert each slice to a number.
                year = atoi(cyear);
                month = atoi(cmonth);
                day = atoi(cday);
                hour = atoi(chour);
                minute = atoi(cmin);
                sec = atoi(csec);

                // Show the time.
                Serial.print(F("The time is "));
                Serial.print(minute);
                Serial.print(F(" minutes past "));
                Serial.println(hour);
            }
        }
    }

    // Do similar operations for the different possible messages
    // you may get.

}


text:
Arduino Uno with Adafruit CC3000
I am using Arduino Uno with Adafruit CC3000 wifi shield to connect to the internet and get data for Arduino. Everything works fine but I can't figure out how to use HttpClient library. The code is:
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
#include <HttpClient.h>

#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "ssid"
#define WLAN_PASS       "pwd"
#define WLAN_SECURITY   WLAN_SEC_WPA2

void setConnection(){

     Serial.println("Initializing...");
     if (!cc3000.begin())
     {
       Serial.println("Couldn't begin()! Check your wiring?");
       while(1);
     }
     Serial.print("Attempting to connect to ");
     Serial.println(WLAN_SSID);
     if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
       Serial.println("Failed!");
       while(1);
     }
     Serial.println("Connected!");
     Serial.println(F("Request DHCP"));
     while (!cc3000.checkDHCP())
      {
          delay(100);
       }
     Serial.println(F("DHCP success!!"));
 }

void dweet(){

  int ctr=0;
  char buff[100];
  int x=0;
  const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

  Serial.println(F("Initializing dweet client ..."));
  HttpClient client;
  client.get(host);
  Serial.println(F("Client Connected !"));

  while (client.available()) {
    char c = client.read();
    Serial.write(c);
    delay(100);
  }

void setup(){

     Serial.begin(115200);
     while(!Serial);
     Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
     setConnection();

}

void loop(){
dweet();
}

If all worked fine then I should have got a json string which is:
{"this":"succeeded","by":"getting","the":"dweets","with":[{"thing":"dunebot","created":"2018-05-12T13:27:56.106Z","content":{"0001":""}}]}

When I run the code, Arduino connects to the wifi network but afterwards when I observe the Serial monitor all I get are garbage values.

I need a way to read the key 0001 from the json string. Any help would be appreciated.Thanks.

The HttpClient object must be instantiated with a Client object which will handle the underlying connection. Source:

Requires a networking hardware and a library that provides transport specific Client instance, such as:

Refer to the following code:

https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/examples/DweetGet/DweetGet.ino
https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/Adafruit_CC3000.h#L86
https://github.com/arduino-libraries/ArduinoHttpClient/blob/master/src/HttpClient.h#L51

In the above example, it is done like
WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);

Which means that for your code, you might want to pull out client as global object and instantiate it as:
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
/* Create new Adafruit_CC3000_Client object */
Adafruit_CC3000_Client cc3000_client;
/* Feed this into the client */
HttpClient client (cc3000_client, "dweet.io", 80);

You should also use the example code to see how to print the response after executing client.get():
  // read the status code and body of the response
  statusCode = client.responseStatusCode();
  response = client.responseBody();
  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

The example code is pretty much example what you want, you just have to give it a Adafruit_CC3000_Client as the Client.
Full code:
#include <Arduino.h>
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
#include <HttpClient.h>

#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIVIDER);
/* Create new Adafruit_CC3000_Client object */
Adafruit_CC3000_Client cc3000_client;
/* Feed this into the client */
HttpClient client (cc3000_client, "dweet.io", 80);

#define WLAN_SSID       "ssid"
#define WLAN_PASS       "pwd"
#define WLAN_SECURITY   WLAN_SEC_WPA2

int statusCode = 0;
String response;

void setConnection(){

    Serial.println("Initializing...");
    if (!cc3000.begin())
    {
        Serial.println("Couldn't begin()! Check your wiring?");
        while(1);
    }
    Serial.print("Attempting to connect to ");
    Serial.println(WLAN_SSID);
    if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println("Failed!");
        while(1);
    }
    Serial.println("Connected!");
    Serial.println(F("Request DHCP"));
    while (!cc3000.checkDHCP())
    {
        delay(100);
    }
    Serial.println(F("DHCP success!!"));
}

void dweet(){

    int ctr=0;
    char buff[100];
    int x=0;
    const char* host = "https://dweet.io/get/latest/dweet/for/dunebot";

    Serial.println(F("Initializing dweet client ..."));

    client.get(host);
    Serial.println(F("Client Connected !"));

    // read the status code and body of the response
    statusCode = client.responseStatusCode();
    response = client.responseBody();
    Serial.print("Status code: ");
    Serial.println(statusCode);
    Serial.print("Response: ");
    Serial.println(response);

    /*
    Typical response is:
    {"this":"succeeded",
    "by":"getting",
    "the":"dweets",
    "with":[{"thing":"my-thing-name",
      "created":"2016-02-16T05:10:36.589Z",
      "content":{"sensorValue":456}}]}
    You want "content": numberValue
    */
    // now parse the response looking for "content":
    int labelStart = response.indexOf("content\":");
    // find the first { after "content":
    int contentStart = response.indexOf("{", labelStart);
    // find the following } and get what's between the braces:
    int contentEnd = response.indexOf("}", labelStart);
    String content = response.substring(contentStart + 1, contentEnd);
    Serial.println(content);

    //There was a missing brace here. Was the code cut off?!
}

void setup(){
    Serial.begin(115200);
    while(!Serial);
    Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);
    setConnection();
}

void loop() {
    dweet();
}

So i did what you told but it throws an error no matching function for call to 'HttpClient::HttpClient(Adafruit_CC3000&, const char [9], int)'. Does HttpClient work with Adafruit cc3000?

@AshishKafle in the library code I linked it says that it derives from the class Client. I will test this my self in just a moment.

@AshishKafle Could you retry that again. I referenced the Adafruit_CC3000 class when it should have been the Adafruit_CC3000_Client class.

the code works nice but after Serial.println(F("Client Connected !"));  nothing seems to work for me. After that i get nothing.

Could you try this sketch and post the output on pastebin. https://pastebin.com/2kUqACgB

The output is here https://pastebin.com/5XeVGdZi . The error is client.get returned error: -1.

Oh, there seems to be another mistake: change host to /get/latest/dweet/for/dunebot

@AshishKafle Please find this file in your local Arduino Library repositary and remove the //. Also  find this file and add the line #define LOGGING true at line 7, then re-post output

It says connection failed. The output is here: https://pastebin.com/NMzNr682 .

@AshishKafle and no output from the CC3300 library although you removed the comment? Unfortunetly I don't have the hardware, so remote debugging is hard. Try adding more debug output to https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/Adafruit_CC3000.cpp#L1414 to understand what's happening.

Yes it was all that it showed. Thanks I will do that.