# Question
Title: Arduino IDE stopped uploading sketches to BLEduino board
I know similar questions to this have been asked before, but I have a "resp=0x**10**" which I haven't found elsewhere, so maybe it's different, the board is also not an Arduino Uno although it's should be fully compatible with it in adition to the Bluetooth part.

I'm a beginner to Arduino (and electronics in general) and I bought a Bleduino board. It was working without problems, I've tested a servo and a DC motor (with a motors shield) without problems. But, it suddenly stopped working! I basically can't upload any sketch no matter what I try, giving me this error (10 attempts):

```
         Using Port                    : COM11
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x10

avrdude done.  Thank you.

```

I did try the reset button before uploading (actually tried both black and white reset buttons on this board), double checked I'm using the correct board and ports.

I've used an old 12V power supply with 1000mA, so maybe that damaged the main chip? The L and LINK LEDs light up though when connected to usb or jack, and the bluetooth also connects to the IOS App.

I read \[this\]\[3\] thorough answer for similar problems and my board passes the loopback test, but while uploading, only the L and RX LEDs flash!

Have I damaged the main chip? Do I have to buy a AVR programmer and burn a new Bootloader?

**Edit:**

A screenshot of wiring to test the Atmega16U2chip:

ATmega328Pchip Response:

```
Atmega chip detector.
Written by Nick Gammon.
Version 1.18
Compiled on Apr 10 2016 at 10:30:58 with Arduino IDE 10607.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
7E20: 0xC2 0x00 0x80 0xE1 0x80 0x93 0xC4 0x00 0x8E 0xE0 0xC9 0xD0 0x25 0x9A 0x86 0xE0
7E30: 0x20 0xE3 0x3C 0xEF 0x91 0xE0 0x30 0x93 0x85 0x00 0x20 0x93 0x84 0x00 0x96 0xBB
7E40: 0xB0 0x9B 0xFE 0xCF 0x1D 0x9A 0xA8 0x95 0x81 0x50 0xA9 0xF7 0xCC 0x24 0xDD 0x24
7E50: 0x88 0x24 0x83 0x94 0xB5 0xE0 0xAB 0x2E 0xA1 0xE1 0x9A 0x2E 0xF3 0xE0 0xBF 0x2E
7E60: 0xA2 0xD0 0x81 0x34 0x61 0xF4 0x9F 0xD0 0x08 0x2F 0xAF 0xD0 0x02 0x38 0x11 0xF0
7E70: 0x01 0x38 0x11 0xF4 0x84 0xE0 0x01 0xC0 0x83 0xE0 0x8D 0xD0 0x89 0xC0 0x82 0x34
7E80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7E90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EA0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EB0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EC0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7ED0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7EF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
7F00: 0xA6 0x01 0xA0 0xE0 0xB1 0xE0 0x2C 0x91 0x30 0xE0 0x11 0x96 0x8C 0x91 0x11 0x97
7F10: 0x90 0xE0 0x98 0x2F 0x88 0x27 0x82 0x2B 0x93 0x2B 0x12 0x96 0xFA 0x01 0x0C 0x01
7F20: 0x87 0xBE 0xE8 0x95 0x11 0x24 0x4E 0x5F 0x5F 0x4F 0xF1 0xE0 0xA0 0x38 0xBF 0x07
7F30: 0x51 0xF7 0xF6 0x01 0xA7 0xBE 0xE8 0x95 0x07 0xB6 0x00 0xFC 0xFD 0xCF 0x97 0xBE
7F40: 0xE8 0x95 0x26 0xC0 0x84 0x37 0xB1 0xF4 0x2E 0xD0 0x2D 0xD0 0xF8 0x2E 0x2B 0xD0
7F50: 0x3C 0xD0 0xF6 0x01 0xEF 0x2C 0x8F 0x01 0x0F 0x5F 0x1F 0x4F 0x84 0x91 0x1B 0xD0
7F60: 0xEA 0x94 0xF8 0x01 0xC1 0xF7 0x08 0x94 0xC1 0x1C 0xD1 0x1C 0xFA 0x94 0xCF 0x0C
7F70: 0xD1 0x1C 0x0E 0xC0 0x85 0x37 0x39 0xF4 0x28 0xD0 0x8E 0xE1 0x0C 0xD0 0x85 0xE9
7F80: 0x0A 0xD0 0x8F 0xE0 0x7A 0xCF 0x81 0x35 0x11 0xF4 0x88 0xE0 0x18 0xD0 0x1D 0xD0
7F90: 0x80 0xE1 0x01 0xD0 0x65 0xCF 0x98 0x2F 0x80 0x91 0xC0 0x00 0x85 0xFF 0xFC 0xCF
7FA0: 0x90 0x93 0xC6 0x00 0x08 0x95 0x80 0x91 0xC0 0x00 0x87 0xFF 0xFC 0xCF 0x80 0x91
7FB0: 0xC0 0x00 0x84 0xFD 0x01 0xC0 0xA8 0x95 0x80 0x91 0xC6 0x00 0x08 0x95 0xE0 0xE6
7FC0: 0xF0 0xE0 0x98 0xE1 0x90 0x83 0x80 0x83 0x08 0x95 0xED 0xDF 0x80 0x32 0x19 0xF0
7FD0: 0x88 0xE0 0xF5 0xDF 0xFF 0xCF 0x84 0xE1 0xDE 0xCF 0x1F 0x93 0x18 0x2F 0xE3 0xDF
7FE0: 0x11 0x50 0xE9 0xF7 0xF2 0xDF 0x1F 0x91 0x08 0x95 0x80 0xE0 0xE8 0xDF 0xEE 0x27
7FF0: 0xFF 0x27 0x09 0x94 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x04 0x04

MD5 sum of bootloader = 0xEA 0x3C 0x5C 0xA9 0x35 0xD1 0x36 0xA6 0x71 0xD1 0xB2 0x3F 0x7E 0x62 0x79 0x6F
Bootloader MD5 sum not known.

First 256 bytes of program memory:

0: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
10: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x00 0x00 0x00 0x00 0x00 0x00 0x00
20: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
30: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
40: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
50: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
60: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
70: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
80: 0x10 0x20 0x40 0x80 0x01 0x02 0x04 0x08 0x10 0x20 0x01 0x02 0x04 0x08 0x10 0x20
90: 0x04 0x04 0x04 0x04 0x04 0x04 0x04 0x04 0x02 0x02 0x02 0x02 0x02 0x02 0x03 0x03
A0: 0x03 0x03 0x03 0x03 0x00 0x00 0x00 0x00 0x25 0x00 0x28 0x00 0x2B 0x00 0x00 0x00
B0: 0x00 0x00 0x24 0x00 0x27 0x00 0x2A 0x00 0x2A 0x01 0x7D 0x02 0x11 0x24 0x1F 0xBE
C0: 0xCF 0xEF 0xD8 0xE0 0xDE 0xBF 0xCD 0xBF 0x11 0xE0 0xA0 0xE0 0xB1 0xE0 0xE2 0xE0
D0: 0xF8 0xE0 0x02 0xC0 0x05 0x90 0x0D 0x92 0xA8 0x30 0xB1 0x07 0xD9 0xF7 0x21 0xE0
E0: 0xA8 0xE0 0xB1 0xE0 0x01 0xC0 0x1D 0x92 0xA7 0x31 0xB2 0x07 0xE1 0xF7 0x10 0xE0
F0: 0xCC 0xEB 0xD0 0xE0 0x04 0xC0 0x22 0x97 0xFE 0x01 0x0E 0x94 0xFB 0x03 0xC8 0x3B

Programming mode off.

```

# Answer
> 0 votes
Looking at this post about the uploading process a response of 0x10 is **STK\_OK**. Now while that looks fine, if the uploader is expecting **STK\_INSYNC** then it's not OK.

I suggest you go through more of the steps in the link you posted.

You could use the "board detector" sketch mentioned on that page, to see if the main chip is completely gone, or if there is another issue. Other issues might be things plugged into D0 and D1, wrong baud rate, wrong clock rate, etc.

---
Tags: arduino-uno, bluetooth, bootloader
---


# Question
Title: Arduino hangs on second GSM message (was GSM based led matrix display)
Friends, my team and I are working on a gsm based wireless display as a part of our project. We are using Arduino UNO as the microcontroller which is interfaced with a sim900 module. Upon arrival of a new sms in the gsm module, its contents will be passed on to the dot matrix led display through SoftwareSerial. We almost got the code working but the problem we now encounter is the reception of new sms. The code works fine for the first sms but to display the next new sms, we had to manually reset the Arduino every time. Can you guys help me? This is the code:

```
#include <SoftwareSerial.h>
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

#define DISPLAYS_ACROSS 1
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

int temp=0,i=0,x=0,k=0;
char str[160],msg[160];
void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

SoftwareSerial SIM900(0, 1);

void setup()
{

   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );

   dmd.clearScreen( true );
   Serial.begin(9600);

   SIM900.begin(9600);
   void SIM900power();
   delay(20000);

     SIM900.print("AT+CMGF=1\r");
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

  void SIM900power()

{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop(){
for(unsigned int t=0;t<60000;t++){
  void serialEvent();
  if(temp==1)
  {
    x=0,k=0,temp=0;
    while(x<i)
    {
      while(str=='#')

      {
        x++;
        while(str!='*')

        {
          msg[k++]=str[x++];
        }
      }
      x++;
    }
   }
  }
     const char* dchars;
      dchars=msg;
     dmd.clearScreen( true );
   dmd.selectFont(Arial_Black_16);

  for(unsigned int i=0;i<=300;i++){
   dmd.drawMarquee(dchars,strlen(dchars),(32*DISPLAYS_ACROSS)-1,0);
   long start=millis();
   long timer=start;
   boolean ret=false;
   while(!ret){
     if ((timer+30) < millis()){
       ret=dmd.stepMarquee(-1,0);
       timer=millis();
     }
   }
 }
}

void serialEvent(){
  while(Serial.available())
  {
    char ch=(char)Serial.read();
    str[i++]=ch;
    if(ch == '*')
    {
      temp=1;
    }
  }
}

```

