texts: Arduino potentiometer (external power) with amplifier

texts:
i am trying to make some kind of an amplifier. I got an amp board but want to read out the value from the potentiometer. The problem is that this pot is connected to the amp and has to be connected to the amps power Is there any way i can still read data (with an arduino) so that i can have a volume percentage on a lcd? Or is this imposible?

Amp 24v Potentiometer = 6pin. B50k

also what zould happen if i connect a 10k resistor instead of a 50k ressistor (audio potentiometer) what would the effect be?


texts: Problems with Arduino Uno Usb 2.0 shield when using a keyboard

texts:
I have an Arduino Uno and a usb 2.0 shield in which I connected a keyboard to. I have all the necessary libraries installed but what I am trying to figure out is how to light an led when I press a specific key.
I am new to codding Arduino boards and I have done a lot of reading but I cant figure out my issue I feel like if I get this figured out I will be a lot better off in my future projects.
#include <hidboot.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

int SKEY = 8;

class KbdRptParser : public KeyboardReportParser
{
    void PrintKey(uint8_t mod, uint8_t key);

  protected:

    void OnKeyDown  (uint8_t mod, uint8_t key);
    void OnKeyUp    (uint8_t mod, uint8_t key);
    void OnKeyPressed            (uint8_t key);
};

void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
  MODIFIERKEYS mod;
  *((uint8_t*)&mod) = m;
  Serial.print((mod.bmLeftCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmLeftShift  == 1) ? "S" : " ");
  Serial.print((mod.bmLeftAlt    == 1) ? "A" : " ");
  Serial.print((mod.bmLeftGUI    == 1) ? "G" : " ");

  Serial.print(" >");
  PrintHex<uint8_t>(key, 0x80);
  Serial.print("< ");

  Serial.print((mod.bmRightCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmRightShift  == 1) ? "S" : " ");
  Serial.print((mod.bmRightAlt    == 1) ? "A" : " ");
  Serial.println((mod.bmRightGUI  == 1) ? "G" : " ");
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
  Serial.print("DN ");
  PrintKey(mod, key);
  uint8_t c = OemToAscii(mod, key);

}

void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
  Serial.print("UP ");
  PrintKey(mod, key);
}

void KbdRptParser::OnKeyPressed(uint8_t key)
{
  Serial.print("ASCII: ");
  Serial.println((char)key);
};

USB Usb;
HIDBoot<USB_HID_PROTOCOL_KEYBOARD>    HidKeyboard(&Usb);

KbdRptParser Prs;

void setup() {

 Serial.begin(9600);
#if !defined(__MIPSEL__)
  while (!Serial);
  Serial.println("Start");

  if (Usb.Init() == -1)
    Serial.println("OSC did not start.");

  delay( 1 );

  HidKeyboard.SetReportParser(0, &Prs);

}

void loop() {
 Usb.Task();
}

Anyways I know how to make if statements and how to activate pins on the Arduino but I cant figure it out in this keyboard library. For now I just made it print "TRUE" since there is not need to get complicated if I cant get the first step to work. Before I made that if statement the serial monitor would show the value assigned to the key and label it DN # and when I let up on the key it would say UP # but how can I translate that to sending a pulse to whatever pin when I push a key and stop sending a pulse when I let up on the key?
Also in my if statement that I made I know I need something before == sign but I tried multiple things and they did not work so I just left it blank and the reason I used the number 16 was because that was the value assigned to the S key in which I wanted to use to light an led. Anyways any help would be greatly appreciated!


texts: Binary reader with arduino blinking 8 leds

texts:
I´m trying to insert a binary raw sequence (01010100, 01101000, 01100001) into Arduino. I would like to make 8-led group blink in a loop, showing with light each 8-group binary sequence when: 0=light off and 1=light on.

It´s possible to do this operation with Arduino-uno ?


texts: What does it mean in I2C, "NACK received"?

texts:
I am reading about I2C. On this site:

http://playground.arduino.cc/Main/WireLibraryDetailedReference#endTransmission

It says that endTransmission() can return one of the following status codes:

0: Successful send.
1: Send buffer too large for the twi buffer. This should not happen, as the TWI buffer length set in twi.h is equivalent to the send buffer length set in Wire.h.
2: Address was sent and a NACK received. This is an issue, and the master should send a STOP condition.
3: Data was sent and a NACK received. This means the slave has no more to send. The master can send a STOP condition, or a repeated START.
4: Another twi error took place (eg, the master lost bus arbitration).

If I attach nothing to my Arduino (or with pull-up resistors to both SDA/SCL), I always get status 2. But how can a NACK (or anything) be received when there is nothing to communicate with? Does it mean something else?

Here is my example code

#include "Wire.h"
void setup() {
  Serial.begin(9600);
  Wire.begin();
}
void loop()  {
  Wire.beginTransmission(42);
  Wire.write(0);
  byte status = Wire.endTransmission();
  Serial.println(status); // always prints 2
}


texts: Wire doesn't work between Uno & ESP32S & ESP8266

texts:
I think i've reached my limit. I can't get Wire to work between an Uno or ESP8266 or ESP32S. On the Uno I had them connected like SDA via Uno SDA -> ESP32 GPIO21 SCL via Uno SCL -> ESP32 GPIO22.

I also tried flipping them like this:

SDA via Uno SDA -> ESP32 GPIO22
SCL via Uno SCL -> ESP32 GPIO21

Connections are as follows:

SDA via ESP32 GPIO21 -> ESP8266 GPIO4
SCL via ESP32 GPIO22 -> ESP8266 GPIO5

I also tried flipping them, as follows:

SDA via ESP32 GPIO21 -> ESP8266 GPIO5
SCL via ESP32 GPIO22 -> ESP8266 GPIO4

I have present a 4.7 kOhm pull-up resistor from SDA and SCL to +3.3 V.

All these combinations led to nil result on I2C bus scanners. I tried 5 scanners and 3 Wire libs. I tried having the ESP32 as slave because I heard the ESP8266 won't work as slave. I know I'm doing something wrong but can't figure it out, I've been at it all day.


texts:
I'm an Arduino newbie having problems with 4 digit 7 segments display.
I want to display some thousands to 4 digit 7 segments display but it display only 0000.
I want to receive data from serial with string. And display the data to 4 digit 7 segments display... So test make String = '2575'... but it's not work.
What's wrong in my codes?
Any suggestions here will be a great help. thanks

int segments[] = {A0, A1, A2, A3};

byte digits[10][7] =
{
  { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }  // 9
};

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

  for(int i=2;i<10; i++) {
    pinMode(i, OUTPUT);
  }

  for(int i=0; i<4; i++) {
    pinMode(segments[i], OUTPUT);
  }
}

void loop() {
  String IncomingData = "2575";

  for(int i=0; i<4; i++) {
    digitalWrite(segments[i], LOW);
    int digit = atoi(IncomingData[i]);
    displayDigit(digit);
    delay(5);
    digitalWrite(segments[i], HIGH);
  }
}

void displayDigit(int num){
  int pin = 2;
  for(int i=0;i<7;i++){
    digitalWrite(pin+i, digits[num][i]);
  }
}


texts:
For my application I need to simulate the sunlight including the rising and setting of the sun.

I have a program that will light up some LEDs slowly over a period of time but I need to know what to type in the (delay on) to keep the lights on for 7 hours?

Will it work if I just replace delay(1000) with delay(25200000UL) ?
I don't want to run anything else at the same time and don't want to use or understand millis().
Thanks for any help.


texts:
I have a code in Visual studio that I want to implement in Arduino. But
there is a problem. Many libraries usable in Visual Studio aren't usable
in the Arduino IDE. How can I use them in my Arduino code? To be
precise, the libraries I want to use are

#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <math.h>
#include <ctime>

I know I have <iostream> available in Arduino. <math.h> is also
available I think along with the <string> library. The main problem is
to how to use #include<queue> and its functions such as
priority_queue() and other functions of iosteam like .pop()? Any
help would be highly appreciated.


texts: Fading red to white to blue continuous loop on ws2812 LED strip

texts:
I'm a big noob when it comes to writing a sketch and have set myself a task for an upcoming 4th July project, which has come to a halt.

I'm trying to set a strip of 30 LEDs to fade from red to white to blue through FastLED on a Wemos D1 mini. I also wanted it to flash each colour after the 3 colours have faded and continuously loop these.

I have searched many different forums and managed to get the fade to go from red to blue, but can't for love nor money add the white in-between.

Can someone point me in the right direction?

#include "FastLED.h"
#define NUM_LEDS 30
#define DATA_PIN D4
#define COLOUR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup() {

    FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}
void loop(){

    //start from red
    for( int colorStep=0; colorStep <= 255; colorStep++ ) {

        int r = 255;
        int g = 0;
        int b = colorStep;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }

    //into blue
    for( int colorStep=255; colorStep >= 0; colorStep-- ) {

        int r = colorStep;
        int g = 0;
        int b = 255;

        // Now loop though each of the LEDs and set each one to the current color
        for(int x = 0; x < LED_COUNT; x++){
            leds[x] = CRGB(r,g,b);
        }

        // Display the colors we just set on the actual LEDs
        delay(10);
        FastLED.show();
    }
}


texts: Sync audio with color and brightness of RGB strip with aux input or mic

texts: I need to make an RGB music sync ledstrip (a normal strip, not one with addressable LEDs). I only need to change the brightness and color in sync with the input through the aux port. If this is not possible, the mic input will do as well. I have 2 Arduino Nanos (if needed somehow) and a 12V generic laptop adapter.


texts:
I bought an Analog Device EVAL-AD7746LDZ water level sensor dev board.
Unfortunately the Analog's documentation is available only for EVAL-7746EB.
My goal is to read the height of water (in mm) via i2c.
I didn't find any library nor example.
So I'm reading the datasheet of AD7746.
Anyway the document explain only how to read the ADC registers, but say nothing about the specific application. I don't understand what is the required configuration for this eval board in order to setup the ADC correctly.


texts: Remote temperature and humidity sensor with long battery life

texts:
I want to build a remote sensor which will measure temperature (range 5-30°C) and humidity (range 20-90%) and provide regularly (in the range of one measurement every minute or tenth of minutes) the measurement via wireless. This sensor will be used indoor, mostly in dark areas.

Note: measurement could be done every minutes and sending them could be done immediately or in batch of 10 measurements or more).

