Sending Large Amounts of Serial Data So in the fields of robotics sometimes you need multiple boards and or computers linked together to share information or save statistical data. Currently I need to send a few different variables over a serial connection and was wondering what was the best way to go about doing such?

So far I've determined that sending structures would probably be the easier way to send data. Does anyone know of any other way that might be more efficient?

Please keep in mind that I will essentially be having to send the data for 4 motors, compressor, different temperatures, random things, and the 3 sections of the arm.

With my personal thoughts on Structs being the most efficient way to send many different variables I've constructed a library to help make it easier to send structs and variables over serial.  Source Code

In this library it makes sending through serial easily. I've used with with hardware and software serial. Usually this is used in conjunct with xbee's so I can wirelessly send the data to and from the robot.

When sending data it make it simple as it allows you to either send a variable or a struct (it doesn't care).

Here is an example of sending a simple char over the serial:

// Send the variable charVariable over the serial.
// To send the variable you need to pass an instance of the Serial to use,
// a reference to the variable to send, and the size of the variable being sent.
// If you would like you can specify 2 extra arguments at the end which change the
// default prefix and suffix character used when attempting to reconstruct the variable
// on the receiving end. If prefix and suffix character are specified they'll need to
// match on the receiving end otherwise data won't properly be sent across

char charVariable = 'c'; // Define the variable to be sent over the serial
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Example of sending a simple int over the serial:

int intVariable = 13496; // Define the int to be sent over the serial
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Example of sending a struct over serial:

// Define the struct to be sent over the serial
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct;
simpleStruct.charVariable = 'z'; // Set the charVariable in the struct to z

// Fill the intVariable array in the struct with numbers 0 through 6
for(int i=0; i<7; i++) {
  simpleStruct.intVariable[i] = i;
}

// Send the struct to the object xbeeSerial which is a software serial that was
// defined. Instead of using xbeeSerial you can use Serial which will imply the
// hardware serial, and on a Mega you can specify Serial, Serial1, Serial2, Serial3.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Send the same as above with a different prefix and suffix from the default values
// defined in StreamSend. When specifying when prefix and suffix character to send
// you need to make sure that on the receiving end they match otherwise the data
// won't be able to be read on the other end.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'u');

Receiving Examples:

Receiving a char that was send via Streamsend:

char charVariable; // Define the variable on where the data will be put

// Read the data from the Serial object an save it into charVariable once
// the data has been received
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable));

// Reconstruct the char coming from the Serial into charVariable that has a custom
// suffix of a and a prefix of z
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Receiving an int that was sent via StreamSend:

int intVariable; // Define the variable on where the data will be put

// Reconstruct the int from xbeeSerial into the variable intVariable
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Reconstruct the data into intVariable that was send with a custom prefix
// of j and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Receiving a Struct that was sent via StreamSend:

// Define the struct that the data will be put
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct; // Create a struct to store the data in

// Reconstruct the data from xbeeSerial into the object simpleStruct
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Reconstruct the data from xbeeSerial into the object simplestruct that has
// a prefix of 3 and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'p');

Once you read the data using StreamSend::receiveObject() you need to know if the data was GOOD, Not Found, or BAD.

Good = Successful

Not Found = No prefix character was found in the specified ostream

Bad = Somehow there was a prefix character found, but the data isn't intact. Usually it means there was no suffix character found or the data wasn't the correct size.

Testing Validity of Data:

// Once you call StreamSend::receiveObject() it returns a byte of the status of
// how things went. If you run that though some of the testing functions it'll
// let you know how the transaction went
if(StreamSend::isPacketGood(packetResults)) {
  //The Packet was Good
} else {
  //The Packet was Bad
}

if(StreamSend::isPacketCorrupt(packetResults)) {
  //The Packet was Corrupt
} else {
  //The Packet wasn't found or it was Good
}

if(StreamSend::isPacketNotFound(packetResults)) {
  //The Packet was not found after Max # of Tries
} else {
  //The Packet was Found, but can be corrupt
}

SteamSend Class:

#include "Arduino.h"

#ifndef STREAMSEND_H
#define STREAMSEND_H

#define PACKET_NOT_FOUND 0
#define BAD_PACKET 1
#define GOOD_PACKET 2

// Set the Max size of the Serial Buffer or the amount of data you want to send+2
// You need to add 2 to allow the prefix and suffix character space to send.
#define MAX_SIZE 64

class StreamSend {
  private:
    static int getWrapperSize() { return sizeof(char)*2; }
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar);
    static char _prefixChar; // Default value is s
    static char _suffixChar; // Default value is e
    static int _maxLoopsToWait;

  public:
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize);
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static boolean isPacketNotFound(const byte packetStatus);
    static boolean isPacketCorrupt(const byte packetStatus);
    static boolean isPacketGood(const byte packetStatus);

    static void setPrefixChar(const char value) { _prefixChar = value; }
    static void setSuffixChar(const char value) { _suffixChar = value; }
    static void setMaxLoopsToWait(const int value) { _maxLoopsToWait = value; }
    static const char getPrefixChar() { return _prefixChar; }
    static const char getSuffixChar() { return _suffixChar; }
    static const int getMaxLoopsToWait() { return _maxLoopsToWait; }

};

//Preset Some Default Variables
//Can be modified when seen fit
char StreamSend::_prefixChar = 's';   // Starting Character before sending any data across the Serial
char StreamSend::_suffixChar = 'e';   // Ending character after all the data is sent
int StreamSend::_maxLoopsToWait = -1; //Set to -1 for size of current Object and wrapper