The DMD library was found on the net.

# Answer
Does nothing clear 'i' at the end of a message? If not, then long/unexpected/multiple messages can overflow your str\[160\] buffer.

It also looks like writing to the msg\[160\] buffer isn't well protected from overflow.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How to access Attiny84 port B in Arduino IDE code?
Referring to guide at High-low tech, I were able to flash ATTiny84 via UNO through Arduino IDE 1.6.7.

I loaded a simple blink LED program on IDE pin 0 (physical Attiny84 pin 13, PA0) and everything works fine for pin 0 till 7 at Port A.

But what if I want to access or blink a LED at one of the pins at Port B? Example, PB0 (physical pin 2)

The following is my current code to blink PA7

```
int led=7; //PA7

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);
  delay(100);
  digitalWrite(led,LOW);
  delay(100);
}

```

# Answer
Refer to url link by @Mikael, this is the answer I'm looking for.

```
Arduino IDE & Pin Mapping
// ATMEL ATTINY84 / ARDUINO
//
//                           +-\/-+
//                     VCC  1|    |14  GND
//             (D 10)  PB0  2|    |13  AREF (D  0)
//             (D  9)  PB1  3|    |12  PA1  (D  1)
//                     PB3  4|    |11  PA2  (D  2)
//  PWM  INT0  (D  8)  PB2  5|    |10  PA3  (D  3)
//  PWM        (D  7)  PA7  6|    |9   PA4  (D  4)
//  PWM        (D  6)  PA6  7|    |8   PA5  (D  5)        PWM
//                           +----+

IDE Attiny84 Physical Pin
  0      PA0           13
  1      PA1           12
  2      PA2           11
  3      PA3           10
  4      PA4            9
  5      PA5            8
  6      PA6            7
  7      PA7            6
  8      PB2            5
  9      PB1            3
 10      PB0            2

```

In order to blink PB0, I would need to replace my code with `int led=2; //PB0`
> 0 votes

# Answer
According to the ATtiny web-page the pin/ports are numbered as below:

The physical pin 2 is the Arduino ATtiny core pin 10. You can also find this well documented in the pins\_arduino.h file.

Cheers!
> 4 votes

---
Tags: arduino-ide, attiny
---


# Question
Title: Will a .ino Arduino Sketch compile directly on GCC-AVR?
Okay, we all have seen those questions all over the web such as Arduino v.s. C++, or other similar questions. And a vast majority of the answers do not even touch compilation differences other than through abstracted information.

My question aims to solve the actual differences (not preferences) in how a .ino file renamed to a .cpp file or other similar file extension for c++ would compile using GCC-AVR. I know that at a minimum you have to include the Arduino header file, but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR. For simplicity's sake, lets use the classic blink example to explain what the differences are. Or if you have a better code snippet to use, please by all means, include the snippet in your answer and explain the differences thoroughly.

Please no opinions as to which is a better way or tool to use.

FYI. I use Platformio for development and I notice a conversion process happening behind the scenes during compilation. I am tryng to understand what is actually happening there, so when I code in Arduino, I understand the "pure" C++ version as well.

Thanks for your thoughtful answers to my question in advance.

# Answer
> 14 votes
See my answer here: Classes and objects: how many and which file types do I actually need to use them? \- specifically: How the IDE organizes things.

> I know that at a minimum you have to include the Arduino header file

Yes you would need to do that.

> but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR.

The IDE generates function prototypes for you. Code in a .ino file may or may not need this (it probably will unless the author is disciplined enough to code in the usual C++ way and do them themselves).

---

If the "sketch" contains other files (eg. other .ino, .c or .cpp files) then these would need to be incorporated in the compile process as I describe in my answer mentioned above.

Also you would need to (compile and) link in any libraries used by the sketch.

---

You haven't asked about the linking side of things, but naturally the various files, as compiled, need to be linked together, and then turned into a .elf and .hex file for uploading purposes. See below.

---

## Example makefile

Based on the IDE output I made a simple makefile a while back:

```
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

```

In that particular case, the .ino file compiled without any problems **after** renaming it to Blink.cpp and adding this line:

```
#include <Arduino.h>

```

# Answer
> 12 votes
I would just like to add a few points to Nick Gammon's answer:

* You do not need to rename a .ino file in order to compile it: if you explicitly tell the compiler it's C++ (option `-x c++`), it will ignore the unusual file extension and compile it as C++.
* You do not need to add `#include <Arduino.h>` in the .ino file: you can tell the compiler to do that for you (`-include Arduino.h`).

Using those tricks, I can compile Blink.ino with *no modification*, just by invoking avr-g++ with the proper command-line options:

```
avr-g++ -mmcu=atmega328p -DARDUINO=105 -DF_CPU=16000000L \
    -I/usr/share/arduino/hardware/arduino/cores/arduino \
    -I/usr/share/arduino/hardware/arduino/variants/standard \
    -Os -fno-exceptions -ffunction-sections -fdata-sections \
    -Wl,--gc-sections -g -Wall -Wextra \
    -x c++ -include Arduino.h \
    /usr/share/arduino/examples/01.Basics/Blink/Blink.ino \
    -x none /usr/local/lib/arduino/uno/libcore.a -lm \
    -o Blink.elf

```

A few notes on the above command-line:

* `/usr/local/lib/arduino/uno/libcore.a` is where I saved the compiled Arduino core. I hate recompiling over and over again the same stuff.
* `-x none` is needed to tell the compiler to mind the file extensions again. Without it, it would assume libcore.a is a C++ file.

I learned those tricks from Sudar Muthu's Arduino-Makefile. This is a very general Makefile that works with many boards and with libraries. The only thing missing relative to the Arduino IDE is the forward declarations.

---
Tags: programming, c++, compile, avr-gcc
---


# Question
Title: Which is faster, Serial or DigitalWrite?
I am working on an Arduino Uno battle bot that uses a Sabertooth moter controller. Right now it is connected to the Arduino through Serial communication. Which is would be faster (So I can increase response time on my robot) Serial, or pwm using DigitalWrite?

# Answer
> 2 votes
Using `digitalWrite()` is the slowest by far.

Using PWM could be the fastest.

Using Serial could be the fastest.

**PWM:**

You have to filter the PWM output to be a smooth analogue signal for it to be of any use. The filtering adds an inherent sluggishness, or response time, to the system - the harder the filtering the slower the reaction to changes in the PWM duty cycle. Adjusting the filter component's values will give an optimum point between smoothness and response time. Bear in mind that the motors may respond erratically if there is insufficient damping of the signal. This will probably give the Sabertooth a hard time, too. The datasheet recommends are filter response time of greater than 1ms.

**Serial:**

If you are considering the 2x 60Amp version (thanks for adding plenty of information in the question, by the way) then the fastest baud rate is 384kbps - or 48k commands per second. The Arduino will of course not be churning data continuously because it'll be busy running the rest of the program, but using serial it is theoretically possible to send commands *faster than the motor controller's output PWM*.

**So which is faster?**

No idea. Only you can determine this, and I doubt you'll be able to determine the answer without wasting your time on some experiments.

The motors will have an inherent mechanical dampening thus creating an overall bottleneck in the whole system response time. I can almost guarantee that both PWM and Serial methods will be much faster than the response time of the motors themselves.

# Answer
> 1 votes
The fastest would be “Simplified Serial Mode” at 38400 bps. In this mode, a command is a single byte, transmitted as ten bits (1 start + 8 data + 1 stop), which would take 0.26 ms to be transmitted. Compare with the ≈ 1 ms lag you would get with an analog filter. As per the data sheet, the caveats are:

* resolution reduced to 7 bits
* the communication may not be reliable at this fast speed.

**Update**: The fastest may actually be PWM, if you “cheat” a little bit with the analog filter. The Sabertooth datasheet recommends

* PWM frequency = 1 kHz
* filter with 10 kΩ + 0.1 µF.

This gives a time constant RC = 1 ms, which is one PWM period. You can then expect a worst case ripple of 1.22 V peak-to-peak. The datasheet says you can increase the frequency or the capacitance beyond those minimum recommended values. In both cases you would get less ripple. But if we assume that this level of ripple is acceptable, we can make things faster by decreasing both the PWM period and the filter's time constant.

The trick is to configure the PWM output to run as fast as possible. The outputs of the Uno can run as fast as 62.5 kHz at 8-bit resolution, but for this we have to configure a timer using low-level port access, instead of relying on the `analogWrite()` Arduino function. I would rather avoid messing with Timer 0, because that would break all the Arduino timing functions (`millis()`, `micros()`, `delay()` and `delayMicroseconds()`). Here is an example program that uses Timer 2 to output two PWM waveforms at 62.5 kHz on outputs 11 (aka OC2A) and 3 (aka OC2B):

```
void setup() {
    DDRB  |= _BV(PB3);    // OC2A = PB3 = Arduino 11 as output
    DDRD  |= _BV(PD3);    // OC2B = PD3 = Arduino  3 as output
    OCR2A  = 127;         // output A starts at 2.5 V
    OCR2B  = 127;         // same for output B
    TCCR2A = _BV(COM2A1)  // output A in non-inverting mode
           | _BV(COM2B1)  // same for B
           | _BV(WGM21)   // fast PWM
           | _BV(WGM20);  // ditto
    TCCR2B = _BV(CS20);   // clock with no prescaling
}

void loop() {
    // Full forward both motors.
    OCR2A  = 255;
    OCR2B  = 255;
    delay (1000);

    // Stop.
    OCR2A  = 127;
    OCR2B  = 127;
    delay (1000);
}

```

You could then smooth these outputs with an RC filter of 2.2 kΩ and 10 nF. That would give a time constant of 22 µs, longer than the PWM period which is 16 µs, and a worst-case ripple of 0.9 V peak-to-peak.

