texts: I'm using too much RAM. How can this be measured?

texts:
I would like to know how much RAM I am using in my project, as far as I can tell, there's no way to actually work that out (other than going through and calculating it myself). I have got to a stage in a rather large project where I have determined that I am running out of RAM.

I have determined this because I can add a section and then all hell breaks loose somewhere else in my code for no apparent reason. If I #ifndef something else out, it works again. There is nothing programatically wrong with the new code.

I suspected for a while that I was getting to the end of available RAM. I don't think I'm using too much stack (although it's possible), what is the best way to determine how much RAM I am actually using?

Going through and trying to work it out, I have problems when I get to enums and structs; how much memory do they cost?

first edit: ALSO, I have edited my sketch so much since starting, these are not the actual results I initially got, but they are what I am getting now.

  text     data     bss     dec     hex filename
 17554      844     449   18847    499f HA15_20140317w.cpp.elf
 16316      694     409   17419    440b HA15_20140317w.cpp.elf
 17346      790     426   18562    4882 HA15_20140317w.cpp.elf

The first line (with text 17554) was not working, after much editing, the second line (with text 16316) is working as it should.

edit: the third line has everything working, serial reading, my new functions, etc. I essentially removed some global variables and duplicate code. I mention this because (as suspected) it's not about this code per sae, it has to be about the RAM usage. Which brings me back to the original question, "how to best measure it" I'm still checking out some answers, thanks.

How do I actually interpret the above information?

So far my understanding is:

`TEXT` is program instruction memory
`DATA` is variables (unitialised?) in program memory
`BSS`  is variables occupying RAM

since BSS is considerably less than 1024 bytes, why does the second work, but the first doesn't? If it's DATA+BSS then both occupy more than 1024.

re-edit: I edited the question to include the code, but now I've removed it because it really had nothing to do with the problem (other than maybe poor coding practices, variable declarations and the like). You can review the code by looking back through the edits if you really want to see it. I wanted to get back to the question at hand, which was more based around: How to measure RAM usage.


texts:
I want to build a gamepad HID using the Arduino Micro, and intend to use Nico’s HID library for that.

But I would like to send some config info from the PC to the Arduino HID as well.

Can you have a gamepad that not only sends state to the PC, but also receives a configuration from the PC?

I intend to use this with a Linux PC as host.


texts:
On Arduino I can set digital pins by setting special variables PORTB and PORTD (or maybe they are not variables?). Where are those variables defined? I grepped /usr/share/arduino, but found nothing.

grep -r 'PORTB' /usr/share/arduino/


texts: Unexpected results when creating 32-bit int from byte array

texts:
I'm having problems creating a 32-bit integer from a 4-byte array. In the following complete, minimal, and verifiable example, converting a byte array containing 0x00, 0x04, 0x04F, 0x45 results in 4F45 (expected result would be 44F45). I must be overlooking something fundamental here.... can anyone see where I went wrong?

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

void loop()
{
    uint8_t bytes[4] = {0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(250);
}

uint32_t byteArrayToInt32(uint8_t* bytes)
{
    uint32_t i = 0;
    i |= bytes[0] << 24;
    i |= bytes[1] << 16;
    i |= bytes[2] << 8;
    i |= bytes[3];
    return i;
}


texts:
How do I read the Json object name in arduino? For { "pi" : "3.14" }, I want the arduino to automatically read the object name "pi" and then th value "3.14"
I'm using arduino Uno.


texts:
I have a Teensy set up as a keyboard, joystick, and I'm giving keyboard commands. Letter and number keys are going fine. But when I try sending ENTER, I get some extra code in my Linux terminal:

$ 16424
16424: command not found

the code I have to give the ENTER key goes like this:

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

void loop() {
  // read the digital inputs and set the buttons
  Joystick.button(1, digitalRead(0));
  Serial.println(digitalRead(0));
  if(digitalRead(0)==0){
    Keyboard.println(KEY_ENTER);
  }
  delay(50);
}

where is this  "16424" coming from, and how do I send an ENTER keypress?
I am using a Teensy 2.0, on Linux, with Arduino IDE 1.6.7.


texts: Sending Large Packets and Reassembling over Serial

texts:
I'm trying to send info of about 30-40kB over the Serial ports on an Arduino Due. But I'm running into a few problems.
First, before we get into the actual transfer over the Serial, I want to try storing 30000 Bytes into a char * array.

Also as a disclaimer, I've modified the SAM library's RingBuffer.h SERIAL_BUFFER_SIZE to 256 from 128.

void setup() {
  Serial.begin(115200);
int i,j=0, cksum=0;
int *test;
test = (int*)calloc(1,30000);
Serial.println("Starting...\n");

for(i=0;i<30000;i++){
  test[i]=i;
  cksum +=j;
  j++;
  if(j>255){j=0;}
}
Serial.print("cksum is: ");
Serial.println(cksum);
cksum = 0;
for(i=0;i<30000;i++){
  if(i<300){ //only print out the first 300 characters, otherwise it's hard to see anything
    Serial.print("[");
    Serial.print(test[i],HEX);
    Serial.print("]");
  }
  cksum+=(int)test[i];
}
Serial.print("\nNow cksum is: ");
Serial.println(cksum);
}

Obviously, since *test is a byte array, I'm only storing int8 into there - so from 0-255.
That means that the data received in *test increments from test[255]= 255 to test[256] = 0. The way around this would be to use some kind of itoa function to write out multiple bytes that represent the numbers being written (causing an overflow because it would no longer be an array for 30000 Bytes). But for these purposes is it ok to simply realize that this is happening and just write the bytes to the array.

Ok, so for part two, I want to do the same thing, but by writing to Serial2 from Serial3 and receiving all of the bytes:

void setup() {
  Serial.begin(115200);
  Serial2.begin(115200);
  Serial3.begin(115200);
int i,j=0;
double cksum=0;
char *buf;
Serial.println("Starting...\n");
buf = (char*)calloc(1,30000);

Serial.println("Writing to Serial3");
  for(i=0;i<30000;i++){
    Serial3.write((byte)i);
    cksum+=j;
    j++;
    if(j>255){j=0;}
  }
 Serial.println(cksum);
 Serial.println("Reading from Serial2");
 Serial2.readBytes(buf,30000);
 cksum = 0;
  Serial.print("Buf is: ");
  for(i=0;i<30000;i++){
    if(i<300){ //only print out the first 300 characters
      Serial.print("[");
      Serial.print(buf[i],HEX);
      Serial.print("]");
    }
    if(buf[i] != j){
      Serial.print("\nMismatch at i = ");
      Serial.print(i);
      Serial.print("\nBuf is: ");
      Serial.print(buf[i-1],HEX);
      Serial.print(",");
      Serial.println(buf[i],HEX);
    }
    cksum+=buf[i];
    j++;
    if(j>255){j=0;}
  }
  Serial.println("\n\nEnd");
  Serial.println(cksum);

}

What happens here is that I get a mismatch at byte 255. The increment (in hex) goes:

[254] = FE
[255] = 30
[256] = 31

But it should read:

[254] = FE
[255] = FF
[256] = 0

After reading some other forums, and the fine AVR Arduino post here, I feel like something is happening on the Serial interrupt level that I am not aware of. All of the data is properly transferred to the Serial and I am able to see all of the bytes in the correct order coming out of TX and into RX on my logic analyzer.
I've also experimented with different baud rates, but see no reason why a 84Mhz chip would not be able to handle a baud rate of 115200.

Has anyone else run into this? How do you handle these transfers of continuous data that is larger than the buffer? Is the only option here to run readBytes in SERIAL_BUFFER_SIZE increments until Serial is no longer available? Or can I still salvage using readBytes all in one go as I am trying to do?

I know this question has been asked in certain forms in other threads like here and here but they do not solve this particular problem I am experiencing, most likely because they are not Due specific.


texts:
I am new to Arduino, and already tried to edit this many time. But I cant figure out whats wrong.

The following code has a PIR sensor, 1 LED and 1 buzzer.
I want to add one more PIR sensor, but it should trigger a separate LED , and the same buzzer. In serial monitor.
I have searched many sketches, but all of them seems to have a different method , cant figure out the basics!

int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                    // variable for reading the pin status
int pinSpeaker = 10;           //Set up a speaker on a PWM pin (digital 9, 10, or 11)

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
  pinMode(pinSpeaker, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    playTone(300, 160);
    delay(150);

    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
      digitalWrite(ledPin, LOW); // turn LED OFF
      playTone(0, 0);
      delay(300);
      if (pirState == HIGH){
      // we have just turned off
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
    duration *= 1000;
    int period = (1.0 / freq) * 1000000;
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(pinSpeaker,HIGH);
        delayMicroseconds(period / 2);
        digitalWrite(pinSpeaker, LOW);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
    }
}


texts: I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?


texts: Hardware damage from executing tight polling loop over extended periods of time?

texts:
I want my project to be standing by at the ready for months and years at a time, so I started writing my code to throttle back from polling at delayMicroseconds  to just delay. Like, after 15 minutes with no user input, switch from 10 microsecond delay intervals to 10 millisecond (or even 10 second intervals). I wonder if spinning its wheels at warp speed for months on end will wear a path in the circuit pathways? This has got to be a stupid question (or at least make someone chuckle), but I'm really 50/50 at this point: worth the effort for the extra code or won't make a lick of difference? (I know there's my implementation and then there's the right one, but this is where I am right now. FYI, I went with 17 GPIO's in parallel to link my Pi to my teensyduino. add 17 optocouplers, hot glue, hinges, scavenged enclosures etc and this thing looks ridiculous.  But I LOVE IT! (It's a mouse that I control over the web)

EDIT
Although I didn't mention any concerns about using batteries, their mention didn't really detract from anything. Rather, I welcomed their inclusion because I realized that I had overlooked things more fundamental. I'm always telling others how important ventilation can be and the impact heat can have, but it went right by me this time!

I do value and appreciate the feedback I have gotten. I don't think I will be writing any code to vary polling speed after timing out. But I would still like if someone wanted to directly answer the specific concern I had when posting this question: "At certain times, my program waits for a GPIO pin to change states. I am using the polling method to determine the status of the pin, and I am using this bit of code to do so:

do
{

} while (digitalRead(pin#) == 0); //wait for pin to go high

So, my question is, "Does it make any difference at all, in terms of wear & tear or stress placed on the CPU, how many loops I choose to make in one second? I'm considering something in the range 0.1Hz -> 100kHz  Assuming that I keep heat under control and other vital parameters within their nominal operating levels, is it true that the frequency I choose won't make a bit of difference, one way or another?"

Thanks in advance for any interest given to this question.


texts: Carry out two consecutive tasks when a button is pressed

texts:
I'm building a project that has 2 motors. What I want to do is:
When button is pressed (hold down through RF controller) then:

Run motor A on pwm at 50 for 1 second
Run motor B on pwm at 255 for 1 second

After that first second

Run motor A on pwm at 255 until button is released
Stop motor B.

And when I hit the button again the whole thing repeats. Here is my rough code but it doesn't work that way. What it does is if I pressed the button in the first second since start up off the Arduino it does the first task. If I press it again it does the second task.

I have looked and tried through a lot of examples of blink without delay and multitasking. But I still can't get it working.

Here is my code:

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

// Motor 1
int dir1PinA = 4;
int dir2PinA = 5;
int speedPinA = 3; // Needs to be a PWM pin to be able to control motor speed

// Motor 2
int dir1PinB = 7;
int dir2PinB = 8;
int speedPinB = 6; // Needs to be a PWM pin to be able to control motor speed

int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;

unsigned long previousMillis = 0;
long OnTime1 = 500;
long OnTime2 = 10000;

void setup(){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();

 pinMode(dir1PinA,OUTPUT);
 pinMode(dir2PinA,OUTPUT);
 pinMode(speedPinA,OUTPUT);

 pinMode(dir1PinB,OUTPUT);
 pinMode(dir2PinB,OUTPUT);
 pinMode(speedPinB,OUTPUT);

 }
 void CandPush()
 {
          analogWrite(speedPinA, 50);//Sets speed variable via PWM
          digitalWrite(dir1PinA, HIGH);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinB, LOW);
          digitalWrite(dir2PinB, HIGH);

 }
 void CandStop()
 {
          analogWrite(speedPinA, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinA, HIGH);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 0);//Sets speed variable via PWM
          digitalWrite(dir1PinB, LOW);
          digitalWrite(dir2PinB, LOW);

 }
 void Home()
 {
          analogWrite(speedPinA, 0);//Sets speed variable via PWM
          digitalWrite(dir1PinA, LOW);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinB, HIGH);
          digitalWrite(dir2PinB, LOW);

 }
 void loop(){

 if (radio.available()){
    bool done = false;
    while (!done){
    done = radio.read(msg, 1);
    Serial.println(msg[0]);
    if (msg[0] == 111)
    {
      unsigned long currentMillis = millis();
      CandPush();
      if(currentMillis - previousMillis >= OnTime1)
      {
        CandStop();
        previousMillis = currentMillis;
      }

    }
 }
 }

 else
 {
  Home();
  Serial.println("Nothing");
 }
 }


texts:
I am looking through the example code found here. I know there are 6 pipes that the nRF24L01 module can use but I've been searching the internet for the address designations and have been able to find nothing. More specifically on line 37, is there a reference for where the author is getting 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL?

Thanks.


texts: Will there be any pin interference in this Project?

texts:
I am working on a project with Arduino Uno Clone. After having a look on my arrangement, please tell me whether I will have to face any difficulty or consider any thing.

I have a relay on pin 2 (drive An Induction cooktop from AC Mains),

6 mini 9g servo from pin 3-8 (want to drive non-pwm pins with any Software library),

a 8 ohm speaker on pin 9,

a microSd card module from pin 10-13 (play .wav files through speaker),

5 pushbuttons from pin A0-A4,

a toy dc motor on A5 (Drive through a transistor). So my questions are:

Will I have to face any pin arrangement problem in my project? If yes, please give me a solution
I have six servos and a dc motor in which only one will be moving at a time, is there really a need of external power source for motors
I have to drive this arrangement through AC Mains, but i dont want to buy An adapter. I have a mobile charger which have written "INPUT 100-250V AC, OUTPUT 4-12V, 800mA" , can I drive my arduino with this?
Can I boost the volume of my speaker by using a transistor or capacitor (I have no idea about amplifier IC) ?
I have to include these librairies, SD library, tmrpcm, SPI, servo, and any one extra to drive servos on non-pwm pins. What would be the total size because my arduino has only 30kb approx?  Thanks To Give Me Time. Please help me.


texts: I can't turn on the motor by Arduino IoT Cloud

texts:
I'm trying to turn ON/OFF a DC motor from Arduino Iot Cloud. I have to turn it ON/OFF physically and through the cloud, physically it works well but from the cloud it does nothing. I'm using an Arduino MKR WiFi 1010, a L298N Dual full bridge,9V DC motor and a push buttom. Mi circuit is like this
My code is this
#include "thingProperties.h"
#include <FTDebouncer.h>

#define MOTOR_PIN 2
#define BUTTON_PIN 5

FTDebouncer buttons;

void setup() {
  pinMode(MOTOR_PIN, OUTPUT);
  buttons.addPin(BUTTON_PIN, LOW);
  buttons.init();

  setDebugMessageLevel(2);
  Serial.begin(9600);
  delay(1500);
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
}

void loop() {
  buttons.update();
  ArduinoCloud.update();
  onMotorChange();
}

void onPinActivated(int pinNr) {
  // do something according to the _pinNR that is triggered. For instance:
  Serial.println(pinNr);
  toggle = !toggle;
}

void onPinDeactivated(int pinNr) {
  // do something according to the _pinNR that is triggered. For instance:
  Serial.println(pinNr);
}
void onMotorChange() {
  digitalWrite(MOTOR_PIN, toggle || motor);
  Serial.print("The motor is ");
  if (toggle) {
    Serial.println("ON");
  }
}

I tried with a LED and it worked very well, but with the motor doesn't.
This is the code that Arduino creates when I add things to the board, the part of

thingProperties.h

// Code generated by Arduino IoT Cloud, DO NOT EDIT.
#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>

// x-ed id
const char THING_ID[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or
use as
key for WEP)

void onMotorChange();

bool toggle;
bool motor;

void initProperties(){

ArduinoCloud.setThingId(THING_ID);
ArduinoCloud.addProperty(toggle, READ, ON_CHANGE, NULL);
ArduinoCloud.addProperty(motor, READWRITE, ON_CHANGE, onMotorChange);

}

WiFiConnectionHandler ArduinoIoTPreferredConnection(SSID, PASS);

Thanks for the help and suggestions. How should I connect the motor or what do I have to change in the code?


texts: Controlling multiple stepper motors non-simultaneously

texts:
I want to control multiple stepper motors one after another and at different speeds/directions. I am using the ULN2003 driver and the stepper has 5 coils.

My current code for controlling one motor is:

#include <Stepper.h>

const int stepsPerRevolution = 500;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(50);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
}