/**
  * sendObject
  *
  * Converts the Object to bytes and sends it to the stream
  *
  * @param Stream to send data to
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize) {
  sendObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}

void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  if(MAX_SIZE >= objSize+getWrapperSize()) { //make sure the object isn't too large
    byte * b = (byte *) ptr; // Create a ptr array of the bytes to send
    ostream.write((byte)prefixChar); // Write the suffix character to signify the start of a stream

    // Loop through all the bytes being send and write them to the stream
    for(unsigned int i = 0; i<objSize; i++) {
      ostream.write(b[i]); // Write each byte to the stream
    }
    ostream.write((byte)suffixChar); // Write the prefix character to signify the end of a stream
  }
}

/**
  * receiveObject
  *
  * Gets the data from the stream and stores to supplied object
  *
  * @param Stream to read data from
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize) {
    return receiveObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  return receiveObject(ostream, ptr, objSize, 0, prefixChar, suffixChar);
}

byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar) {
  int maxLoops = (_maxLoopsToWait == -1) ? (objSize+getWrapperSize()) : _maxLoopsToWait;
  if(loopSize >= maxLoops) {
      return PACKET_NOT_FOUND;
  }
  if(ostream.available() >= (objSize+getWrapperSize())) { // Packet meets minimum size requirement
    if(ostream.read() != (byte)prefixChar) {
      // Prefix character is not found
      // Loop through the code again reading the next char
      return receiveObject(ostream, ptr, objSize, loopSize+1, prefixChar, suffixChar);
    }

    char data[objSize]; //Create a tmp char array of the data from Stream
    ostream.readBytes(data, objSize); //Read the # of bytes
    memcpy(ptr, data, objSize); //Copy the bytes into the struct

    if(ostream.read() != (byte)suffixChar) {
      //Suffix character is not found
      return BAD_PACKET;
    }
      return GOOD_PACKET;
  }
  return PACKET_NOT_FOUND; //Prefix character wasn't found so no packet detected
}

boolean StreamSend::isPacketNotFound(const byte packetStatus) {
    return (packetStatus == PACKET_NOT_FOUND);
}

boolean StreamSend::isPacketCorrupt(const byte packetStatus) {
    return (packetStatus == BAD_PACKET);
}

boolean StreamSend::isPacketGood(const byte packetStatus) {
    return (packetStatus == GOOD_PACKET);
}

#endif


How to use relay shield to control dc motor speed and direction? I tried l298n before but its output voltage wasn't high

so I use relay shield but  it seems that the car can only go forward or stop

Can I control the speed and direction of dc motors?

Using a mechanical relay to control the speed is not a good idea. But you can control the directions.

I prefer you to use Solid state relays (SSR) to do this. Arrange 4 SSR as Hbridge and Use PWM to control the speed.

refer this

or you can use the devices like this which has direction control as well.


How to connect a 2 cell LiPo batter to Arduino Motor Shield? I am trying to connect a 2 cell 7.4 volt LiPo battery into my motor shield. I am a beginner at robotics so I am not sure if I just connect the battery, via a connector of some sort, into the motor shield itself or do I use some 22 AWG wire and connect it via that way. Sorry if that sounds confusing.

From the Motor Shield page,

  External (non-USB) power can come either from an AC-to-DC adapter
  (wall-wart) or battery. The adapter can be connected by plugging a
  2.1mm center-positive plug into the Arduino's board power jack on which the motor shield is mounted or by connecting the wires that lead
  the power supply to the Vin and GND screw terminals, taking care to
  respect the polarities.

So they provide the screw terminals for a battery, you should be able to insert two wires from your battery/pack into the terminals. If your battery has a connector on it, you'll need to either cut it off or find an adapter.

Be extra careful: if you have exposed leads from your battery and they touch, it'll get extremely hot and possibly catch fire.


Arduino Sketch: NodeMCU compilation error Every time I try to compile a program written in Arduino IDE 1.8.5 for NodeMCU (LoLIN version v3), I get the following error:

Arduino: 1.8.5 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

C:\Users\sumeetpatil\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-ar: unable to rename 'C:\Users\SUMEET~1\AppData\Local\Temp\arduino_build_831529/arduino.ar'; reason: File exists

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I have tried reinstalling several times, but I just can't get ahead of this step.

Do a full uninstall of Arduino, then delete the Arduino folder and
  Arduino15 (back them up first if you have any sketches in there!!!!),
  as well as any Arduino folders under Temp. Make sure the folders and
  all contents are really gone, reboot and try again if not. Then, do a
  clean install of the IDE.

Cited from here.


door protector arduino program Please check the arduino program given below and help me to find out error.
The program is for following hardware.
GSM 800 module
Arduino Uno board
Limit switch(2)

We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.

We run this program & it run but it sends the massage repeatedly after some time.
Please help me to find out error..

my ARDUINO code is

const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;
bool i = true;
bool j = true;
bool k = true;
bool l = true;
int buttonState1 = 0;
int buttonState2 = 0;
void setup() {

  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void loop() {
  buttonState1 = digitalRead(Main);
  if (buttonState1 == HIGH && i == true ) {
    digitalWrite(Main_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Main Door is closed");
    Serial.write(0x1A);
    delay(5000);
    i = false;
    j = true;
  }
  else
  { if (buttonState1 == LOW && j == true )

    { digitalWrite(Main_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91---------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Main Door is open");
      Serial.write(0x1A);
      delay(5000);
      i = true;
      j = false;
    }
  }

  buttonState2 = digitalRead(Store);
  if (buttonState2 == HIGH && k == true) {

    digitalWrite(Store_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(5000);
    k = false;
    l = true;
  }
  else
  { if (buttonState2 == LOW && l == true)
    {
      digitalWrite(Store_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91------------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Store room is Open");
      Serial.write(0x1A);
      delay(5000);
      k = true;
      l = false;
    }
  }
}

I can't see any obvious flaws in the code other than the excessive use of delay. However you could make your code a lot cleaner which makes it easier to spot the errors.
The version below has the duplicate lines moved into a function and instead of using the poorly named i,j,k & l to track two states it uses two variables to do the same job. Finally things that don't need to be global have been moved to being local.

const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;

void setup() {
  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void sendMessage(char *text) {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print(text);
    Serial.write(0x1A);
    delay(5000);
}

void loop() {
  static int oldState1 = -1;
  static int oldState2 = -1;

  int buttonState1 = digitalRead(Main);
  if (buttonState1 != oldState1) {
    digitalWrite(Main_led, buttonState1);
    if (buttonState1 == HIGH)
      sendMessage("Main Door is closed");
    else
      sendMessage("Main Door is open");
    oldState1 = buttonState1;
  }

  int buttonState2 = digitalRead(Store);
  if (buttonState2 != oldState2) {
    digitalWrite(Store_led, buttonState2 );
    if (buttonState2 == HIGH)
      sendMessage("Store room is closed");
    else
      sendMessage("Store room is open");
    oldState2 = buttonState2;
  }
}


How to show the º character in a LCD? I have a 16x2 LCD and I want to show a temperature: 23 ºC.

But the º symbol is not properly shown. It shows a strange character instead of the º symbol .

It depends on the exact model of LCD you are using. Or more exactly, on the Dot Matrix Liquid Crystal Display Controller/Driver, like the Hitachi HD44780U that is used in many 16x2 LCD.

For that driver, you have a table of native chars, like this:

In this table, the char "°" is at col 0b1101, row 1111, (0xDF, or 223). But, you have to cast that value to a char before displaying, otherwise you will get the value (223), not the symbol.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.backlight();
  lcd.print("temp 27");
  lcd.print((char) 223);
  lcd.print(" ");
  lcd.print(223);

}

void loop()
{
}


CNY70 from 3.3v instead of 5v? I would like to use a CNY70 with arduino that is not 5v but 3.3v powered. On the web there most tutorials use 5v and 200 + 10k resistors (e.g. here and here). So as far as I understand for 3.3v I would have to use lower ones.

Can someone explain how those 200 or 10k were calculated? How could I use CNY70 with 3.3v (if it's possible at all) ?

The CNY70 is just an IR LED and IR Phototransistor.  You can treat the IR LED (emitter) portion of it just like any LED and size the resistor appropriately.

The receiver is just a phototransistor which can operate at anything from about 1V up to 32V with no need to adjust anything.  The resistor used there is merely a pullup resistor.  You can think of the receiver as a button. When enough IR light falls on it it turns "on".

On an Arduino you could even get away without the pullup resistor and use an input in INPUT_PULLUP mode.


Using LM70 temperature sensor with Arduino I am trying to sense the temperature using the LM70 temperature sensor with an Arduino Mega. As you can see in the Datasheet, it uses the SPI protocol. I have made the following connections (VSSOP-8 Package):

SI/O pin --> Pin 50 Arduino Mega.
SC pin --> Pin 52 Arduino Mega.
CS pin --> Pin 53 Arduino Mega.
V+ pin --> 3.3V Arduino Mega.
GND pin --> GND Arduino Mega.

My code does not work (it does not print the right temperature), and I think it can be for two reasons:

I am not reading correctly the information from the sensor. It sends 16 bits, from which the 11 first bits store the data for the temperature.
I am not calculating the temperature in the right way.

This is my code:
// the sensor communicates using SPI, so include the library:
#include <SPI.h>

void setup() {
  pinMode(51,OUTPUT); //MOSI
  pinMode(50,INPUT); //MISO
  pinMode(52,OUTPUT); //CLOCK PIN
  digitalWrite(53,HIGH); //slave select stays high. When we set this to low, the sensor will start to send data.
  SPI.begin();
  Serial.begin(9600);

  //time to set up
  delay(500);
}

void loop() {
    //enable Slave
    digitalWrite(A0,LOW); //Enable communication with slave
    delay(500); //wait for conversion

    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;
    Serial.println(temperature); //display temperature on serial monitor

    //disable Slave
    digitalWrite(53,HIGH); //set to High again
}

Please, if you see something wrong in my code, let me know.
Thank you in advance.

There are several things that are not doing correctly. This is not a complete answer but to provide you some directions on how to get it right.

A0 is pin 54, it is not SS which is pin 53;

On how to use the SPI library properly, I would suggest that you read my blog on SPI, it will also help you to get the data out of data sheet that you need for SPI programming. Based on the timing diagram on the data sheet, you will need to configure the SPI as SPI_MODE2;

LM70 SI/O pin is used as both MOSI and MISO, you will need to connect MOSI to SI/O via a 10k resistor, and connect SI/O direct to MISO, this information is available in the data sheet;

LM70's temperature data is in Two's complement format, To convert it, it needs a little bit work. It is then need to shift down/right using bitshift operator by 5 bits to get ride of the first 5-bits, before finally multiply by 0.25C as per data sheet.

int value = 0x4b1f;  //value from SPI, temp = 125 degree C
int mask = 0x8000;   // mask for MSB
int temp = (-(value & mask) + (value & ~mask)) >> 5;
Serial.print("Temp");
Serial.println(temp*.25);

Read all links that I provided to understand the subjects and give it a try. Good luck!


Serial.print and char[] & null I don't write a lot of C, so I'm always discovering things I only partly understand in the Arduino variety. One of these is how Serial.print handles char[].

Does Serial.print always require a null terminator? In the case of (say) Serial.print(88, DEC); is a null implied?

What happens in the following cases?

char buff[3] = "ABC"; // warned because no room for a null
Serial.print(buff);   // will absence of a null cause overrun?

char buff[4] = "ABC"; // now there's a null
Serial.print(buff);   // will the null character be sent too?

Any references appreciated.

The "Serial" is a object/class and that makes it possible to have more than one function for Serial.print(). According to the type of the parameter the proper Serial.print() is selected.

This is the include file for the Serial.print(): Print.h
And these are the possibilities:

size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

The reference for Serial.print() is short, but it explains pretty well that those different parameters are possible.

Your Serial.print(88, DEC); does not use a string of text, it uses the integer number 88.

As soon as a string of text is used, it should be zero-terminated.
The line char buff[3] = "ABC"; is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.


Switch case does not work after booting system int value1;
int value2;
int runs1 = 0;
int runs2 = 0;

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2);
int inPin = 6;
int val = 0;
int push_count = 0;
int buttonState = 0;
unsigned long previousMillis = 0;
const long interval = 1800000;
int currentTime;

void setup() {
  Serial.begin(9600);
  lcd.begin();
  pinMode(inPin, INPUT);
}

void loop() {

  unsigned long currentMillis = millis();
  currentTime = 30-(currentMillis - previousMillis)/60000;
  if (currentMillis - previousMillis >= interval || previousMillis == 0) {
    previousMillis = currentMillis;

  measure();
  }

  buttons();
}

void measure() {
 value1=300;
 value2=300;

  if (value1 <= 650)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("1");
   delay(2000);

}
else
{
  lcd.clear();
  lcd.print("Pump 1 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs1++; // increment the number of times pump 1 has run

}

  if (value2 <= 550)
{
   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");
}
else
{
  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");
}
  }

void buttons() {
  val = digitalRead(inPin);

  if (val != buttonState && val == HIGH){
    push_count++;
  }
      else {
      // do nothing
    }

  buttonState = val;
  switch (push_count) {
    case 0:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 1 reads");
      lcd.setCursor(0,1);
      lcd.print(value1);
      delay(20);
      Serial. print("Case 0");
      push_count++;
      break;
    case 1:
      Serial. print("Case 1");
      break;
    case 2:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Sensor 2 reads");
      lcd.setCursor(0,1);
      lcd.print(value2);
      delay(10);
      push_count++;
      break;
    case 3:
      break;
    case 4:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 1 ran");
      lcd.setCursor(0,1);
      lcd.print(runs1);
      lcd.setCursor(5,1);
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 5:
      break;
    case 6:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Pump 2 ran");
      lcd.setCursor(0,1);
      lcd.print(runs2);
      lcd.setCursor(5,1);;
      lcd.print(" times");
      delay(10);
      push_count++;
      break;
    case 7:
      break;
    case 8:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Next cycle in");
      lcd.setCursor(0,1);
      lcd.print(currentTime);
      lcd.setCursor(5,1);
      lcd.print(" Minutes");
      delay(10);
      push_count++;
      break;
    case 9:
      break;
    default:
      push_count=0;
  }
}

When I boot the system (standalone atmega328p circuit) the connected LCD either shows

  Plant

  2

originating from

   lcd.setCursor(8,0);
   lcd.print("Plant");
   lcd.setCursor(10,1);
   lcd.print("2");
   delay(2000);
   Serial. print("Pump 2 OK");

or in my real code (where value1 and value2 are actually measured)

  Pump 2 turned ON

  Water for 40 sec

originating from

  lcd.clear();
  lcd.print("Pump 2 turned ON");
  lcd.setCursor(0,1);
  lcd.print("Water for 40 sec");
  runs2++; // increment the number of times pump 2 has run
  Serial. print("Pump 2");

after I use the button to cycle through all the cases everything works fine. On the next button press I get to case 2 (-> 3).
After a full cycle case 0 (-> 1) gets displayed correctly.

The above MCVE runs perfectly on my breadboard setup, but not in the real setup.

Here's the schematic of the real setup.

So somewhere in the real setup has to be something that my code does not handle properly. The breadboard setup is minimal, just all GND and VCC connections, a 16 Mhz crystal with 22 pF caps.

Personally I don't like the way you handle the "state machine", and I'd implement it in what I perceive is a more robust way (I may be wrong, though).

Moreover if you have a button please add a debounce; I usually do this with the Bounce2 library (or alternatives I code which are modified versions of that library). So... Let's change the things in the way I prefer.

// Include the library
#include <Bounce2.h>

// declare a bounce object
Bounce buttonDebounce = Bounce();

//in the setup:
pinMode(IN_PIN, INPUT); // or INPUT_PULLUP?
buttonDebounce.attach(IN_PIN);
buttonDebounce.interval(5);

//in the loop:
buttonDebounce.update();

Then in the loop you can use the buttonDebounce.rose() function or buttonDebounce.fell() to detect the button presses.

Now, for the state machine. You have four meaningful states (let's call them DISPLAY_1 to 4). It's better to give them more meaningful names. And let's add an invalid state. I usually prefer to use const bytes to force the size rather than enums or defines, but.. whatever ;)

So outside loop or setup declare the values and the state variable:

const byte SM_ErrorState = 0;
const byte SM_Display_1 = 1;
const byte SM_Display_2 = 2;
const byte SM_Display_3 = 3;
const byte SM_Display_4 = 4;
const byte SM_Display_5 = 5;
byte SM_currentState;

Now, the function buttons can be implemented in the classical way I learned to implement state machines, which is first make a switch case to test whether you have to advance, then advance to the next state if necessary and perform the entry action.

void buttons()
{
    buttonDebounce.update();

    nextState = SM_currentState;

    // Check if a new state is requested
    switch (SM_currentState)
    {
    case SM_Display_1:
        if (buttonDebounce.rose())
            nextState = SM_Display_2;
        break;
    case SM_Display_2:
        if (buttonDebounce.rose())
            nextState = SM_Display_3;
        break;
    case SM_Display_3:
        if (buttonDebounce.rose())
            nextState = SM_Display_4;
        break;
    case SM_Display_4:
        if (buttonDebounce.rose())
            nextState = SM_Display_5;
        break;
    case SM_Display_5:
        if (buttonDebounce.rose())
            nextState = SM_Display_1;
        break;
    default:
        nextState = SM_Display_1;
        break;
    }

    // If an advancement is requested, advance and then perform the entry action
    if (nextState != SM_currentState)
    {
        SM_currentState = nextState;
        switch (SM_currentState)
        {
        case SM_Display_1:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 1 reads");
            lcd.setCursor(0,1);
            lcd.print(value1);
            delay(20);
            Serial. print("Case 0");
            break;
        case SM_Display_2:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 2 reads");
            lcd.setCursor(0,1);
            lcd.print(value2);
            delay(10);
            break;
        case SM_Display_3:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 1 ran");
            lcd.setCursor(0,1);
            lcd.setCursor(5,1);
            lcd.print(runs1);
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_4:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 2 ran");
            lcd.setCursor(0,1);
            lcd.print(runs2);
            lcd.setCursor(5,1);;
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_5:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Next cycle in");
            lcd.setCursor(0,1);
            lcd.print(currentTime);
            lcd.setCursor(5,1);
            lcd.print(" Minutes");
            delay(10);
            break;
        default:
            break;
        }
    }
}

Now, the initialization. Remember that I told you to add an error state? This way you can force a state change on initialization by setting the variable to the SM_ErrorState value.

Then, the millis management in the loop. I'd avoid the particular case of the variable equal to 0 to trigger an immediate execution, since this will lead to errors later. Then I also prefer to sum the interval, to avoid having a drift. So I changed your way to another one. I also changed some code for better readability (for instance, letting the "timer" reset every minute rather than every 30 minutes, and changing the defines accordingly).

Here is my complete code; I left out the measure function since it does not impact the other code.

Let me know if this solves your problem. Oh, BTW, UNTESTED CODE, so some bugs may appear...

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Bounce2.h>

LiquidCrystal_I2C lcd(0x3F, 16, 2);

int value1; // I think it is better if these
int value2; // two variables are initialized
int runs1 = 0; // Unsure if this is needed
int runs2 = 0; // Unsure if this is needed
int val = 0; // Unsure if this is needed

int inPin = 6;
unsigned long previousMillis = 0;
const unsigned int millisInOneMinute = 60000U;

byte elapsedMinutes;
const byte intervalMinutes = 30;

Bounce buttonDebounce = Bounce();

void setup() {
    Serial.begin(9600);
    lcd.begin();
    pinMode(inPin, INPUT);
    buttonDebounce.attach(inPin);
    buttonDebounce.interval(5);
    previousMillis = millis();
    elapsedMinutes = intervalMinutes; // Force a new measure
}

void loop() {
    if (((unsigned int)(millis() - previousMillis)) >= millisInOneMinute)
    {
        previousMillis += millisInOneMinute; // Avoid drifting
        elapsedMinutes++;
    }

    if (elapsedMinutes >= intervalMinutes)
    {
        elapsedMinutes = 0;
        measure();
    }

    buttons();
}

void measure() {
    // do your stuff
}

void buttons()
{
    buttonDebounce.update();

    nextState = SM_currentState;

    switch (SM_currentState)
    {
    case SM_Display_1:
        if (buttonDebounce.rose())
            nextState = SM_Display_2;
        break;
    case SM_Display_2:
        if (buttonDebounce.rose())
            nextState = SM_Display_3;
        break;
    case SM_Display_3:
        if (buttonDebounce.rose())
            nextState = SM_Display_4;
        break;
    case SM_Display_4:
        if (buttonDebounce.rose())
            nextState = SM_Display_5;
        break;
    case SM_Display_5:
        if (buttonDebounce.rose())
            nextState = SM_Display_1;
        break;
    default:
        nextState = SM_Display_1;
        break;
    }

    if (nextState != SM_currentState)
    {
        SM_currentState = nextState;
        switch (SM_currentState)
        {
        case SM_Display_1:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 1 reads");
            lcd.setCursor(0,1);
            lcd.print(value1);
            delay(20);
            Serial. print("Case 0");
            break;
        case SM_Display_2:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Sensor 2 reads");
            lcd.setCursor(0,1);
            lcd.print(value2);
            delay(10);
            break;
        case SM_Display_3:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 1 ran");
            lcd.setCursor(0,1);
            lcd.setCursor(5,1);
            lcd.print(runs1);
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_4:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Pump 2 ran");
            lcd.setCursor(0,1);
            lcd.print(runs2);
            lcd.setCursor(5,1);;
            lcd.print(" times");
            delay(10);
            break;
        case SM_Display_5:
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Next cycle in");
            lcd.setCursor(0,1);
            lcd.print(elapsedMinutes);
            lcd.setCursor(5,1);
            lcd.print(" Minutes");
            delay(10);
            break;
        default:
            break;
        }
    }
}

EDIT: Generic implementation of a state machine

Ok, here I post my generic scheme for a state machine. Usually I use the "state-based" state machine, which is actions are linked to states; sometimes I also saw "transition-based" state machines, where actions were linked to transitions, but... Ok, I'm not a real expert, so I don't want to write a lot of (wrong) things.

In this kind of machines, each state can have up to three kind of actions and a check:

actions you perform when you ENTER the state
actions you perform continuously when you are INSIDE the state
actions you perform when you EXIT the state
and of course, you have to CHECK whether you need to make a transition to another state

For instance, when you have in a microwave a state corresponding to the ON state, you have to:

when you ENTER the state, turn on the heater
when you are INSIDE the state, update the timer value
when you are done and you are EXITing the state, turn off the heater
when during the CHECK you see that the timer has expired or the stop button was pressed, you switch to another state

So there are four kind of actions: ENTER, INSIDE, EXIT and CHECK. For linearity I learned that it is much better to write each of them in a separate switch case. This is my usual implementation scheme:

void stateMachine()
{
    byte nextState = currState; // currState of course is defined outside

    switch (currState)
    {
    // Here you have to CHECK, for each state, the conditions
    // needed to switch to another state; if you switch, put
    // the new state in nextState
    }

    if (nextState != currState)
    {
        switch (currState)
        {
        // Perform the EXIT functions for each state
        }

        // Advance to the next state
        currState = nextState;

        switch (currState)
        {
        // Perform the ENTER functions for each state
        }
    }
    else // See note below
    {
        switch (currState)
        {
        // Perform the actions to be performed continuously
        // INSIDE each state
        }
    }
}

NOTE: the else can be omitted or not. If you leave it, in the cycle that you detect the change you do not perform the INSIDE action; if you omit it, the INSIDE action will be performed. This is useful in different cases.

Now, usually (and yours is one of these cases) you only need the CHECK and ENTER sections (if you look at the code, you will see that only these two sections were implemented). Once in a while you will need also the INSIDE section, and once in your life you will also need the EXIT ;) (at least in my experience)


Can not upload to Arduino Nano BLE 33 I am new so please be nice :)
I am trying to upload the Blinky example to my Arduino Nano BLE 33 but I get this error message from the Arduino IDE:
No device found on ttyACM0
Set binary mode
Send auto-baud
An error occurred while uploading the sketch
Set binary mode

Any idea what I could try?
I am running the Arduino IDE as superuser in Manjaro (latest versions of everything). If you need any more information please feel free to ask.
Full IDE output:
Sketch uses 77820 bytes (7%) of program storage space. Maximum is 983040 bytes.
Global variables use 42192 bytes (16%) of dynamic memory, leaving 219952 bytes for local variables. Maximum is 262144 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
Uploading using selected port: /dev/ttyACM0
/root/.arduino15/packages/arduino/tools/bossac/1.9.1-arduino1/bossac -d --port=ttyACM0 -U -i -e -w /tmp/arduino_build_408944/Blink.ino.bin -R
No device found on ttyACM0
Set binary mode
Send auto-baud
An error occurred while uploading the sketch
Set binary mode

It appears you are using Linux. In order to communicate you must establish yourself as being allowed to use it, that is the dial out function. "sudo usermod -a -G dialout " should work but you need to log out then back in before it takes effect. After that you are all set.


How to send Serial data from an Arduino Uno into the Serial of an ESP-01? So, i need to send sound sensor data from an Arduino Uno to the ESP8266 (ESP-01), so it can output a push notification to my phone whenever there's a loud noise. I have the sensor just powered and hooked up to the Analog 0 pin, and the ESP powered and hooked up to the Arduino Serial pins in reverse (RX to TX, TX to RX)
This is the code i have on the Arduino:
void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.write(analogRead(A0) + "\r\n");
  delay(100);
}

And this is the code i have on the ESP:
(i'm omitting the notification part for clarity, it doesn't even use Serial, so i don't think it should interfere)
void setup() {
  Serial.begin(115200);
}
void loop() {
  String val;
  val = Serial.readString();
  if( val.toInt() < 50 ){ sendNotification("Hello!"); delay(10000);}
}

I have tested the Sensor output and it seems fine, whenever i snap or clap the readings show a peak (although reversed, it stays on 1023 constantly then peaks to around 0~50), and the ESP can also send notifications normally. But the trigger on the notification never seems to fire, so i guess the ESP is not receiving the data properly.
I'm new-ish to Arduino, so i don't know if i'm doing something wrong here,
Thanks in advance!

Writing Junk From Memory
Serial.write(analogRead(A0) + "\r\n");

This is advancing a pointer to "\r\n" by whatever number is being returned by analogRead.  In other words, you are not sending the measurement but junk from memory after (or sometimes at) "\r\n"'s memory location.
Serial.println(analogRead(A0)); appears to be what you were going for here.  println's line termination for the UNO serial connection is "\r\n".
Logic Levels
When it comes to attaching the serial connections together, there should be some level conversion going on.  Because an UNO's pins are 5V logic levels and the ESP-01 expects 3.3v levels.


WS2812B LED strip + Arduino First Pixel keeps dying/breaking I am trying too hook up a WS2812B LED strip to an arduino nano. The current strip consists of 6 pixels, and the whole thing is powered via a 5.26V Pc power supply.

The problem is that the first pixel keeps dying after about 1 minute. This means i have to cut the strip and re-solder the connections. Before the failure, the strip runs the correct examples from the FastLED package.

As this happened I looked for solutions. https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices suggested:
1) adding a 1000 µF capacitor between ground and  +5v to cancel power peaks
2) adding a 300-500Ohm resistor between the strip_Data_in and D5

I had no 1000µF+ Capacitor, so i used what i had, a 470µF, and installed it with the resistor.

This did not solve the problem. Another recommendation was to place a diode between the data and +5. ( I think this is to remove any power spikes in the data connection. With a good power supply this should not be necessary i guess, but it couldn't hurt.) Another tip was to add a 100kOhm resistor between data and ground.

putting all mentioned above together gives something like this:

But in the end nothing changed. I tried alot of variations of solutions:

With and without condensator between ground and Vin.
With and without resistor between data and arduino, and varied it between 220 Ohm to 1kOhm.
With and without the diodes. I tried connecting data with a diode to ground, +5v, to both, and to none.
I have tried using a 3.7V power source to see wether i could avoid burning the pixel. The Leds had too little power to light up.
I have tried powering via the USB->Arduino->Arduino +5v pin -> strip +5v

Any Idea where i might be fucking up?

I have burnt 30 pixels so far, with all the same result: blinking, tripping, and eventually failure. Removing the first LED always fixed the problem. This brand of LEDStrip did work on some other premade controller.

Some of my own ideas, of causes:

There really needs to be a 1000µF Capacitor. (i have never had trouble with voltage peaks with this powersupply, and this does not explain why the system fails after some time, instead of at plugin.)

EDIT 1):
I did some additional tests.

Raised the resistor before the data pin, from the recommended 470 Ohm, as high as possible. I reached 8kOhm (higher did not work). -> Same result, burned pixel
Lowered the voltage on the Data input pin, with two resistances, one connected to ground. The LedStrip only recognised data input when the ''Din_High'' was above 3.5 volts. Running at a bit lower voltage stopped the leds from recognising data. Yet still, Same result -> Burned pixel.
Changing the power supply: I changed the PC power supply to a 5V Power bank for loading celphones. The voltage this device was regulated to was between 5.2 and 4.8V. The behaviour was the same -> Burned pixel.

I would guess that IF:

the 5V is stable and within 5.5 and 4.5V And
The Din is within 0 and 5V

The cable should be unable to break itself right?

I finally found the solution:

The soldered pin connections at the cable was leaking current. This was due to the soldering flux remaining around the pins. Rinsing the connection with water carefully solved the problem.

Just scraping, and wiping with tissues between the connections is apparently unreliable. The flux is water cleanable, said the cup. Of course by taking care not to make anything wet besides the connection, and drying careful afterwards. Perhaps it failed after a minute or so because the flux started flowing due to heating up.

Thank you for your tips. You help me keep improving myself.

Any more tips on cleaning soldered connections are welcome.


ADXL345 hangs the micro-controller as vibrations increase I am using ADXL345 accelerometer with Adafruit_ADXL345 library for vibration measurement.

I am reading acceleration at X, Y, Z-axis of a sensor placed on a vibrating platform.And serially sending it to PC at a baud rate of 115200.

When vibration is low sensor shows vibrations but as i increase the vibrations serial transmission seems to be halted. As shown in figure:(x-axis=Samples y-axis=Values )

I thought it may be due to loose connections so I soldered its terminals but it behaved the same way at higher vibrations.
 Here is the code that I’m using.

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
/* Assign a unique ID to this sensor at the same time */

Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12);
int i=0;
struct measure
{
    int timestamp;
    float x;  // ACC in x direction
    float y;  //ACC in y direction
    float z;  //ACC in z direction
};
sensors_event_t event;
struct measure measurements;

