texts: Sending sensor data from Android app to arduino via USB Serial

texts: I've searched this and have only found solutions for receiving data FROM Arduino TO android, I need the opposite. I basically need to figure out how to press a button from my android phone that will activate the hardware attached to my arduino mega 2560 AND make it where my arduino can read sensor values from the android device. I'm not an expert with android or arduino, most of the code I already have pertaining to the USB Serial connection is from GitHub.


texts:
I would like to generate vibration patterns using the MPU-6050.
So if a 10p coin was dropped on a table from 1m at a 90 degree angle then I would expect the second time it dropped to make the same vibration pattern.
When I capture the movement in sensors (x,y,z), send to serial, and go into plotter mode (CTRL+SHIFT+l) I can see distinct patterns for each type of coin.
I would like to store a pattern for each type of coin drop (5p,2p, etc) dropped from exactly the same position and then use the Arduino to constantly monitor until it recognizes the next coin.
Now I could:  Use a mic, capture the sample, and use audio fingerprinting on much more powerful platform using some kind of AI.
However, I was hoping that a simple vibration could be sampled and recognised by the Arduino. Are there any libraries that could help achieve this?


texts: Why does an LED sometimes flash when increasing brightness?

texts:
This is admittedly a cross-post from LED fade malfunction (random flash)  but I can't get an answer on the Arduino forum.

I was mucking around with some very basic code and I noticed that when repeatedly holding an LED at 0 brightness for 1 second and then fading in to full brightness, a small flash would occasionally happen at the beginning of each fade (seemingly random).

int led = 11;
int brightness = 0;

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

void loop()
{
  if(brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    analogWrite(led, 255);
    brightness = 0;
  }
  analogWrite(led, brightness);
  if(brightness == 0)
    {
      delay(1000); //LED off for 1 second
    }

  brightness+=1; //increment brightness
  delay(20);
}

So, the thing that has me completely perplexed is that I can use a different piece of code (below) and the flash goes away!

int i = 0;
int led = 11;

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

void loop()
{
analogWrite(led, i);
delay(6);
if(i%256 == 0)
{
  i = 0 ;
  delay(1000);
}
i++;
}

Has anyone got any clue as to why this would happen? Both programs have basically the same code, except for that i is reset to 0 in the first program whereas in the second, i keeps incrementing past 255 so that analogWrite 'overflows.' I think it must be a firmware, (or maybe a software?) problem.

There is a video on youtube of it happening here, Arduino - fading LED problem.


