How to send data from an Arduino GPRS module to a Django application hosted on Heroku? I have a Django web application hosted on a Heroku server. Currently I am using the free package for hosting. I want to send data from an Arduino using a SIM900L GPRS module to the web application. I want to know if it is possible. I have searched for a solution but couldn't find a proper guide or example for it. My web application accepts get requests and updates values in the database when url is entered. However if the Arduino sends data using the same url I get the following error:

  AT+CIPSTART="TipCP","https://.herokuapp.com",80
  ERROR

Any tested example or suggestions about what I am doing wrong or what I should be doing instead?

     void gprs(float *value1, float *value2, float *value3, float *AFR, float *value5, float *value6)
{

  String APN = "";
  String UNAME = "";
  String PWD = "";
  char fid[] = "";
  char nid[] = "";
  char s_ip[] = "https://<appname>.herokuapp.com";
  char apikey[] = "";

  wdt_reset();
  digitalWrite(A4, HIGH);
  Serial.println(F("GPRS-1 Function"));
  delay(5000);
  wdt_reset();
  delay(5000);
  wdt_reset();

  char buffer1[10];

  uint8_t GSMTries = 0;
  String res;

  //wdt_reset();
  // the below code establishes connection and if not successful
  // tries three times in total
  do {
    sendData(F("AT\r\n"), 1000, DEBUG);
    sendData(F("AT+CIPSHUT\r\n"), 2000, DEBUG);
    sendData(F("AT+CIPMUX=0\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    sendData("AT+CSTT= \"" + APN + "\", \"" + UNAME + "\", \"" + PWD + "\"\r\n", 2000, DEBUG);

    sendData(F("AT+CIICR\r\n"), 2000, DEBUG);
    sendData(F("AT+CIFSR\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
    scnt += s_ip ;
    scnt += "\",80\r\n" ;

    res = sendData(scnt, 10000, DEBUG);
    GSMTries++;

    wdt_reset();

  } while (((res.indexOf("ERROR") != -1) || (res.indexOf("CONNECT") == -1)) && (GSMTries < 3));
  /*
    if(res.indexOf("ERROR") != -1){
    delay(200);
    sendData(scnt, 10000, DEBUG);
    }
  */

  String api = "GET /value?apkey=" ;
  api += apikey;
  api += "&&fid=";
  api += fid;
  api += "&&nid=";
  api += nid;

  Serial.println(F("API......."));
  Serial.flush();
  Serial.println(F("here-1"));

  String Data1 = "";

  //wdt_reset();
  //Co ordinator data is compiled along with html commands
  //and sent through GPRS
  String sensor = dtostrf(*value1, 4, 2, buffer1);
  Data1.concat(api);
  Data1.concat(F("&field1="));
  Data1.concat(sensor);

  sensor = dtostrf(*value2, 4, 2, buffer1);
  Data1.concat(F("&field2="));
  Data1.concat(sensor);

  sensor = dtostrf(*value3, 4, 2, buffer1);
  Data1.concat(F("&field3="));
  Data1.concat(sensor);

  sensor = dtostrf(*AFR, 4, 2, buffer1);
  Data1.concat(F("&field4="));
  Data1.concat(sensor);

  sensor = dtostrf(*value4, 4, 2, buffer1);
  Data1.concat(F("&field5="));
  Data1.concat(sensor);

  sensor = dtostrf(*value6, 4, 2, buffer1);
  Data1.concat(F("&field6="));
  Data1.concat(sensor);

  Data1.concat(F("\r\n"));

  delay(1000);

  String cipSend = "AT+CIPSEND=";
  cipSend.concat(Data1.length());
  cipSend.concat("\r\n");
  sendData(cipSend, 8000, DEBUG);
  sendData(Data1, 8000, DEBUG);
  sendData(F("AT+CIPCLOSE\r\n"), 5000, DEBUG);
  digitalWrite(A4, LOW);

  wdt_reset();

}

The above is a part of code used in arduino to upload data to website. This code was being used before to upload data to thingspeak through its IP address and worked fine.

There's a number of errors in your program regarding your understanding of basic networking:

Let's start with this bit:

String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
scnt += s_ip ;
scnt += "\",80\r\n" ;

That constructs a string:

AT+CIPSTART="TipCP","https://<appname>.herokuapp.com",80

and sends it to the modem.  Now:

There is no such protocol as "TipCP" - I think you meant "TCP"
You need to provide an FQDN (Fully Qualified Domain Name), not a URL.  FQDNs don't start with "https://".  I think you meant to use "foobar.herokuapp.com" where "foobar" is the name of your application.

You then go on to form a GET request and send it.

Now: the URL you used instead of an FQDN starts with https:// - that tells me you want to be using SSL for your communications. I don't know if that is required for Heroku or not, but if it is then you cannot use AT+CIPSTART with it unless you feel like trying to implement the entirety of SSL in your program. Also you would be connecting to port 443 not port 80.

Assuming you don't need SSL fixing your protocol and FQDN may be enough. However using the AT+HTTP... commands instead of manual manipulation of a raw TCP socket may be an easier option.

If you do need SSL (and it is advisable that you do if you can) then you will have to use the SIM900's AT+HTTPS... command set (detailed here).


Transfer a struct's data to an external struct via serial? Using two boards of similar architecture I would like to send the contents of a struct from the sending board to the receiving board. I am using UART to transfer.

My plan was to populate an array with the starting structs data. Transfer that, than un-package the array onto the receiving boards struct.

I'm not sure this is a possible option. Unpacking the array seems sort of rigid, as I would be assigning each struct variable to the array index. It might work but I'm not really convinced I should do it this way.

Here's what my sending sketch looks like.

Send:

typedef struct NWK_DataReq_t
{
 uint8_t      state;
 uint8_t      options;
} NWK_DataReq_t;

//Instance struct
NWK_DataReq_t dataRequest;

void setup()
{
  //Give it some values
  dataRequest.state = 2;
  dataRequest.options = 4;

  Serial.begin(9600);
}

void loop()
{
  //set variable array to struct length
  uint8_t payload[sizeof(dataRequest)];

  //copy struct to variable array
  memcpy(payload,&dataRequest,sizeof(dataRequest));

  //send each item of struct, now contained in payload array
  for(int i=0;i < sizeof(payload);i++)
  {
    //Serial.print(i);
    //Serial.print(":");
    Serial.println(payload[i]);
  }

  Serial.println("");
  delay(1000);
}

Receive:

typedef struct NWK_DataReq_t
{
 uint8_t      state;
 uint8_t      options;
} NWK_DataReq_t;

//Instance struct
NWK_DataReq_t dataRequest;
uint8_t incomingPayload[sizeof(dataRequest)];

void setup()
{
  Serial.begin(9600);
  Serial.print("Recieve started");
}

void loop()
{

  if (Serial.available())
  {
    //add incoming data to array
    for(int i=0;i<sizeof(dataRequest);i++)
    {
      uint8_t incomingByte = Serial.read();
      incomingPayload[i] = incomingByte;
    }
  }

  //set array values to structs
  for (int i= 0;i < sizeof(dataRequest);i++)
  {
    structIndexPosition = incomingPayload[i];
  }
}

structIndexPosition is not attached as I wasn't sure how I might index the struct, or if this is an okay approach.

I think you are over-complicating it to send two bytes. Just send them as straight ASCII with a newline after, and decode it on the receiving end.

eg.

42,87

However if the question was just an example of something much more complex, then you may need to do more work. You need to have the receiving end know when a packet of data starts, and ends, and preferably have some validation that it wasn't corrupted.  If you want to pursue that idea, see my thread about sending data via RS485 which has a library that does that sort of thing.


arduino SD card saving to file Can anyone assist me with read/write to a SD shield. I am using a arduino along with a SD shield (POD  uSD) I am using a ultrasonic sensor to measure a distance, it has a safety factor in it. It also measures the time a measurement was taken, I now need to save the data from the serial monitor to a file and send that file to a SD card. I cannot seem to solve the saving a file part along with the SD shield

I have wrote my code but can seem to implement the shield along with my code, I want to store my data onto a file on the SD card. I've reviewed the example provided in the library's but it won't work for me

My code is;

#define redled 10
#define greenled 11
#define echoPin 12
#define trigPin 13

unsigned long interval=60000; //interval = 60 seconds
unsigned long previoustime=0;
int minutes = 0; //global variables

void setup() {
  Serial.begin (9600); //Set Baud rate to 9600 to match serial monitor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenled, OUTPUT);
  pinMode(redled, OUTPUT);
}

void loop() {
 //-----------------------------------------------------------
  unsigned long currenttime = millis(); //counts time in milliseconds and puts it into current time
  if ((currenttime-previoustime) >= interval) { //When time is greater 60 seconds
    previoustime = currenttime; //Make the previous time equalled to the minute to take away in the next if statement        **Time since start section**
    minutes = minutes + 1; //Add 1 minute
  }
  unsigned long time = (currenttime-previoustime) / 1000; //converts the milliseconds to seconds
  //-----------------------------------------------------------
  long distance = ultra_sensor(); //call function that now returns the distance
  //-----------------------------------------------------------
  if (distance < 4) {            // If distance is less than 4cm
    digitalWrite(redled,HIGH);   // Turn on Red LED
    digitalWrite(greenled,LOW);  // Turn off Green LED
  }
  else {                          //If distance is greater than 4cm
    digitalWrite(redled,LOW);     // Turn off Red LED
    digitalWrite(greenled,HIGH);  // Turn on Green LED
  }
  //-----------------------------------------------------------
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.print("cm");
    Serial.print(" after ");
    Serial.print(minutes);              //Printing distance and time to serial monitor
    Serial.print(" minutes ");
    Serial.print("and ");
    Serial.print(time);
    Serial.println(" seconds");
  }
  //-----------------------------------------------------------
  delay(2000); //Get reading every 2 seconds
}

long ultra_sensor() { //Ultrasonic sensor reading is now a function. More efficient
  digitalWrite(trigPin, LOW);  //Set Trigger to idle
  delayMicroseconds(2); //Wait 2 microseconds
  digitalWrite(trigPin, HIGH); //Set Trigger to high which sends out a wave
  delayMicroseconds(10); //Send the wave for 10 microseconds
  digitalWrite(trigPin, LOW); //Turn the trigger to idle
  long duration = pulseIn(echoPin, HIGH); //make duration the wave that echo recieves back
  long dis = (duration/2) / 29.1; //divide by 2 for going there and back.                         ***Speed of sound***
  return dis; //Send the distance to function call
}

Looks like your sketch (pin usage) is in conflict with the SD shield (SPI pins). Try using other pins.


Arduino analog pins not working I am having a problem with pins of Arduino Uno. I have connected a LED to one of the analog pins (A0), and I want to light up the LED with different intensinty.

int ledPin = A0;
void setup() {
 // put your setup code here, to run once:
 pinMode(ledPin,OUTPUT);

}

void loop() {
 // put your main code here, to run repeatedly:
 analogWrite(ledPin,500);
}

The point is that even if I change the value of analogWrite, the LED lights up always with the same intensity.

analogWrite deals with PWM pins, those are digital pins. See https://www.arduino.cc/en/Reference/AnalogWrite

So connect the LED to one of the PWM pins and change the sketch accordingly. On the Uno those are pins 3, 5, 6, 9, 10, and 11.

The analog pins A0 - A5 are input pins. The value is read using the analogRead(pin) function.


Arduino uno, VIN and 12 volts I have an arduino Uno with a motor shield attached I would like to drive 2 12 volt dc motors. Can I just attach a 12 volt power supply to the arduino Uno?

I ask because if I can attach a 12 volt power supply to the uno, I would like to also try and drive some leds from the Uno as well. I remember that the VIN jumper needs to be connected if connecting a power supply through the Arduino uno. There is also a pin labeled VIN.

If I can connect a 12 volt power supply to the arduino uno, can I power the leds from the vin pin.

Possibly. It depends exactly what it is you want to drive.

When you connect 12V to the barrel jack you get about 11.3V out of the VIN pin. This is because there is a diode in series with the barrel jack to protect against reverse polarity connections. This loses some voltage (could be as much as 0.7V).

Also that diode is rated at 1A maximum. So you can't drive anything that would need more than 1A (including the current needed by the Arduino and shield components).


Relationship between baud rate and the frequency of vibration read using ADXL I am doing a project using Arduino Uno and ADXL 345.
I am quite new to this and I came across this post  in the link" : https://www.sparkfun.com/tutorials/240. Here, a user had posted the below question in the forum.

"Im trying to use this accelerometer to test various frequencies of vibration on a cantilevered beam and I wanted to know what the maximum vibration frequency I could find with using this accelerometer, connected to a 16MHz processor, connected to my laptop. I’m mainly a mechanical person, but after doing some research I found the following: Accelerometer has a maximum of 3200Hz output data rate (so maximum frequency would be 1600Hz) Processor can execute 16,000,000 instructions/sec so this probably is okay Communication rate is 9600 bits/sec so in the program above we read at a minimum 6 bytes for each axis, so that’s 24 bits, leaving you able to read 9600/24 = 400 reads/sec resulting in a one to be capable of reading vibrations at 200Hz. If I bump up the baud rate to 115200, I should be able to then read 4800 times a second, thus measuring 2400Hz vibrations?"

But I do not see any replies to this question. I feel the above analysis mostly makes sense. It would be helpful if someone could confirm that the above analysis is right. If not right , then why isn't it right?

Thanks

Firstly, the datasheet for the accelerometer suggests using >=2Mhz SPI communication rate with 3200 or 1600 Hz output data rate operation.

Since the Arduino SPI library default clock is 4Mhz, the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz.

So the Arduino and accelerometer can detect vibrations up to 1600Hz.

Next, you send the data to your laptop. At 9600 BAUD, you are correct in saying that since the data is 24 bits, it will only update your laptop with the Arduino's measured frequency at 9600/24 = 400 Hz. So 400 times a second the Arduino could tell the laptop what frequency it measures, the measurement having a maximum frequency of 1600 Hz.

For the Arduino to simply pass the raw data to the laptop at 3200 Hz, you would need 24 bits * 3200 Hz = 76800 BAUD minimum.

The measurement data is in any case limited by the accelerometer sampling rate of 3200Hz.


strtok keep original char I want to make a vocab program for an arduino. The vocabs are saved in a char array seperated with an '/'. Now I want to split a random picked char and split it at the '/' so I can save it into two variables. But if I do it with strtok the original string gets sacrificed. If now the same vocab comes again...

I hope you can help me, but if you think a other way to do it would be better I'm open for suggestions.
Here's my code

long random1, random2, random3, random4;
int lengtharray = 5;
char* vocab1;
char* vocab2;
char* vocab3;
char* vocab4;
char* german1;
char* english1;
char vocabs[5][16] = {"Apfel/apple","er/he","Zoo/zoo","sie/she","Hallo/hello"};

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

void loop() {
randomSeed(analogRead(0));
random1 = random(0,lengtharray);
randomSeed(analogRead(0));
random2 = random(0,lengtharray);
while(random2 == random1){
    randomSeed(analogRead(0));
    random2 = random(0,lengtharray);
}
randomSeed(analogRead(0));
random3 = random(0,lengtharray);
while(random3 == random1 || random3 == random2){
    randomSeed(analogRead(0));
    random3 = random(0,lengtharray);
}
randomSeed(analogRead(0));
random4 = random(0,lengtharray);
while(random4 == random1 || random4 == random2 || random4 == random3){
    randomSeed(analogRead(0));
    random4 = random(0,lengtharray);
}

vocab1 = vocabs[random1];
vocab2 = vocabs[random2];
vocab3 = vocabs[random3];
vocab4 = vocabs[random4];

Serial.println(vocab1);
Serial.println(vocab2);
Serial.println(vocab3);
Serial.println(vocab4);
Serial.println("//");
delay(1000);

german1 = strtok(vocab1,"/");
english1 = strtok(NULL,"/");
Serial.println(german1);
Serial.println(english1);
}

Make a buffer large enough to hold the largest of the word-pairs. Copy the selected pair into the buffer and run strtok() in that buffer. Strtok will damage the buffer contents but that is a throw-away; the original word-pair string is still unchanged.


ATmega328p hangs on USART RX interrupt I was able to use USART without interrupt driven and it worked perfectly! However, when I tried adding interrupt on USART_RX_vect, the program does not work as expected anymore.

Below is my small program. The expected behavior of this program is everytime I press a button the LED should toggle its state, but also by default the LED will toggle its state every 500ms. Right now, the LED toggles every 500ms but
 the moment I press a button on my machine keyboard to send data to the ATmega328p, the program stops (the led freezes on its last state).

I am not using an external clock, but I wonder if that could be the problem or I am missing something in my code that I can't figure out.

I appreciate any help. Thank you.

#ifndef F_CPU
#define F_CPU 1000000UL
#endif

#define FOSC F_CPU
#define BAUD 4800
#define MYUBRR FOSC/16/BAUD-1

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

void USART_Init(unsigned int ubrr) {
   UBRR0H = (unsigned char)(ubrr>>8);
   UBRR0L = (unsigned char)ubrr;
   UCSR0B = (1<<RXEN0) | (1<<RXCIE0);
   UCSR0C |= (1<<UCSZ00 | (1 << UCSZ01));
}

IRS(USART_RX_vect) {
    PORTC ^= (1 << PC5);
}

int main(void) {
    USART_Init(MYUBRR);
    DDRC |= (1 << PC5);
    sei();
    while(1) {
        PORTC ^= (1 << PC5);
        _delay_ms(500);
    }
    return 0;
}

Edit#1: I modified IRS handler:
Code:

IRS(USART_RX_vect) {
    while(!(UCSR0A&(1<<RXC0))){};
    unsigned char received = UDR0;
    PORTC ^= (1 << PC5);
}

Status: Program does not work.

Edit#2: Fixed typo ISR instead of IRS (pffff)

Solution: I was missing the code for consuming the RX buffer and I had a typo: IRS should be ISR. Thanks for @Edgar Bonet and @Majenko for the help!

I suspect if you were a fly you would see your LED flashing very very rapidly.

The reason is, your interrupt will constantly trigger itself over and over and over again.

Why? Because you aren't reading the incoming character from the RX buffer. And until you do the chip will keep alerting you that there is something there to read by triggering the interrupt.


ATtiny85 minimum setup to blink led What would be the (very) minimum schematic to make a ATtiny85 blink a led?

Restrictions are:

There must be a C program compiled and uploaded to it, just like an Arduino board would have. The code would use a simple "delay" to wait a little bit before changing the LED state.
The LED must be controlled by a "digital output port" just like an Arduino board would be.

This is the main question. Although I thought to ask a similar question with the restriction of "blinking exactly once per second", that would change completely the schema (not being a MINIMAL after all). So lets restrain to the main question. Maybe some day we can discuss the version 2.0!

This schematic shows a complete connection of a blinking led.

Red cable = +5V (pin 8)
White cable = Ground (pin 4)
Resistor = 1 end at pin 5 (IO 0) and the other in the LED anode (+)
Led anode (+) in the resistor, cathode (-) (small leg) in the ground
Resistor = 330 Ohms

The arduino in the picture is not necessary, just used to give power. But in the video linked below its used to burn the ATtiny85. The resistor can be a 330 ohms for a simple project like this.

Youtube Video with a simple explanation

I hope this explanation will enlighten who wants to start on it.

--

Edited:

If you want to record your ATtiny85 using Arduino UNO as ISP, then you will also need:

10 uF electrolytic capacitor

Here a picture of the pins:


esp32 http client response only 200 didn't receive the data after that i am using esp32 as a client and using following example. So here i am getting header response only that is 200. I am not getting any response after that. here is the example
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "yourNetworkName";
const char* password =  "yourPassword";

void setup() {

  Serial.begin(115200);
  delay(4000);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

}

void loop() {

  if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status

    HTTPClient http;

    http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request

    if (httpCode > 0) { //Check for the returning code

        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }

    else {
      Serial.println("Error on HTTP request");
    }

    http.end(); //Free the resources
  }

  delay(10000);

}

given url works with me as well. but if i give other url then i am getting response as 200 only. but not receiving json data which is present on the request url.

A 200 response doesn't guarantee that your payload will actually contain any data. It depends on the server. The server might determine to respond with a 200 code but still not return any JSON code for your request.
I am not at all sure, but the server may be rejecting your request because it doesn't like your user agent. I have seen my own ESP8266 supply ESP8266HTTPClient as its user agent for HTTP requests. You can see from the source code of the HttpClient class that this is the default:
HTTPClient::HTTPClient()
    : _client(nullptr), _userAgent(F("ESP8266HTTPClient"))
{
// etc...
}

You might consider setting the user agent for your http client object:
http.setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0");

If you'd like to investigate a bit more, you might use curl from the command line (this works on linux) to emulate the http request being formulated by your ESP device:
curl -vA "ESP8266HTTPClient" http://jsonplaceholder.typicode.com/comments?id=10

On my linux machine, this returns all the HTTP header information, followed by some JSON for the url you've specified in your code:
[
  {
    "postId": 2,
    "id": 10,
    "name": "eaque et deleniti atque tenetur ut quo ut",
    "email": "REDACTED@EXAMPLE.COM",
    "body": "voluptate iusto quis nobis reprehenderit ipsum amet nulla\nquia quas dolores velit et non\naut quia necessitatibus\nnostrum quaerat nulla et accusamus nisi facilis"
  }
]

Maybe try that with the other url and see what comes out?
You might also modify your post with the Serial output of your sketch to provide more detail.


OBOE: Need help understanding, possible type conversion issue I have an algorithm that its main purpose is decoding, converting, or what have you a string of uppercase letters (A-Z) into a number. This is almost like converting a base 26 number into base 10, however I believe that a base 26 number encoded would actually include numbers, I am working strictly with uppercase letters, I digress.

I have an implantation working in C++11, in fact most of the controller algorithm was a direct copy, with a slight change to the indexOf method.

The C++11 version works as I expect it to. So initially I thought the new indexOf method was incorrect, but after a simple test, it is working as expected. I have narrowed down the problem to a line in the convertTo10 where I am calling the pow function.

As you can see from the Serial.println()'s in the convertTo10 method, the output is printing exactly what we expect, 0 & 26.

However, the output of this function is 25. WHAT?

I have read the docs on the pow method from the Arduino lib, and it takes in two floats and returns a double. Even if the issue was a type conversion issue, converting a double to an int truncates the number, it does not round it. Well, this is from working with C++.

Any help with this issue would be much appreciated.

#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <inttypes.h>

#include <Arduino.h>
#include <avr/pgmspace.h>
#include <Wire.h>

const char _values[26] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z'
};

