ESP32 saving data to SD card in .csv doesnt format correctly i want to save a vector to a .csv file on a SD Card.

I watched this tutorial on how to do it and it describes it perfectly even though its kinda dated.

My Problem is that everything is saved into the first cell of the .csv file so it gets constantly overridden.
It should save only the first vector into the first cell, then the second vector into the second cell and so on.
I just get all three vectors with the commas into the first vector like this:

8, 9, 10

Also the header witch should appear at the top is also gone.

I would really appreciate some help. Thanks!

Here is my setup and loop:

#include <iostream>
#include <string>
#include <vector>
#include "SD.h"
#include "SPI.h"
#include "EKG_data_transmision.h"

#define CS_Pin 5 // Chip Select Pin

EKG_data_transmision EKG_data_transmision;

std::vector<unsigned short> vector_1 = {1,2,3,4,5,6,7,8,9,10};
std::vector<unsigned short> vector_2 = {2,3,4,5,6,7,8,9,10,11};
std::vector<unsigned short> vector_3 = {3,4,5,6,7,8,9,10,11,12};
unsigned int for_x = 0;

void setup() {
  // open serial
  Serial.begin(9600);
  Serial.print("Init SD Card...");
  pinMode(CS_Pin, OUTPUT);

  if(!SD.begin(CS_Pin))
  {
    Serial.println("Card failed or not present");
    return;
  }

  EKG_data_transmision.vectorData = SD.open("/data.csv", FILE_WRITE);  //erstelle data.csv datei

  if(EKG_data_transmision.vectorData)
  {
    EKG_data_transmision.vectorData.println(", , , ,");
    String header = "ID, Value, Time, Whatever";
    EKG_data_transmision.vectorData.println(header);
    EKG_data_transmision.vectorData.close();
    Serial.println(header);
    Serial.println("card init sucess");
  }
  else
  {
    Serial.println("Couldnt open vector data file");
  }

}

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

  while(for_x <= 8){
    for_x++;
    EKG_data_transmision.write_vector_to_SD(vector_1, vector_2, vector_3);
    delay(1000);
  }

  delay(10000);
}

Here is my function that should save everything to the SD Card:

bool  EKG_data_transmision::write_vector_to_SD(std::vector<unsigned short> vector_ADC_1, std::vector<unsigned short> vector_ADC_2, std::vector<unsigned short> vector_ADC_3) // Übertrage
{
  dataString = String(vector_loc) + "," + String(vector_ADC_1[vector_loc]) + "," + String(vector_ADC_2[vector_loc]) + "," + String(vector_ADC_3[vector_loc]); // + "\r\n"

  vectorData = SD.open("/data.csv", FILE_WRITE);

  if(vectorData){
    //sd karte immer noch da und schau ob data.csv exisitiert
    vectorData.println(dataString);
    Serial.println("This is vector:");
    Serial.println(vector_loc);
    Serial.println("Im actually writing this:");
    Serial.println(dataString);
    vectorData.close(); // close the file
    }

  else{
    Serial.println("Error writing to file !");
}
  vector_loc++;

  return 0;
}

In Arduino SD library FILE_WRITE constant instructs the function to open the file for append, but in the esp32 SD library it opens the file for rewrite. Use FILE_APPEND to open the file for append.

File file = SD.open(path, FILE_APPEND);


Bluetooth HM-10 in central mode bonding with another bluetooth device I have a bluetooth HM-10 configured in central mode. I have successfully connected it to another bluetooth device (a hexiwear bluetooth wearable). The problem now is that the hexiwear requires me to provide a 6 digit pin before it will bond with my HM-10.

Would anyone know the AT command that I could use to send the 6 digit pin from the HM-10 to the hexiwear?

Thank you.

The manual for the HM-10 can be found here.

Page 11 has the AT command you are interested in: AT+PIN:

AT+PIN123456
OK+Set:123456

By default the PIN is 000000.

(The manual is quite vague about the role of that command, so I assume since it is the only reference to PIN codes that it does what you require).


Library for DIY Keyboard I'm planning on making my own Bluetooth mechanical keyboard using the Adafruit Feather 32u4 Bluetooth LE. Something that I haven't really figured out is the programming side of things. I was wondering if there is an easy to use library for this.

I know of the KeyPad library but I'm not sure how to handle modifier keys like Shift and CTRL with it. Any idea can help!

Edit: Like said before the project I'm working on is a Bluetooth mechanical keyboard. So this means there will be 85 (at least for my design) switches in a matrix.

In an ideal world the library I'm looking for can do the following: I specify the keys and their position in a matrix and what the modifier keys are. It can generate the appropriate ASCII character when the matching key(s) are pressed and return it or something, so that I can send it over Bluetooth in another piece of code.

In a less ideal world I use the KeyPad library but I don't really know how to take care of modifier keys like shift when doing that.

Have a nice day!

For shift (making an a into an A), simply program in some ands. Pseudo-code:

if shift AND a:
    return A
elif shift AND b:
    return B

and so on and so forth.


void declaration error I am new to Arduino and C++ and I was practicing with a traffic light project.
This is my code:
int red = 10;
int yellow = 9;
int green = 8;

void setup() {
  pinMode(red,OUTPUT);
  pinMode(yellow,OUTPUT);
  pinMode(green,OUTPUT);
}

void loop() {
  changelights();
  delay (15000);
}

void changelights{
  // 1st action: green off to yellow
  digitalWrite(green, LOW);
  digitalWrite(yellow, HIGH);
  delay (3000)
  // 2nd action: tellow to red
  digitalWrite(yellow, LOW);
  digitalWrite(red, HIGH);
  //3rd action: caution light
  digitalWrite(yellow, HIGH);
  delay (3000)
  //4th action: caution to go
  digitalWrite(red,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, HIGH);
}

I tried compiling it and returned an error message that said that I did not declare my "changelights" function. What should I do to fix this?
Thank you very much

You forgot to put the parenthenses () after the name of the function changelights. They are there to declare variables you can use later in the code like that:
void function(int a){
  a+=1;
  return a;
}

