body:
I want to send data to my php server using sim900 module but I am unable to initialize http service on sim900.

code:

    #include <SoftwareSerial.h>
    SoftwareSerial gprsSerial(8, 9);

    void setup()
    {
      gprsSerial.begin(9600);
      Serial.begin(9600);

      Serial.println("Con");
      delay(2000);
      Serial.println("Done!...");
      gprsSerial.flush();
      Serial.flush();

      // See if the SIM900 is ready
      gprsSerial.println("AT");
      delay(1000);
      toSerial();

      // SIM card inserted and unlocked?
      gprsSerial.println("AT+CPIN?");
      delay(1000);
      toSerial();

      // Is the SIM card registered?
      gprsSerial.println("AT+CREG?");
      delay(1000);
      toSerial();

      // Is GPRS attached?
      gprsSerial.println("AT+CGATT?");
      delay(1000);
      toSerial();

      // Check signal strength
      gprsSerial.println("AT+CSQ ");
      delay(1000);
      toSerial();

      // Set connection type to GPRS
      gprsSerial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
      delay(2000);
      toSerial();

      // Set the APN
      gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"web\"");
      delay(2000);
      toSerial();

      // Enable GPRS
      gprsSerial.println("AT+SAPBR=1,1");
      delay(10000);
      toSerial();

      // Check to see if connection is correct and get your IP address
      gprsSerial.println("AT+SAPBR=2,1");
      delay(2000);
      toSerial();

    }

    void loop()
    {
       // initialize http service
       gprsSerial.println("AT+HTTPINIT");
       delay(2000);
       toSerial();

       // set http param value
       // ToDO : send dynamic value
       gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://www.fohoraayo.000webhostapp.com/?lat=1111&lon=1111\"");
       delay(4000);
       toSerial();

       // set http action type 0 = GET, 1 = POST, 2 = HEAD
       gprsSerial.println("AT+HTTPACTION=0");
       delay(6000);
       toSerial();

       // read server response
       gprsSerial.println("AT+HTTPREAD");
       delay(1000);
       toSerial();

       //gprsSerial.println("");
       gprsSerial.println("AT+HTTPTERM");
       toSerial();
       delay(300);

       gprsSerial.println("");
       delay(10000);
    }

    void toSerial()
    {
      while(gprsSerial.available()!=0)
      {
        Serial.write(gprsSerial.read());
      }
    }

output:

    Config SIM900...
    Done!...
    AT

    OK
    AT+CPIN?

    +CPIN: READY

    OK
    AT+CREG?

    +CREG: 0,1

    OK
    AT+CGATT?

    +CGATT: 1

    OK
    AT+CSQ

    +CSQ: 31,0

    OK
    AT+SAPBR=3,1,"Contype","GPRS"

    OK
    AT+SAPBR=3,1,"APN","web"

    OK
    AT+SAPBR=1,1

    ERROR
    AT+SAPBR=2,1

    +SAPBR: 1,1,"xx.xxx.x.x"

    OK
    AT+HTTPINIT

    ERROR
    AT+HTTPPARA="URL","http://www.fohoraayo.000webhostapp.com/?lat=AT+HTTPACTION=0

    ERROR
    AT+HTTPREAD

    ERROR
    AT+HTTPTERM

    ERROR

title: Sim900 error on AT command AT+HTTPINIT

Answers: 1

body:
For me, your code is working like charm. but change the

    gprsSerial.begin(9600)

to

    gprsSerial.begin(4800)


body:
I have an Atmega 328 chip and want to load the Arduino boot loader to the chip. I have planned to use a SPI protocol to do this, but I have read other posts saying that they have done similar using an UART with using an FTDI chip. I have planned to use the FTDI to support USB.

I did rad some information that said that loading the boot loader through UART is very slow.

Which is best? I would like to save space, if I do not need a SPI header then I would like to remove this. Is what I have read correct?

Thanks

title: Atmega boot loading UART or SPI

Answers: 2

body: Loading via UART is not so bad if you configure the bootloader to use a reasonable baud rate (say, 115200 instead of the default 9600). However, you do have to get the bootloader onto the chip in the first place, and that has to be done with SPI.

body:
> I have read other posts saying that they have done similar using an UART with using an FTDI chip.

You have probably misread something. A brand-new, blank ATmega328 can only be programmed over SPI, or via parallel programming (more pins). There is no "native" UART bootloader.

It's possible to use certain FTDI chips to bit-bang the SPI programming interface. This is probably what the posts you're reading are referring to. As the post suggests, though, this is slower than using a programmer which directly supports the SPI interface, and is only really suitable if you don't have a better programmer available.

If space is a concern, one option to consider may be to provide the ISP port as a set of test points and use pogo pins to access it during manufacturing. You can lay out the test points however you want, possibly at a finer pitch than the 100 mil header you're probably used to.

Depending on your manufacturing process, another approach may be to program the chip before mounting it to the board.


body:
I am wondering if I can control 20 different servo motors with only a single Arduino Uno board. My motors must be able to rotate in both directions and I also should be able to define the speed for each of them independently. Also I am able to use integrated circuits or a device that connects to my Arduino board.

Is this a possible scenario?

title: Controlling 20 servo motors independently with a single Arduino

Answers: 0


body:
I have a project which requires me to read if the input is "HIGH".
I have 15 inputs (switches), and each input has its own output (LED). I am using a Shift Register to control its inputs and outputs.