const int _val_len = 26;

int indexOf(char needle);
int convertTo10(String value, int len);

String x = "BA";
int len = 2;

void loop() {
  Serial.print(x);
  Serial.print("=> ");
  Serial.println(convertTo10(x, 2));
  delay(50000);
}

int convertTo10(String value, int len) {
    int lastIndex = len - 1;
    double output = 0;
    int pos = 0;
    Serial.println();
    for (int i = lastIndex; i >= 0; i--) {
        int r = indexOf(value[i]);

        output += (r * pow((_val_len, pos));
        Serial.print("     output => ");
        Serial.println( output );
        pos++;
    }
    return output;
}

int indexOf(char needle) {

    int first = 0;
    int last = _val_len - 1;
    int mid;

  do {
    mid = (first + last) / 2;

    if (_values[mid] == needle)
      return mid;
    if (_values[mid] > needle)
      last = mid - 1;
    else
      first = mid + 1;
  } while (first <= last);

  return -1;
}

For Reference, Here what it is outputting:

BA =>
     output => 0.00
     output => 26.00
25

way too complicated:

int convertTo10(char *num_26, int len) {
  int tmp = 0;  //hold the output
  int i;  //indexing the input
  while (len--) tmp = tmp * 26 + (num_26[i++]-'A');
  return tmp;
}

note:
 1. "* 26" can be further simplified;

error checking could be built-in here, or somewhere else (better).
better structuring could get rid of one of the temporary variables.


why sound appears between VCC and GND pins in esp8266 module? When I use esp8266 as STATION mode and connect a speaker between VCC(3.3v) and GND pin a sound appears like "doop doop". what is this sound?
I test this in version 01 and 12 of esp8266 module and this appear in both versions.
maybe you ask me why I connect speaker to this pins. problem is that when I use pwm of esp8266 for playing a sound, this sound ("doop doop") appear to it also.
What is problem? How can I fix this?

It's called "noise" and is to be expected. Wi-Fi devices are generally very electrically noisy - and the ESP8266 is no exception.


How much voltage/current do I need for multiple chips? I have a Huzzah ESP826 Wifi breakout chip which requires 3.3V power voltage and peaks at 500mA of current, and an LED strip which requires 12V and 1A.  How can I power both with one dc jack (I have a 12V 5A power supply) on one breadboard?

You need a voltage regulator for the esp. Preferably a dc-dc step down, which will neither waste power nor heat up. Other, passive solutions are possible but not desirable. The regulator can be found on ebay amazon etc.

EDIT:

One more thing about the LEDs: depending on the model you have, they might or might not work with 3.3V input (I'm assuming you want to drive the LEDs from the esp).

In case they take only 12V input, you will need some interface solution, like this one, for example.


Why does per-led current consumption diminishes when more leds are on? I'm rather new to Arduino. I've been performing some current consumption measurements lately, with a INA219 current sensor, on the blue LEDs from a starter kit.

I plugged three LEDs, on pins 2, 3, and 4 of my Arduino UNO, and wrote a simple script:

digitalWrite(led1, 1);
delay(2000);
digitalWrite(led2, 1);
delay(2000);
digitalWrite(led3, 1);
delay(2000);
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 0);

Which turns on the leds one by one, and finally turn them off at once.
I measured the current consumption of the first LED, and measured that:

When it's the only one on, LED 1 consumes ~23.5 mA
When the second one is on, LED 1 consumes ~21.7 mA
When the third one is on, LED 1 consumes ~20.2 mA

Could you please tell me why it behaves that way ? Is there any source I should read that would formalize that ?

Thank you

If using a constant voltage source it is advisable to use current limiting resistors in series with LEDs.

If these LEDs are different colors that may explain the different current readings.

Or, if all LEDs are of the same color and you are powering the project from a source with internal resistance (a battery), the more current you draw the lower the supply voltage.  This may show up as a reduced incremental current increase.

Or, if using a poor power source or operating at the current capacity of the power supply - again - this may show up as a reduced incremental current increase.

Note that different generations of LEDs operate at slightly different voltages.  But, in general, RED, GREEN & BLUE LEDs of the same generation operate at slightly increasing voltages respectively.  Details can be found here in this wikipedia.com page:

  Typically, the forward voltage of an LED is between 1.8 and 3.3 volts.
  It varies by the color of the LED. A red LED typically drops 1.8
  volts, but since both voltage drop and light frequency increase with
  band gap, a blue LED may drop from 3 to 3.3 volts.

Use the LED current (Iled) and voltage (Vled) specifications to determine the proper resistor value for a given supply voltage (Vbatt).

The following equation from this article should prove useful for this calculation:


I want to make mesh network with nodemcu (esp8266) in this all the nodemcu are in both mode receiving and transmitting, if i made 6 nodemcu connected with each other as mesh network to control home appliances, using mac address.  suggest how i will start to reach the destination.

there are libraries for this already, i have used this one, but i have not tested the mesh function yet


Why is this IIR Filter unstable on the Arduino Due? I am using an Accelerometer (on the MPU6050) and connected it to the Arduino Due. In order to filter the signal I am using an IIR Filter with the following transfer function:

H(z) = Y(z)/X(z) = B/A

B = 0.00000376 + 0.00001127*z^(-1) + 0.00001127*z^(-2) + 0.00000376*z^(-3)

A = 1 - 2.9372*z^(-1) + 2.8763*z^(-2) - 0.9391*z^(-3)

which is an IIR 3th Order Butterworth, Cutoff Freq: 0.5Hz, Samling Freq: 100Hz. These numbers can be calculated by any IIR calculator.

Thus, then discrete equation is:

y[n] = 0.00000376*x[n] + 0.00001127*x[n-1] + 0.00001127*x[n-2] + 0.00000376*x[n-3] + 2.9372*y[n-1] - 2.8763*y[n-2] + 0.9391*y[n-3]

I first tried it on the Arduino UNO. Then I found out that decimal point precision (float & double) on the UNO is only 6-7 digits. But the therm "B" in the transfer function has for example (0.00000376) 9 digits. I thought this is the porblem, so I switched to Arduino Due and now I am using double (instead of float) which should have enough precision.

It is still unstable. It is not oscillating but getting bigger. I also tried an IIR 4th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz. This one is oscillating.

However, the only IIR that seems to be stable is an IIR 3th Order Butterworth, Cutoff Freq: 1Hz, Samling Freq: 100Hz.

I have no idea so far what the problem is. Could anyone help please?

The precision of a float is about 7 significant digits. The
constant term of B in your transfer function (0.00000376) has only 3
significant digits.
Your transfer function has a pole at z = 1. It is thus not really
stable, but only marginally stable. Any parasite DC component in
the input will make the output drift without bounds.

It seems to me that your problem is not related to the implementation of
the filter on the Arduino, but rather to the filter design. Where did
you get that transfer function from?

Edit: I looked at the filter you are trying to make. It turns out it
is very sensitive to the precision of the coefficients of A(z). If you
try to add these coefficients, they almost cancel out: their sum is
about 3e-5. At zero frequency, both A and B are 3e-5, and the transfer
function, which is their ratio, is 1. By rounding the coefficients to
four decimal places, you made the cancellation exact, and the transfer
function infinite.

Just write the transfer function with more decimal places in the
coefficients and it should work:

H(z) = 3.75592×10−6 (1 + 3 z−1 + 3 z−2 + z−3)
         ÷ (1 − 2.9371759 z−1 + 2.8763097 z−2 − 0.9391038 z−3)


Is it possible to run Python embedded in Arduino? I know how to program in C but I'm more productive in python, so, I would like to know if there is a way to run a python code into arduino.

You can use other kind of board called MicroPython

But yes, is possible using some kind of TX-RX Python class...


What is the purpose of the howMany integer in the wire.onReceive() function from the example code? In the master write/ slave read example for the wire library, there is an integer declared howMany that is never used.

 void setup() {
   Wire.begin(8);                // join i2c bus with address #8
   Wire.onReceive(receiveEvent); // register event
   Serial.begin(9600);           // start serial for output
}

void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
   char c = Wire.read(); // receive byte as a character
   Serial.print(c);         // print the character
}
 int x = Wire.read();    // receive byte as an integer
 Serial.println(x);
}