texts: undefined reference to `PPMintIn::PPMintIn(int)'

texts:
I am making a new library that will utilize PinChangeInt's library.
My intention is to further simplify repetitive code by creating a library. (This is to allow for multiple PPM channels without rewriting a bunch of code for each channel i decide to add.)
Since i understand OOP i knew that i could go the route of make my own library.

The problem i'm having right now, is that the library is returning an undefined reference. The IDE i'm using is UECIDE with QTcreator on the side to help me with my syntax. The compiler is avr-gcc. The chip is an Arduino Uno. The problem i'm recieving is

  C:...\RCRoomba_TestPulseV2.cpp.o: In function '__static_initialization_and_destruction_0':
  C:...\RCRoomba_TestPulseV2.ino:5: undefined reference to 'PPMintIn::PPMintIn(int)'
  C:...\RCRoomba_TestPulseV2.cpp.o: In function 'setup':
  C:...\RCRoomba_TestPulseV2.ino:9: undefined reference to 'PPMintIn::begin()'
  Failed linking sketch

I tried to define the variables in my h and cpp files but it doesn't seem to be fixing the problem.

Here is the .ino code.
for some reason UECIDE can't see the Pinchange and PPMint libraries

#include "arduino.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PinChangeInt\PinChangeInt.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PPMintIn\PPMintIn.h"

PPMintIn CH1(A0);

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

void loop(){
}

Here is the .cpp code

#include "arduino.h"
#include "ppmintin.h"
#include "PinChangeInt.h"
//defined these
volatile int pwm_value = 0;
volatile int prev_time = 0;
uint8_t latest_interrupted_pin = 0;

PPMintIn::PPMintIn(int pin){
    pinMode(pin, INPUT);\
    digitalWrite(pin, HIGH);
    _pin = pin;
}

void PPMintIn::rising(){
    PPMintIn::latest_interrupted_pin = PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::falling(){
    PPMintIn::latest_interrupted_pin=PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::begin(){
    PCintPort::attachInterrupt(_pin, &rising, RISING);
}

void PPMintIn::getSignal(){
    return(PPMintIn::pwm_value);
}

Here is the .h code

#ifndef PPMINTIN_H
#define PPMINTIN_H

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
  #else
  #include "WProgram.h"
#endif
#include "PinChangeInt.h"

class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

#endif // PPMINTIN_H

here is the full thing in github in case I didn't supply it here.
https://github.com/tisaconundrum2/PPMintIn


texts: Arduino IDE fails on Fedora with arduino-builder error "Parameter 'tools' is mandatory"

texts:
The arduino-builder app when invoked directly with parameter --tools /usr/bin works, but the IDE fails with the error in the title for any sketch (including the Blink example).

I've tried adding things to preferences.txt like

tools.path=/usr/bin

And variations, but I keep getting the same failure in the IDE.  This is using a fresh distro package install on Fedora 27 (I did not have this problem previously using Fedora 25).


texts:
Is it possible to burn arduino code programmatically?

I was thinking of one way and that is to download hex file from my online server. Store contents of the hex file in a string, and write that string to arduino flash, restart arduino and it should run new code in flash.

Can this be done? If not than please suggest me any other way to burn the code using C++ instructions.


texts: Problem in Serial Communication between nodeMCU and arduino

texts:
I am trying to send some messages from nodeMCU to Arduino using Serial communication (aka UART). Following is the code on nodeMCU side:

#include <ESP8266WiFi.h>

const char* ssid = "my-ssid"; // SSID i.e. Service Set Identifier is the name of your WIFI
const char* password = "my-pasword"; // Your Wifi password, in case you have open network comment the whole statement.

int ledPin = 13; // GPIO13 or for NodeMCU you can directly write D7
WiFiServer server(80); // Creates a server that listens for incoming connections on the specified port, here in this case port is 80.

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

          pinMode(ledPin, OUTPUT);
          digitalWrite(ledPin, LOW);

          // Connect to WiFi network
          WiFi.begin(ssid, password);
          //Trying to connect to wifi
          while (WiFi.status() != WL_CONNECTED) {
            delay(500);
          }
          Serial.println("$Wifi Connected#");
          server.begin();
        }

        void loop() {
          // Check if a client has connected
          WiFiClient client = server.available();
          if (!client) {
            return;
          }

          // Wait until the client sends some data
          while(!client.available()){
            delay(1);
          }
          // Read the first line of the request
          String request = client.readStringUntil('\r');
          client.flush();

          int value = LOW;
          if (request.indexOf("/LED=ON") != -1)  {
            digitalWrite(ledPin, HIGH);
            Serial.println("$Led High#");
            value = HIGH;
          }
          if (request.indexOf("/LED=OFF") != -1)  {
            digitalWrite(ledPin, LOW);
            Serial.println("$Led Low#");
            value = LOW;
          }

          // Return the response
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println(""); //  do not forget this one
          client.println("<!DOCTYPE HTML>");
          client.println("");

          client.print("Led pin is now: ");

          if(value == HIGH) {
            client.print("On");
          } else {
            client.print("Off");
          }
          client.println("

");
          client.println("<button>Turn On </button>");
          client.println("<button>Turn Off </button>
");
          client.println("");
          delay(1);
        }

Following is the code on Arduino side:

String msgFromNodeMCU;
void setup() {
  pinMode(13,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  msgFromNodeMCU=Serial.readString();
  Serial.println(msgFromNodeMCU);
}

which was working fine until I modified that code to:

String msgFromNodeMCU;

void setup() {
  pinMode(13,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  msgFromNodeMCU=Serial.readString();
  delay(10);
  String wifi_connected="$Wifi Connected#";
  String led_High="$Led High#";
  String led_Low="$Led Low#";
    if (msgFromNodeMCU.equalsIgnoreCase(wifi_connected)) {
      Serial.println("Wifi Connected");
      delay(10);
    }
    if (msgFromNodeMCU.equalsIgnoreCase(led_High)) {
      digitalWrite(13,HIGH);
    }
    if (msgFromNodeMCU.equalsIgnoreCase(led_Low)) {
      digitalWrite(13,LOW);
    }
}

With this code, I see no "Wifi Connected" message on my Serial monitor and there is no response on pin 13. This implies msgFromNodeMCU is not heard. What can I do for msgFromNodeMCU to be heard? Any sort of help is highly appreciated. :D


texts: How to generate true random numbers over Arduino Uno without any external hardware?

texts: Using a 'random' function in sketch gives same pattern of numbers every-time. But, I need to generate different numbers such that any number to repeat itself should have a very less probability.


texts: How can I make Arduino IDE use Atmel's provided toolchain? (Linux/Ubuntu)

texts: I have an Arduino based board using ATmega168PB, but so far only Atmel's provided toolchain supports this microcontroller. I can download the toolchain from Atmel's website, but I am not sure how to make the Arduino environment use it.


texts:
In my design, one arduino pulls a line high on other arduino, the other arduino polls this pin and if that is high sends the data on I2C bus.

The first arduino holds the line high for 100ms using the delay() method, the other arduino is sending the data during this time, but the I2C receive interrupt is not being triggered.

I have attached a sequence diagram for a better explanation for what is happening.

I suspect that the delay() method somehow is disabling the I2C ISR from triggering.


texts: Arduino Uno vs Arduino MKR1000 analogRead discrepancies

texts: I'm using an Arduino to control a BLDC motor connected with the motor driver. It is just a simple control which I'm using a PWM as a signal. Before this, I'm used Arduino Uno pin 5 to control BLDC motor, the analogue value starts from 80. Now, I'm changed to Arduino MKR1000 board with the same pin 5 to control BLDC motor. But, for MKR1000 to rotate the motor, analogue value start from 125. My question is, why two of this board using a different PWM value for rotating the BLDC motor.


texts: How should I make a UI for my arduino project?

texts:
It's easy enough to attach a display for displaying sensor data, but I'm wondering what the proper way is to have the user change variables using an user interface on the attached 2x16 display.
The only library I found for this purpose:
https://liudr.wordpress.com/libraries/phi_prompt/

Takes a lot of code just to set up. I'm wondering if there's perhaps an easier option. All thoughts appreciated!


texts:
I'm attempting to hook up an arduino uno with a Sparkfun Oled. I downloaded the example program and made these changes:

#define PIN_RESET 3  // Connect RST to pin 3
#define PIN_DC    4  // Connect DC to pin 4
#define PIN_CS    10 // Connect CS to pin 10
#define DC_JUMPER 0

I connected everything according to Sparfun's walkthrough. I also wired accordingly. However, I cannot seem to get the Oled to do, well, much of anything. I have tried switching the MOSI and MISO to see if that makes a difference, but it doesn't seem to have any effect.

I'm using:
pin 13 - clock (in the picture I was trying pin 8 for the clock but I have tried both)

pin 12 - MISO

pin 11 - MOSI

pin 10 - CS

pin 4 - DC

pin 3 - RESET

Can anyone tell me what's going wrong? I've tried to figure it out for a good long while now and I can't make the display do anything productive.

Thanks


texts: Wireless Communication Between Raspberry Pi 2 and multiple Arduinos

texts:
I have about 10 Arduinos that have sensors attached, which report information back around my house. I would like to have a RPi 2, because they have nice screen and GUI options, to collect the information and display it accordingly.

I am looking for success stories on what wireless parts you used to get these two working. The the wireless must be able to penetrate a brick wall about 120ft away.

Thanks for replying, I edited the response above.


texts: Error initializer-string for array of chars is too long using ESP32 Webserver

texts:
i tried to use an asynchronic webserver for a new project with friends using this tutorial.
We want to run an FFT while also changing some settings via the webserver. Since the tutorial only put code in the setup() i thought it would be good for performance.
When i just copy paste the code it works pretty ok, but then i wanted to change everything into classes like a good boy. Now i get this error:
 In file included from sketch\webserver.cpp:2:0:
webserver.h:36:29: error: initializer-string for array of chars is too long [-fpermissive]
   const char index_html[] = R"rawliteral(

sketch\webserver.cpp: In constructor 'webserver::webserver()':
webserver.cpp:4:22: error: initializer-string for array of chars is too long [-fpermissive]
 webserver::webserver() {

I tried to search for a solution, but all the other problems with this type of error, didnt seem to fit with my problem.
This is the header file where the char string is declared
#ifndef webserver_h
#define webserver_h

#include "Arduino.h"
#include "ESPAsyncWebServer.h"
#include "AsyncTCP.h"
#include <WiFi.h>

class webserver {

  private:
  // Insert Private Variables And Functions

   // Replace with your network credentials
  const char* ssid     = "ESP32-Todesstern";
  const char* password = "CaptainHook";

  const char* PARAM_INPUT_1 = "input1";
  const char* PARAM_INPUT_2 = "input2";
  const char* PARAM_INPUT_3 = "input3";

  // Set web server port number to 80
  AsyncWebServer server(int port);

  // Variable to store the HTTP request
  String header;

  IPAddress IP;
  //WiFiClient client;

  public:
  //Insert Public Variables and Functions
  webserver();

  String music_state;

  const char index_html[] PROGMEM = R"rawliteral(
  <!DOCTYPE HTML>
    <title>ESP Input Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <form action="/get">
      input1: <input type="text" name="input1">
      <input type="submit" value="Submit">
    </form>

    <form action="/get">
      input2: <input type="text" name="input2">
      <input type="submit" value="Submit">
    </form>

    <form action="/get">
      input3: <input type="text" name="input3">
      <input type="submit" value="Submit">
    </form>

  )rawliteral";

  void setup_server(AsyncWebServer server);

  void notFound(AsyncWebServerRequest *request);

};

#endif

Thanks for the Help,
Xenoshell


texts: How to measure room light without LEDs interfering?

texts:
I'm trying to measure the light in a room with a simple circuit: a phototransistor connected in series with a resistor. An LED strip changes brightness according to the brightness level in the room.

The problem here is that the phototransistor also picks up the light from the LEDs. It is not an option using an IR phototransistor because I also need to measure the light from the room's light bulbs. Also, because of the device's casing, I need the sensor to be surrounded by the LED strip. Finally, I tried turning off the LEDs before measuring does not seem to work, as either the Arduino or the sensor is too slow, to turn off, perform the measurement, and turning back on the LEDs, without a human eye perceiving it.

Is there any standard or well known solution to this problem?

I will appreciate any help you can provide.

Additional Information

The LED strip is the WS2812B.
The phototransistor I'm using operates between 420 nm and 1130 nm, with peak sensitivity around 850 nm.

Furthermore, to specify the functionality I'm trying to achieve: whenever the room is dark, I want the LEDs to be not too bright. If the room is too bright, I want the LEDs to shine brighter as well.


texts:
I'm a bit of a noob in the Arduino area but I found an Arduino nano I bought a long time ago sitting on my shelf and collecting dust,
so I taught "why not make a project". I game a lot of racing games so I wanted to make a simple ignition button with it, but every time I tried to compile or verify it, it says

  Keyboard not found. Does your sketch include the line #include "Keyboard.h"


texts: How to tell if there is a line break from Nextion display to Arduino at Serial

texts:
Well I am trying make language page with Nextion display and Arduino Mega. If user enter the language page Nextion display is sending page name with this commend to Arduino for which is current page.

While page preinitializing moment.
print "dil"

If user choice a language and then press the Next button, Nextion sending this comment to Arduino.
if(r0.val==1)
{
  va0.txt="en"
}else if(r1.val==1)
{
  va0.txt="tr"
}else
{
  va0.txt="de"
}
print va0.txt
page 2

Everyting is normal until here. If user press back button at page 2 in a short time. Serial print not only send "tr" or "de" or "en" but also sending "dil" comment all together. Because of that Serial2.readString(); commend return such as "trdil" or "endil" or "dedil". So that program not working properly. Just I want to receive language's 2 letter short code.
There is a comment which is useful if I send data Arduino to Nextion to understand last of the commend line.
  Serial2.write(0xff);
  Serial2.write(0xff);
  Serial2.write(0xff);

How can tell the Arduino there is a line break after sending "tr" or "en" or "de".
Assume that I am using simple Serial receiver commend.
void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
}

void loop() {
  if (Serial2.available() > 0)
  {
    String Received  = Serial2.readString();
    Serial.println(Received);
  }
}


texts: What is ECC608 crypto chip accelerator used for in Arduino Uno Wifi rev2?

texts:
Arduino Uno Wifi rev2 includes an ECC608 crypto accelerator chip.

Even their documentation states "As for the WiFi connection, that's made secure with the new ECC608 crypto chip accelerator."

My question is: how exactly the ECC608 is used? I'd like to see the sources the Arduino makes the "WiFi secure" with it.


texts: How to shorten this code (because my sensor reads slowly)?

texts:
I'm making a fare meter for our school project. I have too much lcd.print code. This code is not finished yet. My only concern is how to minimize the usage of lcd.print. I think it's the one that makes my sensor reading slow.
I'm new at Arduino; sorry if I have too many mistakes. I appreciate any of your answers. Thank you!
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <virtuabotixRTC.h>

virtuabotixRTC myRTC(6, 7, 8);
float d[4] = {};
int x = 0;
int f = 0;
int dis = 0;
const uint8_t disBut = 13;
int input = A0;
int state = 0;
int disF = 0;
int buttonstate = 0;
LiquidCrystal_I2C lcd(0x27, 20, 4);
LiquidCrystal_I2C lcd1(0x26, 20, 4);

void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  lcd1.init();
  lcd1.backlight();
  pinMode(disBut, INPUT);
  pinMode(buttonstate, OUTPUT);
}

void loop() {
  myRTC.setDS1302Time(18, 10, 10, 7, 18, 9, 2020);

  Serial.print("Current Date / Time: ");
  Serial.print(myRTC.dayofmonth);
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print("  ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);
  delay(500);

  d[0] = (x * 1.73);
  d[1] = (x * 1.73);
  d[2] = (x * 1.73);
  d[3] = (x * 1.73);

  lcd.setCursor(8, 0);
  lcd.print(d[0]);
  lcd.setCursor(8, 1);
  lcd.print(d[1]);
  lcd.setCursor(8, 2);
  lcd.print(d[2]);
  lcd.setCursor(8, 3);
  lcd.print(d[3]);

  lcd.setCursor(0, 0);
  lcd.print(F("P1"));
  lcd.setCursor(0, 1);
  lcd.print(F("P1"));
  lcd.setCursor(0, 2);
  lcd.print(F("P1"));
  lcd.setCursor(0, 3);
  lcd.print(F("P1"));

  lcd.setCursor(6, 0);
  lcd.print(F("D="));
  lcd.setCursor(6, 1);
  lcd.print(F("D="));
  lcd.setCursor(6, 2);
  lcd.print(F("D="));
  lcd.setCursor(6, 3);
  lcd.print(F("D="));

  lcd1.setCursor(0, 0);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 1);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 2);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 3);
  lcd1.print(F("W="));

  lcd1.setCursor(6, 0);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 1);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 2);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 3);
  lcd1.print(F("dscnt="));

  lcd1.setCursor(15, 0);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 1);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 2);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 3);
  lcd1.print(F("F="));

  int counter=digitalRead(A0);
  if (state == 0) {
    switch (counter) {
      case 1:
        state = 1;
        lcd.setCursor(11, 0);
        x = x + 1; lcd.print(x);
        break;
      case 0:
        state = 0;
        break;
    }
  }

  if (counter == LOW)
    state = 0;
  if (state == 0) {
    switch (counter) {
      case 1:
        state = 1;
        x = x + 1;
        break;
      case 0:
        state = 0;
        break;
    }
  }

 if (counter == LOW)
   state = 0;
}


texts: Bootloader on Atmega328p overwrites whenever it gets programmed

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

In Summary

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


texts: How does the ssd1306 handle different screen sizes?

texts:
I noticed that if I have two SSD1306 displays, the 128x32 display will lose every other row if written in x64 mode, and the 128x64 display will show blank horizontal lines if written in x32 mode. How does this physically work, and can I expect this to be a reliable feature?

I would have thought that half the screen would get cut off somehow, but it appears that it must interlace the data instead (which seems a lot more complicated). Yet there's also some sort of configuration to the driver chip to make it do this (It seems to be the 0xDA command, but I'm not clear how/why it has these options).

Can I expect that, at least if I use the same driver library, that using the wrong screen will always have this behavior? I was planning to use it to help the user detect what screen they have.


texts: Corrupted output from HC-05 Bluetooth module

texts:
I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).

I am using 9600 baud rate and trasmitting the following:

void serialTransmit(int data){
  // send to raspberry pi or other device(s).
  Serial.print("Serial Transmit: ");
  Serial.println(data); // this is hard coded as "12" for testing
}

I tried switching rx/tx pins around but got same corrupt output. Tried changing baud rate but then it wouldn't transmit anything at all and default rate is 9600 so that was expected.

What could be the cause?


texts: How to get variable from callback function?

texts:
There is a library  davetcc / IoAbstraction. The only library working as expected with my rotary encoder. The problem that on rotation I can only see serial output with position data, but I cannot get these data as some variable value.
There is the swithch initialization and function definition in main.cpp
switches.addSwitch(spinwheelClickPin, onSpinwheelClicked);
void onSpinwheelClicked(uint8_t pin, bool heldDown) {
  Serial.print("Button pressed ");
  Serial.println(heldDown ? "Held" : "Pressed");
}

The definition from SwitchInput.cpp
bool SwitchInput::addSwitch(pinid_t pin, KeyCallbackFn callback,uint8_t repeat, bool invertLogic) {
    if(internalAddSwitch(pin, invertLogic)) {
        KeyboardItem item(pin, callback, repeat, invertLogic);
        return keys.add(item);
    }

    return false;
}

There is the callback function type definition from SwitchInput.h
typedef void(*KeyCallbackFn)(pinid_t key, bool heldDown);

I canon just change void to bool. So how can I get this heldDown variable value?
Sorry if the question is stupid.


texts: 16 X 2 LCD display blank with Arduino Uno

texts:
So I am following this tutorial to make my arduino display hello world and millis(), I got it to work for a minute, but then it stopped updating the milliseconds, and when I pushed the reset button it went blank. since then, It has been blank but I have double, triple, and qaudruple checked checked my wiring, and it is flawless. I tried it with both of my 16 segment displays, but to no avail. I have redone the wiring, but it is still blank. Does anybody know what I could be doing wrong?

I followed this diagram
this is my code:

// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

This is the result (the screen is lit up, but there is no text even when turning the potentiometer)


texts:
I have a string:

string s="digitalWrite(8,LOW);"

Is there any way to run it as a code?


texts:
I have the Arduino Uno (non-original replica) board, general SPI lcd, and GUVA-S12SD analog UV sensor module.
The board (powered via USB) reads the data from the analog pin 0, converts it to voltage (multiplying the readout by (5.0/1023.0) ) and prints out to the LCD.

Being illuminated with an UV-flashlight, the sensor gives unstable readouts varying for around 0.03-0.04 V each readout cycle. I am a complete noob in electronics, so I want to ask how can I check where the problem is? Is this my error in wiring, faulty module, just normal behaviour of an analog sensor or something else?

Mine sensor module isn't from Adafriut and looks a bit different, the one in the diagram is just to show the general wiring.

Thanks!

(Sensor module description: https://www.electroschematics.com/11509/guva-s12sd-uv-sensor-module-circuit/ )

The code of the sketch is:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
int sensorValue;
float sensorVoltage;
LiquidCrystal_I2C lcd(0x27,16,2);  // display setup
void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("");
}

void loop() {
  sensorValue = analogRead(A0);
  sensorVoltage = sensorValue * (5.0 / 1023.0);
  lcd.setCursor(0, 0);
  lcd.print(sensorVoltage/0.1); // rather low voltage is expected
  delay(1000);
}

Update: I tried to measure the output with a multimeter (as Vasekdvor suggested in answers) and it showed very similar results: continuous 0.04-0.07 V oscillations. Their magnitude seems to grow along with the intensivity of the illumination.

With sensor being dark, multimeter shows 0.006 V (changing to 0.007 V occasionally) between A0 pin and the ground.


texts: Can I control analog IO pins using Yun Linux

texts:
2 days back I bought Arduino Yun. I'm able to flash Led on 13 pin. And I'm able to flash Led on Bread board connected to A0. I'm able to run linux commands.

Now I want control A0 pin using Linux/Python program. Is this possible? I read many documents. But I didn't find thing related to this.

How I  can flash the LED using Linux programs?


texts:
I'm using STM32(generic board) and I want to control bi-color LED(common anode). STM32 pin layout and scheme is below, so please see it.
Now, in theory scheme Works, but in practice it Works halfway. Red LED is connected with PB8 pin and green LED is connected with PB3 pin.
Code is simple so I think that problem is not in the code. Red LED Works, but green doesn't work. If I connect green cathode with GND manually, then it Works, otherwise(with STM32) it doesn't.
Later I found that pin PB3 has Trace SWO mark(see pin layout below). I'm not completly sure what Trace SWO means, just found that it some kind of debugigng protocol(I guess) but I can't find info can it be used for digitalWrite purposes. Is there any way to habilitate PB3 pin for digitalWrite? All other pins are in use.

Code:

// DOWN
digitalWrite(PB3, HIGH);
digitalWrite(PB8, LOW);
delay(750);

// UP
digitalWrite(PB8, HIGH);
digitalWrite(PB3, LOW);
delay(750);

STM32 pin layout

R4 doesn't exist, it's mistake in scheme


texts:
I'm trying to get GPS coordinates using my SIM808 module by connecting it with Arduino. When I use this code,

#include "SIM900.h"
#include <SoftwareSerial.h>
#include "gps.h"

//To change pins for Software Serial, use the two lines in GSM.cpp.

//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.

//Simple sketch to start a connection as client.

GPSGSM gps;

char lon[15];
char lat[15];
char alt[15];
char time[20];
char vel[15];
char msg1[5];
char msg2[5];

char stat;
char inSerial[20];
int i = 0;
boolean started = false;

void setup() {
  //Serial connection.
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");
  //Start configuration of shield with baudrate.
  //For http uses it is recommended to use 4800 or slower.
  if (gsm.begin(2400)) {
    Serial.println("\nstatus=READY");
    gsm.forceON(); //To ensure that SIM908 is not only in charge mode
    started = true;
  } else Serial.println("\nstatus=IDLE");
  if (started) {
    //GPS attach
    if (gps.attachGPS())
      Serial.println("status=GPSREADY");
    else Serial.println("status=ERROR");
    delay(20000); //Time for fixing
    stat = gps.getStat();
    if (stat == 1)
      Serial.println("NOT FIXED");
    else if (stat == 0)
      Serial.println("GPS OFF");
    else if (stat == 2)
      Serial.println("2D FIXED");
    else if (stat == 3)
      Serial.println("3D FIXED");
    delay(5000);
    //Get data from GPS
    gps.getPar(lon, lat, alt, time, vel);
    Serial.println(lon);
    Serial.println(lat);
    Serial.println(alt);
    Serial.println(time);
    Serial.println(vel);
  }
};

void loop() {
  //Read for new byte on serial hardware, and write them on NewSoftSerial.
  serialhwread();
  //Read for new byte on NewSoftSerial.
  serialswread();
};

void serialhwread() {
  i = 0;
  if (Serial.available() > 0) {
    while (Serial.available() > 0) {
      inSerial[i] = (Serial.read());
      delay(10);
      i++;
    }
    inSerial[i] = '\0';
    if (!strcmp(inSerial, "/END")) {
      Serial.println("_");
      inSerial[0] = 0x1a;
      inSerial[1] = '\0';
      gsm.SimpleWriteln(inSerial);
    }
    //Send a saved AT command using serial port.
    if (!strcmp(inSerial, "TEST")) {
      stat = gps.getStat();
      if (stat == 1)
        Serial.println("NOT FIXED");
      else if (stat == 0)
        Serial.println("GPS OFF");
      else if (stat == 2)
        Serial.println("2D FIXED");
      else if (stat == 3)
        Serial.println("3D FIXED");
    }
    //Read last message saved.
    if (!strcmp(inSerial, "MSG")) {
      Serial.println(msg1);
    } else {
      Serial.println(inSerial);
      gsm.SimpleWriteln(inSerial);
    }
    inSerial[0] = '\0';
  }
}

void serialswread() {
  gsm.SimpleRead();
}

After some time, I get this error on the Serial Monitor of Arduino:

status=ERROR

The connections are as follows:

TX of Module = Pin 2 of Arduino
RX of Module = Pin 3 of Arduino
GND of Module = GND of Arduino
5V of Module = 5V of Arduino

The Arduino is powered by USB connected to my PC.


texts:
I am trying to make my own delay function. Briefly mydelay function is calling toggled function every secs seconds. The code is not well written, i know (this is the first version). But i am just trying to get it work properly. Then i will refactor it. But i have some unexpected bugs. First time the loop in x function is working properly. It is printing "I am in while" for 1 second and then it prints "Im ending mydelay" which is the behaviour i want. But after finishing the loop in x. The second time when it loops. It enters the mydelay function (that is ok). But then it is not printing "I am in while" at all. It just prints "Im ending mydelay" which is not good.

Here is the code:

#include <Arduino.h>
int led = 7;
void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  x();
  Serial.println("Im ending main loop");
}

void x() {
  for (int i = 0; i <= 10; i++) {
    mydelay(led, 0, 1);
    mydelay(led, 1, 1);
  }
}

void mydelay(int pin, int hol, int secs) {
  int starttime = millis();
  while ((millis() - starttime) <= (secs * 1000)) Serial.println("I am in while");
  toggled(pin, hol);
  Serial.println("Im ending mydelay");
}

void toggled(int pin, int hol) {
  digitalWrite(led, hol);
}


texts: How to use the additional SPIs on Arduino Due

texts:
According to the following image it is possible to use a second SPI bus on the Arduino Due by using Serial1 and SCL1 as SCK0 for SPI (or Serial2 and SCK1).

source

However I did not find the code necessary to set up the additional SPI interfaces. I would prefer using these SPI interfaces as they are accessible on the stacking headers in contrast to the default SPI.

Additionally can a SD-Card be accessed using these SPI buses while still using the corresponding Arduino Library?


texts: Working with multiplexers for constant voltage output

texts:
I'm working on creating a circuit where I'm trying to have the ability to switch multiple strands of LED rope on and off at a time using an Arduino and a multiplexer.

With my current configuration, I have the a circuit and a sketch that will cycle through the various LED rope strands, turning them on and off.

What I'm not sure how to do is modify my sketch / circuit so that I can turn ALL of the rope strands on and off, as well as individually.

Below is my current Arduino sketch:

//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);

}

void loop(){

  //Loop through and read all 16 values
  //Reports back Value at channel 6 is: 346
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

I'm using two multiplexers to control multiple rope strands. Here's roughly what that looks like:

I'm still a bit new to electronics prototyping (coming from software development); so I'm not sure if what I want to do is possible with a multiplexer

Happy to start offer a bounty to a helpful answer.

Thank you


texts: Arduino GSM Shield NET and STATUS led turn off after a few seconds

texts:
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;     // include a 'true' parameter to enable debugging
GSMScanner scannerNetworks;
GSMModem modemTest;

// Save data variables
String IMEI = "";

// serial monitor result messages
String errortext = "ERROR";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("GSM networks scanner");
  scannerNetworks.begin();

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  // get modem parameters
  // IMEI, modem unique identifier
  Serial.print("Modem IMEI: ");
  IMEI = modemTest.getIMEI();
  IMEI.replace("\n", "");
  if (IMEI != NULL) {
    Serial.println(IMEI);
  }
}

void loop() {
  // scan for existing networks, displays a list of networks
  Serial.println("Scanning available networks. May take some seconds.");
  Serial.println(scannerNetworks.readNetworks());

  // currently connected carrier
  Serial.print("Current carrier: ");
  Serial.println(scannerNetworks.getCurrentCarrier());

  // returns strength and ber
  // signal strength in 0-31 scale. 31 means power > 51dBm
  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
  Serial.print("Signal Strength: ");
  Serial.print(scannerNetworks.getSignalStrength());
  Serial.println(" [0-31]");
}

Results:
When I run the program, I can see the "GSM networks scanner" message appear on my serial monitor, but it does not display anything else after that. Also, the NET and STATUS LEDs turn off after some few seconds when the program starts running. I already made the minor adjustments necessary for the Arduino Mega, and the power supply is temporarily from the USB port of my laptop connected to the Arduino Mega. I am using a SIM card that has been activated.

I think my program stops at this stage:

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

P.S. when I run the program without inserting a SIM card, the NET and STATUS LEDs keep on working (NET is blinking, while STATUS remains ON)

I tried this program as well https://www.arduino.cc/en/Guide/ArduinoGSMShield#toc9
and it has the same problem (i.e. stops at the same stage as the previous program)


texts: MEGA2560 only starts program after pressing RESET button multiple times

texts:
I am working on a program where I am controlling an MP3 player by using UART between my MEGA2560 and the MP3 player. The MEGA2560 sends serial commands to the MP3 player when external interrupts are generated on INT4 and INT5 and it all seems to work fine.

When I want to test my program I press the RESET button on the Arduino in order to start the program. However, sometimes the program only starts after pressing the RESET button multiple times. This happens often but not all the time, which is weird.

What do you think could be the reason for this?


texts: arduino mega overheat when connected to TFT 7" and TFT shield

texts: I have bought a 7" LCD (TFT01-7) and a shield to make it work with arduino mega (http://www.elecfreaks.com/store/lcd-tft01-mega-shield-v10-p-214.html), but when I upload my code to the arduino and plug my LCD to the shield the arduino get overheated and the LCD lose power and I don't know why even when I power my arduino with external 9V 2A adapter, I even tried uploading an example from the library but it does the same, I used to work with the same code and the same shield but with 5" LCD ITDB50 and I didn't have this problem before, how can I fix this?


texts: How to transfer serial data or plot wirelessly on an arduino?

texts:
I have an arduino uno and an accelerometer connected reading vibrations. I want to be able to send the serial data or serial plot wirelessly from the arduino to any program(recommendations will be considered) on the pc without using the USB port on the pc. Is it possible?

I have an arduino ethernet shield, bluetooth modules HC-05 and HC-10 all at hand if they will be helpful.
please help, any help would be greatly appreciated.


texts: Using Arduino with through beam sensor on combine harvester

texts:
I have a project where I'm trying to capture the output from a through beam sensor (infra red) installed on a combine harvester. I'm not much of an electronics wiz but was hoping it was going to be simple to capture the output from this sensor whilst not interfering with the operation of the sensor as far as the combine harvesters electronics were concerned.

The receiver component of the sensor has 3 wires, ground, 12v supply and output (sensor) lead. If the receiver can see the transmitter the voltage on the sensor wire is 5v when it cant see the transmitter its voltage is 1.5v. Strangely if I remove the sensors from the combine and power them on the test bench, the sensor will pass the powered voltage i.e if supplied with 12v then the receiver will pass 12v on the sensor wire if it can see the transmitter. I think the combine electronics are doing some trickery way beyond my understanding BUT that's fine, all I want to do is capture the pulse from the sensor and pass it to an Arduino without interfering with the combines electronics.

I have tried a couple of setups to no avail this is my last attempt but I cant get a signal from the sensor. I'm not sure the diode (D1) is required but as I had it I added it. In a test environment I can add 5v through R2 and the PC817 triggers and I pick a pulse up on the Arduino. All grounds are linked and the Arduino is powered from the 12v coming from the ecu.

simulate this circuit – Schematic created using CircuitLab

Is there a clever bit of circuit or component which I can use to steal the pulse from the through beam whilst not interfering with its operation as far as the combines systems are concerned?

Any help appreciated with regards to how to properly design a circuit and how to make this work. I have been reading about op amps but not sure that will sort the problem.


texts: Is it possible to make an Arduino send signals to an RC receiver?

texts:
I have found bunch of information about how to hack an RC car with a PCB; and how to control an Arduino from a receiver. Also how to run a servo from an Arduino, but I'm looking for a way to make an Arduino send signals to a 27 MHz 3 channel receiver, Using three potentiometers to decide servo location.

Is there any information about this somewhere? - I have an old transmitter lying around if needed.

Links, pointers - anything is welcome.

[It does not have to be 27 MHz AM, it is just what I have on the shelve, without investing in new gear]


texts:
#include <IRremote.h>
const int pingPin=7;
int PIR=0;
int IR_Recv=11;
IRrecv irrecv(IR_Recv);
decode_results results;

void setup ()
{
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(10, OUTPUT);

  Serial.begin(9600);
}

void loop()
{long duration,cm;
 pinMode(pingPin, OUTPUT);
 digitalWrite(pingPin, LOW);
 delayMicroseconds(3);
 digitalWrite(pingPin, HIGH);
 delayMicroseconds(3);
 digitalWrite(pingPin, LOW);

 pinMode(pingPin, INPUT);
 duration = pulseIn(pingPin, HIGH);

 cm = microsecondsToClockCycles(duration);

 Serial.print(cm);
 Serial.print("cm");
 Serial.println();
 if(cm<50)
 {
   digitalWrite(13, LOW);
   digitalWrite(12, LOW);
   digitalWrite(10, HIGH);}
 else
 {
   digitalWrite(13, LOW);
   digitalWrite(12, HIGH);
   digitalWrite(10, LOW);
 }
}
 if (IRrecv.decode (5results))
 {

 long int decode = results.value;
   Serial.println(results.value);
   switch(results.value);
   {

     case 16593103: Serial.println("0");
        digitalWrite(13, HIGH);
        digitalWrite(12, HIGH);
        digitalWrite(10, HIGH);
     break;

     case 16582903: Serial.println("1");
        digitalWrite(13, LOW);
        digitalWrite(12, LOW);
        digitalWrite(10, HIGH);
     break;

     case 16615543: Serial.println("2");
        digitalWrite(13, HIGH);
        digitalWrite(12, LOW);
        digitalWrite(10, LOW);
     break;

     case 16599223: Serial.println("3");
        digitalWrite(13, LOW);
        digitalWrite(12, HIGH);
        digitalWrite(10, LOW);
     break;

     case 16623703: Serial.println("5");
        digitalWrite(13, HIGH);
        digitalWrite(12, HIGH);
        digitalWrite(10, LOW);
     break;

   }
irrecv.resume();
 }
}
long microsecondsToInches(long microseconds);{
  return microseconds / 74 / 2;
}
long microsecondsToCentimetres(long microseconds);{
  return microseconds / 29 / 2;
}


texts: Getting different numbers after sending an unsigned int 8-9 times between Arduinos via Serial

texts:
I am trying to transfer unsigned int values between 2 Arduinos. When sending 61805 for the first 8-9 times, I am getting 61805.  But after then after these numbers: 61937 28013 61937.
Sender's code:
unsigned int s = 0;

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

void loop()
{
  s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

Receiver's code:
unsigned int upperByte, lowerByte, r=0,p=0;

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

void loop ()
{
  if (Serial.available() > 1)
  {
    upperByte = Serial.read();
    lowerByte = Serial.read();
  }

  r = (upperByte << 8) + lowerByte;
  Serial.println(r);
}


texts: arduino leonardo stops transmitting once hdmi cable is connected to a screen

texts: I am using arduino leonardo for moving mouse pointer with head tracking using MPU6050. It works fine in general. But as soon as I connect an external lcd screen to my laptop via hdmi cable, it stops transmitting. (that is the TX led goes off altogether and the mouse stops moving) I am not able to figure out what the issue is here Will using a teensy 3.0 instead of leonardo solve this problem?


texts: Timer for Control Motor using Limit Switch

texts:
Im not good in arduino, but I have project that control motor using limit switch.

The rule is:

When switch OFF, motor ON
When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)
After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.


texts: Arduino Serial Communication with Python: sending an array

texts:
I am a bit new to both Arduino and Python. My aim is to send commands to Arduino to run a stepper motor. I need to send an array containing the parameters. After consulting many earlier posts like:

https://stackoverflow.com/questions/27639605/send-a-list-of-data-from-python-to-arduino-using-pyserial

Send multiple int values from Python to Arduino using pySerial

I wrote my Arduino code:

long  incoming[3];

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready");
}

void loop() {
  if(Serial.available()) {
    for (int i = 0; i < 3; i++) {
      incoming[i] = Serial.read();
    }
    Serial.println(incoming[0]);
    Serial.println(incoming[0]);
    Serial.println(incoming[2]);
  }
}

And the Python(2.7) code:

from time import sleep
import serial
import struct
ser = serial.Serial('COM6', 9600)

while True:
     ser.write(struct.pack('>iii',2000,10,220))
     print ser.readline()
     sleep(.5)

Now coming to the problem:

The values printed on the Python shell are completely wrong, including negative values.
If I use >BBB instead of >iii, I am getting the correct result, but I can't go beyond 255, the integer limit. There is a small catch here also, the initial two sets are giving minus values and then it becomes alright.
Further, is there any way to interrupt a running void loop?

Any help is deeply appreciated.


texts: Water pump controlled by soil moisture sensor

texts:
I'm just learning to code in Arduino.

The purpose is that first the sensor measures the moist level (I mapped the reading values from 0 to 100). If the value is less than threshold 70, then it will turn on a water pump. As soon as the value goes beyond 70, the pump stops pumping water.

The problem is that even when the value is less than 70, the pump doesn't work.

I tried replacing the pump with a LED, it turns on a the right moment. I tested the pump itself, and it also works perfectly.

//for mapping values
int mostMoist = 100;
int leastMoist = 600;
int percent;

//direct value from sensor
int raw;

//threshold for minimum percentage to turn on pump
const int threshold = 70;

//initial state of water pump
bool dosomething = false;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  //if it's not pumping water:
  while (dosomething == false){
  //check sensor value, map out of 100, and display on monitor
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);
  if (percent < 0){
    percent = 0;
  }
  Serial.println(percent);
  Serial.println("dosomething is set to false");

  //check if percentage moist is less than threshold. if so, set dosomething true, orelse, loop dosomething false
  if (percent<threshold){
    dosomething = true;
  } else{
    dosomething = false;
  }
  delay(2);
  }

  //if it's pumping water:
  while (dosomething==true){
  //check sensor value, map out of 100, and display on monitor
  raw = analogRead(A0);
  percent = map(raw,leastMoist,mostMoist,0,100);
  if (percent < 0){
    percent = 0;
  }
  //turn on pump
  digitalWrite(13,HIGH);
  Serial.println("dosomething is set to true");
  //check if percent moist is less than threshold value, if so, loop dosomething true, orelse, set dosomething false
    if (percent<threshold){
    dosomething = true;
  } else{
    dosomething = false;
  }
    Serial.println(percent);
  delay(2);
  }

}


texts: LED and Switch Compolation Error Arduino 101

texts:
I'm getting an error on line 9 for some reason, (digitalWrite(Sender, HIGH);), and I just cant figure out why. My goal is to have two sets of flashing patterns, one for each switch state. I don't know how important this is but I'm using an Arduino 101. This is also my first day programming so the answer could be staring me right in the nose, (in fact, I would prefer that haha). Thank you for your time!

// Starting this by declairing intigers
int Sender = 2; // Switch Out on pin two
int LedG = 10; // LED Green out on pin ten
int LedR = 11; // LED Red out on pin eleven
int Reader = 12;  // Switch Input on pin twelve
//configuring I/O
pinMode(Sender = OUTPUT); // Setting pin two to output
pinMode(Reader = INPUT); // Making pin 12 set to read switch data
digitalWrite(Sender, HIGH); //Making pin two hot
//main loop
void loop() {
  if (digitalRead (Reader) == HIGH) { // if Switch input is reading on than do pattern A
    digitalWrite(LedG, HIGH); //turning on green led
    delay(50); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
    digitalWrite(LedR, HIGH); //turn red led on
    delay(50); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
  }
  else { //if switch input is readion off than play pattern b
    digitalWrite(LedR, HIGH); //turn red led on
    delay(1000); //delay next instruction
    digitalWrite(LedR, LOW); //turn red led off
    digitalWrite(LedG, HIGH); //turning on green led
    delay(1000); //delay next instruction
    digitalWrite(LedG, LOW); //turn green led off
  }
}


texts: How to add additional include path (e.g. as a flag) to Arduino Compiler?

texts:
I have been trying for a while to add an additional include path to Arduino compiler (in VS-Code) to be able to compile my project that has header and source files distributed in different levels of folders.
Including the directories I want in the includePath in c_cpp_properties.json is not enough because this includePath is used only for the IntelliSense (and apparently that is right because I am not able to compile, because the header files cannot be found, even though the IntelliSense works).
The only hope I found is to pass an additional flag -I to the compiler, this is what I tried to do (I tried both using the workspace variable and the absolute path, but none worked):
{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "C:\\Users\\MYUSER\\AppData\\Local\\Arduino15\\packages\\esp8266\\tools\\**",
                "C:\\Users\\MYUSER\\AppData\\Local\\Arduino15\\packages\\esp8266\\hardware\\esp8266\\2.7.4\\**",
                "${workspaceFolder}\\include\\**"
            ],
            "compilerPath": "C:/Program Files (x86)/Arduino/hardware/tools/avr/bin/avr-gcc.exe",
            "forcedInclude": [],
            "intelliSenseMode": "clang-x64",
            "cStandard": "c17",
            "cppStandard": "c++17",
            "compilerArgs": [    <<===== Trying to pass the include path to the compiler.
                "-I${workspaceFolder}/include",
                "-IC:/Users/MYUSER/MYPROJECT/Firmware/include"
            ]
        }
    ],
    "version": 4
}

But my tries did not work, I am still not able to compile, because the compiler cannot find the header files. Using the absolute path of the header files directly in my CPP code is not an option.
What am I doing wrong? Could anyone please help me to be able to pass the include paths to the compiler successfully?
UPDATE
Checking the output of compilation in verbose mode shows that the paths I tried to include are not considered (there didn't present in the output at all). I am not sure why they are ignored...


texts: How can I differentiate between multiple circuits?

texts:
I'm building a puzzle for an escape room. I want to give the user 6 wires and 6 terminals, then confirm that they've connected the correct wires to the correct terminals (one-to-one).

My first (successful) attempt to implement this puzzle was to connect the wires to 6 PWM analog outputs set to different levels, and connect the terminals to 6 analog input pins. By time-averaging the readings on the input pins, I was able to determine which wire(s) are connected to which terminals, if any.

I currently have no resistors in the circuits.

As the puzzle is currently designed, it's possible for the user to do weird things like:

Connect multiple wires to the same terminal.
Connect multiple wires together, without connecting them to any terminal.
Touch multiple exposed wires and/or terminals.

My questions boil down to two:

Is my current approach dangerous, either for the Arduino or my users, and are there recommended precautions I should take?
Is there a better (safer or simpler or more robust) way to implement the puzzle?

I'm a software engineer, but a complete noob when it comes to real electronics and Arduino, so please feel free to assume I know nothing.


texts: Utilizing two different serial ports simultaneously on a due

texts:
I am trying to understand how the serial ports are configured on the due board. Please correct me if i'm wrong, but to my understanding, the due has:

Four separate serial ports ("serial", and "serial 1-3"), each with SX and TX pin functions
A USB port paired with serial, simultaneously sending and receiving data from the serial function via USB protocol

I'm currently sending MIDI data over serial1 with the required baud rate of 31250. I want to configure another serial function (assumingly with a different baud rate to match the IDE serial monitor) in order to monitor Serial.print messages simultaneously for debugging.

In setup():

Serial1.begin(31250);  //MIDI baud rate
Serial.begin(115200);

and then, in a for loop i want to monitor each value i in the array loop1[i]):

Serial.print(String(loop1[i]) + " ");

However, i can't seem to make it work... My question is, is it possible to transmit the MIDI data via serial, in parallel with serial.print data with a separate serial function?


texts: Detect movement on moving robot? PIR Sensor

texts:
I am working on a human following robot project and I am trying to achieve this with 1 Ultrasonic sensor that makes sure the robot won't crash into something and 3 PIR sensors that will detect human movement.

The robot has an Ultrasonic Sensor and a PIR sensor attached to the front and a PIR sensor attached to the right side and another PIR sensor attached to the left side.

If the front PIR reads HIGH, then the robot will move forward. If the left or right PIR reads HIGH, then the robot will start turning in a 360 degree motion to the left/right side and will keep on doing so until the front PIR reads HIGH, and the robot moves forward again.

I am currently working with this build and I am having issues with the sensors. Sometimes they read HIGH when they shouldn't and sometimes they read LOW when they should be reading HIGH.

So my question is, what can I do to help the PIR sensors with getting the correct reading and is it possible to do so while the robot is turning?

Also, how will calibration work here? Am I able to let the robot turn slowly in 360 degree motion so the 3 PIR sensors will be calibrated with the rooms surrounding or is this a dumb question? If so I'm sorry, I am pretty new to PIR sensors.

UPDATE:

Thanks for the help everyone. I have now replaced the side PIR sensors with Ultrasonic sensors. I have kept the front PIR sensor though. It is working a lot better than with the side PIR sensors and I thank you all for your input.


texts: Continuous push button detection in for Stepper control

texts:
Currently, I've worked on code for controlling stepper motor with pushbuttons. So, basically, I have to press two push button to run forward and backwards.
but the problem is when I press the 1st pushbutton it detects that pushbutton and run motor CW or CCW,  That means it cannot detect the press of another pushbutton to make it counterclockwise.
I realize that the program isn't detecting the second push button after pressing 1st one.
Tried different options to make it work. but failed.
any suggestions?
Here's my code for reference:-

#include <AccelStepper.h>

const int button1Pin = A2 ;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
   pinMode(button1Pin, INPUT);
   pinMode(button2Pin, INPUT);

   Serial.begin(9600);
}

void loop()
{

      int sensorReading = analogRead(A0);
      int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

     stepper.setMaxSpeed(2000);
     stepper.setSpeed(motorSpeed);

     if (button1State == HIGH)
       {

        stepper.setSpeed(motorSpeed);
        Serial.print("ok");
        stepper.runSpeed();

       }

  if (button2State == HIGH)
       {

        Serial.print("ok2");
        stepper.setSpeed(-motorSpeed);
        stepper.runSpeed();

      }
}

Another problem is in this current code, it cannot detect the potentiometer input inside the if ( button state ) {} loop.
it would be a great help pointing out my mistakes.


texts: How to send IR data from Arduino to USB-TTL

texts:
I have a led receiver KY-022 and led emitter KY-005, I also have a PL2303 (USB-TTL). This is the code of the issuing LED:

#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     //Serial.print(0xa90,HEX);
     delay(40);
   }
}

The following is the connection scheme:

The output of the KY-022 I have connected to the pin RXD of the PL2303 which has a led that indicates that it receives data, however when using the HyperTerminal program to see the data I receive nothing appears.

I found similar information but they use another LED model, however I think it should work the same. What can I do?

I'm also testing with node js using the node js package, but in the console I only get non-readable characters, or something like this Buffer 00 e0 e0 e0 e0 if I do not apply toString () to the data.

This is my code in node JS.

var SerialPort = require('serialport');
var io = require('socket.io').listen(3000);

var serialPort = new SerialPort("COM9", {
    baudRate: 9600,
    parser: new SerialPort.parsers.Readline("\n")
});

io.sockets.on('connection', function(socket){
    socket.on('message', function(msg){
        console.log(msg);
    });

    socket.on('disconnected', function(){
        console.log('disconnected');
    });
});

var clearData = "";
var readData = "";

serialPort.on('open',function(){
    console.log('open');
    serialPort.on('data', function(data){
        console.log(data);
        readData += data.toString();
        io.sockets.emit('message',data);
    });
});


texts: NodeMCU ESP8266 Ver 0.1 not powering on with VIN

texts:
I'm trying to power on my NodeMCU ESP8266 Ver 0.1 (thats what is written in board), via VIN and Ground with my phone charger.
I'm 100% sure that the USB charger is working, providing 5V, and that the ground and VIN are connected to the right positions.
If I use the same phone charger via the NodeMCU USB, the program blinks the builtin led alright.
If I power via VIN, it flashes when I connect the charger to DC, but the program does not work.
It seems as the NodeMCU is not powering on complety.
Bizarrely, if I short 3V and G pins, the board starts working normally as powered directly via USB port.
This is the code
/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}


texts: I am trying to write a float value to the EEPROM on an Arduino MEGA2560. According to some research I should use Arduino EEPROMex library. I added the library to Arduino, but I get the message "EEPROM was not declared in this scope". How can I solve this problem or have you got any suggestions to do this?


texts:
I am trying to control a servo using keyboard.

void loop() {
if (Serial.available() > 0) {
  x = Serial.parseInt();
  while(pos < 180){
  pos = x + pos;
  Serial.println(pos);
  myservo.write(pos);
  delay(100);
 }
  }
else if(Serial.available() > 0){
if(pos>=180){
  pos = 0;
  delay(500);
  myservo.write(0);

  }
  }
 }

Right now the servo takes the input correctly. The only thing is that it wont change positions immediately. It will wait until it hits 180 resets to 0 and then use the input I put in. This isnt the behaviour I want. I want it to change immediately. How Do I set this up?


texts: Error: "invalid use of non-static member function" while calling a function from my own class-method

texts:
I'm having a bad time trying to call a correctly-working expression (ultra[currentSensor].ping_timer(echoCheck)) from an own class method (myclass::run) instead of from void loop().

I'm getting the following compiler error:
"invalid use of non-static member function".

If I call ultra[currentSensor].ping_timer(echoCheck) directly from void loop() it gives me no error, so I may be missing something.

Here's the (shortened) piece of code which is generating the error:

#include <NewPing.h>

#define ULTRA_NUM      3
#define MAX_DISTANCE 200

class myclass {
  public:

    void run();
    void echoCheck();

    unsigned int distance[ULTRA_NUM];
    uint8_t currentSensor = 0;
};

NewPing ultra[ULTRA_NUM] = {
  NewPing(4, 5, MAX_DISTANCE),
  NewPing(6, 7, MAX_DISTANCE),
  NewPing(8, 9, MAX_DISTANCE)
};

void myclass::run() {
// ....
      ultra[currentSensor].ping_timer(echoCheck);  // Compiler error
  }

void myclass::echoCheck() {
  if (ultra[currentSensor].check_timer())
    distance[currentSensor] = ultra[currentSensor].ping_result
}

ping_timer() is defined as it follows:

void NewPing::ping_timer(void (*userFunc)(void), unsigned int max_cm_distance) {
    if (max_cm_distance > 0) set_max_distance(max_cm_distance);

    if (!ping_trigger()) return;
    timer_us(ECHO_TIMER_FREQ, userFunc);
}

I hope any of you can help me!

Thanks in advance,

Eduardo

Edit:
What I am trying to do is to adapt this example (from NewPing Arduino Library) so that the sonar ping (sonar[currentSensor].ping_timer(echoCheck)) is done from a class method, and not from void loop().


texts: Having some trouble incrementing counters

texts:
So, I have some simple code here. I'll just try and explain what I am trying to have my code do here.

I am trying to rotate my stepper motor by half a turn, and then move it back and forth by 200 steps or so.

The problem I have is in my loop function, where I have a variable called ctr. I am trying to increment this ctr when I execute an if statement. The ctr increments inside the if statement and I can see the result when I do Serial.println as it changes to 1. However, when I Serial.println(ctr) right below the if statement, it prints out as 0 even after the previous print statement prints out 1.

Why is this happening? I am a C/C++ noob, so is there something I am missing about variable scoping or pointers?

void loop()
{
    stepper1.run();
    int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      ctr++;
      Serial.println(ctr);
    }
    Serial.println(ctr);
    if(stepper1.currentPosition() == 824 && ctr > 0){
      forthMotion(stepper1.currentPosition());
    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}


texts: ESP8266 - AT Command for Network Requiring Username AND Password

texts:
I have been using my ESP8266 module with my Arduino on my university's Wi-Fi network, which only requires a password to log on to.

The university will soon terminate that Wi-Fi network and replace it with one that requires a username and password to log on.

What would that AT command be to connect to such a network?

Edit: I have since found out that the university has changed the network so that a user can "connect" to the network and then enter their university id/password in a captive portal to gain internet access (and perhaps other features of the network). Also, I have since learned how to overwrite the firmware on my esp-01 so that I no longer need to use the AT commands -- in fact, I can program it in the Arduino IDE just as I would with another esp8266-based device, such as the NodeMCU.


texts: Receiving junk values in Arduino serial monitor console

texts:
I want to send a character from a Zigbee transmitter to an Arduino Mega 2560. After the character is received, Arduino should send some data back to Zigbee. But Arduino is always receiving junk values at the console. If I send a character, suppose 'a', instead of 'a', Arduino console is always showing 'y'. It is the same for every character I send.

#include <EEPROM.h>
#include <SoftwareSerial.h>
SoftwareSerial XBee(19, 18); // RX, TX
int addr = 0;
unsigned long startMillis;  //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 1000;  //the value is a number of milliseconds
void setup()
{

  XBee.begin(9600);
  Serial1.begin(9600);
  Serial.begin(9600);
  startMillis = millis();  //initial start time
 }
void loop()
{
  int id = 1;
  EEPROM.write(addr, id);
  if (Serial1.available()>0)
    {
      currentMillis = millis();  //get the current "time" (actually the number of milliseconds since the program started)
  if (currentMillis - startMillis >= period)  //test whether the period has elapsed
  {
    char recbyte=Serial.read();
    Serial.print(recbyte);
    // delay(1500);
    Serial1.write(id);
    Serial1.write(" 30 ");
    Serial1.write(" 99 ");
    Serial1.write(" 72 ");
    Serial1.write(" 1098 ");
    Serial1.write(" 728 ");
    Serial1.write(" 578 ");
    // Serial1.write("$");
    Serial1.write('PS=1\r\n');
    Serial1.end();
    startMillis = currentMillis;
  }
    }
}


texts:
I am trying to write to Sharp memory LCD "LS027B7DH01" which isn't going well for me. I didn't find any useful information for beginners. I just want to display any character on the LCD. Here's my code:

#include<SPI.h>

int SCS=10;
int SI=11;
int SCLK=13;
int EXTCOMIN=4;

 void setup()
 {
   pinMode(SCS,OUTPUT);
   pinMode(EXTCOMIN,OUTPUT);
   pinMode(SCLK,OUTPUT);
   pinMode(SI,OUTPUT);
   digitalWrite(SCS,HIGH);
   tone(EXTCOMIN,40);
   SPI.setClockDivider(SPI_CLOCK_DIV16);
   SPI.setBitOrder(MSBFIRST);
   SPI.setDataMode(SPI_MODE0);
   SPI.begin();
   SPI.transfer(0×20);
   delay(3000);
}

void loop()
 {
   SPI.transfer(0×80);
   delay(3000);
   for (byte i=0; i<30;i++)
    {
       SPI.transfer(i+1);
       delay(3000);
      for(int j=0; j<50;j++)
       {
         SPI.transfer(0x0F);
         delay(3000);
       }
       delay(3000);
       SPI.transfer(0×00);
    }
    delay(3000);
    SPI.transfer(0×00);
  }


texts:
I have a code that sends 384 pulses at 38kHz with an infrared LED. It's very easy to understand it. At the beggining the code sends the pulses using the LED and in the middle of the code I check the sensor if it has any signal coming. So far so good, yes? Please, take a look:

for(int i=0;i<384;i++) {
  digitalWrite(IRledPin,HIGH);
  delayMicroseconds(13);
  digitalWrite(IRledPin,LOW);
  delayMicroseconds(13);
}

if (digitalRead(IRsensorPin) == LOW){
  digitalWrite(D13ledPin,HIGH);
} else {
  digitalWrite(D13ledPin,LOW);
}

My question is this: I first send the pulses, so when I reach the line if (digitalRead(IRsensorPin) == LOW){ the pulse should already have passed the sensor. So why does it work? It should not work cause I first send the pulse and then I check for the pulse but as I understand the 384 pulses should already have passed the sensor.

I have no idea why this code works. I would be glad to listen smarter people to help me understand this.

Thank you.


texts: Encoding clock signal into linear block codes

texts:
In the VirtualWire library, it is possible to encode the clock signal as the library is doing with 4b/6b coding. This is possible because VirtualWire uses convolutinal coding, where the information is spread along the sequence. But, is the same possible for linear block coding, such as LDPC/Hamming?

Otherwise, if it is not possible, then how would I best deal with the signal going out of sync with serial communication, given I want to use LDPC coding.

Lastly, the reason I am using serial communication is because I will have numerous nodes in my wireless mesh network, so to my knowledge, for the sake of: speed, power efficiency, scalability, ease of implementation, etc, serial communication works best. But has anyone had better luck with any other types of communication that can take care of the sync problem, while accounting for speed, power efficiency, scalability, etc?

EDIT: The way I am doing wireless communication is by using simple rf transceivers. There will by one transceiver per node and I am trying to create a stable channel between one node to another. The communication channel isn't very reliable without some error correction. And I don't want to use the existing VirtualWire's convolutional error correction. I want to use LDPC codes, developed by Radford Neal. My goal is to first create a stable channel from one Arduino to another. Then, I will implement the network.


texts: Does serial communication between PC and Arduino has to be in a loop?

texts:
I am trying to send a few variables from my python script to my Arduino. I am using pySerial. I am able to send the variables to the Arduino, but my Arduino sketch runs only for a second and then stops. But if I put the ser.write() command in a while loop (which I want to avoid) the sketch runs fine.

For example, I wrote this script on my PC -

import serial
ser = serial.Serial('COM3',9600)
counter = 'Y'
ser.write(counter)

This script should pass a "Y" to the Arduino and should stop executing.

My Arduino code-

int flag = 0;
void setup() {
   Serial.begin(9600); // set the baud rate
   Serial.println("Ready"); // print "Ready" once
   pinMode(13, OUTPUT);
}

void loop() {
   char inByte = ' ';
   if(Serial.available()){
      inByte = Serial.read(); // read the incoming data
      Serial.println(inByte);
      flag ++;
   }
   if(flag == 1){
      digtalWrite(13, HIGH);
   }
}

Now according to me the Arduino should receive the data and increment the flag variable to 1. Next the program checks whether flag is one and if it is turns the onboard LED on. However when I run the python script, the onboard LED flashes for just a second and then goes blank. I again have to run the python script to make it light up or I have to put ser.write in a loop. I can't put ser.write in a loop as my script won't run further.

So how can a value be passed to an Arduino without having to put the ser.write() in a loop.

Thanks!

EDIT :

I wrote a new sketch, but it still doesn't work. Here's the sketch -

int ledPin = 13;
char data = ' ';

void setup(){
   pinMode(ledPin, OUTPUT);
   Serial.begin(9600);
}

void loop(){
   if (Serial.available()>0) {
      data = Serial.read();
   }
   if (data == 'Y'){
      digitalWrite(ledPin, HIGH);
   }
   delay(500);
}

Here's an image of the wiring -


texts:
I am using this https://github.com/watterott/SilentStepStick stepper driver to drive a stepper motor.
I am having trouble setting pins to HI-Z/floating to configure the stepper driver.

To set the driver to 16 micro steps and full interpolation, one has to set 2 configuration pins to HI-Z/floating (datasheet, p.9).
The example code on github (TMC2100.ino) just doesn't touch the pins at all, this works fine for me.

However, if I only add the lines:

pinMode(11, INPUT);  //connected to CFG1
pinMode(10, INPUT);  //connected to CFG2

which should set the pins to HI-Z/floating, the result is different.
The motor turns at the same speed, but makes more noise, I believe the driver is using the 16 step method with no interpolation. This corresponds to both pins being interpreted as high.

This makes me believe, that the Arduino uses a different code at startup than being used in pinMode(x, INPUT) to configure all pins. I am using a Teensy 3.1/3.2.

How can I solve the problem? Pins 11 and 10 are hard wired to the driver, as it replaced the well known A984.
Apart from the obvious "don't configure the pins then", I would like to know what's going on here.


texts: limit length of the generated timestamp from ESP32 with DS3231 to 13

texts:
I am using ESP-WROOM-32 (Olimex ESP32-PoE) with DS3231. I have used the a patch from PR on RTClib to avoid the rollover from the DS3231.

Since the DS3231 RTC provides Unix Epoch Timestamps which have a precision of only seconds, I wish to concatenate the millis() to the above mentioned timestamps to provide millisecond precision.

This is critical since I want to store information to InfluxDB from the nodes with ms precision. For that the timestamps should always be 13 digits.

code

#include <RTClib.h>
#include <Wire.h>

// PoE setting for Olimex PoE board

#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT
#define ETH_PHY_POWER 12

// Pins for I2C on Olimex PoE board
#define I2C_SDA 13
#define I2C_SCL 16

RTC_DS3231 rtc;
RTC_Millis software_time;

void setup() {
  // put your setup code here, to run once:
  Wire.begin(I2C_SDA, I2C_SCL, 400000);
  Serial.begin(9600);
  if (!rtc.begin()) {
    Serial.println("No RTC Detected");
  }
  // adjust RTC Time
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // adjust software timer
  software_time.adjust(rtc.now());

}

void loop() {
  // put your main code here, to run repeatedly:
  DateTime rtc_now_time = rtc.now();
  DateTime software_now_time = software_time.now();
  Serial.println();
  Serial.print("RTC now: "); Serial.print(rtc_now_time.unixtime());
  Serial.println();
  Serial.print("millis: "); Serial.print(millis());
  delay(100);

}

Output

RTC now: 1538502183
millis: 28
RTC now: 1538502183
millis: 128
RTC now: 1538502183
millis: 228
RTC now: 1538502183
millis: 328
RTC now: 1538502183
millis: 428
RTC now: 1538502183
millis: 528
RTC now: 1538502183
millis: 628
RTC now: 1538502183
millis: 728
RTC now: 1538502183
millis: 828
RTC now: 1538502183
millis: 928
RTC now: 1538502184
millis: 1028

I will store the timestamps in String so I was thinking of concatenating the .unixtime() with millis(). However since I want all my timestamps to be of fixed lenght (13) with the increasing millis value seems to be difficult because as soon as the number goes more that 999 the a digit increases making the string length 14.

Side Effect

if the timestamps for ms do not match length of 13, InfluxDB rejects the data passed through

Epoch Time

the output provided above is of 10 digits which is the epoch time since 1970. The precision of the timestamps above is of seconds. If one wants to add milliseconds to it one needs to add 3 more digits behind it. If precision needs to be microseconds it should have 6 digits and so on..
One can check the timestamps above on [https://epochconverter.com]

Any suggestions on overcoming this issue ?


texts:
I want to turn my Arduino MKR1000 into an Access Point. My code is the following:

#include <SPI.h>
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

WiFiServer server(80);
char ssid[] = "MKR1000";
int status = WL_IDLE_STATUS;

void setup() {
  delay(1000);
  Serial.begin(9600);
  Serial.print("Creating access point named: ");
  Serial.println(ssid);
  if (WiFi.beginAP(ssid) != WL_CONNECTED) {
    Serial.println("Creating access point failed");
    while (true);
  }
  server.begin();
  printStatus();
}

void loop() {

}

void printStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  Serial.print("To connect, join the network and open a browser to http://");
  Serial.println(ip);
}

After uploading this, in the serial monitor I get this:

Creating access point named: MKR1000
Creating access point failed

I'm new to this so I really don't know what's the problem. I hope someone knows what's going on.Thank you in advance.


texts:
My project is based around the ATMEGA32u4 microcontroller.

I followed the Arduino Pro Micro schematic to design my own board layout and build a custom PCB, soldered on the components.  Then I used the Arduino IDE to successfully upload the Arduino bootloader with SPI.

Currently I can also upload programs to my `32u4 over SPI (using "in-serial programming").  Tested that with Blink.

