texts: Problem with sending a POST request using the WiFiEsp library

texts:
I'm using an ESP8266 version 1 with the WiFiEsp library to connect to WiFi, and that works just fine.

I'm setting up the device using the same code as in the example WebClientRepeating.

I need to send a POST request instead of a GET request, but I can't get it to work as I want. If I create my POST request like this, it works just fine:

if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println();

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

I get the response like this:

[WiFiEsp] Connecting to 192.168.10.137
Connecting...
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 19
ETag: W/"13-jSAaqMh5E3R94/b2aONzvg"
Date: Sun, 13 Nov 2016 10:20:58 GMT
Connection: close

{"temp":"Testdata"}

However, if I try to send some body data in the request it fails:

if (client.connect(server, 3005)) {
  Serial.println("Connecting...");

  // send the HTTP POST request
  client.println("POST /open/peripherals HTTP/1.1");
  client.println("Host: 192.168.10.137:3005");
  client.println("User-Agent: Arduino/1.0");
  client.println("Connection: close");
  client.println("Content-Type: application/x-www-form-urlencoded");
  client.println("Content-Length: 16");
  client.println();
  client.println("temperature=22.7");

  // note the time that the connection was made
  lastConnectionTime = millis();
}
else {
  // if you couldn't make a connection
  Serial.println("Connection failed");
}

Then the response from serial output is:

[WiFiEsp] Connecting to 192.168.10.137
Connecting...
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Data packet send error (1)
[WiFiEsp] Failed to write to socket 0
[WiFiEsp] Disconnecting  0

However, the POST request including the body is received by the Web server just fine, but the response sent to the Arduino I can't read because it shows me an error instead of a proper response. From my webserver the response for the POST call that works and the POST call that fails is the same.

Does anyone knows why this fails when I add Content-Type, Content-Length and some body data?

Thanks in advance!


texts: Arduino Uno - Can' get LCD Display work crrectly

texts:
I make an automatic light that's triggered from a Visitor Counter. I use an LCD to show the actual counter state. The LCD does not anly show the actual count but also the numbers before. For Example:

If the counter is actual 2, it blinks between 1 and 2.

This behavior does not occur in the original project where the correct number is shown.

Please, can I know why, and how to fix it? Thank you!

This is the code:

//Visitors Counter and Automatic Room Light
//Viral Science  www.youtube.com/c/viralscience

#include<LiquidCrystal.h>
LiquidCrystal lcd(13,12,11,10,9,8);

#define in 14
#define out 19
#define relay 2

int count=0;

void IN()
{
    count++;
    lcd.clear();
    lcd.print("Person In Room:");
    lcd.setCursor(0,1);
    lcd.print(count);
    delay(1000);
}

void OUT()
{
  count--;
    lcd.clear();
    lcd.print("Person In Room:");
    lcd.setCursor(0,1);
    lcd.print(count);
    delay(1000);
}

void setup()
{
  lcd.begin(16,2);
  lcd.print("Visitor Counter");
  delay(2000);
  pinMode(in, INPUT);
  pinMode(out, INPUT);
  pinMode(relay, OUTPUT);
  lcd.clear();
  lcd.print("Person In Room:");
  lcd.setCursor(0,1);
  lcd.print(count);
}

void loop()
{

  if(digitalRead(in))
  IN();
  if(digitalRead(out))
  OUT();

  if(count<=0)
  {
    lcd.clear();
    digitalWrite(relay, LOW);
    lcd.clear();
    lcd.print("Nobody In Room");
    lcd.setCursor(0,1);
    lcd.print("Light Is Off");
    delay(200);
  }

  else
    digitalWrite(relay, HIGH);

}


texts: Arduino Uno: how to increase distance of serial communication to PC

texts: Does Arduino Uno's serial communication to  PC has the same distance as USB communication? (if I'm not mistaken 5m) If it is, what are the options for me to be able to communicate from Arduino Uno to PC with a longer distance? Thank you for any help!


texts:
I am currently trying to learn about SPI and how it works on the Arduino. I want to wire a MAX7219 chip to it to drive an 8x8 LED matrix with. Normally, I would assume the wiring from Arduino to MAX7219 goes:

PIN 10 SS -> CS
PIN 11 MOSI -> DIN
PIN 13 SCK -> CLK

And indeed, this answer confirms my assumption.
However, after going through some other resources and guides I found some confusing and conflicting information about how the pins on the two devices should be connected.

For instance, the documentation that came with my Arduino kit has this schematic.

This tutorial I found has the same wiring.

Most surprisingly, this tutorial doesn't even use the SPI pins at all.

What perplexes me the most is the sentence

  The VCC and GND of the module go to the 5V and GND pins of the Arduino and the three other pins, DIN, CLK and CS go to any digital pin of the Arduino board.

Is this true? If yes, then what is the point of the SPI pins at all? Why are the pins wired in so many different configurations?
I am really confused by this.


texts: strtok() command with Serial communicaton

texts:
After i take char* variable from serial communication, i use strtok to split variables with " ". But when i do that it acts like there is " " after every character. i dont know why. How can i fix this ?

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  char* a = "The quick brown fox jumped over the lazy dog.";
  char* c = a3;
  char* b;
  b = strtok(c, " ");
  while(b != NULL){
        Serial.println(b);
        b = strtok(NULL, " ");
      }
}
void loop() {
}

outcome :

The
quick
brown
...

this parse code works perfectly. until i take it from serialports. Serial code here. like this :

..

#include <SoftwareSerial.h>
#define bRSerial 9600
#define bRmY 9600

char vD[45];
int i = 0;

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  Serial.begin(bRSerial);
  while (!Serial) {
    ;
  }
  mySerial.begin(bRmY);
}
void loop() {
if (mySerial.available()) {
    //Serial.write(mySerial.read());
    vD[i]=mySerial.read();
    i++;
    if(i=46){
      char* a = vD;
      char* b;

      b = strtok(a, " ");
      while(b != NULL){
        Serial.println(b);
        b = strtok(NULL, " ");
      }
      i=0;
    }
  }
}

...outcome

T
h
e
q
u
i
c
k
b
r
o
w
...

so isthere a way to fix this ? i need to get it from serial and parse with " ". THANK YOU SO MUCH.


texts: Can I use this board to control multiple vibration motors?

texts:
I am looking at this: https://learn.adafruit.com/16-channel-pwm-servo-driver

Although it’s meant for servos, I was wondering if I could use them to control vibration motors.

Motors like these: Diameter Flat Button Type 3V-4.5V Cellphone Micro Vibration Motor (Pack of 3) https://www.amazon.in/dp/B07CQXZBZD/ref=cm_sw_r_cp_tai_yzSvDb8V7JAF4

Any suggestions? I would like to control about 200 motors with minimal number of controllers.

Each motor should be controllable individually.


texts: How to allow cross-domain requests on ESP8266WebServer