As the function does not work without it, i would like to know what is its exact purpose.I would imagine that is something regarding the buffer size.

It tells you how many bytes have been received, and consequently how many you can read with Wire.read().

Before you have read anything with Wire.read() Wire.available() will return the same value.  As you read from the buffer Wire.available() will decrease, but howMany will stay the same.


Bootloader on Atmega328p overwrites whenever it gets programmed I built my first custom circuit board with an Atmel ATMega328p-AU the tqfp-32 form factor. I connected xtal1 and xtal2 to an external 16mhz crystal to 22pf caps tied to ground. It seems to work great, I load the Arduino Bootloader using AVRDude and an arduino as an isp. As soon as I load a sketch on using the ftdi it blows out the bootloader and I can't upload a new sketch until reloading the bootloader. The sketch works as expected, my board has an on board relay and an onboard mosfet I've programmed various blink patterns on both the mosfet and relay.I just don't want to have to reload the bootloader everytime I want to make a change, my sketch is an evolving piece of work and it's frustratinf to take these steps. So far I've tried changing the lock bits to 0x0F 0xEF 0xFF and 0X2F. I've tried various fuse bits, I've changed the signature 0x1e 0x95 0x14 to 0x1e 0x95 0x0F. Nothing seems to change the results, the only thing I've managed to do is one upload caused the chip to run at 8mhz instead of 16mhz, oops. That was easily fixed though. Please if someone can help that would be great, unfortunately the fuse bit calculators I have found don't have the 16mhz crystal as an option even though it's clearly functional.

