texts: Problem with piezo readings and Arduino Due

texts:
I'm using 1mOhm resistor in parallel to a piezo that is connected to analog1 pin on the Due,

and the following code to observe the readings in the serial monitor:

int piezo = A0;
int threshold = 200;//anything over 200 means I've hit the piezo

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

//this part checks if the threshold has been reached and then writes the strenght of the signal

void loop(){
    int piezoVal = analogRead(piezo);

    if (piezoVal>threshold){
        Serial.println(piezoVal);

        delay(10); //delay is used to prevent from getting multiple values one after another, usually 3-4
    }
}

The things that bother me are:

if I do not use threshold, then I am constantly getting readings from the piezo, even if the threshold is slightly below 200.
if I do not use delay, then I'm getting getting multiple values one after another
and the strangest thing is while I hit the mouse pad that covers the piezo, the readings in the serial monitor are not matching the force being used to trigger the piezo. Sometimes they stay the same, sometimes they reach 6-700 after I directly touch the piezo, sometimes I hit really hard and I only get some slight increase (for ex. from 225 to 229).

This doesn't make sense to me. I think the stronger the vibration, the higher the values should be. Cause I've tried with two different piezos and different resistors (1mOhm, 1.2 mOhm and 1.5 mOhm) and I'm still getting the same result. I bought the Due few days ago in order to build a drum kit, and I have no problem with sending midi notes to a DAW, but this piezo sensitivity thing is driving me crazy. Any suggestions?


texts:
On Arduino due, Is this possible to get the current time in nano seconds?
At 84Mhz, I guess it will always be a multiple of ~12ns.

And a perfect solution would read a register/variable rather than call a function. Because I want to avoid the cost of calling a function which is in order of microseconds.
what about counting clocks since start of execution. is this possible?


texts: ld.exe:linker_script.ld:138 cannot move location counter backwards | ArduinoFFT Error

texts:
Board: Arduino Nano 33 BLE Sense
I'm pulling PCM data from an onboard microphone and running it through the arduinoFFT library (version 1.5.6) to obtain a spectrogram. Since the arduinoFFT library requires the data be an array of doubles, I've converted the data from short to double, and started the FFT process. The FFT.Windowing() function worked fine, but I get the error at the FFT.Compute() function call (line 77). The error goes away when I remove the function call. The error:
Found 25 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <arduinoFFT> 1.5.6
|-- <PDM> 1.0
Building in release mode
Linking .pio\build\nano33ble\firmware.elf
c:/users/benlu/.platformio/packages/toolchain-gccarmnoneeabi/bin/../lib/gcc/arm-none-
eabi/8.2.1/../../../../arm-none-eabi/bin/ld.exe:linker_script.ld:138 cannot move location counter
backwards (from 000000002004a470 t
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\nano33ble\firmware.elf] Error 1

And the code:
#include "Mic.h"
#include <arduinoFFT.h>

// FFT

arduinoFFT FFT = arduinoFFT(); /* Create FFT object */
/*
These values can be changed in order to evaluate the functions
*/
const uint16_t samples = 16128; //This value MUST ALWAYS be a power of 2
const double signalFrequency = 16000;
const double samplingFrequency = 16000;
const uint8_t amplitude = 100;
/*
These are the input and output vectors
Input vectors receive computed results from FFT
*/
double vImag[samples] = {0};

// buffer to read samples into, each sample is 16-bits
short* sample_buffer;

// number of samples read, read from Mic class on loop
volatile int samples_read;

// The length of the buffer to use. Currently set to 4 seconds.
int buffer_size = 16000;
double double_buffer[16384] = {};

// Instantiate
Mic mic;

// DO NOT PRINT INSIDE THIS FUNCTION - Causes it to hang.
void onPDMdata() {
  mic.sample();
}

void setup() {
  Serial.begin(115200);
  while (!Serial);
  PDM.onReceive(onPDMdata);
  PDM.setBufferSize(16128);

  Serial.println("3...");
  delay(1000);
  Serial.println("2...");
  delay(1000);
  Serial.println("1...");
  delay(1000);
  Serial.println("Listening!");

  mic.begin();
}

void loop() {

  // wait for samples to be read
  samples_read = mic.samples_read();

  // If desired buffer size is reached.
  if (samples_read >= buffer_size) {
    // Retrieves audio buffer
    sample_buffer = mic.sample_buffer();

      // print samples to the serial monitor or plotter
      for (int i = 0; i < samples_read; i++) {
        double_buffer[i] = (double)(sample_buffer[i]);
        Serial.println(double_buffer[i]);
      }

    Serial.println("---------- SAMPLE BREAK ----------");

    FFT.Windowing(double_buffer, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
    FFT.Compute(double_buffer, vImag, samples, FFT_FORWARD); /* Compute FFT <--------------------- THIS LINE */
    // FFT.ComplexToMagnitude(double_buffer, vImag, samples); /* Compute magnitudes */

    // delay for data collection only, comment when not collecting
    delay(1000);
    Serial.println("Listening!");

    // clear the read count and resume recording
    mic.clear_buffer();
  }
}

Where can I start to troubleshoot this issue? I've not had to deal with linker errors before, so any pointers would be greatly appreciated. Thanks in advanced!


texts:
I am working on prototyping an underwater navigation system with Arduino. It's going to be used to track movement underwater from a starting point and then be able to tell how to get back to that point or relatively close. The unit would only be going a few hundred feet underwater.

I am using an Arduino Nano, is this going to be sufficient? Also, what IMU would you recommend? I'm sure it will need to at least have a 3-axis gyroscope, 3-axes accelerometer, and possibly a 3-axis magnetometer.

This does need to be relatively affordable. Currently I'm building a unit that can go underwater and just record data onto an SD card so that I can take the data and map it out to check the IMUs accuracy, error margin, along with test various filters on the data. Any recommendations would be greatly appreciated.


texts: Use website to communicate with Arduino WirelessProtoShield

texts:
I have a small office with wireless network, is it possible to make a wireless doorbell?
Practical example:
Arduino is connected to the main wireless network and has a static ip,
i have a website that connects through arduino using ftp to activate the "open door" function.
note: "open door" activates a motor to press the button, or i will hack the current doorbell to connect wires :D


texts:
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 12452 bytes (38%) of program storage space. Maximum is 32256 bytes.
Global variables use 970 bytes (47%) of dynamic memory, leaving 1078 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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


texts: What will happen if I give my Arduino Uno more or less than 5 volts?

texts: Will it still run on less than 5 volts? Will it break?


texts: FlexyStepper: set current position leads to reach the old target

texts:
I'm using the FlexyStepper library.Unfortunately there's no way to write an issue to the author so I'm going to ask my question here.

The documentation says about the setCurrentPosition*() functions:

  set current position of the motor in millimeter, this does not move the motor

But I see a different behavior.
Looking at the code, it seems it just update the current position, leaving unchanged the target position. This leads to an expected movement of the motor. Example:

set the target position to, say: 1000
the motor reach that position
set the current position to, say: 1500
now the motor come back to 1000

Instead, I want the current position from now is 1500, but because it has already reached the target, it shouldn't move further.

Of course a workaround is to set both current position and target to the same value.

I wonder if I'm wrong about the documentation or this might be considered a bug.


texts: Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi

texts:
I'd like to assemble a device that could accomplish the following:

Connect to my home wifi (WPA2-Personal)
Connect to my home PC with via Ethernet cable
Able to send WoL signal to the PC when getting a signal over wireless connection
The whole set up needs to be less than 45USD, desirably much less, otherwise I'd just buy a wireless bridge.

The goal is both to have a useful device (that will allow me to wake up my pc remotely) but also have fun learning something new (arduino).

I have no background in Arduino or Electronics in general. I program well though and learn fast.

Do you think Adruino is adequate for the above? Is soldering required (I'd rather not, or at least not a lot)?


texts:
I bought some material on the net to start working with Arduino. I didn't want to buy an Arduino, since it costs a bit too much IMHO, so I bought an ATMega328P-PU, and made an Arduino on a breadboard. However, when I use my USBasp to program it it says that he can't set sck period (settings are: Arduino Uno as Board, USBasp as Programmer). It says that it has loaded the bootloader/program anyway, so I tried to go on and ignore it. The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works). Here I describe the circuit:

First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);
1st pin, Arduino Reset -> also to USBasp RST;
7th pin, Arduino VCC -> directly to 5V (and USBasp VCC);
8th, GND -> directly to Ground (and USBasp GND);
9th, XTAL -> to one pin of the 16MHz Crystal Oscillator, and to 22 pF capacitor, which connects to ground (not the pin);
10th, XTAL -> exactly as above, but it's connected to the other pin of the same crystal;
17th, digital 11 -> USBasp MOSI;
18th, dig 12 -> USBasp MISO;
19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);
20th, AVCC, and 21st, AREF -> directly to 5V;
22nd -> directly to ground (not pin).


texts: Is it possible to increase the voltage on 3.3v output to 5v on an ESP board to power a DC motor?

texts:
I am trying to use an ESP32s controller connected to an RC car DC motor. I found that when using my Arduino this is easily accomplished, and I can see that my output pin produces 5v for the motor to spin. My ESP32, however, only produces 3.3v, so of course the motor does not spin. Do I need to use a motor driver board, transistors, or will the ESP32 simply not work in this scenario?

Thanks in advance.


texts: Dynamically create functions for AccelStepper that use Adafrut_StepperMotor.oneStep methods?

texts:
In the Adafruit_MotorShieldV2Library>Accel_MultiStepper example, AccelSteppers are initialized using the following static forwardstep1 and backwardstep1:

#include <Wire.h>
#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>

//First, get an Adafruit_MotorShield
Adafruit_MotorShield AFMStop(0x60); // Default address, no jumpers

//Then, get a stepper motor from it
Adafruit_StepperMotor *myStepper1 = AFMStop.getStepper(200, 1);

//Then, create callbacks for the AccelStepper's constructor
void forwardstep1() {
    myStepper1->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
    myStepper1->onestep(BACKWARD, SINGLE);
}

//Finally, create the stepper motor
AccelStepper stepper1(forwardstep1, backwardstep1);

I intend to then use these AccelSteppers as members in a MultiStepper, which I'm skipping here because it shouldn't be relevant.

I want to make a function that automates this process. Ideally it would work something like this:

typedef void(*mover)();
AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
    // create functions of type mover
    mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
    mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
    return AccelStepper step(forward, back);
}