int timestamp = 0;

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

  Serial.println("Accelerometer Test"); Serial.println("");

  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }
  accel.setDataRate(ADXL345_DATARATE_3200_HZ);
  accel.setRange(ADXL345_RANGE_16_G);
     pinMode(LED_BUILTIN, OUTPUT);
  delay(2000);
}

void loop(){

 accel.getEvent(&event);
   measurements.timestamp = timestamp++;
   measurements.x  = event.acceleration.x;
   measurements.y  = event.acceleration.y;
   measurements.z  = event.acceleration.z;

if(measurements.timestamp%2==0)
  digitalWrite(LED_BUILTIN, HIGH);
  else
    digitalWrite(LED_BUILTIN, LOW);

  /* Sending the array with data through serial*/

  Serial.print(measurements.timestamp);
 Serial.print(",");
 Serial.print(measurements.x+0.06);
 Serial.print(",");
 Serial.print(measurements.y+0.7);
 Serial.print(",");
 Serial.println(measurements.z-10.10);
}

Where does problem lie? How to resolve this issue?

Circuit Connections:

There is a known issue with the default "Wire" library, where if a certain transition is missed, the code goes into an infinite loop (rather than timing out). You possibly are reaching that situation. A possible reason is your printing of numbers at quite a high baud rate. The printing could be taking up so much time (itself causing serial interrupts as the serial buffer empties) that the I2C code doesn't execute in time the I2C interrupt.