# Answer
> 0 votes
pwm is faster. PWM is directly to the port. Serial goers to a buffer is send char by char and the receiver needs to wait for all the data to arrive.

# Answer
> 0 votes
Both are (relatively) slow. **When speed is of the essence, use port manipulation.** This can execute a pin change as fast as a single clock cycle--*faster than any library.*

---
Tags: arduino-uno, c++, motor
---


# Question
Title: Arduino configure script for conditional compilation of libraries
I have a library that uses conditional compilation based on the preprocessor variables. The library is a separate `.cpp` object file with a header file.

How can I pass preprocessor variables to the compilation of the library? Standard `#define` in a sketch file wouldn't work, since their life will be limited to my sketch object file(s), not the library's.

Normally it is solved by the `./configure` script and/or the custom make process. How can I do it on Arduino?

Supplying a separate compilation/source code of the library for all 2^8 combinations of the preprocessor switches doesn't seem feasible...

# Answer
> 3 votes
The problem here is that the Arduino IDE is not setup for doing this. Any real IDE has the possibility to set defines.

If you want your library to be used by arduino IDE users you will have to go to dirty routes like the #include and config.h approach already mentioned. If I'm not mistaken arduino IDE compiles libraries with the full include path so you can have the config.h next to your sketch.ino file.

If the library is not intended for arduino IDE users I would advice using a real IDE like my Arduino Eclipse Plugin.

# Answer
> 1 votes
There's two basic methods:

1. Provide a config.h file with the options in that the user modifies
2. Place the options on the command line with -D

A decent IDE allows you to modify the compilation command line to add options.

My IDE, UECIDE, allows the creation of menu entries that set library options.

# Answer
> 0 votes
Another solution: Rename the library's `.cpp` file into another `.hpp`, and let the user include it in exactly one object file of his.

User would configure the library in `lib_customization.h` included before every `#include<lib.h>`. User would also need to include an extra source file `object_file_that_defines_lib.cpp` which includes library definitions.

### `Sketch.ino:`

```
#include"lib_customization.h"
#include<lib.h>

void loop() {}
void setup() {}

```

### `lib_customization.h:`

```
#define LIB_INCLUDE_FEATURE_A
#define LIB_INCLUDE_FEATURE_B

```

### `object_file_that_defines_lib.cpp:`

```
#include"lib_customization.h"
#include<lib_definitions.h>

```

---
Tags: c++
---


# Question
Title: Trying to pass a char to software serial with a button press
Good day everyone, I'm returning to the Arduino world after my a 3 year hiatus following the birth of my son.

I'm trying to push a button connected to pin 2 and have that send a 'd' to SoftwareSerial on pins 10,11. This should trigger an output back from the device connected to the SoftwareSerial.

I'm encountering an issue:

When I press the button it sends about 15 d's. I would like to limit this to just one char per button press, I attempted to build an if statement but it seems to ignore the conditions.

```
#include <SoftwareSerial.h>
// software serial #1: TX = digital pin 10, RX = digital pin 11
SoftwareSerial portOne(10, 11);
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int button1State = 0;

// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // Start each software serial port
  portOne.begin(4800);
  while (!portOne) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

// the loop function runs over and over again forever
void loop() {
  int Once = 0;
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH ) {
    if (Once == 0) {
      Once = 1;
      // turn LED on:
      digitalWrite(ledPin, HIGH);
      // send D to Radio
      portOne.write("d");
      Serial.write("d");
      Serial.print(Once);
      Serial.println();
      delay(1);
    }
  }
  else (buttonState == LOW) {
    // turn LED off:
    Once = 0;

    digitalWrite(ledPin, LOW);

  }
  portOne.listen();
  // while there is data coming in, read it
  // and send to the hardware serial port:
  while (portOne.available() > 0) {
    char inByte = portOne.read();
    Serial.print(inByte);
  }
}

```

# Answer
As Edgar stated my issue was I didn't make the Once variable static

"1) You should debounce your button. 2) You should qualify Once as static, otherwise it's reset to zero (actually, recreated) every time you enter loop()."
> 0 votes

# Answer
As pointed out by Edgar you should debounce the button. Perhaps increasing the delay() should do the trick.

Try with 100-200 milliseconds.

With this edit you can delete Once unless you are planning on using it somewhere else.
> 4 votes

---
Tags: softwareserial
---


# Question
Title: Arduino Mimicking Voltage Dividing Keypad / Matrix
Still very new to Arduino, so bare with me. I've been all over Google looking for ways to hack my alarm keypad. This is my first time using the Arduino to hack something :smiley-confuse:

The keypad has a 13.7v input. Every other contact I can touch shows 5v or less. I realized quickly that the key buttons were producing various voltages. A quick search revealed that it was a voltage divider. I can see the resistors on the ladder. I though about mimicking the ladder via the Arduino and using a common ground.

I can see two shift resistors that say HEF4094BT. My guess is that these power the led's on the board. I can also see a chip that reads KSL1 r1342 that I can't seem to find a datasheet on.

I have a few questions, but I guess I need to tell you my end goal. I want to make my keypad an IoT device. I want to be able to read the status of the alarm, and possibly mimick the keypresses to disable the alarm or activate it.

1st. I was thinking I could share a common ground, and read a led state for high/low. Like the "Armed" Led. Thought I'd ask the community before I go and short something :(

2nd. How can I mimick the keypad's output voltages? Maybe a DAC? If so, what do you recommend?

Other Information: It's a DSC PC1550 - 6 zone alarm. (...and I'm also guessing the Rx/Tx are some DSC proprietary serial connection for security :/ )

Cheers, Robert.

# Answer
> 2 votes
Reading the leds would work. Depending on the voltage going out of the shift register, you might need to add a buffer chip, to lower the voltage.

For the keypad I'd probably go with a variable resistor, better known as a digital potentiometer.

You could probably add a way to also read the keypad, from the arduino. Which might be useful, maybe.

---
Tags: sensors, communication, hardware, analogread, voltage-level
---


# Question
Title: How can I test/demonstrate what the serial input and output buffers are?
Serial is causing me a lot of pain, and I think there are certain basic principles that I simple have not understood. I hope that by understanding how to test/demonstrate the buffer size, I will come one big step closer to understanding how serial works.

I suspect it is only possible to demonstrate this by writing a piece of software for "the other end"; the pc. I do understand Python, and to some extent how to work with serial on Python, so if possible, please write the pc code in Python.

If you supply an example (piece of code), please explain *how* the example works.

# Answer
> 2 votes
You can think of the incoming serial buffer as a bucket of water under a dripping tap. Next to the bucket is a cup.

Water arrives through the tap and drips into the bucket. When you want to get some water, if there is enough water in the bucket, you dip the cup in and remove a cupful of water. If there isn't enough water you don't get anything in your cup.

If you don't dip the cup in for a while too much water will dribble into the bucket and it will overflow all over the floor.

It's exactly the same with serial data. It arrives through the UART hardware and is placed into the "bucket" by the UART receive interrupt. If you don't dip your cup in fast enough (Serial.read()) the bucket will overflow and any new data that arrives will spill onto the metaphorical floor.

To test this out you can just send more data to the Arduino than will fit into the serial buffer (typically 64 bytes) without reading any. Then after you have finished flooding the buffer you can read what is actually in the buffer and send it back again (maybe formatted nicely) so you can see what has actually ended up in the buffer and what hasn't.

One quick and dirty test would be to send the raw bytes 0 to 255 to the Arduino, then after a delay read them back and display the DEC values for them (`Serial.print(Serial.read(), DEC))`) to see exactly which bytes arrived and which didn't (hint: you should see the numbers 0 to 63 if the buffer is 64 bytes big).

---

For the transmit buffer it's slightly different. You can think of it more as a bucket with a small hole in the bottom.

You pour data (water) in the top at whatever speed you want, and it trickles out of the bottom at a pre-set rate (the baud rate - the size of the hole). You don't like wet messes though, so if the bucket is full you wait a while before putting more water into it. Just like with serial - if the transmit buffer is full any attempts to add to it will *block* until data has been sent out by the UART transmit interrupt.

---
Tags: serial
---


# Question
Title: Advice for checking integrity of serial char strings?
I'm trying to create a flexible but reliable system for arduinos to interact using serial ascii strings. I'm using a message structure comprised of Command\[10\] + (optional) Params\[20\] + (optional) Header\[30\] + '\0' ( terminator).

Each arduino node looks for incoming serial Commands (plus any appropriate optional Parameters) that it must respond to.

During development and debugging it's sufficient to send Commands and Parameters using the IDE serial monitor without optional Header block or error-checking.

But for interactive node-to-node communications, an optional 'Header' (technically a Footer) block is automatically added to the end of the message.

If an incoming serial message includes a header block, it means that the message was sent automatically from another node (rather than manually from the IDE serial monitor), and consequently the message integrity should be checked against any relevent accompanying header contents, then an acknowledgement returned to the sender if the message was received ok.

Header contents can optionally contain any of the following, and in any order:- s(source)=nnn, d(destination)=nnn, i(id)=nnn, l(msg length)=nnn, and non-critical mixtures of commas and/or spaces can be used as delimters.

To test for message length, the transmitted l=nnn value (text representation) is padded to 3 digits with leading zeros, so the length stays the same whatever the value (eg:.anything from 000 to 999 still requires 3 digits).

So far so good. But although a length test is better than nothing, it doesn't trap for corrupt characters, and the plan is for nodes to communicate via UDP broadcasts, so some form of error-checking and acknowledgement is essential.

So the plan was to (also, or instead) use an optional c(checksum)=nnn in the header, whose value would be the mod sum of everything EXCEPT itself in the header entry. This is easily enough achieved for transmission by taking the mod sum of everything else when assembling the message, then adding the c=modsum on the end (or anywhere in the Header for that matter).

In theory, the receiving end just needs to remove the c=nnn entry (plus any preceding delimter) from wherever it is in the Header, then compare the remaining message's calculated mod sum value against the transmitted c=nnn value.

