texts: RFID/NFC (13.56 MHz), is it possible to send raw bytes and receive response?

texts:
I'm trying to implement a card reader (i.e. credit cards) for shopping purposes, and AFAIK those cards are ISO 14443-A compliant (Mifare Classic 1K). I already made an Android app that can send custom APDU to read specific sectors by using raw SendBytes().

Since I need to build a circuit with a custom antenna, I chose Arduino-uno with a NFC module (was thinking about StrongLink SL013), I wanted to know if it's possible to send raw bytes and receive the response from the tag. I only found some higher-level implementation (readSector, writeSector and so on).


texts: SPI Temperature sensor interface with Arduino Uno

texts:
I want to interface with an AD7314 Temperature Sensor. I want to only read the temperature value from the sensor and output the value on to 8 LEDs connected to the Arduino. But so far I have not been able to read from the sensor. The datasheet says that the temperature readings are in 10 bit 2's complement, so I plan to convert to 8 bit before putting it out on the LEDs. Here is my code so far.

I am new to SPI and clearly don't understand the temperature sensor's datasheet. Please can anyone elaborate or explain where I am going wrong?

Note: I have chosen pin A0 (PIN 23 of ATMEGA328P) as slave select and not pin 10

#include <SPI.h>

byte val;

void setup (void) {
  pinMode(0, OUTPUT); //LED 1
  pinMode(1, OUTPUT); //LED 2
  pinMode(5, OUTPUT); //LED 3
  pinMode(6, OUTPUT); //LED 4
  pinMode(7, OUTPUT); //LED 5
  pinMode(8, OUTPUT); //LED 6
  pinMode(9, OUTPUT); //LED 7
  pinMode(10, OUTPUT);//LED 8
  pinMode(11, OUTPUT); // MOSI
  pinMode(12, INPUT); //MISO
  pinMode(13, OUTPUT); //CLOCK PIN
  digitalWrite(A0, HIGH);  // ensure Slave select stays high
  SPI.begin ();
  Serial.begin(9600);
} // end of setup

void loop (void) {
  // enable Slave Select
  digitalWrite(A0, LOW); // enable communication with slave
  delay (0.425);// wait for conversion
  val = SPI.transfer(0x00);// read from sensor
  Serial.println(val); // display reading on serial monitor
  // disable Slave
  digitalWrite(A0, HIGH);
}


texts: How to monitor 12 V LiPo charging from Arduino

texts:
What's the safest way to determine a lithium-ion polymer battery's discharge and charging state using an Arduino?

I see a ton of 12 V LiPo batteries like this being sold on eBay and elsewhere.

They have a built-in charger, and I'd like to use one to power an Arduino, but the Arduino needs to know "when" the battery needs to be charged, and "when" the battery is fully charged. Unfortunately, the battery doesn't expose any pins or LEDs or other outputs that I could tap into.

I've found a few LiPo charging circuits specifically designed for the Arduino, but they all can only handle 3.7 V cells.

I'd like to avoid having to disassemble the battery or modify it to allow me to monitor its state. Is there an easier way, like connecting a battery lead to an analog pin and measuring voltage, or using a coulomb counter?


texts:
I'm trying to connect a FLIR Lepton to an Arduino Due. A thread by pureengineering talks of rerouting some pins. I am not sure what they precisely mean.

Does this rerouting mentioned in the link also apply to Arduino Due?


texts: SparkFun ESP8266 find out when on battery power and when charging

texts:
For one of my projects I use the SparkFun ESP8266 board with an additional LiPo battery in cases power supply goes down.

Now I would like to communicate the power loss - or the fact that the board is running on battery power via WiFi.

Is there a way to find out (in code) when the board switches from mains power to battery and back?


texts: Is every Arduino comes with onboard compass?

texts: The doubt was came in mind after seeing Arduino documentation. I have to turn my Arduino uno robot 20 degrees without using encoders. So I surfed on Internet for how can I do that. Interestingly I found the reference available on above link. They are not saying about any specific Arduino board. So I have to know that can I do this stuff on my Arduino uno? Also I have to know is that every Arduino comes with onboard compass?


texts:
I'm using a -12E with three light sensors and a sketch I've successfully used with an Uno.  I cannot get the -12E to print anything but 0 or 1023 for a light level (0 when I connect the grounds, 1023 without grounds).

I've successfully printed from a single light sensor but now I'd like to try three.

I'm curious to know what I'm missing.  Any guidance would be appreciated.

Code is as follows:

const int photocellPin_0 = 16; // D0
const int photocellPin_1 = 5; // D1
const int photocellPin_2 = 4; // D2
int photocellReading_0;
int photocellReading_1;
int photocellReading_2;

void setup() {
  delay(4900);
  Serial.begin(115200);
  Serial.println("Startup");
  delay(100);
  pinMode(photocellPin_0, INPUT);
  pinMode(photocellPin_1, INPUT);
  pinMode(photocellPin_2, INPUT);
}

void loop() {
  delay(1000);
  photocellReading_0 = analogRead(photocellPin_0);
  photocellReading_1 = analogRead(photocellPin_1);
  photocellReading_2 = analogRead(photocellPin_2);
  Serial.println("-----NEW ON READING-----");
  Serial.print("Photo Sensor #1 = ");
  Serial.println(photocellReading_0); // the raw analog reading
  Serial.print("Photo Sensor #2 = ");
  Serial.println(photocellReading_1);
  Serial.print("Photo Sensor #3 = ");
  Serial.println(photocellReading_2);
  delay(5000);
}

This is based on an adafruit sketch I pulled off of some website (modified for three photo sensors) and I'd credit it if I could recall exactly where I got it from.


texts: What are the best GPIO pins to use for my project?

texts:
I'm working on a home automation project to control my Sommer Base+ garage door opener through Home Assistant.

The project consists of a WeMos D1 Mini with two reed switches (to detect door open/closed) and a 5V relay to control the door opener.

When the door is open the 'top / open' switch is triggered, giving a status of open. Likewise when the door is closed, the 'bottom / closed' switch is triggered, giving a status of closed. When neither switch is triggered (i.e. when the door is in motion), the status is either opening or closing, depending on the previous status.

This works fine unless the WeMos is powered up while either reed switch is closed (so if the door is open or closed).

I know this is because D3 and D8 GPIO pins for the open/close sensors and those can put the device into boot mode (I think that's what it's called).

What I want to know is which pins are the best to use for this project.

Is it possible for me to just change to pins ?? and ?? without needing to update my code?
Is it possible that the WeMos D1 Mini isn't a good fit for what I want?


texts:
In the Arduino IDE: How can I get the line numbers shown in a sidebar of the editor?

It is hard to find which line my errors are referring to without them...

I am using Arduino IDE on a form of Windows.


texts: Can I receive data on the Arduino by sending data to /dev/ttyACM0?

texts:
I'm working on a Raspberry Pi connected to an Arduino.
When I execute

echo 'Hello' > /dev/ttyACM0

, the Arduino receives the data, as indicated by its LED. How can I read the data on the Arduino and process it?


texts: How to upload one program into several Arduinos at once?

texts:
I am trying to upload a single program to a number of Arduinos one by one. But it is time consuming. So I would like to know if there is any way to upload the code at once to multiple Arduinos.

I have tried as follows:

3 Arduino with all the Rx, Reset, Vcc, Gnd line connected to each other. Only pin left is Tx line. So I just connect the Tx line of one arduino and program it and so on.

Is there any other way?


texts: Esp8266 not responding to GET request from Android app created using MIT App Inventor

texts:
I hope I am posting this question in the right section.
I am making a Smart Home Project for my college semester finals. I am using an Atmega328p microcontroller along with an ESP8266 (Esp 01). The Atmega328p controls all the sensors and actuators and sends the data to Esp01 via serial communication.

I have created a web server on the Esp01 which I plan to access by creating an app using MIT App Inventor. My GET request is of the format "http://192.168.43.42/4" where the digit at the end is data I want to send to the server and the response I get from the server is of the format "12&0&34.8" where the '&' is used to separate different values.

My problem is , when I access the server from Chrome in my laptop I get the desired response but when I access it using the App , I get an error "Error 1101 :Cannot find the specified URL". The Esp01 is connecting to a hotspot from my phone and I have checked the IP assigned to the Esp01 to ensure my GET request is correct.

The code for Esp01 in Arduino IDE is here : https://gist.github.com/TheMagicSmoke/467d6227d670697464038056e22f302d

The blocks for the app made in App Inventor is below:

The GET request URL when entered from Chrome in laptop returns a blank page at first but upon refreshing Chrome I get the desired response I told earlier. And in the app , I have used a timer which queries the server with the same GET request every 2 seconds. But when I open the App the error keeps on popping up. Please suggest me a solution, I have googled this without any success.


texts: I am trying to connect a mfrc522 module with nodemcu. I have tried all tutorials available in youtube. Everytime it shows firmware version: 0x89 (unknown}.


texts: Not able to find right library for MPU9250

texts:
I am using an Arduino Uno and learning to use the motion sensor. Currently I was not able to find the library which looks simple and would like to get your suggestion. I found this https://github.com/hideakitai/MPU9250 library to be simple but don't know how to use it.

For example, take this code:-

#include "MPU9250.h"

MPU9250 mpu;

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

    Wire.begin();

    delay(2000);
    mpu.setup();
}

void loop()
{
    static uint32_t prev_ms = millis();
    if ((millis() - prev_ms) > 16)
    {
        mpu.update();
        mpu.print();

        Serial.print("roll  (x-forward (north)) : ");
        Serial.println(mpu.getRoll());
        Serial.print("pitch (y-right (east))    : ");
        Serial.println(mpu.getPitch());
        Serial.print("yaw   (z-down (down))     : ");
        Serial.println(mpu.getYaw());

        prev_ms = millis();
    }
}

Some values are not defined here, like registration code and input pins. I am not used to reading the documentation code so might need help in that.


texts: Problem in bootloading 328p using Arduino as ISP. Please help me in figuring out the problem.I have uploaded the verbose below

texts:
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

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

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

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x000000 (retrying)

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

avrdude: Device signature = 0x000000 (retrying)

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

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

avrdude done.  Thank you.

Error while burning bootloader.