How would I define each stepper motor differently?

Sorry if I have not asked the question properly. I will try to clarify as time goes on.


texts:
I am new to Arduino so please give me some advice on this really simple problem. I am currently using an Arduino Mega in a school project to make 4 capacitive sensors which are supposed to receive an input when you touch the sensors, and I have programmed the arduino such that you will light up an LED upon touching the sensors.

Now the problem is after I light up the LEDs the serial data monitor gives me many different numbers when I am touching the sensors. Is it actually possible for me to tweak my program such that outputs of my sensor will show up as a single line of '0' when the sensor is not being touched and '1' when the sensor is being touched? This would really help me in the quantifying of some of the data I would wish to collect from my experiments with the sensors.

My code is

#include <CapacitiveSensor.h>

CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);

void setup()
{
   cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1
   cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);

   Serial.begin(9600);
   pinMode(3,OUTPUT);
   pinMode(6,OUTPUT);
   pinMode(9,OUTPUT);
   pinMode(12,OUTPUT);
}

void loop()
{
 long sensor1 =  cs_2_4.capacitiveSensor(50);
 long sensor2 =  cs_5_7.capacitiveSensor(50);
 long sensor3 =  cs_8_10.capacitiveSensor(50);
 long sensor4 =  cs_11_13.capacitiveSensor(50);
Serial.print("\t");
Serial.println(sensor1, BIN);  // print sensor output
Serial.print("\t");
Serial.print(sensor2, BIN);
Serial.print("\t");
Serial.print(sensor3, BIN);
Serial.print("\t");
Serial.print(sensor4, BIN);

    if(sensor1 >= 1000)
   {
    digitalWrite(3,HIGH);
   }
   else{
    digitalWrite(3,LOW);
   }
     if(sensor2 >= 1000)
   {
    digitalWrite(6,HIGH);
   }
   else{
    digitalWrite(6,LOW);
   }
    if(sensor3 >= 1000)
   {
    digitalWrite(9,HIGH);
   }
   else{
    digitalWrite(9,LOW);
   }
    if(sensor4 >= 1000)
   {
    digitalWrite(12,HIGH);
   }
   else{
    digitalWrite(12,LOW);
   }
   }

and the output that I end up receiving is

Hence it would be really great if I could tweak my code such that the output on the serial monitor would be '0' when there is no output(Not touching sensor) and '1' when there is an output (touching sensor)

Thanks a lot for the help once again!