In practice, I don't know how to exclude the c=nnn entry from the header in order to calculate the remaining modsum, without being forced to accept and pander to unwelcome restrictive assumptions, such as the c=nnn value having to be the final entry, and having to use very strict delimiting.

I'm trying to keep things as flexible and informal as possible, so that other x=nnn type instruction options may be added anywhere to the header if needed without risk of breaking existing rigidity.

Perhaps I should add that this time a year ago I hadn't touched an arduino or C, and that this project has long ago changed from my original automation/security needs to become a goal for providing a simple-to-use interactive arduino distributed functionality cluster system suitable for anyone to use.

The end finally seems to be in sight, which is thanks to the help and advice from you guys (a quick look through my questions shows how far you've brought me), so hopefully your greater experience and wisdom may also be able to offer a more satisfactory integrity-test solution if it is possible.

I would also welcome any other comments that might help me improve on what I'm trying to do.

*ADDITIONAL INFO*

New incoming serial messages are received in char Buffer\[64\]. This gets split by delimiters into Command\[10\], Params\[20\] and Header\[30\], but these sizes are only arbitrary first guestimates which may change.

Commands and Parameters can be whatever the node has been programmed to respond to. A trivial 'Blink' example might be a couple of nodes, one looking for incoming "PING" Commands and responding by returning "PONG" Commands, and the other node vice- versa.

A more useful example could be an IR receiver node issuing instructions to a remote IR blaster node, so the "Command+Param+Header" string might be:-

"IRSEND 'NEC 0xFFEEAB99, 32', s=1, d=2, l=044"

The Command/Params parser accepts comma or space as delimiter except if they are contained within quotes. Quotes may be sent inside of quotes of the other type (single or double). Mr T's invaluable Header parser is slightly modified to also accept comma's or spaces as delimiters in the Header, therefore " , s=nnn,d=nnn, i=nnn l=nnn , " all extracts ok.

All of the above is working ok in a very messy and disjointed proof-of-concept form.

```
    static char buffer[64];
    int msgpos = 0;
    int msglength;
    int quotes=0;
    int parseMode=0;
    bool echo=false;
    bool ack=false;
    byte chksum=0;
    int modchk = 0;

    char command[10];
    char param[20];
    char header[30];
    int snum=0, dnum=0, inum=0, lnum=0, cnum=0;

  void setup()
  {
    Serial.begin(9600);
    Serial.println("Ready");
  }

  int readline(int readch, char *buffer, int len) { //  If a CR terminated ascii string is received, returns string length, else returns -1
    static int pos = 0;
    int rpos;
    if (readch >0) {                               // if a valid ascii character
      msgpos++;
      if (msgpos == 1) resetBuffer();              // First chr, so reset everything to make a new start
      if (!(pos < len-1)) Serial.println("Error: Msg too big for buffer");
      else if ((readch !=10) && (readch != 13)) {
        buffer[pos++] = readch;
        modchk += readch;
        modchk %= 100;
    //  Serial.print("modsum%='"); Serial.print(modchk); Serial.println("'");
        buffer[pos] = 0;
      }  // end if (pos < len-1)
      switch(readch) {
      case 10: break;                                                                             // Ignore new-lines
      case 39: if (quotes==0) quotes=1; else if (quotes==1) quotes=0; else addChr(readch); break; // Turn on or off single-quotes
      case 34: if (quotes==0) quotes=2; else if (quotes==2) quotes=0; else addChr(readch); break; // Turn on or off double-quotes
      case 33: if (quotes==0) parseMode=-1; else addChr(readch); break;                           // ! Header info
      case 32: if ((quotes>0) || (parseMode==-1)) addChr(readch); else parseModeBump(); break;    // space delimiter
      case 44: if ((quotes>0) || (parseMode==-1)) addChr(readch); else parseModeBump(); break;    // comma delim
      case 13:                                                                                // CR stop char
        if (parseMode==0) {Serial.println("Error: blank or corrupt message"); pos=0;  return 0; }
        else if(quotes>0) {Serial.println("Error: open quotes not closed"); pos=0;  return 0; }
        else {// new msg recvd ready for processing. TODO: check if msglength and/or checksum sent, if so and if correct, return ack to sender
          rpos = pos;
          pos = 0;    // Reset position index ready for next time
          return rpos;
        }
        break;
      default:
        addChr(readch);
        break;
      }  // end case
    } // end if (readch >0);
    return -1;        // No end of line CR yet, so return -1.
  }

  void resetBuffer() {
    modchk=0; quotes=0; parseMode=0; command[0]='\0'; param[0]='\0'; header[0]='\0';
    snum=0; dnum=0; inum=0; lnum=0; cnum=0;
  }

  bool parseModeBump() {
    switch (parseMode) {
    case  0: parseMode=1; break;
    case  1: parseMode=2; break;
    case  2: parseMode=-1; break;
    case -1: Serial.println("Error: too many delimited parameters"); return false;
    }
    return true;
  }

  bool addChr(char readch)  {                  //
    char addch[2];
    bool ret=true;
    addch[0]=readch; addch[1]='\0';
    if (parseMode==0) parseMode=1;
    switch (parseMode) {
    case  1: strcat(command,addch); break;
    case  2: strcat(param,addch); break;
    case -1: strcat(header,addch); break;
    default:
      Serial.println("addChr Error: too many delimited parameters"); ret = false;
    }
    return ret;
  }

  void show() {
    Serial.print("SHOW: Command='"); Serial.print(command); Serial.print("'");
    Serial.print(" Parameter='"); Serial.print(param); Serial.print("' ");
    Serial.print(" Header='"); Serial.print(header); Serial.println("'"); Serial.println();
    Serial.print("Msg Length='"); Serial.print(msglength); Serial.println("'");
    if (snum) { Serial.print("snum="); Serial.println(snum); }
    if (dnum) { Serial.print("dnum="); Serial.println(dnum); }
    if (inum) { Serial.print("inum="); Serial.println(inum); }
    if (lnum) { Serial.print("lnum="); Serial.println(lnum); }
    if (cnum) { Serial.print("cnum="); Serial.println(cnum); }
  }

  /*
  bool padzeros() {  // Flawed - redo from scratch using 2 for loop passes
    char lengthstr[4]="7";
    Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
    int maxsize=sizeof(lengthstr);  // size of lengthstr array
    int steps=strlen(leng)+1;       // number of chars to be moved
    int hop=maxsize-steps;          // number of steps to be jumped over each move
    if((steps>1)&&(maxsize>steps)) {
      for (int pos=steps-1; pos >= 0; pos--) {
        lengthstr[pos+hop] = lengthstr[pos];
        lengthstr[pos]='0';
      }
    }
    Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
  }
  */

  unsigned int calcmodsum(char* s){
    unsigned int i = 0;
    int m=0;
    byte b;
    do { b = s[i]; m += s[i]; i++; }
    while (b != 0); //keep going until null terminator found at end of string
    m %= 100;                   //
    return m;
  }

  int getheader() {      // extract values from header
  //  char header[] = "s=123 d=789 c=463";
    ack=false; echo=false;
    char * ptr = header; // header string pointer
    char * eq = NULL;    // search char (=)
    int * num = NULL;    // empty at start
    int c = 0;
    while (1){
      eq = strchr(ptr, '=');
      ptr = eq;          // update the pointer
      if (ptr == NULL)  break;  // found no '=' chars
      switch (*(ptr - 1)){
        case 'd': num = &dnum; break;
        case 's': num = &snum; break;
        case 'i': num = &inum; break;
        case 'l': num = &lnum; break;
        case 'c': num = &cnum; c=3; break;
        default:  num = NULL;
      }
      ptr++;
      if (num == NULL) //unrecognized var
        continue;      // locate next = char
      *num = 0;
      while (*ptr && (*ptr != ' ') && (*ptr != ',') && isdigit(*ptr)) {  // while valid digit and end of string not yet reached
        *num *= 10;    // extract each int
        *num += *ptr - '0';
        c++;
        ptr++;
      }
    }                  // Now Process any extracted header values
    if (lnum) {
      Serial.print("Msg length="); Serial.print(strlen(buffer)); Serial.println();
      Serial.print("lnum="); Serial.print(lnum); Serial.println();
      if (lnum==strlen(buffer)) Serial.println("* Msg length OK"); else Serial.println("* Incorrect msg length");
    }
    if (cnum) {
      Serial.print("calcmodsum='"); Serial.println(calcmodsum(buffer));
      Serial.print("cnum='"); Serial.print(cnum); Serial.println("'");
      Serial.print("count='"); Serial.print(c); Serial.println("'");
      if (modchk==cnum) Serial.println("* Checksum OK"); else Serial.println("* Incorrect checksum");
    }
  }

  void loop() {
    //  Check for new received serial string
    msglength = readline(Serial.read(), buffer, 64);  // Returns length of new ascii string, or -1 while receiving, or 0 if received msg is corrupt
    if(msglength==0  ) { Serial.println("ERROR: received serial message was invalid and discarded");show(); resetBuffer();}
    else if(msglength > 0) {  // New msg to deal with
      if (header) getheader();
      show();

      msgpos=0;  // reset ready for new msg after finished with last msg
    }
  }

```

Once I can finalise a satisfactory c=nnn validity test, I shall tidy up this working 'receiver' part and move on to doing the 'sender' part, which I'm hoping should be quite trival in comparison.

I suppose it would be 'proper' to assemble the outgoing message into something like a char outmsg\[64\] string, but I'm trying to keep resources minimal to maximise the resources available for the arduino's 'real' functionality, so perhaps it may be better just to send the outgoing msg as consecutive serial chunks, ie:-

Serial.print(Command); Serial.print(Params); Serial.println(Header);

The header will be built up as required. If s=nnn (source) was received it will be assumed that an acknowledgement response is required by the source to prevent it repeating failed transmissions, so the received s=nnn would be used as the outgoing d=nnn destination to respond to - outgoing msgs need only include a source s=nnn if they requires a response back. The i=nnn (msg id) isn't yet used, but could eventually be for re-assembling individual chunks of larger msgs, or keeping track of msg order if multiple msgs are expected.

The l=nnn is a zero-padded count of all transmitted characters (excluding the terminating ), so can be anywhere within the Header string.

It would be preferable if the zero-padded c=nnn checksum could also be anywhere in the Header, but this will require a checksum() calculator function to be able to apply its calculation to all Header characters except the nnn data characters of c=nnn.

As things are, I can jump straight to "c=" wearing blinkers, but that offers no relative position info, so leaves me oblivious of everthing before it. And I'd prefer not having to split Header\[\] into seperate Left\[\] and Right\[\] chunks which would unnecessarily wastes at least \[30+30\] chars of memory.

So I think I must sequentially step through all Header characters looking for "=" while applying the mod sum calc to each, except for the 3 following chars when the preceeding char is "c", but I can't quite get my head around how to do that yet.

If the C string functions could return relative string positions instead of absolute * pointers it could all be so much more straightforward.

Does anyone know of any alternative string-relative functions that might be available?

* NEW INFO 2 *

Most "Hello world" examples (eg: IRlib) demonstrate functionality using the IDE serial monitor for user interaction. Whatever the functionality, they can all be considered as just a black box capable of recognising a few incoming serial plain-text commands and actioning as appropriate, possibly by also issuing serial text command responses of their own.

The aim of my project is for a user to easily turn that existing and already-proven serial user interaction into an automatic arduino to arduino serial interaction if wished. The headers are just an optional bolt-on for arduino to arduino reliability, but during dev and debugging the various optional header contents will still need to be read and written by users with the IDE serial monitor, which only allows ascii text interaction.

Although this sort of system would not be the preferred solution for experts, it offers much advantage for non-experts. Un-skilled hackers could create effective working solutions without needing to aquire any rocket science first, and without needing to worry too much about resource limitations, or the problems and complexity of trying to consolidate incompatable or conflicting functionality onto any single device.

If they have an arduino that can serially interact, they can use it as an interactive node. If two can interact over serial, then more can serially interact using RS485, or using serial Ethernet UDP slaves (ESP8266's are small and cheap). Only nodes that 'recognise' an incoming command would respond to it.

A Triggers node could send ascii Alerts such as 'Mailbox Opened', 'Gate1 Visitor', Shed Door Opened' etc. A Responder node could parse such incoming Alerts to match against entries in a config file, then parse the corresponding config entry for appropriate Response commands to be issued to other cluster nodes, such as 'Mailbox: Announce Mailbox Delivery', or 'Zone2: Announce Zone 2 Activity, CCTV: Select Zone2'.

This would allow new node functionality to be added easily just by updating the Responders appropriate config file entry to include any additional Response commands that become available from any new nodes. So adding an X10 node for instance might offer a new Response command such as 'X10, A12 ON', which only the newly added X10 node would be looking for and respond to.

A cluster system could be evolved into whatever sophisticated functionality was required, with minimal software skills and knowledge. Commands and parameters could be any plain-text names that the user prefers, which when matched during input parsing would branch to any required local function. Despite any resulting complexity, all individual nodes could still just be considered as relatively simple black boxes capable of recognising a few incoming serial plain-text trigger commands and replying with plain-text responses.

Cluster nodes aren't even limited to being arduinos, because they could include ANY devices capable of receiving and responding to simple ascii command strings. This offers easy gradual progression to other platforms if wished without needing to abandon all existing efforts and start over again from scratch.

I knew I was biting off more than I could chew, but each time I play devils advocate trying to avoid wasting my time going up a dead-end, the more benefits become apparent to make the effort seem worthwhile. The forums are littered with questions and libraries aiming in a similar direction, but I haven't yet found anything which offers that simple black-box plain-text interaction capability, hence my continued struggle. I'm not a programmer so I'll never be able to offer an efficient library solution, but I must try to keep going until I've got something that is usable, and if others find it useful then maybe eventually it might offer incentive for someone to wish to optimise and improve on it.

Hopefully the following should do what I want as far as ignoring "c=nnn" from the mod checksum wherever it finds it.

```
unsigned int calcmodsum(char* passedstr){     // calculates the mod sum of passedstr excluding the 3 "c=nnn" value digits
  int pos = 0;
  int modsum=0;
  byte b;
  do {
    b = passedstr[pos];
    if ((passedstr[pos]=='c')&&(passedstr[pos+1]=='=')&&(pos>2)) pos=pos+4; else modsum += passedstr[pos]; // skip next 3 digits after finding c=
    pos++;
  }
  while (b != 0); // keep going until null terminator found at end of string
  modsum %= 100;
  return modsum;
}

```

# Answer
> 3 votes
Hmm... the length of your question makes it difficult to focus an answer. I'll try by stating my interpretation, then I'll provide a *longer* answer ;-)

> Is there a way to wrap a text message between two Arduinos
> (to increase reliability), but would still
> allow me to do testing without the wrapper?

If I assume that's what you're asking, then the above comments have touched on various aspects of an answer: "Yes."

Let's progress through my interpretation:

* "Text" means ASCII values between 32 and 126 (SP and '~', the *printable* characters).
* "Wrapping a message" means sending some bytes before and possibly after the text.
* "Increasing reliability" means *detecting* and/or *correcting* characters that get corrupted.
* "Testing without the wrapper" means that you would like to use the Serial Monitor to send example commands while you're in a noise-free environment, testing the logic of the command execution, not the mechanism of communicating reliably.

### Wrapping

You're on the right path by prefixing the text with a binary header, and Nick's library shows how to use a "special" start and end byte to delimit the messages. (This is also called message "framing".) If the START byte can appear inside the message elsewhere, you will need to either (1) "escape" the START byte when it appears inside the message, (2) provide a second method of verifying that the message is framed correctly (e.g., an END byte and/or a length), or (3) decrease the odds of a false start by using a multiple-byte START sequence.

You appear to have chosen (2). You are free to chose the bytes that follow the START byte. Addressing, sequence number and message type are common. Of course, the message length is in there somewhere.

### Reliability.

If you're happy to simply detect an error at the receiving end, a checksum is sufficient. I'd like to suggest the Fletcher checksum, as it is simple, quick and fairly robust. CRCs are more robust, but a little more expensive to compute.

But because they are calculated over the rest of the message (the "payload"), they almost always appear at the end, before any END sequence. This also makes it easier for the receiver, because it can accumulate the checksum as the bytes are received, and reject the message if the received checksum does not match the calculated checksum.

You can also use error detection to help with acknowledgements, if you decide to implement them. An alternative to ACK/NAK messages is to request the current state (a poll command), expecting that it should reflect the previous (unacknowledged) command. If the state doesn't match, send the command again.

If you also want to perform error correction, there are *numerous* ways to add that. All of them will increase the size of the message, as well as the CPU time. (Sorry, Nick, but sending complemented nybbles is not a very robust detection scheme, and it doubles the message size without adding correction capability.)

### Testing without the wrapper

You could use CR/LF as your message framing and assume that anything after CR/LF is the start of an unwrapped message. If it starts unwrapped, set a `bool` flag that skips the checksum part and END byte.

### Final notes

Your current program is structured to hold the complete message in RAM for processing (sent or received). This is not always feasible in the Arduino environment. You don't put all the print chars in a buffer, then do one big `Serial.print( buffer )`, do you?

Just like breaking a `Serial.print` into several smaller prints, reception can be performed the same way. You can watch for keywords, or accumulate parameter values *without* buffering the entire message. While it saves a lot of RAM, it also saves CPU time because each received character is handled once. With a buffered approach, each character is handled multiple times: `read()` into a buffer, then compared during a search, and maybe parsed.

One of my recent posts has some general structure information, snipped a little for here:

> Reading data on the Arduino is different from most PC applications. Calling Serial.read() does not always return data. Well, it returns -1 (or 0xFF) if no characters are available. In a PC app, calling read will usually wait until a data has been received: the PC app is "blocked" until a character comes in. That's not very noticeable because the PC has a nice multitasking OS so your pointer keeps moving and other windows respond, even though the one app is waiting for a character.
>
> On the Arduino, you can make it block the same way, but there's no OS that will let you do something else while you're waiting for data (yes, there are multitasking solutions, but let's avoid that for now). So blocking on the Arduino can keep you from doing other things you may need to do, like blinking an LED or catching a button press.
>
> There are a few common ways to write an Arduino sketch that can cope with this speed disparity:
>
> 1) Force the Arduino to wait for each character (i.e., block), and write the sketch in a very linear, top-to-bottom fashion:
>
> ```
> while (Serial1.available() == 0)
>   ; // wait
>   inByte1 = Serial1.read();
>
>   if (inByte1 == 0x3E){ // START byte
>     buffer[0] = inByte1;
>
>     while (Serial1.available() == 0)
>       ; // wait
>     inByte1 = Serial1.read();
>
>     if (inByte1 == 0x03){
>
> ```
>
> 2) Save each character in a buffer as it arrives until you have received an entire packet. Then parse the packet all at once with similar linear code:
>
> ```
> static uint8_t count = 0; // keeps its value across calls to loop
>
> if (Serial1.available()) {
>   inByte1 = Serial1.read();
>
>   if (inByte1 == 0x3E) { // START character
>
>     // Next packet starting, process the current one we've been saving,
>     //   if we have saved enough bytes (skips small/bad packets).
>
>     if ((count > 6) && (buffer[0] == 0x3E)) {
>
>       // SNIP: handle previous packet
>
>     }
>
>     // Reset the count to start a new packet with the 0x3E we just received.
>     count = 0;
>   }
>
>   // Save the current byte
>   if (count < sizeof(buffer))
>     buffer[ count ] = inByte1;
>   count++;
> }
>
> ```
>
> 3) Parse each character as it arrives, picking up where you left off after doing other things.
>
> void loop() { // statics keep values across calls to loop static uint8\_t count = 0; static bool skipping = true; static uint8\_t messageLength = 0;
>
> ```
>   if (Serial1.available()) { // or 'while'
>
>       uint8_t inByte = Serial1.read();
>
>       if (inByte == 0x3E) { // START  byte
>
>           // Starting a new packet!
>
>           buffer[0] = inByte;
>           count    = 1;
>           skipping = false;
>
>       } else if (!skipping) {
>
>           // Saving a packet, store the current byte
>
>           if (count < sizeof(buffer))
>             buffer[ count ] = inByte;
>
>           // Use the current byte, depending on 'count'
>           switch (count) {
>             case 1:
>               if (inByte != 0x03)
>                 skipping = true; // ignore other packet selector values
>               break;
>
>             case 2:
>               messageLength = inByte;
>               // Error check?
>               if (messageLength != 40)
>                 skipping = true;
>               break;
>
>             case 3:
>               // packetID = inByte; ?
>               buffer[3] = inByte;
>               break;
>
>             case SNIPPED: other header information fields
>             case SNIPPED: accumulate/parse payload
>             case SNIPPED: verify checksum (ignore packet or execute packet)
>          }
>
>          count++;
>      }
>  }
>
>  // Do other things, too?
>
> ```
>
> }
>
> Choice 1 is very linear. The disadvantage is that it blocks and does not recover from data errors very well.
>
> Choice 2 is pretty easy to understand and it doesn't block; other tasks can do things while waiting for a complete packet. The disadvantage is that all the packet processing happens when the last byte is received (actually, the first byte of the next packet in that code).
>
> Choice 3 is more difficult to understand, because the entire section is executed for each character, either starting a new packet or using the switch statement to handle each char. Different cases do a little work, depending on the count. The advantage is that the processing is spread out over each character, and you can decide to skip the rest of a packet at any point.