texts:
I am using a Raspberry Pi running Chrome (handling the user interface) and connecting via ajax to an Arduino D1 compatible using the IP address as follows:

    $.ajax({
        type: "GET",
        url: "http://10.1.1.100/myfunc?id=5",
        error:  function(jqXHR, exception, response) {
                console.log(exception, response);

        etc...

I recently started getting this error (wonder why it didn't happen for the last two years):

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://10.1.1.100/myfunc?n=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I tried various things including setting the browser (Chrome) to --disable-web-security and various suggestions, here and here (and many more) but I can't seem to get it to work. Currently, I have:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);

void handleRoot() {
  server.send(200, "text/plain", "Root of WebServer!");
}

void setup() {
IPAddress ip(10.1.1.100);
IPAddress gateway(10.1.1.1);
IPAddress subnet(...);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
  // put your setup code here, to run once:
  WiFi.begin(ssid, password);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  server.on("/", handleRoot);

  server.on("/myfunc", [](){
    String message = "";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET)?"GET":"POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";
    for (uint8_t i=0; i<server.args(); i++){
      message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }
      String num = server.arg(0);

    server.send(200, "text/plain", message);
 });
  server.on("/myfunc", HTTP_OPTIONS, []() {
    server.sendHeader("Access-Control-Allow-Origin","*")
    server.send(204);
 });

  server.onNotFound(handleNotFound);
  server.begin();
}

void loop() {
  delay(1000);
  ...
  server.handleClient();
}

void handleNotFound(){
  String message = "Error!";
  server.send(404, "text/plain", message);
}

So what am I doing wrong? Also, one complication that might crop up later is that the domain from where I am calling this in ajax is https and from what I understand https and http are not compatible with cross-domain requests.

Any help is appreciated!


texts: How to program arduino due without arduino ide

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

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


texts: USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol

texts:
Arduino UNO is 5V, 16 MHz.

USB 1.1 Low Speed spec operate:

at 5V level - so we avoid to maintain voltage level
at 1.5 Mb/s - so we have 16/1.5 ~= 10 instructions per elementary protocol signal

Is it possible to make Arduino as slave USB device from UART lines connected to USB D+/D- interface with careful timing and assembler programming?

I doesn't familiar with ATmega328P pin I/O capabilities, may be them can't operate at 1.5 MHz so project isn't possible?

UPDATE I found V-USB library that:

implementation of a low-speed USB device for Atmel’s AVR® microcontrollers,
making it possible to build USB hardware with almost any AVR® microcontroller,
not requiring any additional chip.

Still dig into docs to realize possibilities.


texts: What would be the best way to sniff an established serial connection?

texts:
I am studying a system running a serial connection and looking not to intercept its packets, but merely to inspect the traffic as it passes.
Option 1
Hook the RX and TX wires to the RX of two serial channels on my Arduino. Read the messages sent in either direction separately. Don't know the baud rate so this might be experimental?
Option 2
Split the connection, absorb both sides of the break into a RX TX serial connection on the Arduino, and set up forwarding from each to the other while inspecting the content.
In either option I can see the need to inspect the connected wires and establish the highest observed baud rate to match to. In the second option until I inspect enough data to reliably get the baud rate, data will be lost unless it is buffered.
Has anyone got any experience with a situation like this?


texts: Adafruit motor shield 1 and Arduino Pro Mini

texts:
Can any one tell me how to connect Adafruit motor shield v 1.0 with Arduino Pro Mini 5v 8 Mhz. Motor shield uses which pins as I want to replace my Arduino UNO to Pro Mini and need re-wiring. Tried it using jumper cables but did not work. Please help...

Product page here
Manual here
Larger version of schematic here

Schematic:


texts: LCD 16x2 shows one line cut and the 7th column also cut

texts:
My 16x2 LCD shows one line cut and the 7th column also cut:

Applying pressure:


texts: How can I get the source files for Arduino libraries?

texts:
I've been looking for a while inside Arduino's files to find the core library. However, I haven't found them yet. Where on my hard drive can I obtain the core library files (.cpp and .h) necessary for all Arduino code?

Looking around on Google, I couldn't find a way to find the above files. I did see something about getting an .a file while Arduino is compiling, however, that isn't what I want. I want to browse the code and look at functions such as delay to see how they would react when given the values not expected. (i.e. Will my code stall if I use delay(-200); by not being to exit the loop, or will it create a black hole and disrupt the space-time continuum?)


texts:
I have a project and i need to convert string (contain numbers and letters) to array
String name = "s111, s222, bbbb,cccc ";

and i want
array[0] = s111;
array[1] = s222;
array[2] = bbbb;
array[3] = cccc;

here is the code :
 String name = "s111, s222, bbbb,cccc ";
 int array[50];
 int r=0,t=0;

 for(int i=0;i<name.length();i++){
      if(name.charAt(i) == ','){
          array[t] = name.substring(r,i);
          r = (i+1);
          t++;
         }
 for(int k=0 ;k<=t ;k++){
   Serial.println(array[k]);
  }

When I compile I get just zeros like :
array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;


texts: How can I initialize an array of objects in setup?

texts:
How can I declare an empty global array, to be initialized in setup?

What I would like to do is this:

#include <ResponsiveAnalogRead.h>

const size_t ANALOG_SIZE = 3;
const int ANALOG_PINS[ANALOG_SIZE] = {A0,A1,A2};
ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

void setup() {
  for(size_t i=0; i<ANALOG_SIZE; i++){
    analog_reads[i]=ResponsiveAnalogRead(ANALOG_PINS[i], true, 0.01);
  }
}

But the error I get is:

sketch_may29c:5: error: no matching function for call to 'ResponsiveAnalogRead::ResponsiveAnalogRead()'
 ResponsiveAnalogRead analog_reads[ANALOG_SIZE];

                                              ^

Is it impossible to declare an empty array of a given size?


texts:
My goal is to run a vibrating motor for specific time intervals. I am using the millis() function to successfully turn the motor on and off, but only if the intervalOn = intervalOff. The problem comes when I try to change the intervals to turn the motor on for e.g. 120 ms, then turn off for 200 ms etc. My code seems to cause AVR restart and my motor sometimes stays running. First I thought this is caused by insufficient decouple capacitor (I have 100 uF one) but when running the millis() code with one no-changing interval, it all works flawlessly...
Is there any other way to change the intervals?

The Vibrating() function gets called from the loop() whenever vibrEnabled = true

unsigned long interval = 0;
unsigned long previousMillis = 0;
int last = 120;
int pause = 200;

void Vibrating()
{
unsigned long currentMillis = millis();
static byte cyclesPassed = 0;

if((unsigned long)(currentMillis - previousMillis) >= interval)
{
    PORTC ^= (1<<PC1);//toggle motor

    if(interval != last) //this part causes the problem
        interval = last; //
    else                 //
        interval = pause;//

    cyclesPassed++;
    if(cyclesPassed == 8)//motor is on 4x
    {
    cyclesPassed = 0;
    vibrEnabled = false;
    }

    previousMillis = millis();
 }
}


texts:
I'm currently using google geolocation to get location data to one nodemcu and sending it through serial to another Arduino.
The serial command I'm getting right now is,

1.450187T103.824745

I'm using the following code to parse it.

 if (Serial.available())  {
    char c = Serial.read();  //gets one byte from serial buffer
    //if (c == '\n') {  //looks for end of data packet marker
    if (c == '\n') {
     // Serial.println(readString); //prints string to serial port out
      //do stuff
      substring = readString.substring(0,8);
      lati = substring;
      loc = readString.indexOf("T");
      substring = readString.substring(loc+1, loc+11);
     longi = substring;
       readString=""; //clears variable for new input
      substring="";

    }
    else {
      readString += c; //makes the string readString
    }
  }

It works most of the time but sometimes I get 'T' inside the string as well.
like this

lat=1.450146&longi=102464T103

What's wrong in my code?


texts: Can I use these cheap GSM module with arduino?

texts:
I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not.
Will you help me please?

Here are the link-

http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8

http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D70128bc79b60410d862b64d36cc479b3%26pid%3D100033%26rk%3D1%26rkt%3D4%26sd%3D281517486292


texts: Powering Arduino with reverse car lights?

texts:
I'd like to build a reverse car sensor using Arduino

When we select reverse gear, the reverse lights powers, so we can take electricity from them.

My question is can i power my Arduino directly from the reverse lights wires, or should i use regulators or anything else?


texts:
is it possible to perform an action maximum x times per hour on the arduino?

I made a automatic water sprinkler that sprays when the humidity is lower than 50%. but if the sprayer performs this "spray" more than 4 times an hour the humidity wil be to high and wil rise to fast.so is there a way to restrict the amount of times an action is performed per hour,and then if the next hour comes the sprayer can perform his "sprays" 4 times before it stops again

sorry for bad english, this is not the language I speak (and type) mutch


texts: ESP12E motorshield analogWrite issue when powering DC motor

texts:
I am relatively new to adruino and this whole space. I am currently trying to power a DC motor using an ESP12E motor shield and an ESP8266 Module

Motor Shield - https://www.amazon.com/gp/product/B078CPZDW1/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

ESP8266 - https://www.amazon.com/gp/product/B010O1G1ES/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

DC Motor - https://www.amazon.com/gp/product/B07MTT7B88/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

Here is my code

#define DIRA 0
#define PWMA 5
#define LED 2

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

  Serial.println("Preparing motor...");
  pinMode(DIRA, OUTPUT);
  pinMode(PWMA, OUTPUT);
  analogWrite(PWMA,0);
  digitalWrite(DIRA,1);
  delay(5000);

  Serial.println("Starting motor...");
  analogWrite(PWMA,5);
  delay(5000);

}

void loop() {
}

Here is how I have wired it up

Note: This setup is similar to what I have but not exactly, I have 4 AA batteries connected and only 2 motors

I am expecting the motor to start once I upload this code but nothing is happening. If I change the analogWrite to digitalWrite, the motor runs but I want to be able to control the speed, rather than just having it run at one speed.

I have tested using analogWrite by changing the intensity of an LED and it was working, although the output pin was not the same as the one I use for the motor.

Would greatly appreciate any help as I have already gone through pages of google searches without any luck. I have been using this example as a reference, https://hackaday.io/project/8856-incubator-controller/log/29291-node-mcu-motor-shield.


texts: System Is not Functioning Error. Windows XP, Arduino Uno R3, C# Listen SerialPort

texts:
Can anyone help me with this issue.

We created an arduino project. We listen microswitch.
If switch click, Arduino send basic serial data.
And C# application read serial port.

This solution is working but after more times (3Hours, 5Hours,..) system stoped.
Error message is "a device attached to the system is not functioning"
Solution: Usb remove and retry plug system is going to running.

We are try putty.exe maybe problem C# project but don't working.

If microswitch click don't flash "TX" or "RX" led.

const int button = 3;

uint64_t bounceTime = 50;
uint64_t holdTime = 250;
uint64_t doubleTime = 500;

uint64_t lastReading = LOW;
uint64_t hold = 0;
uint64_t single = 0;

uint64_t onTime = 0;
uint64_t lastSwitchTime = 0;

void setup() {
 pinMode(button, INPUT_PULLUP);
 Serial.begin(9600);
}

void loop() {

 int reading = digitalRead(button);

 if (reading == HIGH && lastReading == LOW) {
   onTime = millis();
 }

 if (reading == HIGH && lastReading == HIGH) {
   if ((millis() - onTime) > holdTime) {
     hold = 1;
   }
 }

 if (reading == LOW && lastReading == HIGH) {
   if (((millis() - onTime) > bounceTime) && hold != 1) {
     onRelease();
   }
   if (hold == 1) {
      delay(5000);
      reading = digitalRead(button);
      if(reading==LOW){
              Serial.println("B");
      }
     hold = 0;
   }
 }
 lastReading = reading;

 if (single == 1 && (millis() - lastSwitchTime) > doubleTime) {
   single = 0;
 }

}

void onRelease() {
 if ((millis() - lastSwitchTime) >= doubleTime) {
   single = 1;
   lastSwitchTime = millis();
   return;
 }

 if ((millis() - lastSwitchTime) < doubleTime) {
   single = 0;
   lastSwitchTime = millis();
 }

}


texts:
Can you help me out to understand if this is possible with ESP8266 / 32 ?

I have a main binary that i upload to the chip, let's call it A - that's done from arduino.

A starts to work, but communicates every couple of minutes with central server polling for a task.

If there is a task - let's call it B

A downloads it and stores it on SPIFFS.

Now what should happen is that A uploads it, reboots and B starts to work.

When B finishes it loads up again A and the circle closes - this process goes on forever.

Questions:

1) Is it possible that a stored on SPIFFS binary file can be uploaded to the chip? Like OTA does via www.

2) Can i somehow store A onto the SPIFFS, so that when B finishes i reupload A ?

Thanks for any input into this


texts: How to read temperature from multiple DS18B20 faster?

texts:
I am writing an Arduino sketch to read temp data from multiple DS18B20 sensors and then write it to serial. The problem is, as I am connecting more sensors, the delay between my temp data is written to a serial increases (like 100ms for 1 sensor and 1s for 4 sensors). Can I somehow improve my sketch to read it faster?

Here is the sketch I am using:
(I am using DallasTemperature to simplify it all)

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 10
#define TEMPERATURE_PRECISION 8
#define BAUD_RATE 9600

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress devices[10];
int devicesFound = 0;

void setup(void)
{
  // start serial port
  Serial.begin(BAUD_RATE);
  //Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(sensors.getDeviceCount(), DEC);
  Serial.println(" devices.");

  devicesFound = sensors.getDeviceCount();

  // report parasite power requirements
  Serial.print("Parasite power is: ");
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  for (int i = 0; i < devicesFound; i++)
    if (!sensors.getAddress(devices[i], i))
      Serial.println("Unable to find address for Device" + i);

  // show the addresses we found on the bus
  for (int i = 0; i < devicesFound; i++)
  {
    Serial.print("Device " + (String)i + " Address: ");
    printAddress(devices[i]);
    Serial.println();
  }

  for (int i = 0; i < devicesFound; i++)
    sensors.setResolution(devices[i], TEMPERATURE_PRECISION);
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

// function to print the temperature for a device
String printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC < 10)
    return "0" + (String)tempC;
  else
    return (String)tempC;
}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  Serial.print("Resolution: ");
  Serial.print(sensors.getResolution(deviceAddress));
  Serial.println();
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  Serial.print("Device Address: ");
  printAddress(deviceAddress);
  Serial.print(" ");
  printTemperature(deviceAddress);
  Serial.println();
}