What I've tried:

Obviously the above solution. This doesn't work because myStepper isn't captured, but if you capture it it's not a mover object and can't be passed to AccelStepper.
Using an object's function. This doesn't work because object functions have the implicit first parameter this. See this for more info
Making the parameter myStepper static after it's passed in. This doesn't work because it gets over-written on every call to the function.
Using std::forward. This would probably work, but I don't think std::forward is defined in ArduinoSTL because I keep getting the error 'forward' is not a member of 'std'. See the code below:

Note, In an attempt to make this work, I upgraded the following folders to -std=gnu++17 on my ubuntu machine, resulting in __cplusplus == 201500:

~/.local/share/umake/ide/arduino/hardware/arduino/avr/platform.txt
~/.local/share/umake/ide/arduino/hardware/hardware/platform.txt

std::forward attempt

#include <ArduinoSTL.h>
using namespace std;
#include <iostream>
#include <functional>
#include <utility>

typedef void(*mover)();

template <classF>
mover lambda_to_ptr(F&& f){
    static F fn = std::forward<F>(f);
    return []{ return fn();};
}
AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
    // create functions of type mover
    mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
    mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
    return AccelStepper step(lambda_to_prt(forward), lambda_to_ptr(back));
}

p.s. Of course, I could always change the functions in the library, but this is (almost) always a bad idea.


texts: Digispark clone not recognised when plugged in

texts: When I plug in my digispark clone the computer doesn't make any sounds or some kind of acknowledgement that it has been plugged in. Anyone know why this may be or is it just a dodgy clone?


texts: Is there a library for non-SAMD Arduinos to use the DMP on MPU9250

texts:
I would like to use the DMP of the MPU9250 with my BTLE Feather board but the docu of the official library says that only SAMP-Processors are supported.

Is the a different library I can use?


texts:
I have an Arduino UNO and OV7670 camera sensor without FIFO. I wanted to build a device, that would take frame once in a while, and would send it through bluetooth (HC-05) or wi-fi (esp-01). I didn't know though, that the microcontroller inside Uno has so little RAM memory, that the frame doesn't fit inside. Moreover, even Arduino Mega has too little memory...

My question is- is there anything I could do to take a VGA-resolution photo (circa 1MB) and send it through any serial medium?

I suppose it'd be some kind of a buffer or memory- I'm asking for references to concrete chips or solutions (like- would it be possible to encode or compress an image on-the-fly)?


texts: How to drive 16 stepper motors with Arduino?

texts:
I'm trying to drive 16 of these little steppers on an Arduino Uno.

Each test driver uses 4 digital pins for control (2 for each coil) so that would be 64 pins I will need.

I'm thinking either getting something like this or 4 of these.

Would something like that work ?
What's the most straight forward way to drive these on an Arduino Uno ?


texts:
I'm making a -12 to +12V DC regulated power supply, on which I want to measure voltage and current with Arduino (through a voltage divider, of course).

I'm not sure, how to either detect nor measure negative voltage. I could "detect" it via a Schottky diode, but I'd get about 0.3V voltage drop, but that's not what I want, because any voltage between 0.0V and -0.3V wouldn't be measured. I want also to be able to measure positive and negative voltage on the same Arduino analog input pin.

And furthermore, how to measure current, flowing into both ways? (not an AC current, but will change during operation).

I will make additional PCB for this application, so size and number of components isn't important at all.


texts: Range of Offset Value in pH sensor module?

texts:
In finding the pH value of a liquid/Soil, what is the range of Offset voltage value that I can use in my code?

Using / calibrating pH sensor module

I considered the above link as a reference. But I didn't come to know the range of Offset Value...

Here is the logic below to find the value of pH right...

avgValue = 0;
for (int i=2;i<8;i++)       // take the average value of 6 center sample
avgValue+=buf[i];

float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
phValue=3.5*phValue+Offset;

What is the range of Offset value can I use in the above/my code?

Thanks in Advance


texts: Can I change the USB device name of Arduino?

texts:
I have several Arduinos connected to my Windows PC, and they appear as follows:

  COM7 (Arduino Uno)
  COM11 (Arduino Uno)
  COM13 (Arduino Uno)

So there's no way to tell which is which, and when I want to upload a sketch to one, I have to unplug the others to make sure my code goes to the right one.

Is there a way to change the "Arduino Uno" description?

(I found a similar question but that was about Mac specifically).


texts: Is there an equivalent to Grbl for Excellon PCB drilling?

texts: For CNC milling we have code such as Grbl Controller in the PC, and Grbl itself in an Arduino, and these handle the appropriate G-code files. Is there an equivalent package to handle Excellon files and drive a 3-axis drilling machine?


texts:
What I would like to do is,
 step 1:

led1 fades from black(off) to green (max-on 255)
led2 fades from black(off) to red (max-on 255)

this happens at the same time.
If the max value is reached, then both leds fade out (to black, off)
so step 2:

led1 fades from green to black
led2 fades from red to black

Then step 3, almost same as step 1 but opposite colours:

led1 fades from black(off) to red(max-on 255)
led2 fades from black(off) to green(max-on 255)

And step 4, both fade to black

led1 fades from green to black
led2 fades from red to black

This is the code that fades led 1/3/5 from red to black and back to red
and led 2/4/6 from green to black, and back.

#include <FastLED.h>
    #define NUM_LEDS 6
    #define DATA_PIN 3

        CRGB leds[NUM_LEDS];

           void setup() {
               Serial.begin(9600);
       FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
   }

       void loop()
{

  int x = 1;
   for (int i = 1; i > -1; i = i + x){

     leds[0] = CRGB(i,0,0);
     leds[1] = CRGB(0,i,0);
     leds[2] = CRGB(i,0,0);
     leds[3] = CRGB(0,i,0);
      Serial.println(i);
      FastLED.show();
      if (i == 55) x = -1;             // switch direction at peak
      delay(100);

   }
}

****Original question****

  I am trying to fade a led (WS2812B) from black to green or red, and
  back to black. (that is working)  But now I want the same led fading
  to blue.

  How could I do that? I was trying a if..else but can't figure it out
  Or should I count the for loops?

  This is the starting code I am using

  maybe something like

    if (i==0)
{
             leds[0] = CRGB(i,0,0);
             leds[1] = CRGB(0,i,0);
             leds[2] = CRGB(i,0,0);
             leds[3] = CRGB(0,i,0);
}
    else
{
             leds[0] = CRGB(0,0,i);
             leds[1] = CRGB(0,0,i);
             leds[2] = CRGB(0,0,i);
             leds[3] = CRGB(0,0,i);
}
              FastLED.show();
              if (i == 100) x = -1;
              delay(100);

  But that is not working. Any suggestions?


texts: Problem uploading to board. arduino-1.8.8-windows

texts:
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"
Sketch uses 2018 bytes (6%) of program storage space. Maximum is 32256 bytes.
Global variables use 50 bytes (2%) of dynamic memory, leaving 1998 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\.\COM7": The system cannot find the file specified.
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.


texts:
Put plainly: is there a way to get an HTTPS connection on the Arduino?

I have been looking in to it, and I have found it is impossible with the standard library and the Ethernet shield, but is there a custom library that can do it?

What about a coprocessor, i.e. like the WiFi shield has? Anyone know if the Arduino yún has ssl?


texts:
I have a joystick and am using the following code to show the output to the serial monitor:

// Arduino pin numbers
const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output

void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  Serial.begin(115200);
}