But I cannot upload programs with the USB, like you would normally be able to do with a Pro Micro.  What things should I look for to debug this?

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\Myname\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

     Using Port                    : COM12
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding


texts: How can I add two different programs of bldc motor and servo motor in one so that they work in parallel?

texts:
This is for the servo motor:

#include <Servo.h> //Servo library

Servo servo_test;
//initialize a servo object for the connected servo
int angle = 0;

void setup() {
  servo_test.attach(9);
}

void loop() {
  for(angle = 0; angle < 180; angle += 1) {
    servo_test.write(angle);
    delay(15);
  }
  delay(1000);
  for(angle = 180; angle>=1; angle-=5) {
    servo_test.write(angle);
    delay(5);
  }
  delay(1000);
}

This is for the bldc motor with esc:

#include <Servo.h>

Servo esc_signal;

void setup() {
  esc_signal.attach(12);
  esc_signal.write(30);
  delay(3000);
}

void loop() {
  esc_signal.write(55);
  delay(15);
}


texts:
I want to do something along the lines of

for (int i = 0; i < 4; i++) {
  analogRead(i);
}

Which appears to work, but the following does not:

for (int i = 0; i < 4; i++) {
  pinMode(i, INPUT);
  pinMode(i + 4, OUTPUT); // should make Analog Pin (i + 4) into an output
  digitalWrite(i + 4, LOW);
  analogRead(i);
}