You could try dropping the printing baud rate (something I wouldn't normally recommend) which means the serial interrupts would occur less frequently.

There is a library by DSS Circuits that has a time-out for I2C which may work around this issue to an extent:

http://dsscircuits.com/articles/arduino-i2c-master-library

Another thing you could try would be to summarize the data (eg. sample for 500 ms and then send the average), which would reduce the amount of serial comms.

Also you might try lower values for the pull-up resistors, like 4.7k.

So, my recommendations are:

Drop the baud rate (eg. to 9600 baud) and see if the hanging goes away
Summarize data rather than sending each reading
Try 4.7k pull-up resistors

If you have a logic analyzer you could look at the I2C signals and see if you can work out if the data is being transmitted as expected when the vibrations occur.

Saleae sell logic analyzers, the cheapest being $US 109. I use their (more expensive) analyzers extensively for debugging this sort of thing.


HTTP post request in JSON Format using SIM900 module I tried to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data. While posting the data I'm getting the error response while initializing the server using the command:

{("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path")}

I don't know what the error is and how to fix it. Please help me to fix this.

#include<SoftwareSerial.h>

SoftwareSerial client(2,3);

String testReading="{  \"testID\" : 1,  \"testLevel\" : 1, }";

void setup() {
  Serial.begin(9600);
  client.begin(9600);
  delay(1000);
  if(client.available()) {
    Serial.print("Connected");
  } else {
    Serial.print("Not Connected");
  }
  checkSignal();
  connectGPRS();
  postData();
  delay(1000);
}

void loop() {
  if(client.available()) {
    checkSignal();
    connectGPRS();
    postData();
    delay(1000);
  }
}

void connectGPRS() {
  client.println("AT+CGATT?");
  delay(1000);
  ShowSerialData();
  client.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(1000);
  ShowSerialData();
  client.println("AT+SAPBR=3,1,\"APN\",\"www\"");
  //Using Indian Standard Vodafone Sim and so APN is www
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=1,1");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=2,1");
  delay(1000);
  ShowSerialData();
}