In Summary

Sketches overwrite my bootloader and I want my bootloader locked but I can't find a solution after nearly a full day of googling and experimenting

Almost certainly your fuses are wrong. The fuses tells it whether or not to run the bootloader. With an empty PROGMEM (ie. no sketch) the processor probably skips over all the 0xFF bytes until it hits the bootloader. Once you have a sketch there it will run the sketch.

On my Uno (which is an Atmega328P) running at 16 MHz from a crystal, my fuses are:

Low = FF High = DE Ext = FD Lock = EF

I suggest you visit http://www.engbedded.com/fusecalc to work out fuse settings.

You want the BOOTRST fuse set (that is, the high fuse should be 0xDE or something with the low-order bit clear). On the AVR chips, having a bit clear (0) means the fuse is set.

I have a bootloader programmer sketch which not only puts the bootloader there, it sets the correct fuse bit.

I also have a chip detector sketch which will tell you the current fuse settings.


Does Nano not get sufficient power via USB? I have an Uno, and I can play all I want with it, just using a USB cable.

Then I got two Nano clones, and they both show the same behavior:

When I connect it to the USB cable (which leads to my PC) it blinks a few times, then seemingly does nothing. I am also not able to connect to it via the Arduino IDE.

If I then connect an external power source to Vin and Gnd, it wakes up and blinks forever, and I am able to connect to it.

Is this just because I got a cheap clone? Or is this really the accepted / expected behavior?

I have a few clones but have not seen this behaviour so I guess it could be one of three things (in order of most likely to least):

They have a fault related to taking power from the USB connector.
The USB lead is not able to supply enough power ie. it is cheap and extremely thin and cannot carry much current. Have you already tried other cables?
Your USB port cannot supply enough power. Given that the spec says 500mA from a USB 2 port, this seems unlikely unless the port is faulty. Have you tried other ports / another PC?


What power supply should I use? I am building a robotic arm using 8 servo motors. I am wondering about what voltage my external power will need to be to control all of them at 6v. I am wanting to use a rechargeable battery.

I am wondering about what voltage my external power will need to be to control all of them at 6v

Well that would be 6V then wouldn't it?

You're asking the wrong question. The question you should be asking is:

  How much current will I need from my 6V power supply?

And the answer is:

Add up the total current required by all of the devices and that is the minimum current the PSU has to provide

On top of that you need to consider how long the supply should last. The average current need to draw from the batteries, multiplied by the number of hours you need it to run for, is the minimum capacity of battery you need.

For instance, if you need to draw an average of 500mA for 6 hours then you need (0.5*6 =) 3Ah (or 3000mAh) batteries (or better).


eval() function for Arduino? I plan to do the following:

void setup(){
  String term = "12 + (2 * 5)";
  int result = eval(term); // eval function (from Python)
  Serial.println(result); // expecting 22
}

However there is no eval function. Are there any alternatives?

TinyExpr does what you want, and more.

TinyExpr is a very small recursive descent parser and evaluation engine for math expressions. It's handy when you want to add the ability to evaluation math expressions at runtime without adding a bunch of cruft to you project.
In addition to the standard math operators and precedence, TinyExpr also supports the standard C math functions and runtime binding of variables.

Your example
You'd just need to save tinyexpr.h and tinyexpr.c next to your Sketch.
#include "tinyexpr.h"

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

void loop() {
  char term[] = "12 + (2 * 5)";
  Serial.println(term);
  int error;
  double result = te_interp(term, &error);
  if (error){
    Serial.println("Problem with expression.");
  } else {
    Serial.printf(" = %.10g\n", result);
  }
  delay(1000);
}

It outputs:
12 + (2 * 5)
 = 22

Since term is known at compile-time, this example is not very useful, and it simply outputs 22 in an endless loop.
Basic interactive console
If you use the input from Serial, you can write a very basic interactive console. A String has been used for conciseness, but this example could be rewritten with cstrings:
#include "tinyexpr.h"

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

void loop() {
  if (Serial.available() > 0) {
    String expression = Serial.readStringUntil('\n');
    Serial.print("> ");
    Serial.println(expression);

    int error;
    double result = te_interp(expression.c_str(), &error);

    if (error) {
      Serial.print(" ");
      for (int i = 0; i < error; i++) {
        Serial.print(" ");
      }
      Serial.println("↑");
      Serial.println("I didn't understand this part.");
    } else {
      Serial.printf(" = %.10g\n", result);
    }
  }

  delay(50);
}

TinyExpr knows the order of operations, and it understands many other mathematical expressions:
> 12 + 2 * 5
 = 22
> 3^5
 = 243
> exp(7)
 = 1096.633158
> (1 + sqrt(5)) / 2
 = 1.618033989
> 1 + 2 * 3 + 4 * 5
 = 27
> sin(pi/2)
 = 1
> sin(pi/3)
 = 0.8660254038

If there's a syntax error somewhere, error tells you the position of the first encountered error:
> 3 +
      ↑
I didn't understand this part.
> sin() * 5
      ↑
I didn't understand this part.
> 3 / (4 + 5 * 7
                ↑
I didn't understand this part.


MPU6050 acceleration values not 16-bit? I'm looking at the little code snippet from this (many other projects also use similar code):

void loop(){
 mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

 ax = map(ax, -17000, 17000, -1500, 1500);
 ...

If my reading is correct, it's assuming the value of ax to be between -17000 and 17000. But isn't the value supposed to be 16-bit? If so, shouldn't the range be wider than -17000, 17000? Is the value capped?

Any thought appreciated.

The ADC for the accelerometer is 16 bit, yes. Also the data being sent out is in 16 bit format.

But what you are confusing is resolution and range.

The accelerometer can be programmed to have a sensitivity of 2g, 4g, 8g or 16g.  With it set to the least sensitive, that is 2g, the full range of -32768 to +32767 would equate to ±2g.

That's fine when you're measuring G-forces of up to 2g, but when all you are sensing is tilt then there is only 1g - the 1g the Earth exerts on it.

That 1g is half the 2g range, which is -16384 to +16363.  So round that up and give a little extra headroom to your calculations, and you get -17000 to +17000. It gives enough range in your calculations to give the full ±1g range "plus a little bit".


Running Arduino with 2 outputs and 2 inputs Totally new to Arduino, 3 weeks old!
I am doing a project with 2 inputs (2 x ultrasonic sensors) and 2 outputs (buzzer and send SMS)
The code to run the buzzer and sms works perfectly individually. For the buzzer, it will stop buzzing after approx 5 seconds.
I would love them to run concurrently but it didn't work as planned when I upload the code on the board.
I've read on forums to use millis / blinkwithoutdelay but am unsure how I can incorporate those functions on my mode as the examples posted online are different from my project.
The following is the code I have created.
Would appreciate if I can get some help from the experienced folks here.
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

int ctn = 0;

void setup() {
  Serial.begin(9600); // Serial monitoring
  pinMode(TRIG, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {

  digitalWrite(TRIG, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);

  digitalWrite(TRIG, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG, LOW); // Send pin low again
  delayMicroseconds(2);

  digitalWrite(TRIG1, LOW); // Set the trigger pin to low for 2uS. Give a short LOW pulse beforehand to ensure a clean HIGH pulse
  delayMicroseconds(2);

  digitalWrite(TRIG1, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG1, LOW); // Send pin low again
  delayMicroseconds(2);

  int distance = pulseIn(ECHO, HIGH, 26000); // Read in times pulse
  int distance1 = pulseIn(ECHO1, HIGH, 26000); // Read in times pulse
  distance = distance/58;
  distance1 = distance1/58;

  if (distance < 25) {
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    /*Replace XXXXXXXXXX to 10 digit mobile number & ZZ to 2 digit country code*/
    Serial.print("AT+CMGS=\"+YYXXXX\"\r"); // YY is the country code XXX is the number
    delay(1000); //
    //The text of the message to be sent.
    Serial.print("HELLO There");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
  }
  else {}

  if (distance1 < 25 && ctn < 150) {
    ctn += 1;
    digitalWrite(Buzzerpin, HIGH);
  }
  else {
    digitalWrite(Buzzerpin, LOW);
  }

  if (distance1 > 25 && ctn >= 150) {
    ctn = 0;
    digitalWrite(Buzzerpin, HIGH);
  }
}

First thing: you should call pulseIn() right after sending the TRIG
pulse. If you wait too much, you will miss the start of the echo pulse.
For instance, here:
int distance = pulseIn(ECHO, HIGH, 26000);
int distance1 = pulseIn(ECHO1, HIGH, 26000);

the second pulseIn() is starting too late, because of the time taken
by the first one.
Next, the general approach for doing things is a non-blocking fashion
(and thus being able to handle concurrent tasks) is to program each task
in the form of a finite state machine. Combine this with the
timing technique used in the “Blink without delay” Arduino tutorial if
you need time-triggered actions.
Here I would use one state machine for sending the SMS and another one
for the buzzer. The first one is the most complex:
Edit: I expanded on how I designed this state machine.
In a canonical finite state machine implementation, each action is
associated with a state transition. We then have a transition for each
command sent to the GSM module, and we can label the states according to
which commands have already been sent, like this:
SENT_NOTHING → SENT_CR → SENT_CMGF → SENT_CMGS → SENT_MSG →
SENT_ALL.
All of the above transitions send a string to the GSM module. The first
one (SENT_NOTHING → SENT_CR) is triggered by the distance detected
being less than 25 cm. The following ones are time-triggered one
second after the previous one. We have to add one final transition
(SENT_ALL → SENT_NOTHING) that performs no action but lets the system
“forget” it has sent an SMS and thus makes it ready to send a new one.
This transition would also be time-triggered, after a potentially long
delay (how often would the user like to receive those reminders?). In
the code below, this last delay is one second, which I believe is too
short, but matches the last delay(1000) in the code you posted. The
implementation would be like this:
static enum {
  SENT_NOTHING, SENT_CR, SENT_CMGF, SENT_CMGS, SENT_MSG, SENT_ALL
} sms_state = SENT_NOTHING;
static uint32_t time_last_command_sent;
uint32_t now = millis();
switch (sms_state) {
  case SENT_NOTHING:
    if (distance < 25) {
      Serial.print("\r");
      time_last_command_sent = now;
      sms_state = SENT_CR;
    }
    break;
  case SENT_CR:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGF=1\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGF;
    }
    break;
  case SENT_CMGF:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGS=\"+YYXXXX\"\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGS;
    }
    break;
  // and so on for the cases SENT_CMGS and SENT_MSG...
  case SENT_ALL:
    if (now - time_last_command_sent >= 1000) {
      sms_state = SENT_NOTHING;  // forget we sent an SMS
    }
    break;
}

I have an issue with this implementation though: it is overly
repetitive, as the cases SENT_CR, SENT_CMGF, SENT_CMGS and SENT_MSG
are essentially copies of the same code. In order to make the code
dryer, I prefer merging them into a single state, and splitting
the state information into two variables: sms_state and
commands_sent. The new possible values for sms_state are now:

SMS_READY: the code is ready to send the message as soon as it is
required by the detected distance.
SMS_SENDING: it has started to send the commands to the GSM module,
but is not done yet.
SMS_DONE: the SMS has been sent, but no other one will be sent until
some time has elapsed, after which it will transition to SMS_READY.

The mapping to the “full” machine states is then:
 full state    │ sms_state   commands_sent
───────────────┼───────────────────────────
 SENT_NOTHING  │ SMS_READY         0
 SENT_CR       │ SMS_SENDING       1
 SENT_CMGF     │ SMS_SENDING       2
 SENT_CMGS     │ SMS_SENDING       3
 SENT_MSG      │ SMS_SENDING       4
 SENT_ALL      │ SMS_DONE          5

It could be argued that sms_state is redundant, as all the state
information is contained in commands_sent. I still wanted to keep
sms_state in order to easily switch on it. This is not the only
possible approach though, and it would be perfectly sensible to write
something like
if (commands_sent == 0) {
  // handle the case SMS_READY
} else if (commands_sent < command_count) {
  // handle the case SMS_SENDING
} else {
  // handle the case SMS_DONE
}

For the buzzer, there are only two states: BUZZER_OFF and BUZZER_ON.
The transitions are conditioned by the measured distance and, for the ON
→ OFF transition, also by the time it has been ON.
Here is my tentative, untested implementation of this approach:
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

// Commands to be sent to the GSM module.
const int command_count = 5;
const char * const commands[command_count] = {
  "\r",
  "AT+CMGF=1\r",
  "AT+CMGS=\"+YYXXXX\"\r",
  "HELLO There",
  "\x1a"
};

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT);
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {
  // Measure both distances.
  digitalWrite(TRIG, LOW);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG, LOW);
  int distance = pulseIn(ECHO, HIGH, 26000) / 58;
  digitalWrite(TRIG1, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG1, LOW);
  int distance1 = pulseIn(ECHO1, HIGH, 26000) / 58;

  // Timing for both state machines.
  uint32_t now = millis();

  // Send the SMS.
  static enum {SMS_READY, SMS_SENDING, SMS_DONE} sms_state;
  static uint32_t time_last_command_sent;
  static int commands_sent = 0;
  switch (sms_state) {
    case SMS_READY:
      if (distance < 25) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        sms_state = SMS_SENDING;
      }
      break;
    case SMS_SENDING:
      if (now - time_last_command_sent >= 1000) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        if (commands_sent >= command_count) {
          sms_state = SMS_DONE;
        }
      }
      break;
    case SMS_DONE:
      if (now - time_last_command_sent >= 1000) {
        commands_sent = 0;
        sms_state = SMS_READY;
      }
      break;
  }

  // Drive the buzzer.
  static enum {BUZZER_OFF, BUZZER_ON} buzzer_state;
  static uint32_t time_buzzer_started;
  if (buzzer_state == BUZZER_OFF && distance1 < 25) {
    digitalWrite(Buzzerpin, HIGH);
    buzzer_state = BUZZER_ON;
    time_buzzer_started = now;
  } else if (buzzer_state == BUZZER_ON && distance1 >= 25
             && now - time_buzzer_started >= 2000) {
    digitalWrite(Buzzerpin, LOW);
    buzzer_state = BUZZER_OFF;
  }
}