To fix your error just change
void changelights{

to
void changelights(){

Keep in mind if you want to program C++ (which would be Off-Topic here, but you mentioned it in your question) you have to declare the function in the beginning or mention it.


RedBearLab Wifi Mini I am trying to make a program using 'Energia'

  Energia is based on the latest and greatest Arduino IDE modified for TI Launchpad & RedBearLab development boards.

and RedBearLab Wifi Mini v1.0.

Every time I upload a program, even with the standard Arduino 'Blink' example, it resets my board and I need to manually click the RESET button on the board.

I have all the drivers and add-ons installed correctly. How do I fix that?
This is what it shows on the console when I upload a program.

Using HID to reset for RedBearLab board
Opening \\.\COM10
Getting storage list
Bootloader Version: 4
Silicon version ES1.32 or higher
Bootloader version is 2, 1, 4, 0
It's a CC3200 device: PG1.33 or higher
Switch UART pinmux to APPS
Switch to NWP bootloader complete
Load common boot command for PG1.33 or higher
Bootloader version is 2, 0, 4, 0
BlockSize is 4096, number of blocks is 16
erasing 13 blocks starting from  0
erasing file "/sys/mcuimg.bin"
deleting file "/sys/mcuimg.bin"
erase file completed
Downloading file "/sys/mcuimg.bin" with size 2936
.Download complete

I think it always will if the redbear is the type of board that has very little memory and only runs one program at given time.  It resets to run the new program in my humble opinion.  Your mileage may vary.


problem using #define to substitute functions This might be more a general programming question, but I am using the Arduino compiler, and I've created my own ISR driven version of millis(), which I simply call myMillis(). So let's say I'd like to use this addition to a working project. Rather than do a global search and replace, I got the idea to simply put this define near the top of the program...

#define millis myMillis

uint32_t myMillis()
  { // my code ...
  }

So when I compile, every instance of millis() does indeed compile as if I did a global search and replace. I like that, because it means I don't have to make the change permanent, and can easily comment out my defines to compare program operation.

My question is, if I do as I just explained, what if, for whatever reason, there is some place within the project where I actually WANT to call the original version. A simple example might be if I wanted to occasionally output a message via serial.println(), comparing the returned value of millis() and myMillis(). I think there is a way to specify such an exception to my #define MACRO, but I'm not sure how.

There is no way to suppress define substitution. You could use #undef and then #define again in required section.

Name the define MILLIS and use this name in code, except where you want the original millis() function.


Locating a fault in writing a variable I'm writing this piece of code for Arduino Uno, which takes in input on pin 2 the value of a PIR sensor. In order to debug, in this moment I'm taking the signal on pin 2 from the 5V power supply:

int inputPinSensor1 = 2; // input pin for sensor 1
int sensor_1_State = LOW; // we start assuming no motion detected for sensor 1
int val = 0; // variable for reading the pin status

void setup() {
  pinMode(inputPinSensor1, INPUT); // declare sensor 1 pin as input

  Serial.begin(9600);
}

void loop(){
  detectChange(&inputPinSensor1, &sensor_1_State);
}

void detectChange(int* inputPin, int* pirState) {
  // read input value
  val = digitalRead(*inputPin);
  // check if the input is HIGH
  if (val == HIGH) {
    if (*pirState == LOW) {
      // we have just turned on
      Serial.println("Current detected");
      *pirState = HIGH;
    }
  } else {
    if (*pirState == HIGH){
      // we have just turned off
      Serial.println("Current ended");
      *pirState = LOW;
    }
  }
}

This code should detect the passage from a LOW value to an HIGH value on pin 2, and vice versa. In this way I'm expecting to have an HIGH value on pin 2 when I connect the jumper and a LOW value when I disconnect the jumper. But what I get is two possible behaviors: sometimes I get "Current detected" at the begin of the execution, after which there are no further messages, and sometimes I get a rapid alternation of "Current detected" and "Current ended".

As Majenko says in their comments, a pin that's not connected to anything "floats" and gives unpredictable results.

You either need to connect such a pin to ground through a "pull-down" resistor or to +5V through a "pull-up" resistor. (10KΩ is a good value to start with.)

If you connect the pin to +5V through a pull-up resistor then you would ground it to change it's state. In that case the pin reads HIGH normally, and drops to LOW when triggered. Note that the Arduino has a special mode, INPUT_PULLUP, that connects the pin to an internal pull-up resistor. In that case you don't need an external pull-up resistor.

In your case, connect the pin to ground with a 10KΩ restistor. Then when you want the pin to go high attach the pin to +5V. That will swamp the connection to ground and pull the pin up to just below 5V.


Arduino to Home Speakers I know little about electronics in general. I wanted to connect Arduino, and play a tone using tone() through my home speakers.

I've used a 1/8'' audio jack and connect ground to ground and left/right to pin 2. Run it and it was too loud.

Then I read the specification and it says,

Input impedance = 20 kOhm

Input sensibility = 400mV +/- 50mV

Arduino sends 5V so that should be a lot. Did I damage my speaker? They still work.

It's probably not damaged, but you shouldn't do it again.

To get the 5V signal down to 400mV you need to create a voltage divider. As such you will need a:

5V / (400mV / 20kohm) − 20kohm = 230kohm

resistor between the pin and the input. 220kohm should be close enough.


[Solved]How to make my stepper motor run clockwise and counterclockwise? I'm relatively new to Arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

I am using AccelStepper Library

Here is my code:

#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
}

I have tried to add delay and counterclockwise code but its not working.

#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  Serial.println("clockwise");
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
  Serial.println("counterclockwise");
  stepper.setSpeed(-1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
}

Hi here it the reference to the library functions that are available in accelstepper library.

Go through the link, it will provide you the issues with your code and example for your application like @smajli said steps more than 1000 is unreliabe, here you can see setSpeed(float) function where setting negative or positive sign selects the direction and value set the speed of rotation.


Upload Code on Arduino Mega using FTDI Cable I would like to upload my code to the Arduino Mega 2560.

The USB is fried hence I have to use the FTDI
I've a FTDI cable, but it has only 4 wires, Vcc,GND,TX,RX

How do you upload, as the ATmega is not responding to anything?

FTDI cables usually have RTS which is used to bring Reset low. If you only have four pins, press the Reset button on the board the moment you start the upload.


Can external interrupts be OR'd together on the '328 (Uno)? I'm thinking about how to handle a rotary encoder. I'm planning on using interrupts and would like to use both the 'A' and 'B' phase transitions to generate interrupts. I'm wondering if there is any reason why the signals couldn't be OR'd together to generate the interrupt so that I wouldn't need to consume both external interrupts for the encoder.

Regarding the notion that “"internal" interrupt latency and/or software overhead is much higher than it is for the "external" interrupts”, it certainly is true that PCI (pin-change interrupts) libraries PinChangeInt.h (deprecated) and EnableInterrupt.h have high software overhead.  By keeping track of former values, for each pin those libraries support separate callback routines for Rising, Falling, Change, High, and Low.  PCIs are grouped in sets of eight pins per interrupt vector, leading to 40 different cases of callback routines when a PCI fires.  That is, when a PCI occurs, the libraries quickly find out which set of pins changed – because that's what the hardware supports – but then they go through all eight pins on the vector one by one checking if it changed, and how it changed, then calling the callback associated with the particular pin and its particular state.

For reading pins of a rotary encoder, say a KY-040, the overhead described above can cause loss of 10%–20% of rotary counts.  If you are concerned about not losing counts, write your own ISR()-level interrupt service routine.  The example below illustrates a routine using ISR(); this example is from my answer to previous question #18221, with some comments added here and there.  See that answer for discussion of the timing data that is this program's output.  (For rotary encoder quadrature-counting, see discussion below).

/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  // Note, if using an encoder without pullups on it,
  // change INPUT in next 2 lines to INPUT_PULLUP
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

Note, for the above you may need to download and install Streaming.h via Streaming5.zip from arduiniana.org.

Rotary encoder quadrature-counting

The program above tracks and reports pulse-length times, instead of decoding the quadrature signals the rotary encoder provides.  The program below reports rotary encoder counts, but does so using INT0 and INT1 instead of PCIs.  You will want to combine relevant portions of the two routines together – ie, use the interrupt setup and handling framework from above, with the body of the service routine from below.  [Note, this program is from my answer to previous question #16420.  The encoder decoding code within it is faster and shorter than other decoding code I've looked at, and is fast enough to support two encoders rotating simultaneously while losing few counts.]

/*  roto_jw4.ino -- JW, 29 September 2015 --
 *  A 4-state state-machine implementation of rotary
 *  encoding for KY-040 rotary knobs.  The state-machine picture at
 *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
 *  in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts
 *  increasing on transitions 10 -> 11 -> 01 -> 00 -> 10 and
 *  decreasing on transitions the other way.  Transitions between 00
 *  and 11 or 10 and 01 are invalid.  This code detects valid
 *  transitions by (abOld xor abNew) equaling 1 or 2.  It detects
 *  up-count events by the tri-bit value ABA' (where A' is the new
 *  reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of
 *  0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7
 *  (a bit mask of 0x99).
 *
 *  On a KY-040 unit I tested, there are 30 detent positions per turn.
 *  With this unit the code generates 60 counts per turn, which can be
 *  seen individually as one turns the rotor slowly.  Odd counts
 *  appear between detents, even counts at detents.
 *
 *  Set quadrature-signal pin numbers, via PinA and PinB constants.
 *  Set IPINMODE to INPUT_PULLUP if there are no external pull-ups
 *  on encoder AB pins, else set IPINMODE to INPUT
 */
enum { PinA=2, PinB=3, IPINMODE=INPUT };

static  byte abOld;     // Initialize state
volatile int count;     // current rotary count
         int old_count;     // old rotary count

void setup() {
  pinMode(PinA, IPINMODE);
  pinMode(PinB, IPINMODE);
  attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts
  attachInterrupt(1, pinChangeISR, CHANGE);
  abOld = count = old_count = 0;
  Serial.begin(115200);
  Serial.println("Starting Rotary Encoder Test");
}

// On interrupt, read input pins, compute new state, and adjust count
void pinChangeISR() {
  enum { upMask = 0x66, downMask = 0x99 };
  byte abNew = (digitalRead(PinA) << 1) | digitalRead(PinB);
  byte criterion = abNew^abOld;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*abOld + abNew/2)))
      count++;
    else count--;       // upMask = ~downMask
  }
  abOld = abNew;        // Save new state
}

void loop() {
  if (old_count != count) {
    Serial.print(millis());
    Serial.print("  ");
    Serial.println(count);
    old_count = count;
  }
}

Using other pins for PCIs

If you wish to monitor two rotary encoder lines using pin change interrupts on pins other than A0 and A1, you may need to replace vector PCINT1_vect with some other vector, and will need to replace the pins mask with a different one.  The following program can be used to display a table of PCI vectors, masks, etc.  (As noted in my question Why PJ0 and PJ1 are not reporting as PCINT pins, pins PJ0 and PJ1 on an ATmega-2560 board will not report correctly.)

/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

ISR-framework-generating Sketch

The program below generates frameworks for specified PCI pins and prints them to Serial.  See usage comments within the program.  This provides an easy way to create the basic outline of an ISR to handle PCIs.

/*  pinFunctions -- JW, 1 October 2015 --
 *
 *  Displays direct pin-access and pin-change-interrupt setup code,
 *  for inclusion in a sketch, for specified pin numbers.  The
 *  displayed code can be pasted into a sketch where execution speed
 *  matters.
 *
 *  When called with a call like `genCode ("affix", "9,11");`, genCode
 *  will produce a set of procedures: ISR routines for pins that
 *  support pin-change interrupts; get and put routines to read from
 *  or store to registers; and a setup routine.  The generated get,
 *  put, and setup routines will have names formed by suffixing the
 *  affix to get, put, and setup, respectively.  For example, if the
 *  affix is ML47 the names of generated routines will include
 *  getML47, putML47, and setupML47.
 *
 *  Generated get() and put() code is of the following forms (in which
 *  u, v are port-letters; values mu, mv, ni are numerical constants;
 *  and w is a parameter value) if all the pins, n1, ... nk in the
 *  pins-list are in port u, under mask mu:
 *
 *             return PINu & 0xmu; // Get pins n1, ... nk
 *             PORTu = PINu & ~mu | w & mu;
 *
 * For example, with Uno pins 3, 4, 6, get() and put() bodies are:
 *
 *             return PIND & 0x58;
 *             PORTD = PIND & 0xa7 | w & 0x58;
 *
 *  The following forms arise if the pins are in ports u and v; and so
 *  forth if more than two ports are involved.
 *
 *             return PINu & masku | PINv & mv; // Get pins n1, ... nk
 *             PORTu = w & 0xmu;   // Put pins <u pins>
 *             PORTv = w & 0xmv;   // Put pins <v pins>
 *
 *  genCode() does not require that all pins belong to the same port.
 *  It will produce usually-desired results if bit positions don't
 *  interfere, otherwise may not.  For example: An Arduino Uno
 *  pins-list "2,10" corresponds to port pins PD2 and PB2.  Both are
 *  in bit position 2, so get's result will be the OR of the PB2 and
 *  PD2 values, while put will store the same bit value to both pins.
 *
 *  To use the pasted code: A statement like `w = getAFFIX();` will
 *  read a set of pins and store the value in w.  A statement like
 *  `putAFFIX(w);` will write w to a set of pins.  Also, add a line
 *  like the following in setup():
 *
 *       setupAFFIX(ioMode, enablePCI);
 *
 *  In the `setupAFFIX(ioMode, enablePCI);` call, substitute an
 *  appropriate affix in place of AFFIX; substitute one of INPUT,
 *  OUTPUT, or INPUT_PULLUP in place of ioMode; and substitute 1 or 0
 *  for enablePCI, to enable or not enable pin-change-interrupt setup.
 *
 *  If you want to save room and don't plan to use pin-change
 *  interrupts, instead of merely not enabling PCI setup, you can
 *  remove the ISR routines and the `if (enablePCI) {...}` section
 *  from the pasted code.
 *
 *  Each generated ISR routines contains one line, of form
 *
 *        byte datum = PINu & mu; // Read pins <list>
 *
 *  The idea is that you will paste the generated ISR into your
 *  sketch, then populate it with appropriate interrupt processing
 *  code.  Note 1: datum contains data from one port, a port which
 *  belongs to the interrupt vector.  If you need data from other
 *  ports as well, then paste appropriate lines from the get() routine
 *  into the ISR.  Note 2: This version of pinFunctions does not
 *  announce pins that don't belong to PCI vectors, if any.
 *  (Processor pins with functions like PCINT0 ... PCINT23 belong to
 *  PCI vectors.)  You can compare the masks used in get() to those
 *  used in the ISR's to detect this.  If the masks differ, some pins
 *  aren't PCI pins.  Note 3: If multiple ports' pins belong to one
 *  vector (eg Ard#0 or PE0 for PCINT8 and Ard#15 or PJ0 for PCINT9,
 *  both on vector PCINT1_vect), a code-generation error of form "Pin
 *  x's port #y isn't #z" will appear and you will need to paste in
 *  appropriate lines from get() or otherwise manually prepare correct
 *  code.
 */