This is actually a Finite-State machine approach, and Nick Gammon has a great description, too.

---
Tags: serial, programming, networking
---


title: Fritzing file for prototyping shield

text:
# Question
Title: Fritzing file for prototyping shield
I have a prototyping shield with mini breadboard similar to Adafruit Proto Shield for Arduino Kit - Stackable Version R3.

Is there a Fritzing file for this.

# Answer
> 0 votes
A quick google search turned up a solution in the very first result:

https://forums.adafruit.com/viewtopic.php?f=31&t=36560

It is a contribution from an Adafruit customer. All credits go to them.

Source thread: https://forums.adafruit.com/viewtopic.php?f=31&t=36560

---
Tags: arduino-uno
---


# Question
Title: Script on pc only gets 640 characters via serial
I experience that if the Arduino (Teensy 3.2) writes a rather long stream of characters to serial, the python script on the other end only receives the first 640 characters. I have found this result both by printing chars, printing lines and by using ArduinoJson's prettyPrintTo(Serial).

Note, that it does not matter what chunks of characters I read in the Python scripts, whether it is `read(5)` or `read(1000)`.

With the Arduino Serial Monitor, I get all the data, ie more than the 640 characters.

From what I can understand, it is not possible for a sketch to write "too fast" or "too much" to the serial, so there must be something on the pc side receiving the data. However, the Python script for some reason does not get all the data.