texts: Put ATmega328 in very deep sleep and listen to serial?

texts:
I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options.

So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up.

I am using a custom PCB (not the UNO), with ATmega328p.

Setting the chip to deep sleep:

 set_sleep_mode (SLEEP_MODE_PWR_DOWN);
 sleep_enable();
 sleep_cpu ();

would not wake it up with serial communication,according to this.

You will need to put it in IDLE mode, to listen to serial, but this would consume a few mA -bad.

I have found this link where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins.

I also read this article of Gammon, where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this:

 power_adc_disable();
      power_spi_disable();
      power_timer0_disable();
      power_timer1_disable();
      power_timer2_disable();
      power_twi_disable();

So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation?
For example, waking up with long serial data input?


texts: arithmetic operation outcome differs from the expected outcome

texts:
I am writing a function

void Sound_Play(int frequency,int millisec)

A part of this function is:

  counting=(millisec*frequency/1000);  //counting is type int
  Serial.println((String)"millisec="+millisec+" frequency="+frequency+" (millisec*frequency/1000)="+(millisec*frequency/1000)+" counting set to="+counting);

But when I call the function with millisec=500 and frequency=220, the result on the Serial Monitor is:

millisec=500 frequency=220 (millisec*frequency/1000)=-21 counting set to=-21

Shouldn't counting should be 110 instead.I tried casting the result to int but in vain. What am I doing wrong and how to correct it?
Thanks!
Bhuvnesh


texts:
I know this question has be asked before on this site. However it was never really answered. I have an Arduino Uno. I am trying to get it to read a 2 GB SDHC Micro SD card. The problem is, the SD card never intializes. I am not sure if there is something wrong with the wiring (which I think is NOT the issue) or the SD card/shield. I have formatted the SD card, but perhaps I did use the wrong settings to do so. Additionally, this SD card is quite old, probably several years. It can still be managed on my PC however.

I bought the following Micro SD shield off Amazon. It has the pins VCC, GND, MISO, CS, MOSI, and SCK, for which I figured the following:

MISO = D0
CS = D1
MOSI = CLK
SCK = D3

I have the circuit wired in the following way:

SCK to Pin 10 on Arduino
CS to Pin 11 on Arduino
MISO to Pin 12 on Arduino
MOSI to Pin 13 on Arduino
VCC to 3.3V source on Arduino
GND to Arduino Ground

The image below is a compilation of the closeup of the shield and my wiring. Not that I am also using Pin 9 in the picture. However this is used for a different portion of the circuit.

The code that I am trying to run comes from the SdFat library. Though the Amazon page says the device can be used without this library, I prefer to have it. I am running the SdInfo.ino example located in SdFat/SdFat/examples/SdInfo/. I have changed the coding so that:

const uint8_t SD_CHIP_SELECT = 10;

I have also tried running the Basic.ino example in the TMRpcm library, located at: TMRpcm/examples/basic, but this doesn't work either. Below is the code:

#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328, can use other pins
#include <TMRpcm.h>           //  also need to include this library...
#include <SPI.h>

TMRpcm tmrpcm;   // create an object for use in this sketch

void setup(){
  tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  tmrpcm.play("music"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){
  if(Serial.available()){
    if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("music");
    }
  }
}

In short. My SD card does not initialize, and I cannot seem to figure out why.


texts: How do I know if bootloader flash was successful?

texts:
I just bought a raw Atmega328p microcontroller. I am attempting to flash it with the Arduino bootloader.

The process seemed relatively straightforward as I had just followed the posted tutorial (https://www.arduino.cc/en/Tutorial/ArduinoISP).

Everything seemed to go fine and I even got a message after the second attempt with a message of 'Burning Bootloader Done'. I am targeting the device as if it were an Arduino Pro Mini.

I then moved onto program the chip with an Arduino sketch via the FTDI programmer. However, the sketch upload fails. It says that it is out of sync. I verify that everything is wired up correctly, yet it still fails. I then remove power to the Atmega328p chip (just to see if I get a different error) yet I still get the out of sync error.

This has me questioning whether or not the bootloader was even flashed in the first place. So how do I know if the bootloader actually was successful? A couple things to note:

When I power on the Atmega328p, the PB6 output starts blinking immediately. I would assume that if there were a bootloader, there would be a moment of pause until the regular program starts. Should I expect to see a pause if the bootloader is on the chip?
If the bootloader is on the chip, should I even expect to see the Atemga328ps default heartbeat?
When I flash the chip with the bootloader, it says that it could take up to a minute to finish. However, it only takes 6 seconds until it states 'Bootloader Finished Burning'. This seems like it's happening too fast.

If we determine that the problem is due to something else (i.e. not the bootloader), I will begin a new discussion. However, right now I'm just curious how I know if the bootloader is actually on the device.


texts: Getting an Arduino Uno and MKR zero to communicate

texts:
I'm very new to Arduino and especially the forum so please let me know if I am on the wrong topic or anything.

Anyways let me get straight to the point. I am working on a school project where I need to create a robot head that can move and talk using the Arduino Uno. I have the speech files as a .wav and from what I gathered you need an sd card reader connected to the Uno to read .wav files. So I purchased the Arduino MKR Zero, but after I got the board I realized that it is a standalone board, not a file reader for the Uno. This project is due next week so I need to figure out how to make the MKR Zero read the files and play them off the speakers but have it timed and programmed off the Uno. Is this possible with the hardware I have?

Here is a picture of my setup:


texts: green house vent servo based reading a sensor wrong

texts:
I am trying to make a green house vent that will open based on the temperature, however in my code the thermometer is not reading correctly, I've been designing it  in tinkercad and heres the link
https://www.tinkercad.com/things/fxhHvZCoqmQ
when the thermometer is on A0 i9t reads 14, if its on A3 it is 17.
I am very new at this so please help.


texts: Programmed 5 Volt output to power a relay

texts:
I need to put out 5 volts from an Arduino UNO digital pin. I've read that the pins can do approx. 5 volts, but I need to know if it will actually reach 5. I'm also powering a few other devices from the Arduino.

Are the digital pins capable of emitting 5 volts consistently? Are there any better alternatives?
Thanks.


texts: I'm making a project and I neee to use 2 different references on the same ADMUX. One reference is 0-5V and the other is 0-2.5V. I'm aware that I can use the reference of the Arduino to the 5V sensor. But how I put a 2.5V reference while using the 5V at the same time?


texts:
I've been communicating with a teensy arduino over USB using pySerial--which has been simple, but slow. With simple write commands from Python and a corresponding read command on the teensy, I can only achieve 200kHz transfer rates. I'm hoping to get over 1MHz at least, but I don't see a path towards that rate.

Are Ethernet shields capable of augmenting for rates over the MHz range? How can I get faster data transfer rates between my computer and arduino? I'm mainly interested in one-way communications (computer directs teensy).


texts: Bluetooth module discovered by computer and not smartphones

texts:
I've been playing with Groove Bluetooth Module (HM-11) and for some reason my computer can see it, but none of my cell phones can.

I've tried two Huawei P7 (BL 4.0 + BLE) as well as some Samsung Galaxy & some older sony with Bluetooth 2.0. None of the cell phones can see the device. Any ideas?


texts:
I have programmed ESP8266 to make it accessible over the network using below program.

First Program

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

//SSID and Password of your wifi router
const char* ssid = "Moto";
const char* password = "reset1234";

ESP8266WebServer server(80);

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

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();          //Handle client requests
}

It is working fine, What is the way to reset it to run below program? I wanted to send AT commands on serial monitor using below program which has been uploaded successfully but not responding AT commands on Serial Monitor, as ESP8266 is running above program and showing output of above program on running below program on Serial Monitor.

I want to reset ESP8266 so it responds to below program. What is the way ?

Connected to Moto
IP address: 192.168.43.115
HTTP server started

SecondProgram

#include "SoftwareSerial.h"

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

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(9600);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer
    Serial.write("Hello");
    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}


texts:
I'm using an Arduino Mega 2560 to make a fire alarm control panel. The control panel takes 50 (inputs) supervised inputs. The normal way as mentioned in the link is to use the analog inputs, which I am short of. Is there any other way to monitor supervised inputs other than using analog inputs?

Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.


texts: Is there any way that the two 'different' programs of arduino can be run one after another keeping each one separate?

texts: I have made a 8*8*8 led cube using arduino. I have found two different codes from different developers having different animations in them. i wanted to combine them and get to run all the animations at once. Both the codes have some similar function names and some are different as well. I wanted to know if i can keep both these separate from each other yet run them one after another. Almost all parameters are different including setup() of both codes. Please help


texts: sleep and wake up arduino mega according to ds3231 interrupt

texts:
how can I make my arduino mega sleep during 6pm-7am..and wakes or stay up during 7am-6pm and doing its job like activating the solenoid valve based on my soil moisture sensor reading.this is for my backyard farm.anyone can help me making a code for it? please i really need it.

here is my code