void loop(void)
{
  if (devicesFound == 0)
  {
     Serial.println("No devices found.");
     return;
  }

  sensors.requestTemperatures();

  String sent = "";

  // print the device information
  for (int i = 0; i < devicesFound; i++)
  {
    sent += printTemperature(devices[i]);
    if (i != devicesFound - 1)
      sent += " ";
  }

  Serial.println(sent);
}


texts: I need help purchasing components for my Arduino project

texts:
I am a newbie on this hardware stuff. I need help on purchasing the components

Brief description of my project

I need a device that would remotely detect weight or pressure when somebody push on it and send the info to the webserver or websockets. The device could be located up to 300 ft.

After doing some research on it I learned that I need, arduino uno as the device main platform, xbee for wireless communication with the web, xbee shield for the xbee and Force sensitive resistor sensor to detect small weight or pressure.

Question

First am I correct above mentioned components would solve what I am trying to do? If not what am I missing? Anything I mis-stated?

I have learned that there are stuff like xbee explorer, Arduino stackable headers, break-away headers, and breadboard. Do I really need these?

In the future I want to be able do other experiments with the board like use ultrasonic sensor with it or infrared sensor to detect objects. Will I need to buy anything specific to make these sensors compatible with the board or they are all standard?

Basically I want to buy everything I need in one shot. Thank you in advance. Any help will be appreciated.


texts: What will use less memory, an array or if ... else?

texts:
I'm trying to make my sketch smaller. Right now I use an array for the AM/PM part of my time display. My thinking is this makes it easy to change the formatting:

char* ampms[]= {"am", "pm"};

void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; ampm=1; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      dataFile.print(ampms[ampm]);
}

I could do this instead:

void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      if (hour>12) { lcd.print("am");} else {lcd.print("pm"); }
}

No more am/pm array. But, I have to add an if... is one better than the other for memory? Why?


texts:
Question

Is there a reason for unstable button numbers of an IR remote?

Desciption

I wrote a remote class where I identify the pressed number of the remote to set states. But however I get never the same number of the pressed key.

For example I press the number '1' and on the serial interface shows this:

3588650484
2740290906
3148594742
689746115
2396927248
2934053595
4294967295
3876827360

And it should look like this:

16724175 // Button 1
4294967295
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1

Hardware

I am using an arduino UNO board and the standart remote of the starter kit. There is no name just 'SPECIAL FOR MP3'.

Some more infos

Ok, in my first project I used the code from Noreddine Kessa(Example Project) which works fine. Next I copied some code in my new class 'IRControl.cpp' ( you can see below). Then I created an object IRControl in the main.cpp and run the menu() in the loop.

h-File:

/*
 * IRControl.h
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#ifndef IRCONTROL_H_
#define IRCONTROL_H_

//Remote Defines
#define buttonON 16753245
#define buttonMode 16736925
#define buttonSoundOff 16769565
#define buttonPlayStop 16743045
#define buttonTrackBack 16712445
#define buttonTrackForward 16761405
#define buttonEQ 16769055
#define buttonMinus 16754775
#define buttonPlus 16748655
#define button0 16738455
#define buttonRepeat 16750695
#define buttonJSD 16756815
#define button1 16724175
#define button2 16718055
#define button3 16743045
#define button4 16716015
#define button5 16726215
#define button6 16734885
#define button7 16728765
#define button8 16730805

#include "IRremote.h"
#include "wiring_private.h"

enum zustaende{Motor1, Motor2, Motor3, Sleep};
extern int zustand;

class IRControl {
private:
    IRrecv *irrecv;
    decode_results remoteValue;
public:
    IRControl(int RECV_PIN);
    virtual ~IRControl();
    void menu();
};

#endif /* IRCONTROL_H_ */

cpp-File:

* IRControl.cpp
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#include "IRControl.h"

IRControl::IRControl(int RECV_PIN) {
    // TODO Auto-generated constructor stub
    irrecv = new IRrecv(RECV_PIN);
    pinMode(RECV_PIN , INPUT);
    irrecv->enableIRIn();
}

IRControl::~IRControl() {
    // TODO Auto-generated destructor stub
    delete irrecv;
}

void IRControl::menu() {
    if (irrecv->decode(&remoteValue)) {
        //lReceived = remoteValue.value ;
        Serial.println(remoteValue.value);
        /*
        switch(remoteValue.value)
                {
                case button1:
                    zustand = Motor1;
                    //digitalWrite (LED1, HIGH); // for control
                    break;

                case button2:
                    zustand = Motor2;
                    //digitalWrite (LED2, HIGH);
                    break;
                case button3:
                    zustand = Motor3;
                    //digitalWrite (LED3, HIGH);
                    break;

                case button0:
                    zustand = Sleep;
                    break;

                default: break;
                }
                */
        irrecv->resume(); // Receive the next value
      }
}

Where the problem could be

I think there could be a problem with the IRrecv *irrecv;. But i'm not sure.

Thanks for your help


texts: Unable to upload sketches after little oopsie (reversed input polarity)

texts:
So playing around with an arduino uno, I was powering it with a 12volt battery (putting power between Vin and Gnd) and I fat fingered the battery terminals, putting them in reverse (oops)

I see smoke coming out of the 5 volt regulator (the little 3 pin IC). I immediately pull out the battery thinking I've just bricked this thing.

After a minute or two I plug the battery in again (taking care to plug it in straight this time) and to my surprise it works, works pretty well. The last sketch I uploaded works perfectly fine.

I've been using the same thing for an hour or so. But now I wanted to upload another sketch and it doesn't upload. The voltages seem to be fine, I'm putting in 11.8 volts on Vin, there is 5.12 volts on 5v and 3.34 volts on 3v3

I thought there may be some problem with the voltage regulator, so I tried connecting it directly to the USB (powering it from USB) but still the same thing.

I find it intriguing that it works perfectly for everything except uploading new sketches, especially after such an explosive oopsie. Can any of you chaps deduce what the problem might be? I have a USBasp module so I can reburn the bootloader, but I doubt that's the problem.


texts: Driving conveyor belts using Arduino Unos

texts:
We are planning to drive conveyor belts with Arduino Unos using stepper motors. We are planning to use easy drivers, so that we control at least 3 motors with one Uno. Currently we are still at an initial stage, we are designing and planning the setup of conveyor belts. But what I wanted to ask was, regarding the coding.

How would I code so that say the belt moves forward for x seconds, and then after time it moves backwards for y seconds. Any basic idea on the code would be great thank you. I could do the basic code, but I just need help with timers part.


texts: Arduino keypad and RF 433MHz transmitter problem

texts:
So, the basic idea is that user presses a key on keypad, and key that is pressed is sent with RF transmitter.
I got individual parts to work(keypad and transmitter), but can't send the actual key. When I try to send it, I get a strange string on the other end. I am convinced its simple issue with my syntax, so if anyone could help me, that would be great. Code is below:

#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile
RH_ASK driver; //use this driver for transmitter

#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{

    char key = keypad.getKey();

    if (key){
      Serial.println(key);//outputs correct key
      //transmitter part
//      const char *msg = "Hello World!";
      const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
      driver.send((uint8_t *)msg, strlen(msg));
      driver.waitPacketSent();
      Serial.println(key);//outputs correct key
      Serial.println("packet_sent");
    }
}


texts: I have two devices connected to my Arduino using the SoftwareSerial library. However, it seems that they cannot communicate at the same time. I can only communiate with both by switching between which one I am listening to every 1000ms (they poll for 1500ms), but this slows down overall communication significantly. Is there anyway to communiate with both at the same time? Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?


texts:
I've asked another question in electronics about what to use to compare 2 input voltages, the answer was to use comparators.

Digging around a bit, turns out most of the comparators outputs are pull-up, which makes it quite difficult to translate (probably due lack of general electronics knowledge, self-learned) and I'm not able to distinguish from maker's PDFs which comparators have pull-up or pull-down outputs.
I've figured PD comparators illustrate in PDF a resistor right after the output... but many illustrations I've seen doesn't clarify PD / PU, or I'm just missig that.

But my question is, are there any PD comparators (well known) where it's output can be connected to the digital pins or arduino (while those are defined as INPUT mode)?

I appreciate any guidance on this topic.

Just a side note, I want to switch on a led, when ever external source is at 12V and turn that same led off when it's below 11.5V...


texts:
I just found the alpha version of Arduino Pro IDE and I was wondering why this project is not open source as the classic IDE.
I didn't found anything about that online.


texts: How to make universal remote controller?

texts:
I am trying to make simple TV remote using Arduino.

I got this link from Google for making a remote.

Code uploaded perfectly on my device. But all it does is blink a the LED on pin 13.

I hope I have got right code. I have tested it on my TV at home. Is that the correct way of testing it?

IR receiver I have is TSOP-15

P.S. I am completely new to Arduino

The below shown is my Arduino board(induino r3)


texts: Can we use UART COMMUNICATION with MCP23017?

texts:
I am using MCP23017 as a GPIO expander with Arduino in my project. I have too many serial devices and no pins left on Arduino for UART communication.
I am wondering if I can use this MCP23017 GPIO expander pins for UART communication or not?


texts: How can i read and write the data from a Delta plc-s series through Arduino UNO?