char buffi[128];        // We create text-to-write in buffi
char buffn[32];         // also in buffn
byte nbuff=0;           // #chars used in buffn
char *c;            // c points into pinsList
byte pin;           // pin number
byte nPCICR;            // 0, 1, or 2 for mask-register #
byte vecmask;           // OR of 1<<nPCICR values
byte intmask[3];        // OR of int. enable masks
byte maskBitPC;         // 0 to 7 for bit in PCI mask
byte maskBitIO;         // 0 to 7 for bit in I/O mask
byte pinPort;           // pin's port #, in range 1 to 12
byte PCInum;            // PCINT# if pin is a PCI pin

// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}

// Get next pin number from pinsList, and its associated reg numbers
byte getPinNumber() {
  byte cc=*c;
  if (!cc)
    return 0;
  pin=0;
  for (; '0' <= cc && '9' >= cc; cc=*++c) {
    pin = 10*pin + cc - '0';
  }
  pinPort = maskBitIO = PCInum = nPCICR = maskBitPC = 0;
  if (pin < NUM_DIGITAL_PINS) {
    pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
    maskBitIO = digitalPinToBitMask(pin);
    if (digitalPinToPCICR(pin)) {        // Is it a PCint pin?
      nPCICR  = digitalPinToPCICRbit(pin); // 0, 1, 2 for p's PCICR bit#
      maskBitPC = digitalPinToPCMSKbit(pin);
      PCInum =  nPCICR*8+ getBitfromBV(maskBitIO);
    }
  }
  if (!cc)         // At end of string? If so,
    --c;           // allow for caller incrementing c
  return 1;
}

void genCode (char *affix, char *pinsList) {
  char *portLet = "?ABCDEFGHIJKL?";
  enum { portMax=12 };
  byte readmask;        // Input-bits mask
  byte port;            // Port #

  snprintf(buffi, sizeof(buffi), "\n// %s : pins %s", affix, pinsList);
  Serial.println(buffi);

  //==================================================================
  // Generate  "byte get<affix>() { // Get pins <list>"
  //              return PINu & mu | PINv & mv | ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "byte get%s () { // Get pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of get...() function
  nbuff = snprintf(buffi, sizeof(buffi), "  return");
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask)
      nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " PIN%c & 0x%02x |",
            portLet[port], readmask);
  }
  snprintf(buffi+nbuff-2, sizeof(buffi)-nbuff, ";\n}"); // -2 loses extra " |"
  Serial.println(buffi);  // Print last two lines of get...() function

  //==================================================================
  // Generate  "void put<affix>(byte w) { // Put pins <list>"
  //              PORTu = PINu & ~mu | w & mu;
  //              ...
  //            }"
  nbuff = snprintf(buffi, sizeof(buffi), "void put%s () { // Put pins", affix);
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "% d,", pin);
    readmask |= maskBitIO;
      }
    }
    if (readmask) buffi[nbuff-1] = ';'; // Replace extra , by ;
  }
  Serial.println(buffi);    // Print first line of put...() function
  for (port=1; port<=portMax; ++port) {
    for (readmask=0, c = pinsList; getPinNumber(); ++c) {
      if (pinPort==port) {
    readmask |= maskBitIO;
      }
    }
    if (readmask) {
      snprintf(buffi, sizeof(buffi), "  PORT%c = PIN%c & 0x%02x | w & 0x%02x;",
           portLet[port], portLet[port], (byte)(~readmask), readmask);
      Serial.println(buffi);  // Print a port-setting line of put...() function
    }
  }
  Serial.println("}");  // Print last line of put...() function

  //=================================================================
  // Generate ISR's:  Process 3 possible pin-change interrupt vectors
  vecmask = 0;
  for (byte ivect=0; ivect < 3; ++ivect) {
    byte sinPort=15;        // currently-in-use same port #
    intmask[ivect] = 0;
    byte busyvect=0;              // Assume vector not used
    byte readmask=0;              // Input mask
    // Loop to see if vector is used
    for (c = pinsList; getPinNumber(); ++c) {
      if (nPCICR == ivect) {
    ++busyvect; sinPort = pinPort;  // Bits on same port get read once
    vecmask |= 1<<ivect;
    intmask[ivect] |= 1<<maskBitPC;
      }
    }
    if (busyvect) {     // If vector is busy, create its ISR
      snprintf(buffi, sizeof(buffi), "ISR(PCINT%d_vect) {", ivect);
      Serial.println(buffi);
      nbuff = 0;
      for (c = pinsList; getPinNumber(); ++c) {
        // See if it's a PCint pin, and on the current vector
    if (digitalPinToPCICR(pin) && nPCICR == ivect) {
      intmask[ivect] |= 1<<maskBitPC;
      readmask |= digitalPinToBitMask(pin);
      nbuff += snprintf(buffn+nbuff, sizeof(buffn)-nbuff, " %d,", pin);
      if (pinPort != sinPort) {
        snprintf(buffi, sizeof(buffi), "Pin %d's port #%d isn't #%d",
             pin, pinPort, sinPort);
        Serial.println(buffi);
      }
    }
      }
      snprintf(buffi, sizeof(buffi), "  byte datum = PIN%c & 0x%02x; // Read pins %s\n}",
           portLet[sinPort], readmask, buffn);
      Serial.println(buffi);
    }
  }
  snprintf(buffi, sizeof(buffi), "void setup%s(byte ioMode, byte enablePCI) {", affix);
  Serial.println(buffi);
  for (c = pinsList; getPinNumber(); ++c) {
    nbuff = snprintf(buffi, sizeof(buffi), "  pinMode(%2d, ioMode); // %2d, P%c%d",
         pin, pin, portLet[pinPort], getBitfromBV(maskBitIO));

    if (maskBitPC)
      snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "   PCINT %d", PCInum);
    Serial.println(buffi);
  }
  Serial.println("  if (enablePCI) {");
  for (byte ivect=0; ivect < 3; ++ivect) {
    if (intmask[ivect]) {
      snprintf(buffi, sizeof(buffi), "    PCMSK%d |= 0x%02x;", ivect, intmask[ivect]);
      Serial.println(buffi);
    }
  }

  snprintf(buffi, sizeof(buffi), "    PCIFR  |= 0x%02x; // clear PC interrupts if any",
       vecmask);
  Serial.println(buffi);
  snprintf(buffi, sizeof(buffi), "    PCICR  |= 0x%02x; // enable PC interrupts\n  }\n}",
       vecmask);
  Serial.println(buffi);
}

void setup() {
  Serial.begin(115200);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("Starting Code Generation");
  genCode ("A0A1",  "14,15\0"); // A0, A1 on a nano
  genCode ("Pair78",  "7,8");
  genCode ("Trip346",  "3,4,6");
  genCode ("Quad789A", "7,8,9,10");
  genCode ("Hex8toD",  "8,9,10,12,11,13");
  genCode ("LotsSmall", "2,6,7,8,9,10,11,12,13,14,15,19,20,21,22,28,29,30,31,37");
  genCode ("LotsBig",   "31,37,38,37,38,45,46,52,53,54,55,61,62,63,69,70,71,76");
  Serial.println("Ending Code Generation");
  Serial.end();
}

void loop() {
}


How to get Baite Pro Mini working? I have recklessly bought the Baite Pro Mini and I find it difficult to upload any program. I use Ubuntu Linux, but out of frustration I am ready to install Windows, if it is necessary.

I've read the information from the blog http://nerdralph.blogspot.ca/2014/01/baite-pro-mini-review.html . Too bad, that the blog owner didn't put much details. Can anyone here fill some blanks for me?

How exactly should I connect the Arduino device to the computer?
I have a converter USB to serial pl2303HX:  which I tried to connect with the Baite Pro Mini in almost any plausible permutation of the wires, but never got any result.

edit:

Here is the description of pins of the pl2303HX:

I did connect it the following way:

Baite Pro Mini      pl2303HX
GND
GND  <------------> GND
VCC  <------------> +5V
RXI  <------------> TXD
TXC  <------------> RXD
DTR

I also tried the permutation with different GND pin. I also tried pressing the reset button on the Baite Pro Mini around the time of hitting the "Upload" button on the Arduino standard compiler.

I believe my failure might have something to do with the absence of DTR pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

Which exactly Arduino bootloader do I need?
How to connect USBASP to the Beite Pro Mini?