void checkSignal() {
  client.println("AT+CSQ");
  delay(1000);
  ShowSerialData();
}

void ShowSerialData() {
  while(client.available()!=0)
    Serial.write(client.read());
}

void postData() {
  client.println("AT+HTTPINIT");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CONTENT\",\"application/json");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPDATA=99,10000");
  delay(1000);
  ShowSerialData;

  client.println(testReading);
  delay(1000);
  ShowSerialData;

  client.println("AT+HTTPACTION=1");
  delay(10000);
  while(!client.available());
  ShowSerialData();
}

Hi all use this code below for establishing HTTP connection with the server. And to neglect the 601 or 504 error use proper posting format. Here I'm using JSON format. I just gave manual data. Ignore those errors in HTTPINIT, AT+SAPBR=2,1. The data will be posted to the server

 #include<SoftwareSerial.h>

SoftwareSerial client(2,3);

String reading="{  \" : 1,  \"latitude\" : 12.983027,  \"longitude\" : 80.2594,  \"timestamp\" : 100,  }";

void setup()
{
  Serial.begin(9600);
  client.begin(9600);
  delay(500);

  if(client.available())
  {
    Serial.print("Connected");
  }
  else
  {
    Serial.print("NotConnected");
  }

  //initSIM();
  connectGPRS();
  connectHTTP();
}

void loop()
{

}

void connectGPRS()
{
  client.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=3,1,\"APN\",\"www\"");//APN
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=1,1");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=2,1");
  delay(1000);
  ShowSerialData();
}

void connectHTTP()
{
  client.println("AT+HTTPINIT");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"URL\",\"http://xxx.xxx.xx/Listener/\"");//Public server IP address
  client.println("AT+HTTPPARA=\"URL\",\"http://testServer/Listener/\"");//Public server address
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  delay(1000);
  ShowSerialData();

  client.println(reading);
  delay(1000);
  ShowSerialData;

  client.println("AT+HTTPACTION=1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPREAD");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPTERM");
  delay(1000);
  ShowSerialData;
}

void ShowSerialData()
{
  while(client.available()!=0)
  {
  Serial.write(client.read());
  delay(100);
  }
}


Using usb port to communicate with standalone atmega328p circuit noob here

So I managed to get my circuit to be a standalone circuit (as pictured below). I want to use this circuit as an input to a game on my computer. What I want to know is could this micro-usb breakout board https://www.diyelectronics.co.za/store/breakout-boards/2414-micro-usb-power-switch-breakout-module.html
 be used to communicate with the computer. Where would the data pins (d+/d-) connect to the atmega328?

Any help will be most appreciated

The ATmega328 does not have any native USB capability, so there is nowhere appropriate to connect D+/D- to the ATmega328.

Assuming you are emulating an Arduino Uno, then something like this:

https://www.jaycar.com.au/arduino-compatible-usb-to-serial-adaptor-module/p/XC4464

is what will come closest to mimicking the USB function on an Uno (ie a serial connection).

This shows how such a device would be connected:

https://www.jaycar.com.au/usb-serial-converter


Atmega328 and ADXL335 - is the right choice for vibration analysis? I'm planning to use the ATMEGA328 and the ADXL335 accelerometer to monitor the bearing and gears vibration of a industrial extractor that works at maximum speed of 3000rpm at 380VAC - 50Hz .
The main scope of this monitoring is to get continuously the vibration readings and apply the FFT transform in order to identify if there is something that is not running well.
My primary concerns are regarding the sampling speed of the ATMEGA328P: i've tried to identify the needed sampling speed but i'm a little bit confused about the relation of motor/gear speed and the ADC sampling speed of the ATMEGA...also, the ADXL is the right choice?

First of all, 3000 RPM is only 50 Hz, so sampling is not a problem for the fundamental frequency.  But you usually want to see harmonics, to pick up gear tooth issues, etc.
I suggest using my Daqarta software with a sound card to do your initial testing.  It already does everything you need, including waveform, spectrum, and spectrogram displays plus a lot more.  You can use it free for 30 sessions or 30 days, then the sound card inputs are no longer supported.  By that time you should have a good idea about what you need.  As it turns out, Daqarta also supports Arduino, and that does not end with the trial period.  So you may be able to do everything with an Arduino, for free.  The Daqarta site also has a contact page, and I am glad to answer questions and provide specific help for any issues that arise.  That include free users.


Use the TCS3200 color sensor without the included LEDs just a quick question. I want to know if it is possible to use the TCS3200 color sensor without the 4 LEDs included on the breakout board. I want to get the sky colors. Is that possible?

The photodiodes in the device itself have filters so it should theoretically be possible to use it without auxiliary light sources. Note, however, that the green and blue sensors have two sensitivity peaks and so using it outdoors without an infrared filter is not advised.


ArduinoUNO/MEGA, Is there a way to exceed 256 in analogWrite I am using Arduino UNO/MEGA, I want to

analogWrite(pin, val);

where the value is 0-1023.

How can I make that ?

Thanks.

Section 16, "16-bit Timer/Counter1 with PWM" of Atmel-8271J-AVR- ATmega-Datasheet_11/2015 describes using Timer/Counter-1 for 16-bit PWM, including sample code in both C and assembler. It might take a couple of reads over that section to get familiar with the hardware and learn what else T/C-1 is used for, and that you might have to give up while using it for PWM, but the code is fairly straightforward.

Using this T/C would give you 2-bits more resolution in your PWM output than mapping onto an 8-bit counter, if that is what your project needs.

+1 for the question. Not having needed PWM output for anything more than a demo with my DMM (yet), it hadn't occurred to me to look for a higher resolution until now.


SOLVED: Soft Power On SIM900 module - JP pads missing! I have this SIM900 board and working just fine.
But i can't find a way to soft power on this board from arduino.
I read for JP pads. They need soldering first, but from my board this JP pads missing.
Know someone other way to soft power on this from arduino?

OK for anyone who has the same problem. I solved this by soldering a cable on the underside of the board on this pin (see image) on power button. Then I connect the cable to pin 9 on Arduino and run this on sketch:

  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  pinMode(9, INPUT);

I don't know how it works, but it solves my problem.


How to make an RC mixer with the arduino I want to make a RC mixer mixing two channels of a receiver.

What I have: a delta model plane, two servos, a receiver and a Arduino Nano.

So I'd like to mix the aileron (two channels) with the elevator(one channel).

EDIT: What I've done: I read the input of the receiver and wrote it to the servos. The problem: The servo stutters and the arduino displays false inputs.

int pin = A0;
int pin1 = A1;
unsigned long duration;
unsigned long dur;

unsigned long duration2;
unsigned long dur2;

#include <Servo.h>

Servo myservo;
Servo myservo2;

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);
}

void loop()
{
  duration = pulseIn(pin, HIGH);
  dur = duration;
  Serial.println(dur);
  myservo.writeMicroseconds(dur);
  delay(50);
//  duration2 = pulseIn(pin1, HIGH);
//  dur2 = duration2-980/4-200;
//  Serial.println(dur2);
//  myservo2.write(dur2);
}

You do not need to use long for values from pulseIn, using int will be sufficient.

Your code is not complete, at least there is a missing '}' at the end of setup.

The slower the baud rate (9600) actually the more it interferes with timing code, to a point.  PWM is all timing code.  I would suggest 57,600.

You never set the servos to any pins.  And is using Servo lib needed? I have always used analogWrite with no problems.

You are not using parenthesis on your math (currently commented). It will not give you the result you expect. But you are somewhat on the right track, subtract 1500 from each pulse read, that will give you -/+ range. How you mix that depends on how your radio is setup (servo reversing, which channel is which). Keep in mind ailerons is 1 channel, so left aileron = -rightAileron.  Elevator up = that + elevator.  so;

aileronLeft = airleronChannel + elevatorChannel
aileronRight = -airleronChannel + elevatorChannel

You do realize this a $3 part?

update: I have always used analogWrite, but I also always use good equipment. I see cautions that cheapo servos might be damaged with analogWrite. You can read more here. It has always worked for me.


Is it possible to read-write the memory of a Gikfun ISD1820 voice recording module? I just got a Gikfun ISD1820 voice recording module for an Arduino project that I'm working on. I want to be able to record a few seconds message and then send the message over wifi to another Arduino Mega 2560, which will then play back the message.

The ISD1820 module can record and play back short messages and can be controlled from the Arduino, but I want to know if it is possible to access the memory / read-write the memory of the ISD1820 module to accomplish my goal. And how would I do it?