I was looking to build this solution using an Arduino, DHT22 sensor and a radio transmitter using ZigBee or Z-Wave protocol, and power it via AA rechargeable batteries. But after studying this solution, I found that it would be challenging to even get a week of battery life, this would require using the radio sparingly and to try to use as much as possible the power modes of the Arduino ATmel controller.

That's not enough, I want a battery life in the range of several months, 1 month would be "acceptable", 6 months would be the target, breakthrough would be > 1 year.

Note: I don't want wifi, this seems to suck even more power than the other mentioned radio protocol

Questions

Is there another more power efficient way to wireless-ly transmit the data?

Or shall I reconsider Arduino all together and look for another more power efficient controller?

Or is there another way?


texts:
I have a PN532, so it's capable of both reading and writing. I've used it for a few perfectly functional things, but I want it to authenticate based on the contents (for example 1024 bytes) of a tag.

I'd generate some pseudorandom data, possibly on my PC, and write that into each card, and use a checksum of that as the key.

Should I just stick with the standard authentication of tokens, or is this a worthwhile alternative method? The UIDs of the tokens are not interesting for authentication.

If worthwhile, what checksumming algorithms should I use? If not, would someone care to explain how I can program the memory of tokens, and how to use that in addition to UID for auth?

Thanks in advance.


texts:
I am trying to control a 28BYJ-48 stepper motor + ULN2003 motor driver module  (this is a picture) using MATLAB.

I tried to follow the instructions on this page, but these instructions are specific to Adafruit MotorShield, and I couldn't understand how to modify the code to fit my motor/driver.

Specifically:

How do I wire my motor/driver/Arduino?
How do I modify this command:

shield = addon(a, 'Adafruit\MotorShieldV2')

Do I need to flash my Arduino with any libraries?


texts:
Problem:

I'm working with a GPRS module (the same as in the Arduino GSMShield). In some cases the PUK code is requested, and the PIN is thus locked. For this I wrote some code (which can be seen under "Software"). This code is based on the documentation of "GSM PIN Management". The only problem is that the module is telling us that both the PIN & PUK code is locked. The tutorials, however, does not provide an example how we should resolve this issue from the Arduino itself.

EDIT: When the SIM card is inserted in a smartphone. The PUK code is requested. When the PUK code is provided (and a new PIN) the SIM card is back to normal. But adding the PUK code via the GSM lib. doesn't really work, in contrast to using a smartphone to unlock the PIN code.

Question:

Does anybody have an idea how to resolve this issue? And if it can be done?

Hardware:

Atmega328p
Quectel M95 (as GPRS module)

Software:

PINManager.begin();
int pin_query = PINManager.isPIN();
Serial.print(F("Pin Query is: ")); //output: -2
Serial.println(pin_query);
if(pin_query == -1)
{
  #ifdef DEBUG
    Serial.println(F("PUK is requested"));
  #endif

  if(PINManager.checkPUK(PUK_NUMBER, PIN_NUMBER_CORRECT) == 0)
  {
    PINManager.setPINUsed(true); // I also think this must by "false". Both things were tested, none of them worked.

  }
}


texts:
I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists.

Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?


texts:
My current function is supposed to play a sound effect, then after the sound effect is done (14 seconds), perform the next action (digitalWrite(CONTROLLINO_R1, LOW)).

if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch) {
  skeleLatch = 1;
  wTrig.trackPlayPoly(2);
  unsigned long currentMillis = millis();
  if((currentMillis-previousMillis) >= 14000) {
    digitalWrite(CONTROLLINO_R1, LOW);
    previousMillis = millis();
  }
}

As it is, it performs both at the same time. I do not know how to correctly implement the delay so that it waits.

Any help would be appreciated. Thank you.


texts:
So i'be been toying with the idea in my head of creating a solar powered weather station with an arduino, two 6V 2W solar panels in parallel, two 5V USB battery packs, and an adafruit module which converts voltages from 3-12V to 5V (to charge my batteries). I'm also working on using some small relays or MOSFETs for the arduino switch between batteries.

The problem: If my solar panel voltage drops below 3V, the adafruit board will supply the batteries with a n unstable voltage below 4.8V. I need some sort of circuit or sensor that is capable of detecting when the voltage  from the solar panels drops below 3.3V and which will open the circuit to protect the batteries from unstable voltages.


texts: How to connect a LiFePO4 battery directly to an esp32?

texts: If I want to connect a LiFePO4 battery (as the power supply) directly to an esp32 - would this be the correct way: the plus of the battery to the 3.3 volt pin and the minus to a ground pin?


texts: Do I have to connect RX and TX of SIM900A with any pins (say TX, RX of Arduino) for network purpose? Shouldn't the network status LED blink slower after connecting the power sources with SIM900A?


texts:
I have a strange issue. I have 3 LEDs, each is supposed to beep with a correlated tone... Imagine the beginning of a racing game (beeping with traffic lights). Here's my code:

#include "pitches.h"

//Beginning Melody
int melody[] = {
  NOTE_C3, NOTE_C3, NOTE_C4
};

//Beginning Note Durations
int noteDurations[] = {
  2, 2, 1
};

int redLight = 3;
int yellowLight = 5;
int greenLight = 6;

void setup() {
  Serial.begin(9600); //initialize serial communication

  pinMode(redLight, OUTPUT);
  pinMode(yellowLight, OUTPUT);
  pinMode(greenLight, OUTPUT);
}

void loop() {
  playBegin();
  delay(5000);
}

void playBegin(){
  int lightColor = 1;

  for (int thisNote = 0; thisNote < 3; thisNote++) {

    if(lightColor == 1){
      analogWrite(redLight, HIGH);
    }else if (lightColor == 2){
      analogWrite(yellowLight, HIGH);
    }else{
      analogWrite(greenLight, HIGH);
    }
    lightColor++;

    int noteDuration = 1000 / noteDurations[thisNote];
    tone(11, melody[thisNote], noteDuration);
    delay(1000);
    noTone(11);

    analogWrite(redLight, LOW);
    analogWrite(yellowLight, LOW);
    analogWrite(greenLight, LOW);
  }
}

Originally, the 3 LEDs would light up correctly. The red light is plugged into Pin 3, the yellow light into Pin 5, and the green light into Pin 6. HOWEVER, when I added in the tones, the red light (in Pin 3) doesn't light up. The 3 tones still sound off correctly, and the yellow and green LEDs work perfectly fine. This is ONLY not working for the red LED, it just doesn't light up while the 1st tone happens.

When I take out the line of code where tone() is, it works fine and the red light will turn on at the correct time again. This is ONLY happening when the tone() function is included.

To be clear, this is the exact line of code that is affecting the red LED:

tone(11, melody[thisNote], noteDuration);

Furthermore, I swapped the pins of the yellow and red LEDs to see if it was an issue with the red LED, and it was not. It's whatever LED is plugged into Pin 3, and again, ONLY when the tone() function is in the code as well. I'm not sure how they're conflicting. This does not appear to be an issue with my hardware.

I'm working with Arduino Uno. If you need anymore info, let me know.

Thanks!


texts: Possible to use the hardware serial port for peripheral on ATmega32u4 when using USB for programming?

texts: I have a Arduino Pro Micro and use the USB port for programming. Is it possible to use the hardware serial port for connecting with a peripheral while I'm using the USB port (and hence the hardware serial port) for programming? Or must I disconnect the USB cable or otherwise reconfigure the hardware?


texts:
Is it possible to have an Arduino Uno + WiFi 101 recognize when the USB cable has been connected and prompt a user to enter a network name and password?

Can this be stored on the Arduino itself or does it need to be something run locally on the user's PC?


texts: SOLVED: Soft Power On SIM900 module - JP pads missing!

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


texts: On the Uno, why does VIN require 7-12 volts and the USB only 5 volts?

texts: I'm just wondering why the VIN would require 7-12 volts when the USB port itself only requires 5 volts? What happens if you power an Uno on VIN with 5 volts?


texts: How can I send a number from a master and make the slave read it?

texts:
I am building a fan controller using an Arduino and a Raspberry Pi (the Pi is the master and the Arduino is the slave). The Raspberry Pi generates random numbers and I want the slave (Arduino) to be able to read the string of numbers and increase the current speed of a pwm fan by the amount read.
How I can read the bits sent over I2c as numbers to allow me to do what I want to do?


texts: Why we can wake Arduino Uno from sleep using only pin 2?

texts: Can we use other pin as an interrupt to wake Arduino Uno from sleep ?


texts: Single LED controlled by two pushbuttons - one of which acts like a toggle switch

texts:
Trying to control this LED with those 2 pushbuttons - one button that starts a short flashing sequence, another pushbutton acts like a toggle switch, one press bulb is on, another press bulb is off.
If I switch the LED on and then push the flashing button, the on-off flashing starts but then the LED is shut off because off is the last state of the flashing sequence. How do I make the led turn to original state?
#include <ezButton.h>

const int flashing_pin = 2;
const int switch_pin = 3;
const int led_pin = 8;

ezButton button(switch_pin);

int ledState = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(led_pin, OUTPUT);
  pinMode(switch_pin,INPUT_PULLUP);
  pinMode(flashing_pin,INPUT_PULLUP);
  button.setDebounceTime(50);
}

void loop() {
  button.loop();

  if(button.isPressed()) {
    Serial.println("Press");

    ledState = !ledState;

    digitalWrite(led_pin, ledState);
  }

  if( digitalRead(flashing_pin) == LOW )   {
    doFlash(4);
  }
}

void doFlash(uint8_t number_of_times)  {
  while(  number_of_times-- > 0 ) {
    digitalWrite(led_pin,HIGH);
    delay(250);
    digitalWrite(led_pin,LOW);
    delay(250);
  }

}

To explain what I want in short;

if LED is off - flashing sequence works like "ON OFF ON OFF"
if LED is on - flashing sequence works like "OFF ON OFF ON"


texts: Serial monitor doesn't work with piezo buzzer

texts:
So I can't see the distance of the proximity sensor anymore as soon as I type the code for the piezo buzzer. I've tried many things but it doesn't work.. Can anybody help me fixing this?

int trigPin = D7;
int echoPin = D8;
int BLUE = D3; //D3 zit in blauw
int GREEN = D4;
int RED = D5;
int piezoPin = D10;