I have several clone Pro Minis I got from several sources on ebay for ~ £2 ($3) each. I also use Ubuntu (10.04 on this old PC but it's fine).

I started with a USB converter similar to yours and it was a bit hit-and-miss choosing when to press the reset to upload. Once I got connections right and worked out when to press reset it became a more reliable procedure but still a pain.

I realised that it would be better to use the auto-reset from DTR so I got a cheapo USB to serial from ebay which claimed to be FTDI (or compatible?) though I didn't know what that meant at the time. With a small converter board to make the right connections it works well.

Your connections look good so if you haven't damaged anything it's probably a matter of when to press reset. Windows won't help!

You must choose the correct board in the Tools menu of the Arduino IDE - Pro Mini with correct AVR chip, speed and voltage. I use programmer AVR ISP (I think)


Have I fried my A2 port? I'm playing around with a SparkFun Redboard (essentially, an Arduino UNO).

I have a simple 5V sensor that I'd been trying to get to work with A2 and analogRead(). Nothing seemed to work. It's supposed to be cycling from 0 to 5V, which should give me values from 0 to 1023, and instead I get constant values of around 260.

In desperation, I tried using other ports. On A0, A1, and A3 I get the signals I expect. On A2, still nada.

So, the question. Is there something I could have done in configuring things that would have made A2 and only A2 stop reading correctly? If so, how can I reset it?

Or is there some other function that I might be using that could interfere with A2? Currently, I'm only using Serial over USB - could that interfere with A2?

Or could I simply have fried the port?

I wrote a simple program that used all six analog pins as digital outputs, and wired up an LED. All of the pins except A2 would blink the LED. So yes, it is fried.  Thanks.


How to connect two Arduino without shields? I'm planning an Arduino system that consists of several Arduino boards. The maximum distance between the boards is about 50 meters. I want to send basic data between these, like short strings or integers. I know I could send data through ethernet cables but that requires an ethernet shield or the Arduino Ethernet board that doubles the costs. Is there a low budget way I could connect the boards using only the most basic boards (like Uno) and some other components but not a full shield?

For long distance wired communication, look at RS-485.

  Since it uses a differential balanced line over twisted pair (like
  RS-422), it can span relatively large distances (up to 4,000 feet
  (1,200 m)). A rule of thumb is that the speed in bit/s multiplied by
  the length in meters should not exceed 108. Thus a 50 meter cable
  should not signal faster than 2 Mbit/s

You can use the MAX485 chip. It's pretty easy to work with but there's a good library as well:

https://github.com/Protoneer/RS485-Arduino-Library


Data Logging without Interfacing SD Card module I want to log data to a text document without connecting the SD card module. I don't want to print the data on Serial Monitor I want to store it in a file. Is it possible? Can someone help me with it?
I am using a Arduino Nano on a Windows 10 system, and I want to know if there is an Arduino library to write logs to a file.

The simplest answer is to install a program that handles serial connection and can write everything into a logfile. On Linux, CuteCom is a program like that. On Windows, putty can handle serial (as well as SSH and telnet), and has logging.

The more advanced soulution is to write a program (or a simple script) that can do that. You could make it to do some other stuff as well (like configuring the Arduino side), and you can run it in the background without user interaction.


Two solenoid valves, both independent I am currently working an automatic home gardening system. There are two moisture sensors and two solenoid valves to allow water to plant two different zones. Preferably, I want to water the plants for x amount of time. I started programming this and I noticed that with my code below, if one solenoid valve goes off, the entire program will delay until one of the solenoid valves closes and thus the other solenoid valve will not open until the other one is closed.

However, I want to prevent this from happening and I want the program to continue reading the moisture readings while one of the solenoid valves is open so that the other solenoid valve can open whenever the zone needs water as well.

int solenoidPin1 = 1; //connected to Digital 1
int solenoidPin2 = 2; //connected to Digital 2
void setup(){
  pinMode(solenoidPin1, OUTPUT);
  pinMode(solenoidPin2, OUTPUT);
}
void loop(){
  int moisture1 = analogRead(moisturePin1);
  int moisture2 = analogRead(moisturePin2);
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
}

I was thinking that I should do the following for the conditioning part. Will this work instead for what I'm trying to do?

  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  }
  else if (moisture1 >= 550){
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  }
  else if (moisture2 >= 550){
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }

Note: I'm using a capacitive moisture sensor, so the output voltage/reading is higher the drier the dirt is.

The essence of your problem is that the delay() function blocks
your program until the delay is over. This is only acceptable if the
program is doing one single things at a time. If you need to do multiple
things in parallel, like monitoring two moisture sensors, this approach
does not work.

Then, the first thing is to get read of delay() and instead use
millis() for managing time in a non blocking fashion. The essence of
this approach is to never wait. Instead, if it is time to do something
right now, you do it. If not, you just don't do it this time, but you
don't wait. This is nicely covered in the Blink without delay
Arduino tutorial. You should get familiar with this technique, as it is
essential for many Arduino projects.

Your problem is slightly more complex than blinking an LED though, as
the valve can be in two different states, and the action to perform
depends on that state. This is managed by a software construct called a
finite state machine. Essentially you have to remember the current
state and, depending on it, you decide what to do and what the next
state should be. Here is how you could do the timed watering with this
approach:

static enum { OFF, ON } stateValve1, stateValve2;
static uint32_t startedValve1, startedValve2;  // time when started

if (stateValve1 == OFF && analogRead(moisturePin1) <= 250) {
    digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
    startedValve1 = millis();
    stateValve1 = ON;
} else if (stateValve1 == ON
        && millis() - startedValve1 >= WATERING_TIME) {
    digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
    stateValve1 = OFF;
}

// and the same for valve 2.

For more in-depth coverage of the subject, I recommend you read the
Majenko's tutorial on finite state machines

At this point, the next step would be to throw in some modularization in
order to make the code less repetitive. I suggest making a class for
representing a “timed valve”. The valve has a turnOn() method that
turns it on, but does nothing if the valve is actually already on. The
class takes care of turning the valve off when the time has elapsed. But
since it cannot do that all by itself, you have to call an update()
method periodically to give it a chance to check whether it's time to go
off. Here is my implementation of that class:

const uint32_t WATERING_TIME = 100000;  // for example

class TimedValve
{
public:
    TimedValve(uint8_t pin) : valvePin(pin), state(OFF) {}
    void turnOn() {
        if (state == ON) return;  // do nothing if already ON
        digitalWrite(valvePin, HIGH);
        state = ON;
        timeStarted = millis();
    }
    void update() {
        if (state == ON && millis() - timeStarted >= WATERING_TIME) {
            digitalWrite(valvePin, LOW);
            state = OFF;
        }
    }
private:
    uint8_t valvePin;
    enum { OFF, ON } state;
    uint32_t timeStarted;
};

And you would use it like this:

const int solenoidPin1 = 1;
const int solenoidPin2 = 2;
const int moisturePin1 = A1;
const int moisturePin2 = A2;

void setup(){
    pinMode(solenoidPin1, OUTPUT);
    pinMode(solenoidPin2, OUTPUT);
}

void loop()
{
    static TimedValve valve1(solenoidPin1), valve2(solenoidPin2);

    // Turn the valves ON if needed.
    if (analogRead(moisturePin1) <= 250)
        valve1.turnOn();
    if (analogRead(moisturePin2) <= 250)
        valve2.turnOn();

    // Let them turn OFF if it's time.
    valve1.update();
    valve2.update();
}


How can I use my Arduino sketches on my Raspberry Pi IDE? I have installed the Arduino IDE 2:1.0.5 on my Raspberry Pi3 under Raspbian and am using a cobbler breakout which provides a nice breadboard.  On that breadboard I have installed an Arduino Nano to do analog voltage readings, which it then communicates back to the Rpi3 via the USB serial port which shows up as /dev/ttyUSB0 on the Rpi3.

This port opens as a regular file in Python for further processing such as adding a date & time stamp (obtained by an NTP server) and saving the results to a data file that is displayed in gnuplot 4.6.

You'll notice I am using 3.3 Volts for the fan to keep it quiet, and the two wires heading up to the top go to the voltage source I am monitoring.  If you look closely you can see the voltage divider circuit.

Here is today's solar plant voltages which this thing tracks.  The block at the bottom means the inverter was on.  Green means the battery bank is full.

Anyway, it turns out that the same serial connection is supported by the Rpi Arduino IDE for programming.

Rather than programming the Nano on a laptop and constantly having to unplug/replug it on the breadboard my goal is to use Rpi Arduino IDE for programming.

So I moved all my sketches over from the Arduino IDE on the laptop to the Rpi.

But

.... then every time I start the Rpi IDE it throws error messages for all the sketches that have underscores in their names.  Turns out the Rpi version will only allow alphanumeric directory names.  I have a couple dozen sketches and this is not productive.  It requires clicking OK for every directory it skips - which turns out to be all of them.

So my question is:  What can I do about this?

To fix this problem I came up with the following procedure which takes out all the underscores from the directories & filenames and capitalizes each word instead.

First, I copied all my sketches and libraries (from my documents/arduino directory) to a USB flash drive.

The Rpi Arduino IDE creates a sketchbook directory upon install, so I

Copied the libraries folder to ~/sketchbook/libraries

Copied the sketches folder to ~/sketchbook/AMSsketches

Then I wrote a custom script that is copied to my home directory on the Rpi, which can be obtained here as a text file (use Chromium or wget to copy it to the file ~/AMS2Rpi)  - Here is the link:  http://calttc.net/AMS2Rpi

which contains this code:

#! /bin/bash
#
#  AMS2Rpi - Converts MS Arduino IDE Sketch names to RPI Arduino IDE Sketch names
#
#                  SDsolar      2017-01-29
#
#  Reason:    Arduino IDE on MS inserts underscore characters in file & directory names
#             Arduino IDE on Rpi rejects all but alphanumeric characters
#
#  Solution:  Remove all but alphanumeric characters
#             and capitalize each word in the names
#
#  Usage:
#    Install Raspbian Arduino IDE 2:1.0.5 on the Raspberry Pi 3
#    Use a USB flash drive to copy sketches and libraries from the MS-based Arduino IDE
#      On the Rpi, copy the libraries directory to ~/sketchbook/libraries
#      On the Rpi, copy the sketches directory to ~sketchbook/AMSsketches
#    Copy this script to your home directory as AMS2Rpi using Chromium
#    cd
#    chmod +x AMS2Rpi
#    ./AMS2Rpi    (This will take some time)
#    cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMSRpiQ
#    chmod +x ~/AMS2RpiQ
#    ~/AMS2RpiQ
#    Open the Rpi Arduino IDE
#
#  Alternatively, if you have a lot of sketches you might want to
#    change the "mv -i" below to "mv"
#    and cat it into AM2SRpiX above
#    so you don't need to answer "y" for every rename.
#
#  Props to Marco Fioretti for his article at http://www.techrepublic.com/blog/linux-and-open-source/how-to-remove-weird-characters-from-file-and-directory-names-automatically/
# ---------------------------------------------------------------------
rm -f /tmp/AMS2R*
cd $1
find .  | awk '{ print length(), $0 | "sort -n -r" }' | \
        grep -v '^1 \.$' | cut -d/ -f2- > /tmp/AMS2Rpi_1