What is the problem here? Where should I look for the problem/solution? Perhaps this is more a Linux or Python question, but I will try here.

**Sketch - printLines()**

```
void printLines() {
  for (int i=0; i<100; i++) {
    // length below is 40 incl end of line character
    Serial.printf("abcdefthijklmnopqrstuvxyz123456789--%03d\n", i);
  }
}

void setup() {
  Serial.begin(9600);
  delay(500);
  printLines();
  //printChars();
  //printJson();
}

void loop() {}

```

**Sketch - printChars()**

```
void printLines() {
  for (int i=0; i<1000; i++) {
    Serial.write('x');
  }
}

```

**Sketch - printJson()**

```
void printJson() {
  StaticJsonBuffer<10000> jsonBuffer;
  JsonArray &root = jsonBuffer.createArray();
  for (int i=0; i<700; i++) {
    root.add(i);
  }
  root.prettyPrintTo(Serial);
}

```

**Python script**

```
import serial

ser = serial.Serial('/dev/ttyACM0')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
for i in range(num_iterations):
    s = ser.read(num_chars)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))

```

**Terminal output**

```
jan@jan:~/Desktop/batlogger/localserver$ sudo python localserver.py
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
### i: 2, reading 100 chars, char 200 to 299, len(s): 100, total chars: 300
### i: 3, reading 100 chars, char 300 to 399, len(s): 100, total chars: 400
### i: 4, reading 100 chars, char 400 to 499, len(s): 100, total chars: 500
### i: 5, reading 100 chars, char 500 to 599, len(s): 100, total chars: 600
### i: 6, reading 100 chars, char 600 to 699, len(s): 40, total chars: 640
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 640
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 640
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 640

```

# Answer
> 3 votes
You are not using a serial connection, you are using a USB CDC/ACM connection, and that is a very very different thing.

With a serial connection when you send data it gets sent regardless of whether there is anything listening for it - the TX IO pin toggles high and low regardless.

However, with a CDC/ACM connection it's only possible to send data when there is something actively listening at the remote end - that is, when the port /dev/ttyACM0 has been opened by an application.