My current code looks like this (4 inputs and 4 outputs, it works though...):

    #include "SPI.h"
    #include "MFRC522.h"
    #include "rgb_lcd.h"
    #include <Wire.h>

    #define SS_PIN 17
    #define RST_PIN 7

    int counter = 0;
    int lock = 100;

    MFRC522 rfid(SS_PIN, RST_PIN);
    rgb_lcd lcd;
    MFRC522::MIFARE_Key key;

    // Define Pins
    int SHIFTIN_LATCH = 22;
    int SHIFTIN_DATA = 23;
    int SHIFTIN_CLOCK = 21;
    int numberToDisplay = 0;

    #define SHIFTOUT_DATA  18
    #define SHIFTOUT_LATCH  19
    #define SHIFTOUT_CLOCK  20

    //Define variables to hold the data
    //for each shift register.
    //starting with non-zero numbers can help
    //troubleshoot
    byte keySlotID[15] = {
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    byte keyInsert[15] = {
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    byte keyReg[10] = {
      0,0,0,0,0,0,0,0,0,0}; // amt of reg.

    void setup() {
      //start serial
      Serial.begin(9600);

      //define pin modes
      pinMode(SHIFTIN_LATCH, OUTPUT);
      pinMode(SHIFTIN_CLOCK, OUTPUT);
      pinMode(SHIFTIN_DATA, INPUT);

      pinMode(SHIFTOUT_DATA, OUTPUT);
      pinMode(SHIFTOUT_LATCH, OUTPUT);
      pinMode(SHIFTOUT_CLOCK, OUTPUT);
      Serial.begin(9600);
      SPI.begin();
      rfid.PCD_Init();
      lcd.begin(16, 2);
    }

    void KeyID(){
      // Key slot indicator.
      keySlotID[0] = (keyReg[0] & 0x1E) >> 1;
      keySlotID[1] = (((keyReg[1] & 0x03) << 3) | ((keyReg[0] & 0xE0) >> 5)) >> 1;
      keySlotID[2] = (keyReg[1] & 0x78) >> 3;
      keySlotID[3] = (keyReg[2] & 0x0F);
      // Key inserted indicator.
      keyInsert[0] = (keyReg[0] & 0x01);
      keyInsert[1] = (keyReg[0] & 0x20) >> 5;
      keyInsert[2] = (keyReg[1] & 0x04) >> 2; // X
      keyInsert[3] = (keyReg[1] & 0x80) >> 7; // X
    }

    void registerWrite(byte data1, byte data2) {
      digitalWrite(SHIFTOUT_LATCH, LOW);
      delay(10);
      shiftOut(SHIFTOUT_DATA, SHIFTOUT_CLOCK, MSBFIRST, data2);
      shiftOut(SHIFTOUT_DATA, SHIFTOUT_CLOCK, MSBFIRST, data1);
      digitalWrite(SHIFTOUT_LATCH, HIGH);
      delay(10);
    }

    void LedIFs() {

      if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 0) {
        registerWrite(0xFF,0);
      }
      else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 1) {
        registerWrite(0x40,0);
      }
      else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 0) {
        registerWrite(0x10,0);
      }
      else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 1) {
        registerWrite(0x50,0);
      }
      else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 0) {
        registerWrite(0x04,0);
      }
      else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 1) {
        registerWrite(0x44,0);
      }
      else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 0) {
        registerWrite(0x14,0);
      }
      else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 1) {
        registerWrite(0x54,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 0) {
        registerWrite(0x01,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 1) {
        registerWrite(0x41,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 0) {
        registerWrite(0x11,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 1) {
        registerWrite(0x51,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 0) {
        registerWrite(0x05,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 1) {
        registerWrite(0x45,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 0) {
        registerWrite(0x15,0);
      }
      else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 1) {
        registerWrite(0x55,0);
      }
    }

    void loop() {

      //Pulse the latch pin:
      //set it to 1 to collect parallel data
      digitalWrite(SHIFTIN_LATCH,1);
      //set it to 1 to collect parallel data, wait
      delay(1);
      //set it to 0 to transmit data serially
      digitalWrite(SHIFTIN_LATCH,0);

      //while the shift register is in serial mode
      //collect each shift register into a byte
      //the register attached to the chip comes in first
      keyReg[0] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);
      keyReg[1] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);
      keyReg[2] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);

      LedIFs();
      KeyID();
    }

The problem I'm facing is that it would be too long for me to write down 15 `KeyInsert`s. That would mean I have to write about or close to 200,000 lines of code...

title: Multiple If Conditions Arduino

Answers: 3

body:
I will be using `digitalRead`s and `digitalWrite`s but just follow this logic:

    int state[num_of_switch_that_you_have];

    for(int i=0; i<num_of_switch_that_you_have; i++)
    {
      //buttonPins is the pin to which all your buttons are connected to in an array
      state[i] = digitalRead(buttonPins[i]);

      //leds is the pin to which all your leds are connected to in an array
      digitalWrite(leds[i], state[i]);
    }

Try to follow this logic while using your shift registers. Sorry if I don't have a full code with shift registers for you, I'm not really good with them!

If you need any more details, please comment, I'll be happy to help!

body:
Let's assume value that will be stored into "keyInsert" are either "1" or "0". Therefore, its a waste to declare them as an array byte

    byte keyInsert[15] = {
      0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

It means that you will have 15 * 8 bytes variable, and its overkill.
it will be much simpler if you declare it as

    uint16_t keyInsert;

Which have 16 bits data (2 bytes).
in your code, you can implement it by doing

    void LedIFs() {
    if (keyInsert == 0x0001) registerWrite(0xFF,0); else
    if (keyInsert == 0x0002) registerWrite(......)......
    ......
    }

body:
I can't quite get the logic of your `keyInsert[]` array. Why don't you
use a binary number (e.g. `uint16_t`, which is 16 bits) instead of an
array of zeros and ones? Also, half of the lines of the output shift
register seem essentially unused.

If I understand correctly, you want to simplify `LedIFs()` in order to
handle many bits with few lines of code. Examining your current
implementation, it appears that you are writing to the output register
the very same bits you have in `keyInsert[]`, only in different
positions. Instead of testing every possible combination, it would be
much simpler to just move the bits into their appropriate positions:

* `keyInsert[0]` becomes bit 0 (i.e. least significant) of the first
  argument of `registerWrite()`
* `keyInsert[1]` becomes bit 2 (it's weight is 22 = 0x04)
* `keyInsert[2]` is bit 4 (weight: 24 = 0x10)
* `keyInsert[3]` is bit 6 (weight: 26 = 0x40)

This is done using bit shifts, and joining the bits with the `|`
bitwise-or operator:

    void LedIFs() {
        byte val = keyInsert[0] << 0
                 | keyInsert[1] << 2
                 | keyInsert[2] << 4
                 | keyInsert[3] << 6;
        if (val == 0) val = 0xff;
        registerWrite(val, 0);
    }

Notice that `<< 0` has no effect: it is here only because it looks nicer
(more symmetric, easier to read) this way. The compiler will optimize
out this operation anyway. Also, the case when all the bits are zero is
special, since you are writing 0xff instead of zero.

If I were you, what I would do is store the information in `keyInsert[]`
as a single number with the bits already at their correct position. Then
I would write

    uint16_t keyInsert;

    //...

    static inline void LedIFs() {
        registerWrite(keyInsert ? keyInsert : 0xff, 0);
    }


body:
We are currently deploying units with the ATMEGA328 chip. Currently, all ICs have been flashed using the Arduino IDE. Upon release, we would like to offer updating of firmware in some cases, but obviously we would not want to send them the source code and let them download the arduino IDE.

We would like to send a firmware file, and an .exe file like a firmware upgrader, as most companies do. How would I start to go about this?

title: Firmware update for remote situations

Answers: 1

body: Send them avrdude (including the config file) and the hex file. Look at the commands the IDE runs to see the right command format. You can then put that into a batch file if you like.


body:
I'm doing my final year project, My project is based on **"Arduino Real Time Gprs/Gsm & GPS Tracker"**. So Now I have purchased the hardware components such as:

 1. Arduino UNO R3
 2. GSM Shield SIM900 V2.0
 3. Ublox GPS Neo - 6M Module

I'm a begginer to this project, I have a doubt connecting these components together. I have stack the GSM Shield with the Arduino Uno but I don't know how to connect the GPS module to the GSM Shield (How to wire the components). because as you see my pic you might see on the top of the GSM shield there are no female headers except one which comes for the display.

 1. So do I need to implement a female header on the GSM Shield and solder it to conncet the GPS module?
 2. Can't I connect the GPS module to the GSM Shield's UART Pins?

    Please Help me Guys :)

[![Hardware Components][1]][1]

  [1]: https://i.stack.imgur.com/gU5bq.jpg

title: How to connect GPS Neo-6M module to GSM Shield SIM900 V2?

Answers: 1

body:
For your program, I'll highly suggest to use `softwareSerial`. It pretty much emulates the serial communication on other pins (**NOT PIN 0 & 1**). Then connect it like if you would normaly connect an UART device to your Arduino on the 2 other pins that you chose (**NOT PIN 0 & 1**). This should make it easy to prorgam your Arduino while having the GPS and GSM module connected to your Arduino.

The shield can cause problems if it uses Tx and Rx on pins 0 & 1, **WHICH ARE THE PINS NOT TO USE IF YOU USE SOFTWARE SERIAL**, so you might as well connect it with jumper wires. Take the TXs from both of your module and connected to whatever GPIO you want and do the same to the RXs, **NOT ON PIN 0 & 1**.

Once again, `softwareSerial` is **NOT ON PIN 0 & 1**.


body:
We work in groups on a project at school. We had to build an electric scheme with an Arduino to make a small car moving.

We got the parts from our school, except the Arduino (we had to buy it ourselves). We had to use a battery of 11.5 V. We also had electrical resistors to protect the Arduino and the stepper drivers.

The car worked for a while, but then we wanted to change the program and tried to upload new software to the Arduino. Now the Arduino is not recognized by any computer.

We tried several things, like multiple times unplugging the USB cable, hitting the reset button on a specific timed moment (some method found on the internet).

But it still doesn't work. When the Arduino is connected via USB, the 'on' LED on the Arduino is on. After that all we came also to the conclusion that some people made mistakes on building the electric scheme...

- Is it possible that the Arduino is broken, since the battery has 11.5 V?
- If the Arduino isn't broken, can the problem that it's not recognized by the computer be solved?

(Arduino Uno)

title: Is my Arduino possibly broken?

Answers: 2

body:
Considering that you used resistors to lower the 11.5V to an *cough - cough* "very normal and regulated 5V", that most certainly is the problem.

The "right and cheap" way to lower such high voltage and connect them directly to your 5V (just assuming, since you said that you used resistors to protect the Arduino) is actually to use a voltage regulator. Any cheap 7805 should do the job. The Arduino actually has its own voltage regulator on it, if you connect it though the Vin pin.

The "true and efficient" way to step down some voltage is actually to use a step-down converter. The way this is better then any normal regulator is that a regulator will lower your voltage by creating heat when the step-down converter will do it in a more efficient process.

The USB of your PC might also be the problem. There is a fuse on the Arduino and one in almost all USB ports of decent PCs. If the voltage spike is high enough, it might have burned the port. That is quite a rare event, but still possible.

Need anymore help, just comment. I'll be happy to help you!

body:
If you connect 11.5V directly to the Arduino then you _might_ have killed you Arduino, *BUT* you say the LED comes up when you hook up the USB lead.  So take things one step at a time.

 1. Get an Arduino that you know is working and try it in the PC with the same cable.  Does it work?  (No -> Cable or PC is broken - Get a new cable/PC)
 2. Remove all wires, shields, etc. from your Arduino.
 3. Connect the USB cable to the PC, does the Arduino power up? (No -> Arduino is almost certainly dead)
 4. Does the PC recognise the board? (Window -> Beeps, tries to download drivers, etc.) (No-> Manually uninstall the drivers and then repeat this step if it doesn't succeed then the Arduino is very unwell)
 5. Start the Arduino IDE and open Examples->Basic->Blink.  Upload the program to your board.  Does it work? (No -> You need more advanced fault finding)
 6. Change Blink so it prints a message every time the loop, Serial.println("Hello"); will do.
 7. Upload you modified program and open the serial monitor.  Does it show the message?  (No -> You need more advanced fault finding)

I know this doesn't fix the problem, but hopefully this will help you narrow down the fault.
My gut feeling is that your Arduino has executed its last lines of code, but you never know...


body:
I have the following problem, the arduino is receiving a command like

**LCD,Display line text one, Display line text two**

I use an strcmp to match the beginning of the string that works but now I would like to ignore the beginning of the string (LCD) and scan in the next 2 variables until the comma to 2 new variables.

                    sscanf(Command, "%[^,]%[^,]%[^,]", &dummy, &lcd_display_l1, &lcd_display_l2);

I don't know if it's possible to ignore the first variable (which would be the LCD) but I setup a dummy variable for it anyway what I not going to use.

All I get with this is the LCD in the dummy the other 2 does not fill up.
I have tried this syntax:

https://support.microsoft.com/en-us/kb/38335

Doesn't work either. Any ideas?

title: Arduino SSCANF stop on comma delimiter

Answers: 1

body:
I would suggest using `strtok()` to chop the string up:

    char *prefix = strtok(mystring, ",");
    char *firstString = strtok(NULL, ",");
    char *secondString = strtok(NULL, ",");

That has the effect of slicing the existing string up in memory replacing the commas with `\0` and placing three pointers at the start of the three substrings. It has the advantage that it doesn't need to copy the contents of the string anywhere, so doesn't use any extra memory (other than the few bytes for the pointers).


body: I am doing some byte manipulation in Arduino, but when I enter an integer into the serial monitor, such as `1`, and my program stores it as `byte incomingByte`, the value stored in `incomingByte` is 49 and not `1`. How do I enter the ASCII equivalent of an integer?

title: Entering integers as bytes in serial monitor

Answers: 3

body:
Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as [RealTerm][1] (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.

  [1]: http://realterm.sourceforge.net/

body:
You can do this little trick:

    void loop()
    {
    while (Serial.available() == 0); //waiting for input
    int val = Serial.parseInt(); //read as integer
    }

body:
Check out the [ASCII table][1].

When you enter `1` into the Serial Monitor you are telling it to send the (ASCII) *character* `1` - which is represented by the decimal value 49, so the `byte` that is sent is `49`.

I don't believe it is possible to enter the decimal value `1` into the Serial Monitor (you'd have to find some way of entering `SOH` via the keyboard), so the only option is to recognize and accommodate that on the Arduino end.

The usual way to do this is to subtract 48 from the received value. However this is typically written as `- '0'` which is actually *subtract the ASCII value of 0* (this helps indicate that you converting from ASCII)

So...

`int intVal = incomingByte -'0';`

... should work fine for you if you are receiving single digit integers.
However, if you also want to accommodate multi digit integers (e.g. 123) then it becomes more complex requiring converting each byte to it's integer equivalent and then multiplying it by 10 to the power of it's position/column...

`123 = (1 * 10^2) + (2 * 10^1) + (3 * 10^0)`

This is a fun little coding task in itself, but if you're not into that kind of thing then `parseInt('123');` will get you going faster...

  [1]: http://www.asciitable.com/


body:
We have been working on this "disaster bot" code for days and hours. AFter all of our hard work, Arduino gives us this error code: expected primary-expression before void. Please please please assist we are so desperate to get this to work. Here is our code below. Please.

    // HEARTBEAT SENSOR (displays heart rate on LCD screen)
    int sensorPin = A0; // This is the analog sensor pin the backwards S pin is connected to
                               // you can use any of the analog pins, but would need to change this to match
    double alpha = 0.75; // This code uses a rather cool way of averaging the values, using 75% of the
                                   // average of the previous values and 25% of the current value.
    int period = 20; // This is how long the code delays in milliseconds between readings (20 mSec)
    int in = 8;
    int Reset=6;
    int start=7;
    int count=0,i=0,k=0,rate=0;

    // LCD SCREEN
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    // BIG SOUND SENSOR
    int soundDetectedPin = 10;
    int soundDetectedVal = HIGH;
    boolean bAlarm = false;

    unsigned long lastSoundDetectTime;

    int soundAlarmTime = 500;

    // PUSH BUTTON AND BUZZER
    int buzzer = 3;
    int ledPin = 13;
    int inPin = 7;
    int val = 0;

    #define sing

    #define NOTE_B0  31
    #define NOTE_C1  33
    #define NOTE_CS1 35
    #define NOTE_D1  37
    #define NOTE_DS1 39
    #define NOTE_E1  41
    #define NOTE_F1  44
    #define NOTE_FS1 46
    #define NOTE_G1  49
    #define NOTE_GS1 52
    #define NOTE_A1  55
    #define NOTE_AS1 58
    #define NOTE_B1  62
    #define NOTE_C2  65
    #define NOTE_CS2 69
    #define NOTE_D2  73
    #define NOTE_DS2 78
    #define NOTE_E2  82
    #define NOTE_F2  87
    #define NOTE_FS2 93
    #define NOTE_G2  98
    #define NOTE_GS2 104
    #define NOTE_A2  110
    #define NOTE_AS2 117
    #define NOTE_B2  123
    #define NOTE_C3  131
    #define NOTE_CS3 139
    #define NOTE_D3  147
    #define NOTE_DS3 156
    #define NOTE_E3  165
    #define NOTE_F3  175
    #define NOTE_FS3 185
    #define NOTE_G3  196
    #define NOTE_GS3 208
    #define NOTE_A3  220
    #define NOTE_AS3 233
    #define NOTE_B3  247
    #define NOTE_C4  262
    #define NOTE_CS4 277
    #define NOTE_D4  294
    #define NOTE_DS4 311
    #define NOTE_E4  330
    #define NOTE_F4  349
    #define NOTE_FS4 370
    #define NOTE_G4  392
    #define NOTE_GS4 415
    #define NOTE_A4  440
    #define NOTE_AS4 466
    #define NOTE_B4  494
    #define NOTE_C5  523
    #define NOTE_CS5 554
    #define NOTE_D5  587
    #define NOTE_DS5 622
    #define NOTE_E5  659
    #define NOTE_F5  698
    #define NOTE_FS5 740
    #define NOTE_G5  784
    #define NOTE_GS5 831
    #define NOTE_A5  880
    #define NOTE_AS5 932
    #define NOTE_B5  988
    #define NOTE_C6  1047
    #define NOTE_CS6 1109
    #define NOTE_D6  1175
    #define NOTE_DS6 1245
    #define NOTE_E6  1319
    #define NOTE_F6  1397
    #define NOTE_FS6 1480
    #define NOTE_G6  1568
    #define NOTE_GS6 1661
    #define NOTE_A6  1760
    #define NOTE_AS6 1865
    #define NOTE_B6  1976
    #define NOTE_C7  2093
    #define NOTE_CS7 2217
    #define NOTE_D7  2349
    #define NOTE_DS7 2489
    #define NOTE_E7  2637
    #define NOTE_F7  2794
    #define NOTE_FS7 2960
    #define NOTE_G7  3136
    #define NOTE_GS7 3322
    #define NOTE_A7  3520
    #define NOTE_AS7 3729
    #define NOTE_B7  3951
    #define NOTE_C8  4186
    #define NOTE_CS8 4435
    #define NOTE_D8  4699
    #define NOTE_DS8 4978

    #define melodyPin 3
    //Hotline Bling Melody
    int hotlineb_melody[] = {
      0, NOTE_D5, NOTE_D5, NOTE_D5,
      NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5,
      NOTE_E5, NOTE_C5, 0,  NOTE_F5,
      NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5,

      NOTE_C5, NOTE_A4, NOTE_F5, NOTE_E5,
      NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5,
      0, NOTE_F5, NOTE_E5, NOTE_D5,
      NOTE_C5, NOTE_E5, NOTE_C5, NOTE_A4,

      NOTE_F5, NOTE_C6, NOTE_C6,
      NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
      NOTE_D6, 0, NOTE_F5, NOTE_A5,
      NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

      NOTE_A5, 0, NOTE_C6, NOTE_C6,
      NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
      NOTE_D6, 0, NOTE_F5, NOTE_A5,
      NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

      NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
      NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
      NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
      NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,

      NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
      NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,
      NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
      NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,

      NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
      NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
      NOTE_F5, NOTE_C6, NOTE_A5, NOTE_C6,
      NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,

      NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
      NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
      NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
      NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,

      NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
      NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,
      NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
      NOTE_G5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_G5
    };

    //HotlineBLING tempo
      int hotlineb_tempo[] = {
      12, 12, 12, 12,
      12, 12, 12, 12,
      6, 2, 3, 12,
      12, 12, 12, 3,

      3, 3, 12, 12,
      12, 12, 6, 2,
      3, 12, 12, 12,
      12, 3, 3, 4,

      12, 12, 12,
      12, 12, 12, 12,
      2, 3, 12, 12,
      12, 12, 12, 12,

      2, 3, 12, 12,
      12, 12, 12, 12,
      3, 3, 12, 12,
      12, 12, 12, 12,

      2, 12, 12, 12,
      12, 12, 12, 12,
      12, 1.5, 12, 12,
      12, 12, 12, 12,

      12, 12, 6, 2,
      12, 12, 12, 12,
      12, 12, 12, 12,
      6, 2, 12, 12,

      12, 12, 12, 12,
      12, 12, 6, 2.4,
      12, 12, 12, 12,
      12, 12, 12, 12,

      12, 1.5, 12, 12,
      12, 12, 12, 12,
      12, 12, 6, 2,
      12, 12, 12, 12,

      12, 12, 12, 12,
      6, 2, 12, 12,
      12, 12, 12, 12,
      12, 12, 8, 24, 2
    };

    void setup() {

    {
      //lcd.createChar(1, heart);
      lcd.begin(16,2);

      lcd.print("Heart Beat");
      lcd.write(1);
      lcd.setCursor(0,1);
      lcd.print("Monitering");
      pinMode(in, INPUT);
      pinMode(Reset, INPUT);
      pinMode(start, INPUT);
      digitalWrite(Reset, HIGH);
      digitalWrite(start, HIGH);
      delay(1000);

      lcd.begin(16,2);
      lcd.print("need to talk?");
      delay(1000);

      lcd.begin(16,2);
      lcd.print("not yet satisfied with care?");
      delay(1000);
    }
    // This code runs on startup, it sets ledPin to output so it can blink the LED that is built into the
    // Arduino (but then never does), and sets the serial port up for fast 115,200 baud communication
    // of the values (make sure you change your serial monitor to match).

      Serial.begin (115200); // the baud rate of the serial data
      {
        Serial.begin(115200);
        pinMode (soundDetectedPin, INPUT);
      }
      //PUSH BUTTON AND BUZZER
      {
        pinMode(buzzer, OUTPUT);
        pinMode(13, OUTPUT);
        pinMode(inPin, INPUT);
        }
    }

    void loop() {
      // HEARTBEAT SENSOR
        static double oldValue = 0; // used for averaging.
        static double oldChange = 0; // not currently used
        int rawValue = analogRead (sensorPin); // This reads in the value from the analog pin.
                                                                  // this is a 10 bit number, and will be between 0 and 1023
                                                                  // If this value doesn't change, you've connected up
                                                                  // something wrong

      unsigned long time2,time1;
      unsigned long time;

        double value = alpha * oldValue + (1 - alpha) * rawValue; // Calculate an average using 75% of the
                                                                                // previous value and 25% of the new

        Serial.print (rawValue); // Send out serially the value read in
        Serial.print (",");          // Send a comma
        Serial.println (value);   // Send out the average value and a new line
        oldValue = value;        // Save the average for next iteration
        delay (period);            // Wait 20 mSec

      if((digitalRead(start)))
      {
        k=0;
        lcd.clear();
        lcd.print("Please wait.......");
        while(k<5)
        {
         if(digitalRead(in))
         {
          if(k==0)
          time1=millis();
          k++;
          while(digitalRead(in));
         }
        }
          time2=millis();
          rate=time2-time1;
          rate=rate/5;
          rate=60000/rate;
          lcd.clear();
          lcd.print("Heart Beat Rate:");
          lcd.setCursor(0,1);
          lcd.print(rate);
          lcd.print(" ");
          lcd.write(1);
          k=0;
          rate=0;
        }

      if(!digitalRead(Reset))
      {

          rate=0;
          lcd.clear();
          lcd.print("Heart Beat Rate:");
          lcd.setCursor(0,1);
          lcd.write(1);
          lcd.print(rate);
          k=0;
      }
      // LCD SCREEN (helpful hotlines message)
      {
        lcd.setCursor(0,1);
        lcd.clear();
        lcd.begin(16,2);
        lcd.print("1-800-273-8255");
        delay(1000);
        lcd.clear();
        lcd.begin(16,2);
        lcd.print("1-877-726-4727");
        delay(1000);
      }
      // BIG SOUND SENSOR
      {
        soundDetectedVal = digitalRead(soundDetectedPin);

        if (soundDetectedVal == LOW)
        {
          lastSoundDetectTime = millis();
          if (!bAlarm){
            Serial.println("you're doing great :)");
            bAlarm = true;
          }
        }
        else
        {
          if( (millis()-lastSoundDetectTime) > soundAlarmTime && bAlarm) {
            Serial.println("keep breathing");
            bAlarm = false;
          }
        }
      }
      // LCD SCREEN (are feeling better/listen to these sick tunes buddy message)
      {
        lcd.setCursor(0,1);
        lcd.clear();
        lcd.begin(16,2);
        lcd.print("if still need comfort");
        delay(500);
        lcd.clear();
        lcd.begin(16,2);
        lcd.print("hold button");
        delay(1000);
        }
        //PUSH BUTTON AND BUZZER
        {
          val = digitalRead(inPin);
          if (val == HIGH) {
            digitalWrite(buzzer, LOW);
          } else {
            digitalWrite(buzzer, HIGH);
          }
          }
    // BUZZER
    {{
      sing(1);
      sing(1);
      sing(2);
      }
      int song = 0;
       void sing(int s) {
        song = s;
        if (song == 1) {
          Serial.println("recognize this?");
          int size = sizeof(hotlineb_melody) / sizeof(int);
          for (int thisNote = 0; thisNote < size; thisNote++) {
            int noteDuration = 1000 / hotlineb_tempo[thisNote];

            buzz(melodyPin, hotlineb_melody[thisNote], noteDuration);

            int pauseBetweenNotes = noteDuration * 1.30;
            delay(pauseBetweenNotes);

            buzz(melodyPin, 0, noteDuration);
          }
        }
      }
      {
        void buzz(int targetPin, long frequency, long length) {
          digitalWrite(13, HIGH);
          long delayValue = 1000000 / frequency / 2;
          long numCycles = frequency * length / 1000;
          for (long i - 0; i < numCycles; i++) {
            digitalWrite(targetPin, HIGH);
            delayMicroseconds(delayValue);
            digitalWrite(targetPin, LOW);
            delayMicroseconds(delayValue);
          }
          digitalWrite(13, LOW);
              }
            }
          }
        }
      }
    }

title: Error: Expected primary-expression before void

Answers: 1

body:
Here are the problems I found while trying to make your code compile:

## Opening and closing braces should match

Trying to autoformat your code gave me the error:

> Auto Format Canceled: Too many right curly braces.

I had to remove the last two braces for Auto Format to succeed.

## Functions cannot be nested

You should move the declarations of `sing()` and `buzz()` out of
`loop()`. You can **call** them from `loop()` though.

## Other random errors

* `#define sing` is defining `sing` as an empty string, and you cannot
  give a function an empty name

* the variable `song` should be either global or local to `sing()`, not
  local to `loop()`

* to declare and initialize a variable to zero you should write
  `int i = 0`, not `int i - 0`

* `soundAlarmTime` should be unsigned

* `oldChange` and `time` should be removed (they are not used)


body:
I am making a circuit which turns a LED on and off through internet. I am connecting an Arduino to a LED and to an Ethernet controller(ENC28J60), but when I make a `GET` request to the device, it takes too long to respond - around 2 minutes - but my internet connection is fast.Before i get ip "ether.begin(sizeof Ethernet::buffer, mymac,8)" command fails it returns zero still i am able to control it.

Code:

    #include <EtherCard.h>

    #define STATIC 0

    // mac address
    static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
    // ethernet interface ip address
    static byte myip[] = { 172,26,40,250 };
    // gateway ip address
    static byte gwip[] = { 172,26,40,1 };

    // LED to control output
    int ledPin10 = 10;

    byte Ethernet::buffer[700];

    const char page[] PROGMEM =
    "HTTP/1.0 503 Service Unavailable\r\n"
    "Content-Type: text/html\r\n"
    "Retry-After: 600\r\n"
    "\r\n"
    ""
    "<title>"
    "Service Temporarily Unavailable"
    "</title>"
    ""
    "
This service is currently unavailable
"
    "
"
      "The main server is currently off-line.
"
      "Please try again later."
    "
"
    ""
    ""
    ;

    void setup () {
        pinMode(ledPin10, OUTPUT);

      Serial.begin(9600);
      Serial.println("Trying to get an IP...");

      Serial.print("MAC: ");
      for (byte i = 0; i < 6; ++i) {
        Serial.print(mymac[i], HEX);
        if (i < 5)
          Serial.print(':');
      }

      if (ether.begin(sizeof Ethernet::buffer, mymac,8) == 0)
        Serial.println( "Failed to access Ethernet controller");
      else
        Serial.println("\nEthernet Controller Initialized");

    #if STATIC
      Serial.println( "Getting static IP.");
      if (!ether.staticSetup(myip, gwip)){
        Serial.println( "could not get a static IP");

      }
    #else

      Serial.println("Setting up DHCP");
      if (!ether.dhcpSetup()){
        Serial.println( "DHCP failed");
      }
    #endif

      ether.printIp("My IP: ", ether.myip);
      ether.printIp("GW IP: ", ether.gwip);
      ether.printIp("DNS IP: ", ether.dnsip);
    }

    void loop () {

      word len = ether.packetReceive();
      word pos = ether.packetLoop(len);

      // IF LED10=ON turn it ON
      if(strstr((char *)Ethernet::buffer + pos, "GET /?LED10=ON") != 0) {
      Serial.println("Received ON command");
      digitalWrite(ledPin10, HIGH);
    }

    // IF LED10=OFF turn it OFF
    if(strstr((char *)Ethernet::buffer + pos, "GET /?LED10=OFF") != 0) {
      Serial.println("Received OFF command");
      digitalWrite(ledPin10, LOW);
    }

    // show some data to the user
    memcpy_P(ether.tcpOffset(), page, sizeof page);
    ether.httpServerReply(sizeof page - 1);
    }

[![circuit][1]][1]

  [1]: https://i.stack.imgur.com/P9bS8.png

title: Slow response from ENC28J60

Answers: 0


body:
My objective is if ultrasonic readings ranging between 1 to 10 cm and no distance change for 10 seconds or more, a LED will turn on. Here is my current code.

    #define trigPin 7
    #define echoPin 8
    #define led 13
    #define led2 12

    long duration, distance, interval = 4000;
    int detection = 0;

    void setup() {
       Serial.begin (9600);
       pinMode(trigPin, OUTPUT);
       pinMode(echoPin, INPUT);
       pinMode(led, OUTPUT);
       pinMode(led2, OUTPUT);
       detection = millis();
    }

    void loop() {

       ultraSonic();

       if (distance > 0 && distance < 10 && (millis() - detection >= interval)) {
       digitalWrite(led, HIGH);
       digitalWrite(led2, LOW);
       } else {
       digitalWrite(led, LOW);
       digitalWrite(led2, HIGH);
       }

       Serial.print(millis());
       Serial.print(" - ");
       Serial.println(distance);

       delay(250);
    }

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

Sorry for my bad english.
Cheers.

title: How to turn a LED if ultranonic HC-SR04 reading is on defined range for some interval

Answers: 2

body:
    void loop() {

       ultraSonic();

       if ((distance > 0) && (distance =< 10)) {
       digitalWrite(led, HIGH);
       digitalWrite(led2, LOW); // turning LED on
       } else {
       digitalWrite(led, LOW);
       digitalWrite(led2, HIGH); // turning LED off
       }

       Serial.print(millis());
       Serial.print(" - ");
       Serial.println(distance);

       delay(250);
    }

body:
Based on previous answer and your comment, maybe you can try this one
I assume if the range is ranging 1-10 cm for 10 secs or more the led will turn on:

    void setup() {
       Serial.begin (9600);
       pinMode(trigPin, OUTPUT);
       pinMode(echoPin, INPUT);
       pinMode(led, OUTPUT);
       pinMode(led2, OUTPUT);
    }
    int togle = 0;

    void loop() {

       ultraSonic();

       if ((distance >= 1) && (distance =< 10)) //dont use (distance>0)
       //there are possibility you get 0.xx distance
       {
         Serial.print("Distance on range - ");
         if (toggle == 0)
           {
            toggle=1;
            detection=millis();
            Serial.println("last detection outside range");
           } else
      if (toggle == 1)
      {
            Serial.print("last detection in range - ");
      if ((millis()-detection) >= interval)
       {
        Serial.println("objective complete");
       }
            else Serial.println("not enough interval");
      }
       } else
       {
      //turn off the led
      Serial.println("Distance out of range");
         toggle = 0;
       }

    }

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

Feel free to tell if something is not right


body:
Is there a way to make a listener for a key press to begin a loop?

Example:  I press the <kbd>Tab</kbd> key on my keyboard and the programmed loop begins running.

Essentially creating a keyboard hotkey.

title: Keyboard key press listener

Answers: 1

body:
The answer is yes and no.

Only the Arduino and its IDE, no.

The way I found is to use Processing to wait until it detects a hotkey, then send a serial message to your Arduino. If you tune in the right COM port, this should work.


body:
I was trying to evaluate the speed of communication between pc and Arduino, using this code in Arduino:

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

    void loop() {
      Serial.println("Ciao Arduino");
    }

and this in Python:

    import time, serial

    arduino = serial.Serial('/dev/cu.usbmodem1421', 250000)

    time.sleep(3)
    count = 0
    start = time.time()
    while True:
       a = arduino.readline()
       print a
       count = count+1
       time1 = time.time()
       if time1-start >1 :
          print "--" + str(count)
          print a
          count = 0
          start=time1

Wich print out how many readline() he managed to do to evaluate the speed in further project.
And I realized two things:

 1. The program is working even with different baudrate
 2. and with correct baudrate(For ex. 300-300 or 250000-25000) the baudrate is irrelevant(and wrong), I mean the 300 baudrate makes 20000 readline() and the 250000 make 5000 of them.

What's the problem? thank you

title: What's the problem with baudrate?

Answers: 1

body:
On a direct USB CDC/ACM connection (as you get on the Micro) there is no such thing as baud rate.

Any baud rate setting performed by the host (the PC) is merely an instruction to the device (the Arduino) to say "I would like you to operate at this speed", not "I would like you to communicate with me at this speed".

It is used in situations where the PC may want to set the baud rate of a real UART interface within the device, such as when the ATMega16U2 is used as a USB interface on the Uno - in that case the PC tells the 16U2 that it wants to communicate at, say, 115200 baud, and the 16U2 sets its UART (the one that communicates with the ATMega328P) to 115200 baud. The actual PC to ATMega16U2 (or ATMega32U4 in the case of the Micro) is at the native USB 2 bulk packet rate.

[![enter image description here][1]][1]

It is also used as a "reset" instruction to the ATMega32U4 - if the CDC/ACM port is opened by the PC at 1200 baud and then immediately closed again the 32U4 resets and enters the bootloader. This makes programming (usually) easy, as long as the program on the chip hasn't crashed and left the USB interface in an unusable condition (as sometimes happens).

  [1]: https://i.stack.imgur.com/ekeB1.png


body:
I have some SN74HC165N, CD4021B chips. How many (minimally) such ICs would I need to get 70 inputs to an Arduino Uno? What is the exact circuit diagram and the code? Im not sure how the wring cascades into each of the chips to make it grow to over 70 inputs, or what the code is for the 70 input circuit. I do understand how to use one of those ICs though. My second easier question is -is there an development board with 70 or more inputs?

CD4021B,SN74HC165N are the chips, you know the ones, that has a parallel input pins that are listened to by latch pin, and the clock pins such outputs the parallel data into the serial data-so I am interested with solution with this pin because I know how it works.

It is for sure 70 pins that are required -not any less-I am sure of that. Because the inputs cannot be further simplified to less than 70. The reason the inputs are 70 is because the algorithm used has 70 free variables in it. Hence by definition it uses 70 or more variables. The input for each of the 70 inputs can be a digital high or a digital low but this is not known before hand. So it cant be simplified because it like saying you can simplfy the information from 70 or more sensors at runtime, and each sensor has an unpredictable value. Anyway this explanation is moving away from the point of my question. I just want to know the circuit that does 70 inputs or more using the mentioned IC-I can live with that answer even if its not the most efficient.

title: I need 70 or more input pins for the Arduino -how to do this?

Answers: 2

body:
> I have some 74HC595 chips. How many (minimally) 74HC595 would I need to get 70 inputs to an Arduino Uno?

None. Those chips are for output, not input.

> I do understand how to use one 74HC595 though.

Evidently not, since you don't even know what they do.

>  My second easier question is -is there an development board with 70 or more inputs?

Yes, there are. None made by Arduino though, but there are plenty of other options. Myself I work with microcontrollers with hundreds of IO pins.

However, I think you need to re-think what you are trying to achieve. There are many options for reducing the number of inputs you need to use depending on what it is you are doing. Maybe if you told us a little more about what you want to do, not how you think you want to do it, we can help you a little more.

body:
The best way I know to do it is by using the MCP23017, which gives you 16 extra GPIOs via I²C communication. They can be configured for both input and/or output. I've done it myself and it worked like a charm. It has 3 pins for dynamic addressing (3 bits), which allows you to use up to 8 (0..7) MCP23017 for a total of **128** extra GPIOs.
This is the chip datasheet:
(http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf)
There's a lot of examples about its use on the internet. Just google for "MCP23017 arduino" and you'll find them. For example:
http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/


body:
At the moment I am following the instructions of this project [https://github.com/JoernL/LimiTTer][1]. Besides the peripheral parts like a Bluetooth module and an NFC module, the central unit is an Arduino Pro Mini.
I am a bloody novice with Arduino and just taught myself how to solder stuff. So far, I successfully uploaded the program from the project above to the Arduino Mini Pro and will continue as soon as the other parts arrive.

Anyhow, since I am strictly following the instructions I have some serious knowledge gaps and hope you can help me out. So, for instance.

 - How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?
 - How can I delete a program from the Arduino board?
 - When I upload a program, will the program that is already on the Arduino been overwritten?
 - Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

  [1]: https://github.com/JoernL/LimiTTer

title: delete the memory or re-upload a program

Answers: 1

body:
>How do I know, how much storage capacity is available on the Arduino board before and after I uploaded something?

In yellow is how much bytes does your program take.

In purple is how much bytes are available on your board.

In green is how many bytes does your **global** variables take.

In orange is how many bytes are left for **local** variables.

In blue is how many bytes are available for **all** of your variables.

In red is the general specs of your board and to which COM port it is connected to.

[![enter image description here][1]][1]

---

>How can I delete a program from the Arduino board?

Once  a new program is uploaded, the old one is deleted (somewhat). Still, you get all your bytes back and it is like if you start from scratch

---

>When I upload a program, will the program that is already on the Arduino been overwritten?

Yes.

---

>Is an Arduino generally used to execute one specific program and not to hold a set of totally different programs?

An Arduino can only execute 1 program at the time. It doesn't usualy hold on to any other programs, but can store 1024 bytes in it's EEPROM. This lets your write in the EEPROM with a program and access that data with an other.

  [1]: https://i.stack.imgur.com/2MTAr.png


body: I'm looking for a counter that can be incremented and will overflow with predictable behavior, preferably reset to 0 on overflow. I've tried using integers for counting but I'm getting weird overflow issues. Is there some library that provides an implementation of a counter?

title: Is there a counter library in Arduino?

Answers: 1

body:
Since you dont give the largest number your counter over flows at. You may want to look at libraries that implement arbitrary size integers. This means that there the integers can be bigger than usual - You would need to implement a counter, reset to 0 if the integer gets too big (just use a if statement if what youre doin is that simple-it sounds like it). So its entirely predictable for your purpose (whatever that is you didnt state). If you google around you will find libraries for arbitrary large integers for arduino e.g.

https://forum.arduino.cc/index.php?topic=85692.0

a library by Nick Gammon.


body:
After hours of searching for a solution and try many ways of wiring, I must asking here for Help:

I'm using a ESP8266 (ESP-12E) with a WS2801 - 4 Wire LED Strip and using this Pinout-Diagram to connect WS2801 wires to NodeMCU.

https://alexbloggt.com/wp-content/uploads/2015/10/nodemcu_pinout_700.png

Here is my Wiring:

    LED     ESP
    ====   =====
    5V --> Vin
    GND --> GND
    CK --> GPIO2 (D4)
    SI --> GPIO3 (RX)

I have found this sample Program which should turn on and off all LEDs one after each other for 100ms. But it happens nothing after compiling and uploading it to NodeMCU board using Arduino IDE. Any help is highly appreciated.

[![enter image description here][1]][1]

    //This program was taken from the FirstLight.ino supplies with the FastLED library
    // It has been modified for use with a NodeMCU for use in a tutorial by NQMakerSupplies.com.au
    // Hosted at theMakers.org.
    //
    // Special thanks to the people behind FastLED.io and all the contributors :)

    #define FASTLED_ESP8266_NODEMCU_PIN_ORDER   // map output pins to what they are called on the NodeMCU
    #include "FastLED.h"

    ///////////////////////////////////////////////////////////////////////////////////////////
    //
    // Move a white dot along the strip of leds.  This program simply shows how to configure the leds,
    // and then how to turn a single pixel white and then off, moving down the line of pixels.
    //

    // How many leds are in the strip?
    #define NUM_LEDS 10

    // Data pin that led data will be written out over
    #define DATA_PIN 3

    // Clock pin only needed for SPI based chipsets when not using hardware SPI
    #define CLOCK_PIN 2

    // This is an array of leds.  One item for each led in your strip.
    CRGB leds[NUM_LEDS];

    // This function sets up the ledsand tells the controller about them
    void setup() {
        // sanity check delay - allows reprogramming if accidently blowing power w/leds
       delay(2000);
       FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    }

    // This function runs over and over, and is where you do the magic to light
    // your leds.
    void loop() {
       // Move a single white led
       for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed = whiteLed + 1) {
          // Turn our current led on to white, then show the leds
          leds[whiteLed] = CRGB::White;
          // Show the leds (only one of which is set to white, from above)
          FastLED.show();
          // Wait a little bit
          delay(100);
          // Turn our current led back to black for the next loop around
          leds[whiteLed] = CRGB::Black;
       }
    }

  [1]: https://i.stack.imgur.com/uENwt.png

title: Wiring and Connecting WS2801 to NodeMCU ESP8266

Answers: 1

body:
Changing the first line from

     #define FASTLED_ESP8266_NODEMCU_PIN_ORDER
to

     #define FASTLED_ESP8266_RAW_PIN_ORDER
has solved the Problem.


body:
I made some arduino code for leds that blink down a row and then back again, but when the program is run, there is an approximately 2 second delay in between the first for loop and the second. This is my code in the loop function:

    int leds[] = {13, 12, 11};
    int i;

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

      for (int i = 0; i < sizeof(leds); i ++) {
         pinMode(leds[i], OUTPUT);
      }
    }

    void loop() {
        for (i = 0; i < sizeof(leds); i ++) {
           digitalWrite(leds[i], HIGH);
           delay(250);
           digitalWrite(leds[i], LOW);
        }
        for (i; i > 0; i --) {
           digitalWrite(leds[i], HIGH);
           delay(250);
           digitalWrite(leds[i], LOW);
        }
    }

It really makes the program look weird when the LEDs are blinking on a breadboard. Keep in mind that this only happens after the first for loop, the second is continuous back to the first. Any idea why this might be and how to fix it?

title: Unexpected Delay Between For Loops

Answers: 3

body:
The cause it that your 3rd led (2nd element in the array) is repeated twice.

Try this instead:

    int leds[3] = {13, 12, 11};

    void setup() {
      for (int i = 0; i < 3; i++) {
        pinMode(leds[i], OUTPUT);
      }
    }

    void loop() {
      for (int i = 0; i < 2; i++) {
        digitalWrite(leds[i], HIGH);
        delay(250);
        digitalWrite(leds[i], LOW);
      }
      for (int i = 2; i > 0; i--) {
        digitalWrite(leds[i], HIGH);
        delay(250);
        digitalWrite(leds[i], LOW);
      }
    }

body:
The claim “The cause it that your 3rd led (2nd element in the array) is reapeted twice” is wrong.

Apparently that sentence is supposed to mean that the long delay is due to `i` being one too large, coming out of the first loop and entering the second one.  Indeed, `i` *is* too large, but that's because each element of the array is a 2-byte `int`, so that instead of `for (int i = 0; i < sizeof(leds); i ++)` being equivalent to `for (int i = 0; i < 3; i ++)`, it is equivalent to `for (int i = 0; i < 6; i ++)`.

Thus, one second goes by with an extra 4 occurrences of `delay(250);` in the first loop, and another one second with 4 extra occurrences of `delay(250);` in the other loop.

To correct the problem, write `sizeof leds/sizeof leds[0]` instead of `sizeof(leds)`, and write for `(--i; i > 0; i--)` instead of `for (i; i > 0; i --)`.

body:
The problem is on "for loops" condition,
Try this:

    int leds[] = {13, 12, 11};
    int i;

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

      for (int i = 0; i < (sizeof(leds)/sizeof(leds[0])); i ++) {
         pinMode(leds[i], OUTPUT);
      }
    }

    void loop() {
        for (i = 0; i < (sizeof(leds)/sizeof(leds[0]); i ++) {
           digitalWrite(leds[i], HIGH);
           delay(250);
           digitalWrite(leds[i], LOW);
        }
        for (i=((sizeof(leds)/sizeof(leds[0])-1); i>=0; i --) {
           digitalWrite(leds[i], HIGH);
           delay(250);
           digitalWrite(leds[i], LOW);
        }
    }


body:
I use  [`RH_RF24.h`][1] to control Si4463, and realize some simple communication between two Si4463 . But I don't know the mean of `RH_RF24_MAX_MESSAGE_LEN` in this [example][2].

 `RH_RF24_MAX_MESSAGE_LEN` is a constant ? If so , what decides it ? And if I need to sent and receive  a long  char string , how to do it ?

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/classRH__RF24.html
  [2]: http://www.airspayce.com/mikem/arduino/RadioHead/rf24_client_8pde-example.html

title: RH_RF24_MAX_MESSAGE_LEN in RH_RF24.h

Answers: 1

body:
`RH_RF24_MAX_MESSAGE_LEN` is probably defined in the header file RH_RF24.h.

It doesn't matter what size it is, you should always use `RH_RF24_MAX_MESSAGE_LEN` rather than the number because the value might change in the library and this will break your code if you have used the number.

If you want to send a message that is larger than `RH_RF24_MAX_MESSAGE_LEN` then you will need to 'fragment' the message (unless the library supports that).
I would use the first byte of the message as the type of message and define one of those types as a multi part string.  Then send a number of these message and reassemble the data on the receiver. When the receiver sees a message that contains a character with the ASCII value 0 then that is the end of the string.


body:
I have an Arduino Pro Mini 3.3v in a robot. The problem is, the Mini would automatically randomly overwrite the uploaded sketch with the default blink sketch... And this is becoming quite a problem.

I have connected the Arduino to a L293D Motor Driver and the Arduino gets its power from the motor driver only. It will work just fine, but randomly will reset to the blink sketch...

Please help

P.S- It automatically corrected after a while

title: Arduino Pro Mini automatically resetting

Answers: 1

body:
The most obvious cause for a reset is pulling to much current from the Arduino.  I have never heard of an Arduino downloading a new sketch to itself.  Is it possible you are seeing the board booting up and flashing the LED as its doing so?

If you are getting the power from the motor driver its possible you are either giving the board noisy/dirty power or the motor is pulling to much current and depriving the board of power.  I would run them on separate supplies (with a common ground) to avoid this.


body:
I am trying to call a web service from a server but didn't get the correct response on Serial Monitor arduino, i get the error "hostname is invalid". Below is the code along with the result:

Thanks @Edgar Bonet, i have tried as you suggested. Following is the correction and the result, now the error is "The request verb is invalid"
    {

    EthernetClient client1;

    //second
    int inChar;
    char outBuf[64];
    char params[65];

    Serial.print(F("Method 2 connecting..."));

    if(client1.connect("198.38.93.76",807) == 1)
    {
    Serial.println(F("connected"));

    // send the header
    client1.println(F("POST /JMS_Auth_WebService.asmx HTTP/1.1"));
    client1.println(F("Host: 198.38.93.76"));
    client1.println(F("Content-Type: text/xml; charset=utf-8"));
    client1.println(F("Content-Length: 315"));
    client1.println(F("Connection: keep-alive"));
    client1.println(F("SOAPAction: \"http://jbscrms.com/GetThresholdOfDeviceForSaud\""));
    client1.println();

    client1.println(F("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
    client1.println(F("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"));
    client1.println(F("<soap:Body>"));
    client1.println(F("<GetThresholdOfDeviceForSaud xmlns=\"http://jbscrms.com\">"));
    client1.println(F("<Device_id>2</Device_id>"));
    client1.println(F("</GetThresholdOfDeviceForSaud>"));
    client1.println(F("</soap:Body>"));
    client1.println(F("</soap:Envelope>"));

    Serial.println(F("Done Calling New Web Service"));

    }
    else
    {
    Serial.println(F("failed"));

    }

    int connectLoop = 0;

    while(client1.connected())
    {

    if(client1.available())
    {
    inChar = client1.read();

    Serial.write(inChar);
    connectLoop = 0;
    }

    delay(1);
    connectLoop++;
    if(connectLoop > 30000)
    {
    Serial.println();
    Serial.println(F("Timeout"));
    client1.stop();
    }
    }

    Serial.println();
    Serial.println(F("disconnecting."));
    client1.stop();
    }

 Following is the result on Serial monitor arduino

    Ready
    Entered<R_TempData>29</R_TempData>
    <R_smokeData>226</R_TempData>
    <R_humidityData>36</R_TempData>
    Method 2 connecting...connected
    Done Calling New Web Service
    HTTP/1.1 400 Bad Request
    Cache-Control: private
    Content-Type: text/xml; charset=utf

    -8
        Server: Microsoft-IIS/8.5
        X-AspNet-Version: 4.0.30319
        X-Powered-By: ASP.NET
        Date: Fri, 11 Nov 2016 07:23:28 GMT

    Content-Length: 0

    HTTP/1.1 400 Bad Request
    Content-Type: text/html; charset=us-ascii
    Server: Microsoft-HTTPAPI/2.0
    Date: Fri, 11 Nov 2016 07:23:28 GMT
    Connection: close
    Content-Length: 326

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
    <TITLE>Bad Request</TITLE>
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Verb

HTTP Error 400. The request verb is invalid.

    disconnecting.

title: Host name is unvalid

Answers: 1

body:
 1. I think you need a \r\n between the Post statement and the HTTP statement.
 2. Why are you including the Port number in the Host name?
 3. Your SOAPAction line is wrong, but I guess that's a typo in the post.


body:
So for my project I have one Arduino Mega hooked up with a quadrature rotary encoder which is connected to the computer. An Arduino Uno is connected to a circuit I built, which in turn is connected to a valve and a touch connector (also connected to the computer via USB). Both of them should be controlled with a Python script.

If the rotary encoder is moved, I can read out a value via the serial port. The value of the rotary encoder is used in Python to move a dot on the screen. If the dot on the screen reaches a certain point, I want to give a signal to the valve to open (something like `pin.write(1)` to turn on or `pin.write(0)` to turn it off). At the same time I want to be able to detect the touch sensor if the circuit is closed.

The issue is now that I need to somehow need to read the rotary encoder, process the data and send it to the valve, as well as reading the touch sensor simultaneously. So far I have not found a way how to achieve this as my code does not function.

At the moment I have custom code on My Arduino Mega and a `StandardFirmata` on the Arduino Uno, but I am open to other suggestions that could work.

Arduino Mega code:

    /*
    by Ben-Tommy Eriksen
    https://github.com/BenTommyE/BenRotaryEncoder
    */

    // Encoder connect to digital pin 2 and 3 on the Arduino.

    int counter = 0;
    //This variable will increase or decrease depending on the rotation of encoder

    void setup() {
      Serial.begin (4600);
      //Setting up interrupt
      //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
      attachInterrupt(0, ai0, RISING);
      //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
      attachInterrupt(1, ai1, RISING);
    }

    void loop() {
      // Send the value of counter
      Serial.println (counter);
    }

    void ai0() {
      // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
      // Check pin 3 to determine the direction
      if(digitalRead(3)==LOW) {
        counter++;
      } else {
        counter--;
      }
    }

    void ai1() {
      // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
      // Check with pin 2 to determine the direction
      if(digitalRead(2)==LOW) {
        counter--;
      } else {
        counter++;
      }
    }

Python code:

    import pyfirmata
    import serial
    import time

    #Associate pyfirmata with python for my UNO board
    port='COM5'
    board= pyfirmata.Arduino(port)
    #Use iterator thread to avoid buffer overflow
    it = pyfirmata.util.Iterator(board)
    it.start()

    #Define pins (giving roles to pins: i.e. d=digital,7=pin number,i=input)
    lickPin = board.get_pin('d:10:i') #records signal from the touch sensor
    outPin1 = 12 #passes the signal to the valve

    s = serial.Serial('COM4',4600)
    while time<60s #generalized:
        rotary = s.readline() #reads the counter of the rotary encoder form arduino

        #convert the rotary to an integer try/except is needed to work
        try:
            var = long(rotary)
            last_var = var
        except:
            var = last_var
            pass

        value1 = lickpin.read()

        # Here I move the cursor up and down depending on the rotation of the encoder
        # if the cursor moves above a certain value
        if y>-18:
            board.digital[12].write(1) #should open the valve

Unfortunately the code above does not trigger the valve to be opened, and I do not know why. Help is greatly appreciated. Thanks!

title: Read/write data from 2 Arduinos simultaneously with Python

Answers: 1

body:
I wrote a simple sketch to read a KY-040 encoder with an Arduino UNO (or nano) board and to display the output in the Arduino IDE serial plotter (CTRL + SHIFT + L).

Here is the pinout:

 ENCODER            ARDUINO UNO
 ====================================
    GND            ⇒   GND
    +              ⇒   +5V
    SW  (button)   ⇒   pin D4 (PORT D4)
    DT  (encoder)  ⇒   pin D3 (PORT D3)
    CLK (encoder)  ⇒   pin D2 (PORT D2)

Here is a screenshot of the output in the serial plotter:

[![KY-040 encoder output in Arduino IDE serial plotter][1]][1]

Here is the picture of a project I am doing now (you need only the Arduino and the encoder for the sketch to work):

[![horloge cycles ultradiens Arduino nano + KY-040 encoder][2]][2]

And here is the code :

    /*
    LECTURE D’UN ENCODEUR ROTATIF KY-040
    ====================================
    # DESCRIPTION DU PROGRAMME
    Lecture d’un encodeur rotatif KY-040 pour affichage dans le traceur
    série de l’IDE Arduino (CMD-SHIFT-L).
    La rotation du bouton est détecté avec des interruptions sur les
    broches 2 et 3 du port D.
    Ce programme implémente un filtrage des rebond en deux étapes (voir
    la procédure “lectureEncodeur”).
    Ce programme est basé sur celui d’Oleg Mazurov
    https://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino
    Pour la gestion des interruptions, voir
    https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
    # RÉFÉRENCE DE L’ENCODEUR
    http://www.banggood.com/5Pcs-5V-KY-040-Rotary-Encoder-Module-For-Arduino-AVR-PIC-p-951151.html
    # CONNEXIONS DE L’ENCODEUR KY-040 SUR ARDUINO NANO
        GND            ⇒   GND
        +              ⇒   +5V
        SW  (bouton)   ⇒   pin D4 (PORT D4)
        DT  (encodeur) ⇒   pin D3 (PORT D3)
        CLK (encodeur) ⇒   pin D2 (PORT D2)
    juin 2016, ouilogique.com
    */

    #define ENC_A 2
    #define ENC_B 3
    #define ENC_C 4
    #define ENC_PORT PIND
    #define BtnRead  ! bitRead( ENC_PORT, ENC_C )

    bool encodeurTourne = false;
    byte ENC_PORT_VAL = 0;

    // Modifier ici la sensibilité de l’encodeur pour qu’il ne réagisse
    // pas trop vite. Cette valeur représente le nombre de millisecondes
    // avant un changement sur la sortie.
    static const long sensibiliteEncodeur = 10;

    // Gamme de sortie de l’encodeur. À modifier en fonction de l’application.
    static const int8_t minVal = 0;
    static const int8_t maxVal = 10;

    void setup()
    {
      pinMode( ENC_A, INPUT_PULLUP );
      pinMode( ENC_B, INPUT_PULLUP );
      pinMode( ENC_C, INPUT_PULLUP );

      PCICR  |= ( 1<<PCIE2 );
      PCMSK2 |= ( 1<<PCINT18 );
      PCMSK2 |= ( 1<<PCINT19 );
      PCMSK2 |= ( 1<<PCINT20 );
      PCMSK2 |= ( 1<<PCINT21 );

      encodeurTourne = true;

      Serial.begin( 115200 );
    }

    void loop()
    {
      static int8_t compteur = 0;

      // Lecture et affichage des valeurs de l’encodeur
      // dans le traceur série de l’IDE Arduino (CMD-SHIFT-L)
      if( encodeurTourne )
      {
        int8_t encodeurVal = lectureEncodeur();

        // Si le bouton est pressé, on remet le compteur à 0.
        if( encodeurVal == 2 )
        {
          compteur = 0;
          Serial.println( 0 );
          while( BtnRead ){ _delay_ms( 1 ); }
          _delay_ms( 20 );
        }

        // Sinon on met le compteur à jour en le gardant dans la gamme minVal..maxVal.
        else if( encodeurVal != 0 )
        {
          if( compteur < minVal || ( compteur == minVal && encodeurVal < 0 ) )
            { compteur = minVal; }
          else if( compteur > maxVal || ( compteur == maxVal && encodeurVal > 0 ) )
            { compteur = maxVal; }
          else
            { compteur = compteur + encodeurVal; }

          Serial.println( compteur );
        }
        encodeurTourne = false;
      }
    }

    /*
      lectureEncodeur() retourne
      -1 pour une rotation dans le sens anti-horaire
       0 pour une valeur impossible (rebond)
      +1 pour une rotation dans le sens horaire
      +2 si le bouton de l’encodeur est pressé
    */
    int8_t lectureEncodeur()
    {
      // Si le bouton est pressé, on quitte en retournant 2.
      if( ! bitRead( ENC_PORT_VAL, ENC_C ) )
      {
        return( 2 );
      }

      // Lecture des signaux de l’encodeur et comparaison
      // avec les valeurs possibles dans le code de Gray.
      // Ceci permet de filtrer la plupart des rebonds de l’encodeur.
      // Les valeurs à 0 représentent les transitions impossibles
      // et qui doivent être supprimées (resultat = 0).
      // Les valeurs à 1 représentent les transitions dans le sens horaire.
      // Les valeurs à -1 représentent les transitions dans le sens anti-horaire.
      static const int8_t enc_states[ 16 ] PROGMEM =
        { 0,-1, 1, 0, 1, 0, 0,-1,-1, 0, 0, 1, 0, 1,-1, 0 };
      static uint8_t old_AB = 0;

      old_AB <<= 2;
      bitWrite( old_AB, 0, bitRead( ENC_PORT_VAL, ENC_A ) );
      bitWrite( old_AB, 1, bitRead( ENC_PORT_VAL, ENC_B ) );
      uint8_t resultat = pgm_read_byte( &enc_states[ ( old_AB & 0x0F ) ] );

      // On accumule “maxVal” résulats dans un sens ou dans l’autre
      // avant de bouger. Ceci permet de supprimer les derniers rebonds
      // de l’encodeur qui n’ont pas été filtrés ci-dessus.
      if( resultat != 0 )
      {
        static int8_t resultatCumul = 0;
        const int8_t maxVal = 2;
        resultatCumul += resultat;
        if( resultatCumul >= maxVal )
        {
          resultatCumul = maxVal;
          resultat = 1;
        }
        else if( resultatCumul <= -maxVal )
        {
          resultatCumul = -maxVal;
          resultat = -1;
        }
        else
          { resultat = 0; }
      }

      // On rejete quelques lectures pour limiter la sensibilité de l’encodeur
      // et éviter ainsi qu’il ne tourne trop vite.
      static long lastT = millis();
      if( millis() - lastT < sensibiliteEncodeur )
        { resultat = 0; }
      else
        { lastT = millis(); }

      // On retourne le résultat.
      return( resultat );
    }

    ISR( PCINT2_vect )
    {
      ENC_PORT_VAL = ENC_PORT;
      encodeurTourne = true;
    }

  [1]: https://i.stack.imgur.com/v2QhZ.png
  [2]: https://i.stack.imgur.com/uXelt.jpg


body:
I use Fedora 24/25 and now Ubuntu 17.04 Gnome on my Lenovo Yoga 900, which has an extremely high pixel density display. For these situations on Mac and Windows, I find a `gui.scaling` option in the Arduino settings. However, on Linux there is no such option, and entering it in `~/.arduino15/settings.txt` does not have any effect.
The version I use is Arduino 1.6.4 (now 2.1.0.5) from the Fedora (Ubuntu) repos. Is the scaling gui option not implemented on linux? Or is there some fix for this?
On the physical display the following screenshot has an approximate width of 4cm -> the green buttons are not usable at all!
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/IEeKX.png

title: Gui Scale on Linux HD display

Answers: 0


body:
I am trying to make my own delay function. Briefly `mydelay` function is calling `toggled` function every `secs` seconds. The code is not well written, i know (this is the first version). But i am just trying to get it work properly. Then i will refactor it. But i have some unexpected bugs. First time the loop in `x` function is working properly. It is printing "I am in while" for 1 second and then it prints "Im ending mydelay" which is the behaviour i want. But after finishing the loop in `x`. The second time when it loops. It enters the `mydelay` function (that is ok). But then it is not printing "I am in while" at all. It just prints "Im ending mydelay" which is not good.

Here is the code:

    #include <Arduino.h>
    int led = 7;
    void setup() {
      Serial.begin(9600);
      pinMode(led, OUTPUT);
    }

    void loop() {
      x();
      Serial.println("Im ending main loop");
    }

    void x() {
      for (int i = 0; i <= 10; i++) {
        mydelay(led, 0, 1);
        mydelay(led, 1, 1);
      }
    }

    void mydelay(int pin, int hol, int secs) {
      int starttime = millis();
      while ((millis() - starttime) <= (secs * 1000)) Serial.println("I am in while");
      toggled(pin, hol);
      Serial.println("Im ending mydelay");
    }

    void toggled(int pin, int hol) {
      digitalWrite(led, hol);
    }

title: Arduino creating delay function

Answers: 2

body:
As mentioned in the comments, your main problem is you declare `starttime` as an `int`. This is a signed value with a range of -32,768 to 32,767. You will quickly overflow - in about 32 seconds.

The solution is to use an `unsigned long` which has a range of 0 to 4,294,967,295.

body:
You can try something along these lines:

    void verboseDelay(unsigned long ms)
    {
        unsigned long now = millis();
        Serial.print(F("delaying"));
        unsigned long start = now, lastPrintTime = now;
        do {
            now = millis();
            if (now - lastPrintTime >= 20) {
                Serial.write('.');
                lastPrintTime += 20;
            }
        } while (now - start < ms);
        Serial.println();
    }

The trick is to used `unsigned long` for all the time-related variables,
and also to avoid printing too fast.


body:
For a project, I need to connect more than one device to an Arduino through a serial port with hardware flow control (RTS/CTS).

Sparkfun used to make breakout boards for the [SC16IS750][1], but this product is discontinued and I can't find any place to order it. There are also plenty of ICs doing what I need, but I am not keen on soldering SMD components and I cannot find any products coming in e.g. an old fashioned DIP package.

Does someone know about an available breakout board or a DIP packages I2C to UART bridge? Since the device will be battery powered, I would prefer a dedicated low-power circuit instead of a programmed microcontroller as suggested by majenko.

  [1]: https://www.sparkfun.com/products/retired/9745

title: I2C to UART bridge as breakout or in DIP package

Answers: 1

body:
Perhaps what you're looking for:

http://sandboxelectronics.com/?product=sc16is750-i2cspi-to-uart-bridge-module

---

From that page:

[![SC16IS750 I2C/SPI to UART Bridge Module][1]][1]

> ## SC16IS750 I2C/SPI to UART Bridge Module
>
> This module is designed to enable I2C/SPI to UART conversion. It works in I2C/SPI slave mode and interfaces with devices working in I2C/SPI master mode. There are also 4 extra GPIOs for IO expansion. NXP SC16IS750 is used as the key component on this module. Flow control and modem signals are also supported.
>
> This module is useful when extra UART interface is needed. Due to the multi-slave characteristics of I2C and SPI, many UART interfaces could be added to the system at the same time.

  [1]: https://i.stack.imgur.com/Xkv8y.jpg


body:
In my little weather station I collect temperature, humidity, MQ-2 smoke sensor, and wind speed readings for display on a 20x4 LCD display, every 500 ms.
The Anemometer readings jump up and down by quite a bit.

Initialization of variables before Setup is like so:

    // Wind Speed Anemometer
    const int sensorPin = A3;
    int sensorValue = 0;
    float sensorVoltage = 0;
    float windSpeed = 0;
    float voltageConversionConstant = 0.004887586;  // (5/1024)
    float voltageMin = .33;   // 0.4 in the documentation
    float windSpeedMin = 0;
    float voltageMax = 1.5;   // 2.0 in the documentation
    float windSpeedMax = 32;

 // 20 x 4  LCD Display
    #include <LiquidCrystal_I2C.h>
    // set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Then in Setup I initialize the LCD and flash the backlight.

    lcd.begin(20,4);
    lcd.clear();
    for(int i = 0; i< 3; i++) {
      lcd.backlight();
      delay(250);
      lcd.noBacklight();
      delay(250);
      }
    lcd.backlight(); // finish with backlight on

In Loop, I paint the initial screen then take readings and display them

    void loop() {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Weather");

      ...etc... to display time and show temp and humidity

      // Wind Speed
      sensorValue = analogRead(sensorPin);
      sensorVoltage = sensorValue * voltageConversionConstant;
      if (sensorVoltage <= voltageMin) windSpeed = 0;
      else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);
      lcd.setCursor(0,3);
      lcd.print(windSpeed);
      lcd.print(" MPH  ");

      ...etc... to display smoke detection...

      delay (500);
      }  // end loop

So the question is:  How can I slow down the Wind Speed fluctuations?  It jumps up and down quite widely.

title: How can I deal with rapid fluctuation of Anemometer readings?

Answers: 2

body:
A:  Use a running average

In the initialization I include an array to hold 10 values

    // Wind Speed Anemometer
    const int sensorPin = A3;
    int sensorValue = 0;
    float sensorVoltage = 0;
    float windSpeed = 0;
    float voltageConversionConstant = 0.004887586;  // (5/1024)
    float voltageMin = .33;   // 0.4 in the documentation
    float windSpeedMin = 0;
    float voltageMax = 1.5;   // 2.0 in the documentation
    float windSpeedMax = 32;

    float ws[10] = { };      // (initializes all to zero)
    int wsIndex = 0;
 float wsTot = 0.0;
 float wsDisplay = 0.0;

Then in the Loop I fill the array with values and display the average of the 10 readings stored there

      // Wind Speed
      sensorValue = analogRead(sensorPin);
      sensorVoltage = sensorValue * voltageConversionConstant;
      if (sensorVoltage <= voltageMin) windSpeed = 0;
      else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

      if (wsIndex<9) {
        ws[wsIndex] = windSpeed;
        wsIndex++;
        }
      else {
        wsTot = 0.0;
        for (int i=0;i<=9;i++) wsTot = wsTot + ws[i];
        wsDisplay = wsTot / 10.0;
        lcd.setCursor(0,3);
        lcd.print(wsDisplay);
        lcd.print(" MPH  ");
        wsIndex = 0;
        ws[wsIndex] = windSpeed;
        }

body:
How about this one, it supposed to press fluctuations of your sensors reading

    void loop(){
    ..
    ...
    ....
    last_reading = sensorValue2; //

    sensorValue = analogRead(sensorPin);
    sensorVoltage = sensorValue * voltageConversionConstant;
    if (sensorVoltage <= voltageMin) windSpeed = 0;
    else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

    sensorValue2 = (sensorValue+last_reading)/2;
    ....
    ...
    ..
    }


body:
I have some Arduino Pro Minis. I have both the 3.3V/8MHz and 5V/16MHz versions. I'm trying to get them to work with the [nRF24L01 RF modules][1].

I've lightly modified some example code from the RF24 library, and gotten it working with an Arduino Micro and Nano. Basically, I just send an increasing integer from one to the other, and the receiving one displays on an LCD the latest number it received, which lets me know if a transmitter is working.

So that all works. Now I'm trying to use a Pro Mini (tried both 3.3V and 5V versions) to transmit instead of the Nano I was using before. The regulator is a 3.3V LDO. The battery is supplying that LDO and the RAW pin of the Pro Mini with ~8.5V, which should be good. Measuring the voltage out of the LDO gives 3.3V.

I looked at the pinout of the Pro Mini, and I believe I've hooked up the module to the correct MOSI/MISO/SCK pins, as well as pins 7 and 8 for the module's CE and CSN pins.

Buuut... it's not working. Nothing is appearing on the LCD. I know the nRF and its header thing work fine, because I can pop the exact one into the circuit with the Nano that works.

Even more strangely, I'm pretty sure the Pro Minis are getting programmed successfully. I can upload the Blink example to them, and that works. I'm using an Adafruit FTDI friend to upload, and that appears to be working (compiles, uploads, etc without error).

[Here's the code I'm using for the transmitter][2], it's pretty simple. Does anyone have any suggestions? Thanks in advance. Let me know if there's anything I forgot to include.

edit: It won't let me include more than two links because of my low rep, so I can't include images of my ciruit/wiring. But I'll manually write it out here:

The numbering here is with respect to the pins in the nRF link above.

    nRF module pin           Arduino Pro Mini Pin
    1 (GND)           GND rail (not on Arduino)
    2 (VCC)           3.3V rail (from external regulator)
    3 (CE)           Digital pin 7
    4 (CSN)           Digital pin 8
    5 (SCK)           Digital pin 13
    6 (MOSI)           Digital pin 11
    7 (MISO)           Digital pin 12
    8 (IRQ)           Not connected to anything

  [1]: http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
  [2]: http://pastebin.com/hcN6Rds7
  [3]: https://i.stack.imgur.com/X7NLQ.png

title: Why is my radio circuit working with other arduinos but not the Pro Minis?

Answers: 0


body:
This is my first post. I hope that I am posting in the right section of the forum. Otherwise, could an admin move this topic to the appropriate section please?

Board : Arduino Pro Mini 3.3V 8MHz

Arduino IDE : 1.6.12
Arduino is powered by a FTDI Board and USB Mini-B cable from the computer USB port in the following order :

Arduino        FTDI

BLK              GND

GND             CTS

VCC             VCC

RXi              TX

TXo             RX

DTR             DTR

Also, I have connected a HC-06 bluetooth module in the following order :

Arduino    HC-06

GND         GND

VCC         VCC

D10         TXD

D11         RXD

The Serial Monitor is open on COM4, Newline, 9600 baud.

The code that I'm trying to run is :

    #include <SoftwareSerial.h>
    SoftwareSerial BT(10, 11);
    void setup()
    {
      pinMode(13, OUTPUT);
      BT.begin(9600);
      // Send test message to other device
      BT.println("Hello from BTSerial");

      Serial.begin(9600);
      Serial.println("Hello from Serial");
    }

    char a; // stores incoming character from other device
    void loop()
    {

      if (BT.available())
      // if text arrived in from BT serial...
      {
        a=(BT.read());
        if (a=='1')
        {
          digitalWrite(13, HIGH);
          BT.println("LED on");
        }
        if (a=='2')
        {
          digitalWrite(13, LOW);
          BT.println("LED off");
        }
        if (a=='?')
        {
          BT.println("Send '1' to turn LED on");
          BT.println("Send '2' to turn LED on");
        }
        Serial.println(a);
      }
    }

I am trying to communicate with the HC-06 from an Android phone.
I am posting in this section of the forum because when I send a message from the phone to Arduino the following is printed in the Serial Monitor :

    à„…€ƒ¦¤„„‡…§¤¦„‡Å„EóAãbBãbHãb

When I am trying to send a message from Arduino to the phone, nothing is received on the phone.

Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window?
Is there a problem with the Arduino IDE?

**Edit 12.11.2016**

This is what I get when I open the Serial Monitor in the Arduino IDE with this code :
Newline, Baud rate 9600

    ‚Æ‡¥Ç$¤†Fó

If I change the Serial Monitor properties to Newline, Baud rate 19200 this is what I receive :

    Hello from Serial

On the Android phone application I do not get anything printed.

Also, please note that this question is also addressed on the Arduino forum at the following link :
http://forum.arduino.cc/index.php?topic=434623.0
I will try and answer in both places as I am not sure that everybody has an account on the forum

title: Arduino Pro Mini Serial Monitor garbage

Answers: 4

body: Flip the RX and TX wires of the HC06. This is because this statement : `SoftwareSerial BT(10, 11); ` actually means `SoftwareSerial BT(RXpin, TXpin); `. Considering this, 10 is your Rx and 11 is your Tx. In this case, you have to connect pin 10 (software Rx) of your Arduino to the Tx pin of your HC06 and pin 11 (software Tx) to the Rx pin.

body:
> BLK GND
>
> GND CTS

That looks backwards to me. Connect GND to GND and CTS to BLK.

The bluetooth module operates at a predefined baud rate. You need to ensure that your Arduino communicates at that baud rate - you don't get to pick any old baud rate.

The baud rate can be changed with the `AT+UART=x` command (where `x` is a single digit representing the baud rate: `1=1200, 2=2400, 3=4800, 4=9600 (default), 5=19200, 6=38400, 7=57600, 8=115200, 9=230400, A=460800, B=921600, C=1382400`).  If the HC-06 isn't on the default baud rate of 9600 (which is highly possible) then you will have to guess what the right baud rate is. Work through the possible ones listed there in yopur `BT.begin(...)` function to see if one of them starts working.

body:
> Could someone please explain why I get garbage output on the Serial Monitor even though the baud rate is the same in the code as it is in Serial Monitor window? Is there a problem with the Arduino IDE?

Even if the baud of serial monitor and the code is same, there is a possibility that you have not configured your HC-06 to works on the same baud.
There are many ways to check and configure it by using AT-Command. You will easily found them since many tutorial has been written, here is some of the example :
[link 1][1]
[link 2][2]

  [1]: http://www.instructables.com/id/AT-command-mode-of-HC-05-Bluetooth-module/step4/Setting-up-connection/
  [2]: http://www.instructables.com/id/AT-command-mode-of-HC-05-Bluetooth-module/

body:
I had the same issue. The problem was solved in an other forum:
https://forum.arduino.cc/index.php?topic=434623.0
I copy the solution here:

    It appears that in fact your board is not running at 8MHz, but instead 16MHz.
    Please select the correct setting for your board:
    Tools > Processor > ATmega328(5V, 16MHz)
    Or if it has the ATmega168:
    Tools > Processor > ATmega168(5V, 16MHz)


body:
I'm trying to see how fast I can read an Arduino IO port.  It's being toggled with an random speed /white square wave and I want to see which is faster, the Arduino or the signal.  The pin on port D is driven by an open collector comparator (LM311).

So I have this code

buffer[0] = PORTD;
buffer[1] = PORTD;
buffer[2] = PORTD;
buffer[3] = PORTD;
buff...

...fer[28] = PORTD;
buffer[29] = PORTD;

 that I can read the port in burst mode.  This code is as fast as I can write I think.  I've unrolled a possible loop here.  buffer[] is a local variable as that seems faster.  I'm not an assembly expert so I can't really browse the assembly instructions.

I've added a 500 Ohm pullup resistor to the input pin that I'm interested in.  A lower value seems to give more randomly distributed values that a 10k resistor.

I tried timing buffer[0] ... buffer[29] readings and that returns 4 microseconds with interrupts off.  I hope that micros() doesn't need interrupts to function!  That would equate to 7.5 million readings /sec.  That's about 2 clock cycles per instruction on my 16 MHz board.  Can this be right?

How fast can this code run?

title: How fast can I read Arduino port D?

Answers: 2

body:
Your timing seems reasonable.

At a rough guess, without actually compiling it, your code will turn into something along the lines of:

    IN R24,PORTD  ;First read   - temp = PORTD     - 1 cycle
    ST X+, R24    ;First store  - buffer[0] = temp - 2 cycle
    IN R24,PORTD  ;Second read  - temp = PORTD     - 1 cycle
    ST X+, R24    ;Second store - buffer[1] = temp - 2 cycle
    ...

This is indeed the fastest way of reading the port if you want to keep the data. Basically it will do an IO read from PORTD using the `IN` instruction which takes 1 clock cycle. Then it will perform a store to SRAM using the `STS` instruction which takes another 2 clock cycles. The store instruction can also post increment the pointer it is using (stored in the R28/R29 X-register pair in my example) for free which saves you time.

So basically that should do 3 clock cycles for every read - one to do the read, and one to do the store, or >5 million reads per second from a 16MHz clock.

---

There will additionally be a couple of cycles at the beginning to set X-register to point to the buffer. If the buffer is a constant pointer - i.e. the buffer has a fixed address, it will only take two instruction cycles at the beginning to load the address. If it is a non-constant address, it will take up to four as it has to load the address from the SRAM.

body:
I just tried compiling your code with avr-gcc 4.9.2:

<!-- language: lang-c++ -->

    buffer[0]  = PORTD;
    buffer[1]  = PORTD;
    ...
    buffer[29] = PORTD;

Here is what I got:

<!-- language: lang-lisp -->

    in  r24,    0x0b  ; temp = PORTD     – 1 cycle
    sts 0x0110, r24   ; buffer[0] = temp – 2 cycles
    in  r24,    0x0b  ; temp = PORTD     – 1 cycle
    sts 0x0111, r24   ; buffer[1] = temp – 2 cycles
    ...

That's 3 cycles per read, i.e. a 5.33 Mhz reading frequency. For
some reason the compiler didn't want to use the `st X+, r24`
instruction suggested in Tom Carpenter's answer. Let's try to hint the
compiler a little bit, and rewrite the C code as follows:

<!-- language: lang-c++ -->

    uint8_t * p = buffer;
    *p++ = PORTD;
    *p++ = PORTD;
    ...

This generated the exact same assembly! The compiler somehow figured out
the address of each memory write, and it replaced each occurrence of the
pointer `p` by an explicit address. To prevent this kind of
“optimization”, let's make the pointer a variable whose value is unknown
at compile time:

<!-- language: lang-c++ -->

    void fill_buffer(uint8_t *p)
    {
        *p++ = PORTD;
        *p++ = PORTD;
        ...
        *p++ = PORTD;
    }

Here is the generated assembly:

<!-- language: lang-lisp -->

    movw r30,  r24   ; Z = p (Z is the register pair r31:r30)
    in   r24,  0x0b  ; temp = PORTD   – 1 cycle
    st   Z,    r24   ; *Z = temp      – 2 cycles
    in   r24,  0x0b  ; temp = PORTD   – 1 cycle
    std  Z+1,  r24   ; *(Z+1) = temp  – 2 cycles
    ...
    in   r24,  0x0b  ; temp = PORTD   – 1 cycle
    std  Z+29, r24   ; *(Z+29) = temp – 2 cycles
    ret              ; return

Still 3 cycles per read. Here the compiler is using the `std`
(store with displacement) instruction rather than `st X+` (store with
post-increment).

In the end, what instruction the compiler chooses doesn't really matter.
All memory access instructions takes two cycles. Then, no matter what
you do, repeatedly transferring data from a port to RAM will take
3 cycles per transfer, irrespective of the instruction you choose
for the memory write.

Now, this doesn't mean you can't read faster. The AVR CPU core has
32 general purpose registers. Since you are only performing
30 port reads per burst, this means you can use the register file
as an ultra-fast temporary buffer. This seems easier to do in assembly,
and it will cost you a significant overhead in saving registers to the
stack and restoring them afterwards. But the read burst itself will be
faster:

<!-- language: lang-lisp -->

    ; declare as:
    ;   extern "C" void fill_buffer(uint8_t *p);
    .global fill_buffer
    fill_buffer:

        ; Prologue: save registers and move the pointer.
        push r2         ; save all the registers belonging to the caller:
        push r3         ;  - 18 register to save (r2 – r17, r28, r29)
        ...
        push r28        ;  - 2 cycles per register
        movw r30, r24   ; Z = p (Z = r31:r30 is a pointer register)

        ; Now we can read the port really fast.
        in   r0,  0x0b  ; temp_0  = PORTD – 1 cycle
        in   r1,  0x0b  ; temp_1  = PORTD – 1 cycle
        ...
        in   r29, 0x0b  ; temp_29 = PORTD – 1 cycle

        ; Now save to RAM.
        st   Z+,  r0    ; *Z++ = temp_0   – 2 cycles
        st   Z+,  r1    ; *Z++ = temp_1   – 2 cycles
        ...
        st   Z+,  r29   ; *Z++ = temp_29  – 2 cycles

        ; Epilogue: restore the registers.
        pop  r28        ; restore all the previously saved registers:
        ...
        pop  r3         ;  - 18 registes to restore
        pop  r2         ;  - 2 cycles per register
        clr  r1         ; leave r1 cleared, as required by the ABI
        ret             ; return

Now we are reading the port at 16 MHz: one read per cycle!

It turns out that that we can convince the compiler to do exactly this.
I had to see to believe, but it works. Something essentially equivalent
to the above assembly can be generated from C++ like this:

<!-- language: lang-c++ -->

    // Quickly read the port into temporaries.
    uint8_t temp_0  = PORTD;
    uint8_t temp_1  = PORTD;
    ...
    uint8_t temp_29 = PORTD;

    // Now save to RAM.
    buffer[0]  = temp_0;
    buffer[1]  = temp_1;
    ...
    buffer[29] = temp_29;