touch /tmp/AMS2Rpi_2
while read line
  do
  BASE=`basename "$line"`
  NEWBASE=`basename "$line" | perl -e '$N = <>; chomp ($N); $N =~ s/[^a-zA-Z0-9.]//g; $N =~ s/_+/_/g; $N= lc($N); $N =~ s/_([a-z])/_.uc($1)/eg; print ucfirst($N);' `
  if [ "$BASE" != "$NEWBASE" ]
  then
  OLDPATH=$(echo "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  DIR=$(dirname "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
  echo "mv -i $OLDPATH $DIR/$NEWBASE" >> /tmp/AMS2Rpi_2
  fi
done </tmp/AMS2Rpi_1
rm -f /tmp/AMS2Rpi_1
mv /tmp/AMS2Rpi_2 /tmp/AMS2Rpi
exit

Then set it to executable and run it:

cd
chmod +x AMS2Rpi
./AMS2Rpi

When it is finished, I filter out just the directory I want (VERY IMPORTANT):

cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMS2RpiQ

(You can look at that file to verify it before running it)

chmod +x ~/AMS2RpiQ
~/AMS2RpiQ

Cleanup if you wish:

rm /tmp/AMS2R*
rm ~/AMS2RpiQ

Now the Arduino IDE on the Rpi opens cleanly and all my sketches are there.

Problem solved.   It works great.


Can't manually connect HC-05 master to slave Using this as a tutorial, I've tried to connect the master Bluetooth module from my Nano to the slave module in my Mega. After following the steps in the tutorial, when I enter the command to my serial monitor:

AT+BIND=98d3,31,30690

I receive:

ERROR:(7)

After looking up the error, I only get results for ERROR:(0)

Does anyone know what the error means or how to fix it?

I found the solution.

Apparently, both of my modules were at 9600 baud rate when the optimal rate is of 38400. I had to use AT+ORGL in command mode to reset both slave and master. Afterwards I was able to connect them manually.

So apparently ERROR:(7) represents a failed connection? Just don't forget to make sure everything is exactly like the tutorial that's teaching you.


Arduino PWM fading led I am trying to blink an LED with PWM on Arduino.

I don't know what is wrong but my LED is not fading as expected. What is wrong?

I think that I have bad registers settings, but I am not sure.

LED is connected to Arduino pin 9.

Here is my code:

#include <avr/io.h>
#include <util/delay.h>
const int delay=1000;
void initialize_PWM()
{
    TCCR0A|=(1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
    TCCR0B=1;
    DDRB|=(1<<PB1);
}

void set_pwm(uint8_t data)
{
    OCR0A=data;
}

int main (void)
{
    initialize_PWM();
    uint8_t brightness=200;
    while(1)
    {
        for(brightness=0;brightness<255;brightness++)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }

        for(brightness=255;brightness>0;brightness--)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }
    }
    return 0;
}

From your code you are using Timer0 in FastPWM mode with top = 0xFF.

In this mode, as used in your code, OCR0A defines the pulse width rate (more precisely, OCR0A / 256).

Timer0 uses port OC0A and OC0B to ouput PWM signals, in your code, you are using only OC0A (which is perfectly fine).

Now if you take a look at ATmega 328 data sheet, chapter 14.3.3 you will see that pin OC0A maps to port D, pin PD6 (on Arduino UNO, this is port D6, according to http://arduino.cc/en/Hacking/PinMapping168).

So this means that you have used the wrong port in your setup (Arduino pin D9 maps to OC1A, which is pin PB1 of port B on ATmega328, OC1A is used by Timer1, not Timer0).

Hence you should do the following to fix the problem:

Plug the LED to Arduino pin D6 instead of D9
Fix initialize_PWM() by replacing DDRB|=(1<<PB1); with DDRD|=(1<<PD6);

Otherwise, if you want to keep Arduino pin D9, then you will have to change the timer you use: Timer1 instead of Timer0. Updating the code is left as an exercise!


Nodemcu does not connect to phone wifi All welcome.

I'm trying to connect nodemcu to the phone's wifi.

And nodemcu can't do it. But sometimes after several reboots she does it. Also if i use my old phone - nodemcu connects perfectly! Why?

My "new" phone: Fly FS504 Cirrus 2

My old phone: Fly IQ4504 Quad.

My code:

#include <ESP8266WiFi.h>

const char *ssid =  "Just my SSID";

const char *pass =  "Some password";

WiFiClient client;

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

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

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            // stack here (only with new phone)
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");
}

void loop()
{

}

From my experience the esp8266's wifi is a little bit buggy sometimes. I'm not sure if it has something to do with the esp auto-connecting to known networks, but I managed to work-around this issue by explicitly WiFi.disconnect()ing from any potential network right before calling WiFi.begin().

Another thing that I noticed several times is that the esp can be easily disturbed when connected to a breadboard, in special when wifi is in use (in this case the esp might even crash). There must be some bad interferences, I guess.


Can wifi shield connect to local network without internet? I have an Arduino Uno and a Texas Instruments CC3000 WiFi shield. I need to connect the Arduino to a local network which has no Internet access so that it can send information to a computer also connected to the same local network. I am using a Linksys WRT120N for the local network.

I can't use the Internet access WiFi because it is WPA2 Enterprise which is why I created the local network. Currently the computer is connected to the local network via WiFi.

I have downloaded and installed the correct library but when I run the connection test, it searches for Internet access which doesn't exist and sends back errors.

How do I verify that it is connecting to the local network?

Btw, I have almost no experience coding an Arduino but I have access to people who are proficient; However, they have no experience with a WiFi shield.

If you have created your own local network, you may need a DHCP server to give it an IP address, or you will have to configure your Arduino with a static ip. I can't think of a reason why it would need internet access, but it is not uncommon for devices to refer (incorrectly) to connectivity issues on the local network as "internet" issues.


Bluetooth HC-05 Library for Proteus I m working on a project in which I am using HC04 module so can anyone give me any Arduino Library for Proteus which have HC05 in it. Or tell me how to use HC05 in Proteus.

Thanks.

I don't know Proteus, but I think HC05 a bluetooth module? If so, the module interface from HC05 <==> arduino is done through Serial (UART) communication.
Arduino has built in support for this - you don't need any special libraries besides SoftwareSerial.
wire up the module as such:

Then run the following code:

#include <SoftwareSerial.h>

#define rxPin 10 // connected to TX pin of HC05
#define txPin 11 // connected to RX pin of HC05

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char bt;

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

  mySerial.begin(9600);
  mySerial.println("World");
}

void loop(){
  while(mySerial.available()){
    bt = mySerial.read();
    Serial.print(bt);
  }

  while(Serial.available()){
   bt= Serial.read();
   mySerial.print(bt);
  }
}


Increasing payload size above 32 bytes using nRF24L01+ I tried to modify the example in the following page, by replacing the given string with a 56 bytes one after making all the suitable changes to read(), write() and max_payload_size(increased to 64 bytes), payload_size() parameters/methods in the RF24 library.

http://shanes.net/another-nrf24l01-sketch-string-sendreceive/

The problem is the receiver truncates the string to 32 characters. Is 32 bytes a hard limitation for payload with the nrf24l01+ radio? If so how to I modify the receiver in above example problem to receive the entire string?

If you look at the specification or datasheet for the nRF24l01+, you will see that the 32 byte payload is the maximum that the device can handle.
For example:

If you need to transmit anything larger than 32 bytes, you will need to develop a protocol that splits up your data into chunks of 32 bytes or less and sends the data in several packets.
The actual protocol you design is up to you, but a simple technique might be using the first packet to send a count of the number of data packets to expect and then simply send those packets, each with a part of your data and reassemble it at the receiving end.
You may need to design something more robust so you don't get confused by lost packets or bad data. The larger your payload, the more chance of transmission errors, so it might be an idea to experiemnt with the payload size to get the best throughput for your particular application.


How to avoid calling multiple times Wire.begin() in libraries? it's all in the title ; I'm developping a library and use *TwoWire pointers in this library ; but I am using an external library that calls Wire.begin(). I've seen something about TWCR register in arduino but I don't know what it is exaclty.

Thanks in advance :)

What you are interested in is this bit of the Wire library:

TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

The important bit is the TWEN bit - TwoWire ENable.

If that bit is set in the TWCR register than Wire.begin() has been called already and you don't need to call it again:

if (TWCR & _BV(TWEN) == 0) {
    Wire.begin();
}

However, it really doesn't matter if you call it multiple times.


How to interpret Serial data received by Bluetooth module I'm experimenting with a hc-05 knockoff the JDY-30 and am confused about the Serial data I'm getting from it. I downloaded an app called BlueUino to send commands from my Android to my Arduino Uno via Bluetooth. I then print the data I get via Serial port using the code below:
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = '1'; //Serial.read(); // Reads the data from the serial port0
    stateData = Serial.read();
    sprintf(data, "Data is %u", stateData);
    Serial.println(data);
    Serial.println();
 }

Here are some of the results I get in the log which I can't make sense of. For example, sending the string "def" doesn't contain the sequence of data from sending the command "e". Also, how does one convert these values to characters ?
Send Command "b"
Data is 128
Data is 0
Data is 248

Send Command "abc":
Data is 120 // doesn't contain the sequence of Data of "b"
Data is 120
Data is 120
Data is 0
Data is 120
Data is 0
Data is 248

Or just storing the inbound data in a char type and use single quotes when parsing incoming bytes so that the compiler knows your dealing with ASCII, print them out on serial and they should be familiar characters, of course with the baud rate mismatch fixed


AnalogWrite only working for one pin of RGB LED I'm working on some code for a Nerf blaster with an LED indicator light. When attempting to use analogWrite to PWM my LED pins, only one pin (blue) behaves as expected and dims down. The other two (red, green) don't light up at all. The LED is confirmed working and the Arduino.cc fade example works fine on each pin individually when testing. Here is the code:

#include <ClickButton.h>
#include <Servo.h>

Servo esc;

ClickButton rev(6, LOW, CLICKBTN_PULLUP);
ClickButton mode(7, LOW, CLICKBTN_PULLUP);
ClickButton trig(8, LOW, CLICKBTN_PULLUP);

int flyPin = 2;
int escPin = 3;
int pushPhasePin = 4;
int pushSpeedPin = 5;
int RED = 9;
int GREEN = 10;
int BLUE = 11;