Instead, it appears to treat the pin addressed by digitalWrite(i + 4, LOW); as one of the digital pins.

Do I really have to explicitly specify A0, A1, A2, ... anytime I want to loop over the analog pins?


texts: OTA update for ESP32 in Arduino ide from a different nework

texts:
I am trying to use the OTA to update my code in esp32. I have used Web updater so far and it has worked perfectly. But I want to update the code even when I am not connected in the same network with my esp32. Say, the esp32 have an ip from my phone Ap : 192.168.1.43 and I am connected in a different one say, 192.168.25.12 As both of them are class C ip having default subnet mask then we are in different network.

I have found this following question
OTA updating the ESP32 from a separate server
It did not clarify things to me.


texts: can I use Arduino cuurent-shield-sensor to measure very small voltage?

texts:
I want to measure very small voltage in small Range -100/+100 mv from a circuit,
can Arduino-shield ACS712 (max471) do that direkt ?


texts: Serial monitor garbage output on both MacOS and Windows devices, output used to make sense

texts: Baud rate is set to 115200 in both the serial monitor and in the setup() portion of the code. The output to the serial monitor just looks like a bunch of reverse question marks on MacOS and on Windows it's a bunch of gibberish characters. Any idea how to fix this and why it would have changed when the output used to be what I expected? Weird thing is the program on the board is still working because I'm seeing the proper output on my server but I want the serial monitor working for debugging if it's not making it to the server.