#include <DS3231.h>
#include <Wire.h>
#include <avr/sleep.h>

 int wakePin = 2;   // pin used for waking up
 int led = 13;

 DS3231 clock;
 RTCDAteTime dt;

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

 // initialize DS3231
 Serial.println("Initailize DS3231");
 delay(100);
  clock.begin();
  pinMode(wakePin,INPUT_PULLUP);
  pinMode(led,OUTPUT);

   //Disarm alarms and clear alarms for this example, beacuse alarms is battery backed.
   //Under normal conditions, the settings should be reset after power and restart microcontroller
   clock.armAlarm(false);
   clock.clearAlarm();

   //Set Alarm1 - Every 20s in each minute
   // setAlarm1(date or day,hour,minute,second,Mode,Arrmed=True)
     clock.setAlarm1(0,0,0,20,DS3231_MATCH_S);
     attachInterrupt(0,wakeUpNow,LOW);

   //check alarm settings
    checkAlarms();
  }

   void checkAlarms()
  {
   RTCAlarmTimea1;
   RTCAlarmTimea2;

    if (clock.isArmed1())
   {
    a1 = clock.getAlarm1();

     Serial.print("Alarm1 is triggered:);
     switch(clock.getAlarmType1())
    {

       case DS3231_MATCH_S:
       Serial.print("When seconds match: ');
       Serial.println(clock.dateFormat("_ _:_:s",a1));
       delay(100);
        break;
        default:
         Serial.println("UNKNOWN RULE");
         break;
     }
    }
   }

       void wakeUpNow()
   {
       //execute code here after wake-up before returning to the loop() function
      //timers and code using timers(serial.print and more...)will not work here.
     //we don`t really need to execute any special functions here, since we
     //just want the thing to wake up
      Serial.print("Woke up");
     delay(100);
     }

      void sleepNow()
     {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);  //sleep mode is set here
      sleep_enable();   //enables  the sleep bit in the mcucr register
      attachInterrupt(0,wakeUpNow,FALLING); //use interrupt 0(pin2) and run function
      sleep_mode();
         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

         sleep_disable();  //first thing after waking from sleep: disable sleep
         detachInterrupt(0); //disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running
          time.
        }

         void loop()
        {
           dt=clock.getDateTime();

             Serial.println(clock.dateFormat("d-m-Y H:i:s-I",dt));
              delay(100);
           //Call isAlarm1(false)if you want clear alarm1 flag manualy by                     cleaAlarm1();
              if(clock.isAlarm1())
           {
                 Serial.println("ALARM 1 TRIGGERED!");
                 digitalWrite(led,HIGH);
                   delay(1000);
                  digitalWrite(led,LOW);
                  Serial.println("Entering Sleep");
                    delay(100); //sleep fucntion called here
                     sleepNow();
               }
                delay(900);
               }


texts:
I hooked up a 16x2 Arduino compatible LCD yesterday and made sure all the connections were according to the program and the schematics provided all over the web. My contrast is adjusted perfectly but the problem is that there are black boxes on the top line while the lower one is empty.

I know this question has been asked many times but no one has answered the question other than saying, "Check your contrast pin". I'm using the default sample code provided in the Arduino IDE.
HELP!

Regards.


texts:
I'm looking at the datasheet of the ATMega328, and I see the different channels you can select for AD conversion. ADC0..7, ADC8 (temperature), 1.1V (VBG), and lastly 0V (GND).

What would be the use of measuring 0V?
Would it ever result in a reading other than 0? I find it very intriguing.

The datasheet doesn't seem to give any additional information about it.

AVR126 seems to give a hint:

  configure 0V (GND) in ADC by setting Mux bitfield (MUX3:0) equal to 1111. This is done to discharge the capacitor of ADC.

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

Is it to protect the ADC from to high a voltage in the ADC capacitor, when changing to a different (lower) reference voltage? Rather odd you need software to protect the IC, and it's not even mentioned in the datasheet. Also I've never seen anyone do this (e.g. when measuring the internal temperature of the ATMega).


texts: How to stop extra LEDs from lighting in LED cube

texts:
So I build LED cubes and the way I have it programmed is I use an analog pin for the ground layers and set them to high when i want an led on that layer lit up. So lets say I wanted the following LEDs lit

But in reality the LEDs light up in all the layers that are set to high obviously so this is what actually ends up lighting

What should I incorporate in order to avoid this happening. I am using an Arduino Nano, do I need to edit my code or is it hardware?


texts: Is it possible to measure analog output?

texts:
I'm using PWM to control LED brightness using MOSFET, using analogWrite(pwmPin,val), while val is a 12 bit bit value.

pwmPin is defined as- pinMode(pwmPin, OUTPUT);

Since val changes in time due to external lightning, I wish to measure PWM value, for later use in code. Using analogRead(pwnPin) yielded a changing value ranges 7-14.

Is there a way to measure PWM value defined as an output ?

EDIT 1:

Saving val's value won't save the problem I'm looking for, since code reaches a deepSeleep phase, which val can be stored, but I want an actual incidication of its value, and if it actually on.


texts:
I have been trying to get my 9g tower pro servo to work and no matter what i do nothing happens. I connected the servo to the arduino with the red wire to 5v, brown to ground and orange to pin 6.

#include <Servo.h>
Servo myServo;

void setup(){
myServo.attach(6);
}

void loop() {
myServo.write(0);
delay(1000);
myServo.write(60);
}

I have been using this code to test it.
Another weird occurrence is when i disconnect the servo it sometimes start moving very slowly even though it has now power. I dont think the Uno is broken as other projects work fine on there, are my servos fried?


texts:
This sample code for the esp32 doesn't work. When contacting the website I get a 301 error and the website acts as if nothing was ever recieved. Note: Been using arduino for 2 years.
/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "lol";
const char* password = "u tried";

//Your Domain name with URL path or IP address with path
String serverName = "http://requestbin.net/r/63agtdpl";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

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

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?temperature=24.37";

      // Your Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());

      // Send HTTP GET request
      int httpResponseCode = http.GET();

      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}


texts: How do I connect Arduino to RS232 via USB?

texts:
I have a device that takes commands in the form of RS232 communication. I've connected the Arduino's USB port, through an adapter, to the device's 9-pin serial port, but no communication has happened.

The full chain of adapters is a printer cable (which would connect the Arduino to a computer), a female-to-female usb adapter, and a Sabrent USB to serial adapter.

I made sure the communication wasn't happening using the code while (!Serial) and blinked an LED in a certain pattern.

Is there something I'm missing? How do you get the devices to communicate?


texts:
So I basically tried to control a Servo motor with an IR Remote. I'm a complete newbie in arduino programming but I just took some things from other scripts and tried them out until It worked, and it kinda did but my main problem is that as soon as I press a button the action is exectuted but the command like left arrow on the remote control just spams over and over again so I cannot have an action after that one
`
#include "IRremote.h"
#include "IR.h"
#include <Servo.h>

int receiver = 11;

IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
Servo myservo;

void setup() {
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn();
  myservo.attach(9);
  myservo.write(0);
}

void loop()
{
if (irrecv.decode(&results))
 {
   //  irrecv.resume();   // Receive the next value
  // }
  //if (results.value == 0xFF629D)  // change according to your IR remote button number
  //  {
    //  myservo.write(0);
      //delay(15);
   // }
    //if (results.value == 0xFF629D)  // change according  to your IR remote button number
    //{
     // myservo.write(30);
    //delay(15);
    //}

      switch(results.value)
  {
  case 0xFFA25D: Serial.println("POWER"); break;
  case 0xFFE21D: Serial.println("FUNC/STOP"); break;
  case 0xFF629D: Serial.println("VOL+"); break;
  case 0xFF22DD: Serial.println("FAST BACK");
  myservo.write(90);
  delay(15);
  break;
  case 0xFF02FD: Serial.println("PAUSE");    break;
  case 0xFFC23D: Serial.println("FAST FORWARD");
  break;
  case 0xFFE01F: Serial.println("DOWN");    break;
  case 0xFFA857: Serial.println("VOL-");    break;
  case 0xFF906F: Serial.println("UP");    break;
  case 0xFF9867: Serial.println("EQ");    break;
  case 0xFFB04F: Serial.println("ST/REPT");    break;
  case 0xFF6897: Serial.println("0");    break;
  case 0xFF30CF: Serial.println("1");    break;
  case 0xFF18E7: Serial.println("2");    break;
  case 0xFF7A85: Serial.println("3");    break;
  case 0xFF10EF: Serial.println("4");    break;
  case 0xFF38C7: Serial.println("5");    break;
  case 0xFF5AA5: Serial.println("6");    break;
  case 0xFF42BD: Serial.println("7");    break;
  case 0xFF4AB5: Serial.println("8");    break;
  case 0xFF52AD: Serial.println("9");    break;
  case 0xFFFFFFFF: Serial.println(" REPEAT");break;
  default:
    Serial.println(" other button   ");`

That's my code, and whenever I press like Fast Back I can't do anything else and the Serial Monitor is just full of Fast Back


texts: If an Arduino goes to sleep, does the attached ESP also sleep?

texts:
I am using Arduino Uno + an attached ESP-01 (ESP8266).

I want to save battery, so I made my Arduino get sleep & interrupt by a watchdog timer.

But if the Arduino goes to sleep, does the attached ESP also sleep?


texts: Why does getting list of files from SD card FAIL if not printing to Serial? (ESP8266)

texts:
I've got this piece of code for reading a list of files from root directory on SD card, which I run on ESP8266 chip (maybe it makes a difference):

  File dir = SD.open("/", O_RDONLY);

  int n = 0;
  while(true)
  {
     File entry =  dir.openNextFile();
     if (!entry) break;
     if (!entry.isDirectory())
     {
       Serial.println(entry.name());
       Serial.flush();
       n++;
     }
     entry.close();
  }
  dir.close();
  Serial.println(n);

The code works fine, but can someone please tell me why, when I comment out printing file names to the Serial in this loop, the program crashes? How is this possible? Are the files opened too rapidly or what? And how can I get the list, let's say into a vector<String> without printing it to the Serial?

When I comment out the printing the chip crashes with this in output:

ctx: cont
sp: 3ffeb540 end: 3ffeb950 offset: 01b0

>>>stack>>>
3ffeb6f0:  000000ff 00007c52 0000012c 3ffea30c
3ffeb700:  000000c0 3ffea4dc 00000000 40203a70
3ffeb710:  00000040 000000ff 3ffea318 402042f7
(...)
3ffeb940:  00000000 00000000 3ffea930 40100378
<<<stack<<<
ň"_Çc_ÇĎ


texts: Interfacing SD card with arduino without shield

texts:
I am trying to connect SD card with arduino without using a shield. To convert to 3.3v, I have used voltage divider circuit as described in these two sites:

http://garagelab.com/profiles/blogs/tutorial-how-to-use-sd-card-with-arduino

http://www.martin-gardner.co.uk/how-to-connect-your-old-sd-card-to-an-arduino/

When I uploaded the code i got the following error on serial monitor:

Initializing SD card...initialization done.

error opening test.txt
error opening test.txt


texts: How to control 30 stepper motors using Arduino?

texts:
To prototype my project, I'm going to use an Arduino. I need to control 30 step motors.

4 of these step motors should always be ready to work, no matter other motors are working or not. But the other 26 motors never work in the same time (only one or none of these 26 step motors work at the same time).

So I'm looking for a fast and cheap way to prototype my machine and I need your advice.