texts:
I am trying to communicate PLC with arduino through rs232 as well rs 485. But, I am not able to read and write data. I can observe the data in PLC through ladder logic but not in arduino. I am trying to implement the Modbus ASCII here but reading and writing both is not happening.

#include <EmSevenSegment.h>
#include<SoftwareSerial.h>

EmSevenSegment disp(4, 'C', 4, 3, 2);
SoftwareSerial debuggingSerial(0, 1); //RX,TX

[![enter image description here][1]][1]String readlineString = "";
String integerString = "";
String decimalString = "";
String outputString = "";
char startChar = 0x01;
char endChar = 0x01;
//char weight[10];

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

}

void loop() {
  Serial.print("!!!!!!!!!!11111111111\n");
  delay(1000);
  if (debuggingSerial.available())
  {
    Serial.print("!!!!!!!!!!2222222222\n");
    readlineString = debuggingSerial.readString();
    Serial.print(readlineString);
  }

  if (readlineString.length() > 0)
  {
    Serial.print("!!!!!!!!!!333333333333\n");
    integerString = readlineString.substring(10, 12);
    decimalString = readlineString.substring(13, 15);
    int number = (integerString + decimalString).toInt(); // 6789; //Number to be displayed
    disp.print(number); // Print the number
    Serial.print(readlineString);
    readlineString = "";
  }

}

Please find the image of rs232 connection:


texts: LED strip brightness decreases when using multiple strips

texts:
Newbie question here.