texts:
I'm trying to provide analog control to a Bluetooth controlled car, via Arduino. I have joystick app (as the pot).
It send values between 0 to 255
So I'm thinking... Whether this flow down here  will work?

Joystick app --> Bluetooth Rx --> DAC --> Vs pin of L293D. Or motor?

Is Arduino required at all? Or is the serial word enough to translate into voltage via DAC?


texts: everything works independitly but not together. Piezo not generating a tone

texts:
My goal with the code is simple. Let the Piezo buzz when temperature reaches 25 degrees. My piezo is hooked up correctly, because It makes a buzz when the arduino boots or when I put this line of code anywhere else in my code.

I also checked if the If statement was called. And yes it is! So the if statements is happening yet I don't hear a buzz.

I am aware that I am breaking my seven segmented screen by using the delay. But I don't mind the screen working when the buzzer is.

void loop()
{
  //local vars
  if (millis() % 5000 <= 10) {
      float lm35TempC = lm35.getTempC();
      sevseg.setNumber(lm35TempC, 2);
      if (lm35TempC > 25.00) {
        tone(1,500,1000);
        delay(3000);  <------- WHERE IT PROBABLY GOES WRONG
      }
      if (lm35TempC < 25.00) {
        noTone(1);
      }
  }
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

To conclude: The If-statement is working yet I don't hear a buzz. How does this happen?

Thanks in Advance!


texts: How to connect ESP8266 to my home WiFi securely

texts:
I'm working on a home automation project using NodeMCU ESP8266. Most of the example projects I see online provide their WiFi SSID and password in plain text at the beginning of the code by storing them into some variable

Is there a secure way of doing that? I'm worried if my ESP8266 gets hacked by someone online, they'll now have my WiFi SSID and the password. Is there a way of encrypting this information before passing it to ESP8266. Or is there a way of creating a separate WiFi password which will only be used by the ESP8266?


texts:
I was looking for wiring the VCNL 4000 Proximity Sensor.

I found this one http://bildr.org/2012/11/vcnl4000-arduino/

but there is used a sensor on a red board, which has other pins like mine (which has a blue board) see http://www.adafruit.com/products/466?&main_page=product_info&products_id=466

as I see SCL,DSA,GRND on both

the red has IR+ which is connected to the 5V . mine (blue one) has VIN. Is this meant to be the same and should it be connected to the 5V ?

Any hints?

I tried the following wiring but the following call does not finish.

3,3V TO 3,3V POWER

SCL TO SCL (Last pin on the digital side)

SDA to SDA (Beside SCL)

GND TO GND on the Analog side

Vin to 5V

 readVCNLByte(0x81); is called

i used the example code from adafruiut


texts:
OK,so this is my first program written via the Tinkercad utility. I have saved the program as a text file, and it equates to about 22K.

My simple question is, when uploaded / compiled to the actual board, is the size increased or decreased? I plan to use the Nano (32K) If it shrinks or stays roughly the same, I should be OK. However,if it 'bloats' due to extra C code ...

** As someone used to working with sub routines, arrays and variables, found it a bit of a hassle that everything has to be in one loop, only conditional statement breaking the flow - leastin TinkerCAD. And when you want to control 8 LED outputs, having to switch each one on and off via a digital write line. For example, the four output lines below:

11001100
01100110
00110011
10011001

... needs 32 digital write commands !! (And whilst the above is 4 lines, there are nearer 150 similar lines in final code, hence it's size)

The way I wrote it using ths above utility was something like:

for(counter=0; counter<4; counter){
if (counter==0){
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }
if (counter==1){
    digitalWrite(2, LOW);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(9, LOW);
  }
//etc
}


texts: Piezo buzzer not sounding well with ATmega328

texts:
I am using an ATmega328 to drive a 16x2 LCD, a LED, and a piezo buzzer. Piezo buzzer needs to buzz after every 5 seconds. But it doesn't make a nice sound it just gives out a faint buzz. Suspecting the buzzer to be faulty, I tested it separately from a 5V supply and it worked well. Then I put it back in the circuit and checked for the amount of current the whole circuit used. It was about 26mA when buzzer and LED were turned off, and 36mA with buzzer and LED ON. So no problem there. Additionally, the buzzer sometimes start sounding well too occasionally. This occurs after about half a minute the circuit is turned ON. This looks like that the buzzer is somewhat warming up before it can work properly. But this occurs occasionally.

I am using A0 Analog pin (or Pin no. 23 on ATmega328) for driving the Buzzer and giving 100Hz square wave to it.

What could possibly be the reason for this problem?


texts: Unable to receive and print sms on serial monitor arduino uno and SIM900A

texts:
I'm trying to receive sms and show it on serial monitor.

My code is as follows:

void setup() {

Serial.begin(2400);

Serial.write("AT+CMGF=1\r"); //set GSM to text mode

delay(1500);

Serial.write("AT+CPMS=\"SM\"\r"); //Preferred SMS
//message Storage

delay(1000);

Serial.write("AT+CMGL=\"ALL\"\r"); //List SMS Messages
//from Preferred Storage

while(1)

 {

   if(Serial.available())

     {

        Serial.write(Serial.read());

      }
  }
}
void loop() { }

The output that I am getting is as follows:-

  AT+CMGF=1AT+CPMS="SM"AT+CMGL="ALL"AT+CMGF=1

  OK

  AT+CPMS="SM"

  ERROR

  AT+CMGL="ALL"

  ERROR

This I am not able to use AT+CPMS or AT+CMGL commands. Please help.
The circuit diagram is as follows:-

.


texts: Programming an Arduino over the air using an ESP8266

texts:
This question stems from this article (Originally in Spanish/English) which Hack a Day summarizes (Includes link to partial English translation). These articles show that it is possible to update an Arduino Uno via an ESP8266 over WiFi.

I've modified the code so that when I hit the reset button on the Arduino connects to an "Update" server via the ESP8266, configured in "transparent" mode, to check for an update. If one is present the ESP8266 updates the Arduino which reboots itself. If there isn't an update I reset the ESP8266 and quickly tell it to drop any connection before it can reconnect to the "Update" server thus allowing me to connect to a "Logging" server instead for normal operation.

There is a slight difference in how one connects. The "Update" server is connected with the ESP8266 in "transparent" mode. While connecting to the "Logging" server the ESP8266 is in "normal" mode.

At present I have wired an additional connection to the reset pin of the ESP8266. Whenever it doesn't do what I want it to do I drop the power on the reset pin, confuse it and Zap in a command before it's managed to re-establish any "transparent" connection. This works but seems a little like black magic.

I was curios to know if there is a better way to force the ESP8266 out of "transparent" mode.

Note: I have not flashed the ESP8266 with NodeMCU/ESPLink or some other firmware.

Aside: There is an ESP8266 Arduino Core library does this also flash the ESP8266 in a manner similar to NodeMCU/ESPLink or does this run on the Arduino and facilitate over the air updates using the native firmware as I am trying to do ? I've only just started reading their documentation. (As this is a first post I've run out of links to share)


texts: Saving byte array in PROGMEM instead of SRAM

texts:
For an ethernet project I do, I need to store the Ethernet Shield's MAC address.
I store it like that:

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

That works OK, but in my project I need all the SRAM available, so every byte of memory is important. I've used the F() macro and PROGMEM everywhere, but I couldn't manage to store the MAC byte array in the PROGMEM.

How can I store it in PROGMEM? Is it even possible?


texts:
I'm using a NodeMcu for my project and am running out of pins to use. I have a MFRC522 Module, IR Receiver, Buzzer and RGB LED connected. I am facing the problem that whenever I start scanning for RFID tags with the MFRC522 module, the onboard LED starts flashing very fast and the RGB LED changes to an undefined color.

I looked up the pin definitions of the NodeMcu, but couldn't quite find information on what pins I can use for this and which I can't, and why this only happens once I start up the RFID reader.

This is my wiring sketch:

I found this pin layout image, as well as the datasheet.

The code shouldn't be really relevant since it works before starting the RFID reader, but here is the setup of the reader, just in case:

#define SS_PIN D4   // SPI - Slave Select Pin
#define RST_PIN D2  // SPI - Reset Pin - not actually connected

MFRC522 mfrc522(SS_PIN, RST_PIN);

// Initial setup for SPI and MFRC522
bool rfidSetupCompleted = false;
void setupReader()
{
  SPI.begin();
  mfrc522.PCD_Init();
  rfidSetupCompleted = true;
}

These are the pin definitions of the RGB LED:

#define LED_BLUE D8
#define LED_GREEN D3
#define LED_RED D2

Any help is highly appreciated! I'm assuming I am using a pin that is used for other purposes (such as maybe D8), but I can't figure out which, and why. I did try to change up the pins and switched D0 and D8 (buzzer and one LED pin), but without luck. I also tried disconnecting each LED pin separately, but didn't learn anything from that either.


texts: Arduino Not Working as Intended when using barrel jack

texts: I am using an Arduino to control some mechanical components in a project I have. It controls a motor, two servos, a valve, and a compressor. When plugged into the computer, everything works fine and perfectly. However, when I power it through the barrel jack using our power supply, some weird things happen. First of all, our servos, which are powered through the Arduino, stop working. All the other components work except for them. Secondly, at the end of the code we have a 5 second delay. Using the computer it works fine. When powered with our supply the delay doesn't seem to happen at all. Any ideas?


texts: Arduino Nano + RFID RC522 + Ethernet shield W5100

texts:
I have this Arduino Nano, Ethernet shield W5100 and RC522 as card reader. They are sharing pins D13, D12, D11, D10 is SS pin for W5100 D8 is SS pin for RC522. Problem is with pin D12, like it doesn't share it.

For example if I unplug D12 from W5100 RC522 reader works, if I wire it back it doesn't work anymore. W5100 works no matter if RC522 is wired or not, so problem would be somehow with pin D12.

Does anybody have some ideas, what I'm doing wrong right here?


texts: How to flash an ATmega directly without a dedicated flashing device?

texts:
An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP).