texts: How to send the MFRC522 RFID module into sleep mode?

texts: I'm trying to get the power consumption of a MFRC522 RFID module down, currently while running it consumes about 4mA. There should be a way to put it into sleep mode, I just can't find any documentation on it. I'm using the module with a arduino currently if that helps; and this is the module itself : MFRC522


texts: Is it better to use c_str or toCharArray?

texts:
When reading/trying a recent answer, I was surprised to see that Arduino's String class supports the c_str() method, just like the C++ std::string class. As expected, it appears to get a pointer to the string's contents as a null-terminated char array (i.e. C-style string).

However, (as far as I can see) that method is not mentioned in the official Arduino documentation. Additionally, in all example code I've seen using String, a different approach seems to be used. A secondary char buffer is setup, and then the contents of the string are copied to it using String::toCharArray(). This obviously requires double the memory, plus an O(n) copy operation.

It seems like c_str() should be the preferred approach. Is there some reason why toCharArray() is more commonly used?


texts: Troubleshooting an Arduino Computer Program

texts:
I am trying to make a serial monitor print something based on when a button is pushed.

When the button is not pushed, the variable storing it equals 1.
When the button is pushed, the variable equals 0.
When I have an if statement like this, why does it print what I want when I have one where the zero is, but not when it is like that and the button IS pressed.