I have bought a 5V, 40A power supply to externally power up some LED strips (WS2812B). The Arduino Nano is powered by a standard USB wall charger (5V).
So far I have tested with 4 LED strips (each of about 25 LED's). Each of the strips is connected to an individual data pin on the Arduino in addition to the power supply (5V and ground).

So, to the problem. For each LED strip that gets powered it seems that the brightness of the LED's decreases. Using for example "white color", all the LED's shows a "yellow"-ish color when all the LED strips are powered. If only one or two is powered it looks fine.
The Arduino by the way shares the same ground as the power supply.
What could the cause to this issue be? The power supple should be more than sufficient for the task. Is it the data pins that can't handle it?

Thanks for any help!

EDIT:

I more detail, each LED strip has 3 pins (1 for 5V, 1 for data input, and 1 for ground). Each for the LED strips 5V pin are connected to the + rail on a breadboard where the power supplies + is also connected. The same goes for the ground pin of the LED strips (they are connected to a ground rail on the same breadboard where also the ground of the power supply is connected).
The data pin on the LED strips are connected to 4 (when all are connected) different data pins on the Arduino Nano (A1,A2,A3 and A4).

The ground pin on the Arduino Nano is connected to the same breadboard ground rail as the rest. When I didn't do this the LED's had weird behaviour.
The wires going from the LED strips into the breadboard are standard 24 AWG stranded wires (each of about 50 - 80 cm in length).

Power supply used is "AC 110V-220V TO DC 5V 40A" from ebay.
https://www.ebay.com/itm/AC-110V-220V-TO-DC-5V-12V-24V-Switch-Power-Supply-Driver-Adapter-LED-Strip-Light/152134115704

LED strips that are used "5M WS2812B 5050 RGB, 150LEDS ip65 Waterproof"
https://www.ebay.com/itm/5M-WS2812B-Strip-LED-Lights-5050-RGB-30-60-LED-M-IC-Individual-Addressable-DC5V/113117301639?


texts: Arduino Vin pin does not work, but Arduino 5v pin power works

texts:
I have a very weird problem, at least it seems to me that way. I have connected L298N motor driver, Arduino and a hobby servo with a 6v power supply (tested with both 4xAA and 9v alkaline batteries). And wrote a simple program to rotate the servo every 10ms. There are no other motors connected as of yet.

Power supply is connected to the L298N 12v and GND.
Arduino is connected to the 5v and GND of L298N driver with the Vin and GND of Arduino respectively.
Servo's power (red wire) is connected to L298N 5v, GND is connected to the L298N's GND, and, servo's control (orange wire) is connected to pin 9 of Arduino.

The problem is that the servo hardly moves when Arduino gets power supply gets from the Vin input. However, if I connect it to the 5v of the Arduino power it works as expected. But I was under the impression that 5v pin of Arduino was to for the output and not for the input power supply. Could you guys please tell me what am I doing wrong here?


texts: In CLion, how can I set up multiple cpp files for arduino

texts: I'm using the Arduino plugin in CLion. I can't seem to figure out how to have multiple cpp files for my classes. I have been putting the code in my .h up until now, but that's going to bite me soon.


texts: What is the difference between the revisions of the Arduino Uno board?

texts: There are three different revisions of the Arduino Uno. What changed in each revision?


texts: Determining state of charge using current sensor (ACS758) with arduino uno

texts:
I am working on a university project and I am struggling with estimating the state of charge of our batteries, by using coulomb counting.

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

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

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

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

Thanks in advance!


texts: Leds become dimmer after they reach a certain brightness, why?

texts:
Even if I don't use buttons and I do an automated thing that makes the led brighter(Even the non-rgb one)after sometime it resets itself to a dimmer light, why?*
int Gled = 5;
int Bled = 6;
int Rv;
int Gv;
int Bv;

int b1 = 7;
int b2 = 8;
void setup()
{

  pinMode(b1, INPUT_PULLUP);
  pinMode(b2, INPUT_PULLUP);
  Rv = 0;
  Gv = 0;
  Bv = 0;
  analogWrite(Rled, Rv);
  analogWrite(Gled, Gv);
  analogWrite(Bled, Bv);

}

void loop()
{

  if(digitalRead(b1) == LOW)
  {
    Rv += 10;
    analogWrite(Rled, Rv);
  }
  if(digitalRead(b2) == LOW)
  {
    Gv += 10;
    analogWrite(Gled, Gv);
  }

}


texts:
I'm trying to get 110dB out of a 25khz Piezo Transducer.  This piezo resonates at 25khz and as per the illustration in its datasheet should emit 110dB with 10 volts and 25khz frequency.

Any assistence as to what I'm doing wrong here would be GREATLY appreciated !!

My code is bit-banging it.  With an oscilloscope, I confirmed that I'm getting a nice clean 25khz square wave.

I have attached a step-up circuit to the device and am seeing 10volts across the terminals of the piezo while it is emitting it's 25khz frequency.

However, instead of 110dB, I'm only getting 50dB.

I've tried upping the voltage to 20, and still get the same volume level.  The voltage is adjustable via the screw on the top of the blue capacitor on the Voltage Step Up (pictured below).

I've tried changing the duty cycle having HIGH go for 25microseconds and LOW go for 5microseconds.  I've tried several combinations and a 50/50 duty cycle appears to achieve maximum volume which is 50dB.

Here's how I'm connected:
1.  The inputs of the Step Up are attached to GND and 3.3V pins on the Arduino.
2.  The output+ of the Step Up is connected to 1 pin of the Piezo.
3.  The output- of the Step Up is NOT connected to anything. (tried to connect it to GND but it didn't change anything.
3.  The other pin on the Piezo is connected to D11 on the Arduino.

I'm Running the following code:

 #include<Wire.h>

const int SPK = 11;

void setup()
{
  Serial.begin(9600);
  pinMode(SPK, OUTPUT);
  digitalWrite(SPK, LOW);
}

void loop()
{
  long startTime = millis();
  for (int i = 0; i < 25000; i++)
  {
    digitalWrite(SPK, HIGH);
    delayMicroseconds(15);
    digitalWrite(SPK, LOW);
    delayMicroseconds(15);
  }

  Serial.println(millis() - startTime);
}

UPDATE:

Ok, I am now set up to look like this:

Is this the next step (ie: Adding an Inducer) ?


texts:
12bit ADC will give us about 1.2mV per step:

5 / 4096 = 0.00122

But if we give Arduino a 1.2V voltage reference we get 1.1mV per step:

1.2 / 1024 = 0.00117

Does that means Arduino can be more accurate than a 12 bit ADC?


texts:
am trying to completly turn off ra-01 radio and esp8266 and turn it on by external trigger but i have issues getting the lora radio to turn off
#include <LoRa.h>
#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  // while (!Serial);

  // disable wifi
  WiFi.mode( WIFI_OFF );
  WiFi.forceSleepBegin();

  // LoRa
  #define dio0 2
  #define ss 15
  #define rst 16
  //#define rst 32

  LoRa.setPins(ss, rst, dio0);
  LoRa.setSyncWord(0xF3);

  Serial.println("LoRa: OK");

  if (!LoRa.begin(433E6)) {
    Serial.println("LoRa: Fail!");
    while (1);
  }
  Serial.println("Sending packet: ");

  // send packet
  LoRa.beginPacket();
  LoRa.print("c");
  LoRa.endPacket();
  LoRa.end();

  // shutdown spi
  SPI.end();
  digitalWrite(dio0, HIGH);
  digitalWrite(ss, HIGH);
  digitalWrite(rst, HIGH);

  // deep sleep
  ESP.deepSleep(0);
}

void loop() {

}``


texts:
I have a problem with my Arduino project and I tried everything to fix it but nothing helps.

I am trying to rotate my DC motor with two buttons:

one button is to stop/start rotating on left side, and;
the second one is for stop/start rotating on the right side.

I can't switch the states and if the motor is rotating I can't stop it. The speed is controlled by the potentiometer and works fine, just the buttons are the problem. I hope somebody can help me.

int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int switchPin1 = 6;
int potPin = 0;
int statusPin= 13;
boolean status;

void setup()
{
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
  pinMode(switchPin1, INPUT_PULLUP);

  pinMode(statusPin,OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(13,HIGH);

  int speed = analogRead(potPin) / 4;

  boolean reverse = digitalRead(switchPin);
  boolean reverse1 = digitalRead(switchPin1);

  if(reverse == false){
    status = true;
  }
  if(reverse1 == false){
    status == false;
  }

  setMotor(speed, status);
}

void setMotor(int speed, boolean reverse)
{
  analogWrite(enablePin, speed);

  digitalWrite(in1Pin, ! reverse);
  digitalWrite(in2Pin, reverse);
}

I just added the second button with paint, so don't get confused.


texts: Client or WiFiClient wrapper for adafruit CC3000 wifi other than web

texts: Basically I want a contact to a socket (keep open) for sending strings and characters as well as receiving them. I do not want anything to do with web. I am writing my own server in vb and actually have that working. I also have working the Arduino ethernetshield. I just wanted an alternative wifi solution.


texts: Invalid conversion from 'const char' to 'uint8_t*'

texts:
I am just a newbie, don't know how to solve this issue

void loop()
{
  UdpSend("Test", "192.168.0.240", 4210);
}

void UdpSend(const char* message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

Arduino IDE can't compile.

The error message:  invalid conversion from 'const char' to 'uint8_t* {aka unsigned char*}' [-fpermissive]*

Trying to change with this code:

void UdpSend(uint8_t * message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

Also doesn't work, the error message: invalid conversion from 'const char' to 'uint8_t* {aka unsigned char*}' [-fpermissive]*

Please help...


texts: How do I turn on or off an array of LEDs based on the value of a variable?

texts:
I've created a function whereby an int ('cleanCount') automatically goes up or down (0-1000) based on the situation. The value changes every few milliseconds.

Based on the value, I would like to turn on or off LEDs. Let's say for every increment of '100' another LED goes on. So if the value is 359 there are 3 leds on, if It would been 899 there would've been 8 LEDs on.

I could simply write

if (cleanCount <= 100) { // turn on NO LEDs
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    ...
}

...

else if (cleanCount <= 500) { // turn on 4 LEDs
    ...
    digitalwrite(led3, HIGH);
    digitalwrite(led4, HIGH);
    digitalwrite(led5, LOW);
    digitalwrite(led6, LOW);
    ...
}

but that would be a big pile of code which could be way more efficient. Perhaps.. my code isn't even correct.

So how could this be more efficient or perhaps actually working?

The whole code, here below.

int cleanCount = 1000;
int softpotPin = A0; //analog pin 0

void setup () {
    Serial.begin(9600);
    digitalWrite(softpotPin, HIGH); //enable pullup resistor
}

void loop() {
    int softpotReading = analogRead(softpotPin);
    if (softpotReading < 980) { // IF AANGERAAKT
        digitalWrite(werktIeLED, HIGH);
        ++cleanCount;
        Serial.println(cleanCount);
        delay(16); // 5x zo snel als leeglopen
    }
    else if (softpotReading > 980) { // IF NIET AANGERAAKT
        digitalWrite(werktIeLED, LOW);
        --cleanCount;
        Serial.println(cleanCount);
        delay(64); // 1000 / 60 seconden
    }
    else {      // Als er een fout optreed..
        Serial.println("Fout!");
        digitalWrite(werktIeLED, HIGH);
        delay(250);
        digitalWrite(werktIeLED, LOW);
        delay(250);
    }

}


texts: Can't reprogram Arduino on protoboard (perfboard), but could program the same circuit on breadboard

texts:
So I have a circuit that works well when it's on a breadboard and without removing any pins I'm able to upload sketches, but for some reason when I transition it to a protoboard I can no longer upload sketches.

My circuit consists of an MPU6050, an Arduino Pro Mini, and a HC-08 BLE module. I've tried protoboarding this circuit twice with Arduino Pro Minis and once with an Arduino Nano, and now I'm not able to upload sketches to any of these three circuits.

I'm using perfboard (not stripboard, so yes I have already connected the jumper wires to the header pins) and know that the circuit partially works since the IMU, Arduino, and BLE LEDs all light and you can connect to the BLE on a mobile terminal app.

The error I get is:

avrdude: stk500_getsync(): not in sync: resp=0x00,

I use SoftwareSerial.h so NO pins are connected to the Arduinos 0 and 1 pins.
I've already tried restarting the IDE
I've tried disconnecting/reconnecting the USB cable
There's only one COM# port so I'm sure I'm using the right one.

I'm so stumped because this error message did not occur when I was playing with the same circuit on a breadboard...

Any ideas on how I can fix this or what I'm doing wrong?


texts: Arduino code of making a LED digit display not functioning properly

texts:
I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code

int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;

void setup()
{
   for(int i = 2; i++ ; i<9)
   {
      pinMode (i, OUTPUT);
   }
}
void _1()
{
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _2()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _3()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _4()
{
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( b, HIGH);
   delay(1000);
}
void _5()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _6()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   digitalWrite ( d, HIGH);
   delay(1000);
}
void _7()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _8()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void _9()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( d, HIGH);
   digitalWrite ( f, HIGH);
   delay(1000);
}
void _0()
{
   digitalWrite ( a, HIGH);
   digitalWrite ( b, HIGH);
   digitalWrite ( c, HIGH);
   digitalWrite ( e, HIGH);
   digitalWrite ( f, HIGH);
   digitalWrite ( g, HIGH);
   delay(1000);
}
void wait()
{
   digitalWrite ( a, LOW);
   digitalWrite ( b, LOW);
   digitalWrite ( c, LOW);
   digitalWrite ( d, LOW);
   digitalWrite ( e, LOW);
   digitalWrite ( f, LOW);
   digitalWrite ( g, LOW);
   delay(100);
}
void loop()
{
   _0();
   wait();
   _1();
   wait();
   _2();
   wait();
   _3();
   wait();
   _4();
   wait();
   _5();
   wait();
   _6();
   wait();
   _7();
   wait();
   _8();
   wait();
   _9();
   wait();
}

The problem is that it stays at _0 and then never changes. Any suggestions?


texts: Fried Ams1117 on 9v power supply toxicity

texts: I just fried ams1117 on 9v voltage supply module while working with nodemcu. I was in my living room and inhaled the burst of smoke. How toxic is it?


texts:
I have the code, it's purpose is to receive the string from a comport like:
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
and translate it into four byte arrays byte user1[16], user2[16], pass1[16], pass2[16]. Here's the code:

String inString = ""; // COM port incoming data buffer

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

void loop() {
  // put your main code here, to run repeatedly:
  // Receive data from com port
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
    } else {
      // New line
      String Action = inString.substring(0, 3);
      if (Action == "Set") {
        SetCard(inString);
      } else if (Action == "Get") {
        Serial.println("1");
      } else {
        Serial.println(Action);
      }
      inString = "";
    }
  }
}

void SetCard(String Data) {
  Serial.println(Data);
  // Data Set@user1@user2@pass1@pass2
  // Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
  byte user1[16], user2[16], pass1[16], pass2[16];

  String user1str = inString.substring(4, 20);
  String user2str = inString.substring(21, 37);
  String pass1str = inString.substring(38, 54);
  String pass2str = inString.substring(55, 71);

  Serial.println("Strings");
  Serial.println(user1str);
  Serial.println(user2str);
  Serial.println(pass1str);
  Serial.println(pass2str);

  Serial.println("Arrays");
  user1str.getBytes(user1, 16);
  user2str.getBytes(user2, 16);
  pass1str.getBytes(pass1, 16);
  pass2str.getBytes(pass2, 16);

  writeByteArray(user1, 16);
  writeByteArray(user2, 16);
  writeByteArray(pass1, 16);
  writeByteArray(pass2, 16);
}

void writeByteArray(byte array[], int arrlength)
{
  for (int j = 0 ; j < arrlength ; j++) //print the block contents
  {
    Serial.write (array[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

When I run this code and send my string through a com port I expect the output:

Start
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
Strings
1234567890123456
1234567890123456
1234567890123456
1234567890123456
Arrays
1234567890123456
1234567890123456
1234567890123456
1234567890123456

And yet, I receive

Start
Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
Strings
1234567890123456
1234567890123456
1234567890123456
1234567890123456
Arrays
123456789012345
123456789012345
123456789012345
123456789012345

Why? And how do I receive desired output?
getBytes docs


texts: How can I run Hello World using Serial Monitor in Tinkercad Arduino simulator?

texts:
I want to achieve printing Hello World in the serial monitor using Tinkercad to simulate Arduino.
Here is a very simple example code for real Arduino.
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Hello World!");
}

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

}

However, putting an Uno board, typing this code, and clicking "Start Simulation" in Tinkercad doesn't show the Hello World message.
Is it doable? If so how?
For real Arduino, you need to select Arduino serial port and open Serial Monitor. But I can't find such an option for Tinkercad. I can't find Serial Monitor in Thinkercad.
My real purpose is to use Serial Monitor output to test code snippets. Right now I don't have real Arduino board with me, so I thought a simulator would be ideal. If I can easily check the values of variables, it doesn't have to be Serial Monitor.
Sorry if this is not a place to ask questions about simulators.


texts: arduino webserver serves single web page to WAN/Internet very very slowly

texts:
I have an arduino web server running from a mega 2560 and a wiznet ethernet shield.

It serves the single page just fine (and very fast) to the LAN (192.168.1.50), but serves the same page very, very, slowly when accessed from the  WAN/Internet.

I have port forwarding set-up on the modem router so that the Arduino web page  can be accessed from the outside world, and it does work, I can see the page from anywhere, but it's page serve rate is impractically slow. The page takes 30 - 45 seconds to load up.

(I have the RaspPi with Apache set-up, also in the house, using the exact same port forwarding settings - with a different port - and it serves pages to the WAN/Internet very fast).

Has anyone any ideas what might be wrong ?

Thank you


texts: "Update driver software" not showing. :(

texts:
I've followed tutorials installing arduino drivers for a while, but this is getting in my way:

The all-important "Update driver software" button isn't showing? Can anyone explain this and how I can fix it? Many thanks!


texts: HC-05 Stuck in slave loop mode (loopback)

texts: got my HC-05 today and accidently set the AT+ROLE=2(slave loop) and now I can't get out of it! Anything I send it just resends it back to me, even commands like AT+RESET and AT+ORGL, they just get returned. I can't figure out how to put the device back in slave mode, your help would be highly appreciated!


texts: Delay on multiple NRF24L01+ (RF24.h) and Arduino nodes

texts:
I have set up a system using 4 arduino clones, each wired to an NRF24L01+ radio. I am using the RF24 library by maniacbug (https://github.com/maniacbug/RF24) and have set-up the nodes with 1 base node as a receiver and 3 child nodes that transmits continuously to the receiver.

What I want to do is to send the read and analog value wirelessly from the child nodes to the base node as fast as possible. I used the starping example as a guide and it looks almost realtime when only 1 child node is active. When I turn on another child node, most of the time the update stops for a while then continue on, with randomly updating either child 1 or child 2.

I'm guessing there's a collision that's causing the delays. How do I lessen these delays? I'm thinking of having some sort of scheduling system for the children to send their messages (like, child2 will send only after child1, etc.) I also tried radio.setAutoAck(false) in an attempt to lessen the delays but that made all my readings stop altogether.

base node:

    #include "Timer.h"
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    RF24 radio(9,10);
    Timer t;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    unsigned int values[3] = {0,0,0};
    void setup(void)
    {

      Serial.begin(115200);
      printf_begin();
      //printf("Receiver Node Active\n\r");

      radio.begin();

        radio.openReadingPipe(1,pipes[0]);
        radio.openReadingPipe(2,pipes[1]);
        radio.openReadingPipe(3,pipes[2]);
        radio.openReadingPipe(4,pipes[3]);
        radio.openReadingPipe(5,pipes[4]);

      radio.startListening();
      radio.printDetails();
      t.every(1, print_values); //call print_values() every 1ms

    }

    void loop(void)
    {
        int sender_id;
        uint8_t pipe_num;
        if ( radio.available(&pipe_num) )
        {
          unsigned int message;
          bool done = false;
            while (!done)
            {
                done = radio.read( &message, sizeof(message) );
            }
          sender_id = pipe_num - 1;
          values[sender_id-1] = message;
        }
        delay(1);
        t.update();

     }

     void print_values(){
       //formatted for arduinoscope
       printf("%d %d %d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n", values[0], values[1], values[2]);
     }
    // vim:ai:ci sts=2 sw=2 ft=cpp

child node:

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    RF24 radio(0,1);

    const int SW01 = 18;
    const int SW02 = 19;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    int node_id;

    void setup(void)
    {
      node_id=3; //hard coded id
      radio.begin();
      radio.openWritingPipe(pipes[node_id]);
    }

    void loop(void)
    {
        unsigned int val = analogRead(A0);
        radio.write( &val, sizeof(val) );
        //delay(1);
    }


texts:
I need dynamic casts for my project, I'm getting:

error: 'dynamic_cast' not permitted with -fno-rtti

It appears that RTTI (run-time type information) is disabled with the fno-rtti compiler flag.

How do I change this?


texts: Detect if multiple variables are the same?

texts:
I'm setting a series of variables with: uint32_t currentLedColor[9]

What I'd like to check is if certain ones of those are the same.

Basically want to say if currentLedColor[0] and currentLedColor[1] and currentLedColor[2] are equal

How would I write that?


texts: Confused between SPI and I2C for SSD1306 OLED

texts:
I recently got myself an SSD1306 OLED display:

I haven't been able to successfully wire it to an Arduino (Mega 2560) however. I have been reading up on I2C and SPI and checked some libraries from Adafruit and U8G2.

However, I'm confused, since most of the Internet is talking about a similar OLED display with GND - VDD - SCL - SDA labelled pins, where mine has SCK instead of SCL.

Now, the number of pins make me believe I need to interface with I2C, but the SCK label points to SPI, right?

One person seemed to have the same problem as me, but the solution he got (pull-up resistors) didn't do the trick for me, I'm afraid.

So, my question remains: how to wire this OLED display to the Mega 2560?

Much appreciated if someone could point me to the right direction.

Thanks!


texts: EB - 4x4 Soft Keypad Driver Diagram from Makerstudio needed

texts:
I have found this interesting device wile looking for a cheap Arduino.

It's a "driver" that converts a 4x4 Keyboard 8-PIN (8-IO)
to a 4-Pin (2-IO) Device
I would like to know if is Achieved by a shift register ,One Wire Keypad or some other magic. If you have a diagram/tutorial/video please share (I know the "One Wire Keypad" uses Only 3-PINS (1-Analog-IO))Naturally ordered one to have a look but its gonna take some time to get here and i am way to exited.


texts: I want to make mesh network with nodemcu (esp8266)

texts: 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.


texts: can I program a nano over SPI with another nano?

texts: I'm fairly new to arduino, but I want to program a nano over SPI to skip the bootloader. I know I can program the nano with an uno as a programmer to do this, but I don't have an uno, but I do have a couple of nanos. Can I set up one as a programmer, connect it to another over SPI, and program the 2nd?


texts: Do I have to use Arduino IRRemote libraries?

texts: I have seen some tutorials to build your own IR Remote. But all of them use a library that contains the IR code. The question is, could I just skip, injecting a library and make the Arduino output a IR signal?


texts: Low-power detect rise and fall of input signal

texts:
For a very low-power-project (where I want to keep the micro-controller asleep or powerless as much as possible), I need to detect the rising and the falling of an input-signal (which could power-on the controller and send a signal).

I tried sleeping and waking up the controller via an interrupt, but it would be even better to switch of the controller completely and just power up when there is a change in input signal (only a few times a day, with a signal length of several minutes).

Making the controller powerless (and processing all there is to be done in the setup before switching off again) is a better solution than the deep sleep solution, because of the low frequency of occurence of the input signal changes.

The output does not have to be exactly 30 seconds, it can be any other value. It could use a power latch.

I looked at monostable circuits but they only detect (generate a pulse) on rising.

Does anyone have a solution (which only costs a few uAmps) for this?

Thanks.

Addendum:

Voltage is 3.3V, current is "as low as possible" because this circuit should work as long as possible on a few cells. The input signal is generated by a mercury switch mounted on a bridge (which can be opened and closed)...

Instead of waking up from deep sleep (and being able to calculate the number of hours the circuit can last on an small battery) it is far better to power off "completely" and being able to calculate the number of activations from the bridge-movement (as long as the electronics I am looking for consume less than the deep sleep). Power consumption by the micro-controller+circuits is in deep sleep >10mA (too much for battery).


texts: Interfacing a CCTV camera (AV output) with Arduino Uno

texts:
I have to use a camera to take picture in my major project. I want to use this camera, which has AV output. Please tell me how to interface this camera with my Arduino Uno and use the data from camera and send it to my PC using a Wi-fi Module?

P.S. Please do not suggest me to use wireless camera because firstly they are expensive and secondly I require a board in my project anyway.


texts: Adafruit Gemma unrecognised USB device on Windows 10

texts:
I have a V2 Adafruit Gemma from the Gemma starter pack, and I'm running Windows 10 Home (version 10.0.14393), on a 64-bit laptop. Following the  Introducing Gemma guide I've installed the Adafruit drivers and I'm now trying to get it to connect via USB.

After connecting, the board shows the green power LED, but not the pulsing red LED, and Windows shows the 'USB device not recognised' message.

Tried so far

I'm definitely using USB 2 ports, and I have tried it connected directly to the PC and via a USB hub.
I'm pretty sure the cable is working correctly (It works for exchanging data on a phone, and I've tried a few different ones).
Under Device Manager, the board shows as 'USB Device (Device Descriptor Request Failed)'.
'Update driver software' > 'Search automatically...' reports that 'The best driver software for your device is already installed'.
If I do 'Update driver software' > 'Browse my computer...' and point it to the manual Adafruit driver files (available on the link to the guide), I get the same message.

Can anyone suggest anything to try? Do I need to (re)install the bootloader itself, and if so, can you point me in the direction of how I do this?

Update

As mentioned in the comments I have posted on Adafruit's own support forum but got absolutely nothing yet. I have also tried it on my work PC (Windows 10 Pro, 64-bit) and got exactly the same behaviour.

I'm keen to get this sorted so bounty added for anyone who can at least come up with some suggestions of what to try!


texts: For Arduino, is there a meaningful difference between carriage returns?

texts:
Serial.write(0x0d); // hex

Serial.write(13);   // ASCII

Serial.write('\r');  // char

Is one more efficient? I read how it depends on the terminal program. So does that mean the IDE? (This is my first time working with serial comm.)


texts: Function pointer call results in InstrFetchProhibited (ESP32)

texts:
I have the following issue which I'm unable to resolve by myself. Perhaps one of you could point me to issues in my code which I don't see.

There is a class called communicator which handles an MQTT connection. I use PubSubClient as a MQTT client. The constructor of communicator looks like the following. Besides connection arguments, it also receives an array of structs SubscriptionHandler. These structs define which topics should be subscribed to and also point to a callback method. When a communicator receives a MQTT message, it compares the topic to the known ones and calls the appropriate callback.

Communicator(char * mqttBrokerIP, uint16_t mqttBrokerPort, char *mqttUsername, char * mqttPassword, char * mqttClientHostname, SubscriptionHandler subscriptionHandlers[], int lenHandlers);

SubscriptionHandler. is defined like this:

typedef void (*callback)();

struct SubscriptionHandler
{
    char *Topic;
    callback Callback;
};

I tried the following: In the main file, I defined two methods for demonstration purposes:

void enableHandler()
{
  Serial.println("enable handler");
}

void disableHandler()
{
  Serial.println("disable handler");
}

The communicator is created in the setup()-Method:

SubscriptionHandler handlers[] = {{&strEnable, enableHandler},
                                    {&strDisable, disableHandler}};

callback (in communicator.h) typedef void (callback)();

strings : String strEnable = ("test/" + hostname + "/command/enable"); and the same for disable. Those are also defined in main.cpp –

As soon as the communicator receives a MQTT message, the ESP32 crashes with the following message:

Guru Meditation Error: Core  1 panic'ed (InstrFetchProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x3ffc9306  PS      : 0x00060c30  A0      : 0x8017e97c  A1      : 0x3ffb1ed0
A2      : 0x3ffc9306  A3      : 0x3ffc9306  A4      : 0x3ffc9306  A5      : 0x3ffc1318
A6      : 0x3ffb1f44  A7      : 0x00000000  A8      : 0x800d4df0  A9      : 0x3ffb1eb0
A10     : 0x0000000d  A11     : 0x0000000b  A12     : 0x3ffc24a4  A13     : 0xa98b32f8
A14     : 0x3ffc1318  A15     : 0xff000000  SAR     : 0x00000004  EXCCAUSE: 0x00000014
EXCVADDR: 0x3ffc9304  LBEG    : 0x400014fd  LEND    : 0x4000150d  LCOUNT  : 0xffffffff

Backtrace: 0x3ffc9306:0x3ffb1ed0 0x4017e979:0x3ffb1f00 0x400e280e:0x3ffb1f20 0x400d4f3e:0x3ffb1f70 0x400d5cff:0x3ffb1f90 0x400e4c45:0x3ffb1fb0 0x400889dd:0x3ffb1fd0

Therefore, something is wrong with how I use the function pointer (or somewhere which I don't even think about). Could anyone give me a hint where I could start?


texts: ESP8266 timer to trigger actions (logic issue)

texts:
so I have an application in which there are 2 specific times (eg 9AM, 6PM) where a variable curPos is updated. Everything is converted in ms since 00:00 (9AM = 32400000, 6PM = 64800000). Now, the actions (curPos updates) should be triggered every day at these times. To retrieve the current real time (always in ms) I'm sending a http request to a website. This is done only once in the setup().

The idea is that I have to access somehow (http request) the current real time in order to determine when are 9AM and 6PM in my ESP8266, since the start of the sketch. The current real time is needed only once at the beginning (in case there's an issue and the sketch restarts).
Then I can calculate the difference between the current real time and the timers.

The next step would be to translate the values into a 24hour cycle starting at the startup/reset time, so that it can repeat itself without need to request again the real time.

I'm lost in the logic on how to deal with this and with millis() to check when it's time to trigger one of the actions.

This is what I'm doing now with the HTPP GET payload in the setup() (I can successfully retrieve the 3 values in ms from the GET response)

      String payload = http.getString();

      int commaIndex = payload.indexOf(',');
      int secondCommaIndex = payload.indexOf(',', commaIndex + 1); //Search for the next comma just after the first

      mainTime = payload.substring(0, commaIndex).toInt(); //current real time in ms
      timers[0] = payload.substring(commaIndex + 1, secondCommaIndex).toInt(); //9AM in ms
      timers[1] = payload.substring(secondCommaIndex + 1).toInt()); //6PM in ms

      timers[0] = abs(mainTime - timers[0]); //the time difference before reaching the first timer (in ms)
      timers[1] = abs(mainTime - timers[1]); //the time difference before reaching the second timer (in ms)

      // my attempt to turn the time differences into a 24hrs "local" (in the sketch) time
      //dayMs is 24hrs in ms (86400000)
      if(timers[0] < 0)
        timers[0] = dayMs - timers[0];

      if(timers[1] < 0)
        timers[1] = dayMs - timers[1];

and in the loop I'd need a comparison (I think) but I'm just really lost on this

//I think millis need to be reset after 24hrs since the start of the sketch?

if(millis() == timers[0]){
      curPos = 1; //first timer expired then trigger
  }else if(millis() == timers[1]){
      curPos = 7; //second timer expired then trigger
  }

thanks!


texts: Question about viability of building a Bill Counter machine

texts:
I have a need for a bill counter at my current job, but besides counting bills we also could use a machine to count admission cards.

The idea is to either buy a bill counter machine (like those that the Banks have), or make one from scratch by buying the parts.
Besides the bill counting feature i wanted to make it so that it also counts the certain number of cards, and check if they are either stamped or not.

My question is:

Is this possible?

If so, is it easier to just buy a arduino and use it with other parts (sensors, moving gears etc etc), or to buy a bill counter and just "crack" the OS?

Any insight would be appreciated!

PS: I am a 1st year Computer Science student, but i have 0 experience in programming in Arduino


texts:
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);

}

void loop() {
  uint8_t buttons = lcd.readButtons();
  int a;
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      lcd.setCursor(0,0);
      lcd.print(a);
    }
  }

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!


texts:
Recently I've started playing around with an Arduino Uno (rev 3), and I've set up a communication bridge between the Arduino and my computer using Python. So I send a command in Python ("ping" for instance), which is then read and interpreted. I've had it working before, using the Python commands to control a motor, but today it became non-responsive. However, only if I boot the serial monitor from the Arduino IDE, it suddenly accepts my commands again. Further inspection reveals that the Arduino is probably reading empty or corrupted data, interpreting it as ð, à and ÿ and such.

Here is an excerpt of the Python code I'm using:

import sys, glob, serial, time, re

class interface:

     timeout = 2    # 10 second time-out

    def __init__(self):
        port = "/dev/ttyACM0"
        self.connect(port)
        pass

    def connect(self, port="/dev/ttyACM0"):
        global arduino
        arduino = serial.Serial(port, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0.1)  # Establishing connection
        time.sleep(3) # Allowing the connection to settle
        arduino.flush()
        print "Connection established..."

    def ping(self):
        arduino.flush()
        arduino.write("ping")
        msg = self.listen_arduino()
        print msg
        if msg == "ping_ok":
            print "pinged"
            return True
        return False

    def listen_arduino(self):
        timeout = self.timeout
        matcher = re.compile("\n")
        buff = ""
        t0 = time.time()
        buff += arduino.read(128)

        while (time.time() - t0) < timeout and (not matcher.search(buff)):
            buff += arduino.read(128)
        return buff.strip()

And here is the Arduino C code:

String readString;

void setup() {
    Serial.begin(115200); // use the same baud-rate as the python side
}

void loop() {
    readString = listen(); // listen for any commands
    if (readString.length() > 0) {

        Serial.println(readString); // print the command

        if(readString == "ping") {
          Serial.write("ping_ok");
        }
    }
}

String listen() {
    String readString;
    while (!Serial.available());
    while (Serial.available()) {
        delay(1); // Allow the buffer to fill
        if (Serial.available() > 0) {
            char c = Serial.read();
            readString += c;
        }
    }
    return readString;
}

I suspect there is something fishy with the connection I'm making on the Python side, as the Arduino IDE serial monitor works just fine. I hope anyone can spot the problem in this code, I'm willing to provide more details on request.

Thanks


texts: Burn Bootloader to Chinese Arduino 2560 with AVR ISP programmer

texts:
I got my hands on one of these ISP programmer for Atmel AVR microcontroller in USB stick design:

Then I selected Progammer > AVR ISP and clicked on Burn Bootloader but it says

stk500_recv(): programmer is not responding.

Has anybody any experience doing this and if so, could they point me in the right direction?

Edit:
I've also added the following to programmers.txt

mySmartUSB.name=mySmartUSB
mySmartUSB.protocol=stk500v2
mySmartUSB.communication=serial
mySmartUSB.program.tool=avrdude
mySmartUSB.program.extra_params=-P{serial.port}


texts: Arduino Web Server: Receiving response from web form

texts:
I am using an Arduino Mega and I have a basic webpage built using EthernetServer for the connection and EthernetClient to write the HTML to the client. I have a simple web form:

client.println("<form method=get>");
client.println("<input type=text name=data>");
client.println("<input type=submit value=Submit>");
client.println("</form>");

I'd like to receive any input from the form and check it against values in order to do stuff on the back end (e.g. reset certain data). How do I get the data from the web page?


texts: Storing a counter to EEPROM - how to extend the life?

texts:
I am building a circuit that has a button, which when pressed, should increment a counter. I want to store this counter so that when I power off my circuit, it can be read when I power it back on. However, I am worried about the lifetime of the EEPROM - apparently it is only rated to handle 100k writes.

I am using an Adafruit Trinket Pro. Should I cycle my writes through different addresses so as not to write to a single cell over and over? What other strategies are there? I don't expect to be pressing the button many times in a short period of time - maybe at most one press per minute.

Is there some other external storage option I should look at? I really don't want my little project to die randomly one day because I've exceeded ~100k button presses!


texts: Public variable in class not incrementing

texts:
I'm not sure what is wrong with my code, but whenever I call addNewLine, the linesInserted variable is not updating correctly. When I print the value of linesInserted inside of the addNewLine method, it shows as incrementing, but when I print the value inside of the draw method, it shows that it is 0.
I have tried different increment operators (linesInserted += 1 and linesInserted = linesInserted + 1). Oddly enough, when I do linesInserted = 99 instead of linesInserted++, it sets the value correctly. I'm wondering if I am possibly messing up a reference somewhere?
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1331.h>
#include <SPI.h>

class Character {
  public:
    char** lines; // using char for 8 bit integer
    int sizeOfLines;
    char symbol;
    Adafruit_SSD1331* display;
    int width;
    draw(int x, int y, int color);
    addNewLine(char startX, char startY, char endX, char endY);
    int linesInserted = 0;
};

Character::draw(int x, int y, int color) {
  if (linesInserted < sizeOfLines) {
    display->setCursor(0, 39);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "SYMBOL %c\nWASTED MEMORY", symbol);
    Serial.println(symbol);
    Serial.print(linesInserted);
    Serial.print(" ");
    Serial.println(sizeOfLines);
    display->print(buf);
  }
  for (int i = 0; i < sizeOfLines; i++) {
    char* line = lines[i];
    display->drawLine(line[0] + x, line[1] + y, line[2] + x, line[3] + y, color);
  }
};

Character::addNewLine(char startX, char startY, char endX, char endY)  {
  linesInserted++;
  if (linesInserted > sizeOfLines) {
    display->setCursor(0, 15);
    display->setTextColor(0xF800);
    display->setTextSize(1);
    char buf[30];
    sprintf(buf, "ERROR\nSYMBOL %c\nTOO MANY LINES", symbol);
    display->print(buf);
  } else {
    lines[linesInserted - 1] = new char[4]{startX, startY, endX, endY};
  }
};

EDIT: Git repo to the project is added - https://github.com/Pyrodron/charger-destination-board


texts:
I am working with Arduino and Android. I am interested in connecting Arduino (Mega 2560 ADK) to my Android tablet (Nexus 7) wirelessly. The chepaest option is via bluetooth but the communication in not reliable. Now I would like to connect it via WiFi. But I don't want to use WiFi shield on my Arduino.

As Arduino can send the information to my laptop via serial USB connection will it be possible to put this information on my home WiFi network and get it on my Android device by connecting it to the same WiFi network?


texts: Smallest package possible reading microSD

texts:
I have a project running on an arduino nano, and as part of it, I'd like to read from and write to a microSD card.  My problem is that the microSD shield for it doesn't fit my form factor (think slightly larger than a pen; definitely handheld).

I've purchased a PJS008-2003-0, and I'm wondering, assuming I have the soldering chops, is there any real reason I can't connect this directly?  What does the breakout board get me other than nicer connection points and a blinking light?  Do the example SD sketches rely on anything the shield provides, or will they work for me?


texts:
I bought some cheap Arduino Nanos from ebay, but the watchdog does not work in them.

So I removed their old bootloader and burnt a new Nano bootloader from the Arduino IDE. Same problem, the watchdog didn't work.

Then, I burned a Uno bootloader to the Arduino Nano and now the watchdog works properly. The only issue here is that in Arduino IDE I now have to tell it that I am programming an Arduino Uno instead of a Nano. So far everything seems to work just fine.

Are there other problems that may arise from using a Uno bootloader in a Nano? I notice that there are some extra analog pins in Arduino Nano, but I will still be able to use them with the Arduino Uno bootloader right?


texts: How to power an Arduino using automated mains/rechargeable battery switching?

texts:
I'd like to power my Arduino circuit like a smartphone. That is:

When the device is unplugged, power by rechargeable battery
When the device is plugged in, power by mains and charge battery at the same time

I'd like to not go the expensive shield route and instead purchase some inexpensive breakout boards from Aliexpress or eBay if possible. I'm willing to put in the time to learn if someone will point the way.

Can someone please provide some guidance?


texts: Arduino and using a SSL secured mqtt broker

texts:
I'm looking for a library helping me to connect from an Arduino to a MQTT Broker. Of course I want to secure the connection via TLS/SSL.

The "physical" connection is established via a SIM800 module.
The Arduino itself should be as power efficient as possible (it's battery/solar powered).

In case the Arduino is too weak to perform such a task (SSL) is there any other suitable device? maybe a PyBoard?

Anyone can point me to the right direction?


texts: Uploading Arduino bootloader to ATmega32U4 with another Arduino?

texts:
I am in a situation where it is useful if I can upload a bootloader into an ATmega32U4 using another Arduino like this, for ex:https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard. I have a different circuit though.

Is there a reason to believe that this can't be adapted to ATmega32U4?

Are there any important differences between the ATmega328P and ATmega32U4, that I have to take into account for this to work?


texts: Debouncing a limit switch in Arduino ISR with delays

texts:
I have a limit switch attached to an arduino Mega 2650 for motion control. The limit switch's two Normally Open contacts are connected to an Arduino Pin and ground, such that when the Limit Switch is engaged, the Arduino Pin gets short circuited to ground.

As expected, I have bouncing issues with this setup. I confirmed it using counters in my ISRs. Finally, I wrote the following code that seems to reliably identify whether my limit switch is engaged or disengaged at any given point in time.

const int lsOuterLeftIn = 18; // lsOuterLeftIn is my Limit Switch
const int LED = 9;
volatile bool lsEngaged = false; // flag for limit switch engaged
void setup() {
    pinMode(lsOuterLeftIn, INPUT_PULLUP);
    pinMode(LED, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR1, FALLING);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR2, RISING);
}
void  loop() {
    if (lsEngaged) digitalWrite(LED, HIGH);
    else digitalWrite(LED, LOW);
}
void ISR1(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}
void ISR2(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}

But, here is my problem. I came upon this Arduino documentation page, and it says

"Since delay() requires interrupts to work, it will not work if called inside an ISR. "

But, I do make use of delay() inside ISRs and it seems to work, what is going on? Do I have a situation where things are working at the moment, but could break easily because the delay() function could malfunction on me as the documentation says?


texts:
I am worried that my Arduino is fried from a previous attempt at connecting a servo to it. To test my concerns, I changed the circuit to see if Arduino could even power a simple LED:

Code:

int led = 13;

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

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

Wiring:

In that pic, the Arduino is connected to a 9V battery. When I test the purple connections with my multimeter, the power bounces between ~5V and a weird 1.65V value every four seconds. I assume thats power being applied to the output pin in keeping with my code.

However, the LED does not light up. Any ideas as to what could be going wrong or how I could troubleshoot?


texts:
I have build a simple voltage divider with a light resistor and a 5.6k resistor. I am reading the input on A0 on my arduino board but it is almost always at 1023, independent of light. If I cover it it might go down to 1020 but not more than that.

Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?

The light sensor is similar to this: http://www.ebay.com/itm/20x-5549CDS-Photo-Light-Dependent-Sensitive-Resistor-Photoresistor-LDR-Photocell-/281425650814?pt=LH_DefaultDomain_0&hash=item418646a47e

I think that the resistance is pending between 1k-10k.

The circuit is like this image:

Where Vin is 5V from the arduino. R1 is the light sensor, R2 is 5.6k and Vout is connected to A0.


texts: Adjusting variables in code without reprogramming?

texts:
I'm a teacher, working on eliminating some difficulties of Arduino in the name of getting to the fun stuff. Namely, I am building a small Arduino powered device that will collect simple data from sensors like a DHT11, or an accelerometer. That being said, I want to pass simple settings (sample rate, sensor type, etc.) into the device with out reprogramming the board out right. I'm worried I'm over thinking the challenge. Initially, I wanted to pass the settings over serial in Python script, then save the settings to EEPROM and read them when rebooting...but sending strings over serial from Python is proving to be challenging, let alone the EEPROM.

Long term, this will run on an ESP8266 and I'd try to make a simple interface for entering the SSID and password for the Wifi network we want to connect to. Simply plug in the board over USB, run some simple little Python app that asks for SSID, password, maybe sample rate, sensor type and hit configure.

Is there an easier way to build a user interface for adjusting variables in code already running on an Arduino?


texts: Why is there a need to ground a circuit?

texts: Please tell me why I have to connect one of the wires of arduino gnd to the gnd of a relay or a bluetooth module?


texts: How to use tinygps.h library to measure distance? using NEO6mv2

texts:
any reference site for the format code for tinygps.h to measure distance?
or any codes for tinygps.h for measuring distance i'm just a beginner in learning arduino thank you


texts: How to correctly read a string from Arduino serial port?

texts:
I'm trying to communicate with my Arduiono UNO via USB serial port, more precisely I'm trying to read a string like 125,0, I know it's full of article out there about this, but belive me I've tryied more or less everything, now I got a NODEJS server on a Raspberry Pi that looks like:

var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM1", { baudrate: 115200 });

server.listen(8080);
app.use(express.static('public'));

var brightness1 = 0;
var brightness2 = 0;
var string;

io.sockets.on('connection', function (socket) {
    socket.on('led', function (data) {
        brightness1 = data.value1;
        brightness2 = data.value2;
        string = brightness1 +","+brightness2;
        var buf = new Buffer(1);
        buf.write(string);
        serialPort.write(buf);
        console.log(buf);
        console.log(string);
        io.sockets.emit('led', {value1: brightness1, value2: brightness2});

    });

So based on that, I'm sending a string over the serial and the console log showed above gives me that:

<Buffer 32>    //console.log(buf);
23,0           //console.log(string);

Wich I think it should be ok because I'm sending what I need a 32 and a 0, also if i don't know what it means the

Arduino side I used the sketch provided here and retouch it a bit based on my needs:

void setup()
{
  Serial.begin(115200);
}
void loop()
{
  while(!Serial.available());   //wait until a byte was received
      Serial.println(Serial.read());
      int a = Serial.parseInt();
      int b = Serial.parseInt();
      Serial.println(a);
      Serial.println(b);
      //analogWrite(3, a);
}

but the result of my Serial.print() are really incongruents, something like:
5--2224, which is totally nosense, my question so is WHY? Where I'm getting wrong? I read a lot around, am I missing something?


texts:
My dad told me, if i can mount some servo (to control 4 way ventil of heating) to his arduino-controlled home. But there is a problem... The servo does not have a normal 3 cables but 6 and I have no idea how to control. So i start some research about it and i found web site of manufacturer. There was also a Datasheet, but i dont understand it :D. So here is a link to the Manufacture´s web: http://www.mutmeccanica.com/prodottomutmeccanica.php?p=207
And link to datasheet: http://www.mutmeccanica.com/download_file.php?file=downloads/scheda_V70.pdf

And I have a question: Is any hope to connect this to arduino? Is there some shield for it?


texts: Run Servo when detect object on OpenCV Python

texts:
I want to connect OpenCV (Python) with arduino Uno when it detects a tennis ball.

OpenCV code:

import numpy as np
import cv2
import serial
face_cascade = cv2.CascadeClassifier('tennisballdetect.xml')
cap = cv2.VideoCapture(0)
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
print(faces)
    for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
detect=(x+y)/2
    print(detect)
cv2.imshow('img', img)
k = cv2.waitKey(30) & 0xff
if k == 27:
    break
cap.release()
cv2.destroyAllWindows()

# Module -2: Trigger Pyserial
if detect > 0:

     ser = serial.Serial('COM1', 9600)
     print(ser)
     ser.write('Y')
else:

   ser = serial.Serial('COM1', 9600)
   print(ser)
   ser.write('N')

My Arduino Code:

#include <Servo.h>
int servoPin = 3;
Servo Servo1;
char incomingBit;    // for incoming serial data

void setup() {
// We need to attach the servo to the used pin number
// Servo1.attach(servoPin);
pinMode(servoPin, OUTPUT);      // sets the digital pin as output
Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
}
void loop() {
if (Serial.available() > 0) {       // Serial.available(), which detects if
any data has been sent to the
                                   //serial port
 //  Serial.read() will read the incoming character and store it in
incomingBit
    incomingBit = Serial.read();
    Serial.print("I received:  ");
    //if the value of incomingBit is ‘Y’, we need to turn the LED ‘on’, else we turn it ‘off’. So,
    //in a nutshell,if detecting faces from a given image was successful, this will turn on the LED

            if(incomingBit == 'Y' || incomingBit == 'y') {

             // Make servo go to 0 degrees
  Servo1.write(0);
  delay(1000);
 // Make servo go to 90 degrees
   Servo1.write(90);
 delay(1000);
 // Make servo go to 180 degrees
 Servo1.write(180);
 delay(1000);
 //exit(0);
            }
            else {
              digitalWrite(servoPin, LOW);
            }
  }
}

Servo is correctly connected to Arduino and it is moving without serial communication. openCV is also working and detecting tennisball.

But when trying to connect OpenCV to arduino, servo is not moving.
Any kind of help is appreciated.