I tried to flash the program into the microcontroller by saving the machine code to a MicroSD card that I then attached to the microcontroller. I figure we can use the USB SPI reader to test the program without dedicated device like USBtiny.

But I suspect that the compiler is just producing the hex file and then the USB will translate it to machine code.

Was I thinking wrong?

If the compiler loads the machine code through the USB programmer to microcontroller so don't we just need a MicroSD USB to program it?


texts: What can an Arduino Due do that a Mega 2560 can't? What can a Mega 2560 do that a Due can't? I've heard the Due is 3.3V so it can't work with most shields.


texts: Building projects on the command line using the Bare-Arduino-Project template

texts:
I'm trying to program an Adafruit Trinket using avr-gcc et. al. with the Makefile from the Bare-Arduino-Project on macOS Catalina.

I can build projects for standard boards like the Uno, but not for the Trinket. Everything works as expected using the "official" Arduino IDE (1.18.10). In the Bare-Arduino-Project Makefile I'm specifying the Trinket as:

BOARD_TAG         = trinket5
BOARD_SUB         = attiny85

I get an error from avr-gcc that mmcu is not defined. I assume this is because the command line tools aren't finding the Adafruit equivalent of boards.txt. When I look in the Arduino IDE package I don't find the Adafruit boards in boards.txt or anything that looks like the definitions for the Adafruit boards (despite having added them in the IDE).

Any ideas about how to set up support for the Trinket (or other third party boards) when using command line tools?


texts: Use distance sensor to trigger LED strip and stay on while the person is in range

texts:
I'm trying to use a distance sensor to trigger an LED light, as you can see below. However, I also want the LED to stay on/white when a person is within the 38 inches range. How should I do that?

//Tell the Arduino IDE to include the FastLED library
#include <FastLED.h>

//Setup the variables for the HC-SR04
const int trigPin = 9;
const int echoPin = 6;
//Setup the variables for the NeoPixel Strip
#define NUM_LEDS 60 // How many leds in your strip?
#define DATA_PIN 4 // What pin is the NeoPixel's data line connected to?
CRGB leds[NUM_LEDS]; // Define the array of leds

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

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);

  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  if (inches <= 38)  {
    for ( int colorStep = 0; colorStep < 256; colorStep++ ) {
      int r = 255 - colorStep;
      // Redness starts at zero and goes up to full
      int b = 255 - colorStep;
      // Blue starts at full and goes down to zero
      int g = 255 - colorStep;
      // No green needed to go from blue to red
      // Now loop though each of the LEDs and set each one to the current color
      for (int x = 0; x < NUM_LEDS; x++) {
        leds[x] = CRGB(r, g, b);
      }
      // Display the colors we just set on the actual LEDs
      FastLED.show();
      delay(10);
    }
  } else if (inches > 38) {
    fill_solid( &(leds[0]), NUM_LEDS /*number of leds*/, CRGB::Black);
    FastLED.show();
  }
  delay(1000);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second). This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}


texts: This website in Arduino lists language references like functions and structures. What makes structures there different from functions?

texts:
https://www.arduino.cc/reference/en/
Language Reference
Arduino programming language can be divided in three main parts: functions, values (variables and constants), and structure.
functions
For controlling the Arduino board and performing computations.
variables
Arduino data types and constants.
structure
The elements of Arduino (C++) code.
I find it really confusing that they had to separate the structures but also call them functions in their descriptions. I kind of want to get a visualization or organization of the different language references present in Arduino, but this just confuses me. Are structures in the website also functions, and mainly syntax can be classified into functions and variables? Can someone present a organization of language references that doesn't involve terminologies being mixed up?


texts: How is this simple transistor circuit suppose to work?

texts:
I've tried to replicate this circuit today.

My motor is a computerfan, they apperntly don't need a flyback diode since there are no brushes.
I used a 12V power source for my arduino and hooked it up via
VIM.
I used the arduino ground as external power source.
I verified that the transistor worked as expected with a voltmeter.

Here is the transistor I used:

As I understand this, the transistor is stimulated to "steal" electrons away from the motors circuit. But it seems connected to the base. Why would you do that?


texts:
This is my Arduino code that checks the water Level of two different water reservoirs via 2 water Level Sensors A and B:

#define Water_Level_A 5;
#define Water_Level_B 6;

boolean Water_Level_Check_A(){
boolean Result = digitalRead(Water_Level_A);
return Result;
}
boolean Water_Level_Check_B(){
boolean Result = digitalRead(Water_Level_B);
return Result;
}

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

void loop() {
if (Water_Level_Check_A() == LOW){
--> Water Pump A
}
if Water_Level_Check_B() == LOW{
--> Water Pump B
}

What's the best way to simplify this code so that I only need one Water_Level_Check function so that the distinction between A and B and Water_Level_A and Water_Level_B is made within the function and the loop part looks like this:

void loop() {
if (Water_Level_Check_(A) == LOW){
--> Water Pump A
}
if Water_Level_Check_(B) == LOW{
--> Water Pump B
}


texts: Trying to create a beats per minute monitor but having diffuctly with the coding? coding wont print any values

texts:
Any advice on what coding to adjust. New to Arduino.

const int sensorPin = A0;
float voltage=0.0;
int sensorVal=0;
int heartbeats=9;
float BPM=0.0;
const int led1=2;
const int led2=3;
int starttime = 0;
boolean counted = false;

void setup() {
pinMode(sensorPin, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(9600);
boolean counted = false;
}
void loop() {

starttime = millis();
while (millis()<starttime+10000)
{
  sensorVal = analogRead(sensorPin);
  if (sensorVal >550 && counted == false)
  {
    counted = true;
  }
  else if (sensorVal < 500)
  {
    counted = false;
  }
}

    BPM = heartbeats*6;
 Serial.println("Your BPM is");
 Serial.println(BPM);
BPM =0;
heartbeats =0;

}


texts:
I'm trying to control a DC motor through L293D motor controller

const int controlPin2 = 4; // connected to pin 2 on the H-bridge
    const int enablePin = 3;   // connected to pin 1 on the H-bridge

void setup(){

  pinMode(controlPin2, OUTPUT);
  pinMode(enablePin, OUTPUT);

  digitalWrite(enablePin, LOW);
  digitalWrite(controlPin2, LOW);

Serial.begin(9600);
Serial.println("Ready");
}

void loop(){
if (Serial.available() > 0) {
    int inByte = Serial.read();

    switch (inByte) {
    case '0':
  digitalWrite(enablePin, LOW);
   digitalWrite(controlPin2, LOW);
 Serial.println("OFF");
      break;
    case '1':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 50);
    Serial.println("CW slow");
      break;
          case '2':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 100);
    Serial.println("CW slow +");
      break;
          case '3':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 150);
    Serial.println("CW medium");
      break;
          case '4':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 200);
    Serial.println("CW fast");
      break;
          case '5':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 250);
    Serial.println("CW fast +");
      break;
    case '6':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 50);
    Serial.println("CCW slow");
      break;
      case '7':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 100);
        Serial.println("CCW slow +");
      break;
      case '8':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 150);
        Serial.println("CCW medium");
      break;
       case '9':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 250);
        Serial.println("CCW fast");
      break;
}
}
}

It is working well except 1 to 5 are reversed:

1 should be the minimum speed
5 should be the maximum.

But it is back to front:

5 is the minimum speed
1 is the maximum speed

Any ideas?


texts: Wiring Lilypad USB + ESP8266 Serial WiFi Module

texts:
I am trying to solve the following scenario:
Lilypad USB connected to WIFI through ESP8266 Serial WiFi Module.

http://arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardLilyPadUSB

http://www.seeedstudio.com/wiki/WiFi_Serial_Transceiver_Module

According to the wiki:
I should connect to TX RX pins. None of them are present as "selectable pins", because they are built in.

This post Using LilyPad Arduino USB with LilyPad Xbee Shield  talks about using SoftwareSerial something that is new to me.

Could anyone explain how should I proceed with the wiring and if possible a sample sketch just to connect the lilypad usb with the WIFI module to my personal WIFI.

Edit:

I found the following tutorial (spanish one but easy to follow...) where they use the Arduino UNO. I tried the example with the software serial and it worked.
I saw in that tutorial sometimes the pin RST is needed. So I tried to do the same with the lilypad USB, but still didn't work.


texts:
Some people have managed to send simple AM signals with just a bare Arduino. An example is here.
This works thanks to the fact that the PWM can reach high frequencies and, setting the divider properly, it is possible to broadcast a 1337 kHz carrier over a short distance with just a wire acting as an antenna.
I know it's not that useful, but it's really nice as an educational tool.

I was wondering if it would be possible to apply the same concept, but for the receiver. For instance simply using a pulseIn() detection on a pin connected to an antenna. Would it be possible to detect the carrier, and, maybe, even demodulate a message, eg, in morse code?

If not, would just a adding an amplifier be sufficient? Any recommendations for the amplfier and the circuit?

Thanks very much for your suggestions.


texts:
I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.

I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?

Master makes request for string that could be about 180 bytes max - ever.

Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200
while (Wire.available())
{char c = Wire.read();
cmdInStr.concat(c);
}

Slave sends

int len = cmdOutStr.length()+1;
char ascii_num[len];
for (int i=0; i<len; ++i)
{ Wire.write(ascii_num[i]);
}


texts:
in "Disabling the Bridge Script" of http://cylonjs.com/documentation/platforms/yun/