If it is impossible, what hardware should I get instead? Do I need a wave shield with a SD card or a wifi shield with an SD card?

Thanks!

No. You can't. That module can only record and play.

The only possible thing you could do is record onto the chip then play it back recording it on to the Arduino (at ridiculously low quality) - in which case, what would the point of the chip be?

If you want some quality to your recordings you need a powerful microcontroller with an I2S interface and a CODEC chip.  However any powerful MCU (such as the ARM chip on the Due, or the Teensy, or the PIC32 chip on the chipKIT boards) can sample at a reasonable quality through the ADC inputs.

The Arduino Uno can record very short bursts at very low quality (due to lack of memory) without any external hardware (except a suitable microphone preamplifier). The Mega can record slightly more, but the quality will still be very low.


Reading bits from a const char pointer I'm getting a bit tripped up on const char pointers lately.
I'm getting a message from a server that comes through as either a c style string, a standard library string, or a WString:

I'm sending down a buffer of 32bit values from my server that aren't ascii or utf text, they're just bit values I want to parse and read on the esp32 side:

I thought "oh, I'll just mask the bit values 32 bits at a time and right shift the data to get the message (in reverse order, but still I can work with that). The problem that I'm running into is that I can shift numbers but not strings or byte arrays.
I wrote out a function to allow me to grab a piece of the string 32 bits at a time and convert that into a number while using an offset:
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{

  uint32_t payload = 0;
  for (uint8_t i = 0; i < 8; i++)
  {
    payload <<= 0;
    payload += data[i + offset];
  }
  return payload;
}

But when I try to grab the first couple of 32 bit chunks the data isn't what I expected:
void handleGameFrame(const char *data, uint32_t length)
{

  uint8_t phaseAndColission = get32BitInt(data, 32);
  uint8_t player = getByte(data, 32 * 2);

  Serial.print("data: ");
  Serial.println(data);
  Serial.print("phaseAndColission: ");
  Serial.println(phaseAndColission, DEC);
  Serial.print("player: ");
  Serial.println(player, DEC);

}

yields:

I know the Serial.println(data); isn't going to output anything b/c it's a c-string of non-printable values, but the other chunk grabbing isn't giving me the same output from my server. It's hard to verify everything without being able to see all of the bits in the overall data pointer and I think I tied myself in (another) knot.
Is there a good way to parse 32 bit values out of a const c-string?

You wrote:

I wrote out a function to allow me to grab a piece of the string 32
bits at a time and convert that into a number while using an offset

This function is almost correct. Try this:
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{

  uint32_t payload = 0;
  for (uint8_t i = 0; i < 4; i++)
  {
    payload <<= 8;
    payload |= data[i + offset];
  }
  return payload;
}

Compared to your version, the differences are:

It reads 4 bytes instead of 8, as 32 bits are four bytes.

For each byte being read, it shifts the payload by 8 bits (i.e. one
byte) instead of zero. Shifting by zero has no effect.

It uses |= instead of +=: just a micro-optimization for the sake
of 8-bit MCUs. It shouldn't make much if a difference on a 32-bit
micro.


HX711 Load Cell application strange behaviour I have an application where an HX711 ADC is used with 4 load cells. (in wheatstone bridge configuration, rated at 50kg each).

The thing is that I am trying to sense 30~ish gram changes with it accurately, while the cells will be loaded with 10 to 40 kilograms.

I have built up the circuitry and placements properly, calibrated and tested etc. but I have 2 questions that I couldn't come up with a solution.

1st question:
When powering arduino from USB cable the readings are much more stable (they are fluctuating like +-5 grams only) but when I connect a 12V power source (with 5A output) to the arduino, the readings start to fluctuate much more. (+-30 grams or so). The HX711 is powered from arduino 5v out pin but even though i tried to power it from a 5v adapter the fluctuations seemed to happen.

I should also note that the HX711 is connected to the analog pins A0 and A1, and there are 8 other sensors connected to the pwm pins of the arduino.

Now any ideas why does that happen? Any way to prevent this fluctuation?

2nd question:
If I calibrate with a load close to the max. weight (as suggested in many papers) the small changes seems to be very unreliable. If I calibrate it with a small weight (like around 200g) I can sense small weights properly but this time when a 2 kg weight is put it is read like 2.3kg or something. Is this normal?

I know that my load cells are not the proper ones for the application but I would like to push them as much as i can.

Thanks for your time

1) Put your power source on an oscilloscope and check it. I assume what's happening is you don't have a clean sine, and the power fluctuates, whereas power from a PC USB port is usually very well regulated. This may be causing issues in your sensor due to under/over voltage at a minuscule level.

2) Because you're pushing your sensors to the edge of their capabilities, you're going to have to work around them, so the normal scenario's don't really offer much help, as they are usually based on working within the middle ground of capabilities.

You said that factoring based on low load vs high load created unreliable  variances in your measurements, i would personally suggest calibrating not for max load, nor min load, but 2/3 of max, or 1/3 max, and see if that stabilizes you, or at least gets you somewhere to the middle of the road where your differences are nominal, or something you can live with.


Building RS485 serial to USB adapter with digispark Is it possible to build an serial-adapter with digispark board?
Like: Embedded System with 2-wire RS-485 Port connect to my digispark board. Digispark Board is connected via USB to my Computer (running Linux tty or Windows COM Putty Interface)
I also own a Raspberry Pi. I'm very new at this thing, so maybe there is a way to convert the RS485 signals to monitoring my devices with my computer?

There are some good books available to help. There is the Raspberry Pi cookbook and the Arduino cookbook. These will take you from the very beginning to the point where you can make your own designs and they will work.


Joy stick Implementation on PID controlled balancing robot I am developing a self balancing robot which uses DC motor as actuator, IMU as input sensor and PID as controller. I want to use Dual axis joystick to control the forward and backward motion as well as to turn the robot left and right. Regarding forward and backward motion, I have come up with the idea however, I am stuck with the direction(left and right). I would be grateful if someone could share their idea on this.

I'm not 100% sure what your expect problem is … I assume you can read left and right on the joystick (very similar to up and down).

To make a left movement, you have to either stop the left wheel and rotate the right wheel forward (so you make a left turn), or if you want an even faster movement, move the left wheel backwards and the right wheel forward.

For a right movement, do the opposite.

(actually having a different speed for the left and right wheel already causes a turning movement).


How to correctly use functions that return pointers to multiple typedef'ed types in Arduino IDE? I have a program that typedef's two structs. Each one has a corresponding function that returns a pointer to it....

typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

This program produces the following error when compiled under the Arduino IDE...

sketch_nov10a:18: error: 'y' does not name a type

 y *g(void)

If we copy/paste to switch the order of the two blocks like so...

typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

void loop(void) {

}

void setup(void) {

}

...then we instead get the following error...

sketch_nov10a:18: error: 'x' does not name a type

x *f(void)

...so apparently the Arduino IDE only supports functions that return pointers to the first typedef'ed type defined in the file?

Is there a rational to this? How would you implement the above code to get it to compile under the Arduino IDE (it works fine in gcc).

The Arduino IDE, rather annoyingly, tries to "help" you by generating function prototypes for functions, something it sometimes fails to do.

You can make your code compile by adding one yourself:

typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void);    // <------------------ ADD THIS
y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

I have a post about how to avoid the quirks in the IDE which may help you.

If you just move your code into a separate .CPP file and leave the main sketch blank, it will compile, if you add this line to the start of the .CPP file:

#include <Arduino.h>

The Arduino IDE uses gcc, so it isn't a problem with the compiler exactly, it is a problem with how it "helps" you.


Arduino and a Web Server I'm here because I couldn't find any answer anywhere and the problem seems pretty easy and hard in a same time.

I have a website, for exemple : My_website.host.fr
I have arduino's sensors at home, for exemple temperature sensor in my garage, servomotor in shutter, etc... with Wifi-module.

I want to, as a User, access the website, update some information on the website, for exemple : I want the shutter down, so I put it to 0 on the website, and the arduino will, for exemple each X seconds check if the value has changed, if it does then it updates itself and so lower the shutter.

So, by this, i'll never have to connect directly through an @ip to my arduino, without hosting a server at home which could be hacked or anything, the arduino update itself with the infos that are on the website,

So from my arduino I must ? I have no idea, get the source code of the web page and search for some value, or, from the web page, update a file with PHP variables and retrieve that file with my arduino then read it for the values ?

I don't know if it's clear tho and I have no idea how to manage it.

Sorry about the bad english sentence or words, not main language;

Thank for the help i'm kind of lost.

From your comment of Jul 1st, I understand that you can program your
server in PHP. Then, and to expand on my own comments, I am only
recommending that, whatever Web API you design, you keep it as simple as
possible. For example, for telling the Arduino whether it should keep
the shutter open or closed, you could write something like this in PHP:

header('Content-Type: text/plain');

if (user_wants_shutter_open())
    echo "open";
else
    echo "close";

In particular, it makes absolutely no sense to write a PHP program that
generates an HTML document. Consider that the Arduino is a very low
powered platform: there is no point in having it process more than a
handful of bytes when you only want to communicate a single bit of
information. And you should know that there is really nothing wrong with
using HTTP to transport plain text (but you should use the header
Content-Type: text/plain). If you want to send a more complex set of
data, you could use something like text/tab-separated-values, or maybe
even application/json.

Concerning web scrapping, it is a solution to a specific problem, the
problem being that the server returns the information in a format that
is not very well suited for machine consumption. You do not have this
problem. Obviously, you could create the problem by having your PHP
return an HTML document, and then you could apply the solution. My point
is that it is better to avoid creating the problem in the first place:
just return the information in a format that is as easy to parse as
possible.