void setup() {// deze code gaat maar 1 keer
  Serial.begin (115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(RED, OUTPUT);

}

void loop() { //code wordt steeds herhaalt
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); // trig zendt een signaal uit
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // kijkt hoelang het duurt totdat signaal heen en weer gaat
  distance = (duration/2) / 29.1;
  // omdat het signaal heen wordt gezonden moet het door twee gedeelt worden
  // snelheid van geluid door lucht is circa 29 microseconden per cm dus gedeelt 29.

    Serial.print(distance);
    Serial.println(" cm");

//afstand wordt in cm weergegeven in serial monitor

  delay(500);

   if ((distance > 100) && (distance <= 150)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 100 cm en gelijk aan of kleiner dan 150 cm is.
    analogWrite(BLUE, 0);
    analogWrite(GREEN, 255);
    analogWrite(RED, 0);

    tone(piezoPin, 1000, 1000); // toon duurt 1 seconden
    delay(2000); // 2 seconden geen geluid
    tone(piezoPin, 1000, 1000);
    delay(2000);

   }

   else if ((distance > 50) && (distance <= 100)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan 50 cm en gelijk aan of kleiner dan 100 cm is.
    Serial.println("Ga weg!");

    analogWrite(BLUE, 0);
    analogWrite(GREEN, 102);
    analogWrite(RED, 252);

    tone(piezoPin, 1000, 700); // toon duurt 0.7 seconden
    delay(1000); // 1 seconde geen geluid
    tone(piezoPin, 1000, 700);
    delay(1000);

  }

  else if ((distance >= 0) && (distance <= 50)){ //dit gebeurd er als de afstand vanaf sensor tussen groter dan of gelijk aan 0 cm en gelijk aan of kleiner dan 50 cm is.

    analogWrite(BLUE, 0);
    analogWrite(GREEN, 0);
    analogWrite(RED, 255);

    tone(piezoPin, 1000, 200); // toon duurt 0,2 seconden
    delay(100); // 0,1 seconden geen geluid
    tone(piezoPin, 1000, 200);
    delay(100);

  }

   else {
    analogWrite(BLUE, 0);
    analogWrite(GREEN, 0);
    analogWrite(RED, 0);

 }

}


texts: cannot connect ESP8266 web server after some time

texts:
I am new to ESP8266 and found an example about turning a LED ON/OFF using web interface. It works well but after some time (few minutes) i cannot open the web page (in my case it is http://192.168.100.23 and i made it static IP). It keeps 'waiting for 192.168.100.23'. I can ping the IP. Can someone please help to find what the problem is? Thank you very much!

Below is the code:

#include <ESP8266WiFi.h>
#define LED D2
const char* ssid = "myAP";
const char* password = "32133213";
unsigned char status_led=0;
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  /*WiFi.persistent( false );
  WiFi.setAutoConnect(true);
  WiFi.mode(WIFI_STA);*/
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  Serial.println("new client");
  while(!client.available())
  {
    delay(1);
  }
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  if (req.indexOf("/ledoff") != -1)
  {
    status_led=0;
    digitalWrite(LED,LOW);
    Serial.println("LED OFF");
  }
  else if(req.indexOf("/ledon") != -1)
  {
    status_led=1;
    digitalWrite(LED,HIGH);
    Serial.println("LED ON");
  }
  String web = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  web += "\r\n";
  web += "\r\n";
  web += "
LED Status
\r\n";
  web += "
\r\n";
  if(status_led==1)
      web += "LED On\r\n";
  else
      web += "LED Off\r\n";
  web += "
\r\n";
  web += "
\r\n";
  web += "\r\n";
  web += "<button>LED On</button >\r\n";
  web += "\r\n";
  web += "
\r\n";

  web += "\r\n";
  web += "<button>LED Off</button >\r\n";
  web += "\r\n";

  web += "\r\n";
  web += "\r\n";

  client.print(web);
}


texts: Check contents of buffer after serial read

texts:
I would like to test the contents of data received over a serial connection. In my loop() I store the data in bffr; and afterwards I would like to test to see if there are some predefined words in it.

#define BFFSZ 90
char bffr[BFFSZ];
char bffridx;

void loop()
{
   readline();

   //- Test the bffr
       if(strstr(bffr, "CLOSED")){ //- WORKS
          Serial.println("> conn. closed");
          digitalWrite(A1, HIGH);
       }else if(strstr(bffr, "RING")){ //- WORKS
          Serial.println("> Someone is ringing");
          digitalWrite(A2, HIGH);
       }else if(strstr(bffr, "0,7,j,BLINK")){ //- Doesn't work
          Serial.println("> Blink");
          digitalWrite(A2, HIGH);
          delay(300);
          digitalWrite(A2, LOW);
       }
}

void readline()
{
   memset(bffr,0,sizeof(bffr));
   char c;
   int i =0;
   bffridx = 0; // start at beginning

   long previousMillis = millis();
   while (1) {
     unsigned long currentMillis = millis();
     if(currentMillis - previousMillis > 20000) {
       Serial.println("TIMEOUT");
       return;
     }
     delay(2);

     c=gsm.SimpleRead2();
     //- debug only, to see if there is something received.
     Serial.write(c);

     if (c == -1)
       continue;
     if (c == '\n')
       continue;
     if ((bffridx == BFFSZ-1) || (c == '\r')) {
       bffr[bffridx] = 0;
       return;
     }

     bffr[bffridx++]= c;
     delay(2);
   }
}

The debug-line makes that I can see the data flowing, eg when I phone the SIM.

But it looks like the buffer isn't tested properly. The first two will work, but the last test fails. It is part of a larger string: $0,7,j,BLINK,567^ But I thought the strstr(1,2) searches for 2 in 1. And as 0,7,j,BLINK, is within the haystack I assume it wil return true. But apparently not...

The gsm.SimpleRead2() comes from GSMlib and is my altered version of gsm.SimpleRead(). Instead of printing the char, I just return it so we can buffer it in the readline function.

void SIMCOM900::SimpleRead()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     Serial.print(datain);
   }
 }
}
char SIMCOM900::SimpleRead2()
{

 char datain;
 if(_cell.available()>0){
   datain=_cell.read();
   if(datain>0){
     return datain;
   }
 }
}

Does anyone know the answer to this?


texts: Arduino Wifi Rev2, bug when reading PWM duty cycle value on pin 6

texts:
I am trying to read the PWM duty cycle set for pin 6 on the Arduino Wifi Rev2.
By default, the timer used is TCB0, used in 8-bit PWM mode. The 16-bit Compare channel CCMP is used as two 8-bit registers, the lowest byte CCMPL is for the period, while the highest byte CCMPH is for the duty cycle.
However, something weird happens when I try to read the Compare channel register, the value of CCMPH is unexpecteadly copied into CCMPL.

// PWM on pin 6, timer TCB0
//TCB_t* timer_B0 = (TCB_t *)&TCB0; // pointer on timer structure

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

void loop() {
  setPWMValueOnPin6(20);
  setPWMValueOnPin6(40);
  setPWMValueOnPin6(60);
  setPWMValueOnPin6(80);
}

void printCompareChannelValues()
{
  Serial.print("Compare channel = ");
  unsigned int r = TCB0_CCMP;
  //byte r = timer_B0->CCMP;
  Serial.println(r);

  Serial.print("Compare channel L = ");
  byte l = TCB0_CCMPL;
  //byte l = timer_B0->CCMPL;
  Serial.println(l);

  Serial.print("Compare channel H = ");
  byte h = TCB0_CCMPH;
  //byte h = timer_B0->CCMPH;
  Serial.println(h);
}

void setPWMValueOnPin6(byte value)
{
  analogWrite(6, value);
  printCompareChannelValues();
  delay(2000);
}

Here is the serial monitor output:
Compare channel = 5375
Compare channel L = 255
Compare channel H = 20
Compare channel = 10260
Compare channel L = 20
Compare channel H = 40
Compare channel = 15400
Compare channel L = 40
Compare channel H = 60
Compare channel = 20540
Compare channel L = 60
Compare channel H = 80
Compare channel = 5200
Compare channel L = 80
Compare channel H = 20
Compare channel = 10260
Compare channel L = 20
Compare channel H = 40
Compare channel = 15400
Compare channel L = 40
Compare channel H = 60
Compare channel = 20540
Compare channel L = 60
Compare channel H = 80
Compare channel = 5200
Compare channel L = 80
Compare channel H = 20

Problem occurs even when removing the serial functions (by watching at a led intensity on pin 6).
The same behavior occurs on pin 3 (timer TCB1).
Does someone has any idea what is going on? Thanks for your help.


texts: Arduino Mega 2560 as ISP for ATTINY2313 / ATMEGA328P

texts:
I have posted this on the Arduino forum also, but I give it more chance if posted here also.

I've been trying to use my Arduino Mega as an ISP for programming two different ATMEGA328P's and a ATINY2313, but I just don't succeed.

I am running the Arduino IDE (version 1.5.8 ) on windows 7. I've been using these http://www.instructables.com/id/How-to-use-Arduino-Mega-2560-as-Arduino-isp/ http://www.instructables.com/id/Arduino-ATtiny2313-Programming-Shield/ instructables for help. The circuit are built on a breadboard. On my Arduino Mega is use the pins reset: 53, MOSI: 51, MISO: 50, SCK: 52.

First I upload the arduino as ISP sketch on my Mega. There are LEDs on the programming, error and heartbeat outputs, the heardbeat is pounding. I then select the according board from the boards list (the ATINY2313 1MHz from the instructable for the ATTINY and either the Arduino UNO or the Arduino Duelimanove for the ATMEGA328P) and after that the programmer árduino as ISP'. When uploading the Blink sketch I get errors like:

avrdude: Yikes! Invalid device signature
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51
I have tried things like capacitors/resistors between the reset and the ground or between the reset and the +5V, but nothing different. I have searched for help on the internet and alot of people have problems with it, but no clear or working answers. I have been looking at the MegaISP guide form Arduino, but this is not very clear to me.

I have no idea where to start anymore. Does anybody have an idea what I can try or where to start searching for answers?

I appriciate all the help I can get!


texts:
I found this sketch online and would like to reuse it. I do have a dot-matrix-display, that is accessable through an i2c with the address 0x70. How do I change the code to be able to use the hardware address instead of the Data, Load and CLK pins?

#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>
#include "LedControl.h"

//Pin definition constants
const int mDataIn=12, mLoad=11, mClk=10;  //Max7219 LED matrix

int h1, h2, m1, m2, s1, s2; // Each digit
int tChange; //Scratch used during change time via pushbutton

// Matrix library instance
LedControl lc=LedControl(mDataIn, mClk, mLoad,1); //Pin assignments and number of matrices (1)