int m = 1;
int singleShot = 100;

bool shot = false;

void setup() {
  pinMode(flyPin, OUTPUT);
  pinMode(pushPhasePin, OUTPUT);
  digitalWrite(pushPhasePin, HIGH);
  pinMode(pushSpeedPin, OUTPUT);

  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);

  esc.attach(escPin, 1000, 2000);
  esc.write(0);

  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, HIGH);
  digitalWrite(GREEN, HIGH);
  delay(500);
  digitalWrite(RED, LOW);
  digitalWrite(BLUE, LOW);
  digitalWrite(GREEN, LOW);
  delay(500);
  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, HIGH);
  digitalWrite(GREEN, HIGH);
  delay(500);
  digitalWrite(RED, LOW);
  digitalWrite(BLUE, LOW);
  digitalWrite(GREEN, LOW);
  delay(1500);
}

void loop() {
  rev.Update();
  mode.Update();
  trig.Update();

  if (mode.clicks != 0) {
    m++;
    if (m > 3) {
      m = 1;
    }
  }

  if (m == 1) {
    digitalWrite(RED, LOW);
    digitalWrite(BLUE, LOW);
    analogWrite(GREEN, 120);
  }
  else if (m == 2) {
    digitalWrite(RED, LOW);
    analogWrite(BLUE, 120);
    digitalWrite(GREEN, LOW);
  }
  else if (m == 3) {
    analogWrite(RED, 120);
    digitalWrite(BLUE, LOW);
    digitalWrite(GREEN, LOW);
  }

  if (rev.depressed) {
    digitalWrite(flyPin, HIGH);
    esc.write(40);
  }
  else {
    digitalWrite(flyPin, LOW);
    esc.write(0);
  }

  if (trig.depressed) {
    if (m == 1) {
      if (!shot) {
        digitalWrite(pushSpeedPin, HIGH);
      }
      delay(singleShot);
      shot = true;
      digitalWrite(pushSpeedPin, LOW);
    }
    if (m == 2) {
      if (!shot) {
        digitalWrite(pushSpeedPin, HIGH);
      }
      delay(singleShot * 3);
      shot = true;
      digitalWrite(pushSpeedPin, LOW);
    }

    if (m == 3) {
      digitalWrite(pushSpeedPin, HIGH);
    }
  }

  else {
    digitalWrite(pushSpeedPin, LOW);
    shot = false;
  }
}

The relevant portion that is failing is under the "if m == 1,2,3" blocks. Where m [for mode] == 2, the blue light works but the other leds do not light when cycling through the modes. Note the leds are on PWM pins (9,10,11). Thanks for any help!

You are trying to combine the use of the Servo library and PWM on pins 9 and 10. You can't do both. PWM on pins 9 and 10 uses the same timer as the servo library.

As it states on the Servo library web page:

  The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.


USB detect on Arduino DUE I want to know when something is connected to USB port by blinking an LED.

I suppose have to check PB10 UOTGVBOF, but how to do this ?

What I'm going to say is probably not the most efficient way to do it, but it should work: if your DUE is used as gadget and you wnat to detect the presence of a master, connect a GPIO to the +Vcc line of the usb port and either poll or program an edge triggered interrupt to detect when the line goes high.


CRC16 calculation for MODBUS RTU I am trying to communicate an industrial type counter using Modbus.
I have to calculate CRC16 value as two byte for send it.
I previously googled for few Arduino libraries and I get a same function as below. But, I couldn't understand the function well.

I need CRC as two bytes and as input I have 6 bytes.

Can someone explain the below function and what are the argument I need to provide.

uint16_t crc16_update(uint16_t crc, uint8_t a)
  {
    int i;
    crc ^= a;
    for (i = 0; i < 8; ++i)
  {
    if (crc & 1)crc = (crc >> 1) ^ 0xA001;
    else crc = (crc >> 1);
  }
    return crc;
 }

CRC-16 is just a term that describes an algorithm. There are multiple implementations possible. They not only differ by the used polynomial but also by the initial value.

Your particular implementation uses the IBM CRC-16 polynomial.

Other Possible polynomials are for example:
x^16 + x^15 + x^2 + 1 (IBM)
x^16 + x^12 + x^5 + 1 (CCITT)
x^16 + x^10 + x^8 + x^7 + x^3 + 1 (DECT)
(there are more on wikipedia)

Actually you can take any primitive polynomial. (UPDATE: Not using a primitive polynomial will reduce the output space but is still going to work.) So you will have to find out which one you have to use and then know the initial value.

Assume you are right with the IBM polynomial then assume the initial value is 0xffff. You use the function as follows:

uint16_t crc = 0xffff; // the initial value
uint8_t a[]; // your data
crc = crc16_update(crc, a[0]);
crc = crc16_update(crc, a[1]);
…
crc = crc16_update(crc, a[n]);
// done
// crc now holds the value of the data stored in a


Can I force Arduino not to be powered by USB? I'm building a 3D printer and I'm using an ATmega2560 + RAMPS board.

The whole thing is powered by an ATX PSU (12v for motors and stuff, 5v for the Arduino), but when I plug in my USB cable, I can't shut the printer down, as it switches over to USB power.

Is there a way to make the Arduino never use the USB power, only the external power source?

Thanks!

The best way of doing this, if you want your USB connection to still work, is to remove the P-channel MOSFET T1 from the board.

You can't just disconnect the power from the USB port since that power connection goes directly to UVCC on the ATMega16U2 chip. That is used to power the internal USB peripheral (it goes to a 3.3V regulator inside the chip) and without it the USB interface won't have power.

The USB power is connected to the main 5V rail through that transistor, so if you remove that transistor the 5V from the USB remains connected to the ATMega16U2, but is no longer connected to the rest of the circuit.


How to rotate a servo motor on a specific angle? I am trying to rotate a top on a specific angle after every 1 second. For example: 1 degree/second. I have two question:

Can I achieve this with servo motors?
If not, what motor should I use?

I know this question has very little description. I am mainly a programming guy. I don't much about arduino stuff. It's actually a hobby project for me.

Thanks in advance.

The kind people who have written the Arduino libraries include software drivers for servo control.  These drivers abstract the hardware from the programmer of the sketch software (the sketch is application software you write in C or C++).  It is unnecessary to understand the driver in detail.  However the servo driver software (likely written in C++) can been examined here.

To move a normal servo to a particular position, make a call to the Arduino Servo Driver using the function write(angle) passing an angle value from 0 to 180.  The value is an approximation of degrees and the value type is of type integer.

In the above links you will find this example of sweeping the servo motor across its range:

/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

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

Proceed to that page for more details including a schmatic (diagram) of how the servo is connected to an Arduino Uno board.


Arduino 16x2 LCD Black Boxes I hooked up a 16x2 Arduino compatible LCD yesterday and made sure all the connections were according to the program and the schematics provided all over the web. My contrast is adjusted perfectly but the problem is that there are black boxes on the top line while the lower one is empty.

I know this question has been asked many times but no one has answered the question other than saying, "Check your contrast pin". I'm using the default sample code provided in the Arduino IDE.
HELP!

Regards.

I have done some Googling across the web and it turns out that this can be caused by a couple of things:

Incorrect wiring.
Wiring of LCD backwards (ie 1 to 16 and 16 to 1).
Faulty wiring (ie broken cables & dry joints).
Incorrect initialization of the LCD.
Buggy software.
Damaged screen.

The LCD screen that you have is a based on the Hitachi HD44780 chipset. It is the most common interface for text-based LCDs. It can be identified by the 16-pin interface. I2C is the next most common interface and is distinguishable as it has a 4-pin (sometimes 5-pin) interface.

Lets assume that your screen isn't damaged. From the details in your question, it sounds like your contrast is working just fine. The list above can be shrunk to just 2 things: bad wiring and/or bad code. Lets eliminate both of those by using known working software and known working circuit.

Arduino has an LCD library with example programs. Details for this library, including a wiring diagram, can be found over at the Arduino site in the Reference section. I use these example sketches to test my wiring connections before I write my own program. I recommend using the Autoscroll example.

Schematic:

These diagrams are from the Arduino Autoscroll page. I highly suggest that you read this page thoroughly.

The code can be easily uploaded into your Arduino, through the IDE, by going into File > Examples > LiquidCrystal > AutoScroll, then Sketch > Upload.
You should see the sketch print the characters 0 to 9 on the top line (with autoscroll off), then moves the cursor to the bottom right (turns autoscroll on,) and prints the characters 0 to 9 on the bottom line, but as it prints each character the display should move one to the left.

If you get this example program to work then you know that you have a working LCD and also that your wiring is OK as well.


How to know which Arduino to choose: Nano, Micro or Pro Micro? I'm puzzled at the moment with which one to choose.

Form-factor plays a significant role in my project, so I prefer the smaller boards mentioned in the title to fuller boards like the UNO, MEGA, etc.
I have an RC522 RFID read/write module and would like to use it without having to deal with level switching, as the RFID module requires 3.3V.

What can you advise?

Thank you in advance!

I'm currently using inexpensive Arduino Nano boards running GRBL for a couple of little CNC machines.  The version I have uses an ATmega328 running at 5V and they work very well.

They may be available with 3.3V regulator instead of 5V - I don't know and I preferred to have 5V anyway.

The nano boards that I have look to be a complete Arduino: one side of the board has the ATmega and voltage regulator, the other side of the board has the USB interface chip and some LEDs.

You can purchase Chinese-made nano boards very inexpensively.  Look on eBay for sellers offering free International shipping.


Making my own libraries Does anyone know of a site or book where you can learn how to create, or for first reed, libraries. Because I think the libraries I use are sometimes unnecessary complicated, or have similar features, for example Wire and OneWire.

I think, these make my sketch unnecessary big, when I need both of them.

Arduino has a library tutorial here: http://www.arduino.cc/en/Hacking/LibraryTutorial

and a formal specification here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

these explain the specifics to making arduino libraries, like the propeties files, the keywords file, and the directory structure. Most of that is unnecessary though.

Anyway, there are not many differences between the actual code in an arduino library and the normal code you write for arduino sktech. The only major ones being that

The arduino preprocessor doesn't generate function declarations - you have to make your own header file
You can't use setup or loop