Not waking up more than once? I'm trying the following code on an Uno. I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once. Just once. Does anyone know why this might be the case?

It works fine if I use LOW for attachInterrupt along with a pull-up resistor though. Just not with RISING and a pull-down.

#include <avr/sleep.h>
#include <avr/power.h>

int pin2 = 2;

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

  /* Setup the pin direction. */
  pinMode(pin2, INPUT);

  Serial.println("Initialisation complete.");

}

void pin2Interrupt(void)
{
  /* This will bring us back from sleep. */

  /* We detach the interrupt to stop it from
   * continuously firing while the interrupt pin
   * is high.
   */
  detachInterrupt(digitalPinToInterrupt(pin2));
}

void enterSleep(void)
{

  sleep_enable();

  /* Setup pin2 as an interrupt and attach handler. */
  attachInterrupt(digitalPinToInterrupt(pin2), pin2Interrupt, RISING);
  delay(100);

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  sleep_mode();

  /* The program will continue from here. */

  /* First thing to do is disable sleep. */
  sleep_disable();
}

int seconds=0;
void loop()
{
  delay(1000);
  seconds++;

  Serial.print("Awake for ");
  Serial.print(seconds, DEC);
  Serial.println(" second");

  if(seconds >= 3)
  {
    Serial.println("Entering sleep");
    delay(200);
    seconds = 0;
    enterSleep();
  }
}

For a RISING interrupt you never need to disconnect the interrupt to prevent repeat triggering.

A RISING interrupt specifically only triggers the once when the input pin transitions from LOW to HIGH rather than all the time it's in a state like a level interrupt.

Attach the interrupt once in setup() and leave it alone after that.  Your interrupt handler routine can be completely empty.  It will only ever be triggered at the exact moment you press the button.  To trigger it again you will just need to press the button again.


Can't drive long NeoPixel strips with Due or Duemilanove? I spent a significant part of today developing a sprite movement library for a 30-pixel NeoPixel strip using my Arduino Duemilanove (ATmega 168). It works like a charm. However, if I change N_LEDS to a significantly higher value, the program seems not to run. I can't get it to run on the Duemilanove for a strip of longer than 50.

In fact, (see the below code) a relatively high N_LEDS value won't even allow the test patterns to run as defined in setup(). This leads me to believe that inexplicably the constructor for Adafruit_Neopixel is failing.

A friend of mine (who has the ultimate application for this) is hoping to drive a strand of 750 LEDs using this code on an Arduino Due. I can't imagine memory would be an issue with the Due, so what's going on here?

Headers:

#include <Adafruit_NeoPixel.h>

#define PIN    6
#define N_LEDS 30      // <-- If this number is > ~50, nothing happens
#define MAXSPRITES 5
#define MIN_UPDATE_INTERVAL_IN_MS  15
#define MAX_UPDATE_INTERVAL_IN_MS  40
#define SENSOR_TIMEOUT_IN_MS  2000
#define SCANNER_WIDTH  9

Strip declaration:

Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_LEDS, PIN, NEO_GRB + NEO_KHZ800);

setup() and loop():

void setup() {
    randomSeed(analogRead(0));

    strip.begin();

    darkenStrip();

    manager = new SpriteManager();
    manager->Add(new TestPatternSprite(0, 0xff0000));
    manager->Add(new TestPatternSprite(5, 0x00ff00));
    manager->Add(new TestPatternSprite(10, 0x0000ff));
}

loop() {
    ...
}

Are there any coding mistakes in the above that wouldn't allow us to run this code on the Due? Or is this a known limitation?

Your Duemilanove only has 1k of RAM. That's not much. Each pixel takes 3 bytes of RAM (R/G/B). So (say) 60 pixels would be 180 bytes. That's less than 1k, but there would be other uses of RAM in your sketch.

750 LEDs sounds like pushing it for the low-RAM Arduinos.

You might want to look at NeoPixels Revealed: How to (not need to) generate precisely timed signals The author managed to drive over 1000 NeoPixels with a Duemilanove.

I'm not sure if that applies to your exact type of NeoPixels, but it is worth considering.


The 8 bit Arduinos don't have precision, or anything even close to precision when it comes to working with decimal values.

There is no such thing as double on an 8-bit Arduino - it is only an alias for float. By using double you aren't gaining any more precision than using float.

Even double isn't perfectly precise. It's more precise than float (on systems that support double), but still far from precise.

People that care about specific levels of precision code using variables of that precision. That's called using fixed point mathematics, and it's what DSPs work in. It's fast, efficient, and precise up to the point that you define it to be.

Fixed point mathematics works by operating in multiples of a pre-defined fraction. That fraction is your precision, or granularity and is the smallest value that can be represented. However, working with large numbers and fine granularity results in very large variables to store all that data - which is why for most things people use float: because it compresses the data down into a very small space - and like a highly compressed MP3 it loses a lot of the data.


Debugging library - Error- expected unqualified id before '.' token I'm writing a library for my project, which interfaces sensors used and structures them in different systems.

But I'm such a noob at C++. The compiler is throwing this error:

libraries/cec-core/cec-core.cpp: In member function 'void Habitaculo::Update()':
libraries/cec-core/cec-core.cpp:15:8: error: expected unqualified-id before '.' token
_Sluz.Update();

This is the header of that class:

class Habitaculo
{
    public:
    Habitaculo(int refrate, int luzpin, int dhtpin);
    //Values from Indoor Sensors
    int temp;
    int hum;
    int luz;
    //Update Methods
    void Update();      //Updates sensors value
    void UpdateReg();   //writes to SD or enabled output method
    private:
    //Clock Managing
    long _PreviousMillis;
    unsigned long _CurrentMillis;
    int _RefreshRate;
    //Sensor instances
    class _Sluz;
    class _SDHT;
};

This are the member functions affected:

Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin){
    //Clock management
    _RefreshRate = refrate;
    _PreviousMillis = 0;
    //Systems to initialize
    LDR _Sluz(luzpin);      //analogpin
    DHT11 _SDHT(dhtpin);    //buspin
}
void Habitaculo::Update(){
    _CurrentMillis = millis();
    if (_CurrentMillis-_PreviousMillis > _RefreshRate){
        _Sluz.Update();  //unqualified-id before '.' token
        _SDHT.Update();  //unqualified-id before '.' token
        temp = _SDHT.temp;  //expected primary-expression before '.'
        hum = _SDHT.hum;  //expected primary-expression before '.'
        luz = _Sluz.value;  //expected primary-expression before '.'
        _PreviousMillis = _CurrentMillis;
    }
}

The error is thrown in every step of the Update method. But I can copy that piece of code right in the Habitaculo constructor and it works well. So I assume I'm missing something basic about language syntax, because I'm really new to all this scene.

Every class involved in this (LDR, DHT11) works fine. It's when I try to put all this together into a new class - inside an unified Update method - that everything crashes.

class _Sluz;
class _SDHT;

You're forward declared two classes but I see nothing about what those classes are. You then to and use those class declarations as if they were class instances.

I think you are lacking a bit of basic syntax knowledge there. You may have meant:

Sluz _Sluz;
SDHT _SDHT;

Though not knowing what those classes are meant to be or how they are even defined I cannot know really what you think you're meaning.


Make Piano keys on Webpage create sound on Arduino (w/out Shield) So I am trying to make a digital keyboard on webpage, that when one of the keys are clicked it creates sounds on the Arduino board. I want to do this without an ethernet shield. I am a beginner so I am not sure how to proceed. I'm not even sure what type of code it needs to work. I just know that I need Processing sketch to act as a go between for the webpage and the Arduino.

You are asking for something that sounds simple, but it's far from simple.

The security of modern web browsers is based on simple premise. Websites cannot in any way interact with the system of the user. Unless you are a hacker ant you are using an exploit you cannot make a website that will send data to the PC it's opened upon, or even read anything (like files and folders from hard drive) except the things that browser tells it (like what fonts are installed)

You can write a browser plugin that will break that rule, but it's a bad practice to deliberately make suck an awful backdoor.

Websites can only communicate with the server they were opened from. You can use AJAX made easy by a javascript library like jQuery. This means that You will have to write your own plugin to any of the existing http servers like apache (for php), or create your own server using for example flask framework (for python) and use it to communicate through serial protocol with the hardware.

The arduino code will be the simplest task in your project.

The code should read from serial a string value. Since You can only press one key at the time with a mouse you just need to read a value of key that was pressed like "12". Then play correct sound using for example a buzzer

The ethernet shield can help only by allowing you to install server on the hardware itself, connecting it to your wifi and forwarding it outside to be accessible by everyone on the web. For that I suggest using raspberryPi, omega2 or even esp8266 and not an arduino.


avrdude : stk500_get sync attempt 10 of 10 not in sync : resp=0x20 how do i get pass this error for ardunio uno board When I first started with a bare minimum code. The compiler compiles the code, but when I try to upload, this is the error message I get:

 AVRDUDE: STK500_GETSYNC<> ATTEMPT 10 OF 10 NOT IN SYNC :RESP=0X20

How do I fix this?

There are multiple reasons why you are getting this error.

Bootloader is either missing or corrupted. This is fairly unlikely.
Wire connected to pin 0 (RX)
Wrong COM port is chosen within the arduino IDE.
Drivers are not installed. You can update it within the Device Manager if you are using Windows.

Here is a link to an article explaining the causes and how to fix them, http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/


Want to create bluetooth audio control (volume up/down, play, pause, etc.) for smartphone I want to create a bluetooth remote audio control to control smartphone audio, essentially identical in function to this type of equipment:

https://www.amazon.com/FAVOLCANO-Bluetooth-Button-Smartphone-Samsung/dp/B01C5E95XG/ref=pd_lpo_147_bs_t_1?ie=UTF8&refRID=1GRBCPDRMD9YPYPGK73Y