void setup() {

  // Notify Arduimo that the RTC is the external time provider
  setSyncProvider(RTC.get);

  //Initialize the MAX72XX in power-saving mode.
  lc.shutdown(0,false);
  lc.setIntensity(0,1); // Set brightness to a low value
  lc.clearDisplay(0); // Clear the display
  delay(100); // Wait after initializing display

  Serial.begin(9600);
}

void loop() {

  //Isolate hours, minutes, seconds, one digit to each LED matrix column.
  h1=n1(hour());
  h2=n2(hour());
  m1=n1(minute());
  m2=n2(minute());
  s1=n1(second());
  s2=n2(second());

  // Cast as (change integer to) byte, write to LED row.
  // (Row runs from pin to pin on model used.)
  lc.setRow(0,7,byte(h1));
  lc.setRow(0,6,byte(h2));
  lc.setRow(0,4,byte(m1));
  lc.setRow(0,3,byte(m2));
  lc.setRow(0,1,byte(s1));
  lc.setRow(0,0,byte(s2));
  }

  int n1(int num) {  // Function to isolate first digit of 2-digit integer
    num = num / 10; //Integer division by 10 (discard remainder)
    return num;
  }

  int n2(int num) {  // Function to isolate second digit of 2-digit integer
    num = num % 10; //Modulo division by 10 (keep remainder only)
    return num;
  }


texts: Understanding memory fragmentation due to char arrays in functions

texts:
This is similar to:
Is this function subject to memory fragmentation?

I am trying to get my head around Memory fragmentation in Arduino's and embedded systems in general.

Currently I have a function in a __lcdAux__ Class which is responsible for doing basic operation on the lcd.
One of the members of the class is a char array double2StrBuff1 which is used with __dtostrf()__ to create a double which is then passed to sprintf. So the following function (__lcdAux::UpdatePosition__) is responsible for updating the position on the lcd.

void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

Currently, I am under the impression that by defining once the class as a global variable and then using it throughout the program, then the char array is allocated only once memory space. Therefore by using it afterwards no memory fragmentation occurs.

However, I read that functions allocate space on the stack which is immediately recoved when the function is exited. Therefore I am curious if the following declaration is any different in terms of memory fragmentation.

void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
    lcd->setCursor(0, 2);
    char double2StrBuff1[10];
    dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
    sprintf(lcdBuff, "X: %s", double2StrBuff1);
    lcd->print(lcdBuff);
}

To sum up:

by putting  the declaration for variable __char double2StrBuff1[10];__  inside the function, is the memory allocated from the stack and therefore recovered upon exiting the function (therefore there is no need to declarate a member variable on the class level),

OR

is the fact that __double2StrBuff1__ is a pointer means that the pointer is allocated in the stack but the values are located in the heap (therefore what I am doing makes sense)?

PS: Because some might point out that  __"X: %s"__ is worse in terms of memory usage and fragmentation, I'll state the following. Instead of the format string __"X:%s"__ I use a _PROGMEM const char_ array and __strcpy_P()_, but to simplify the question I replaced it with the literal string , since I feel that is another problem.


texts: How might the SD library be reading phantom files?

texts:
I have the Sparkfun CAN Bus shield with integrated SD card writer attached to an Arduino Mega 2560. I can delete a logged file from the SD card using Windows, log more data using the SD library, then look at the logged data in, say, Excel. The new log file will include the logged data from the old, deleted file.

The card is formatted in Windows in FAT32 and the logged file has the same name as the original. It seems like the SD card reader/SD library is able to 'recover' the deleted file by name, open it for writing having read its uncorrupted contents, and continue logging to it, despite it having been 'deleted' in Windows. I know a deleted file doesn't get rid of the data unless it is overwritten, but there seems to be some bug/oversight in how the SD library in card reader or how it interrogates the SD card or FAT32 volume for the existence of the file.

Has anyone come across this before? Is it a bug or am I doing something wrong?


texts: Distance Readings Getting Manipulated When Calling Unrelated Function

texts:
I'm using a Lidar Lite v3 to measure the distance from one object to another. I pass the results to the serial monitor to see what that distance is. It appears that when I call an unrelated function, the distance that's being printed seems to be roughly subtracted by 512.

To describe exactly what I mean, this is my function:

int pulseWidth = pulseIn(monitorPin, HIGH); //begin measurement of time
int distanceConverted = (pulseWidth / 10); // 10usec = 1 cm of distance
Serial.println(distanceConverted); // Print the distance

and it gives me an output of this (which is correct):

780 cm
787 cm
790 cm
794 cm
782 cm
787 cm
790 cm
786 cm
790 cm
780 cm
788 cm
784 cm

I'm using these distances to control LED lights and a speaker, and call this function to do so:

void lights(int distanceConverted)
{
    if (distanceConverted < 1000 && distanceConverted > 500)
    {
      digitalWrite(yellowLEDPin, HIGH);
      delay(20);
      tone(8, 35000, 250);
    }

    else if (distanceConverted <= 500)
    {
      digitalWrite(redLEDPin, HIGH);
      delay(20);
      tone(8, 40000, 250);
    }
}

However, when this is called (and I call the function after I print the distance values), these are the results I get:

268 cm
267 cm
266 cm
267 cm
269 cm
267 cm
265 cm
267 cm
266 cm
266 cm
267 cm
264 cm
269 cm

When I try to account for this and multiply by three, my values become even more off and seem to be multiplied by ten:

int distanceConverted = (pulseWidth / 10)*3; // 10usec = 1 cm of distance

New Values:
2640 cm
2673 cm
2634 cm
2649 cm
2592 cm
2619 cm
2631 cm
2628 cm
2631 cm
2673 cm
2634 cm

At first I thought it might have been the delays within the lights() function manipulating the readings, but even after commenting them out I still get the same results. I don't know how the function could be throwing my values off.

Edit: I noticed at when the program is first looping, the 512 gets subtracted after the first time I run through the lights() function.

761 cm <- first value from sensor, correct
312 cm
308 cm
308 cm
309 cm
308 cm
307 cm
307 cm
309 cm
308 cm
308 cm

When I comment out the tone() function, that seems to fix my problem. Could that function be overwriting a bit in the memory register causing it to subtract 512 from my distanceConverted variable?


texts: How to send messages to multiple numbers using Arduino uno & SIM800 module?

texts:
I am using following code to send message using Arduino Uno & SIM800 module.
But I need to send same message on multiple numbers then what changes should I make in my code.

const int buttonPin = 8;   // Main gate sensor 1
const int buttonPin1 = 7;  // Main gate sensor 2
const int buttonPin2 = 9;  // Store room sensor 1
const int buttonPin3 = 10; // Store room sensor 2

bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(buttonPin, INPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  digitalWrite(buttonPin, LOW);
  digitalWrite(buttonPin1, LOW);
  digitalWrite(buttonPin2, LOW);
  digitalWrite(buttonPin3, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
  void sensor1()
  {
  if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91...................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is Closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }

  if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91........................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
  }
  void sensor2()
  {
  if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}


texts:
I have googled all around and I know about some tricks to make ATmega328 not being a power hog. I am using Arduino Nano V3.0.

However, I didn't find out what is the minimal consumption possible with it?

My project consists of an Arduino that will wake up each 10 seconds and, by bluetooth (BT) will scan for existing devices, and if one specific device is not listed, it will lit a LED for 5 seconds and then go to sleep again.

In sum:

Sleep for 10 secs
Wake up
Scan for BT devices
If device ABC is in the list go to 1.
Lit LED
Delay 5 secs
Go to 1.

For bluetooth I will use NRF8001, because it is the most efficient BT module I know so far.

Can you give me some ideas of what tricks should I use to make this ATmega328 and BT module last like one year with a 500mAh battery? Has anyone tried this that can share his experience? Is ATmega328 the right uC for this? I am using it just because I already have code/libraries for it.

  Creating the new tag 'nrf8001' requires at least 150 reputation. Try something from the existing tags list instead.


texts: Seamlessly loop through LED's - Shift Register

texts:
I am using the following code to create a snake-like affect (3 LED's wide) moving through 24 LED's using 3 shift registers:

 for(int i = 0; i < 27; i++){
    setRegisterPin(i, HIGH);
    writeRegisters();
    if(i >= 3){
     setRegisterPin(i-LEDLength, LOW);
     writeRegisters();
    }
    delay(100);
  }//end for

The problem with this is that the snake has to completely end before it starts again, instead of looking like one continuous snake going in circles.

So when the three LED's get to the end I want it to immediately begin to light the beginning again. If 2 are lit at the end then 1 should be lit at the start, etc. Like this pattern:


texts: Powering an Arduino directly from a motor driver (DRV8825) or external power source?

texts:
Hello people from StackExchange,

I'm new to Arduino and driving stepper motors in general; please excuse me for my limited knowledge on the subject. I've been doing research for a few hours already, looking into powering stepper motors and the Arduino, though I've gotten conflicting information regarding my problem.

My problem, or well question if you will, is as follows:
The circuit I need, simplified, contains an Arduino, a stepper motor driver (DRV8825), a NEMA17 5kg.cm stepper motor and a 12V battery pack (yet to be decided what kind of pack, though it will be 12V). Do I need another, lower voltage, battery pack?

After looking into how to power stepper motors using the Arduino online, I found several sites instructing me how to do so. All of the sites had the same circuit I would use, only the motor was different. Here is one of the circuits:

As you can see, it only has a single power supply (with capacitor to catch voltage peaks). I understand most of the circuit, though one question remains: why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver? (You can see the pin descriptions in the second image below) Or do they simply not show the (5v) power supply for the Arduino?

The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not? And if not, would connecting the Arduino to the power supply via the VIN pin work? That would be nice, as it would offer a simple way of fixing the problem instead of getting a separate power source. Connecting the Arduino through USB wouldn't work for my project, as it can't have any wires coming from it. It needs to be completely mobile.

For comparison, here is a circuit that does show the Arduino with an external power source:

I'm a first years mechanical engineering student, hence my little knowledge on Arduino's and stepper motors.

Thanks in advance.


texts: Arduino serial port reset in Serial monitor & Python

texts:
So am I using an Arduino with a shield to gain some voltage values for an ECG. I am then plotting that data in Python. However whenever I "observe" the serial port, be that through the Arduino serial monitor or in attempting to plot the values of time (using millis()) against ECG (voltage) the values reset, so millis() resets the zero, which is fine, except that some of the older values still show up. Now this is especially a problem in Python because it means the plot is malfunctioning at the start of the script, because it is plotting some of the older values and then after a couple of seconds it resets and the plot looks normal again.

To demonstrate this I have recorded it on video and put it on YouTube, here it is:

https://www.youtube.com/watch?v=dNpUakcRPec

Now initially I thought the problem was with Python or the Pyserial module so I labelled the video as such, but since it occurs in the serial monitor I realised the solution would be in the Arduino sketch. I have tried flushing, didn't work, I have tried even to not start the data till I send a start byte, but this didn't work on Python.

Ideally I could start the Python plotting script and it would skip, or ignore those initial values from the serial port before beginning again.

Here is the Arduino sketch I am using:

#include <eHealth.h>

unsigned long time;
// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);

}

// The loop routine runs over and over again forever:
void loop() {

  float ECG = eHealth.getECG();
  time = millis();
  Serial.print(time);
  Serial.print(" ");
  Serial.print(ECG, 3);
  Serial.println("");

  delay(50);    // wait for 50 millisecond
}


texts:
I'm trying to connect WiFi at home in my esp32 but in the serial monitor shows a looping connecting to WiFi but never connect. look this
The link that I followed.
To my application. I want to connect a DHT11 sensor and to communicated with node-red. Unfortunately, My esp32 doesn't connect with WiFi.
    // Projeto Curto Circuito – ESP32: DHT11 Teste
#include <WiFi.h>
#include "DHT.h" // Inclui a biblioteca DHT
#define DHTPIN 14 // Define que OUT será conectado em D14
#define DHTTYPE DHT11 // Define o modelo de sensor como DHT 22  // DHT irá interpretar os valores de leitura do pino de acordo com o tipo de sensor
DHT dht(DHTPIN, DHTTYPE);
char* ssid = "Filipe";
const char* password =  "1234512345";
void setup()
{

 Serial.begin(9600); // Taxa de transmissão 9600 dBs
WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 dht.begin(); // Taxa de transmissão do sensor

}
 void loop()
{
 delay(2000); // Intervalo de 2 segundos entre as leituras // Indica a Umidade (%)
 float h = dht.readHumidity();
 float t = dht.readTemperature();
 Serial.print("Umidade: ");
 Serial.print(h);
 Serial.println(" %\t");
 Serial.println("");
 Serial.print("Temperatura: ");
 Serial.print(t);
 Serial.println(" *C ");
  Serial.println("");
}

I hope somebody can help me.
I'll be so glad with your contribution.


texts:
I want to use a proto shield (brand is unimportant) and solder some components to it, to make something more premanent than using a breadboard.

My question is can the components be soldered directly to the middle area where there are a lot of small holes?

I would assume this is possible, but everywhere I look people add mini breadboards to their proto shields.

If it's possible, then I assume components and wires can't just be connected in a row like on a breadboard and would instead need some solder between 2 holes where for example a component and seperate wire are connected?


texts: Global variable changes its value when loop starts again

texts:
I have a problem with the global variable calibrationValue. It is initially set with the correct value and is also displayed correctly in the output. As soon as the loop function is restarted, the value of the variable is wrong, although it is not rewritten. Can someone help me please?
The following values are printed in the image:

new AI value
wrong calibrationValue (!)
sumOfValues (needed for calculation of calibrationValue) correct
numValues (needed for calculation of calibrationValue) correct
Text and calibrationValue (correct!)

    int op_mode_Pin = 7;                      // Digital input Pin which transmittes the op_mode_Ardui
    int op_mode_Ardui;                        // Operator Mode of Arduino
    int returnValue1 = 12;                    // First digital return value for transmitting box weight
    int returnValue2 = 13;                    // Second digital return value for transmitting box weight

    int sensorPin = A0;                       // Select the input pin for the potentiometer
    long weightValue = 0;                     // Variable to store the value from the sensor
    long calibrationValue = 0;                // Value which is filled in calibration progress
    int numValues = 50;                       // Number of taken values for calculating an average
    int thresBoxWeight = 300;                 // Weight for separating heavy and light boxes

    unsigned long sumOfValues;                // Sum of the taken values
    unsigned long aveOfValues;                // Average of the values

    char stringBuffer[30];                    // Buffer for combining string and variables

    void setup() {
      // Initiate serial communication to screen
      Serial.begin(9600);

      // Initiate some variables
      //weightValue = 0;
      //calibrationValue = 0;
      //numValues = 50;
      //thresBoxWeight = 300;

      // Set the Input Pins for op_mode_Ardui
      pinMode(op_mode_Pin, INPUT);            // sets the digital pin 7 as input

      // Set the Output Pins for Box declaration
      pinMode(returnValue1, OUTPUT);          // sets the digital pin 12 as output
      pinMode(returnValue2, OUTPUT);          // sets the digital pin 13 as output

    }

    void loop() {
      Serial.println(analogRead(sensorPin));
      Serial.println(calibrationValue);
      // Reset of Sum and Average variables for next cycle
      sumOfValues = 0;
      aveOfValues = 0;
      op_mode_Ardui = digitalRead(op_mode_Pin);

      if (op_mode_Ardui == HIGH){
        for (int i=0; i<numValues; i++){
          weightValue = analogRead(sensorPin);                                                  // read the value from the sensor
          sumOfValues = sumOfValues + weightValue;                                              // Build the sum of all values
        }
        Serial.println(sumOfValues);
        Serial.println(numValues);

        calibrationValue = sumOfValues / numValues;
        sprintf(stringBuffer, "Calibration accomplished with value: %d", calibrationValue);     // Combine text and variable to output
        Serial.println(stringBuffer);                                                           // print text and variable to screen
        delay(3000);
      }
    }


texts:
I have a problem. I am making an autonomous (obstacle avoiding) firefighting firetruck. I already have a code however it only stops when it detects fire and when the ultrasonic reaches less than 15cm, the flame sensor automatically detects fire even there is no fire near the sensor. I get my code form different tutorials.

Here it is:

#include <Servo.h>
#include "Ultrasonic.h"

//Constants
const int button = 2;
const int led    = 3;
const int pump = 4;
const int motorA1= 6;
const int motorA2= 9;
const int motorB1=10;
const int motorB2=11;
const int flame=12;
const int buzzer=12;

Ultrasonic ultrasonic(A4 ,A5);
Servo myservo;

//Variables
int distance;
int checkRight;
int checkLeft;
int function=0;
int buttonState=0;
int pos=90;
int flag=0;
int flame_detected;

void setup()
{
 Serial.begin(9600);
   myservo.attach(5);
   myservo.write(pos);
 pinMode(button, INPUT_PULLUP);
 pinMode(led,  OUTPUT);
 pinMode(buzzer, OUTPUT);
 pinMode(motorA1,OUTPUT);
 pinMode(motorA2,OUTPUT);
 pinMode(motorB1,OUTPUT);
 pinMode(motorB2,OUTPUT);
 pinMode(flame,INPUT);
 pinMode(pump,OUTPUT);

}

void loop()
{
 flame_detected = digitalRead(flame);
 if (flame_detected == true)
 {
   Serial.println("No flame detected. stay cool");
 //Check button state
 buttonState = digitalRead(button);
 unsigned long currentMillis = millis();

   if (buttonState == LOW) {
     delay(500);
     if ( flag == 0){
         function = 1;
         flag=1;
     }
     else if ( flag == 1){
       function = 0;
       flag=0;
     }
   }

 if (function == 0){
   myservo.write(90);
   stop();
   noTone(buzzer);
   digitalWrite(led, HIGH);

 }
 else if (function == 1){
   //Read distance...
   distance = ultrasonic.Ranging(CM);

   if (distance > 15){
     forward();
     noTone(buzzer);
     digitalWrite(led,LOW);
   }
   else if (distance <=15){
     stop();
     tone(buzzer,500);
     digitalWrite(led,HIGH);

     for(pos = 0; pos < 180; pos += 1){
               myservo.write(pos);
               delay(10);
           }

           checkLeft = ultrasonic.Ranging(CM);

           for(pos = 180; pos>=0; pos-=1){
               myservo.write(pos);
               delay(10);
           }

           checkRight= ultrasonic.Ranging(CM);

           myservo.write(90);

           if (checkLeft < checkRight){
             left();
             delay(400);
             }
           else if (checkLeft > checkRight){
             right();
             delay(400);
           }
           else if (checkLeft <=10 && checkRight <=10){
             backward();
             left();
           }
   }
 }

}

else {
 put_off_fire();
 Serial.println("Flame detected...! take action immediately.");
}
delay(500);
}
void forward(){
 digitalWrite(motorA1, HIGH);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, HIGH);
 digitalWrite(motorB2, LOW);
}

void backward(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, HIGH);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, HIGH);
}

void left(){
 digitalWrite(motorA1, HIGH);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, HIGH);
}

void right(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, HIGH);
 digitalWrite(motorB1, HIGH);
 digitalWrite(motorB2, LOW);
}

void stop(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, LOW);
}

void put_off_fire()
{
 {
   delay (500);

   digitalWrite(motorA1, HIGH);
   digitalWrite(motorA2, HIGH);
   digitalWrite(motorB1, HIGH);
   digitalWrite(motorB2, HIGH);

  digitalWrite(pump, HIGH);
  delay(500);
 }
 digitalWrite(pump,LOW);
 flame_detected=false;
}

I really need help. Thanks


texts: Read sd card content(text files) and display it on lcdi2c

texts:
i am working for a project based on lifi using arduino and i need to diplay content of sd card to lcd i tried a lot some online programs also i tried but there is a simple blank screen. one of the code i used is this:
CODE:
#include <SD.h>
#include <SPI.h>

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7);

File myFile;
const int CSpin = 10;

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

  lcd.begin(20,4);
  lcd.setBacklightPin(3, POSITIVE);
  lcd.setBacklight(HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  lcd.setCursor(0,0);
  ReadLine();
  myFile.close();
}

void ReadLine(){
  myFile = SD.open("Sample.txt", FILE_READ);
  myFile.seek(0);
  char cr;
  for(unsigned int i = 0; i < (3 - 1);){
    cr = myFile.read();
    if(cr == '\n')
      {
        i++;
      }
  }

  while(true){
    cr = myFile.read();
    Serial.write(cr);

    if(cr == '\n'){
      break;
    }
    //here...
    else if(cr >= 0x20 && cr <= 0x7E){
      lcd.print(cr);
    }

  }
}

displays blank screen
Please help me out!! Any other working program also would work.!! Thanks in advance.


texts:
I'm working on the Adafruit Firewalker shoes.

I can't make my code compile to test my flora project.

This is my error message:

Arduino: 1.6.7 (Windows 10), Board: "Adafruit Flora"

C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel: No such file or directory

 #include <Adafruit_NeoPixel>

                             ^

compilation terminated.

exit status 1
Error compiling.

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

https://learn.adafruit.com/firewalker-led-sneakers/test-circuit

    #include <Adafruit_NeoPixel.h>

const int analogInPin = A9;  // Analog input pin that the potentiometer is attached to
Adafruit_NeoPixel strip = Adafruit_NeoPixel(10, 6, NEO_GRB + NEO_KHZ800);
int sensorValue = 0;        // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
 pinMode(9, INPUT_PULLUP);
   strip.begin();
  strip.show(); // Initialize all pixels to 'off'

}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // print the results to the serial monitor:
  Serial.print("sensor = " );
  Serial.println(sensorValue);

if (sensorValue < 100){
  Serial.println("leds triggered");
colorWipe(strip.Color(255, 0, 0), 25);
colorWipe(strip.Color(0, 0, 0), 25);
}

}

void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
}


texts: Difference between print() and println()

texts:
What is the difference between print( ) and println( )?
I see none when I run a code.


texts: AutoConnect module does not broadcast SSID on ESP32 Dev Board

texts:
This is my first post so I apologize if I'm missing all required info about my Arduino setup.  I'm a little new to this type of development.

Arduino 1.8.9

ESP32 Dev Module on /dev/cu.SLAB_USBtoUART

Mac OSX High Sierra 10.13.

I'm using the AutoConnect by Hieromon Ikasama v1.1.3 library to create an access point (AP), but the SSID (network name) is not being broadcasted even with the simplest code example.

Why isn't "ESP-78e9" showing up in my network list on my MAC or iPhone?

⸮⸮⸮8Y8⸮
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[E][Preferences.cpp:38] begin(): nvs_open failed: NOT_FOUND
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.192, MASK: 255.255.255.0, GW: 192.168.1.1
WiFi connected: 192.168.1.192 on ESP-78e9

Full code sample below, written with the Arduino IDE

#include <WiFi.h>
#include <WebServer.h>
#include <AutoConnect.h>

WebServer         Server;
AutoConnect       Portal(Server);
AutoConnectConfig Config;

void rootPage() {
  char content[] = "Hello, world";
  Server.send(200, "text/plain", content);
}

void setup() {

  Config.apid = "ESP-" + String((uint32_t)(ESP.getEfuseMac() >> 32), HEX);
  Config.psk = "Password1";
  Portal.config(Config);

  delay(5000);
  Serial.begin(9600);
  Serial.println();

  Server.on("/", rootPage);
  if (Portal.begin()) {
    // Serial.println("WiFi connected: " + WiFi.localIP().toString());
    Serial.println("WiFi connected: " + WiFi.localIP().toString() + " on " + Config.apid);
  }
}

void loop() {
    Portal.handleClient();
}

I've tried looking into why "nvs_open failed: NOT_FOUND" is occurring as that feels like the next step, but can't find any information on how to fix it.

I've also tried this on two boards of the same model.

Any ideas?

** Update **
I've modified the code to include the following, but still no AP and captive portal.

https://hieromon.github.io/AutoConnect/advancedusage.html#on-demand-start-the-captive-portal

According to the link above, that SHOULD start a captive portal before attempting to connect to WiFi.

  Config.autoRise = false;
  Config.immediateStart = true;

Instead I get the debug text here:

[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 14 - AP_STOP
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START

Update 2

There may be a bug in the documentation.  I changed "autoRise" to true and the SSID was broadcasted.

  Config.autoRise = true;
  Config.immediateStart = true;


texts: I control an analog circuit with Arduino Uno. I want to simulate an Arduino Uno with operational amplifiers (741). Can I simulate Arduino with SPICE?


texts:
I will be brief. There is as windows PC running a program. This program has live updating data on it. Without modifying the PC or adding any programs to the PC, is it possible to program an Arduino to read specific data from this program. In other words the Arduino would be connected to the PC via a USB port and it would need to actively read specific data from this program without having to modify the PC in any way, software or otherwise. I do have access to the PC and can learn almost anything I need to about the program during the development of this system, however in practice, I need the Arduino to simply be plugged into this PC and begin reading its data. Is this possible?  I am not asking for a tutorial however if you could point me in the right direction that would be great.
Thanks


texts: Where is the Arduino IDE log file located? Not the Serial Monitor

texts:
"An error ocurred while uploading the sketch"
I'm having this specific error when uploading a sketch to my board and the IDE doesn't specify the problem correctly.
It's version is 1.8.13 for Windows 10.
I would like to get a file with detailed information about the IDE's error. Where should I look for it?


texts: What are the main differences between Arduino and mbed?

texts:
I have been working a lot with the Arduino platform over the last year. Arduino makes it very easy for beginners (in my opinion) to get started and has a large community and a lot of libraries for all kinds of peripherals.

Now, I am considering to have a look at mbed, too.
What are the main differences I would face, both practical and conceptually?


texts: How Atmel Studio 7 compile Arduino code?

texts:
Atmel stated in their website:

  Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.

I wonder how they do it? Is it just a plug-in meaning that we still have to install Arduino software? Or do they have their own compiler and debugger?


texts:
I am implementing an FIR filter using Arduino. I am using an input signal as an audio signal. The audio signal has a duration of 3 seconds with total samples, 66150. What I am doing is reading this file in python and storing the data in an array. Using Serial, I want to send this sampled data to Arduino serial and process it, then send it back to serial and receive in  Python.

Python Code

import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile # get the api
import serial, time

samplerate, data = wavfile.read("sample.wav")
samples = len(data)
plt.plot(data[:20000])
arduino = serial.Serial('COM4', 9600, timeout=.1)
time.sleep(1) #give the connection a second to settle

for i in range(0,samples):

    arduino.write(data[i])
    time.sleep(1)
    print(arduino.readline())

Arduino Code

  void setup() {

  Serial.begin(9600);
  }
  int i = 0;
  int newdata[10];
  void loop() {
     if(Serial.available() > 0) {
          int data = Serial.read();
          newdata[i] = data;
          Serial.print(newdata[i]);
          i = i+1;
        }
   }

The problem I am facing is that I am stuck at very first step. As a check, I sent 10 samples values at start from Python to arduino using a loop and tried to recover them back to read on Python console. These values were not correct. When I entered a string inside the arduino.write(), it was receiving but when I input a variable inside the arduino.write(), it doesn't print that value after transferring back to python.
I just tried many things like changing to string but I didn't get the desired result. The output for this code is attached. Tomorrow is my submission and I am stuck in this thing. Help will be highly appreciated.


texts: Compilling error not highlighting line in code

texts: A newbe here. How come when I compile with an error I do not get the line or line number highlighted? I Get the errors just can't find where they are.


texts: seperate ATmega 2560 - turn on a single LED - troubleshooting

texts:
I have got my own PCB with "some stuff" on it and first I want to make it run a simple "turn on LED".

My setup:

Atmega 2560
LED connected to PE4 (D2 in Arduino language) => PE4 - LED - 1K resistor - 5V
ceramic resonator (CSTCE16M0V53-R0 16MHZ) connected to XTAL1 + XTAL2 with 1MOhm resistor inbetween
all VINs are pulled to GND with capacitors

Upload is working through ICSP (MISO, MOSI, SCK, RESET, 5V, GND) with an USBasp

Here is my Arduino sketch, which I upload through the Arduino software:

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

void loop() {
  digitalWrite(2, LOW);
}

I checked the fuses on the atmega as well:

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (H:FD, E:D8, L:FF)

avrdude uploads successfully: (output truncated!)

avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.01s
avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: writing flash (1518 bytes):
Writing | ################################################## | 100% 5.47s
avrdude: 1518 bytes of flash written
avrdude: reading on-chip flash data:
Reading | ################################################## | 100% 3.45s
avrdude: verifying ...
avrdude: 1518 bytes of flash verified

avrdude done.  Thank you.

Problem: the LED doesn't work. It is OFF all the time.

Any ideas why it is not working?

Cheers
Hendrik


texts: Serial Communication between 2 Arduinos for analogRead value

texts:
I have an optical sensor connected to A0 on Arduino #1 (Nano) giving me values from 200 to 1010. I need to receive these values in Arduino #2 (Nano) through serial communication. I have used a simple code for sending and receiving bytes, but I don't understand how to get the actual sensor values as int. I found some examples showing single values, but as far as I can understand variable values are more complex.

Transmitter Code:

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

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
}

Receiver Code:

void setup() {
        Serial.begin(9600);
}
void loop() {
        if (Serial.available() > 0) {
        int incomingByte = Serial.read();
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
        }
}


texts: Can a 9V battery be used as a backup power supply (to Arduino Uno) while plugged directly into Vin and ground?

texts:
Sorry if this has been asked before, but I've read tons of threads and it seems the answer is only implied on a couple of occasions.

I'm an electrical noob, but I understand that a 9v battery plugged into a wall wort with a diode would serve as a battery backup if the power was cut from the wall wort.  I also understand that Vin on an arduino already has a diode to do this.

I'm currently powering a temp/humidity that is dumping data into MySQL using a standard A-B USB cable and 5V DC USB power supply.  I'd like to incorporate a 9V battery plugged into Vin and ground, so that if DC power turns off, I can dump the data onto the SD card instead (since my MySQL server may or not be running during an outage).


texts:
Im trying to understand how the Arduino ISR keeps track of timing between pulses stored in a variable, if that variable is latter used.

Say, for example, you have a magnet mounted on a circular object, that passes a reed switch. Using this to trigger the ISR that calls a function that would have something like counts++ in it, then storing that value in a variable.

If that varible is used latter to turn on a motor, for example, according to the count capture, how does the arduino MCU know the freq or timing to output the count or pulses of the magnet passing the reed switch, at the same frequency that the counts were received? For example, a magnet mounted on a 2 inch dia shaft would turn slower past a reed switch than one mounted on a .5 inch shaft, or one could vary the speed of the magnet past the reed as they wish. So how does counter++ keep track of this freq? is it reading the attachinterupt pin (or is the function that is being called, keeping track) or does the ISR time stamp each pulse it receives and store that interval in the declared variable? so when the variable is used again, it has this interval stored in it?

To be more clear, if it takes one second for the magnet to complete one revolution, how does the MCU know it took one second and store this, along with the counts of the revolutions?

Thanks for any help