Thanks

int led = 2;
const int buzzer = 3;

int upButton = 5;
int downButton = 7;
int enterButton = 6;

int up = 1;
int down = 1;
int enter = 1;

bool homeActivated = true;
bool appsActivated = false;

int homeLocation = 1;
int appsLocation = 1;

bool homePrinted = false;
bool appsPrinted = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode (upButton, INPUT);
  pinMode (enterButton, INPUT);
  pinMode (downButton, INPUT);
  Serial.println("Initializing");
  delay(2000);
}

void loop() {
  up = digitalRead (upButton);
  enter = digitalRead (enterButton);
  down = digitalRead (downButton);

  //move up and down
  if (up = 0)
  {
    if (homeActivated = true)
    {
      homeLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      homePrinted = false;
    }
    else if (appsActivated = true)
    {
      appsLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      appsPrinted = false;
    }
  }


texts: Cannot get esp8266 - 12 wifi module to always read analogRead incoming voltage accurately

texts:
So I have and arduino uno that is firing an output on pin 8. This code is not in this file just to be clear. From there Im taking that output and using it to fire pin 0 on the wifi module. Im using pin 0 because from what I understand all other pins have a pullup or pulldown resistor. When pin 0 is hot I want to print that value. Sometimes it works when I do it other times the analog values reads very low. I am using the 3.3v from the arduino uno and I plan to get a voltage regulator for the wifi module but would this cause this kind of issue? I am very very new to arduino so if anyone has any ideas I would appreciate a very dumbed down explanation. Thanks a lot. Also the reason why I have the delay turned down so low is because it seemed to make the analog signal pick up more often. Im not sure why this would matter but at a delay of 3000 it would almost never change analog value but when I turned the delay down to one the value came through much more consistently. Currently the code just outputs low analog numbers and occasionally pops up 1023 when voltage is applied but not consistently. And sometimes it just stops altogether until I keep trying for a while. I am getting voltage to the pin however so I know I have a complete circuit and power.

include

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

const char* ssid = "ENDOWED Underwear";
const char* password = "endowwear";

HTTPClient http;

static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t D9   = 3;
static const uint8_t D10  = 1;

int featherPin = D3;

void setup() {
  Serial.begin(115200);
  pinMode(featherPin, INPUT);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED) {
    delay(10);
    Serial.println("Waiting for connection");
  }
}