void loop() {
  Serial.print("Switch:  ");
  Serial.print(digitalRead(SW_pin));
  Serial.print("\n");
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pin));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pin));
  Serial.print("\n\n");
  delay(500);
}`

Even when I am not moving the joystick, the X and Y axis outputs change continuously. Anywhere from around 50 to 600 (it seems.)

Every read has a new number.

What could be causing this?

I used the guide on https://www.brainy-bits.com/arduino-joystick-tutorial/


texts:
I have an RGB LED common Anode attached to my Uno and this code detects a long press to turn the LED on and off.  Short presses cycle through colors, then off.

The problem is that a longpress is 2+sec, but it doesn't register until I release the button.  How would I set this up to execute the code at 2sec regardless of whether the button is released?

It's probably not worth my time if it requres too much modification.  I have a working item, it's just not... ideal.

Xhunsigned long keyPrevMillis = 0;
const unsigned long keySampleIntervalMs = 25;

int redPin = 11;
int greenPin = 10;
int bluePin = 9;
int LEDcolor=0; // 0=White, 1=Red, 2=Green, 3-Blue, 4=Yellow, 5=Purple, 6=Pink, 7=Orange, 8=Off
int LEDstatus =0; //0=Off, 1=On
int changed =0; //has the LEDstatus just changed?
byte longKeyPressCountMax = 80;    // 80 * 25 = 2000 ms
byte longKeyPressCount = 0;

byte prevKeyState = HIGH;         // button is active low
const byte keyPin = 2;            // button is connected to pin 2 and GND

// called when button is kept pressed for less than 2 seconds
void shortKeyPress()
{
   Serial.println("short");
   if (LEDstatus==1)
   {
      LEDcolor = LEDcolor +1;
      if (LEDcolor==0) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 0);Serial.println("White");}
      if (LEDcolor==1) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Red");}
      if (LEDcolor==2) {analogWrite(redPin, 255);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Green");}
      if (LEDcolor==3) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 0);Serial.println("Blue");}
      if (LEDcolor==4) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Yellow");}
      if (LEDcolor==5) {analogWrite(redPin, 175);analogWrite(greenPin, 255);analogWrite(bluePin, 175);Serial.println("Purple");}
      if (LEDcolor==6) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 155);Serial.println("Pink");}
      if (LEDcolor==7) {analogWrite(redPin, 5);analogWrite(greenPin, 215);analogWrite(bluePin, 255);Serial.println("Orange");}
      if (LEDcolor==8) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Off");LEDstatus=0;}
   }
}

// called when button is kept pressed for more than 2 seconds
void longKeyPress()
{
   Serial.println("long");
   if (LEDstatus==0 && changed==0)
   {
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
      LEDcolor=0;
      changed=1;
      LEDstatus=1;Serial.println("On");
   }
   if (LEDstatus==1 && changed==0)
   {
      analogWrite(redPin, 255);
      analogWrite(greenPin, 255);
      analogWrite(bluePin, 255);
      LEDcolor=0;
      changed=1;
      LEDstatus=0;Serial.println("Off");
   }
   changed=0;
}

// called when key goes from not pressed to pressed
void keyPress() {
   Serial.println("key press");
   longKeyPressCount = 0;
}

// called when key goes from pressed to not pressed
void keyRelease() {
   Serial.println("key release");

   if (longKeyPressCount >= longKeyPressCountMax) {
      longKeyPress();
   }
   else {
      shortKeyPress();
   }
}

void setup()
{
   Serial.begin(9600);
   pinMode(keyPin, INPUT);
   digitalWrite(keyPin, HIGH);
   pinMode(redPin, OUTPUT);
   pinMode(greenPin, OUTPUT);
   pinMode(bluePin, OUTPUT);
   analogWrite(redPin, 255);
   analogWrite(greenPin, 255);
   analogWrite(bluePin, 255);
}

void loop() {
// key management section
   if (millis() - keyPrevMillis >= keySampleIntervalMs) {
      keyPrevMillis = millis();

      byte currKeyState = digitalRead(keyPin);

      if ((prevKeyState == HIGH) && (currKeyState == LOW)) {
         keyPress();
      }
      else if ((prevKeyState == LOW) && (currKeyState == HIGH)) {
         keyRelease();
      }
      else if (currKeyState == LOW) {
         longKeyPressCount++;
      }

      prevKeyState = currKeyState;
   }
}


texts: Why am I getting this error- "exit status 1 expected ';' before '{' token "

texts:
void setup()
{

  pinMode{13, OUTPUT};

}

void loop() {

  digitalWrite{13, HIGH};

}


texts:
The main idea is to create trigger which can be switched on by touching 2 plates on opposite walls. And these should be performed by few peoples holding each other hands.

Obviously human body has big resistance so I couldn't just connect these plates to ground and to one of Arduino pins.

There is a toy that do almost what I what (see it there). But I haven't found any information about how to create it by myself.
Do you have any ideas how to create it?


texts: Arduino acting strange with photoresistor data

texts:
So I stumbled into strange problem. I have this circuit, where I connect 2 photoresistors and bluetooth HC05 to Arduino. When one of the resistors senses bright light bluetooth sends '1' or '3' accordingly to another circuit. When dark is sensed, bluetooth sends '2'or '4'. When dark on both resistors is sensed for more than 1.5 second, then everything goes to while loop and bluetooth sends '1' and '3'. So for example, when left photoresistor senses bright light, and right darkness, then bluetooth sends '1' and '4'. At first for a couple of months everthing worked just perfectly fine and one day it just... stopped. While troubleshooting I found out, that when changing bright light/darkness mode on resistor, data, which is seen on com port, stops for a bit and goes in batches again, it does not flow continously. I changed photoresistors, everything is the same. I even changed Arduino, still nothing. Here is the code:

#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
int fk = A0; // left photoresistor
int fd = A1; // right photoresistor
int a = 0;
int b = 0;
unsigned long dl; // time
const unsigned long p = 1500; //how many milisecs dark should be sensed

void setup()
{
    Serial.begin(9600);
    BTserial.begin(9600);
    pinMode(fk, INPUT);
    pinMode(fd, INPUT);
    dl = millis();
}

void loop()
{
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    if(a>1000)
    {
    BTserial.write('1'); // left photo senses light
    dl = millis(); // capturing last time light was sensed
    delay(10);
    }
    else
    {
    BTserial.write('2'); // left photo senses dark
    delay(10);
    }
    if (b>1000)
    {
    BTserial.write('3'); // right photo senses light
    dl = millis();
    delay(10);
    }
    else
    {
    BTserial.write('4'); // right photo senses dark
    delay(10);
    }
    while (a<1000 && b<1000)
    {
        if ((millis() - dl) >= p) //if dark is being sensed more than 1.5 sec
        {
        BTserial.write('1');
        BTserial.write('3');
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    }
}
    }

And when I use only this batch of code without while loop

    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    if(a>1000)
    {
    BTserial.write('1'); // left photo senses light
    dl = millis(); // capturing last time light was sensed
    delay(10);
    }
    else
    {
    BTserial.write('2'); // left photo senses dark
    delay(10);
    }
    if (b>1000)
    {
    BTserial.write('3'); // right photo senses light
    dl = millis();
    delay(10);
    }
    else
    {
    BTserial.write('4'); // right photo senses dark
    delay(10);
    }

Everything works fine, data is flowing continously, even when light states are changing fast.
But also everything works fine, when I use only while loop standalone without previous batch. So in my opinion bad things happen in transitions between these two batches of code? But I completely cannot understand what is wrong, why it suddenly stopped working, maybe time is calculated wrongly? I realized that when I soldered bluetooth to another board, but bluetooth is not the case, as I tried the same code with bluetooth data sending part removed. Data still goes with strange batches.
I am completely lost.


texts: Unusual use of << operator... not a bit shift?

texts:
Poking through the example code of SDFS, I saw the following:

static ArduinoOutStream cout(Serial);
// F stores strings in flash to save RAM
cout << F("\ntype any character to start\n");

What exactly is << doing in this case? Moreover, F seems to never be defined prior to this. This seems like a useful trick, but I don't understand how it works.

full code available here: https://github.com/greiman/SdFs/blob/master/examples/SdInfo/SdInfo.ino


texts: How can I record something using an arduino and use bluetooth to search those terms on google now?

texts: I'm trying to build something that can use voice recognition to search something up. I am planning to use this small module for the mic (https://www.sparkfun.com/products/12758), because I want to make it as compact as possible. So I've hooked up a bluetooth module to my arduino uno and I can hook the microphone up, but how would I get the microphone to connect to my phone's Google Voice Search in realtime through bluetooth?


texts: Is it possible to use CCMP as cipher type on ESP32's softAP mode?

texts: Currently I'm starting softAP mode on ESP32 with WPA2_PSK as auth type(as WPA3 is not supported for softAP). When I am trying to connect my iPhone to the softAP, iOS gives a warning that WiFi security is weak as it is using WPA2(TKIP). Instead it is asking to configure the AP to use WPA2(AES). I learnt that I need to use CCMP as cipher type instead of TKIP. But I cannot find any API to set cipher type for softAP. Is it supported? Or should I use only TKIP as encryption type? Thanks in advance!


texts: Yet another basic and silly question about C++ strings

texts:
I made a sketch like this:

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

  char str1[64] = "test with spaces";
  char str2[32] = "test with spaces";

  Serial.println(str1);
  Serial.println(str2);

  if (str1 == str2) Serial.println("Equals");
  else Serial.println("Different");

  if (strcmp(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

//  if (strcoll(str1, str2)) Serial.println("Equals"); // <-- this won't compile for Arduino UNO { why ??? }
//  else Serial.println("Different");

  if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
  else Serial.println("Different");

  if (areEqual(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  strcpy(str1, "test+with+spaces");
  strcpy(str2, "test with spaces");

  Serial.println();
  Serial.println(str1);
  Serial.println(str2);

  if (str1 == str2) Serial.println("Equals");
  else Serial.println("Different");

  if (strcmp(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
  else Serial.println("Different");

  if (areEqual(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  strcpy(str1, "test+with++++++++++++++++++++++++++++++++++++spaces");
  strcpy(str2, "test with spaces");

  Serial.println();
  Serial.println(str1);
  Serial.println(str2);

  if (str1 == str2) Serial.println("Equals");
  else Serial.println("Different");

  if (strcmp(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

  if (memcmp(str1, str2, sizeof(str2))) Serial.println("Equals");
  else Serial.println("Different");

  if (areEqual(str1, str2)) Serial.println("Equals");
  else Serial.println("Different");

}

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

}

bool areEqual(char* string1, char* string2) {
  return ((strlen(string1) == strlen(string2)) && (strstr(string1, string2)));
}

Which produces this:

test with spaces
test with spaces
Different
Different
Different
Equals

test+with+spaces
test with spaces
Different
Equals
Equals
Different

test+with++++++++++++++++++++++++++++++++++++spaces
test with spaces
Different
Equals
Equals
Different

The first comparisson is silly (==), I know. It compares the address of the pointer, not of the string itself. I just put it there to show how hard it is for a programmer who comes from another language to understand such a thing.

The second comparison (strcmp), as the reference says "Compares the C string str1 to the C string str2.", NO, it doesn't. They are exactly the same, except for their pre-specified size. But the strings are equal to my eyes.

The third comparison (strcoll) uses locale to compare the two strings, but how come it says different when they are equal?

The fourth comparison (memcmp), given two pointers to the exact same sequence of characters, why does it say "different"?

The mind blowing part is the comparison "works" when you add as many "+" as you wish to only one of the strings. Isn't a "+" sign also a character?

It's obvious I must be missing something really basic about c++ style strings, but I dare to ask: what is it?

Thanks.


texts:
I'm trying to get the status of my set top box (on/off).
It does have USB but it's always powered on.
It has optical out that is also always on.
It has an IP address that always responds to ping.

So my next idea is to read the signal in the SCART.
If I read the voltage across pin 8 and 14 I get 0-ish when off and 12 when on.
But when it powers on it spikes at 18 volt (at least what my multimeter can see).
 https://youtu.be/D2eVFe33MeM

What do I need to do to read this?
If I add a voltage divider with 1 and 4.7 Kohm I get a safe voltage if it does not go above 18 volt at any time.

But what can I do to be sure I don't burn a ESP chip?
Is there any way to make sure it's safe to read even if it spikes at say 25 volts?


texts: XBee on Arduino Fio - how to read the status of a local digital XBee output pin?

texts:
I am using a Fio to control a set of relays. The unit uses an XBee (series 1 Pro) in transparent mode to receive commands over serial UART and everything works fine. The XBee is also configured for digital Input/Output Line Passing and the XBee on the Fio "mirrors" on an output pin the input state on a remote XBee and also this works fine.

How can I interrogate from the Fio the state of the output pin (e.g. D0) of the local (receiving) XBee? Is there an AT command that I could send via Serial.println("ATxx") that would trigger the XBee to send back over UART the status of the pin (high or low)?


texts: Set EEPROM to initial values when flashing ESP8266

texts:
I have a variable uint8_t a_ram which needs to be initialized from the EEPROM variable a_eeprom when the ESP boots up. Whenever a_ram changes, the new value has to be stored to the EEPROM (a_eeprom), so that the ESP will initialize a_ram to this new value after the next reboot.

The problem I have is to understand, how the value of a_eeprom can be initialized for the very first boot. If a_eeprom has not been set before (that means, that a_ram has not been stored to EEPROM yet), my variable will be initialized to 0, which must not be the case.

I could introduce an extra variable to the EEPROM (kind of a flag), which tells me whether a_ram has been stored to EEPROM or not and only initialize a_ram to a_eeprom if that is the case. But as I don't want to spend this memory if it isn't neccessary, I'd like to know if there is a possibility to set an EEPROM value when flashing the ESP.
Btw, I'm using the arduino IDE.


texts: Is checking an if statement every loop/while iteration inefficient?

texts:
I have code that changes a bool only time in the setup(), and in my loop() I have

if (setupBool) {
// ...
} else {
// ...
}

Is checking the bool every loop slower than having a while(true) with the same code?

And what about checking it in every loop in a while(true)?

Is there any reason I shouldn't do those?


texts: How can I best control various high power LEDs without using PWM

texts:
I want to be able to dim various high powered (20mA) LEDs in an array (8X12 LEDs). I do not need individual control, but would like to be able to dim each row (or two rows together) so that I can create gradients.

An important caveat is that I can't use pulse width modulation (PWM) as there should be no flashing whatsoever, even if it is invisible to humans.

How can I best achieve this?
(I do not care about energy efficiency)

The fist thing I found which seemed to be the right solution in the beginning is using digital potentiometers as explained in this tutorial. However they only support low currents so I can't use one channel for 8 or 16 LEDs.
Maybe I could use various digipots in parallel with one Arduino, each powering 1 LED per channel? But that sounds overcomplicated and a nightmare to wire up. Is there a more elegant solution?


texts: Using AA batteries to power Arduino and GPS unit

texts:
I'm more of a software guy, so I need your help to figure out the power issue with my Arduino.

What I would like to do is using a GSM/GPS unit (Ai-Thinker A7) with Arduino Nano as a car tracking system. I have USB cables in the car, so I can plug it into my Arduino and power both while I'm driving. To power the unit while I'm not driving, I thought using rechargeable batteries would be a good idea. I'm planning to use GPS via SMS activation, so I hope fully charged batteries will be enough to power it for at least a week. But I'm confused about a couple of things.

Rechargable batteries are 1.2V. So technically I can use 5 of them and power my Arduino and the GPS unit (which requires 5V), right? However, for a similar unit at Adafruit they say that a LiPo battery is a must. Well, I think it is because GPS unit draws more power while using GPS and stuff. So, in this case are AA batteries out of the question? Will I fry anything if I build the system as follows?

If AA batteries happen to be fine, do I need another piece in my design, such as this one?

At last, I have no idea if I need any diode, capacitor, resistance or sth else for this system. I would appreciate further comments about my design.


texts: Clock cycle count count for the same command is not equal in ESP32

texts:
I am using ESP32 Pico Kit with Arduino Ide. I want to measure operation cycle for a few commands.

The code is so simple as below:

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

void loop() {
  unsigned long count = 10000;
  unsigned long i = 0;
  unsigned long _start;
  unsigned long _end;
  _start = ESP.getCycleCount();
  while(i < count)
  {
    i++;
  }
  _end = ESP.getCycleCount();
  Serial.println(_end - _start);
}

When I run the code, the result is 13.

Then, I changed the counter variable to different values and ran it again (values: 10, 100, 1000, 10000, ...).

The result is always 13!

Why the execution cycle does not change and it seems that the code is compiled as just one loop and the loop count is not important?

Am I missing something?


texts: SPI: problems communicating with sensor using Arduino

texts:
I have a sensor which I am trying to communicate with over SPI using an Arduino UNO. It is my first time using SPI and I'm experiencing some problems which I'm hoping are just due to some misunderstanding on my part. I have written a simple code to perform one basic operation: Turn on the sensor's fan. The Arduino is being powered through the 2.1 mm barrel jack by a 1.5 A DC adapter. The 5V, GND, MOSI, MISO, SS and SCK pins on the Arduino are connected to the corresponding pins on the sensor. The sensor receives power from the Arduino, drawing up to 250 mA (with the fan on).

The manufacturer provides a list of commands corresponding to each function of the sensor. To turn on the fan, the command list gives the following information:

Command_byte: 0x03
Bytes: 0x03, 0x00
Bytes_in: 0xF3, 0x03
Time_between_current_and_next_byte: 1.7ms, NA
Note: 1ms would be adequate delay between command byte and following byte

Based on my understanding of this, to turn on the fan, I need to send a command byte (0x03), then wait 1.7 ms and send another byte (0x00). My code for doing this is as follows:

#include <SPI.h>
const int chipSelectPin = 10;

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

  SPI.begin();
  pinMode(chipSelectPin, OUTPUT);
  SPI.setClockDivider(SPI_CLOCK_DIV32); //set clock to 500kHz
  SPI.setDataMode(SPI_MODE1);
  SPI.setBitOrder(MSBFIRST);
  delay(10000); // Let the sensor settle for 10 seconds

  digitalWrite(chipSelectPin, LOW);
  indata = SPI.transfer(0x03); //command byte for fan on
  Serial.println(indata);// value returned should be 0xF3
  delay(2);
  indata = SPI.transfer(0x00); //Turn on fan
  digitalWrite(chipSelectPin, HIGH);
  Serial.println(indata);// value returned should be 0x03
}

void loop() {}

When I send the command byte, the returned value (which gets printed to the terminal) is 243 which corresponds to the expected hex value of 0xF3. However, the second command does not turn on the fan and the second returned value is 231 which does not correspond to the expected hex value of 0x03.

I don't think it's a hardware issue because at least one of the returned values is correct and because the sensor does work when used with a different platform. I also experimented with different delays between bytes.


texts:
I want to copy an SD card to another.

What is the best way to attack this problem?

Should i get two sd card shields?
If yes, is it possible to stack two together, or will there be problems with the interface protocols (SPI/I2C)?


texts: Arduino retrieving PHP echo using ESP8266

texts:
I want to retrieve the echo string. Here is my php code

<?php
    echo "<hello word!>";
?>

I am using ESP8266 and Arduino Uno. I have managed to send the request but it's not returning the string from my php file. Any idea where i went wrong with my code? Thanks in advance

#include <SoftwareSerial.h>
#include <Ethernet.h>
#include <SPI.h>

SoftwareSerial esp(2, 3);// RX, TX

String ssid ="";
String password="";

String server = "http://domain.com/";
String location = "/retrieveInfo.php";

char inString[32]; // string for incoming serial data
int stringPos = 0; // string index counter
boolean startRead = false; // is reading?

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

void loop()
{
  String pageValue = connectAndRead(); //connect to the server and read the output
  Serial.println(pageValue); //print out the findings.
  delay(5000); //wait 5 seconds before connecting again
}

String connectAndRead()
{
  //connect to the server
  Serial.println("Connecting...");
    String cmd2 = "AT+CIPSTART=2\"TCP\",\"" + server + "\",80";
    esp.println(cmd2);
    delay(4000);

    if (esp.find("OK"))
      {
        Serial.println("TCP Connection Ready.");
      }
             String postRequest = "GET" + location + "HTTP/1.0\r\n";
             String cmd4 = "AT+CIPSEND=2,80";
             delay(4000);
             esp.println(cmd4);
             esp.println(postRequest.length());
             delay(4000);

             if (esp.find(">"))
                {
                   Serial.println("Sending...");
                   delay(1200);
                   esp.println(postRequest);
                   esp.println();

                  if (esp.find("SEND OK"))
                  {
                    Serial.println("Packet sent");
                    Serial.println();
                    delay(4000);
                    //Connected - Read the page
                    return readPage(); //go and read the output

                 }
                  else
                  {
                    Serial.println("Connection failed");
                  }
            }
    else
      {
        Serial.println("TCP Connection Not Ready.");
      }
}

String readPage()
{
  //read the page, and capture & return everything between '<' and '>'

  stringPos = 0;
  memset( &inString, 0, 32 ); //clear inString memory

  while(true)
  {
      if (esp.available())
        {
          char c = esp.read();
          if (c == '<' ) { //'<' is our begining character
            startRead = true; //Ready to start reading the part
          }else if(startRead){

            if(c != '>'){ //'>' is our ending character
              inString[stringPos] = c;
              stringPos ++;
        }
        else
          {
            //got what we need here! We can disconnect now
            startRead = false;
            return inString;

         }

      }
    }

  }
}

void connectWifi()
  {

    String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"\r\n";
    esp.println(cmd);
    delay(5000);

    if(esp.find("OK"))
      {
        Serial.println("Connected!");
        delay(4000);
        enableconn();
        delay(1000);
      }

    else
      {
        Serial.println("Cannot connect to wifi");
        connectWifi();
      }

  }

void enableconn()
  {
    String cmd1 = "AT+CIPMUX=1";
    esp.println(cmd1);
    delay(4000);
    if (esp.find("OK"))
      {
      Serial.println("Ok");
      delay(4000);
      connectAndRead();
      }
     else
      {
        Serial.println("Cannot enable multiple connections");
      }
  }

for some reason, the line "return readPage();" isn't returning any value. Any heads up would be much appreciated. This is my output in the serial monitor


texts: How to program an nRFL01 RF module that is connected to a pc via a USB to UART/TTL adapter?

texts:
In a few of my previous questions I was told that the nRF24L01 RF Module can be connected to a pc using a USB to UART/TTL adapter. After a bit of research I understand that one way to use it is to connect it to an arduino- and then to use certain dedicated libraries like RF24.h, and nRF24L01.h to send and receive data. Though I've not been able to find any tutorial outlining the procedure for programming the nRF24L01 once its been connected to the pc.
  How do I send and receive data using my pc-interface? What software do I write and how do I write it?


texts: Use the TCS3200 color sensor without the included LEDs

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


texts: Problem burning bootloader on ATmega328P using internal clock

texts:
I'm trying to burn the arduino bootloader onto my ATmega328P so it uses the internal clock. I followed the tutorial in this page but I'm getting this error.

avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     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  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 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 : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

I tried placing a cap from reset to ground but it doesn't wort either.
Any idea on what might be wrong with my procedure?

Thanks

[EDIT]

I followed the procedure described at the bottom of the page linked (Minimal Circuit (Eliminating the External Clock)).
I used the bootloader in "breadboard-1-6-x.zip"
I am using the Arduino IDE v1.8.1


texts: Well this was unexpected. AVR libc has many the variants of printf, including vprintf, but is missing vprintf_P. Is this really just not present or implemented elsewhere?


texts: what will happen if i insert the anode of a LED to pin 12 and cathode of the LED to pin 11 and set pin 12 to high and pin 11 to low,will the led glow??


texts: Switch case inside a switch case with serial input

texts:
I'm trying to build a test program for some hardware. Basically I want to select the piece of hardware with the outer switch case then select the test with the inner switch case. I'm trying to accomplish this by using serial input in the Arduino IDE monitor.

I can't make it work whatever I do. I either end up stuck in the outer switch case or I never enter the inner switch case where I want to select the test.

I've got a bit of code below:

char select_addon;
char select_test;

void setup() {
  Serial.begin(9600);
  Serial.println("(1) PB1");
  Serial.println("(2) PB2");
  Serial.println("(3) PB3");
}

void loop() {
  if (Serial.available() > 0) {
    select_addon = Serial.read();
    switch (select_addon) {
      case '1':
        Serial.println("Test");
        if (Serial.available() > 0 ) {
          select_test = Serial.read();
          switch (select_test) {
            case '4':
              Serial.println(" Test 1.1");
              break;
            case '5':
              Serial.println(" Test 1.2");
              break;
            case '6':
              Serial.println(" Test 1.3");
              break;
          }
        }
        break;
      case '2':
        Serial.println("TEST 2");
        break;
      case '3':
        Serial.println("TEST 3");
        break;
    }
  }
}

Obviously this isn't the finished code, but it's the switch case structure I've been trying to implement. Any suggestions on how I can enter the inner switch case?


texts: Lost AT+ commands on ESP8266 after flashing with "blink" sketch

texts:
I set my ESP8266 ESP-01 to flash mode and uploaded the example blink sketch on the arduino IDE esp example options. I know can no longer communicate with the ESP8266 using AT+ commands. I also cannot flash the device and can only receive the following message under baud 74880

"
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1264, room 16
tail 0
chksum 0x0f
csum 0x0f
~ld
"

Anyone know how to fix this? Thanks.


texts: Is it possible to synchronize two SPI busses to send data out in parallel on the same clock signal?

texts:
We're working with these very odd driver chips which are sort of like shift registers except rather than latch the data at the end, the latch needs to happen over the last 'n' clock cycles in parallel with the data being shifted out.  Depending on the value of 'n', the data is 'latched' into different registers. Like I said, it's an odd protocol.

Here's an example sending six bytes of data (top row) synced to the latch (bottom row).  The latch is HIGH for the last two bits of the data as it's being shifted out.

Time-->
11001100 01010101 10011010 11001011 01001010 10010101
00000000 00000000 00000000 00000000 00000000 00000011

In this example, the latch is synced to the fifth and sixth bit of that last frame (as opposed to the 7th and 8th in the first example) which tells the chip to load this data into a different register.

Time-->
11001100 01010101 10011010 11001011 01001010 10010101
00000000 00000000 00000000 00000000 00000000 00001100

Like I said, it's an odd design, but it basically lets you shoot out data non-stop without having to pause to latch.

Because of having to 'sync' the latch with certain clock cycles in the data, we can't use the standard SPI bus and have to use normal GPIO pins, which of course are substantially slower.

BUT... if I could set up the data for a second SPI bus, then use a buffer to define where the latch is high/low accordingly, that would work.

The issue is I don't know how to, or if it's even possible to sync SPI busses together.

Only thing I can think of is to use one SPI bus as the master and another SPI bus (on the same processor) as a slave, then try to leverage the bi-directional nature of it.  But this is just a guess.

I was considering looking into DMA too, but I'm starting with SPI since I know my chip has four SPI busses on it. (Update: I'm starting to think DMA is the way to go here since I now know it is possible to sync two DMA controllers to the same clock.)


texts: Can't display the two float values correctly from pyserial on Arduino's LCD

texts:
I transported two float values with pyserial to COM3 and Arduino accepted the values.

But it displayed the first value correctly on LCD, the second value can't be read and showed "nan" on LCD.

Python code:

import serial
import struct
ser =serial.Serial("COM3", 115200, timeout=2)

##======Get  Ready================
print("Connecting to Arduino.....")
for i in range (1,10):
    rv=ser.readline()
    print("Loading...")
    #Debug print (rv) # Read the newest output from the Arduino
    print (rv.decode("utf-8"))
    ser.flushInput()
    sleep(1) # Delay for one tenth of a secon
    Str=rv.decode("utf-8")
    #Debug print(Str[0:5])
    if Str[0:5]=="Ready":
          print("Get Arduino Ready !")
          break
##------------------------------------------------------
d = 77.25
a = 111.32
ser.write(struct.pack('>2f',d,a))

Arduino code:

#include <LiquidCrystal.h>
float x;
byte *xdata = (byte *) & x;
float y;
byte *ydata = (byte *) & y;
int num = 0;
char coor[2];

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(115200); // set the baud rate
  Serial.println("Ready"); // print "Ready" once
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
}

void loop(){
  while(Serial.available() > 0){
    for(int i = 0; i < 2; i++){
      coor[i] = Serial.read();
      }
    if(coor[0] == 'B' ){
      xdata[3] = coor[0];
      ydata[3] = coor[1];
      num = 1;
    } else if(num == 1){
      xdata[2] = coor[0];
      ydata[2] = coor[1];
      num++;
    } else if(num == 2){
      xdata[1] = coor[0];
      ydata[1] = coor[1];
      num++;
    } else if(num == 3){
      xdata[0] = coor[0];
      ydata[0] = coor[1];
      num = 0;
    // use the values
    Serial.write(xdata,4);
    Serial.write(ydata,4);
    lcd.print(x);
    lcd.setCursor(8,0);
    lcd.print(y);
      }
    }

The LCD monitor will show 77.25 and nan. It can't show 111.32 correctly.


texts: Memory leakage caused by String Concatenation

texts:
In this link, section "Memory, memory, memory" it's been told that doing many String concatenations in sequence, e.g.: using operator+() multiple times, will cause memory fragmentation, which may lead to the fact that total heap not being totally used.

An alternative I'm suggesting is using strcat() with char buffers and not using Strings at all, and then convert from resultant char buffer to String if a String is needed at the end?
Would that be an escape from fragmentation of the heap?

Clarification: I will specify the upper bound of the char buffer beforehand, as if I know the maximum needed/to-be-used size.


texts: Power 4 leds with max7219 and LedControl.h

texts:
So this is my first arduino (or embedded for that matter) project. I am trying to power 4 leds with max7219. Max7219 seems easy to use, but for some reason after I upload the code, nothing happens. I've looked over my breadboard, and the connections seem right. My confusion arises from the fact that all the projects I have found on google use matrices for the leds. I am using 4 separate leds. Does this even matter?

Here is the code I use:

#include "LedControl.h"

LedControl ledControl = LedControl(12, 9, 10, 1);

void setup()
{
    //should be waking ledcontrol
    ledControl.shutdown(0, false);
    ledControl.setIntensity(0, 8);
}

void loop()
{
    ledControl.setLed(0, 0, 0, true);
}


texts: Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins?

texts:
I'm trying to control the speed of two DC motors that are connected to a dual H bridge. I always used digital PWM pins with analogWrite() to change the speed, but since I'm making a project that will be using most of the digital pins, I wonder if I can use analog pins instead.

P.S. I know I can use analog pins as digital pins to free the digital PWM pins, but I'm not interested in doing that.


texts: Communication between 2 Bluetooth modules

texts:
I successfully connected two Bluetooth modules, HC-05 and HC-06 like on this website:

http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link/

I have an Arduino Nano that's the slave (HC-06) and an Arduino Mega that is the master (HC - 05) and there's is the code for both of them:

Reveiver - Master

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX | TX
String Data = "";
void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
}

void loop(){
    while (mySerial.available()){
        Serial.println(mySerial.read())
    }
}

Sender - Slave

#include <SoftwareSerial.h>
SoftwareSerial BTserial(11, 10); // RX | TX

int c = 100;

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

void loop(){
     BTserial.println(c);
}

I tried

BTserial.write(c)

and doesn't work either, I receive numbers like 245,255. And when I change the data that I'm sending the numbers are different, so I know that they are communicating, I think it's a variable problem, but I tried a bunch of codes of the internet that supposedly work, but it doesn't seem to work for this case.


texts: Help connecting an Arduino and an electronic speed controller

texts:
We have this controller that we are planning to use with this motor. How do we plug it to the Arduino to make it work?

This is a totally new subject for our school team, since we are mostly programmers, so your help will be really appreciated.


texts: How do I print the reading serial data sending from Arduino

texts:
I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert  the data to read.

You can see the receive data has some no printer character.

Workflow of sending and receiving data between QtSerialPort and Arduino

Sending Data with QtSerialPort

void MainWindow::sendData(){

    QString m_allData = m_sendEdit->toPlainText();
    int i = 0;
    int size = m_allData.size();

    QString line = "";
    int c = 0;
    while(i < size){
        line.append(m_allData[i]);
        if(c == 24){
            int sended = m_serialPort->write(line.toUtf8(), 24);
            m_serialPort->flush();
            line.clear();
            c = 0;
        }
        i++;
        c++;
    }
    if(c > 0){
        m_serialPort->write(line.toUtf8(), c);
    }
    m_serialPort->flush();
}

I want to send the data with a buffer size of 24 bytes.

Reading and Sending Data with Arduino

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

 void loop() {

    delay(1000);

    if (Serial.available() > 0){
        short i = 0;
        int size = Serial.available();
        String data = Serial.readString();
        Serial.print(data);
    }
 }

The Arduino code is simple.

Receiving Data with QtSerialPort

void MainWindow::readData(){
    int c = 0;
    char * dataBuffer;
    int size = m_serialPort->bytesAvailable();
    dataBuffer = new char[size];
    c = m_serialPort->read(dataBuffer, size);
    m_receiveEdit->setText(m_receiveEdit->toPlainText() + QString::fromUtf8(dataBuffer));
        delete dataBuffer;
}

I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?


texts: How to monitor state of 50 Digital Inputs

texts:
Good day.

I have a specific project need and I spent the past couple of days searching on forum, blogs, etc and I'm still not clear if that's feasible to do with Arduino or not.

I need to monitor the state of ~50 digital inputs and trigger an action when any of the pin changes either from 0 to 1 or from 1 to 0, pretty much the same as pin state interrupt works, only difference is that I need to "listen" to ~50 pins, instead of just a couple. I must be able to identify what pin triggered the action and what was the change (0->1 or 1->0).

My initial idea is to use a MEGA 2560 and have a group of 50 "if" statements on the main loop comparing the previous state or each pin (stored in individual variables) with the current one and triggering the corresponding action if something changed.

I'd like to hear from the experts here what would be a more elegant or smarter/faster way to accomplishing this.

I'm eager to receive your feedback.

Thank you.


texts:
I am trying to compile the following code:
logger.log_info(F(R"(some text here that may take
    multiple lines
    and here it is done.)"));

But the compiler exists with the following error:

error: unterminated raw string

I am able to use either R or F, but not both together. How should I be able to use them together?


texts:
I'm creating a  controller for a small greenhouse, I have a DHT22 for measuring and two relay module that controls heating and cooling systems, and I will use a piezo to produce humidity when it goes below X amount. This piezo works at 1.7 MHz and I know that Arduino can provide 1.779Mhz, I think It's close enough. After that I'll place a MOSFET at the output and then connect the piezo.
I'm quite new so I'm trying copy-paste some codes and this is what I've done:
I don't know how to turn on and off the frequency generator, I would like to know the code for that
           #include <DHT.h>
            #include <DHT_U.h>

            #define DHTPIN 6
            #define DHTTYPE DHT11 //Define sensor as DHT11

            #define RELAY1  4  // Relay heating
            #define RELAY2  5  // Relay cooling

            int red = 8; // red LED heating
            int blue = 9; // blue LED cooling

            DHT dht(DHTPIN, DHTTYPE);

            float temperature;
            float humidity;

            // Frequency Generator code
            const uint8_t OUTPUT_PIN = 3;  // = OC2B pin inamovible
            const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

            void setup()
            {

              pinMode(red, OUTPUT);
              pinMode(blue, OUTPUT);
              pinMode(RELAY1, OUTPUT);
              pinMode(RELAY2, OUTPUT);

              // Freq generator code
                pinMode(OUTPUT_PIN, OUTPUT);
                TCCR2B = 0;           // stop timer
                TCNT2  = 0;           // reset timer
                TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
                       | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
                       | _BV(WGM21);  // ...ditto
                TCCR2B = _BV(WGM22);  // ...ditto
                OCR2A = PERIOD - 1;
                OCR2B = PERIOD/2 - 1;
            }

            void soundBuzzer() {
                TCCR2B |= _BV(CS20);  // F_CPU / 1
            }

            void silenceBuzzer() {
                TCCR2B &= ~_BV(CS20);
                TCNT2 = 0;
            }
              //End of freq generator code
            void loop()
            {
              delay(1000); //delay time between measurements. 1 sec for DHT11

              temperature = dht.readTemperature(); //Reads temperature
              humidity = dht.readHumidity(); //Reads humidity

             if(temperature < 25)
                {
            digitalWrite(red,HIGH);
            digitalWrite(blue,LOW);

            digitalWrite(RELAY1,0);
            digitalWrite(RELAY2,1);
                 }
             else if(temperature > 25)
                {
            digitalWrite(RELAY1,1);
            digitalWrite(RELAY2,0);
            digitalWrite(red,LOW);
            digitalWrite(blue,HIGH);

            }

        if(humidity < 30)
         {
   TCCR2A |= _BV(COM2B1);
    }
        else if(humidity > 35)
                {
          TCCR2A &= ~_BV(COM2B1);

            }
        }

I don't even know if i'm doing it right, please let me know and thanks


texts: How do I Continuity Test/Troubleshoot a Linksprite RS232 V2 Shield?

texts:
I have a Linksprite RS232 v2 adapter (which uses a MAX232 chip), as per this image. I have soldered on the headers and tested the pins to make sure there are no solder bridges. I have set the jumpers so that D2 is set to TX and D3 to RX. However, I can't establish comms through the device using the Software Serial library, regardless of how I set the jumpers. (Real Term doesn't show me anything when a USB-to-Serial adapter is connected. However, if I change the baud rate to 9600, I get about 5 bytes of 0x00, then nothing.)

If I disconnect the shield from the Arduino board then supply 5V to pin 2 or 3 (from an Arduino) and connect pin 5 of the DB/E9 to the Arduino's GND, I get output from both pins 2 and 3 (RX/TX) on the DB/E9 (regardless of which pin on the board is powered). The voltage between pins 2 and 3 on the connector differs by ~0.1V. Is this normal or is my circuit faulty? How do I test the continuity of the board/connector and diagnose and fix the fault?

In case it's of any relevance, I'm using an Uno with an SMD chip.


texts: Xbee shield to shield connection sends but not receives correctly

texts:
Setup:
2XArduino Uno
2x XBees S1
2x Sparkfun xbee shields.

My first arduino reads in values from a photoresistor and sends the values to the second arduino.
I know for sure the arduino is sending  values because when i plugged the second xbee directly into the computer and opened the serial monitor correct values showed up in the serial monitor. But the problem is when i attach the second Xbee onto its sparkfun shield and arduino i get repetitive wrong values .

Can someone please tell me what i am doing wrong?
I am doing this to make sure i get the right values before i beef up the project.

Sender sketch

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <XBee.h>
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int photocellReading;     // the analog reading from the analog resistor divider
 SoftwareSerial XBee(2,3);
void setup(void) {

  Serial.begin(9600);
  XBee.begin(9600);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Wireless LightDimmer");

}
 void loop(void) {
  photocellReading = analogRead(photocellPin);
  lcd.setCursor(0, 1);
  lcd.print("Photocell= ");
  lcd.setCursor(11, 2);
  lcd.print(photocellReading);
  //Serial.println(photocellReading);
  lcd.setCursor(20, 0);
  lcd.print("Measured in lux");

  delay (500);
  lcd.setCursor(20, 3);
  lcd.print(" ");
 // Serial.print("Analog reading = ");
 // Serial.print(photocellReading);
   photocellReading = 1023 - photocellReading;
 unsigned int LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
   Serial.println( LEDbrightness);
    XBee.print(LEDbrightness);

  delay(1000);
}

recieving sketch

#include <SoftwareSerial.h>
#include <XBee.h>

SoftwareSerial XBee(2,3);

void setup() {
 // Begin Serial communication
 Serial.begin(9600);
 }
void loop(){
 while ( Serial.available() > 0) {
 unsigned int num =  Serial.read();
 Serial.println(num);
 delay(2000);
 }
}


texts: Need function to convert bool array to int- why doesnt this work?

texts:
Hey I wrote this function to convert an bool array to int:
(Math Lob included):

bool b_array[5];

int convertToInt(start_index,stop_index){
    int run=0;
    int result=0;
    for(int id=start_index;id<=stop_index;id++){
        result+=b_array[id] * pow(2.0,run);
        run++;
    }
    return result;
}

but it doesnt this work?

Thanks and kind regards
Nic


texts:
I have just installed the arduino IDE on my gentoo laptop. I then installed the toolchain with the following command:

crossdev -s4 avr

This does a stage 4 install of the toolchain, with all its dependecies etc.

I am following a tutorial, with my arduino uno, which I am assuming is using the Amtel ATmega328 chipset. This tutorial is simply going to turn an led on and off.

I click the verify button and I get the following errors:

/usr/libexec/gcc/avr/ld: cannot find crtatmega328p.o: No such file or directory

/usr/libexec/gcc/avr/ld: cannot find -latmega328p

collect2: error: ld returned 1 exit status

I downloaded the source files "avr-libc" compiled them and noticed inside the directory

/avr-libc-1.8.1/avr/lib/avr5/atmega328p

That the compiled module is named crtm328p.o which is available on my pc under the directory:

/usr/avr/lib/

I dont understand what is wrong and why this is not working. The only posts relating to missing files are over 5 years old and those solutions are not working.


texts: Arduino piezo-buzzer melody for car alarm

texts:
I would like to play car alarm sound through Arduino buzzer - something like this https://youtu.be/nuPHwijMsIg
Does anybody have a library for such melody?


texts: Need to make an action just once when condition is reached

texts:
I'm making a device for the visually disabled that makes a sound when the water in a bowl reach certain levels.

I've already made the sensors for three levels of water and if statements to make the sound, but I need the sound to be played just once for every level change and it loops over and over.
How can I make it to sound just one time?

Here is my code:

#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;

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

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
  }
  else if (mid >50){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
  }
  else if (low > 50){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
  }
  delay(100);


texts: What is better: one sprintf() or multiple strcat() and itoa()?

texts:
I was creating Arduino function which sends two int and additional chars between them and at the beginning and end of char array - then print that array to the serial port in almost real time. (For example "X50Y100T".)

I don't want to use String object in Arduino and I found two possible solutions:

Using sprintf():

char sendBuffer[16];
void dataSend(int first, int second) {
  sprintf(sendBuffer, "X%dY%dT", first, second);
  Serial.println(sendBuffer);
};

Or something like this:

char sendBuffer[16];
void dataSend(int first, int second){
  char convert[6];
  sendBuffer[0] = 'X';

  itoa(first, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'Y';

  itoa(second, convert, 10);
  strcat(sendBuffer, convert);

  sendBuffer[strlen(sendBuffer)] = 'T';

  Serial.println(sendBuffer);
  memset(sendBuffer,0,sizeof(sendBuffer));
};

My question is - which one is better from technical point of view?

The sprintf() looks better but it increases the sketch size by ~1,5KB. Are there any other drawbacks of sprintf()? The second solution do many things to achieve same thing and I don't know if it's efficient... Maybe there are other solutions for sending this kind of char array?


texts:
I'm trying to use a little pump with my arduino nano:

void setup ()
{
  pinMode(waterPump, OUTPUT);
}
...
  while (val < valueWater)
  {
    Serial.println ("in while"); // testing purpose
    digitalWrite(waterPump, HIGH);
    delay(1000); // 1 second
    digitalWrite(waterPump, LOW);
    val = analogRead(sondeEau);
  }

When I try this one, pump isn't working. When I unplug the waterPump pin, I see "LED3" that run, and when I plut it, LED3 is not running, why?

I tried to plug pump directly on 5V on arduino, pump works well...

This is the pump I bought: http://www.dx.com/p/hsyy01-water-pump-motor-w-hose-white-silver-236808

Thanks in advance to help me!


texts:
I am playing with a minimal https server on an ESP01S, using BearSSL::ESP8266WebServerSecure.

With 2048bit RSA keys it takes ~5 seconds to serve a "hello" request.
Using 256bit EC keys it takes ~2 seconds.

I wonder whether it is possible to make key exchange faster without giving up on reasonable security level.

I am struggling with trying to set ec_all_m15 implementation (see Key Exchange) to make it faster without any luck - I have actually no idea how to do it properly .

I tried something like

...
BearSSL::X509List *cert = new BearSSL::X509List(serverCert.c_str());
BearSSL::PrivateKey *key = new BearSSL::PrivateKey(serverKey.c_str());
server.setECCert(cert, BR_KEYTYPE_EC, key);
server.begin();
br_ssl_server_context sc;
br_ssl_server_init_full_ec(&sc, cert->getX509Certs(), 1, BR_KEYTYPE_EC, key->getEC());
br_ssl_engine_set_ec(&sc.eng, &br_ec_all_m15);
br_ssl_server_reset(&sc);

Could someone help pls?


texts:
I have found a similar qustion to mine but there was no good response.

I've connected my ESP8266 to Arduino UNO.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used AT+IPR=9600 command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor.

Note: I connected the esp8266 through a voltage regulator and a power source and both gave the same problem. My firmware is supposed to be updated so I don't think that it is the issue.

Could anyone please help me?


texts: Controlling 10+x 5m led strips with 10+ individual analog floor switches

texts:
I am looking to control around 10 (exact number TBD) non-addressable 5m led strips with an Arduino. Each led strip will be activated when a corresponding DIY analog floor switch.

The idea is to have a hallway with a number of these led strips oriented vertically from the floor to the ceiling and when somebody walks on the corresponding floor switch under the strip, the strip will light up.

I have a number of questions:

How could I have a setup that is scalable from 10 led strips and floor switches to 20? (having enough analog and digital pins)
How should I best distribute power to all the strips and for each switch? This is how I understand to setup 1 of the switches:
How do I wire the one colored non-addressable LED strips to the Arduino?

Note: I have coded before and done some soldering and simple electronics but have never used Arduino.

Thank you!


texts:
I am having a problem when I want to run code like this on a Arduino Uno with esp8266-01. It's not working. In serial monitor nothing about esp.

#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  esp8266.begin(9600);
  esp8266.print("AT+RST");
  delay(1000);
  esp8266.print("AT+CWMODE=1");
  esp8266.print("AT+CWJAP=\"ssisd\",\"pass\"");

}

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

}

But when I load to Arduino empty code and to serial monitor write "AT" it working or I can connect to
my wifi, but only with empty code.

RX is in pin 2 and TX is in pin 3.
And i flashing esp with this Tutorial


texts: Arduino Modbus - Rtu slave with Raspberry pi using MAX-485

texts:
I am trying to use Arduino as Modbus- RTU slave and Raspberry Pi as a Modbus master
I have interfaced Max485 (RS485 to TTL converter) with Arduino and Rs485 to USB converter in Raspberry Pi, Initially, I was able to send data from Arduino to Raspberry Pi, but the data seems to inconsistent and fails to read most times

I am using https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino for Arduino
Minimal Modbus for raspberry pi

Connections:
DI(max485)- TX ( Arduino),
DE(max485) -D4 ( Arduino),
RE(max485) - D4( Arduino),
Ro(max485) - RX( Arduino),
Vcc(max485) -5v( Arduino),
Gnd (max485)- GND( Arduino)

code for Arduino

#include <ModbusRtu.h>
uint16_t au16data[6] = {};
Modbus slave(5,0,4);
void setup() {
  slave.begin(19200,SERIAL_8N1 );
 }
void loop() {
  au16data[0]=100;
  au16data[1]=200;
  au16data[2]=300;
  au16data[3]=400;
  au16data[4]=500;
  au16data[5]=600;
  slave.poll( au16data, 6 );
  delay(3000);
}

python code

import minimalmodbus
from datetime import datetime
import time

instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 5)
instrument.serial.baudrate = 19200
instrument.serial.bytesize = 8
instrument.serial.parity = minimalmodbus.serial.PARITY_NONE
instrument.serial.stopbits = 1
instrument.serial.timeout =5
instrument.mode = minimalmodbus.MODE_RTU

while(1):
    try:
        val = instrument.read_registers(0,6)
        # Registernumber, number of decimals
        print val
    except IOError:
        error_msg = "Failed to read from device"
        error_time = datetime.now()
        print "IO Error Time",error_time.isoformat(),error_msg

    except ValueError:
        error_msg = "Failed to read CRC"
        error_time = datetime.now()
        print "Value Error Time",error_time.isoformat(),error_msg
    time.sleep(2)


texts: I want to work with interrupts and heard that the watchdog timer is effective way to deal with them.  I haven't been able to find a good tutorial on them though and was wondering if someone could head me in the right direction or give me a couple tips and an example.


texts: How to compose an HTTP GET request URL with key/value parameters

texts:
I am experimenting with some code running on an ESP8266 board to retrieve data using a web API. I would like to store the host address and key/value parameters (API key etc.) of the GET request as constants/variables (I'm not sure which is better) and then use them to compose the full GET URL.

How can I compose the full URL from separate strings/char arrays including the correct syntax for the key/values pairs?

EDIT: Just adding that I am using the ESP8266HTTPClient library.

The example I have been following uses a basic API URL with no parameters and stores the host URL as follows:

const char* host = "http://somehost.com/dir/1";

(Side question: please explain the difference between const char* host and const char *host if there is one)

Using this simple URL I can successfully retrieve the JSON data using this method:

HTTPClient http;
http.begin(host);
int httpCode = http.GET();
Serial.print("HTTP RESPONSE: ");
Serial.println(httpCode);
if (httpCode > 0) {
  String payload = http.getString();
  Serial.println("PAYLOAD:");
  Serial.println(payload);
}
http.end()

I am looking into using the "ArduinoJson" library to manage the json data instead of String, but am more interested in figuring out how to compose the URL at the moment.

What I would like to achieve is adding key/value parameters stored as variables to the host URL e.g.:

const char* host = "http://somehost.com/dir/1";
char* app = "123";
char* user = "123456"
char* api_key = "XXXXXXXXXXXXX";

And then join them with strings or char arrays to create the full URL, or simply pass the host address plus the parameter values to a function that composes the URL or sends the full GET request(with the parameter "key=var", question mark, and ampersands etc.):

http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX

This was very easy to achieve in python using the "requests" HTTP library. I was able to store the key/value parameters as a dict and then pass the host address and the parameter dict to the requests.get function and it would compose the URL automatically.

I guess there is more than one question buried in there, but the main one is "what is the best way to compose the full URL without hard coding the whole thing?" An example would be so I could change some parameters such as appid by user input before making the GET request.

I am unsure if I am using the right approach using the character arrays, constants or variables, whether I am using the right approach by trying to compose it manually, and in general what the best practices are for doing this efficiently and avoiding memory fragmentation (which is a problem when using string variables?). This device will be required to run constantly and periodically make these GET requests.


texts:
I'm trying to send data from an ATtiny84 [1mhz] to Arduino Uno using a 433Mhz rf module and Manchester lib.
Now I came across a weird problem, no matter what value I transmit, When I receive it on the arduino and to the Serial monitor, it always shows value of 806,No matter what I have really transmitted.

ATtiny side

void setup()
{
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(transmit_pin, MAN_1200);
}

// And how I transmit
// RGBread is int, I also tried man.transmit((uint16_t)RGBread[i]); same result.
  for(int i=0; i<3; i++)
  {
    man.transmit(RGBread[i]);
  }

Uno

void setup()
{
  man.setupReceive(reciever_pin, MAN_1200);
  man.beginReceive();
}

  if (man.receiveComplete()) {
    Serial.println(man.getMessage());
    man.beginReceive(); //start listening for next message right after you retrieve the message
  }

Thanks to all helpers.


texts:
I am new on Arduino, and I am trying to use the Ethernet shield...

but it need:

IP adress
MAC adress

IP adress is easy to get... but not MAC..

how can I get my arduino MAC adress?


texts:
I am trying to get my Arduino UNO to communicate with a Bluetooth Module (Bluetooth Bee), but I am getting a weird behaviour from the device. First, there are no leds blinking on the board (which I think there should be). Second, every time I send an AT command to the board I get ERROR: (0) which apparently is the caused by an invalid AT command, but it happens as I am sending just "AT" which should return "OK".

The Arduino code:

#include <SoftwareSerial.h>
SoftwareSerial BT(10,11);

void setup()  {

    BT.begin(38400);
    Serial.begin(9600);
    BT.print("\r\n+AT");
}

char a; // stores incoming character from other device

void loop() {

    if (BT.available())  {
        a=(BT.read());
        if (a=='\n') Serial.println((char)(a));
        else Serial.print((char)(a));

    }

}


texts: Connecting arduino to an existing circuit

texts:
I have a little clock with a button on it that i need to push four times every second hour. I am trying to get the arduino micro to do it for me.

I am trying to figure out how to connect the arduino to trigger it. The clock is operated by a CR2 (3.0V) cell battery. Is there a way to do this without a transistor? If not what do i need? How can i find out how much amp my circuit requires?

The red arrow is pointing on the cable i think triggers the clock, and i think the black arrow is pointing on the cable that is the clock gnd.

(edit: I have found similar questions explaining the process with transistor, but not without..)


texts:
I'm trying to connect an Arduino nano to a NodeMCU 1.0 via the hardware UART, in order to send information one way from the Arduino to the NodeMCU (and from there to the network).  I'm connecting the Arduino TX to the NodeMCU RX via a reduction of voltage from 5V to 3.3V but I'm getting nothing read at the serial.  The connectivity part is tested, since if I connect the NodeMCU via USB and write something with the Serial monitor, the data appears on the server.

Is there anything missing from the code on either parts?

The circuit is connected as follows:

and the code that runs on the Arduino (as a test) simply sends a string over and over, but at a low rate

    void setup() {
      Serial.begin(115200);
      while (!Serial) delay(10);
      pinMode(LED_BUILTIN,OUTPUT);
    }

void loop() {
  digitalWrite(LED_BUILTIN,HIGH);
  delay(100);
  digitalWrite(LED_BUILTIN,LOW);
  delay(100);
  Serial.println("Hello");
}

The code that runs on the NodeMCU is as follows:

WiFiClient client;

void connect_to_wifi()
{
  WiFi.begin(ssid, password);
  int tries=0;
  for(tries=0;tries<20 && WiFi.status()!=WL_CONNECTED;++tries)
  {
    digitalWrite(D0,(tries&1)==1?HIGH:LOW);
    Serial.print(".");
    delay(500);
  }
  if (tries>=20)
  {
    status=0;
    Serial.println("Failed to connect to WiFi");
  }
  else
  {
    Serial.println("Connected to WiFi");
    if (client.connect(addr, port))
    {
      Serial.println("Connected to server");
      client.println("Connected");
    }
    else
    {
      Serial.println("Failed to connect to server");
      status=0;
    }
  }
}

void setup() {
  pinMode(D0,OUTPUT);
  digitalWrite(D0,LOW);
  Serial.begin(115200);
  while (!Serial) delay(10);
  connect_to_wifi();
}

void loop() {
  if (status==0)
  {
    digitalWrite(D0,HIGH);
    delay(300);
    digitalWrite(D0,LOW);
    delay(300);
  }
  else
  {
    digitalWrite(D0,HIGH);
    delay(100);
    digitalWrite(D0,LOW);
    delay(100);
    int av=Serial.available();
    if (av>0)
    {
      client.println(av);
      for(int i=0;i<av;++i)
      {
        int c=Serial.read();
        client.print(char(c));
      }
    }
  }
}

EDIT 1:

I connected a scope to see the serial signal and see only high.  I then disconnected the NodeMCU and see a valid signal coming out of the Arduino.

Then I moved the receiving part to D5 on the NodeMCU and used a version of SoftwareSerial for this board, which worked.

For some reason, the hardware Rx is pulled high no matter what.
I would prefer to use hardware Serial, but if no solution can be found, I guess I will have to do with Software.


texts:
BLUF: Is it possible to use a shield to recognize a voice command like a name, then look for that name and info in a CSV file and then store certain info as variables to then actuate something?

Background: I want to work on a project where I would use a 1sheeld to use my phone's sensors for voice recognition and GPS. I want to be able to say a city name, store that input and then search a CSV file for that city's GPS location and then calculate the distance between the phone's location and the city's GPS location. I'm unsure with the 1sheeld example for voice recognition if I can do that (code below). I feel like I would have to make a floating variable that takes the input and then searches the CSV if it can find the city from the voice command and then creates another variable. Let me know your thoughts.

/*

Voice Recognition Shield Example

This example shows an application on 1Sheeld's voice recognition shield.

By using this example, you can play, pause and stop your smartphone's
music using voice commands.

OPTIONAL:
To reduce the library compiled size and limit its memory usage, you
can specify which shields you want to include in your sketch by
defining CUSTOM_SETTINGS and the shields respective INCLUDE_ define.

*/

#define CUSTOM_SETTINGS
#define INCLUDE_VOICE_RECOGNIZER_SHIELD
#define INCLUDE_MUSIC_PLAYER_SHIELD
#define INCLUDE_TERMINAL_SHIELD

/* Include 1Sheeld library. */
#include <OneSheeld.h>

/* Voice commands set by the user. */
const char playCommand[] = "play";
const char pauseCommand[] = "pause";
const char stopCommand[] = "stop";
const char nextCommand[] = "next";

void setup()
{
  /* Start Communication. */
  OneSheeld.begin();
  /* Error Commands handiling. */
  VoiceRecognition.setOnError(error);

  VoiceRecognition.start();
}

void loop ()
{
  /* Check if new command received. */
  if(VoiceRecognition.isNewCommandReceived())
  {
    /* Compare the play command. */
    if(!strcmp(playCommand,VoiceRecognition.getLastCommand()))
    {
      /* Play the track. */
      MusicPlayer.play();
    }
    /* Compare the pause command. */
    else if (!strcmp(pauseCommand,VoiceRecognition.getLastCommand()))
    {
      /* Pause the track. */
      MusicPlayer.pause();
    }
    /* Compare the stop command. */
    else if (!strcmp(stopCommand,VoiceRecognition.getLastCommand()))
    {
      /* Stop the track. */
      MusicPlayer.stop();
    }
    /* Compare the next command. */
    else if (!strcmp(nextCommand,VoiceRecognition.getLastCommand()))
    {
      /* Next track. */
      MusicPlayer.next();
    }
  }
}

/* Error checking function. */
void error(byte errorData)
{
  /* Switch on error and print it on the terminal. */
  switch(errorData)
  {
    case NETWORK_TIMEOUT_ERROR: Terminal.println("Network timeout");break;
    case NETWORK_ERROR: Terminal.println("Network Error");break;
    case AUDIO_ERROR: Terminal.println("Audio error");break;
    case SERVER_ERROR: Terminal.println("No Server");break;
    case SPEECH_TIMEOUT_ERROR: Terminal.println("Speech timeout");break;
    case NO_MATCH_ERROR: Terminal.println("No match");break;
    case RECOGNIZER_BUSY_ERROR: Terminal.println("Busy");break;
  }
}


texts: Reverse engineering LIN bus on E-bike system

texts:
As a project I am trying to 'hack' an old E-bike.
The electronic system of the bike consists of:

A torque sensor measuring deformation of the rear.
A 'spin' sensor measuring if the person is pedeling.
A battery pack with BMS
A speed controller inside the hub motor.
A display to control speed, lights and display distance information etc.

From researching I concluded that the sensors, dislay and speed controller are communicating over LIN because they have a ATA6661 LIN transceiver and they are all connected parallel over the VS, LIN and GND wire.
When I power up the speed controller on its own I can see some LIN communication on my oscilloscope:

I do not have a LIN transceiver to log the data but I attached a USB-TTL transceiver to the uart-side of the LINtransceiver. From my oscilloscope a deduced that the baud rate was 9600. I used termite to listen on my serial port and set it to hex view. This is what I got:

I'm not sure if I should change the amount of bits or parity bits.
My goal is to understand the frames that are send and to deduce which frame holds which sensordata or results in a certain activity.
When I compare this to an CANbus project I was doing it was fairly easy to for example deduce which command was controlling my car's left window because with can-utils (candump) I could see every packet. I could filter unchanged packets and it colorcoded which bit(s) in each packet recently changed.
Any advice/ideas on how to do this for LINbus?


texts: How can I read delay of a note that I am playing

texts:
I am playing note tone with CapacitiveSensor and an output of tone
like this

void loop() {
    time_before = millis();

    long total1 =  cs_2_3.capacitiveSensor(30);
    long total2 =  cs_2_4.capacitiveSensor(30);

    if((total1>200)||(total2>200)) {

        if(total1>200) {

            tone(12,261);
            time_after = millis();
            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }
        if(total2>200) {
             tone(12,294);
             time_after = millis();
             Serial.print("Time: ");
             Serial.println(time_after-time_before);
        }
    }
}

How can I read how many seconds I play this note par example


texts: Am not able to call C++ function pointers from inline assembly

texts:
Due to some curiosity, I was trying to use some assembly with my Arduino MEGA 2560.
I am not able to invoke a function from a c++ function pointer array.
When I uncomment the call function, func_a runs. However, when I almost reproduce the assembly, it doesnt work.
Example:
extern "C" void __attribute__ ((used, noinline, noreturn)) func_a();

typedef void (*volatile func_ptr)();

func_ptr tasks[MAX_TASKS] = {&func_a};

extern "C"
void __attribute__ ((used, noinline)) call(func_ptr *ptr) {
    (*ptr)();
}

void __attribute__ ((noreturn, used)) setup() {

    // call(tasks);

    asm volatile (
    "lds r26, (tasks)\n"
    "lds r27, (tasks + 1)\n"

    "ld r30, X+\n"
    "ld r31, X\n"

    "eijmp\n"
    );
}

Generated assembly recovered from avr-objdump
000001c6 <setup>:
 1c6:   a0 91 00 02     lds r26, 0x0200 ; 0x800200 <tasks>
 1ca:   b0 91 01 02     lds r27, 0x0201 ; 0x800201 <tasks+0x1>
 1ce:   ed 91           ld  r30, X+
 1d0:   fc 91           ld  r31, X
 1d2:   19 94           eijmp
 1d4:   08 95           ret

000001d6 <call>:
 1d6:   dc 01           movw    r26, r24
 1d8:   ed 91           ld  r30, X+
 1da:   fc 91           ld  r31, X
 1dc:   19 94           eijmp

An specific resources I should refer for things like this?
If it matters, I'm using platformio on a linux system for compilation.


texts:
I am wondering if anyone has ever connected the output of their LED strip back to the Arduino to read and make sure the strip is functioning correctly, kinda like checksum functionality.

I am using the FastLed library and it doesn't appear that this has been done.

The reason why I want to do this is because when an LED breaks on the strip, it causes all of the following LEDs to flicker wildly. I need to be able to shut the LED strip off immediately if it starts flickering because my device is being used as a visual therapy aid in a school.

I am using an Arduino Due with WS2812B LED strip.


texts: Problem while interfacing LCD screen with Arduino

texts:
I tried to interface an LCD screen with my Arduino but I have a problem - Nothing is being displayed on my LCD screen:

Here is the code:

#include<LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);  // sets the interfacing pins

void setup()
{
 lcd.begin(16, 2);  // initializes the 16x2 LCD
}

void loop()
{
  lcd.setCursor(0,0);           //sets the cursor at row 0 column 0
  lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
  lcd.setCursor(2,1);           //sets the cursor at row 1 column 2
  lcd.print("HELLO WORLD");     // prints HELLO WORLD
}


texts:
I'm trying to control several RGB leds individually. So far I've been able to control multiple RGB leds using only 3 PWM outputs using NPN transistors as shown here (pic below).

I would like to control each led individually in order to display different colors in each led. If I used the Arduino Mega, which has 12 PWM pins I could only control 4 different groups of leds using the approach mentioned above. It would be nice to be able to control them using the Arduino Uno or other boards with less PWM pins.

What would be a good solution for this? I've been taking a look to shift registers using ShiftPWM and solutions like the TLC5940 but I haven't got enough experience to tell which way would work better.