texts:
Im newbie. I just wanted to ask how can i put my tmrpcm.play into loop. Im trying to put it in a loop but the problem is it didn't play. I also try adding a method and call the method into the loop but it give me the same problem also. It will just only play in the void setup.

Here's my code.

#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

void setup(){
tmrpcm.speakerPin = 9;
Serial.begin(9600);
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}

tmrpcm.setVolume(5);
tmrpcm.play("Yeah.wav");
}

void loop(){  }


texts:
I have the following problem and wonder if anyone may have some inside into what may be happening.

I have an array of 20 leds that i manage to multiplex using the attiny88 using only 9 pins (4 columns by 5 rows). At any given time only one led is on. The different leds are activated with a pushbutton. Initially, i used five transistors with a 1k resistor to turn on and off the rows of the led array.

Everything worked like a charm even at voltages as low as 2.5 vol. I then decided to remove the transistors to free-up some space in my pcb. Now the circuit works well at voltages above four but at 2.5v it makes leds to turn on randomly, when pressing the pushbutton.

I presume this behavior is because the one led is taking to much current, but i wonder why could be the case if the chip is only driving one led at a time. Also keep in mind that the circuit works very well at 4vol.

Any clue about this and how could i fix it? I like the idea of not using the transistors.


texts:
I was using my MLX90614 IRTherm sensor flawless and bought two more. I have connected two sensors serial with pull-ups to SDA --> A4 and SCL --> A5. After digging the internet I found out that I should change their default slave addresses to different addresses so that Arduino can recognize their 7-bit slave addresses.
After changing their address, now I can't read either two new serial MLX'es or my old MLX.

I might have messed up with their addresses and don't know how to
reset their addresses.
How can i connect multiple sensors/ how can i change their adress properly?

  reading sensor data

#include <Wire.h> // I2C library, required for MLX90614
#include <SparkFunMLX90614.h> // SparkFunMLX90614 Arduino library

IRTherm therm; // Create an IRTherm object to interact with throughout

const byte LED_PIN = 8; // Optional LED attached to pin 8 (active low)

void setup()
{
  Serial.begin(9600); // Initialize Serial to log output
  therm.begin(0x5A); // Initialize thermal IR sensor
  therm.setUnit(TEMP_F); // Set the library's units to Farenheit
  // Alternatively, TEMP_F can be replaced with TEMP_C for Celsius or
  // TEMP_K for Kelvin.

  pinMode(LED_PIN, OUTPUT); // LED pin as output
  setLED(LOW); // LED OFF
}

void loop()
{
  setLED(HIGH); //LED on

  // Call therm.read() to read object and ambient temperatures from the sensor.
  if (therm.read()) // On success, read() will return 1, on fail 0.
  {
    // Use the object() and ambient() functions to grab the object and ambient
    // temperatures.
    // They'll be floats, calculated out to the unit you set with setUnit().
    Serial.print("Object: " + String(therm.object(), 2));
    Serial.write('°'); // Degree Symbol
    Serial.println("F");
    Serial.print("Ambient: " + String(therm.ambient(), 2));
    Serial.write('°'); // Degree Symbol
    Serial.println("F");
    Serial.println();
  }
  setLED(LOW);
  delay(500);
}

void setLED(bool on)
{
  if (on)
    digitalWrite(LED_PIN, LOW);
  else
    digitalWrite(LED_PIN, HIGH);
}

  Setting address

#include <Wire.h> // I2C library, required for MLX90614
#include <SparkFunMLX90614.h> // SparkFunMLX90614 Arduino library

IRTherm therm; // Create an IRTherm object to interact with throughout

const byte oldAddress = 0x5A;
const byte newAddress = 0x5B;

void setup()
{
  Serial.begin(9600); // Initialize Serial to log output
  Serial.println("Press a key to begin");
  while (!Serial.available()) ;

  therm.begin(oldAddress); // Try using the old address first

  byte address;
  if (!therm.readID()) // Try reading the ID registers
  {
    // If the read fails, try re-initializing with the
    // new address. Maybe we've already set it.
    therm.begin(newAddress);

    if (therm.readID()) // Read from the ID registers
    { // If the read succeeded, print the ID:
      Serial.println("Communicated with new address.");
      Serial.println("ID: 0x" +
                     String(therm.getIDH(), HEX) +
                     String(therm.getIDL(), HEX));
    }
    else
    {
      Serial.println("Failed to communicate with either address.");
    }
  }
  else
  {
    // If the read suceeds, change the address to something
    // new.
    if (!therm.setAddress(newAddress))
    {
      Serial.println("Failed to set new address.");
    }
    else
    {
      Serial.println("Set the address to 0x" + String(newAddress, HEX));
      Serial.println("Cycle power to try it out.");
    }
  }
}

void loop()
{

}

Edit 1:
Datasheet


texts:
Maybe is to easy to answer but i don't know it. I know IEEE-754 is for float values and double but i don't know if is exclusive for those type.

I use this to convert float and works fine i have another code in javascript to revert it.
But when used it with integer values it just gives some values and the revert doesn't work as supposed to.

So, this definitely doesn't work for integer values?, i can parse it to float and pass it to IEE754 but i just want to know.

this is the code i use in arduino.

void IEEE754( float val, int pos)
{
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}

also, does anyone has the revert code for arduino?..


texts: How to have code/sketch that's easily toggleable to work on different nodes

texts:
i have a question about best practice to achieve what i want to do. I would like to have a sketch setup, and then to be able to deploy to different devices of the same type, but each device/node will have a few different parameters, like ip address and mqtt topic etc,

What would be the quickest way to be able to upload new changes to all of my nodes without having to track my changes and update each seperate sketch for each node?

I was thinking about using some IFDEF statements if i can figure out how to? would that be the best way to go or is there something better?

Thx in advance


texts: Simon Says Project - Can't go from random lights to user input

texts:
I'm new to using an Arduino and I am attempting the Simon Says game. Right now, I do not understand why my program will not go from activating the random lights to the user input. Currently it is flashing all the lights three times like I want it to, but then it will flash three random lights and then go straight to flashing every light, right to left (which is the indicator that the wrong button was pushed).

I am working in Tinkercad/circuits.io and have had the physical implementation looked at, and it is good. I just can't figure out the code. Anything will help, thanks!

// Defining LEDs and buttons.
int leds[] = {12, 10, 7, 4};
int buttons[] = {11, 9, 6, 3};

const int max = 40;
int lightArr[max]; // Array with full patterns of LEDs.
int currArr[max];
int gameState = 0;
int level = 1;
int count = 0; // Counter for every sequence of iterating over the
random array of ints (LEDs).
int buttonPressed = -1;
int correct = 1;

void setup() {
  pinMode(leds[0], OUTPUT);
  pinMode(leds[1], OUTPUT);
  pinMode(leds[2], OUTPUT);
  pinMode(leds[3], OUTPUT);
  pinMode(buttons[0], INPUT);
  pinMode(buttons[1], INPUT);
  pinMode(buttons[2], INPUT);
  pinMode(buttons[3], INPUT);
  randomSeed(analogRead(0));
  allOn();
}

void loop() {
  if (gameState == 0) {
    resetGame();
  } else if (gameState == 1) {
    play();
  } else if (gameState == 2) {
    gameOver();
  }
}

void resetGame() {
  if (level == 1) {
  // Setting up a sequence of random lights.
    for (int i = 0; i < 40; i++) {
      lightArr[i] = random(0,4);
    }
  }
  level = 1;
  gameState = 1;
}

void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

void showPattern() {
  for (int i = 0; i < level; i++) {
    delay(500);
    digitalWrite(leds[lightArr[i]], 1);
    delay(500);
    digitalWrite(leds[lightArr[i]], 0);
    delay(500);
  }
}

int userInput() {
  for (int i = 0; i < level; i++) {
    int buttonPressed = readOneButton();
    digitalWrite(leds[buttonPressed], 1);
    delay(500);
    digitalWrite(leds[buttonPressed], 0);
    delay(500);
    if (lightArr[i] != buttonPressed) {
      // User button pressed.
      gameState = 2;
      correct = 0;
    }
  }
}

void gameOver() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    delay(150);
    digitalWrite(leds[0], 0);
    delay(150);
    digitalWrite(leds[1], 1);
    delay(150);
    digitalWrite(leds[1], 0);
    delay(150);
    digitalWrite(leds[2], 1);
    delay(150);
    digitalWrite(leds[2], 0);
    delay(150);
    digitalWrite(leds[3], 1);
    delay(150);
    digitalWrite(leds[3], 0);
    delay(150);
  }
  gameState = 0;
}

int readOneButton() {
  if (digitalRead(buttons[0])) {
    return 0; // Button: Red
  } else if (digitalRead(buttons[1])) {
    return 1; // Button: Green
  } else if (digitalRead(buttons[2])) {
    return 2; // Button: Blue
  } else if (digitalRead(buttons[3])) {
    return 3; // Button: Yellow
  }
}

void allOn() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    digitalWrite(leds[1], 1);
    digitalWrite(leds[2], 1);
    digitalWrite(leds[3], 1);
    delay(500);
    digitalWrite(leds[0], 0);
    digitalWrite(leds[1], 0);
    digitalWrite(leds[2], 0);
    digitalWrite(leds[3], 0);
    delay(500);
  }
}


texts: Passing the input from one pin to another as output without polling?

texts:
I am trying to pass the input from one pin to another pin as output. Effectively I want to create a blind passthrough. The end goal is to connect two Arduinos and a series of test points together like the diagram below. I want Arduino B to shuffle which test points are connected to which pins on Arduino A on startup.

+-----------+       +-----------+     +-------------+
|           |       |           |     |             |
| Arduino A <-------> Arduino B <-----> Test Points |
|           |       |           |     |             |
+-----------+       +-----------+     +-------------+

I figure one way to do this is to poll the input pins in the loop() and then change the output pins accordingly but I would prefer if the voltage changes just passed right through without it affecting timing.

Update:
For some clarification:

All signaling is digital
I'm looking to "route" around 10-12 test points to Arduino A ideally but 6 at a minimum


texts: How to properly connect ws2812B to a power supply

texts:
I have a ws2812B led strip. The power supply is 60A/5V. (because the total length will be ~30 meters).
I am using an arduino board. An arduino digital pin is connected to the led strip data pin. When I connect the power supply to the LED strip then it starts flickering. When I use the same setup with a power from a PC (USB cable) the led strip is working properly and the program from the arduino is controlling the leds as expected. If I switch back to the power supply random leds start to flicker.
What I am doing wrong and why?