void loop() {
  int sensorValue = analogRead(featherPin);

  if (WiFi.status() == WL_CONNECTED) {
        Serial.println("yay connect");

        http.begin("http://10.150.40.121:3000/");
        http.addHeader("Content-Type", "text/plain");

        int httpCode = http.POST("Message from ESP8266");
        String payload = http.getString();
//        Serial.println(payload);
        http.end();

    } else {
        Serial.println("Error in Wifi connection");
    }

    if (sensorValue > 850) {

      http.begin("http://10.150.40.121:3000/home");
      http.addHeader("Content-Type", "text/plain");

      int httpCode = http.POST("Message from ESP8266");
      String payload = http.getString();
      Serial.println(payload);
      Serial.print("hi");
      http.end();
      } else if (sensorValue < 850) {
        Serial.print(sensorValue);
//        Serial.println("I am not hot");
      }

//  digitalWrite(trigPin, LOW);
//  delayMicroseconds(1);
//  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(2);
//  digitalWrite(trigPin, LOW);
//
//  pinMode(echoPin, INPUT);
//  duration = pulseIn(echoPin, HIGH);
//
//  inches = (duration / 2) / 74;
//  Serial.println(inches);
//
//  spaceIntruded = inches;
//
//  if (spaceIntruded <= 50 || spaceIntruded >= 900){
//      digitalWrite(ledPin, HIGH);
//      digitalWrite(hornPin, HIGH);
//      Serial.println("Intruder Detected!");
//      Serial.println("Sending text Notification...");
//      delay(500);
//      Serial.println("Armed...");
//  }
//
//  else{
//    digitalWrite(hornPin, LOW);
//    digitalWrite(ledPin, LOW);
//  }
    delay(1);

}