I did:

  Edit the /etc/inittab file to comment out the ttyATH0 line (put a # before it)

::sysinit:/etc/init.d/rcS S boot
::shutdown:/etc/init.d/rcS K shutdown
#ttyATH0::askfirst:/bin/ash --login

But I want to turn it on or off manually. Then I can program through WiFi if I want.

How to do that?


texts: Is it possible to run 2 functions, that communicate with 2 different serial devices, in parallel using FreeRtos library?

texts:
This might seem like a very broad question but that's what i want it to be for multiple ways of implementation.

I've an Arduino UNO communicating with 2 Serial devices interfaced using SoftwareSerial flawlessly. I've used [SS_Object].listen() function to switch between the two. Right now, the entire code works sequentially meaning that, once it's work with the 1st Serial device is done, only then it will switch to the 2nd Serial device and work with it. Can i communicate with the 2 in parallel (Multitasking) using FreeRtos? I've heard that the scheduler switches between tasks when it encounters a delay. So may be a small useless delay is required, only for the scheduler, to switch between the two. May be! or May be things will be better if i use more advanced Arduino like Mega or Due.

Thanks for taking your time to read this. Please answer the question the way you've understood it as i am sure different people with different experiences will interpret this differently.

Thanks in advance!


texts:
Introduction
I am trying to program an arduino pro mini, I have to use this board because of it's size.
I use the arduino-cli to program arduino and one of the steps to upload code to the system requires the board's fqbn and I can't find it anywhere.
Question
Does anybody know this board's fqbn (fully-qualified board name)?


texts: How to stop Arduino from drawing power through USB

texts:
I'm working on an embedded project, where I use arduinos as a "sensor shield" for RaspberryPi (I have model B).

The problem is, that the RaspberryPi's USB port is not powerfull enough to drive WiFi adapter and arduino with sensors. The solution is easy, I will power the sensors externally, not through the RPi.

But I was wondering, is it possible to power whole Arduino externally (through Vin) and use the USB only for serial communication.

To clarify, I know how to solve my problem - use some other mean of communication, than USB - GPIO serial, I2C, wireless, etc... I'm just interested if the whole thing will work, with USB cable which has 5V lead cut, for example.

The main issue I can see with this is, that the USB<->Serial chip is powered through USB only, then it will now work.


texts:
I have the code below which is my attempt to control a stepper motor direction that moves a carriage to the right and left. In addition there are limits at each end of the travel that when activated stops movement in the respected direction. My problem is that the motor works just fine in the left and right directions but I can only get one of the limit switches to work. I'd appreciate any suggestions.

int PUL = 7; //define Pulse pin
int DIR = 6; //define Direction pin
int ENA = 5; //define Enable Pin
int RGT = 3;
int LFT = 2;
int potPin = A5;
int count = 0;
int interval = 1000;
int val = 0;
int Spd = 500;

#define Limit01 8  // Pin 2 connected to Limit switch out
#define Limit02 9  // Pin 3 connected to Limit switch out

void setup() {
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
  pinMode (ENA, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  if (digitalRead(LFT) == LOW) {  //  If joystick is moved Left
    if (digitalRead(Limit01) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor clockwise

      digitalWrite(DIR, LOW);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);
    }
  }

  if (digitalRead(RGT) == LOW) { // If joystick is moved right

    if (digitalRead(Limit02) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor counter clockwise

      digitalWrite(DIR, HIGH);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);

    }
  }
}


texts: How is stack memory used for fuctions and local variables?

texts:
I wanted to save some values to the EEPROM and also wanted to free up SRAM by avoiding some variable declarations, but EEPROM memory is byte wise.

If I want to store an int value, I have to use some expressions repeatedly. I thought I would make some functions for those. But I am concerned that, if I create a function, it would still occupy SRAM memory, better I declare an int variable instead of using EEPROM.

How are the functions and the local variables stored in SRAM? Does it only store the address of the fuction pointer from the flash memory or all the variables and commands are stored on the stack?


texts: Updating firmware on Adafruit Huzzah ESP8266

texts:
tldr: I'm trying to re-flash a previously working Adafruit Huzzah ESP8266 breakout module to use the latest AT firmware. The re-flash doesn't seem to be working and I'm getting rather confused. This is the first time I've re-flashed one of these modules.

What I did:

I installed the latest version of esptool.py using pip, and downloaded the latest Espressif AT firmware from github. With the Huzzah on a breadboard I grounded GPIO0 and connected the serial port header to my PC using a FTDI cable. VC on the cable is 5v. The red power light lit. I then ran the following commands:

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x00000 boot_v1.1.bin

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x01000 user1.bin

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7C000 esp_init_data_default.bin

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7E000 blank.bin

Each upload seemed to complete ok, but I found that I couldn't upload the next until I pressed the reset button on the module first, otherwise I got the error:

  A fatal error occurred: Failed to connect to Espressif device: Timed
  out waiting for packet header

This doesn't seem right to me.

After uploading all 4 components as above I disconnected GPIO0 and cycled the power on the module. I then tried connecting using putty at 115200 baud but I get no echo back from the module, and it doesn't respond to commands.

Observations:

The module previously worked and I could connect to it with putty.
If I reset it while connected to putty at 115200, I get a consistent pattern of garbage characters, so my guess is its alive but confused somehow.
I've tried connecting at various baud rates: 9600, 14400, 19200, 38400, 57600, as well as 115200. Same result.
I've found walkthroughs that show firmware like node.mcu being uploaded as a single binary. Should I be somehow merging the four bin files into one before uploading the the Huzzah?

What am I doing wrong here?


texts: Serial.println(): Where is the text printed?

texts:
When I used Serial.println() in the code I naively believed I would see the characters that I sent displayed on that little black area just under the interface (just like a terminal).

#include <Servo.h>

int moveServo;

Servo myservo;

void setup()
{
  myservo.attach(0);
  Serial.println("      Hello Earth");
  Serial.println();
}

void loop() {
}

Can someone tell me just where Hello Earth would be displayed?


texts: If an external voltage of 7 volts is applied to the external voltage input on the Arduino and the power from the USB port remains connected, is there a protective circuit that will protect the Arduino?  Thank you.


texts: Debugging arduino shield for varying voltage

texts:
I'm using this motor shield for arduino from adafruit. It says it can drive 4 DC motors with it. However, two terminals M3 & M4 (as marked in the image) seem to be supplying lesser voltage.

To avoid this becoming an XY problem, some more details:

The entire setup consists of an arduino, shield, raspberry Pi 3 & the motors being  powered with a 2200 mAh 12v supply. The raspberry pi is powered from the 5v supply of this shield.

Now the problem as mentioned is that even though M1 & M2 get the 12v, M3 & M4 don't. When I measured they give varying degree of voltage (3v - 6v). I tried disconnecting & connecting various combinations, with & without motors connected, pi removed, etc. All are giving same result. When I supplied 5v as external power, these pins in question dropped to 2v-3v.

As per this documentation, there seems to be a difference in M3, M4 in that they run at 1KHZ, to save power. But my knowledge to make of this info seems to be limited. Can anyone point me to the right direction here?

The complete setup.


texts: Ultrasonic sensor underwater calibration

texts: Does anyone knows how to calibrate AJ-SR04M using the Arduino? I am working on AUV. underwater reading from current code; it is giving continuous 20cm while moving inches. http://shop2.hanjindata1.cafe24.com/product/aj-sr04m-ultrasonic-ranging-module/206/


texts:
I'm trying to use Timer1 to get fired once a certain event occurs (about 1ms after the event). Using the timer to get a periodic interrupt works fine, but the very first interrupt fires immediately, rather than after the time I want it.

#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  Serial.println("start");
}

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  cli();
  TCNT1 = 50000;

  // if (micros() - stack[0] < 500) return; // work around guard would skip stray 1st interrupt

  stack[ctr++] = micros();

  if (ctr > ENTRIES)
    TIMSK1 &= ~(1 << TOIE1);

  sei();
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;
    cli();

    TCNT1 = 64000; // tick in around 1ms
    TCCR1A = 0;
    TCCR1B = (1 << CS10); // no prescaler
    TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt

    sei();
  }
}

When you enter t on the console it enables the interrupt and - unexpectedly - the timer fires at once. The next one comes after 1ms. A sample output looks like

start
testing
0: 8
1: 980
2: 980
3: 980
testing
0: 8
1: 980
2: 980
3: 980

Uncommenting the guard yields

start
testing
0: 988
1: 972
2: 976
3: 976

How can I modify my code (except setting a guard in the beginning of the ISR) so it is triggered once AFTER 1ms.


texts: Why are some of my GSM modules not taking commands?

texts:
I posted a couple weeks ago about having a GSM error. I moved past it and the code seemed to be working on my GSM module (I think a SIMCOM). But then I needed to create some more systems and out of a total of 8 GSM modules, my code and setup only work on two of them - despite the fact that they should be identical and from the same supplier.

The following code (thanks to this genius post) works without error to send and receive SMS on two of the boards:

#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900 = SoftwareSerial(2,3);

void setup() {
  Serial.begin(19200);
  initializeGSM();
}

void initializeGSM() {
  SIM900.begin(19200);
  Serial.println("Turned on");
  SIM900.print("ATEO\r");
  Response();
  SIM900.print("AT\r");
  delay(1000);
  Response();
  SIM900.println("AT+CMGF=1\r");  // set SMS mode to text
  Response();
  delay(1000);
  SIM900.println("AT+CNMI=1,2,0,0,0\r");
  delay(100);
  Response();
  delay(5000);  // give time to log on to network.
  Serial.println("Ready...");
}

void Response() {
  int count = 0;
  delay(1000);
  Serial.println(SIM900.available());
  while(1) {
    if(SIM900.available()) {
      char data =SIM900.read();
      if(data == 'K'){Serial.println("OK");break;}
      if(data == 'R'){Serial.println("GSM Not Working");break;}
    }
    count++;
    if(count == 100){Serial.println("GSM not Found");break;}
  }
}

void loop() {
  RecSMS();
  delay(2000);
}

void RecSMS(){...}