Other than that, its just normal c++ code that exposes a particular interface and provides an implementation. If you want the library to work well for a lot of users, you will need to put in the extra work to make it run on all the different arduino hardware variants.

Making libraries for c++ often involves creating .a, .so, .dll etc. files of compiled code that new programs can link against, but arduino compiles everything from source for every sketch so you don't need to worry about that here.


ATtiny85 (Digispark) with 433mhz RF transmitter not working I have the following components:

ATtiny85 Digispark
433mhz Mini Low Power RF Transmitter

I got a communication flow transmit/receive working between two Wemos D1 and like to outsource the transmitting part now to a ATtiny85. I used the same code as for the Wemos:

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  pinMode(1, OUTPUT);
  mySwitch.enableTransmit(2);
}

void loop() {
    mySwitch.send("000110110001010100010001");
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
}

But the serial monitor for the Wemos does not receive any communication. I went so far that I built up the communication between the two Wemos again and connected only the data pin of the transmitter to the ATtiny85 in order to exclude any voltage problems (ATtiny gets 5V, transmitter likes <3.6V).

Now I am out of ideas. How can I debug the problem or what else can I try?

Requested setup:

I got it to work. The last comment of @Maximilian Gerhardt about I/O output got me thinking and I read up on it. So if I use 5V to power the ATtiny the I/O output voltage representation for 1 and 0 are significantly higher then with 3.3V. So now I underclocked the ATtiny to 8Mhz in order to use a 3.3V power supply. This way the I/O output matches the transmitters expectations. Now the communication is working.

Thanks for your help Max!


Circumventing overflow error by pushing data into computer? It seems in certain applications, for example signal processing, Arduino and other micro-controllers in general run into the overflow error when they're trying to store even moderate amounts of data. It would seem the obvious answer would be to simply take this data, push it onto the computer, and deal with it there instead, where you have much more available computing power. Is this possible with Arduino, or am I missing something that makes it not feasible?

One of the "features" of most microcontrollers/microprocessors is that they don't have a whole heap of RAM - this keeps costs down, and lets the manufacturers keep everything on one chip (unlike your PC).

However to "push" data to somewhere that can process it, you need to have a fast communications channel. SPI is quite fast, but you don't generally talk to PCs using SPI. Serial communication is slower, but if it gets converted into a USB interface (such as on a Uno) you can get respectable speeds talking to a PC. Something like 115200 baud is usually reliable, which lets you transmit 11520 bytes per second.

However it depends on what you want to send (ie. how many bytes), how you are going to indicate where one piece of data ends and the next one starts, maybe allow for error detection or correction, and so on.

Say, for example, it takes 5 bytes to send one piece of data (eg. 4 digits plus a delimiter). Now you are down to 11520/5 = 2304 pieces of data per second.

This may or may not be adequate for whatever-it-is you are trying to do.


Internet connectivity for the Arduino Due using AtmelStudio? What hardware and software solutions work and what are the tradeoffs for connecting an Arduino Due to the internet?  I gather the ethernet hardware is much cheaper than WiFi hardware (€29 versus €69).  In either case (wired or wireless), what software stacks and drivers work under AtmelStudio?

Well, your best bet is to import the arduino libraries in your Atmel Studio project. Then you'll be able to use existing code to connect to the "traditional" Ethernet Shield using SPI.

Though, the Sam 3X features an hardware ethernet that is not wired, unlike the MBed LPC1768… Sadly that's the ethernet PHY component you saw, but won't be able to actually use…


Advice for lower power clock type project Arduino newbie here! I'm a programmer but my hardware knowledge is ... slim.

I'd like to build a clock type wake up timer for my daughter, using an Arduino type board. Probably overkill, but it's practice for me, not just the end result! The idea is that is sleeps all night, then around say 4, gradually fade on a red LED. At 6, which is when she's allowed to come in, the red LED switches to a green, or some colourful sequence that tells her it's time. At a later time, maybe 7/8, it goes back to sleep to conserve power.

I have an Arduino Uno, but looks like I'll also need an RTC, and I've read that the sleep power consumption is ~40mA, which on batteries is what? A day or two max?

So I'm thinking I can't do this with a Uno.

So, my question is, are there any very low power Arduino compatible boards with built in RTCs that I can use for this project that will get me up and running as quickly as if I was using the Uno?

I will make my comment an answer:
Try one of Arduino supported RTC's boards. The most popular (and simple) are: DS1302, DS1307, PCF8563, and - very nice, precise DS3231 (my fav). Hook any of them up to your Arduino, add some (readily available) libraries, tweak a little and voila. The RTC will work from coin battery (or high capacity capacitor called supercapacitor, like this one)

Most (if not all) of mentioned RTC have 'alarm' function: you can set up your system to wake up your Arduino from sleep (sleep state to save battery) and gradually light up the LED.

To limit current of Arduino try removing LED, or - better - try to use Arduino Pro Mini. To modify it for better power saving see here

EDIT:
There are some other low-power boards:
Moteino
Rocket Scream Mini Ultra
JeeLink

Also, (as mentioned in one of comments) you can try one of ESP8266 and push it to one of many sleep modes. Try this link.


RS-232 is a protocol or a cable? RS-485 and RS-232 are a type of communication protocol or a type and cable?

I studying these serial communication protocols and each place refers to the RS-232 / RS-485 in different ways. Some articles mention that it is a cable, the other a protocol, so I was in doubt.

RS-232 etc mean different things in different contexts.  More specifically it is called TIA/EIA-232.

It refers to both the electrical characteristics of an NRZ signalling system, and at the same time it refers to the packet format for the transmission of data through such a system.

It also refers to the connectors that are used with such a system and, by extension, the cables that have those connectors on them.

  The standard defines the electrical characteristics and timing of signals, the meaning of signals, and the physical size and pinout of connectors. The current version of the standard is TIA-232-F Interface Between Data Terminal Equipment and Data Circuit-Terminating Equipment Employing Serial Binary Data Interchange, issued in 1997.

RS-485, or TIA/EIA-485, in contrast only specifies the electrical characteristics and not the data that is sent down the line. It doesn't specify any connectors to use, nor what format the data should take. For instance you can use RS-232 formatted packets, or you could use a MODBUS-RTU format that uses completely different packets. It only refers to the drivers and voltages used.

  TIA-485-A, also known as ANSI/TIA/EIA-485, TIA/EIA-485, EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems.


Powering Arduino with 110v and controlling relay I've found a lot of tutorials about how to use an Arduino to control power supplies to lamps and things like that using a relay. However, I also need to power the Arduino with the same power that is going through the relay.

In other words, I'd like to be able to plug my device into the wall. The device would use the 110VAC to power the Arduino. My device would also have some outlets that I could plug something into. The Arduino would be connected to a relay and would decide when to enable electricity to the outlet. The important part being that I would like everything to be on one power source.

Do I need to have a step down converter to transform the power, in addition to the relay? Is there some sort of break out board that has both of these functionalities in one board? What is the best way to do this?

In these cases where power must come from mains, my preferred solution is to buy a cheap phone charger+usb cable from ebay. They are sealed and safer than do-it-yourself solutions. The power adapter is barely larger than a normal plug for mains.

If you absolutely need to reach the arduino with only one cable, you can still use the solution i gave, only use a power cord to reach the contraption, then use a socket expander for mains and very short usb cable.


unable to read RS232 output on Arduino mega with MAX232 shield I am trying to read data from an RS232 equipped sensor using a serial monitor connected to an Arduino Mega with RS-232 shield but I do not receive any data.

I am unable to detect the exact cause of the problem, as it only occurs when combining sensor and RS232shield/Arduino, while communication works as expected when testing them separately

What works:

Connecting the sensor to a computer with a RS232-USB converter cable.
Passing data from the computer through the USB-RS232 converter cable to RS232 shield and back through Arduino USB output.
Connecting the RS232-pin 2 to port 10 using {SoftwareSerial} library with inverted logic.

What does not work:

Passing data from the sensor to the computer via the MAX232 and Arduino.

The setup:

Arduino Mega 2560
Seeed RS232 shield (MAX232 based)
Sensor with RS232 output (57600 8N1)

I have connected the RS232 output of the sensor to the shield using an M-M gender changer. The shield and Arduino are connected with three wires: GND-GND , 5V-5V, 232_TX-RX1), and the Arduino connects to a Macbook via USB. The serial monitor on the computer is set to 56700 baud.

I use the following sketch to transfer data from the RS232 shield to Serial:

void setup()
{
// Open serial communications at 5700 baud
    Serial.begin(57600);
    Serial1.begin(57600);

// Check whether Serial1 is active
if (Serial1.available())
     while (!Serial1) {
        ;
    }
    Serial.println("Serial 1 is active");
}

void loop()
{
    if (Serial1.available()){
    Serial.write(Serial1.read());
    }

}

I have solved the above and will share the answer as it may be of help to others:

As the Tx indicator LED on the RS232 shield would not light up when connected to the sensor, I checked the voltage difference between pin 2 (Tx) and pin 5 (GND) of the RS232 connector. This turned out to be only 5V, indicating that the protocol used is TTL-RS232 rather than 'true' RS232.

Due to the low voltage, I have connected the RS232 Tx and GND pins directly to the Arduino. With Tx connected to digital port 10, I used the SoftwareSerial library with logic inversion to read the data: SoftwareSerial mySerial(10, 11, 1).

This works!