I think a CNC Shield or 4 EasyDriver can do the job for controlling those 4 step motors (those motors which need to be ready to work at any moment of time).

But for the other 26 step motors (which can be controlled one by one) is there a way to avoid using 26 EasyDrivers or stacking several other shields? Is there a way to control those 26 step motors using a single driver?

Thanks.


texts: How to (optimally) fetch a button press?

texts:
For my hardware, I need to check if the button was pressed, but I need to do things only once every half a second.

if (digitalRead(pin) == HIGH)
{
    doStuff();
    delay(500);
}

The above does not work, because I have to check other things in the main loop as well.


texts: Specific values not showing when using a numeric keypad

texts:
I have attached a 3x4 keypad to my Arduino Leonardo as an input method. Whenever I press the buttons, the majority of the keys work but specific ones don't. Here's my code, I've set it up to beep a piezo buzzer when it gets a keypress.

#include <Keypad.h>

int buzzerPin = 0;
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};
byte rowPins[ROWS] = {12, 13, 8, 10}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {11, 7, 9}; //connect to the column pinouts of the keypad

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

void setup(){
    Serial.begin(9600);
    pinMode(buzzerPin, OUTPUT); //Set buzzerPin as output
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
}

void loop(){
    char key = keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
        // When the KeyPad will be pressed, the results will appear on the serial monitor.
        switch (keypad.getState()) {
        case PRESSED:
                Serial.print("Enter: ");
                Serial.println(eKey);
                beep(10);
                delay(10);
                break;
        }
}

void beep(unsigned char delayms) { //creating function
    tone(buzzerPin, 2000); //Setting pin to high
    delay(delayms); //Delaying
    noTone(buzzerPin); //Setting pin to LOW
    delay(delayms); //Delaying
}

I based my rows/columns off of this pin-out: https://www.jaycar.com.au/12-key-numeric-keypad/p/SP0770,
but I later found out some of the columns had to be swapped :P

Here's a diagram of what's happening:

The keys in red do not work.

I wouldn't have posted this on stack exchange but it looks like an oddly specific pattern, and no matter what I changed, it didn't work.

(And yes, that is the exact keypad I bought from Jaycar)

Edit: I forgot to mention that I was using a prototype shield to plug the keypad into, but all pins are confirmed working on that.


texts: HMC5883L not working in continuous mode!

texts:
I'm just starting with the HMC5883L, I'm writing my code with C and also my own I2C library.

I noticed that the values on the Arduino IDE's serial monitor are constant.

Then I developed a function to read the mode register. So the value should be 0x00 for continuous mode.

But, what I get is that the device work in single mode which has the value 0x01 at first cycle of the program, then it goes to idle mode with the value 0x03.

So, why is that and what to do?

#include <I2C.h>

#define HMC5883L_read   0x3D
#define HMC5883L_write  0x3C

#define Configuration_Register_A    0x00  //Read/Write
#define Configuration_Register_B    0x01  //Read/Write
#define Mode_Register               0x02  //Read/Write
#define Data_Output_X_MSB_Register  0x03  //Read
#define Data_Output_X_LSB_Register  0x04  //Read
#define Data_Output_Z_MSB_Register  0x05  //Read
#define Data_Output_Z_LSB_Register  0x06  //Read
#define Data_Output_Y_MSB_Register  0x07  //Read
#define Data_Output_Y_LSB_Register  0x08  //Read
#define Status_Register             0x09  //Read
#define Identification_Register_A   0x10  //Read
#define Identification_Register_B   0x11  //Read
#define Identification_Register_C   0x12  //Read
#define declination_angle 3.46

void HMC5883L_init (void);
int16_t data_read (int16_t *results);
uint8_t HMC5883L_read_reg (uint8_t reg);

int16_t results[3];
float m_scale = 1.0;

void setup() {
  // put your setup code here, to run once:
  I2C_init();
  Serial.begin(9600);
  HMC5883L_init();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:
  data_read(results);
  Serial.print("x-axis = ");
  Serial.println(results[0]);
  Serial.print("z-axis = ");
  Serial.println(results[1]);
  Serial.print("y-axis = ");
  Serial.println(results[2]);
  Serial.println();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
_delay_ms(500);
}

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

int16_t data_read (int16_t *results)
{
  uint16_t lsb,msb;
  int16_t status_of_process = 0;
  I2C_start(HMC5883L_write);
  I2C_tx(Data_Output_X_MSB_Register);
  I2C_start(HMC5883L_read);

  msb = I2C_rx();
  lsb = I2C_rx();
  results[0] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[1] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[2] = msb << 8 | lsb;

  I2C_stop();

  return status_of_process;
}

uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  Serial.println(reg_dat);
}

Regards,


texts: Connecting Peltier module to Arduino Nano

texts:
I am a beginner to Arduino programming and started working on my first Arduino project recently to power a Peltier cooling pad. Below is the code I used and in the circuit,
I connected the positive (red wire) end of the Peltier to D12 of Nano Arduino board and the negative end( black wire) to the negative end of the 6V battery. Then I powered the Arduino board by connecting Vin(Arduino) and battery(+) using a jumper wire. The GND pin of the Arduino was connected to the battery(-) using a jumper wire.

The Peltier is not working and it would be a great help if someone can help me to understand what I did wrong.

int p=12;

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

void loop() {
   digitalWrite(p,HIGH);
   delay(2000);
}


texts: High errors in transmission (completely eliminated by adding delay): What's the issue?

texts:
I am using a two Arduino setup with two XBee radios. One radio is sending data and the other is receiving data. I am sending three sensor readings following a protocol which uses three bytes for each sensor reading. Byte one is sensor information, byte two is data, and byte three is for error checking. When I run the set up for about 5 minutes I get approximately 47% errors in transmission. Once one error occurs, there seems to be an avalanche of errors. However, when I add delay in between sending bytes (100ms between bytes and 1s between sensor) it works perfectly. I've tried expanding the hardware buffer, but this didn't work.

        delay(2000);

        // Calcuate weather parameters for serial and web
        calcWeather(); // Go calc all the various sensors

        // send weather out to serial port
        if (prevtemplm34_1 == templm34_1) // 2 in a row must be the same to send
        {
            Serial.write(0);
            Serial.write(templm34_1);
            Serial.write(templm34_1 ^ 0);
        }

        // send weather out to serial port
        if(prevtemplm34_2 == templm34_2) // 2 in a row must be the same to send
        {
            Serial.write(1);
            Serial.write(templm34_2);
            Serial.write(templm34_2 ^ 1);
        }

        // send weather out to serial port
        if(prevtemplm34_3 == templm34_3) // 2 in a row must be the same to send
        {
            Serial.write(2);
            Serial.write(templm34_3);
            Serial.write(templm34_3 ^ 2);
        }
        delay(2000);

The code for parsing received data is:

int readData ()
{
// There must be at least three available bytes to satisfy the protocol
// Otherwise, wait until three bytes have arrived to read anything
if (Serial.available() >= 3) {

      // Read the next three byte in the serial buffer
      incomingByteOne = Serial.read();
      Serial.write("Byte One: ");
      Serial.write(incomingByteOne);
      Serial.println();
      incomingByteTwo = Serial.read();
      Serial.write("Byte Two: ");
      Serial.write(incomingByteTwo);
      Serial.println();
      incomingByteThree = Serial.read();
      Serial.write("Byte Three: ");
      Serial.write(incomingByteThree);
      Serial.println();

      // XOR the first and second incoming bytes so that the result can be checked against the third error checking byte
      byte xorValue = incomingByteOne ^ incomingByteTwo;
      Serial.write("XOR VALUE: ");
      Serial.write(xorValue);
      Serial.println("Number of Errors: ");
      Serial.println(numberOfErrors);
      Serial.println();
      Serial.println();
      if(xorValue != incomingByteThree) {
        numberOfErrors++; // Add one to the total count of number of errors in transmission
      }
      else {
        // Mask for retrieving the five rightmost bits from incomingByteOne (00011111)
        byte maskForSensorNumber = 0x1f;

        // Shift incomingByteOne right 5 times in order to obtain the three bits representing the unit number
        int unitNumber = incomingByteOne >> 5;

        // AND incomingByteOne with the mask in order to retrieve only the five righmost bits representing the sensor number
        int sensorNumber = incomingByteOne & maskForSensorNumber;

        // Store the data for the correct sensor on the correct unit
        data[unitNumber][sensorNumber] = incomingByteTwo*1;
     }
}
}

What could be causing the transmissions to work fine with delay, but not otherwise?


texts: Powering the attiny85 with a separate power source

texts:
I have an LED project for which i'm using a 9v power supply. For part of the project I'm using an off the shelf LED driver that is compatible with 9v however I have one LED component that I want to drive with the attiny85 (random blinking pattern), which is not compatible with 9v.

Does it make any sense to power the attiny85 separately with say a 3v coin cell, while allowing my LEDs to draw from 9v? The attiny85 would only be tripping transistors. I assume the attiny85 itself doesn't consume much power so hopefully I wouldn't be changing out the coin cell too often.

I have a couple 5v buck converters on hand but they take up more space than a coin cell would.

P.S. It's a Guy Manuel Daft Punk Helmet.


texts: Serial plotter isn't displaying my supplied data

texts:
I want to use serial plotter feature of Arduino by using DHT11 as humidity sensor at a time. But I'm getting problem as plotter is not loading by the code I have. Please help me what is the problem because of which serial plotter is not loading.

Here is the Code I wrote:-

#include <dht.h>
#define dht_apin0 A0 // Analog Pin sensor is connected to

dht DHT0;

void setup() {

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity Sensor\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT0.read11(dht_apin0);

    Serial.print("Current humidity = ");
    Serial.print(DHT0.humidity);
    Serial.print("%  ");

    delay(5000);//Wait 5 seconds before accessing sensor again.

  //Fastest should be once every two seconds.

}// end loop()


texts: How to skip the first line and output the second?

texts:
My question is related to my previous question.
These encoder programs outputs two line per pule/tick.

Here is the part of the code I want to use:

void loop()
{
    // Read the status of the inputs
    debouncerA.update();
    debouncerB.update();

    int8_t EncVariation = 0;

    if (debouncerA.rose())
    { // if input A changed from low to high, it was CW if B is high too
        EncVariation = (debouncerB.read()) ? 1 : -1;
    }
    else if (debouncerA.fell())
    { // if input A changed from high to low, it was CW if B is low too
        EncVariation = (debouncerB.read()) ? -1 : 1;
    }
    else if (debouncerB.rose())
    { // if input B changed from low to high, it was CCW if A is high too
        EncVariation = (debouncerA.read()) ? -1 : 1;
    }
    else if (debouncerB.fell())
    { // if input B changed from high to low, it was CCW if B is low too
        EncVariation = (debouncerA.read()) ? 1 : -1;
    }
//
  if (EncVariation != 0) {

        encoder0Pos = encoder0Pos + EncVariation;

        int degs = (encoder0Pos * 6) % 360 ;

        if(degs<0){ degs = 360 + degs; }

        Serial.println (degs);
   }
}

For three inputs/ticks this outputs like:

6

12

18

24

30

36

But I only need the second ones like:

12

24

36

How can I do that?
(I need it to send the relevant data do a PC.)

I spend so long time on it couldnt find any solution.


texts: Help with code for changing motor speed depending on MPU6050 angles read

texts:
I have been trying to create code where my MPU6050 is constantly reading the angle it is at and based on that angle, increase or decrease the motor speed. For example the motor will be off when the sensor is level and maximum speed at 45 degrees, and 22 degrees is roughly half speed.

I have a 5065 200kv brushless motor going to a ESC with a bec which i can attach to the Arduino. I have tried to modify a self balancing drone code that used PID. I took out the PID and tried to do an if-then for if the angle is > 5 < 45 then servo write (anglex36) because the maximum angle is 45 and if i multiply 45 by 36 it will be 1620. It says in the code the maximum rpm is 2000, although mine can go faster, and I will change it later after testing.  It is recommended to have the max motor speed be at most 85% motor power to prevent damage so that is why I have it at 1620 for now and not 2000.

I am fairly new with Arduino and have no experience with the MPU6050 so I apologize for any misunderstanding of information or code.

Here is my code :

#include <Wire.h>
#include <Servo.h>

Servo right_prop;

int16_t Acc_rawX, Acc_rawY, Acc_rawZ,Gyr_rawX, Gyr_rawY, Gyr_rawZ;

float Acceleration_angle[2];
float Gyro_angle[2];
float Total_angle[2];

float elapsedTime, time, timePrev;
int i;
float rad_to_deg = 180/3.141592654;

double throttle=0; //initial value of throttle to the motors