So again, the above code works to set up the module on 2 modules. On the other 6, it simply hangs during the Response() call. SIM900.available() returns 0 and then says "GSM Not Found." So I tried to initialize the TX pin during setup as:

digitalWrite(2, LOW);

Which then gives me a promising SIM900.available() value of about 63, which corresponds to what a confirmation would be. However, when I print the "data" variable containing the byte read off the GSM module/SIM card, I get a couple bits of garbage like the following output:

Has anyone experienced this problem and knows a way to properly initialize the GSM module?


texts: NRF24L01 Transmission Problems between Arduino UNO and Arduino Nano

texts:
I'm a beginner in using NRF24L01 tranceiver module. I tried sending a simple "Hello world" using Arduino Nano and a Arduino UNO with the use of two NRF24L01 modules. I don't get any output in the serial monitor at the receiver side. I checked the wire connection numerous times. Also checked the baud rate of both receiver code and the serial monitor are same and adddresses of the tranceiver code and the receiver code are same. Looking for a solution. Thanks in advance.
This is my tranceiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}
void loop() {
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay(1000);
}

And this is my Receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}


texts: Piezoelectric buzzer interfacing with arduino without using any library

texts: I want to learn programming from the roots, so i have started learning interfacing different modules with arduino without using any libraries. i want to learn how to interface piezoelectric buzzer with arduino without library. i got to know that tone()library uses arduino internal timers but i dont know how. can anyone briefly explain how to do it.


texts:
I want to rotate a gearwheel with a stepper motor. While Arduino is on everything is well.

My gearwheel transfer its power to a gear worm. The worm will go 10th cm and back repeatedly. When I cut the power, Stepper Motor stops where its last step and position. When the power is on Stepper starts from last position but steps starts from the first step.

Assume that 2038 steps are rotating the Motor one revolution. For example, when 1500 step pass and power cut. Worm is on 6th cm now. And the power is on. Stepper is working from 6th cm and is going 2038 steps. Now it is on 16th cm.

If I use servo, when the power is on, I can write the motor to the 0 position. But I have to use stepper motor. How can I fix this?

Stepper Motor: 28 BYJ 48
Driver: ULN2003A

The cod is here;

int State;
int Wait;

void setup() {

  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);

  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);
  State = 8;
  Wait = 2;
}

void loop() {

  turnRight(2038);
  delay(1000);
  turnLeft(2038);
  delay(1000);

  }

void turnRight(int Step) {
    for (int i = 0; i < Step ; i++){
      digitalWrite(State,HIGH);
      delay(Wait);
      digitalWrite(State,LOW);
      IncreaseState();
    }
}

void IncreaseState() {
  State++;
  if (State==12){
    State=8;
  }
}

void turnLeft(int Step) {
for (int i = 0; i < Step ; i++){
      digitalWrite(State,HIGH);
      delay(Wait);
      digitalWrite(State,LOW);
      DecreaseState();
    }

}

void DecreaseState() {
  State--;
  if(State==7){
    State=11;
  }
}


texts: Analog output gives a close range of values

texts:
I try to get a good range of values from VMA309 sound sensor.

However, when I connect it properly it gives me a range of values  +/-5 like below. The documentation says it should give numbers between 0 and 1024.

I turned the potentiometer both sides all the way and that only changed the number, but it keeps gives number in a range of 5 numbers:

An example:

626
623
624
624
624
624
623
624
624

My code:

int sensorPin = A5;
int sensorValue = 0;
void setup ()

{
  Serial.begin (9600)  ;
}

void loop()
{
  sensorValue = analogRead(sensorPin);
  delay (500);
  Serial.println (sensorValue, DEC);
}

What am I doing wrong here?

An image of the wires:
I also tried the wiring directly without a breadboard. But that gave the same results.

I used the code as given from the VMA 309 documentation.


texts: Measuring frequency of 3-wire 12V fan on Arduino Uno

texts:
I am using a PC 12V fan (40x40mm), which I control speed with voltage (with adjustable power supply). I would like to measure the frequency of the fan with Arduino and read it on serial monitor.

I've googled over some results and I came across pulseIn(), which I don't quite understand. I've also used this code, which I found here, but it doesn't work for me. I've added serial.print and delay line.

My output of this program is: "0000000" etc. and nothing else.

My goal is to set the frequency of the fan to around 50-500 Hz somewhere.

int pin = 7;
unsigned long duration;

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

void loop()
{
  duration = pulseIn(pin, HIGH);
  Serial.print(duration);
  delay(1);
}

My schematics:


texts:
I have 2 Arduino Mega 2560 connected via USB to my Ubuntu 18.04 machine. When I boot, one connects to /dev/ttyACM0 and the other connects to /dev/ttyACM1.

Communication works perfectly. However, randomly on boot, the Arduino boards connect to the opposite port of what is coded into the script. I use Python 3.6 to communicate with the boards.

Is there any way to force these boards to always connect to the same port? Or is there a way for Python to detect the board that it's talking to?


texts: Can't upload sketches to breadboard Arduino

texts:
I have an ATmega328 chip with the boot-loader installed.
I also have an Arduino Uno with the ATmega328 chip removed.
I hooked this chip up to a breadboard with the proper 22pF caps, 16MHz crystal, and 10kΩ pull-up resistor.
The LED flasher was loaded prior, and this works fine when I hook an LED and resistor up to pin 19. I have confirmed my external crystal works by disconnecting it, and the flashing stops, when I reconnect the crystal, the flashing continues.
Power is fed from my Arduino Uno 5 V out to the DIY Arduino
I connected the reset wire, and data wires, ensuring pin 2 went to RX and pin 3 to TX.

In the software

First to confirm everything works, I removed the chip from the breadboard and placed it in the Arduino. The sketch uploaded successfully using the settings:  Arduino Uno as board and AVRISP mkll as programmer.

Now I move the chip to the breadboard, and ensure all the wires are connected. The LED starts to blink again, but when I try to upload the sketch, I get an error:

avrdude: stk500_recv(): programmer is not responding

I ensure continuity between the reset, TX, RX, and power connections and try different settings like Arduino as ISP and different boards under settings including the Duemilanove and nano but nothing seems to be working.

Any suggestions on what to try next?


texts:
I'm trying to connect to an http server that uses HTTP 1.1, my problem is that even thought the request is in HTTP 1.1 format and the server does actually use HTTP 1.1(I tried it in a browser) it only responds with HTTP 1.0. I'm using this modified example of the web client, I updated the Ethernet library yesterday and for my server I'm using Node 8.4.0, I'm testing with google first even though I know the server can respond with HTTP 1.1.

Ethernet shield model: Han Run HR911105A 16/02

Arduino: Mega 2560

 This sketch connects to a website (http://www.google.com)
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe, based on work by Adrian McEwen

 */

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
  client.print("GET / HTTP/1.1\r\n");
  client.print("Host: www.google.com\r\n");
  client.print("Content-Type: application/x-www-form-urlencoded\r\n");
  client.print("Cache-Control: no-cache\r\n");
  client.print("\r\n");
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
}

With this I get the following response:

Thank you in advance


texts: Why doesn't this work on a Mega2560 although it works on an Arduino Uno

texts:
So, This is your code slightly altered. I am using it to read the readings of the roll and pitch of a quadcopter. I have tried using this code for a mega 2560 but it does not work in ports A0 and A1. I think it might in A5 and A6 but I am unsure how to alter this code.
THank you,
Rohan Paleja

/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */

#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[2]; // times of prev. rising edges
volatile unsigned long rcTimes[2]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter
int Roll, Pitch;
// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt

  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(9600);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[2]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    Roll = rcTimes[0];
    Pitch = rcTimes[1];

    sei();          // reenable interrupts

    Serial <<  " " << Roll << " " << Pitch
       << " "  << rcN << endl;

  }
  sei();            // reenable interrupts
  delay(1000);
}


texts: Multiplication, division. What is wrong?

texts:
const unsigned long C1 = 30 * 1000;
const unsigned long C2 = (300 * 1000)/C1; // must be = 10

void setup() {
  Serial.begin(57600);
  Serial.println("\n-------");
  Serial.print("C1 = "); Serial.println(C1);
  Serial.print("C2 = "); Serial.println(C2);

  unsigned long V1 = (300 * 1000)/C1;   // must be = 10
  Serial.print("V1 = "); Serial.println(V1);

  long V2 = (300 * 1000)/30000; // must be = 10
  Serial.print("V2 = "); Serial.println(V2);

  int V3 = (300 * 1000)/30000; // must be = 10
  Serial.print("V3 = "); Serial.println(V3);
}

void loop() {
}

Arduino UNO printed in monitor console:

C1 = 30000   (ok)
C2 = 143164  (must be = 10)
V1 = 143164  (must be = 10)
V2 = 0       (must be = 10)
V3 = 0       (must be = 10)

What is wrong?


texts: unexpected change of ADC value with multiple voltage dividers (thermistors and pot)

texts:
So this is my basic circuit. Three voltage dividers: one 10k pot, 2 thermistors. Fan driver circuit using TIP120 (currently just driving an LED from the 3.3v source). Board is a Leonardo clone, circuits.io only had the Uno in their library. Edit: circuit is now more simplified.

Schematic:

reality:

When I adjust the pot, the ADC value of airPinValue changes, regardless of which analog input it is connected to. meatPinValue does not change. Swapping the inputs that airTempPin and meatTempPin are assigned to has no effect, airTempPin changes the same. Physically swapping the thermistors has no effect, nor does switching which input they connect to.

Code:

#define potPin A0
#define airTempPin A5

int potValue = 0;
int airPinValue = 0;
int i = 0;

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

void loop() {
  i++;
  potValue = analogRead(potPin);
  airPinValue = analogRead(airTempPin);
  if (i == 2000) {
    Serial.print(potValue);
    Serial.print(",");
    Serial.println(airPinValue);
    i = 0;
  }
}