texts: What's the maximum number of keys in Yun Bridge?

texts:
The Yun has a Bridge for communicating between the Arduino and Linux processors via a key/value hash. The docs say this is actually stored on the Linux side, but it doesn't say what the limit is.

How many key/value pairs can the Bridge store? What are the practical limitations?


texts: Driving stepper motors adafruit motor shield v2

texts:
I got an Arduino Uno Rev3 and Adafruits Motor Shield V2. I also got two RepRap stepper motors:

Frame size 42 x 42mm - NEMA 17
1.8 degree step angle
Length 47mm
Holding torque 44 N.cm (4.4kg.cm, 62oz.in)
Voltage 2.8V
Current/Phase 1.68A
Resistance/Phase 1.65ohm
Inductance/Phase 2.8mH
Inertia 68g.cm
Bipolar, 4-wire

I thought I was going to be able to run the steppers with the motor shield, but when I tried run one of the steppers it jumps (runs little bit, then stops, then runs etc) until it reach  x steps. I'm driving the the motor shield with 12v 3A power supply.

I read somewhere that the Adafruit steppers should be at-least 5V. Is that correct? Do I need to buy new steppers or any suggestions of stepper driver (shield)?

How many amps do I need to run both steppers at the same time? 1.68 x 2 = 3.36A?

I'm building two of these: https://www.youtube.com/watch?v=C15yPENQ074

Any suggestions/help is appreciated! :)


texts: Arrays, and for loops... faster to use together, or not to use?

texts:
I'm a 4th year EE undergrad, so I'm more of a hardware guy than software. But concerning best programming techniques, is it "better" (more efficient/and/or equally effective) to use for loops when trying to change several items in an array by the same mathematical operation?

--OR--

Is it best to list each item out and have each operation performed by the rate at which the primary "void loop" cycles?

I'm using a Teensy 3.2 board and trying to get a DSP reverb effect working. I have an array of 8 delay tap lines, each with a different time multiplier. I'm trying to determine if it will take more time to process a for loop for each delay-tap line, versus multiplying each element in my array without the additional loop. I need to minimize processing time at all costs to avoid additional system lag.

Sample code:

  //Set delay times
  for(int i = 0; i < 8; i++)
  {
    delay1.delay(i, pot1*pauses[i]);
  }

versus

  delay1.delay(0, pot1*pauses[0]);
  delay1.delay(1, pot1*pauses[1]);
  delay1.delay(2, pot1*pauses[2]);
  .
  .
  .

EDIT
Added sample code.


texts:
Newbie here!
I’m trying to make a pocket level using an LIS3DH but I don’t know how to “reset” all the axis to start reading from a certain orientation since my LIS3dh won’t be mounted flat and will change often.
Ideally whenever the level starts it would start reading everything at 0 no matter the orientation.
I’m sure it’s just math, but it’s way over my head to begin to understand it.
Starting with the absolute basics I’m using the adafruit lib. I can easily get all the readings, and I understand they are acceleration forces. But how do I start them all from 0?
Initially I was thinking to take the very first reading and store it, then add or subtract the new readings from the originals based on if the new numbers are higher or lower than original (subjectively) but that only works in some instances which means that it wasn’t a good solution.
I don’t have specific code to share as I’m using the adafruit LIS3DH example.
Here’s a reading from the sensor of it not flat
X: -11408 Y: -3152 Z: 10560 X: -6.87 Y: -1.87 Z: 6.27 m/s^2
And here’s readings closer to a flat surface
X: -80 Y: 704 Z: 16176 X: -0.02 Y: 0.46 Z: 9.86 m/s^2


texts: How to display extended ASCII characters, e.g., the standard degree symbol, DEC 167, on the Serial Monitor [not LCD]?

texts:
I spent an afternoon researching this, and read a lot of material, but with no successful results.  [I really thought this would be a trivial task.]

Is this problem Windows, or WIN10, specific, as the extended characters all seem non-displayable? Regardless, is there a solution?


texts: NodeMCU Power Draw and charging Circuitry

texts:
I am planning to build a small wireless keyboard, around 5 buttons and 1 rotary encoder, that will connect via WiFi to my Spotify account. For this project, I was looking at the Node MCU for the board.

I could not find online how much of a battery I will need for this project. I read somewhere that it can draw up to 200mA, so, if I use 4 of these batteries and run them through a 3V3 regulator, i should have 20.000mAh, so it should be able to be powered on for at least 100 hours, right? But it will actually be more, as it does not draw 200mA consistently, right?

Should this work? Do you have any other suggestions? Maybe some different batteries?

Also, how should I go about to make it so that it can have an USB C port that can charge the batteries while it is still in use? Sorry if this question is stupid, this is my first real project.

I thought the easiest, cheapest and dumbest solution was to simply try and fit in a regular 28.000mAh power bank and charge the NodeMCU via USB. Is this a decent idea?