This device is simply a bluebooth remote control which allows you to play or pause audio, skip forward or backward and change media volume on the smart phone.

All of the Arduino tutorials I see are about either using the iPhone to control a bluebooth device, or about using bluetooth to control an arduino, neither of which are what I want to do.

Can you point me in the right direction?

Bluetooth supports multiple protocols for multiple purposes.  There is low latency low quality monorail bi-directional communication with a little bit of bandwidth for control for Bluetooth phone calls.  This is called HFE Bluetooth protocol.  If you are interfacing a keyboard or a mouse you would use the Human Interface Device protocol or HID.  If you wanted to listen to music and control it's playback you would use the high latency high quality 2 audio sending channels (stereo) no return audio channel with a little bit of bandwidth for controlling playback called Advanced Audio Distribution Profile or A2DP.

In this specific case we are only interested in controlling playback.  So we could use the HID Bluetooth protocol.  However, the native music players on the platform you are using (Android or iPhone) likely will not be listening to such a device.  In order for this to work you will probably have to write your own Android or iPhone music player.

On the other hand, it is likely the native music players will work with A2DP Bluetooth protocol.  Unfortunately, it is also suspected that once the A2DP Bluetooth connection is established, the phone's speaker will be shutdown and all audio will be diverted to the Bluetooth connection.

Finally, there is the Audio/Video Remote Control Profile or AVRCP.  This protocol is used to control media playback.  There are several versions of this protocol so what features are available for a given device / music-application may vary greatly.


How can I measure if a battery is there? With my arduino I want to measure if one / two AAA batteries are in their single / double battery holder.

When the Arduino is running, connected to some other power supply and the batteries are in place everything is fine: I get my measurements of around 1.5V / 3V on the analog pin the battery is connected to (- of battery and Arduino GND are connected as well of course).

Problems arise when I either

a) pull the batteries out: The analog pin is left floating. Not good. Can I put the pin into INPUT_PULLUP mode? Is the internal resistor big enough? Or will the then connected 5V damage my batteries when they are back in the battery holder?

b) dissconect the Arduino from its external power supply: Because the Arduino is then "powered" by the 3V through the analog pin my blinking LED keeps blinking (at less brightness, but still...). I neither want the batteries to get drained nor damage my Arduino with it. So I would like to avoid this.

Actually I don't care about the actual battery voltage - I just want to know if the batteries are in their holder or not. And I want to leave the batteries there even though the Arduino is not powered. I would even consider something like "a button is held down when a battery is in its holder" or any other (simple) creative ideas.

Is this possible? How?

You could add a pulldown to the analog pin. If the ADC reads a value below e.f. 10, you could consider this the state when there are no batteries.

From the signal perspective a pullup would be better, because without batteries you would read 5V which is unambigous as it can not be provided by the batteries themselves. But in general I don't think that applying higher voltage to the batteries is good practice, even though you could limit the current with a reasonably high resistor.


Bluetooth HID module I try to build custom controller and now searching for bluetooth hid module. Which BT HID module compatible with arduino? (not bluetooth serial)

List of some modules:

BlueSMiRF HID - from sparkfun, expensive (based on rn-42, also available RN-42-EK evaluation board) ✔ compatible
HM-10 bluetooth module - around $10 (aliexpress), based on cc2540 ht
tp://www.ti.com/product/cc2540
HC-05 Transceiver Module  - less $10, maybe supports HID after firmware upgrade(??)
Bluegiga wt12
Bluefruit EZ-HID from Adafruit ~$20 (suggested by mwwalk) ✔ compatible

Thanks

I'm not entirely sure from your question if you want just the module or a whole breakout board.  If the latter, try this from adafruit. It can very easily do his either as mouse or keyboard and is well documented and supported so I think this would be much easier to get running initially. http://www.adafruit.com/products/1535


Using a pushbutton to power Arduino on and off I need help adding a pushbutton to provide power to an Arduino to save power, as I am using a battery and the same button to power it off. This is the circuit I wish to implement.

Thanks.

You can use the button as a switcher for the Arduino power. Just wire up the button between the battery + out and the Arduino's Vin port.


control a jack/cylinder to open/close a window I want to open the window to let the cat enter or go out, but the mecanism of the window may me think that the best way should be to use a jack/cylinder (I don't know what term is more appropriate in english for that) to open and close the door.

I will use rfid or another wireless think to know it the cat is in the place and then open the wondow but I want to close the window and let the wndow close event if there is little bit of wind, so I need domething robust.

Do you know a good hardware with (this would be the best) piece of code that can help me for that?

Thanks in advance

Check out this instructable - for opening a window for a cat :)
The guy used a servo, Towerpro MG995 with 10 kg torque for opening/closing the window, and a 10cm distance sensor for sensing the cat (he used Pololu Carrier with Sharp GP2Y0D810Z0F Digital Distance Sensor, but I believe that any proximity sensor will do).

This is a pictrure of the mechanism, seems quite robust:


Ensure board is always on the same port? I want to make a VB.NET program to communicate over serial with the board, but I need to be sure it knows which port. Instead of programming in more advanced methods of verification, for this project I would simply prefer to keep the board on the same (internal) USB port. Will it always appear on the same serial port (COMx) and will VB always be able to find it there?

Normally, the COM port number wont change, but you cannot simply rely on this.

Depends on various effects, especially if you have multiple USB-Serial devices, update the driver, etc. Also, there's the possibility to clean the COM port numbers in the operating system to get rid of unused legacy entries, which will restart counting them from fresh.

Most applications search for all existing ones, eventually display their names, and leave it to the user to choose the desired port.

And, btw. it's not related to VB.net


How do I send tweets with flame sensor and ESP8266? I want to send tweets with flame sensor and ESP8266. My flame sensor is digital. I think everything is good but it doesn't send.

This is my code:

#define ag_ismi "SSID"
#define ag_sifresi "PASSWORD"
#define IP "184.106.153.149" //thingspeak.com IP address

int sensorPin = 8;
int smoke_level = HIGH;

void setup() {
  pinMode(sensorPin, INPUT);
  Serial.begin(115200);
  Serial.println("AT");
  delay(3000);
  if (Serial.find("OK")) {
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String baglantiKomutu = String("AT+CWJAP=\"") + ag_ismi + "\",\"" + ag_sifresi + "\"";
    Serial.println(baglantiKomutu);
    delay(5000);
  }
}

void loop() {
  smoke_level = digitalRead(sensorPin); // Arduino reads the value from the smoke sensor
  Serial.println(smoke_level);// prints just for debugging purposes, to see what values the sensor is picking up
  if (smoke_level == HIGH) {
    // if smoke level is greater than 500, the buzzer will go off
    sicaklik_yolla();
  }
  delay(20000);
}
void sicaklik_yolla() {
  Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
  delay(1500);
  String tweet = "POST /apps/thingtweet/1/statuses/update HTTP/1.1\n";
  tweet += "Host: api.thingspeak.com\n";
  tweet += "Connection: close\n";
  tweet += "Content-Type: application/x-www-form-urlencoded\n";
  tweet += "Content-Length:67\r\n\r\napi_key=";
  tweet += String("MY API KEY");
  tweet += String("&status=");
  tweet += String("MY TWEET TEXT");
  Serial.print("AT+CIPSEND=");
  delay(100);
  Serial.println(tweet.length());
  if (Serial.find(">")) {
    Serial.println(tweet);
    Serial.println("AT+CIPCLOSE=0");
    delay(100);
  } else {
    Serial.println("AT+CIPCLOSE=0");
  }
}

This schema is old. Sensor connected to pin 8.

I guess your baud rate and network connection with the wifi module is working fine. Have to say that it is a bit difficult to get the data sent to ThingSpeak with ESP8266. I actually did some experiments to get the data sent. The problem is actually with the delay. Adding a delay of 5000 ms between sending the tweet length and the tweet content sorts it out. You can use GET format. Check out this Instructable.


Determining state of charge using current sensor (ACS758) with arduino uno I am working on a university project and I am struggling with estimating the state of charge of our batteries, by using coulomb counting.

Background: We are supposed to build a power supply for a mostly constant load of 100 W (can go up to 140 W) which will be placed outdoors for two years. The plan is to have a small wind turbine plus some solar PV connected to a large battery assembly. The system has to run close to 24/7 with limited downtime.

I have bought some ACS758 50A bidirectional current sensors as well as an Arduino UNO. I am extremely new to Arduino and I would really appreciate some help with the coding. The plan is to have the arduino do the sampling of current and integration, which is then translated to SOC as a percentage and sent to a Raspberry Pi which will send email alerts if the SOC is below a certain level.

I have been looking at sample code describing how to extract the raw data from the ACS sensor: https://www.dfrobot.com/wiki/index.php/50A_Current_Sensor(SKU:SEN0098) as well as sample code that performs integration (Integrating an analog signal using ARDUINO UNO SMD), which is what I would use for coulomb counting.

What I need is most likely a combination between the two, however I do not even know where to start from.

Thanks in advance!

Instead of using a separated component for each thing you can use a proper solution that is itself already a combination of both: the DS2438's integrated current accumulator. This link explain it pretty well, also here is a library to use it with arduino. They are pretty cheap (a few dollars) and will perform very well!

Although, in your place I would consider choosing a different approach. I don't know which kind of battery (Li-ion, LiPo, Lead-acid..) you are using, but in many cases if you monitor the battery voltage, you can have enough information about the battery state. I can't ask you in comment yet beause I'm new here and don't have enough reputation, but if you can describe better the kind of battery you are using and what you intend to monitor which your circuit, I can edit this post to offer you a better solution.