EDIT: much simplified code

EDIT v2.0 : I have now swapped out the board for an official Uno, as well as swapped everything to a different breadboard and a different Leonardo, with no change in behavior.

EDIT v3 : Corrected code sample. I have also dropped my DMM onto this, reading from the 5v rail to the voltage going to A2. With the pot set to 0 I see 2.401v from the divider, pot to max, same voltage, 2.401v.

EDIT v4: with only the pot and airTemp hooked up, still happens. Further DMM probing actually shows that this only happens when the pot and thermistor are both hooked up to the arduino. If either one is disconnected, the voltage being read by airTempPin is stable/correct. Once both are hooked up to the analog pins on the arduino, that's when the voltage at airTempPin goes off...

Also update diagram, pic, and code to match what I'm currently testing with.

EDIT v5 : This is some sort of analog bleed between the analog input ports. Not really sure how I can combat this :\


texts: RTC 1307 when connected to a relay via Arduino Nano

texts:
I was posting a question but to be completely sure i did some more tweaking in the code and solved at least functionally my problem.

I decided to post it anyway to have suggestions for a better solution and / or help whoever has the same problem.

The project is a flowers watering application.
I set up an RTC connected with Arduino Nano using LEDs to simulate the operations, it works really well, no mistakes when RTC.readTime requests.

Once satisfied I replaced the LED with a relay to be connected to the pump, and then the problem appeared:

Randomly the reading is not correct, something like (YYYY/MM/DD H:M:S) represented as 165/0/165 0:165:0.
The combinations of 165 and 0s are completely random but only 165 and 0s are present.

My solution was to check after each reading if there was any 165s into the returned data, and if yes, read the time again. This was the medicine.
This mistake appears only and always when i replace the LED with a relay, with or without connected charge.

Circuitry is very simple as well as is the code.

  RTC.readTime();
  if (RTC.h == 165 ||
      RTC.m == 165 ||
      RTC.s == 165 ||
      RTC.dd == 165 ||
      RTC.mm == 165 ||
      RTC.yyyy == 165 ) {
        RTC.readTime();
        Serial.print("Mistake found in step N. ");
        Serial.println(countCycles);
  }

  countCycles ++;

From the printout I can confirm that the mistake is absolutely random but never immediately subsequent to another mistake.
Any clues?
Thank you for any comments


texts:
I'd like to be able to use Python from a sketch. According to the Arduino playground, one can use PySerial from a computer to talk with an Arduino via Python.

It looks like from that page you can also use various API's to use Python with an Arduino from a computer. However, I'd like to know if you can execute Python directly from a sketch. It would be nice because then you could execute Python directly from a sketch, and not all of it would have to be written in Python.

If this is not possible, is there an easy way to execute Python on an Arduino? Looking at the various API's it was hard to determine exactly what they did, and if you could execute a .py script from a computer or from anything on the Arduino.


texts:
I use this simple HTTP Post request to post some values on my API from Arduino using Switch. each time I push the switch it send a different values to API.

void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post).
The fourth and the fifth posts also works fine but the sixth is same as the third.
Knowing that my API works 100% with Raspberry Pi and it has no errors.

The same thing for PUT and GET.

After Edition:
After I remove the port number from the host line and using strlen(data)instead of sizeof(data), the POST request works but only for first 7th posts. The output of serial monitor on Arduino is like that:

Attempting to connect to WPA SSID: WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.149
signal strength (RSSI):-66 dBm

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...
connected to post server

Starting connection to post server...

Starting connection to post server...

Starting connection to post server...

Before the Editing, it was always giving me "connected to post server" and It always posts but as I told you before It takes a lot of time at the 3rd 6th 9th 12th ..... Now after the 7th post it will not posts.


texts: 1.8 in tft lcd background goes light when tft.drawPixel(), what is wrong?  Using 7735 wit uno.  The background is the desired black after writing.


texts:
I am trying to use a for loop for getting readings on two parallax ping sensors and want to find the difference between both readings.
But am having trouble doing so. Whenever I declare print ping(1), I don't actually get the value of ping(1). How can I have two variables for ping(0) and ping(1) that I can call whenever I want and have them be accurate.
Code

int ultraSoundSignalPins[] = {5,7};
int tx = 4;
char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to indicate direction

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

void loop()
{

 unsigned long ultrasoundValue;
 for(int i=0; i < 2; i++)
 {
   ultrasoundValue = ping(i);
   Serial.print(pingString[i]);
   Serial.print(ultrasoundValue);
   Serial.print("cm, ");
   delay(500);

 }
}

//Ping function
unsigned long ping(int i)
{
 unsigned long echo;

 pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
 pinMode(tx, OUTPUT);
 digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
 digitalWrite(tx, LOW);
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
 digitalWrite(tx, HIGH);
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
 pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
 echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
 return (echo / 29.1); //convert to CM then to inches
}


texts: analogRead() output oscillates even though the pin is grounded

texts:
I'm using Arduino Micro to read from 5 flex sensors and display the corresponding angles to the Serial monitor. I am currently having quite some problems with the oscillating values I am getting from the analogRead(). It doesn't seem to matter whether the pin is connected to a flex sensor or just grounded - the output is oscillating a lot.

Originally everything was being read and outputted just fine but I wanted to have an exact 100Hz sampling frequency and tried to play a bit with Timer Interrupts. And that's when this oscillating behaviour started. I reversed to my original code, which just uses some delay(), and simplified to only read from two pins, but cannot seem to shake off the oscillations.

I think I may have messed up something about ADC when trying to implement Interrupts, but I don't know how to check it or fix it. Please, help me figure out how to fix this!

This is the raw output of analogRead. The drop in values occurs when I bend the flex sensor:

And this is the resulting calculated angle. Also oscillating:

This is the code I've been using to read the pins:

int fin;
const int input[5] = {A0,A1,A2,A3,A4}; // the analog pins

int flex[5]; // analog signal read
float flexV;
float flexR[5]; // resistance on the 47k resistor
int angle[5]; // joint angles

const float VCC = 4.98; // Measured voltage of Arduino 5V line
// Measured resistance of the 47k resistors R1-R5
const float R[5] = {45900.0,45900.0,45900.0,45900.0,45900.0};

// Calibration values of resistance measured during straight phase and 90 deg bend phase
const float R_STRAIGHT[5] = {37651.0,37651.0,37651.0,37651.0,37651.0};
const float R_BEND[5] = {71783.0,71783.0,71783.0,71783.0,71783.0};

void setup() {

}

void loop() {

  for(fin = 0; fin <= 4; fin++) {
   flex[fin] = analogRead(input[fin]);
   flexV = flex[fin]*VCC/1023.0;
   flexR[fin] = R[fin] * (VCC/flexV - 1.0);
   angle[fin] = map(flexR[fin],R_STRAIGHT[fin],R_BEND[fin],0,90.0);
   delay(1);
    }
    Serial.print(angle[0]);
    Serial.print(" ");
    Serial.print(angle[1]);
    Serial.print(" ");
    Serial.print(angle[2]);
    Serial.print(" ");
    Serial.print(angle[3]);
    Serial.print(" ");
    Serial.print(angle[4]);
    Serial.print(" ");
    Serial.println(millis());
    delay(6);
}


texts:
I've bought a module which should communicate via serial RX/TX. The module and code are described here: https://www.dfrobot.com/wiki/index.php/Weather_Station_with_Anemometer/Wind_vane/Rain_bucket_SKU:SEN0186.

I've hooked up everything as described (using an Arduino Nano instead of an Uno, but the rest is the same) and now trying to get things to work. I could not get any decent output. So I decided to switch to a bare-minimum program to read stuff from the serial port in order to see whats going on. I found the following sample: https://gist.github.com/Protoneer/96db95bfb87c3befe46e and implemented this code (only this).

Now what I see is the following:
- With RX/TX connected the wrong way, when I reset the nano, the serial monitor shows me one instance of the string I'm looking for (as described in the module documentation). When connected the right way, the text is not there but that's to be expected as the nano should receive it (and not the serial monitor). This does however prove that the module is actually sending data.
- Serial.available seems to evaluate to 0 all the time, indicating there is no data to be read from the serial line.

So why would Serial.available return 0 even though there seems to be data being sent to serial, as the monitor does show the string I'm looking for with the pins crossed. I have also tried disconnecting the RX line on the module to prevent statements being sent over serial to interfere with the module. The documentation does not state the need to send anything to the module in order to trigger the response. In fact, if you look at the sample code the first interaction with serial (after Serial.begin(9600)) is Serial.available().

Is there anything else I can do from a debug perspective? As you might notice I'm no expert in this stuff.


texts: Set up mesh network with RF Transceivers

texts:
I would like to set up a mesh network of Arduinos with the following features/capabilities:

No master node
Arduinos capable of bootloading other Arduinos through RFs
Capable of communicating over TCP/IP
More than 255 possible network addresses

Is this possible, or infeasible? If it is, what are some software packages that meet these requirements. I was looking at RF24Gateway, RF24Mesh, RF24Network, etc., but as far as I can tell these require having a master node, and they only support 255 IP addresses. Is this correct? I was also looking at an Optiboot clone that works with RF24 modules here but it seems like it requires the other Arduino to be connected to a USB.

Any suggestions/clarifications are appreciated. Thanks!


texts: Unable to initialize W5100 using Arduino Pro Mini

texts:
I am unable to initialize a W5100 module using an Arduino Pro Mini. I try setting the MAC and IP addresses but read invalid values thereafter.

Here is the Arduino program along with the output:

void setup() {
    uint8_t mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    uint8_t local_ip[] = {192, 168, 1, 100};
    Ethernet.begin(mac, local_ip);
    printMacAddress(); // OUTPUT: FF:FF:FF:FF:FF:FF
    printIpAddress(); // OUTPUT: 255.255.255.255
}