texts: Using all ten capacitive touch inputs on the ESP32

texts:
I am using a Wemos Pro ESP32 development board and would like to be able to use all ten of the available capacitive touch inputs. I am able to get readings from nine of them but not T1. Here is the pin diagram for the board I have.

Running this code on my board produces no difference in reading for T1...

#define numTouchPins 10
byte touchPins[] = { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9 };
byte touch[10] = {};

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

void loop() {
    for( byte pin = 0; pin < numTouchPins; ++ pin ) {
        touch[pin] = touchRead( touchPins[pin] );
    }
    for( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print( "\t" );
    }
    Serial.println();
}

So the reason for this is that T1 is on GPIO0 which is also connected to a button labeled 0 on the board. Now I realise this is needed in order to select between the ROM serial bootloader mode and the normal execution mode... But, is there a way to change the pinmode from digital-in to touch-in once normal boot has completed? Is there something I can write in the Arduino setup() method that would make this pin behave like the other touch pins?


texts: My Arduino Fingerprint Sensor FPM10A is not working with an Arduino Nano with Atmega168 processor

texts:
I recently bought this Arduino Fingerprint Sensor FPM10A from Aliexpress. So, when I connected it with my Arduino Nano and uploaded the 'enroll' example and opened the serial monitor. The fingerprint print sensor got detected but when I enter #1 to enroll the fingerprint no output is given on the serial monitor. I think my Arduino Nano just freezes.But other examples such as 'Empty database, it works with no problems. Is this caused by the less powerful Atmega168 microprocessor? If I get a Arduino Uno or an Arduino Nano with an Atmega328P microprocessor will this problem be solved? And I do not think the fingerprint module is defective as other examples worked like a charm.
Please see the attached photo above.


texts: ESP01 connected to Arduino can't read from UART while connected from external power source

texts:
I have an Arduino Uno connected to a NodeMCU ESP01 module, communicating via serial pins. The NodeMCU is powered from the Arduino's 3.3V pin. My idea is that the ESP01 receives MQTT messages, sends them to the Arduino via serial and wait for the Arduino to reply and then publish MQTT messages back.

If I power the Arduino from my computer's USB, everything works fine.

If I use an external power supply 12V/1A, the ESP01 can publish and receive "standard" MQTT messages (meaning, it does not send messages to the Arduino and does not expect a reply). It just receives and directly replies (no Arduino involved).

The problem occurs if the ESP needs to query the Arduino for a result.

The Arduino is able to read and write (I see the correct text in the console) to the serial port, but the NodeMCU ESP01 has problems publishing MQTT messages. Sometimes it does not publish anything (the ESP probably is unable to read what Arduino sends over serial), sometimes it publishes destroyed characters (random text).

It looks like the current needed by the ESP module is not high enough, but it does not make sense for me, since the external power supply should be able to provide more current than USB. Any ideas?

This is my schematic:

Code:

In my ESP01 I have the following MQTT onMessage listener, If the topic is a query for the Arduino (topic is validated by the handleQuery function), then the topic is sent by UART to the Arduino, which listens for specific strings in the loop function. When the Arduino receives a string, it does some logic and writes a reply back to the ESP via UART (Serial.print()).

After the ESP sends a message to the Arduino, it sets listeners for strings, that end with character %. If the reply from the Arduino is received, then it publishes an MQTT message with the result.

function onMessage(client, topic, message)
    if handleQuery(topic.."+"..message) then
        uart.write(0,topic.."+"..message)

        uart.on("data","%", function(data)
            if data=="quit%" then
                uart.on("data") -- unregister event
            end

            if data ~= "quit%" then
                client:publish(topic.."/response","REPLY:"..data,0,0)
            end
        end,0)
    else
        client:publish(topic.."/response","REPLY: Invalid query",0,0)
    end
end

The reply from the Arduino has the following message format:

 REPLY:<value>%
 quit%

This solution works if the Arduino is connected to my desktop computer's USB. It does not work if it is powered from an external power supply. It seems like the ESP is not able to read what the Arduino wrote to UART with Serial.println() if powered from an external power source.

I have no idea why, because power supply should be able to deliver more current.

Edit:

I use the following Arduino clone: eBay link

I tried to connect the ESP01 to the Arduino's 5V output with a voltage regulator (5V should deliver more current), and again, if the USB is connected, the ESP reads UART messages with no problem. If the Arduino is powered from an external power source, the ESP reads damaged characters. The only difference is that those damaged characters seems to be always the same. So perhaps some coding problems(?) or something like that.

So far it looks like a low current value is not a problem.

Edit 2

I removed from my code print() statement from the ESP/LUA code that I used for "debbuging". It printed to serial some messages for me. It seems that it cleaned traffic on Serial line a little bit.

Now I get most of the time correct characters, but the first character is missing, so instead of:

LOW% I get OW%
HIGH% I get IGH%
29.53% I get 9.53%

And from time to time I get String =]�quit%.

Perhaps some input buffer has a problem(?).


texts: Cannot program ATMEGA328PU after burning bootloader with internal clock

texts:
I have build a couple of boards that have an ATMEGA328P-AU (the 32 pin MLF, as used on the Arduino Pro Mini). If I burn a bootloader via SPI to use an external 8MHz clock, I can then use the Arduino IDE to write a program via the serial port. If I burn a bootloader to use an internal 8MHz clock, burning the bootloader is still successful but programming with the Arduino IDE does not work.
The current boards do have crystals, but I want to build the rest of the boards without a crystal, so I need to get internal clock working.
The internal (non-working) script looks like this:
avrdude -Cavrdude.conf -v -patmega328p -B4 -cusbasp -Pusb -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m
avrdude -Cavrdude.conf -c usbasp -p atmega328p -e -Uflash:w:ATmegaBOOT_168_atmega328_pro_8MHz.hex

The external (working) script looks like this:
avrdude -Cavrdude.conf -v -patmega328p -B4 -cusbasp -Pusb -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xFF:m
avrdude -Cavrdude.conf -c usbasp -p atmega328p -e -Uflash:w:ATmegaBOOT_168_atmega328_pro_8MHz.hex

By my reckoning, lfuse=0xE2 should be CKDIV8=1, CKOUT=1, SUT=10 and CKSEL=0010.
Any suggestions how to make the internal clock work?


texts:
I have a array called Table1 witch contains '1','2','3','4'
I do not want to work with global variables
I want to change the content of Table1 with a function called 'Change' that gives a return char array back in to Table1

This is the program i wrote:

void setup()

{
  Serial.begin(9600);
}

void loop()
{
  char tabel1[4] = {'1','2','3','4'};
  int i;
  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }

  tabel1 = Change(tabel1);

  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }
}

char Change(char tabel2)

{
  tabel2[0] = 'n';
  tabel2[1] = 'b';
  return tabel2;

}

This is the error i'm getting:

In function 'void loop()':
testArray:17: error: incompatible types in assignment of 'char' to 'char [4]'
tabel1=Change(tabel1);
^
In function 'char Change(char*)':
30:12: warning: invalid conversion from 'char*' to 'char' [-fpermissive]
return tabel2;
^
exit status 1

[Error] Exit with code=1


texts:
With my team we constructed a circuit using Arduino. The circuit works on the Proteus simulator. It worked fine with LEDs connected directly to Arduino outputs.

However, when I used Arduino output to trigger a BC 337 transistor to try and actuate a 12 V DC coiled relay, it wouldn't trigger. I measured voltage across transistor collector and emitter, it reads 12 V, just like the source I gave... (The transistor is not switched on I guess).

Supply for the Arduino is a constant 5 V DC.

Where have I gone wrong? Picture as uploaded.

Furthermore, we are trying to build a controller for an ice making machine. The power circuit (12 V) is to be controlled by Arduino through the transistors.

I am uploading the codes we used and the full circuit diagram.

const int start = 13;
const int comp= 2;
const int cond=3;
const int hGas=4;
const int wbut=12;
const int watersol=5;
const int dumper=6;
const int iced=11;

int startButton=0;
int waterButton=0;
int dumperlimswitch=0;

void setup() {

  pinMode(start, INPUT);
  pinMode(comp, OUTPUT);
  pinMode(cond, OUTPUT);
  pinMode(hGas, OUTPUT);
  pinMode(wbut,INPUT);
  pinMode(watersol, OUTPUT);
  pinMode(dumper, OUTPUT);
  pinMode(iced, INPUT);
}

void loop() {

startButton = digitalRead(start);
waterButton = digitalRead(wbut);

 if (startButton == HIGH) {

    digitalWrite(comp, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
     delay(800);
    digitalWrite(hGas,HIGH);
    digitalWrite(cond, LOW);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(500);
    digitalWrite(hGas, LOW);
    digitalWrite(dumper, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(800);
    digitalWrite(dumper, LOW);
  }
else {
    digitalWrite(comp, LOW);
    digitalWrite(cond, LOW);
  }
}


texts: What is the correct way to interpret the built-in Analog-to-Digital Converter output?

texts:
When using the built-in analog to digital converter of the Arduino Uno Rev 3's Atmega328P with a reference voltage of 5V, what is the appropriate function to interpret the output? There is conflicting information on the Arduino website and in the datasheet for the Atmega328P (Arduino Uno Rev 3's chipset).

A lot of code examples on the internet indicate that the appropriate conversion factor is 5V/1023 (including the Arduino website: float voltage= sensorValue * (5.0 / 1023.0);).

Per the Atmega328P's datasheet, it indicates the conversion factor is 5V/1024:

If Vin and Vref are 5V, then the ADC reading would need to be 1024 in order to have a true reading of 5V, which is not possible since 1023 is the max output of the ADC. The closest reading to 5V we can get from this equation is ~4.9951 (5V*1023/1024).

With the Arduino example's conversion factor of 5V/1023, we get 5V for an ADC output of 1023.

Additionally, since the information from both sources is in conflict, it got me thinking a little more: The ADC is inherently sampling, and I am not sure if the ADC rounds up/down to the nearest value, so perhaps the closest approximation of Vin is an equation like the following that splits the difference:

Vin = (ADC+(ADC+1))/2 * 1024/Vref

Using the above equation, an ADC reading of 0 with Vref=5V would give Vin = (0 + (0+1))/2 *1024/5V = ~0.00244. This equation never gives a reading of 5V or 0V, but rather a value that splits the difference between samples.

Perhaps I am splitting hairs since the absolute accuracy of the ADC is "±2 LSB absolute accuracy", but I would still like to know which is the best equation to convert an output from the ADC into a voltage measurement.