Regarding PGA bypass in ADS1262 I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

I have taken the reference of example given in this library.

I have interfaced protocentral-ads1262-32-bit-precision-adc-breakout-board with Arduino Ethernet Board.

In the example, I have put #define VREF 5 but it shows the double the input voltage in serial window and when I put VREF 2.5, it shows regular input voltage.

For input voltage range 0 to 5V (single signal), I need to bypass the PGA but I dont know how to do it.

When the input signal is more than 2.5V then it always give the 2.5V only. If the input signal is, say 4.86V then it should give 4.86V but its gives 2.5V.

I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

Look at the register map. it should allow you to by pass the pga.

  In the example, I have put #define VREF 5 but it shows the double the input voltage in serial window and when I put VREF 2.5, it shows regular input voltage.

Simple solution: divide the library's output by 2.

Right solution: the library likely doesn't support bipolar output. So re-write  your own.


Why a servo doesn`t move to angles properly I've got to do a project which uses a servo to drive a turntable.
How much I adjusted the angle, the servo seemed to shift every time it spinned. For instance, the 0 degree angle was getting a bit bigger. I think it is caused by the imprecise PWM control of the Arduino or the bad translation using, I think, the map() function.

Could you fix this issue in code, or the servo doesn't work properly. I observed that every servo (that I've tried) creates a buzzing noice for angles bigger than 170 degrees.

By the way, my code is:

#include

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

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

#define pos0 0
#define pos1 23
#define pos2 48
#define pos3 164

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

void loop() {
  for (pos = pos0; pos  pos0; pos -= 1) {
    myservo.write(pos);
    delay(30);
  }
  Serial.print("pos: ");
  Serial.println(pos);
  delay(5000);
}

Edit: Should I try with a more powerful Arduino, like the Mega, which I think will be the perfect option having more GPIO than the UNO.

Every servo is different, they can have varying specifications:

Angular speed
Rotation range
Stall Torque
Size
Gear material/quality

Servos will vary based on brand; in addition each servo is going to have some individual variance.  So one has to characterize the servo, and discover what the proper control values are. Once the control values are established these are used to initialize the library so angular control will be accurate.

  For instance, the 0 degree angle was getting a bit bigger

I have found that errors in repeatability, like this, are usually found in the mechanism the servo is driving, especially the connection between the servo and the driven mechanisms. Check the connection for slop, see if everything is tightened properly.

  I observed that every servo (that I've tried) creates a buzzing noice for angles bigger than 170 degrees.

The typical maximum range of a servo is 160-190 degrees of rotation. The noise you are hearing is the servo trying to drive the motor to set the angle, but it is stalled as it can't turn that far.

  Should I try with a more powerful Arduino, like the Mega, which I think will be the perfect option having more GPIO than the UNO.

IIRC the servo library can control 12 servos with a basic Arduino, and 48 with the MEGA. This difference is more than just pin count, the MEGA has 4x the hardware timers of the 328p; 12 x 4 = 48

If you need more features you can move to the MEGA, i.e. you need more PWM channels, and the servo library reduces PWM pins from 6 to 4 on the 328p. Another example could needing more timers.

Read the Arduino Servo examples for more information on usage of the servo library and control of servos, etc.


POE with Arduino Leonardo Eth I recently purchased a Leonardo Eth and a 5v POE module in an attempt to have a POE micro-controller.  I installed the module in the holes closest to the Ethernet jack side of the board, but when I apply power, the green power light turns on every second or so, but never fully turns on.

What am I doing wrong? Did I install the module wrong? Is it the wrong module?

From the arduino.cc website.

"The optional PoE module is designed to extract power from a conventional twisted pair Category 5 Ethernet cable. PoE module features are as follows: IEEE802.3af compliant Input voltage range 36V to 57V Overload and short-circuit protection 12V Output High efficiency DC/DC converter: typ 85% @ 80% load 1500V isolation (input to output)"

It sounds like you need the 12V PoE module


Making Servo Motor Automatically Move Based on Input sorry if I sound incompetent, but I know nothing about coding. I have a group project where I must sort various balls into different tracks. The final issue I have is that I must use an arduino for this portion. However, none of us know how to program, and the only experience we have is from doing the lessons from adafruit (copy and paste written code).

What I am attempting to do is attach a paddle to the tip of a high torque servo motor. I will then automatically feed the servo signals, ranging from 0 to 5. Each signal tells which position for the servo to turn to. Could anyone please help guide me in how to write this code? I was thinking of using
this guide for my motor. However it uses a POT. My project must be completely automated. The positons also are all within 180*.

Thank you!

So you have a "number" and you want to set the servo to some angle. The logic is very simple:

If number is 0 then set angle to 90
If number is 1 then set angle to 45

etc.

How you "get" the number hasn't been specified, so I will assume you just have an integer with a value between 0 and 5 inclusive.

Setting a servo's angle is as simple as writing that angle to the servo:

servo.write(45); // Set the angle to 45 degrees

So how do you join the two together?  Well, there's three different ways that spring to mind.

A string of if statements
A switch construct
An array

The first one is just like the bullet points above, just written as C:

if (number == 0) servo.write(90);
if (number == 1) servo.write(45);
... etc ...

The second method is very similar but can be more efficient when you know you only ever select one item from a list of options.  Read this to see how: http://hacking.majenko.co.uk/time-to-make-a-switch

The third option, the array, is especially good when you have a lot of options to manage and they are all the same result with a different value:

const int angles[6] = {90, 45, 315, 0, 0, 0};

// ... later ...
servo.write(angles[number]);


"Bad request" error (HTTP) while posting to PHP server using Arduino and ESP8266 I'm doing an IoT project where the temperature and humidity values from a DHT11 sensor is sent to a PHP server using HTTP post. When I run the Arduino, the Serial Monitor says "Bad request". The sensor values are not appearing on the webpage. Please, help me figure out the problem. I am using an Arduino Uno with and an ESP-01.

// Code to use SoftwareSerial
//The final sketch
#include "SoftwareSerial.h"
#include <dht.h>

#define dht_dpin 8

String data;
String ssid = "TRAK family";

String password = "rukman12345";

SoftwareSerial espSerial(6, 7); // RX, TX

dht DHT;

float t;
float h;

String server = "svce-ece-b.000webhostapp.com";

String uri = "esp.php";

boolean DEBUG = true;

void showResponse(int waitTime)
{
    long t = millis();
    char c;
    while (t + waitTime > millis()) {
        if (espSerial.available()) {
            c = espSerial.read();
            if (DEBUG)
                Serial.print(c);
        }
    }
}

void setup()
{
    DEBUG = true;

    Serial.begin(115200);
    delay(500);

    espSerial.begin(115200);

    espSerial.println("AT+RST");
    showResponse(1000);

    // espSerial.println("CIOBAUD=9600");
    // showResponse(1000);

    espSerial.println("AT+CWMODE=1");
    showResponse(1000);

    espSerial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
    showResponse(5000);

    if (DEBUG)
        Serial.println("Setup completed");
}

void httppost()
{
    espSerial.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");

    if (espSerial.find("OK")) {
        Serial.println("TCP connection ready");
    }
    delay(1000);

    String postRequest =
        "POST " + uri + " HTTP/1.0\r\n" +
        "Host: " + server + "\r\n" +
        "Accept: *" + "/" + "*\r\n" +
        "Content-Length: " + data.length() + "\r\n" +
        "Content-Type: application/x-www-form-urlencoded\r\n" +
        "\r\n" + data;

    String sendCmd = "AT+CIPSEND=";
    espSerial.print(sendCmd);
    espSerial.println(postRequest.length());

    delay(500);

    if (espSerial.find(">")) {
        Serial.println("Sending..");
        espSerial.print(postRequest);

        if (espSerial.find("SEND OK")) {
            Serial.println("Packet sent");
            while (espSerial.available()) {
                String tmpResp = espSerial.readString();
                Serial.println(tmpResp);
            }

            // close the connection
            espSerial.println("AT+CIPCLOSE");
        }
    }
}

void loop()
{
    // Read sensor values
    DHT.read11(dht_dpin);
    float t = DHT.temperature;
    float h = DHT.humidity;
    if (isnan(t) || isnan(h)) {
        if (DEBUG)
            Serial.println("Failed to read from DHT");
    }
    else {
        if (DEBUG)
            Serial.println("Temp=" + String(t) + " *C");
        if (DEBUG)
            Serial.println("Humidity=" + String(h) + " %");

        data = "temperature=" + String(t) + "&humidity=" + String(h);

        httppost();
    }

    delay(1000);
}

This is my PHP code:

<?php
    global $Temp;
    global $Humidity;
    if(isset($_POST['temperature'])){
        $Temp=$_POST["temperature"];
    }
    if(isset($_POST['humidity'])){
        $Humidity=$_POST["humidity"];
    }

    $Write="
Temperature : " .$Temp . " Celcius
" . "
Humidity : " .       $Humidity . " %
";
    file_put_contents('sensor.html',$Write);
?>

The URI path in the HTTP request must start with a /.

It should be:

String uri = "/esp.php";


Trying to run Timer1 in ATmega2560 with assembly I have a slight problem with Timer1 in arduino (ATmega2560) while coding it in assembly. I try to run the Timer1 in CTC mode - I configure everything well in my opinion, but the TCNT1 just doesn't increment each clock cycle, as it should. I checked the registers in Atmel Studio and everything seems okay, but maybe I forgot about something?

Here is the code

.ORG 0
jmp start

.ORG 0x22
call isr_toggle_PA0

.ORG 0x400
start:
LDI R16, HIGH(RAMEND)
OUT SPH, R16
LDI R16, LOW(RAMEND)
OUT SPL, R16 ; initialize stack pointer
clr r16

ldi r16, 0xff
out DDRA, r16 ; port A output
ldi r16, 0x00
out DDRD, r16 ; port D input
clr r16

ldi r20, 1<<OCIE1A
sts TIMSK1, r20 ; enable Timer1 A comapre match interrupt
sei

ldi r20, HIGH(25000)
sts OCR1AH, r20
ldi r20, LOW(25000)
sts OCR1AL, r20

ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20
ldi r20, 0
sts TCCR1C, r20

; --- start main
main:

inc r16
rjmp main
; --- end main

isr_toggle_PA0: // toggle bit on PA0
    ldi r16,0x00000001
    in r17, PORTA
    eor r17,r16
    out PORTA, r17
    reti

Thank you and have a good day :)

Here:

ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20

you are setting the bit WGM11 on TCCR1A. The timer then runs in mode 2 (PWM, Phase Correct, 9-bit) rather than mode 4 (CTC).


LinkNode D1 Serial stops working when using pinMode The following code works. I get an output in the console every second of "Hello" and then the analogValue of the photoresistor.

int greenLedPin = D1;
int yellowLedPin = D2;
int redLedPin = D3;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  Serial.begin(9600);
//  pinMode(greenLedPin, OUTPUT);
//  pinMode(yellowLedPin, OUTPUT);
//  pinMode(redLedPin, OUTPUT);
}

void loop() {
  analogValue = analogRead(lightSensorPin);
  Serial.println("Hello.");
  Serial.println(analogValue);
  delay(1000);
//  digitalWrite(greenLedPin, HIGH);
//  digitalWrite(yellowLedPin, HIGH);
//  digitalWrite(redLedPin, HIGH);
}

Now as soon as I uncomment the pinMode commands nothing shows up on the console.

int greenLedPin = D1;
int yellowLedPin = D2;
int redLedPin = D3;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  Serial.begin(9600);
  pinMode(greenLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
}

void loop() {
  analogValue = analogRead(lightSensorPin);
  Serial.println("Hello.");
  Serial.println(analogValue);
  delay(1000);
//  digitalWrite(greenLedPin, HIGH);
//  digitalWrite(yellowLedPin, HIGH);
//  digitalWrite(redLedPin, HIGH);
}

Any idea what might be going on?

Move int greenLedPin = D1; and int redLedPin = D3; to another pin, because D1 and D3 is Tx and Rx.

http://esp8266.github.io/Arduino/versions/2.0.0/doc/reference.html


Make phone call over 4G LTE I have used the SIM800L module in the past, but with Ting shutting down their 2G network, I have been looking for alternatives. I have a SIM7000A, but I can't seem to find a microphone or speaker pin. Can this make calls, or will I have to find something else? I am using an Arduino Mega.

The SIM7000 doesn't have a microphone or speaker pin.  Instead it provides a PCM interface to connect to an external CODEC chip.

As it says in the Hardware Design Manual:

  SIM7000 provides a PCM interface for external codec, which can be used in master mode with short sync and 16 bits linear format.

If you want to use it for phone calls then you will need a module that also incorporates said CODEC chip and all the associated circuitry to connect to a microphone and speaker.


How do I repeat a piece of code For a school assignment I need to make a LED blink on/of 3 times then stop.
Now I have come up with the following code:

I think it's ''clean'' enough for what it has to do, but I have a feeling that here must be a easier way to make the LED blink 3 times.

Question is: Is there a way to reapeat the part of code 3 times without copy&pasting it?

Here you can use a loop. a classic for loop in C++ looks like this

for (int i = 0; i < n; i++)
{
    // content in between these brackets
}

where n is the amount of times you want to loop

you can also instantiate the i before the loop.

int i;
for (i = 0; i < n; i++)
{
    //content here
}

The code below should work. Toy around with it and see what you get.

int ledPin = 13;
int delayPeriod = 500;

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

    for (int i = 0; i < 3; i++){
        digitalWrite(ledPin, HIGH);
        delay(delayPeriod);
        digitalWrite(ledPin, LOW);
        delay(delayPeriod);
    }

another approach you can do is using a while loop. These kinds of loops will loop until a given parameter has been met. In your case you want an LED to stop blinking after 3 times.

int start = 0;
int stop = 3;

while (start <= stop){
    //content here
}

While loops will continue to go as long as the parameter is true. This means something like while(1) will continue to run forever.


Wake Huzzah Feather ESP8266 With Reed Switch Forgive me if this is a really dumb question but I am new to IOT and hardware in general.

I have a Huzzah Feather ESP8266 and I am trying to make a bathroom occupancy sensor.  I am using a standard reed switch door sensor (example here).

Ultimately what I want this device to do is:

The plan is to wake the device from deep sleep when the door is closed, according to the documentation GPIO16 needs to be connected to RST to send a wake signal.
Once awoken check the reed switch and send a message to Azure IoT hub that says the bathroom is occupied if door is closed.
Put the device into deep sleep, waking every 30 seconds.
Every time the device wakes check the switch, once the door is opened I send a message to Azure that the bathroom is not occupied and then put into deepSleep(0) (i.e asleep until the door is closed again, then the process repeats)

Right now this all works but in the opposite. I can wake the device when the door is opened, the message sends successfully to Azure.

From my super limited understanding of this it seems like what I want to do should be possible.  I imagine I am missing something very simple, but I have hit a wall here.

I dont know how to make wiring diagrams so hopefully a description of my setup will suffice:

GPIO 16: Door sensor wire #2
RST: GPIO 16
GND: Door sensor wire #2

Simplified code sample:

void setup()
{
    initSerial(); //inits serial
    initWifi(); //initis wifi
    door_open(); //sends message
}

void door_open() {
  IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

  if (iotHubClientHandle == NULL)
  {
    Serial.print("Failed on IoTHubClient_LL_Create\r\n");
  }
  else
  {
    // Because it can poll "after 9 seconds" polls will happen
    // effectively at ~10 seconds.
    // Note that for scalabilty, the default value of minimumPollingTime
    // is 25 minutes. For more information, see:
    // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
    unsigned int minimumPollingTime = 9;

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
    {
      Serial.print("failure to set option \"MinimumPollingTime\"\r\n");
    }

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
    {
      Serial.printf("failure to set option \"TrustedCerts\"\r\n");
    }

    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, NULL) != IOTHUB_CLIENT_OK)
    {
      Serial.print("unable to IoTHubClient_SetMessageCallback\r\n");
    }

    IOTHUB_MESSAGE_HANDLE messageHandle;
    if(digitalRead(DOOR) == LOW)
    {
      messageHandle = IoTHubMessage_CreateFromString("closed");
      Serial.println("Door closed");
    }
    else
    {
      messageHandle = IoTHubMessage_CreateFromString("open");
      Serial.println("Door Open");
    }

    if (messageHandle == NULL)
    {
      Serial.print("unable to create a new IoTHubMessage\r\n");
    }
    else
    {
      MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);

      if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
      {
        Serial.print("failed to hand over the message to IoTHubClient");
      }
      else
      {
        Serial.print("IoTHubClient accepted the message for delivery\r\n");
      }
      IoTHubMessage_Destroy(messageHandle);
    }

    while (1)
    {
      IoTHubClient_LL_DoWork(iotHubClientHandle);
      ThreadAPI_Sleep(100);
    }
  }
}

To clarify:  Right now my device will wake when the door sensors magnetic parts are separated.  I want the device to wake when the circuit is complete (i.e the sensors are together).

The RST (reset) pin of the ESP works as the reset pin of any other microcontroller. If you pull it to LOW long enough (the threshold is surely listed in the datasheet), the whole microcontroller will reset as if you had cut and reestablished the power supply. So it will not wake it from sleep, but reset it completely.

It is correct, that you can use GPIO16 connected to RST, to let the ESP reset itself from a deep sleep. This seems to be an internal hardware functionality, that is distinct from the normal IO hardware. But you cannot use the same pin for some other functionality at the same time. Your reed switch is closed, if the door is closed. So it gives a LOW level to GPIO16 and RST, holding it in reset state. In this state no code is executed, thus you never get a message, that the door is closed. When you then open the door, the switch opens too. Since the RST pin isn't pulled to LOW anymore, the ESP can boot and execute your code. The door is open, so you get the corresponding message.

So you have to use a different pin for the reed switch.


ESP8266 crashes when trying to copy a string into a big char I'm trying to parse with tinyxml2 a modest XML (3.4kb) to retrieve some data.

My ESP8266 crashes every time I try to use the toCharArray method.

here's my code

// here I'm getting an http request
String payload = https.getString();

// checking the payload, it seems fine in console but I get some garbage characters when àèéùìò are printed
Serial.println(payload);

// Length (with one extra character for the null terminator)
int str_len = payload.length() + 1;

// Prepare the character array
char xml[str_len];

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here

the length of the string is something around 3900, which I'm not sure can fit this kind of array on this device. If it's the case, what will be a better strategy ?

As you can imagine I'm just starting with the c language :)

EDIT: https.getString().c_str() + less variables was the right way to save memory

Function local variable are created on the stack, and in the case of an ESP8266, the total size is limited to 4096 Bytes - so, 3900 for one variable is cutting it close.

I would recommend you either use malloc/free

int str_len = payload.length() + 1;

// Prepare the character array
char *xml = (char *) malloc(str_len);

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here
//
// when done, free the memory malloc'd

free(xml);

or, if you know an absolute maximum size for the string, e.g. 5000, make char xml[5001]; in the global scope


Wave file will not play with Teensy 3.5 I am attempting to play a wav file from an SD card using a Teensy 3.5. I am using this buzzer and I have the following code currently:
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

// GUItool: begin automatically generated code
AudioPlaySdWav           playSdWav1;     //xy=557,157
AudioOutputPWM           pwm1;           //xy=889,184
AudioConnection          patchCord1(playSdWav1, 0, pwm1, 0);
AudioConnection          patchCord2(playSdWav1, 1, pwm1, 0);
// GUItool: end automatically generated code

void setup() {
  // put your setup code here, to run once:
  Serial.begin(4800);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Play");
  playSdWav1.play("sound.wav");
  delay(100);
  while (playSdWav1.isPlaying()) {
    delay (100);
  }
}

I don't know which pin is supposed to be outputting the PWM signal. I tried searching "patchCord1" to see what the parameters for it are, but was unsuccessful. The code was generated by The Audio System Design Tool.
As for the hardware configuration, I am attempting to wire the I/O pin to various PWM pins (to check for output) with no success. I have GND to Analog Ground and VCC to 3.3V (250 mA max). This is according to this diagram.
Which PIN is the Teensy supposed to output the pulses to?
Edit:
I can get the buzzer to work by using manual PWM (analogWrite), so I know that it functions.

The documentation implies you have to combine pins 3 and 4.
Here is a circuit diagram:
https://www.pjrc.com/teensy/gui/img/pwmdualcircuit.jpg

Source:
https://www.pjrc.com/teensy/gui/?info=AudioOutputPWM


Help to delimit and read specific contents of incoming HTTP string I am sending strings to an Esp8266 via web browser.

The below code returns the following in serial monitor if I send in browser:

Send from browser to esp8266 - http://192.168.1.220/s1s2s3s4s5d1
Receive in Arduino Serial monitor - GET /s1s2s3s4s5d2 HTTP/1.1

How do i read only the contents s1s2s3s4s5d1  ? This content can vary in length, numbers could be double digits but alphabets will remain in between.

Please note I am still a novice.

// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

I have this

if (client.connected()) {
  if (client.available() && client.find(' ')) { // GET /fn HTTP/1.1
    char fn[20];
    int l = client.readBytesUntil(' ', fn, sizeof(fn));
    fn[l] = 0;
    while (client.read() != -1);
    Serial.println(fn);
    client.stop();
  }
}


Serial uart communication issues I know this isnt specific but could you suggest some causes for the following issue:

Mega2560 sends values to Raspi 3 and Raspi 3 receives prints them accordingly (arduino also prints out the values it sends). However, at every occasional instances, garbage data is printed on Raspi terminal while the right data is still printed on the serial monitor for Arduino for a baudrate of 115200 for both.

Any helpful suggestions would be appreciated

This answer will also be not so specific, but you can try:

Check all wiring (use a multimeter/analyzer)
Reduce the data rate
Find out if there is a pattern whenever garbage is created (depending on values?)
Check (if possible) for errors (overrun/parity)
Play with the parity setting/stop bits to see if it makes a difference


Get IR Signal and its strength Using an IR sensor, how can I get and decode signals from other IR devices? I've seen the IRRemote library and its forks, but it doesn't fulfill my second requirement which is that I need to be able to tell the signal strength of the IR signal.

In addition, do I have to use a higher-end TSOP module? Or could I just use one of these?

Thank you!

An IR signal is modulated. To understand the data you need to demodulate the signal. The simplest way is with an IR receiver module.  However they condition the signal into a digital signal - it's impossible (on the majority of modules) to get the signal strength.

The devices you link to are IR Photodiodes. They form the optical receiver portion of the IR modules. You need to couple them with some form of demodulating system - either in hardware or, if your MCU is powerful enough, in software.  However, you can get at the raw analog voltages that the photodiode generates to get a signal strength value.

So you have either an easy time of it but no signal strength, or signal strength but a very hard job of interfacing.

So why not take the best bits of both?  Use an IR module to demodulate the signal and give you the data, and next to it use a photodiode and op-amp (to boost the tiny signal) to give you the raw optical intensity?  Yes, it would cost you more, and the circuitry would be more complex, but it's really the only way that you can do it without using specialist modules.

But of course, it begs the question: why do you really want to get this kind of information? Of what use can it be? The "signal strength" is of little benefit since there are so many factors that influence it - incidence angle, distance, transmitter battery voltage, etc.


When does a pre/post increment occur? Editing here to clarify. The headline asks the question but the example given was not ideal. This was a more general Q than about the example code.

Compilers have sequence points, places where you can be assured that the equations have been evaluated etc and no lingering effects will occur: the compilation is stable. When I couldn't test the original example I went looking for theory, and came across SE/SO posts where there was some discussion about issues like:

   int a = 1;
   int b = a++ - a++ + a++;

What would you expect the values of a and b to be after this? It turns out it hinges on whether the arithmetic operators are sequence points. Apparently this was not well settled in early versions of C, and in other languages (like Java) the results may differ yet again.

I now understand that an expression like (item++ > max) contains no sequence points -- the > operator does not trigger evaluation, but assignment operators and some arithmetic operators do.

//================================

Original Q:

I've read several Qs here concerning x++ vs ++x but I don't see this specific case. I'm still something of a C novice here.

Do these two code fragments do the same thing?

  // assume itemNum == maxItem on entry

if (++itemNum > maxItem) itemNum = 0;

if (itemNum++ > maxItem) itemNum = 0;

I gather that when the increment takes effect depends on the occurrence a 'sequence point' but I don't know if the comparison creates such an inflection.

Both ++x and x++ increment the value of x. The difference is whether you evaluate the value of x in your expression (formula) before or after incrementing it.

int x1 = 0;
int y1 = 0;

int x2 = x1++; //Post-increment: Move current value of x1 (0) to x2, THEN increment x1
int y2 = ++y1; //Pre-increment: Increment y1. Then move the NEW value of y1 (1) to y2.

In the above, x2 will be 0, and y2 will be 1.

The same logic applies to your if expression. If you use pre-increment, your if statement makes its decision on the new value after incrementing it.

If you use post-increment, the if statement makes its decision based on the value before it's incremented.


TCP communication between Arduino client and server I'm currently trying to build an Arduino robot controlled via a wifi connection. I have an Arduino Mega running as a client and it successfully connects to the server on LAN via the Adafruit cc3000 wifi board. However instead of grabbing the contents of the JSON file and printing it to serial, I'm just getting a 100 continue response. While this means I'm doing something right, I don't know what to do next in order to grab the data I need. Do I need to get the 100 message then respond with the GET request, or is there a way that I can GET the data straight away?

Thank you all in advance. Here is the Arduino code I have so far:

#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include <stdlib.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ 3  // MUST be an interrupt pin!
#define ADAFRUIT_CC3000_VBAT 5 // Apparently these can be any two pins
#define ADAFRUIT_CC3000_CS 10  // But I wouldn't change these...
// Use hardware SPI for the remaining pins (On a Mega 2560, SCK = 52, MISO = 50, and MOSI = 51)
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2);

#define WLAN_SSID "VM540258-2G"
#define WLAN_PASS "XXXXXXXX"
#define WLAN_SECURITY WLAN_SEC_WPA2

String readString = String(100); //string for fetching data from address
uint32_t ip = 3232235523; // This translates into the ip address we need
                          // 323223552X; 192.168.0.X

void setup(){
  Serial.begin(115200); //Can also work at 9600

  //Initialise CC3000 module
  Serial.println(F("\nInitializing CC3000..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }
  //Connect to the Wireless Access Point
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP()) { //Obtain IP addeess
    delay(100);
  }

  while (! displayConnectionDetails())
  {
    delay(1000);
  }
}

void loop(){
  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

  if (client.connected()) {
    client.println("GET /project-test/state.json HTTP/1.0"); //Make a request for state.json
    client.println(""); //Mandatory blank line?
    if (client.available()){
      char c = client.read();
      Serial.print(c);
      //read char by char HTTP request
      if (readString.length() < 100) {
       //store characters to string
       readString += c;
      }
    }
  }
  //Once we have obtained the data, disconnect from the server
  client.close();
  Serial.println(readString);
  delay(1000);
}

bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

The initial JSON file I'm using contains the following:

{"speed_left":null,"speed_right":null,"direction_left":null,"direction_right":null}

And the serial output I get when I run the Sketch:

Initializing CC3000...
Started AP/SSID scan

Connecting to VM540258-2G...Waiting to connect...Connected!
Request DHCP

IP Addr: 192.168.0.7
Netmask: 255.255.255.0
Gateway: 192.168.0.1
DHCPsrv: 192.168.0.1
DNSserv: 192.168.0.1

Connect to 192.168.0.3:80
100

Connect to 192.168.0.3:80
100

ad infinitum

you are missing the HOST header in the request, so the server tell you to 100 CONTINUE you request.
Also yes, the final empty row IS mandatory

for example, to ask www.example.com/index.html

GET /index.html HTTP/1.1
Host: www.example.com


About possibility of implementing kalman filter on atmega32 I have searched on the internet on how to get Euler angels from IMU measurements,I found that kalman filter and mahony filter are used...kalman filter has a drawback of complex computations,but mahony has less computation,so mahony is preferred for 8 bit microcontroller,but accuracy of kalman is better than mahony,so my question is ,can we implement kalman filter with its complex computations on 8 bit microcontroller like atmega32

Sure, it can be done, and simply enough. Here is an implementation in C that could be easily adapted.

It won't be as fast as Mahoney, of course, but the calculations are possible. The question is, is it fast enough for your usage?


Turn RGB blinker via serial I have a BLUno bluetooth arduino based on uno.

the logic kind of works, I am connecting ok to the phone, getting and sending messages via blue tooth

but with the serial data, Im having problems using it, and with the logic.

I want to have the option to turn ON/OFF some RGB LEDs, the problem is that the state is sometimes erratic.

here the code

int redLED = 2;
int greenLED = 4;
int blueLED = 3;

static bool redRunning;
static bool greenRunning;
static bool blueRunning;
static bool freq = 34;

void setup() {
  Serial.begin(115200);               //initial the Serial
  Serial.write("started");

  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED, OUTPUT);

  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, HIGH);
  digitalWrite(blueLED, HIGH);

  redRunning = false;
  greenRunning = false;
  blueRunning = false;
  freq = false;
}

void loop()
{

  if (Serial.available() > 0)
  f{
String s = Serial.readStringUntil('\n');

//    String s = Serial.readStringUntil("#");   // Until CR (Carriage Return)
//    s.replace("#", "");
    Serial.println("s:" + s);

if (s == "red_ON")
{
  redRunning = true;
}

if (s == "red_OFF")
{
  redRunning = false;

}  if (s == "green_ON")
{
  greenRunning = true;

}  if (s == "green_OFF")
{
  greenRunning = false;

}  if (s == "blue_ON")
{
  blueRunning = true;

}  if (s == "blue_OFF")
{
  blueRunning = false;

}

 }

 //

  if (redRunning) {
//    Serial.println("redRunning");

digitalWrite(redLED, LOW);
delay(125);
digitalWrite(redLED, HIGH);
delay(125);
  }

  if (greenRunning) {
//    Serial.println("greenRunning");

digitalWrite(greenLED, LOW);
delay(125);
digitalWrite(greenLED, HIGH);
delay(125);
  }

  if (blueRunning) {
    //    Serial.println("blueRunning");

    digitalWrite(blueLED, LOW);
    delay(125);
      digitalWrite(blueLED, HIGH);
    delay(125);
  }

  if (!redRunning && !greenRunning && !blueRunning) {
    digitalWrite(redLED, HIGH);
    digitalWrite(greenLED, HIGH);
    digitalWrite(blueLED, HIGH);
  }

   }

So what is the proper way to handle state? so the LED stay blinking? but also can turn off all LEDs
also if I can turn LEDs combined, at the moment, I'm turning on one, then the other,

All these problems come from not understanding how to handle state internally, and manage changes that come via serial.

Here is some untested code that uses a non-blocking timer to flash the leds.

uint8_t redLED   = 2;
uint8_t greenLED = 4;
uint8_t blueLED  = 3;

static uint8_t redRunning   = HIGH;   // leds off at start
static uint8_t greenRunning = HIGH;
static uint8_t blueRunning  = HIGH;

// static bool freq = 34;             // not sure what this is

void setup() {
  Serial.begin(115200);               // initialize the Serial
  Serial.write("started");

  pinMode(redLED,   OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED,  OUTPUT);

  digitalWrite(redLED,   HIGH);       // leds off
  digitalWrite(greenLED, HIGH);
  digitalWrite(blueLED,  HIGH);

//freq     = false;
  tick     = false;                   // time interval signal
  ledState = false;                   // state of led display

  static uint32_t ledTicker = millis();
}

void loop() {

  if (millis() - ledTicker >= 125) {             // Once every 125 ms
    ledTicker = millis();
    tick = true;                                 // set the tick flag
    ledState = !ledState;                        // changes state at every tick
  }

  if (Serial.available() > 0) {
    String s = Serial.readStringUntil('\n');

//  String s = Serial.readStringUntil("#");      // Until CR (Carriage Return)
//  s.replace("#", "");
    Serial.println("s:" + s);

    if (s == "red_ON"   )  redRunning   = LOW ;  // sometimes, this format is easier to read
    if (s == "red_OFF"  )  redRunning   = HIGH;

    if (s == "green_ON" )  greenRunning = LOW ;
    if (s == "green_OFF")  greenRunning = HIGH;

    if (s == "blue_ON"  )  blueRunning  = LOW ;
    if (s == "blue_OFF" )  blueRunning  = HIGH;
  }

  //
  if (tick) {                                    // 125 ms passed, so update the leds
    tick = false;                                // reset tick so that leds change only once every tick

    if (ledState) {                              // state of leds at this tick
      digitalWrite(redLED  , redRunning  );
      digitalWrite(greenLED, greenRunning);
      digitalWrite(blueLED , blueRunning );
    }
    else {                                       // all off this time around
      digitalWrite(redLED  , HIGH);
      digitalWrite(greenLED, HIGH);
      digitalWrite(blueLED , HIGH);
    }
  }
}


Incorrect DateTime value constructed I'm working on alarm clock project using Arduino Nano (v 3.0, clone) and RTC module ZS-042 (containing DS3231 and EEPROM AT24C32).
The intention is to load the hours and minutes from EEPROM on start-up, use current date (to avoid zero-date problems) and compose DateTime object in order to utilize the TimeSpan object, making time calculations easier than using plain integer math. The issue is, the value in DateTime object seems not constructed correctly, although all the components used for its construction seem OK.
With the following code
/* Hardware definitions */
//RTC using I2C, pins 4,5
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;

#include <extEEPROM.h>
extEEPROM e2p(kbits_32, 1, 32, 0x57);

DateTime  alarm1Time;

void setup(){
  Wire.begin();
  rtc.begin();
  Serial.begin(115200);
  uint8_t e2pStatus = e2p.begin(extEEPROM::twiClock400kHz);      //go fast!
  DateTime t = rtc.now(); //get current time from RTC
  Serial.print("t.year: ");  Serial.print(t.year());
  Serial.print(" t.month: ");  Serial.print(t.month());
  Serial.print(" t.day: ");  Serial.println(t.day());
  alarm1Time = (t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);
  Serial.print("E2P : ");
  Serial.print(e2p.read(1));
  Serial.print(":");
  Serial.println(e2p.read(2));
  char buf1[] = "YYMMDD-hh:mm:ss";
  Serial.println(alarm1Time.toString(buf1));
}

I get on the serial monitor the following:
t.year: 2021 t.month: 1 t.day: 31
E2P : 7:15
060206-06:28:16

The date components (year, month, date) correspond to current date. As the bytes on address 1 and 2 in EEPROM read 7 and 15, I'd expect the Alarm1Time be 2021-01-31, 07:15, which isn't.
The output is constant, whatever the current date and the EEPROM stored time. Later in my code the alarm1Time parses into 6 hours and 28 minutes, in accordance with last line of the serial monitor output.
What could be (or better - where I'm) wrong? Thanks.
Libraries used:
RTClib (https://github.com/adafruit/RTClib)
extEEPROM (https://github.com/JChristensen/extEEPROM/blob/master/extEEPROM.h)

Here:
alarm1Time = (t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);

you are repeatedly using the comma operator, which essentially means
“discard all the values but the last one”. If you want to invoke the
DateTime constructor that takes these arguments, you should call it
explicitly:
alarm1Time = DateTime(t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);

or, better yet, you can declare and initialize alarm1Time at the same
time:
DateTime alarm1Time(t.year(),t.month(),t.day(),e2p.read(1),e2p.read(2),0);


digitalwrite with function parameter as parameter Firstly, excuse my poor English, this is not my native langage.
I'm trying to use an Arduino Uno to drive an 8 relay board from an MQTT Subscription. I ask for help because i'm some kind of beginner in arduino, i'm just a Linux addict.
The idea is to get a payload from PubSubclient and use it to manage relays.
For example, the payload '71' ask the relay 7 to turn on and '42' make the relay 4 to turn off.
All works fine until I wanted to write a function with two parameters : 'relay_number' and 'Action'
All parameters are received but the relay never goes up or down.
My code :
void callback(char* topic, byte* payload, unsigned int length) {

  Relay_Nb = (char)payload[0];
  Action = char(payload[1]);

  Serial.println(Relay_Nb);
  Serial.println(Action);

  RelayControl(Relay_Nb, Action);
}

void RelayControl(char Relay_Nb, char Action) {
  Serial.println(Relay_Nb);   // for debugging purpose
  Serial.println(Action);

  if ( Action == '0') {
    Serial.print("Bringing down Relay ");
    Serial.println(Relay_Nb);
    digitalWrite(Relay_Nb, LOW);
  } else if (Action == '1') {
    Serial.print("Bringing up Relay ");
    Serial.println(Relay_Nb);
    digitalWrite(Relay_Nb, HIGH);
  } else if (Action == '2') {
    // Relay temporisé (ouverture portail par ex)
    Serial.println("Bringing up, and down Relay ");
    digitalWrite(Relay_Nb, HIGH);
    delay(750);
    digitalWrite(Relay_Nb, LOW);
  }
}

I'm sure an old maker have the solution i'm searching for hours now.
Please help and don't hesitate to show me others ways.
Thanks.

You are sending the parameter Relay_Nb as a character, and then using it as an integer.
You need to turn the character into an integer - and the simplest way is to subtract the ASCII value of 0 from it:
Relay_Nb = payload[0] - '0';

But with that said, a note on how you have written your callback:

You aren't checking the data is valid.

You should really be doing, at the very least, the following:

Check that the length parameter is at least 2,
Check that the two data values are within the correct range for your function


I have just done this same code but not getting exact time as per Indian timezone...What thing should I add to get exact time? #include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/

static const int RXPin = 10, TXPin = 11;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup() {
  Serial.begin(115200);
  ss.begin(GPSBaud);
  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop() {
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();
  if (millis() > 5000 && gps.charsProcessed() < 10) {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo() {
  Serial.print(F("Location: "));
  if (gps.location.isValid()) {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid()) {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid()) {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  } else {
    Serial.print(F("INVALID"));
  }
  Serial.println();
}

Use NeoGPS instead of TinyGPS, it has time and date functions for timezone offsets.

Ref:
https://forum.arduino.cc/index.php?topic=473294.msg3237680#msg3237680