Until that port has been opened any data sent will remain in internal buffers. These buffers are 64 bytes each in size (that's the size of a CDC/ACM packet), and there are (I would guess) 10 of them on the Teensy3. After these buffers are full, because there is nothing receiving the data, there can never be any more room made for more data, so instead of blocking like a serial connection does it just discards the data.

So you have filled the buffers with 640 bytes of data and thrown away the rest. That data just sits there.

Then eventually you open the /dev/ttyACM0 port and the Teensy3 is now able to send CDC/ACM packets through the USB. And it has 10 of those packets sat there waiting to go out, so it sends them. So you receive the 640 bytes of data that you had buffered up.

Your mistake is basically not waiting for the port to be opened before sending data to the remote end. You can test the state of the port (kind of, but that's a whole other subject) by examining the Serial object:

```
if (Serial) {
    // ... the port is open
}

```

In general you can usually just wait at the start of your program before starting anything else with a simple while:

```
while (!Serial); // Wait for the port to be opened

```

# Answer
> 0 votes
I wouldn't be running as root. Why do that, just to execute a Python script?

Anyway, your problem is that you are not waiting for input. Your Python script is executing faster than the Arduino can pump out the bytes. At 9600 baud you send one byte every 1/960 of a second, so to send 4000 bytes (100 x 40) would take 4000 * 1/960 = 4.166 seconds. However your Python script powers along, getting the first 600 or so which may have been buffered already, and then finishes. You need to rewrite so you wait for a line to arrive. For example:

```
import serial

ser = serial.Serial('/dev/ttyACM0')

while True:
  s = ser.readline()
  print (s)

```

When I ran that I saw all 100 lines.

Of course, you need to modify that to break out of the loop. Maybe a special character would do that. Typically a newline is used.

---

> PySerial's read function is blocking by default. - or it has a long timeout anyway

Not when I tested it. Using the code in the question, and without the Arduino even plugged in, I get:

```
### i: 0, reading 100 chars, char 0 to 99, len(s): 0, total chars: 0
### i: 1, reading 100 chars, char 100 to 199, len(s): 0, total chars: 0
### i: 2, reading 100 chars, char 200 to 299, len(s): 0, total chars: 0
### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 0
### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 0
### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 0
### i: 6, reading 100 chars, char 600 to 699, len(s): 0, total chars: 0
### i: 7, reading 100 chars, char 700 to 799, len(s): 0, total chars: 0
### i: 8, reading 100 chars, char 800 to 899, len(s): 0, total chars: 0
### i: 9, reading 100 chars, char 900 to 999, len(s): 0, total chars: 0

```

Execution time: 5.5 s.

Of course, the code sets the timeout to 0.5s. But that isn't good enough. You can't assume that 400 bytes will arrive within 0.5s. They *should* if both sides are perfectly synchronized (at 9600 baud it would take 0.416s).

But serial doesn't work that way. You can't just read for 0.5s and hope everything you want arrives in that time. Heck, it may not have even started sending.

---

OK, I admit I tested with my Uno and not a Teensy, but this amended Python script shows similar results:

```
import serial

ser = serial.Serial('/dev/ttyACM2')
ser.timeout = 0.5

# PARAMETERS:
# (As long as num_iterations*num_chars >= 640, EXACTLY 640 characters are read)
num_chars = 100
num_iterations = 10

chars_read = 0
result = ""
for i in range(num_iterations):
    s = ser.read(num_chars)
    result = result + str(s)
    chars_read += len(s)
    print("### i: %d, reading %d chars, char %d to %d, len(s): %d, total chars: %d"
        % (i,num_chars, i * num_chars, i * num_chars + num_chars -1, len(s), chars_read ))
    print ("String = " + str (s))
    print ()

print ("-" * 70)
print ("Total output =")
print (result)
print ("Total length =", len (result))

```

Output:

```
### i: 0, reading 100 chars, char 0 to 99, len(s): 100, total chars: 100
String = b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'

### i: 1, reading 100 chars, char 100 to 199, len(s): 100, total chars: 200
String = b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'

### i: 2, reading 100 chars, char 200 to 299, len(s): 21, total chars: 221
String = b'opqrstuvxyz123456789\xff'

### i: 3, reading 100 chars, char 300 to 399, len(s): 0, total chars: 221
String = b''

### i: 4, reading 100 chars, char 400 to 499, len(s): 0, total chars: 221
String = b''

### i: 5, reading 100 chars, char 500 to 599, len(s): 0, total chars: 221
String = b''

### i: 6, reading 100 chars, char 600 to 699, len(s): 100, total chars: 321
String = b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'

### i: 7, reading 100 chars, char 700 to 799, len(s): 100, total chars: 421
String = b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'

### i: 8, reading 100 chars, char 800 to 899, len(s): 100, total chars: 521
String = b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'

### i: 9, reading 100 chars, char 900 to 999, len(s): 100, total chars: 621
String = b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'

----------------------------------------------------------------------
Total output =
b'thijz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmnopqrstuvxyz123456789yz123456'b'789--68\nabcdefthijklmnopqrstuvxyz123456789--69\nabcdefthijklmnopqrstuvxyz123456789--70\nabcdefthijklmn'b'opqrstuvxyz123456789\xff'b''b''b''b'abcdefthijklmnopqrstuvxyz123456789--0\nabcdefthijklmnopqrstuvxyz123456789--1\nabcdefthijklmnopqrstuvxy'b'z123456789--2\nabcdefthijklmnopqrstuvxyz123456789--3\nabcdefthijklmnopqrstuvxyz123456789--4\nabcdefthij'b'klmnopqrstuvxyz123456789--5\nabcdefthijklmnopqrstuvxyz123456789--6\nabcdefthijklmnopqrstuvxyz123456789'b'--7\nabcdefthijklmnopqrstuvxyz123456789--8\nabcdefthijklmnopqrstuvxyz123456789--9\nabcdefthijklmnopqrst'
Total length = 669

```

---

Since the output of the Uno would be deterministic (it would do the same thing every time) the problem is in the way you are processing the data at the Python end. Look at the line numbers in the above list. They don't even start at 0.

---
Tags: serial, python
---


# Question
Title: Stepper motor doesn't start immediately when i pressed the button
When I release my hand from the button on pin 2, the stepper motor takes at least few seconds to stop, but I want it stop immediately. here's my codes:

```
 #include <Stepper.h>

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

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

    bool dir = false;
    bool power = true;

    void dir_pin() {
      if (!digitalRead(3)) {
        dir = !dir;
      }
    }//when the switch is being pressed
    //it condition would be different from last time

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(60);
      // initialize the serial port:
      Serial.begin(9600);
      pinMode(2, INPUT_PULLUP);//it is a easier way to using INPUT-PULLUP
      //cause you dont have to use a real resistor
      pinMode(3, INPUT_PULLUP);//why choose those two pins
      //cause for uno, the interrupt pin are pin 2 and pin 3
      attachInterrupt(digitalPinToInterrupt(3), dir_pin, FALLING);
      pinMode(A0, INPUT);
    }

    void loop() {
      int pwr = analogRead(A0) / 100;
      Serial.print("power:");
      Serial.print(power);
      Serial.print("  pwr:");
      Serial.print(pwr);
      Serial.print("  dir:");
      Serial.println(dir);
      while (digitalRead(2) == 0)
      {
        if (pwr) {
          myStepper.setSpeed(pwr);
          int pwr = analogRead(A0) / 100;

          if (dir) {
            //Serial.println("clockwise");
            myStepper.step(stepsPerRevolution);
            //delay(500);
          }
          // step one revolution in the other direction:
          else if (!dir) {
            //Serial.println("counterclockwise");
            myStepper.step(-stepsPerRevolution);
            //delay(500);
          }
        }
        else
        {
          myStepper.step(0);
        }
      }
      while (digitalRead(2) == 1)
      {
        pwr = 0;
        myStepper.step(0);
      }
      delay(10);
    }

```

# Answer
You tell it to move whole 200-step revolutions, so once it begins a revolution, it must continue. At 60 RPM, that should be up to 1 full second after you open pin 2. Depending on the analogRead(A0)/100, a full revolution could take much longer than 1 second -- maybe 5.86s to 6000s

If you want it to stop immediately, disregarding full revolutions, you could:

```
      stepsPerButtonpress = 1;

      ...

      if (dir) {
        //Serial.println("clockwise");
        myStepper.step(stepsPerButtonpress);
        //delay(500);
      }
      // step one revolution in the other direction:
      else if (!dir) {
        //Serial.println("counterclockwise");
        myStepper.step(-stepsPerButtonpress);
        //delay(500);
      }

```

Or you could reduce stepsPerRevolution to the fraction of steps you want to treat as a unit, and increase rpm proportionally.
> 0 votes

---
Tags: arduino-uno, motor, arduino-motor-shield
---


# Question
Title: Can I connect an Arduino GSM Shield directly to a PC?
Is it possible to communicate with and use the GSM shield directly from the computer, without using an arduino board?

# Answer
You can connect a https://www.arduino.cc/en/Main/ArduinoGSMShield to your computer with a USB-TTL serial cable, but you need to make sure you supply enough 700-1000ma to drive the GSM when it is transmitting.

> Power It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use.
> 1 votes

---
Tags: shields, gsm
---


# Question
Title: Connecting SIM900A GSM/GPRS module Arduino Mega
I have bought the following SIM900A GSM/GPRS module. I need to connect it to an Arduino Mega. Can anyone answer me which pin I need to connect to the Arduino?

# Answer
> 0 votes
From your pic, it looks like the upper left corner has a jumper with TTL level TX, RX, GND.

---
Tags: gsm
---


title: Servo broken? Explanation, Solution

text:
# Question
Title: Servo broken? Explanation, Solution
I had a question, I tried to control a servo with the arduino, to the servo I attached a stick and at the end of the stick a little weight. After runing my code my servo tried to move the stick, but maybe it had not enough torque to move it so after that I paused the code. Then I tried to control the servo again without weight and this time it didn´t moved. Is it broken? why? Is there a posible solution? Thanks

# Answer
Without seeing the code you are using, it is difficult to know if you are attempting to drive the servo correctly.

Remember, with a servo, the PWM signal is a positioning signal, not a duty cycle signal as used with speed control on regular dc motors.
> 1 votes

# Answer
You may have broken the gears if the servo was not rated for the load applied or if the servo was rotated too far (by software) 1ms and 2ms should be your (conservative) software limits, though most servos will work from 0.7ms to 2.3ms.
> 0 votes

# Answer
Servo is probably broken, or fried.
Same thing happened to me, that too twice!
First time, I had fried the servo(overpowered it).
Second time, one of the gears had broken.(finally I managed to salvage one total servo by using gears from fried one in the one with broken gears)
First, try a different way to control the servo. If the servo fails to respond, then try opening up the servo.You might be able to salvage something.
> 0 votes

---
Tags: motor, servo
---


title: HTTP POST request to IFTTT

text:
# Question
Title: HTTP POST request to IFTTT
I'm trying to send a POST request to IFTTT from a Node MCU. Instead of writing the code from the scratch, I've tweaked an already existing code (for GET request). It does not seem to work, what am I doing wrong? Needless to say, I replaced the WIFI ssid, the password and the IFTTT token. When testing the POST request with CURL, it works perfectly. Here's how the request should look like:

https://maker.ifttt.com/trigger/{event\_name}/with/key/my\_super\_secret\_token

...and the code:

```
#include <ESP8266WiFi.h>

const char* ssid     = "mywifi";
const char* password = "mywifipassword";

const char* host = "maker.ifttt.com";

void setup() {
  Serial.begin(115200);
  delay(100);

  // We start by connecting to a WiFi network

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "trigger/{trigga}/with/key/IFTTT_token";
  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

    // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

```

# Answer
> 2 votes
Problem I see is that the request is incomplete - the server will be waiting for your payload.

```
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");

```

You haven't specified a `Content-Length` header so the payload should start after the headers finish - but you don't send anything.

You need to (at least):

* add a payload *or*
* add a `Content-Length: 0` header *or*
* add a payload with a matching `Content-Length:` header.

You can use `curl` to see a full set of valid `POST` headers like this:

```
curl -v -d "" http://localhost

```

You can use Chrome and Firefox's Web Inspector's Network tab to look at the raw headers of requests too.

---
Tags: esp8266
---


# Question
Title: What variables to declare for controlling a motor with high power motor controller
I was getting started with programming a motor controller with the Arduino Uno, in this case it's a mega motor shield (the motor driver shield I'm using). The problem I have doing this is that I'm not sure what variables to use for the motor which is connected to two outputs labeled MA and MB. I used motorValue to set the speed previously and used motorPin for writing the speed with the Arduino and a breadboard, but I'm not sure what to use in place of that for the motor being connected to the driver shield outputs.

# Answer
> 1 votes
Variables are just names assigned to numbers. The names, as far as your program is concerned, are completely meaningless.

It's the numbers you assign to the variables and, more importantly, what you *do* with those variables that is important.

Your shield seems to have jumpers to select what I/O pins perform which function, so you just need to write the software to control the chosen I/O pins in the right way.

---
Tags: arduino-motor-shield
---


# Question
Title: Can a KCPI-3101 be replaced with an Arduino?
I'm planning to use a KPCI-3101 Keithley with a computer to creat a DAS with a sensor to show the data on computer

can i replace the Card and computer with an Arduino?

# Answer
An Arduino's ADC cannot sample fast enough to sustain 225ksps over 16 channels. That equates to a total of 3.6Msps. The Arduino can manage something like 120ksps in total.

That's not to say there aren't microcontrollers that can't do that kind of speed - there are. The PIC32MZ, for instance, can run at 15Msps (although it's somewhat buggy still) and there are many other microcontrollers.

The main bottleneck though is in the communication between the microcontroller and the computer. Regardless of the sampling speed of an Arduino the serial interface is too slow for high speed sampling. Even at its practical maximum of around 2Mbps it gives you 200000 bytes per second, which with 2 bytes per sample would be 100ksps maximum throughput, not taking into account any protocol overheads.

So that's where having a PCI card is a big advantage. A 32-bit (or even 64-bit on PCI64) 66MHz direct channel to the CPU means you can shift considerably more data. And having the computer perform DMA access means that smooth data transfers without the CPU needing to be involved can be performed.
> 2 votes

# Answer
You can't replace the KPCI-3101 Keithley's 16 channels of 12 bit 225kS/s with an Arduino.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to program arduino due without arduino ide
Is it possible to program the Arduino Due without the Arduino IDE? Is there a standalone program that can be downloaded, and be used to upload a .bin file (which has already been generated from the arduino IDE) to the Due? Any guidance appreciated.