5V pin out, 8 pins and micropython/circuitpython support: does such a board exist? For a project, I am looking for a board to connect eight different neopixel-strips to, on eight different data pins. Because of the great length between the board and the first pixels of these strips, I'd like to have a board that operates on 5V instead of 3.3V. Then, the software that I have written to manage the LEDs is made in (micro)python. Finally, for simplicity's sake, I'd like to run this complete project on a single board without too many external components.
So, I have found 5V boards with enough pins, like the Arduino Mega. I have also found boards with enough pins and support for micropython or circuitpython, like the ESP32 or Arduino Zero.
However, I haven't quite found a board that matches all my requirements. The Arduino Mega doesn't support Python (or does it?) and the ESP32 and Arduino Zero operate at 3.3V, not 5V.
Of course, an ESP32 with a level shifter (as shown on https://github.com/Aircoookie/WLED/wiki) would work, but is there perhaps a board out there that fits all my requirements our of the box?
Edit: It seems I misunderstood some things about the hardware - sorry, I'm a software guy, not really a hardware guy :-) I fixed the question above as not to confuse future readers.

Both your "requirements" for the board are non-requirements.

You do not need PWM pins to drive Neopixel strips. The Neopixel uses its own custom protocol that has nothing at all to do with PWM.
Your board only communicates with the first Neopixel. That one then communicates with the second, which then communicates with the third, etc. The length of the strip is completely irrelevant to what voltage you might want to drive it with.

You only care about having enough general IO pins and if the IO voltage is suitable to communicate with one Neopixel.
According to the WS2812B datasheet VIH is 0.7Vdd, which if you are powering the strips from 5V means 0.7 * 5 = 3.5V. However I think that is an overestimation and they are erring on the side of caution there, since I regularly drive WS2812B strips from a 3.3V microcontroller with no problems whatsoever (after all it's only 0.2V difference).
So just use your favourite 3.3V microcontroller that can run micropython and, if you really want to, drop the power supply voltage to the strips a fraction with a diode.


Trying to read from AD5934 using Arduino on I2C I'm trying to read a block of bytes from an AD5934 Impedance converter (PDF) using I2C.

This is my code so far

Preamble:

#define AD5934_Address                    0xD
#define AD5934_Start_Frequency            0x82
#define AD5934_Block_Read                 0b10100001
#define AD5934_Address_Pointer            0b10110000

Loop:

void loop() {
  readAD5934(AD5934_Start_Frequency, test, 3);
}

Read Function:

byte readAD5934 (int address, long int  data, int len) {
  byte err = 0, counter;

  if (len > 32)
    return 0xFF;

  else if (len > 1) {
    // Part ONE
    Wire.beginTransmission(AD5934_Address);
    Wire.write((byte) AD5934_Address_Pointer);
    Wire.write((byte) address);

    err = Wire.endTransmission();

    // Part TWO
    Wire.beginTransmission(AD5934_Address);
    Wire.write((byte) AD5934_Block_Read);
    Wire.write(len);

    // Part THREE
    Wire.requestFrom(AD5934_Address, len);
    StartHigh = Wire.read();
    StartMed = Wire.read();
    StartLow = Wire.read();
    err = Wire.endTransmission();
  }
return err;
}

For some reason, the Arduino tries to read the three bytes before Part TWO is executed.

I'm aware that I'm ending the I2C transmission after the requestFrom. The datasheet for AD5934 describes how to read a block of bytes on page 26. It does not show a STOP CONDITION before the end.

The oscilloscope shows

START 0001101 WRITE ACK 10110000 ACK 10000010 ACK STOP START 0001101 READ ACK 00000001 ACK 11000111 ACK 11111111 NACK STOP START 0001101 WRITE ACK 10100001 ACK 00000011 ACK STOP

Short:
S 0x0D W A 0xB0 A 0x82 A P S 0x0D R A 0x01 0xC7 0xFF NA P S 0x0D W A 0xA1 A 0x03 A P

The highlighted part (requestFrom and three Wire.read()) should be at the end.

I've spent a long time trying to figure this out, any help would be very much appreciated.

PS. Working on a Sparkfun Pro Micro 5V

I think you should re-see AD5934x datasheet.

To read data from AD5934, we have three ways:

read single byte
read block
using pointer command

If you want to read multi byte, you can refer to my way:

unsigned long GetRegisterValue(unsigned char regAddr, unsigned char len)
{
    unsigned long regValue = 0;
    unsigned char index;
    unsigned char wrData[2] = {0,0};
    unsigned char rdData[2] = {0,0};

    for (index = 0; index < len; index++)
    {
        wrData[0] = 0xB0; //assign pointer cmd
        wrData[1] = regAddr + index;
        I2C_Write(AD5934_ADDR, wrData, 2);
        rdData[0] = 0xff;
        I2C_Read(AD5934_ADDR, rdData, 1);
        regValue <<= 8;
        regValue += rdData[0];
    }

    return regValue;
}


Creating a file in an SD card I have an Arduino Mega connected to an SD card reader (Catalex branded), that at least detects the card as it displays the info of the card. But when I try to create a file, it does not create it. I am using the following code:

if (SD.exists("data.txt")) {
  Serial.println("data.txt exists.");
} else {
  Serial.println("data.txt doesn't exist.");
}
File root=SD.open("data.txt", FILE_WRITE); //open of the File for writting
if (SD.exists("data.txt")) {
  Serial.println("data.txt exists.");
} else {
  Serial.println("data.txt doesn't exist.");
}

I also tried with this code:

File root2 = SD.open("file.txt", O_RDWR | O_APPEND);
    if (!root2) {
       // It failed, so try and make a new file.
        root2 = SD.open("file.txt", O_RDWR | O_CREAT);
        if (!root2) {
          // It failed too, so give up.
        Serial.println("Failed to open file.txt");
         }
    }

[Update]

I also tried with this easier code and it does not work either:

#include <SD.h>

const int chipSelect = 10;
Sd2Card card;

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  File myFile = SD.open("Data.txt", FILE_WRITE);
  if (myFile) {
    for (int i = 0; i < 101; i++) {
      myFile.print(i);
      myFile.print(" multiplied by two is ");
      myFile.println(i * 2, DEC);
    }
    Serial.println("Finished");
    myFile.close();
  } else {
    Serial.println("Error opening Data.txt");
  }
  //do nothing else
  do { } while(1);
}

// open a new file and immediately close it:

Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();

This is what you missed (I guess..).
Please see the link and check the steps followed:
https://www.arduino.cc/en/Tutorial/Files


Did I damage my Arduino? I was trying to build a Bluetooth controlled car. I was near completing it but what I did wrong was that I connected the 5 V output of L298 motor driver to 5V pin of Arduino where I was supposed to connect it in Vin. My Arduino got heated for a couple of seconds. Knowing that I immediately disconnected. Now serial port doesn't work in my Arduino. The serial port option turned gray. I even tried replacing the ATmega IC but got the same result. What might have happened?

Yes, it sounds like you fried something.

I can't quite make out what it was you did from your description (I'm sure it makes perfect sense to you with the hardware in front of you), but the symptoms do sound somewhat fatal.

What actually happened depends very much on the Arduino you have - if it's a genuine one or a cheap Chinese clone. Either way the USB circuitry seems to not be functioning. Whether that is because the USB chip (varies depending on if it's a real Arduino [ATMega16U2] or a clone [CH340G]) or one of the voltage regulators is unknown.

You should power the board up normally and test the voltages at the 5V and 3.3V pins. Also if a component is still getting hot you should note which component it is, and that will give more of a clue as to what went wrong.


circuit breaker/fuse necessary for IoT home monitor? In most 12v CCTV power supplies, each power cable is behind a glass fuse.  I haven't seen fuses or circuit breakers used when distributing 5v power used in IoT projects.  Is there a reason overcurrent protection is not needed in these projects?
edit:
I'm thinking specifically about fire safety.  e.g. the risk of a short circuit overheating 22awg wire run through the house?

Is there a reason overcurrent protection is not needed in these projects?

You're comparing apples and oranges.
The two systems are completely different and have different concerns.
Case in point:

You want to burgle somewhere with CCTV installed. You can creep up on one camera unobserved.
You know a little about electronics and figure if you cut the feed to the camera you can short out the power and blow the whole system, thus letting you wander in unobserved.

But there's fuses on each feed, so all you do is disable the one camera and everything else is fine, catching you red handed.
Go directly to jail. Do not pass go. Do not collect £200.
Now... do you really care that much if all your home temperature sensors lose power because of a fault in one? Probably not. And the chances of there being a fault other than from human negligence is slim. Sure, you could add fuses, but why add the expense? It's really not needed for such a non-critical system.

edit: I'm thinking specifically about fire safety. e.g. the risk of a short circuit overheating 22awg wire run through the house?

22AWG wire has a resistance of about 53Ω per km. Say you have a loop of cable 20m long (10m there and 10m back again) and it shorted out at the far end. That's round about 1Ω.
At 5V you'd be drawing 5A of current.
If you have a really powerful power supply then it would try and supply that, and the wire would warm up - giving off about 25W of heat over the entire length. You might feel a bit of warmth from it.
Of course, most people would be using a smaller power supply than that for simple IoT things, so the power supply would just go "No. You're not having that!" and would die, or its internal fuse would blow. Or it would drop the voltage and get hot itself.
The chance of being able to start a fire from 5V over 22AWG from a normal power supply is pretty much zero. You're more likely going to start a fire from using a low quality power supply that itself melts and catches fire (i.e., a counterfeit Chinese phone charger).
With a very powerful power supply (tens of amps or more) and a short circuit close to the source (so low resistance) the wire will melt. Just that. It'll melt. Once melted there's no circuit, so nothing else happens. There's your fuse right there.
Once a wire has melted it doesn't continue to burn. And you don't get arcs at low voltages. It takes a lot of work to start a fire from low voltages. A lot of work and a lot of current.


Blank Serial Print AdaFruit BTLE I working on a prototype with an Arduino UNO and an AdaFruit Low Energy Blue tooth

I have an array of uint32_t that I am trying to send via blue tooth to a given device.  I don't think i can send the array so I was trying to send it as a comma separated string.

I can print out each individual index of that array just fine, but its completely blank when i try to make a comma separated String..  See code and comments below.

Ay Array:

uint32_t items[]= {0,3513728,7925384,0,0,0};

In My Loop:

String output = "";

for(int i = 0; i<6;  i++){

  BTLEserial.print(items[i]); // Prints as expected
  output += getStringForUI32_T(items[i]);
  output+=",";

 }
 BTLEserial.print(output); // prints BLANK

I imagine this has something to do with memory but I am at a complete loss.. Please help!

I'd probably do it directly like:

for(int i = 0; i<6;  i++) {
  BTLEserial.print(items[i]);
  BTLEserial.print(',');
}
BTLEserial.println();

But with the string I think it would be something like:

String output = "";

for(int i = 0; i<6;  i++) {
  output += getStringForUI32_T(items[i]);
  output+=",";
}
BTLEserial.println(output[0]);

But as someone else got it working using String on your adafruit thread maybe this is just barking up the wrong tree.