void setup() {
  Wire.begin(); //begin the wire comunication
  Wire.beginTransmission(0x68);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(250000);
  right_prop.attach(3); //attatch the right motor to pin 3

  time = millis();

  right_prop.writeMicroseconds(1000);
  delay(7000);

void loop() {

/////////////////////////////I M U/////////////////////////////////////
    timePrev = time;
    time = millis();
    elapsedTime = (time - timePrev) / 1000;

     Wire.beginTransmission(0x68);
     Wire.write(0x3B);
     Wire.endTransmission(false);
     Wire.requestFrom(0x68,6,true);

     Acc_rawX=Wire.read()<<8|Wire.read();
     Acc_rawY=Wire.read()<<8|Wire.read();
     Acc_rawZ=Wire.read()<<8|Wire.read();

     Acceleration_angle[0] = atan((Acc_rawY/16384.0)/sqrt(pow((Acc_rawX/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;
     /*---Y---*/
     Acceleration_angle[1] = atan(-1*(Acc_rawX/16384.0)/sqrt(pow((Acc_rawY/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;

   Wire.beginTransmission(0x68);
   Wire.write(0x43); //Gyro data first adress
   Wire.endTransmission(false);
   Wire.requestFrom(0x68,4,true); //Just 4 registers

   Gyr_rawX=Wire.read()<<8|Wire.read();
   Gyr_rawY=Wire.read()<<8|Wire.read();

   /*---X---*/
   Gyro_angle[0] = Gyr_rawX/131.0;
   /*---Y---*/
   Gyro_angle[1] = Gyr_rawY/131.0;

   /*---X axis angle---*/
   Total_angle[0] = 0.98 *(Total_angle[0] + Gyro_angle[0]*elapsedTime) + 0.02*Acceleration_angle[0];
   /*---Y axis angle---*/
   Total_angle[1] = 0.98 *(Total_angle[1] + Gyro_angle[1]*elapsedTime) + 0.02*Acceleration_angle[1];

    Serial.println(Total_angle[1]);

if( Total_angle[1]> 5 && Total_angle[1]< 45)
{
right_prop.write(Total_angle[1]*37);
}
else{
right_prop.write(0);
}
}

//end of loop void


texts: How to convert numbers from Serial port input to HEX String?

texts:
I am trying to read digits (number from 0 to 255) from Serial port, convert them to HEX String and send them using SoftwareSerial as HEX.

For example:
when I send '60' trough the serial port, the SoftwareSerial will send '3C'

currently I am using the following code:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 4); // RX, TX

String inputString     = "";
boolean stringComplete = false;

int HexInt = 0;
String HexString = "00";

void setup() {
  Serial.begin(115200);
  mySerial.begin(38400);
  inputString.reserve(200);
  delay(500);
  Serial.println("");
  mySerial.println("");
}

void loop() {
  serialEvent();
  if(stringComplete) {
    HexInt = inputString.toInt();
    HexString = String(HexInt,HEX);
    if (HexInt<16) HexString = "0" + HexString ;
    HexString.toUpperCase();

    mySerial.println(HexString);

    Serial.println(inputString); //debug
    stringComplete = false;
    inputString = "";
  }

}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n') continue;
    if (inChar == '\r') {
      stringComplete = true;
      if (inputString == "") inputString = "NULL";
      inputString.toUpperCase();
      continue;
    }
    inputString += inChar;
  }
}

My question is:
Is there a more elegant / effective way to perform the same outcome?


texts:
I have an Arduino device and I'm trying to read two voltages. The first one is the Arduino Vcc by using the bandgap value 1.1V (this requires raw access to registers since it's not implemented in analogRead). The other one is checking the battery voltage using the badgap as a reference. I want both of them because I'm doing a study on the battery life when using a step-up converter.

I'm using these pieces of code:

// Read bandgap with Vcc as reference - this will give use the Vcc
ADMUX = DEFAULT << 6 | 14;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

// Read A1 with 1.1V bandgap as reference - this will give battery voltage
ADMUX = INTERNAL << 6 | 1;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

The problem that I have is that separately they seem to work well, however when using them together the first piece of code ruins the reading for the second one. The culprit is the line ADMUX = DEFAULT << 6 | 14. This sets up the default reference (chip voltage) and reads channel 14 (which is the 1.1V). I can't figure out why after using this line changing back with ADMUX = INTERNAL << 6 | 1 doesn't work.


texts: Deep sleep hangs when used with gpio 16 when we connect to reset pin

texts:
I have a node MCU and it hangs when I used a deep sleep, as shown in the image attached. My code looks like this:
/*
 * ESP8266 Deep sleep mode example
 * Rui Santos
 * Complete Project Details https://randomnerdtutorials.com
 */

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(2000);

  // Wait for serial to initialize.
  while(!Serial) { }

  // Deep sleep mode for 30 seconds, the ESP8266 wakes up by itself when GPIO 16 (D0 in NodeMCU board) is connected to the RESET pin
  Serial.println("I'm awake, but I'm going into deep sleep mode for 30 seconds");
  ESP.deepSleep(30e6);

  // Deep sleep mode until RESET pin is connected to a LOW signal (for example pushbutton or magnetic reed switch)
  //Serial.println("I'm awake, but I'm going into deep sleep mode until RESET pin is connected to a LOW signal");
  //ESP.deepSleep(0);
}

void loop() {
}

Please help!


texts: converting an unsigned integer into a const char pointer

texts:
I know this is simple basic C stuff, but I can't quite figure it out or find a solution when searching and reading.
I have a method I want to call from a library that wants a const char pointer
someclass::send(const char *data)

And the value I want to send is actually an unsigned integer:
enum messageTypeEnum
{
  REGISTER_CLIENT = 0x04,
  CLIENT_REGISTERED,
  UPDATE_CREDENTIALS,
  ADD_BRICK,
  GAME_FRAME,
  ERROR
};

enum clientTypeEnum
{
  GAMEBOARD = 0x01,
  BRICK_CONTROLLER,
  PLAYER_CONTROLLER,
  TOUCH_CONTROLLER
};

uint16_t message = GAMEBOARD;
message <<= 8;
message += REGISTER_CLIENT;

So I want to convert it, but I can't quite figure it out.
I know fundamentally the char pointer is just a pointer to a memory address and that c strings are null terminated, so I should be able to create the pointer, add the enum's underlying bytes to the pointer array, and then add a 0 at the end to terminate it, but I don't know how I would do that exactly.
I tried doing it via casting:
const char *data = (char *)&message;

So here I'm saying (if I'm thinking about it correctly), is:

&message take the memory address of message, our uint16
`(char *) interpret it as a pointer for a character string
const char * store that address in this const pointer

Even typing that out I feel like I'm misunderstanding parts.
This compiles, but it crashes my esp32 and I'm sure it's because I don't have a null terminator at the end, but I'm not sure how to add it (I tried to add it via array index but that failed).
What's the proper way of doing this (I'm sure there's a non-casting way that's probably easier)?
Update
More detail re: PMF and Edgar's comments.
I definitely want to send the binary numbers behind the enums up. I'm building a websocket based interactive project where "controller" websocket clients can drive interactions on "gameboards". Websockets don't have a concept of differentiating between client types (I know socket.io does, but I'm wanting to write it all with regular websockets), so I built a registration system into the server that looks at the first two bytes of an array buffer or blob message to determine the client and message type (it seems overly complicated, but I'm building this to give a talk on binary operations and I'm doing it give functional examples of data parsing).
So yeah, all of that to say I definitely want to send the underlying number values from the enums.
The library I'm using is ArduinoWebsockets and they do have a client method called sendBinary that does have a signature like the Serial.write:

Though when I tried this with a non-null terminated c-string my esp32 crashed. That said, I was fumbling around in the code so it may have been something else that caused the crash.
When I follow the method calls down, the library ultimately uses std::string to pull the data out of the passed in c string and takes in the length (meaning it doesn't need to be null terminated(?)):

So maybe I can use the casting to turn my two byte number into a c string and pass in the length of 16?


texts: Signal a LOW level interrupt with an RTC

texts:
I'm trying to figure out how to use an RTC to send interrupts to my arduino. I'm using a DS3232. I can get an 'edge' interrupt, with the following toy code (I know the code is silly, it's just a short example to test if I have actually set the RTC to send the interrupt, and that the Arduino receives it):

/*----------------------------------------------------------------------*
 * Minimal example of setting a recurring alarm with the DS3232 RTC     *
 * Attach an LED to pin 7, which will flash when the alarm fires.       *
 *                                                                      *
 * Attach the RTC SQ/INT pin to Uno pin 2, with a 10K pull-up to VCC.   *
 * Ard pin A4 -> RTC SDA, Ard A5 -> RTC SCL, 5v -> vcc, GND -> GND      *
 *----------------------------------------------------------------------*/

#include <DS3232RTC.h>        //http://github.com/JChristensen/DS3232RTC
#include <Time.h>             //http://playground.arduino.cc/Code/Time
#include <Wire.h>             //http://arduino.cc/en/Reference/Wire

#define WAKE_PIN 2
#define LED_PIN 7

void setup(void)
{
    pinMode(LED_PIN, OUTPUT);

    // RTC config:
    RTC.squareWave(SQWAVE_NONE);
    pinMode(WAKE_PIN, INPUT_PULLUP);
    attachInterrupt(INT0, wakeUp, FALLING);
    RTC.setAlarm(ALM2_EVERY_MINUTE, 0, 0, 0, 1);
    RTC.alarm(ALARM_2);
    RTC.alarmInterrupt(ALARM_2, true);
}

void loop(void)
{
  if(RTC.alarm(ALARM_2)){
    digitalWrite(LED_PIN, HIGH);
    delay(5000);
    digitalWrite(LED_PIN, LOW);
  }

}

void wakeUp (){
// no-op, just checking if the interrupt fired
}

Why doesn't this work if I set the interupt to "LOW", ie., attachInterrupt(INT0, wakeUp, LOW);?

The reason I ask is I'm trying to use an RTC to wake from low power mode, and I think this doesn't work with a 'falling' interrupt.


texts: How do you concatinate an interger with a string in server.send data?

texts:
I have a class I am trying to add its global counting variable value to
int switch0;

class
void webpage() {
  server.send(
      200,
      "text/html",
      " \
       \

Plant 0 has been fed "+switch0+" times
 \
      <form name='frm0' method='post'> \
       <input type='text' name='sw0' value=8000> \
       <input type='submit' value='Submit'> \
      </form> \n\
      <form name='frm1' method='post'> \
       <input type='text' name='sw1' value=8000> \
       <input type='submit' value='Submit'> \
      </form>  ");
}

but I get the following compile error:
Arduino: 1.8.13 (Linux), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
function 'void webpage()':
wemos4.2.server:36:41: error: invalid operands of types 'const char*' and 'const char [319]' to binary 'operator+'

Plant 0 has been fed "+switch0+" times
 \
                                         ^
exit status 1
invalid operands of types 'const char*' and 'const char [319]' to binary 'operator+'

How do I concatenate a server.send data?


texts: serial communication between arduino to 89c51 with gsm

texts: I need to connect the 89c51 with Arduino UNO but same time I need to connect 89c51 microcontroller with Arduino without using serial reception and transmission pins of UNO b'coz that pins already engage with GSM module. plz, suggest me the program solution to serially receive data from 89c51 and send the message to gsm module.


texts: Do I need a full Arduino board hardwired to a sensor to send data via Wi-Fi?

texts:
Basically I want to wire a Wheatstone bridge style load-cell into a moving trolley and transmit the data to a remote workstation so I can get real-time feedback about the loading conditions.

Do I need to have a full board riding on the trolley that is wired in between the Wi-Fi transmitter and the bridge amplifier or is there a way that the current variations from the bridge can be read directly by the Wi-Fi transmitter and relayed to the remote in some translatable format?

The trolley design is extremely streamlined and it would be a bummer to have to add more than minimal electronics to make this happen...


texts:
I am currently doing a school project.  There you have to program a stopwatch with the Arduino.  I wrote a program where millis starts.  But when I press my start button, millis don‘t start from 0.
Has someone an idea? Please let me know.

Ps: I‘m German, so I‘m sorry for my bad English


texts: Good books to learn more about microcontrollers / electrical engineering?

texts:
I've bought the Arduino starter kit with the project book and I'm about half way through and addicted.

As I go through the projects I wish they would go into more detail on the electrical components, and other things such as Ohms law.

The question here is do you have any suggestions for books to read for the purpose of gaining a better understanding of microcontroller programming/engineering, from a beginners perspective?

Ideally I would like a book that can be read cover to cover in my spare time (more abstract concepts, instead of problem&answer type books).


texts: How to read RPS for fast rotation with status change method in Arduino?

texts:
I'm trying to calculate the coming RPS from rotary encoder. I am  trying to get it by checking the status with digitalRead. However, I can not get more than 6 RPS. Any solution? I will be obliged for your help.
Following is the code.

float rps;

void setup() {
  Serial.begin(9600);
  DDRC &= ~_BV (1); // pinMode (A1, INPUT);
}

void loop() {
  static int lastReedState;
  static unsigned long lastTransition;
  int reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
  // On a rising transition of the reed switch:
  if (reedState == LOW && lastReedState == HIGH) {
    // HIGH LOW measuring the low period
    // Compute time since last valid transition.
    unsigned long now = micros();
    unsigned long revolutionTime = now - lastTransition;
    // measuring the High period
    // Compute the RPS
    rps = 1.00 / (12.00*revolutionTime) *1000000.00;
    // 12 is rotary encoders resolution
    // Remember this transition.
    lastTransition = now;
  }
  // Remember last state.
  lastReedState = reedState;
  Serial.println(rps);
}


texts:
Apparently using delay() commands locks the Arduino during the delay period and there are better ways to control a servo that free the Arduino to do other things at the same time as running the servo.

At this point my code consists of a servo going forwards and backwards like this:

void setup()
{
  pinMode(1, OUTPUT); // makes pin 1 an output
}
void loop()
{
for(int i = 0; i<31; ++i) { //keeps in this position for about 400ms
  digitalWrite(1, HIGH); //turns the servo pin to HIGH
  delayMicroseconds(1000); //sets the servo to move clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}

for(int i = 0; i<31; ++i) { // keeps in this position for about 400ms
  digitalWrite(1, HIGH); // turns the servo pin to HIGH
  delayMicroseconds(2000); //sets the servo to move anti-clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}}

Where and how will I add some code that will allow the arduino to carry out another task for example blinking an led light during the approximately 20ms between servo pulses.

NOTE: The arduino is using the ATtiny 85 Processor.


texts:
I'm trying to program an Arduino to control a motor at different intensities by giving a 0-5V reference value from the board. I have some programming experience, but have very little knowledge of manipulating an Arduino or about electricity. As I understand from reading this, I need to call the AnalogWrite function to output the signal, but how do I do this? How can I control when the voltage (and by extension, the motor intensity) is increased or decreased. Is it possible to do this without additional hardware?

Any help is much appreciated, it doesn't have to be code. I mostly want to understand how to use the Arduino, but code would also help a lot with that. I'm using an Arduino Due, which as I understand, has true analog out.


texts: Arduino uno R3 Not detected in windows 7 64

texts:
i have 3 arduino uno r3 out of which 1 is not detected in any of my Pc's,

i was working and must have accidentally short circuited some how , the power led and 5v regulator on uno is burnt out but,i replaced both of them, but then again, windows was unable to detect it,but if i remove and plug the atmega328p in another uno it works fine.am able to upload sketch and do work,and put back the atmega in the non functioning uno.

the uploaded sketch runs fine but not detected, its kinda tiring removing the atmega and uploading a sketch through another uno and putting it back and the pins are so delicate each time i pull carefully somehow the pins getting bent.

i also checked other components on the board but everything seems to be in good shape and not heating or anything, hope some has better solution...


texts:
I have Arduino Mega and ESP-12F module.
Via AT commands I am on my wifi.

Now, I need to call my script on my pages.
Can you tell me how?
This command can conenct to my pages:
Serial3.print("AT+CIPSTART=0,\"TCP\",\"www.artware.cz\",80\r\n");
But that's all, I am not able to call the script.

Sorry, if this is dumb question.
Thank you


texts:
I have old speaker which I want to use to play sound. I chose to use PWM mode on ATMega328 (which is in turn on Arduino Uno R3 board) in order to do it.

For signal on the speaker I chose rectangular wave because it does not require any additional setup. To generate this signal I chose timer1 because it is easy to change PWM frequency just by changing ICR1 value. For duty cycle I chose 50%. So my program looks as follows:

#define     CLK_FREQ 16000000   //clock frequency on ATMega328
#define     PRSCLR   1024       //chosen prescaler of timer1

//duration of one note
unsigned int halfDur = 200;
//number of notes in the melody
const int notesSize = 32;
//frequencies of notes in the melody:
unsigned int notes[notesSize] = { 220, 277, 329, 277, 220, 277, 329, 277,
                                  207, 277, 329, 277, 207, 277, 329, 277,
                                  184, 277, 369, 277, 184, 277, 369, 277,
                                  220, 293, 369, 293, 220, 293, 369, 293 };
//method to play one note
void PlayFreq( unsigned int freq );

void setup()
{
    //PB1 pin in OUTPUT mode
    DDRB |= ( 1 << DDB1 );

    TCCR1A = 0b0;
    //non-inverting mode of PWM
    TCCR1A |= ( 1 << COM1A1 ) | ( 1 << COM1B1 );
    //Fast mode PWM with ICR1 as TOP:
    TCCR1A |= ( 1 << WGM11 );
    TCCR1B = 0b0;
    TCCR1B |= ( 1 << WGM12 ) | ( 1 << WGM13 );
    //prescaler = 1024
    TCCR1B |= ( 1 << CS12 ) | ( 1 << CS10 );
}

void loop()
{
    for ( int i = 0; i < notesSize; i++ )
    {
        PlayFreq( notes[i] );
        delay( halfDur );
    }
}

void PlayFreq( unsigned int freq )
{
    //claclulate TOP according to note frequency
    ICR1 = CLK_FREQ / PRSCLR / freq - 1;
    //50% duty cycle
    OCR1A = ICR1 / 2;
}

Problem is only several first notes are playing and then there is no sound, then again I hear some notes then there is no sound and so on. It seems that tempo is OK. It just skips some notes. What it could be?


texts:
I was wondering if its possible to send code to the Arduino, and then have it execute this code.

What I'm trying to do is use an Arduino Mega with a bunch of stuff connected to it send code to an Uno with a TFT LCD display to do whatever the Mega tells it to do with the Adafruit GFX Library.  I want to add things to this 'system' gradually so I want the whole program hosted on the Arduino Mega, and a minimal amount of code on the Uno.

Sorry I'm really new at this so if its not possible at all let me know!
Thanks in advance,

-Will


texts: Problems with Hardware Serial (UART) on Nano 33 BLE Sense

texts:
my new Nano 33 BLE Sense arrived today.  I'm working on a project to send data from the the Nano via an Xbee S2C module to a receiver module connected to a Nano 33 IoT.  I had the project working before using an MPU6050 and Mega 2560 board which worked (using Software Serial on the Mega).  On the IoT side, I am using 'Uart XBeeRx  (&sercom0, 5, 6, SERCOM_RX_PAD_1, UART_TX_PAD_0);' to process the data from the Xbee.  Having tried this syntax on the BLE Sense I hit problems and after some Googling found a different syntax.  However my new code isn't working in so far as it compiles, uploads and then crashes the BLE Sense (serial port disappears from tools and the onboard LED blinks slowly and erratically).  I need to keep resetting the board and suspect there is some issue with my hardware serial implementation.  I've cut the code down to simply send accelerometer data.  My code is as follows - the EasyTransfer library simplifies the Xbee comms.  Any help appreciated!
#include <EasyTransfer.h>
#include <Arduino_LSM9DS1.h>

UART XBeeTx (digitalPinToPinName(6), digitalPinToPinName(5), NC, NC);

EasyTransfer ET;

struct SEND_DATA_STRUCTURE {

  float xAcc;
  float yAcc;
  float zAcc;

};

SEND_DATA_STRUCTURE myData;

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {

XBeeTx.begin(9600);

ET.begin(details(myData), &XBeeTx);

}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {

  float x, y, z;

if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(x, y, z);

  }

  myData.xAcc = x;
  myData.yAcc = y;
  myData.zAcc = z;

  ET.sendData();

}


texts: Simultaneous input output in arduino mega

texts:
I need to read 5 analog pins simultaneously , is it possible?

note that:
analogRead(1);
analogRead(2);
analogRead(3);
will not work this case


texts: NodeMCU Arduino set PWM Frequency to specific frequency

texts:
I am using NodeMCU and I program it using Arduino IDE, I need to change the PWM frequency of a port, in Arduino I used to change the frequency using timers registers like that:

TCCR1B = (TCCR1B & 0xF8) | 1 ;

How can I change the frequency of a digital pin using some function like that:

analogWriteFrequency(pin, 31250);

So that the code will looks like that:

#ifdef __AVR__
TCCR1B = (TCCR1B & 0xF8) | 1 ; //generates the MCKL signal
#else
analogWriteFrequency(pin, 31250);
#endif
analogWrite(pin, 128) ;

Thanks.


texts:
I come from a .Net background, typically I would 'lock' operations on an integer when I have thread-safe requirements. I'm not sure that applies to my sketch here? Could I potentially bypass an increment from one of my interrupt pins?

In summary, I have 2 interrupt pins - I want to increment a count which (every 5 seconds) writes via serial and resets.

I'm doing this to, kind of, avoid writing serial from within an interrupt - since I've read it's strongly discouraged.

#include <Controllino.h>

const byte interruptPin0 = CONTROLLINO_IN0;
const byte interruptPin1 = CONTROLLINO_IN1;
int counter1 = 0;
int counter2 = 0;
unsigned long previousMillis = 0;
unsigned long interval = 5000;
int a = 60;
char buffer[256];

void setup()
{
  pinMode(interruptPin0, INPUT_PULLUP);
  pinMode(interruptPin1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin0), pin1Fired, RISING);
  attachInterrupt(digitalPinToInterrupt(interruptPin1), pin2Fired, RISING);
  Serial.begin(9600);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    sprintf(buffer,"A%d",counter1);
    Serial.println(buffer);
    sprintf(buffer,"D%d",counter2);
    Serial.println(buffer);
    counter1 = counter2 = 0;
  }
}

void pin1Fired()
{
  counter1++;
}

void pin2Fired()
{
  counter2++;
}


texts: I keep getting the 'expected unqualified-id before if' error message when trying to run my program

texts:
This is my code:
const int Speaker = 11;
const int trigPin = 9;
const int echoPin = 10;

long duration;
int distance;

void setup() {
  // put your setup code here, to run once:
pinMode(Speaker, OUTPUT); // sets the output as the buzzer which is in pin 11
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);

}

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

digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;

if (distance > 10);
  Serial.print("Distance: ");
Serial.println(distance);
}

if (distance <= 10); {

Serial.print("Distance: ");
Serial.println(distance);

tone(Speaker, 440, 750);
delay(375);
tone(Speaker, 349, 750);
delay(375);
tone(Speaker, 587, 750);
delay(375);
tone(Speaker, 523, 1500);
delay(750);
tone(Speaker, 440, 750);
delay(375);
tone(Speaker, 1500);
delay(750);
tone(Speaker, 294, 750);
delay(375);
tone(Speaker, 392, 3000);
delay(1500);
tone(Speaker, 349, 750);
delay(375);
tone(Speaker, 392, 750);
delay(375);
tone(Speaker, 440, 750);
delay(375);
tone(Speaker, 587, 750);
delay(750);
tone(Speaker, 659, 750);
delay(375);
tone(Speaker, 698, 750);
delay(375);
tone(Speaker, 523, 750);
delay(1875);

}
else {
  Serial.print("Distance: ");
Serial.println(distance);
}

}

sorry I couldn't figure out how to enter it in to look like it does on arduino.
What is my fault?
i'm new to coding so you might have to explain it as easily as you can.


texts: Using more than 8 digits using the sevseg library

texts:
I am using sevseg and i can't get more than 8 digits to work.  I really need 15.  Does somebody know what I can do to get this?

Shown is the original example

This is using Gabriel Staples example in the sevseg library:

#include <SevSeg.h>

SevSeg sevseg; //Instantiate a seven segment controller object

void setup()
{
  byte numDigits = 4; //<<---I am wanting 15, but doesn't work after 8------
  byte digitPins[] = {2, 3, 4, 5}; //Digits: 1,2,3,4 <--put one resistor (ex: 220 Ohms, or 330 Ohms, etc, on each digit pin)
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13}; //Segments: A,B,C,D,E,F,G,Period

  sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
// Note: 100 brightness simply corresponds to a delay of 2000us after lighting each segment. A brightness of 0
// is a delay of 1us; it doesn't really affect brightness as much as it affects update rate (frequency).
// Therefore, for a 4-digit 7-segment + pd, COMMON_ANODE display, the max update rate for a "brightness" of 100 is 1/(2000us*8) = 62.5Hz.
// I am choosing a "brightness" of 10 because it increases the max update rate to approx. 1/(200us*8) = 625Hz.
// This is preferable, as it decreases aliasing when recording the display with a video camera....I think.
  sevseg.setBrightness(10);
}

void loop()
{
  //local vars
  static byte decPlace = 0;

  sevseg.setNumber(8888,decPlace);
  decPlace++;
  decPlace %= 4; //rollover back to 0 once variable gets to 4; To anyone wondering: the % is called the "modulo" operator; see here for explanation & example: https://www.arduino.cc/en/Reference/Modulo

  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

Using the following code, I can't get the 3rd set of 5 numbers to display.  I have changed the sevseg.h file to 15, but that shouldn't matter:

#include <SevSeg.h>

SevSeg sevseg1;//Instantiate a seven segment controller object 1
SevSeg sevseg2;//Instantiate a seven segment controller object 2
SevSeg sevseg3;//Instantiate a seven segment controller object 3

void setup()
{

  Serial.begin(9600);

byte segmentPins[] = {22, 23, 24, 25, 26, 27, 28, 34}; //Segments:     A,B,C,D,E,F,G,Period

  byte digitPins1[] = {29, 30, 31, 32, 33};
  sevseg1.begin(COMMON_CATHODE, sizeof(digitPins1), digitPins1,  segmentPins);
  sevseg1.setBrightness(10);

  byte digitPins2[] = {35, 36, 37, 38, 39};
  sevseg2.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins2, segmentPins);
  sevseg2.setBrightness(10);

  byte digitPins3[] = {40, 41, 42, 43, 44};
  sevseg3.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins3, segmentPins);
  sevseg3.setBrightness(10);

}

void loop()
{

static byte decPlace = 2;

  sevseg1.setNumber( 12345, decPlace );
  sevseg2.setNumber( 12345, decPlace );
  sevseg3.setNumber( 12345, decPlace );

  sevseg1.refreshDisplay();
  sevseg2.refreshDisplay();
  sevseg2.refreshDisplay();
}


texts: Sending a union from Arduino via serial communication and parsing it in python

texts:
I want to send a union from Arduino to a python script running on a pc, and I want to parse the received union. I have read lots of topics online but I am stuck on how to do it in the most efficient way.
Specifically, the union contains a struct of a string containing a sensor name, and a 32 bit integer containing a sensor value.
I use the union as I understood is one of the best ways to deal with binary struct data as the ones I want to send.

Here my Arduino code

int32_t analog_input0 = 0;

// Variables to send data
struct serial_message {
  char sensor_name[20];
  uint32_t sensor_value;
};

union serial_message_union {
   serial_message ser_msg;
   uint8_t serial_message_bytes[sizeof(ser_msg)];
};

union serial_message_union ser_msg_u;

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

void loop() {
  analog_input0 = analogRead(0);
  strcpy(ser_msg_u.ser_msg.sensor_name, "analog_input0");
  ser_msg_u.ser_msg.sensor_value = 100;
  Serial.write(ser_msg_u.serial_message_bytes, sizeof(ser_msg_u.ser_msg));
}

Here my python code:

import serial
ser = serial.Serial('/dev/tty.usbmodem1225061', 115200, timeout = 2)

while True:
    if(ser.in_waiting > 24): #I set 24 because the message is composed by 20 char + 4 bytes for the uint32_t value
        incoming_data = ser.read(24)
        print('Incoming data: "{}" '.format(incoming_data))

# Here I want to parse the incoming data, where the first
# 20 bytes are the sensor name and the last 4 bytes are the sensor value

Can anyone suggest how can I proceed? Do you see any error/bad software practice so far in my code?


texts:
i'm new user with Arduino, i want to know if there is a tutorial to control the rotation of a motor like : with 4 buttons, the first to rotate +pi/2 the second to rotate -pi/2 the third to rotate +-pi and the fourth to stop the rotation
thanks a lot !!


texts: When I plug my new UNO R3 board into a PC's USB port it powers on but no device is detected by the operating system. I've tried on three different PCs, Windows 7, 8 and 8.1 with multiple different cables. My guess is that the board is defective but would appreciate any pointers you can give.


texts: Weird output from chained 74HC595 shift registers

texts:
EDIT 4/2/18: The Arduino tutorial schematics have been corrected! See https://github.com/arduino/Arduino/issues/6433 for that issue.

I have a project where I am trying to load a 16-bit number onto an EEPROM using an Arduino hooked up to two 74HC595 Shift registers.

I'm loosely following this Arduino tutorial: https://www.arduino.cc/en/Tutorial/ShiftOut, but I'm getting unexpected outputs depending on the number I try to load into the register. I've reduced everything to as simple a setup as I can, and have spent several hours trying to figure out what the heck is going wrong... obviously to no avail.

Here is the schematic - with the exception that I moved the capacitor off of ST_CP (why would they put that in the tutorial?) to between power and ground:

Here is my code:

#define SHIFT_DATA 2
#define SHIFT_CLK 3
#define SHIFT_LATCH 4

void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);

  int address = 0b1111111111111111;  // Case 1
//int address = 0b0000000000000000;  // Case 2
//int address = 0b0101010101010101;  // Case 3
//int address = 0b1010101010101010;  // Case 4
//int address = 0b0101100110101110;  // Case 5

  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, (address >> 8)); // Load first 8 bits
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address);        // Load second 8 bits

  digitalWrite(SHIFT_LATCH, LOW);
  digitalWrite(SHIFT_LATCH, HIGH);
  digitalWrite(SHIFT_LATCH, LOW);
}

void loop() {
  // none
}

Here is a picture of my breadboard setup with Case 1 loaded:

And here follows my test cases.

All 1's (1111111111111111). Looks good.
All 0's (0000000000000000). Looks good.
Repeated 01's (0101010101010101). Looks good.
Repeated 10's (1010101010101010). Output: 1010101000000000. First 8 bits match, last 8 are zeros. Huh?
Random sequence (0101100110101110). Output: all over the place. Initially the first 8 bits match as in Case 4, but on repeated resets of the Arduino the output changes, with some weird momentary flickering going on for some of the LEDs. If I press it enough times I can get it back to the initial output, but never what I expect. I am completely stumped. Here is an animated gif of this behavior running on the breadboard: http://i.imgur.com/KEwpSXe.gifv.

What could my problem be? I assume it's something very simple and I'm being an idiot.


texts:
What is maximum voltage PWM pins can give?
can i give a vcc to 14v?


texts: DC motor with L289N driver cannot set RPM lower than 130

texts:
My setup is using an Uno r3, and the motor driver is an L289N.

I am going to set it to run at a lower RPM, but when adjusting enA or enB to set to below 130, it won't spin.

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 2;
int enB = 7;
int in3 = 5;
int in4 = 6;
int in1 = 3;
int in2 = 4;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  delay(500);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 130);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  delay(100); //this function to set masa untuk rotation
  // now change motor directions
  // now turn off motor
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(100);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);

  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  delay(400);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
}

void loop()
{
  demoOne();
  delay(3000);

}


texts: I am trying to figure if SDA and SCL pins from Arduino Uno is a TTL or a CMOS technology. I am not able to find this info anywhere but regarding it is a I2C protocol it does make sense to be a TTL technology. Can someone kindly confirm this info, please?


texts: Can an arduino tell between being powered by USB or by the jack?

texts:
I have an arduino mega that will be communicating through serial to a pc. One of the things I want it to tell the pc is whether or not it is connected to a wall power to 12V converter (where there is a switch between the arduino and the wall power). I was just wondering if there was a way to do that in software without having any additional hardware.

Thanks!


texts:
I have an Arduino Uno. I've been reading about pin change interrupts, and one vector covers the analog pins. However, is it possible to trigger interrupts using analog pins as analog inputs (not digital)?

I actually want to analogRead() a potentiometer inside the ISR.

This is my code so far, http://pastebin.com/ykpp78GB

And my circuit is just two potentiometers connected to pin A0 and A1.


texts: Set local stratum 0 NTP server without internet

texts:
Currently, I'm doing a running track timing gate project to measure an accurate acceleration (a runner for example). The idea is when the runner triggers the first gate (start gate), the system will signals all other ESP32 to start the timing, and as the runner triggers other gates, the system will save each of their time. The expected precision is up to 10 ms.

I've managed to set up an NTP client with an NTP Server pool.ntp.org

#include <WiFi.h>
#include <sys/time.h>
struct timeval timeinfo;
volatile boolean flag = 0;
unsigned long prevTime = 0;
const char* ssid     = "********";
const char* password = "********";

void setup() {
  Serial.begin(115200);
  Start_WiFi(ssid, password);
  configTime(0, 0, "pool.ntp.org");
  attachInterrupt(digitalPinToInterrupt(27), printLocalTime, FALLING);
}

void loop() {
  //unsigned long int currTime;
  //currTime = millis();
  //if (currTime - prevTime >= 1000){
    //prevTime = currTime;
    if (timeinfo.tv_sec != 0 && not(flag)){
      Serial.printf("%ld.%06ld\n", timeinfo.tv_sec, timeinfo.tv_usec);
      flag = 1;
    }
  //}
}

void printLocalTime() {
  gettimeofday(&timeinfo, 0);
}

int Start_WiFi(const char* ssid, const char* password) {
  int connAttempts = 0;
  Serial.println("\r\nConnecting to: " + String(ssid));
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
    if (connAttempts > 20) return -5;
    connAttempts++;
  }
  return 1;
}

However as I won't be having an internet connection I think that I need a different approach, I'm thinking of using a single ESP32 to behave like a stratum 0 NTP server or using Android phone as a stratum 0-like NTP server, which will be connected via a portable router. The other ESP32 will behave like a stratum 1 NTP server. I've read a solution to setup an NTP server using GPS, however actual current time is not necessary for this problem in my opinion.

Is this a good way to approach this problem? If yes, how do I setup a local stratum 0 NTP server?


texts: How to port Arduino project using non-core parts of the arduino library to atmel studio?

texts:
I'm trying to port an Arduino IDE project to Atmel Studio (I have Arduino IDE 1.6.8 and Atmel Studio 7).  I've used the Atmel Studio wizard for importing an Arduino Sketch, which has imported my project successfully and set up a project for the ArduinoCore library, but I now have two problems:

My code contains #include <Wire.h>, but the compiler is complaining it cannot find it, and
I'm using a third-party library (fmalpartida's I2C LCD display module library), and it isn't 100% clear how to import it into the project structure.

How do I go about setting up the environment to make both of these work?

Atmel's web site suggests this should be automatic ("Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project") -- why would this have failed to happen for mine?


texts: Is it possible to make normal pins act like ground pins?

texts:
So what exactly I am trying to do is control a motor and be able to turn it both ways without any extra parts.

So if the hmp was on (the plus pole) and the hmm (the minus pole) acted like ground the motor should start turning right.

But if the hmp acted in this case as ground and the hmm like the plus pole it should start turning the other way.

I know that it's probably not going to work. I'm just experimenting.

int Hmp=12; // the plus pole
int Hmm=11; // the minus pole

while (HR=0 || Sr > Sl+300) {
  pinMode(Hmp, OUTPUT);
  digitalWrite(Hmp, HIGH);
  pinMode(Hmm, INPUT);
}

while (HR=1 || Sl > Sr+300) {
  pinMode(Hmp, INPUT);
  pinMode(Hmm, OUTPUT);
  digitalWrite(Hmm, HIGH);
}


texts: what is the importance of the resistors that connect to push buttons ? can i replace them by wires?

texts:
Please, iam a junior in arduino and i want to know what is the importance of the resistors that connect to push buttons? can i replace them by wires?
thanks in advance.


texts: compilation error when changing variable from char to String

texts:
I have a code with these two lines:

  char handshakecode = "S"; // Capital S
  char receive;

The lines of code are placed in a separate void, and not setup or loop.
When i change the two variables from char to String i get a error(complete error at bottom) when compiling to the arduino or verifying the code.

  String handshakecode = "S"; // Capital S
  String receive;

When i snippes out partial code for just that particular void, it compiles fine, so it must be in combination with the rest of the code, which i have left out from this post at the moment.

Is this a known error or am I doing something wrong?

  In function 'global constructors keyed to 65535_0_WFS_v0.3.ino.cpp.o':

  lto1.exe: internal compiler error: Segmentation fault

  Please submit a full bug report,

  with preprocessed source if appropriate.

  See http://gcc.gnu.org/bugs.html for instructions.

  lto-wrapper.exe: fatal error: C:\Program
  Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc
  returned 1 exit status

  compilation terminated.

  c:/program
  files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe:
  error: lto-wrapper failed

  collect2.exe: error: ld returned 1 exit status

  exit status 1 Error compiling for board Arduino/Genuino Mega or Mega
  2560.