I read about SAM-BA programmer, downloaded it but double clicking the .exe file does nothing. Something seems to open but it disappers.

# Answer
The standalone program for most arduinos is avrdude: http://www.nongnu.org/avrdude/

However, for the Due, it is BOSSA:

> Unlike other Arduino boards which use avrdude for uploading, the Due relies on bossac. -- Arduino Due Overview
> 2 votes

# Answer
Usually when on opening a program you get a console that pops on, it means that this program is meant for commandline usage and not CLI.

You should open a terminal, `cd` in the downloaded .exe directory, and then type that tool's name. You might want to try adding `--help` after the program's name to learn how to use it.

Another good idea is to look at what Arduino does by clicking on the verbose option in the preferences. Then you'll be able to copy/paste the command call and modify it to upload the firmware blob you want.

Finally, if you look up "AVR SAMX upload tool windows" on google you might find a GUI wrapper for the command line tool.
> 0 votes

---
Tags: arduino-due
---


# Question
Title: String matching serial input (was Code for voice recognition for arduino uno)
```
#include <SoftwareSerial.h>// import the serial library

SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=13; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer

void setup() {
  // put your setup code here, to run once:
  Genotronex.begin(9600);
  Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
   if (Genotronex.available()){
BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   Genotronex.println("LED  On D13 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   Genotronex.println("LED  On D13 Off ! ");
   }
}
delay(100);// prepare for next data ...
}

```

can anyone help me how to write the sketch for voice recognition of the above code. I'm using AMR/BT voice control app\`for voice recognition.

# Answer
**Your question is not very specific.**

But, I think your talking about the AMR\_Voice application for Android, and your trying to use the HC-05 BT to connect to your cell. I hope I'm right in my guess, and funny enough, someone over at Instructables did exactly the same thing.

Arduino Voice recognition Via Bluetooth HC-05 - http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/

Hope this helps!
> 2 votes

---
Tags: sketch
---


# Question
Title: How to install Arduino IDE on Raspberry Pi
How do you install the Arduino IDE on the Raspberry Pi running an ARM version of Ubuntu or Raspbian? There doesn't seem to be any official ARM release. Both distros have an "arduino" package in their standard repos, but it only includes an ancient 1.0 version that's missing a lot of features.

# Answer
Arduino at http://playground.arduino.cc/Linux/Raspbian recommends:

```
sudo apt-get update && sudo apt-get install arduino

```

but indeed warns that the version is old:

> Note: This will install an old version of Arduino, and may not support some of the newer boards. You can not download a newer version from the website, because there is no ARM version. -- Arduino wiki on Raspbian

Looking at the raspbian respository at http://archive.raspbian.org/raspbian/pool/main/a/arduino/ currently lists 1.0.5

There are folks working newer versions of Arduino for ARM at https://github.com/arduino/Arduino/issues/3334 but it isn't finished yet.
> 1 votes

---
Tags: raspberrypi
---


title: Client.connect galileo gen2 not working

text:
# Question
Title: Client.connect galileo gen2 not working
I'm having a problem with the intel galileo gen2 ethernet. I am trying to get a webpage, but I can only connect to the ethernet, not the webpage. I get this in the Serial monitor:

My code:

```
/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x98, 0x4f, 0xee, 0x01, 0x8d, 0xdf };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(216, 58, 217, 206); // numeric IP for Google (no DNS)
//char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress dns(192, 168, 1, 122);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    // wait for serial port to connect. Needed for Leonardo only
  }
  delay(5000);
  // start the Ethernet connection:

  Ethernet.begin(mac, ip, dns, gateway, subnet);
  Serial.println("connected to ethernet");
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  int ch = client.connect(server, 80);
  if (ch) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.print("connection failed, error code ");
    Serial.println(ch);
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

```

Any help is greatly appreciated.

# Answer
6 months after figuring out the answer, I found this question again. I solved this question by adding `system("ifup eth0")` which completely solved the problem.
> 1 votes

---
Tags: c++, ethernet, arduino-galileo
---


title: Arduino millis() won't work

text:
# Question
Title: Arduino millis() won't work
This is my program. The LED should turn off after four seconds.

```
int vraag = 7;
int gloeikaars = 5;
unsigned long previousMillis3;
boolean gloeistate = true;

void setup() {
    pinMode(gloeikaars, OUTPUT);
}

void loop() {
    int x = digitalRead(vraag);
    if (x == 0) {
        digitalWrite(gloeikaars, !LOW);
    } else {
        Gloeikaars();
    }
}

// *********************************************************************
// Gloeikaars aansturing
// *********************************************************************
void Gloeikaars() {
    unsigned long huidig = millis();
    digitalWrite(gloeikaars, !HIGH);
    if ((gloeistate == true) && (huidig - previousMillis3 >= 4000)) {
        huidig = previousMillis3;
        digitalWrite(gloeikaars, !LOW);
        gloeistate = false;
    }
}

```

Can someone help me because it won't work?

# Answer
> 1 votes
Your `previousMillis` variable is never set. Two changes:

In setup:

```
...
previousMillis3 = millis();
...

```

In loop:

```
...
previousMillis3 = huidig;
...

```

---
Tags: millis
---


# Question
Title: Analog angle conversion from +70° to -70°
I am using below sensor (accelerometer) .My application is a solar tracker, where I wanted to convert the sensor output into +70° to -70° format.

My question is how can I convert the angle?

```
#define ADC_ref 2.56
#define zero_x 1.569
#define zero_y 1.569
#define zero_z 1.569
#define sensitivity_x 0.3
#define sensitivity_y 0.3
#define sensitivity_z 0.3

unsigned int value_x;
unsigned int value_y;
unsigned int value_z;

float xv;
float yv;
float zv;

float angle_x;
float angle_y;
float angle_z;

void setup() {
  //analogReference(INTERNAL2V56);
  Serial.begin(9600);
}

void loop() {
  value_x = analogRead(A0);

//  value_y = analogRead(A1);
  //value_z = analogRead(A2);

  Serial.print("voltage  of x");
  Serial.println(value_x);
  /*Serial.print("voltage  of y");
   Serial.println(value_y);
   Serial.print("voltage  of z");
   Serial.println(value_z);
   */
  //xv=(value_x/1024.0*2.5)/sensitivity_x;
/*  zv=(value_z/1024.0*ADC_ref-zero_z)/sensitivity_z;
  yv=(value_y/1024.0*ADC_ref-zero_y)/sensitivity_y;
  xv=(0.0032226562499999998*value_x)/sensitivity_x;
  angle_x =atan2(-yv,-zv)*57.2957795+90;

  Serial.print ("x= ");
  Serial.println (xv);
  Serial.print("x_degree= ");
  Serial.print(angle_x);
  Serial.println(" deg");

  /*Serial.print(" g ");

   Serial.print ("y= ");
   Serial.print (yv);
   Serial.print(" g ");

   Serial.print ("z= ");
   Serial.print (zv);
   Serial.print(" g ");

   Serial.print("\n");

   Serial.print("Rotation ");

   Serial.print("x= ");

   angle_x =atan2(-yv,-zv)*57.2957795+180;

   Serial.print(angle_x);
   Serial.print(" deg");
   Serial.print(" ");

   Serial.print("y= ");

   angle_y =atan2(-xv,-zv)*57.2957795+180;

   Serial.print(angle_y);
   Serial.print(" deg");
   Serial.print(" ");

   Serial.print("z= ");

   angle_z =atan2(-yv,-xv)*57.2957795+180;

   Serial.print(angle_z);
   Serial.print(" deg");
   Serial.print("\n");
   */
  delay(1000);
  //delay(1000);
}

```

I have inclinometer off the shelf its Vout is 0~5 V and angle measure from -70° to 70°, and I calculated as below.

```
void calcPos()
{
  Sensor_Value=analogRead(A3);
  voltage = Sensor_Value * ARDUINO_ANALOG_SCALING;
  tracker_actual_pos=(30*voltage)-75;
}

```

# Answer
> 1 votes
So atan2(y,x) gives the angle CCW from the x axis in radians, limited to \[-pi,pi\].

If you want it converted to degrees CW from the Y axis, you would do

```
azimuth=90.0-atan2(y,x)*57.295779;

```

If you need to constrain it to -70,70 then:

```
azimuth_constrained=constrain(azimuth,-70,70);

```

---
Tags: arduino-uno, sensors, accelerometer
---


# Question
Title: Why my RTC module doesn't return the right date/time?
I have a RTC module DS1307 (MR005-001.2) on my Arduino Uno. I use the Wire.h / Time.h / DS1307RTC.h libraries.

The date and time returned is completely wrong ("17:18:9 2 4 2036") ... What do I do wrong ??

Thanks !

Here is my partial code for setup() :

```
    setSyncProvider(RTC.get);
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");

```

This writes "RTC has set the system time", so I guess something is happening right...

Here is my partial code for loop() :

```
    Serial.print(hour());
  Serial.print(":");
  Serial.print(minute());
  Serial.print(":");
  Serial.print(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();

```

Just as in the example ... and the date/time returned is "17:18:9 2 4 2036"

# Answer
> 1 votes
You setup interpretation should be more like:

```
 setSyncProvider(RTC.get);
 if(timeStatus()!= timeSet)
   Serial.println("RTC has never been set");
 else
    Serial.println("RTC has a time");

```

To conditionally sync the clock to the compilation time if the clock is not running:

```
if (! RTC.isrunning()) {
   Serial.println("RTC is NOT running!");
   // following line sets the RTC to the date & time this sketch was compiled
   // uncomment it & upload to set the time, date and start run the RTC!
   RTC.adjust(DateTime(__DATE__, __TIME__));
}
// following line unconditionally resets the RTC to the date & time this sketch was compiled
// uncomment it & upload to set the time, date and start run the RTC!
// RTC.adjust(DateTime(__DATE__, __TIME__));

```

To unconditionally sync it to the compilation time, uncomment the last line and reload for one cycle, then re-comment it and reload to let the clock run itself.

---
Tags: arduino-uno, serial
---