void printMacAddress() {
    uint8_t mac[6];
    W5100.getMACAddress(mac);
    Serial.print(mac[0], HEX); Serial.print(":"); Serial.print(mac[1], HEX); Serial.print(":");
    Serial.print(mac[2], HEX); Serial.print(":"); Serial.print(mac[3], HEX); Serial.print(":");
    Serial.print(mac[4], HEX); Serial.print(":"); Serial.print(mac[5], HEX); Serial.println();
}

void printIpAddress() {
    IPAddress ip = Ethernet.localIP();
    Serial.println(ip);
}

I read in some blog posts that the Arduino may initialize before the W5100 initialization is completed so others recommend manually resetting the W5100 after Arduino initialization.
So I connected the W5100 reset pin to the Arduino digital output 4 and reset the W5100 during setup using the following code.

const int W5100_RESET_PIN = 4;
pinMode(W5100_RESET_PIN, OUTPUT);
digitalWrite(W5100_RESET_PIN, LOW); // Activate reset pin by asserting low
delay(5); // Wait for 5 msec
digitalWrite(W5100_RESET_PIN, HIGH); // Deactivate reset pin by asserting high
delay(300); // Wait for W5100 to initialize[/code]

I observed the W5100 resetting because the module LEDs flashed off and back on each time I manually reset the Arduino. However this does not fix the W5100 mac/IP initialization issue.

How should I troubleshoot this issue?

Here are pictures of the assembly.
https://imgur.com/a/h4TWx

Here is an overview of the W5100 module.
http://arduino-info.wikispaces.com/Ethernet


texts: Powering Arduino Uno R3 with battery packs

texts:
I am using Arduino Uno R3 with MPU 6050 for a personal project. MPU 6050 is being powered by the 3.3V supply pin in the Arduino board.

In order to make the sensor mobile, I ordered this battery, which has one power output of 5V 1Amp that I plan on plugging into the Uno's USB Power/Data Outlet.

I know that when plugged into the computer via the same USB port, around 5V 500 mA is supplied. I was wondering if someone could tell me, whether the 1A battery that I ordered would burn my board or not.

Also, is there a built in fuse inside this board?


texts: Connecting TFT Display MI0283QT-9A to ESP32

texts:
I have purchased a MI0283QT-9A TFT display (https://download.mikroe.com/documents/add-on-boards/other/display/tft-proto/tft-proto-manual-v200.pdf) which is
driven by the ILI9341 display controller.

I've managed to find the following board specification: http://pub.ucpros.com/download/tft_320_240_mi0283qt_9a_v1_3_spec.pdf

First of all, the pins are named differently from all the examples I can find for connecting it to my ESP32 microcontroller. For example, the TFT specs describe:

33 SDO Serial Output Signal
34 SDI Serial Input Signal
35 RD Read execution control pin
36 WRX(D/CX) Write execution control pin ; Serial Register select s Signal
37 D/CX(SCL) Register select signal; Serial Interface Clock
38 CSX Chip Select Signal
39 TE Tearing effect out pin synchronize MPU to frame writng

But this Adafruit ILI9341 example (https://github.com/adafruit/Adafruit_ILI9341/blob/master/examples/graphicstest/graphicstest.ino) talks about CS, DC, MOSI, CLK, RST, and MISO.

I think these map as follows, can anyone confirm that?

ESP32 = TFT
--------------
DC    = RS
CLK   = WR, although maybe it should connect to DC???
CS    = CSX
MOSI  = SDI
RST   = RST
MISO  = SDO

I'm really unsure about the first two!

Second, in the PDF it refers to note 1 on page 11:

So as far as I can tell, I need to set the voltage high/low on the four IM* pins, depending upon the interface I want to use. So the second question is which interface does the Adafruit ILI9341 library use?


texts: Using voltage divider to read voltage from sensor

texts:
Good morning,

I would like to use an Arduino Duemilanove to read the voltage signal generated from a current sensor (CSLA2CD). The datasheet for this sensor can be found here.

The problem is that the sensor requires a supply voltage of 6 to 12v. The signal output voltage is half the supply when no current flows through the sensor. I am using a 8v regulator for its supply, so the signal voltage may range from 4v (no current sensed) all the way to about 6v (about 60 amps).

Unless I'm mistaken, the arduino's analog pin can detect from 0v to 5v. So it would only accurately provide me data up to the 5v signal mark.

My questions are:

Would a voltage divider be a good solution to reduce the signal voltage to a range the Arduino can read? If so,
what would be the best resistor combination to use?

If there are better solutions than a voltage divider then please share.

Thanks very much!


texts: I have built a system using arduino and Ethernet shield. It gets rgb values through URL and changes an rgb led's value. Today I bought an ESP 8266 12E. I want to change to wifi but I cannot find an arduino library that uses spi to connect the arduino to the ESP. I do not want to use only the ESP. Do you know any libraries to do the job or any tutorials.


texts:
I am working on an art project that involves a garage door opener.  I am very new to Arduino, and electronics.  I have a starter kit with a ton of accessories.

The garage door opener has 2 screws (terminals?) designed to connect a button.  If I touch a wire between them, the opener will start.  I connected a button to my bread board, and ran wires to those terminals on the opener to see if a simple switch would work, and it does.

I want to:

press a button, and the Arduino connects the terminals on the opener, and then it starts
button is then ignored (delayed) for a set amount of time (5 seconds for this example)
after the set amount of time, the button works as normal (like in step 1)

I ran through some tutorials on buttons, and I think I got ahead of myself.

I can turn on an LED from a switch on the bread board, and use a delay(5000) to ignore any other button presses.  I tried to connect the wires that were going to LED to the 2 terminals on the garage door opener, and it did not work
In code, I setup pin 5 as OUTPUT, and pin 6 as INPUT.  I used the button to send a HIGH on pin 5, to see if that signal would work when connected to the 2 terminals on the opener.  I tested this a bit in code by reading the state of pin 6, and it appears to have worked.  However, it did not work when I connected both pin 5 to one terminal, and pin 6 to the other.

I tried looking for a simple example, but searching for garage door openers and Arduino results in too many tutorials on how to do super fancy wireless stuff.  I just want to ignore a button press for 5 seconds after it has been pressed once.

I'm looking for a simple example that allows my button to tell the Arduino to make that connection on the garage door opener.  I guess I'm looking for my Arduino to act like a switch instead of my (physical) switch?

My Arduino kit comes with a bread board, wires, switches, Uno R3 and tons of other stuff I haven't gotten to yet.  I apologize in advance if I'm not thinking of something super-simple that would solve my problem.  I'm very new to this.

Thanks for your time!

Edited for spelling.  Elaborated on my attempts.  I'm going to read about what a relay is.


texts:
I have this really simple code.
Let's say I have a variable X.
Then all I want to do is create a random value R, if R > X then I want X to become R.
But for some reason, my n_of_buttons_pressed climbs up and then sometimes drops back to lower values. I can not wrap my head around how it could get a lower value then a previous value.

#define N_OF_BUTTONS 60

int n_of_buttons_pressed;

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

void loop() {

  n_of_buttons_pressed = (int) max(random(0, N_OF_BUTTONS), n_of_buttons_pressed);

  Serial.print("n_of_buttons_pressed:");
  Serial.print(n_of_buttons_pressed);
  Serial.println();

  delay(100);

}


texts: 16Hertz Uno R3 Board vs Arduino Uno R3 Board

texts:
I bought a 16Hertz Uno R3 Board. When I installed the driver and the Arduino IDE,  in the IDE`s menu I saw:

  Tools -> Board -> Arduino Uno

was selected by default which is great, but...

  Tools -> Port -> COM3(Arduino Mega or Mega 2560)

was selected by default which I think might be some kind of misunderstanding...

When I chose:

  Tools -> Board -> Arduino Mega or Mega 2560

On that tools menu appeared new menu "Processor" with two options:

  Tools -> Processor -> ATmega2560 (Mega 2560)

which was selected by default and there was another option

  Tools -> Processor -> ATmega1280

When I restore Tools -> Board settings back to "Arduino Uno" the "Processor" menu with the two options disappeared and Tools -> Port setting did not changed!

If you take my board and look at the Microcontroller there is written:

  ATMEGA328P-PU

Also on that board is written:

  16HzUNO

I need to know:

What does 16Hz mean? Does it mean the clock or frequency of this
Microcontroller? I think it does not, if I try to find out details of my Microcontroller on the rs-online site, there is written:

  ATMEGA328P-PU, 8 bit AVR Microcontroller 20MHz 1 kB, 32 kB Flash, 2
  kB RAM, I2C 28-Pin PDIP

Why was there "COM3(Arduino Mega or Mega 2560)" written on the
Port's menu?
Is my 16Hz Uno R3 and the Arduino Uno R3 board the same? Which one
is better? When one of those is better?
Does the standard Arduino Uno R3 board have the same ATMEGA328P-PU
Microcontroller?


texts:
My project is to use an Arduino to control the lighting of a small apartment. My preferred option is to replace each wall light switch with a 4x4 membrane keypad (https://www.amazon.co.uk/Mirocle-Matrix-Membrane-Keyboard-Arduino/dp/B01LMU6OPG/ref=sr_1_19?s=electronics&ie=UTF8&qid=1504376458&sr=1-19&keywords=membrane+keypad). The UX would allow any keypad to control any light, eg. pressing 1-4 will set light 1 to brightness 4.

The problem I have is this will result require 4 x 8 = 32 pins, so I'm looking for alternatives.

So my questions:-

1/ Is there a simple pll to serial converter that I should be using to interface the keypads?

2/ Can I wire multiple keypads onto the same set of 8 pins? Only one keypad will ever be touched at one time.

3/ Are there simple serial versions of the classic membrane keypad.