texts: Why NVIC_EnableIRQ handler function only run once?

texts:
I have a code that spit out random number when the ISR register is ready:
#define TRNG_KEY  0x524E47
uint8_t lut[10] = {0xF6, 0x12, 0xAE, 0xEC, 0xD8, 0x7C, 0x7E, 0xE0, 0xFE, 0xFC};
uint32_t msk = 0x1FE;

void setup()
{
  Serial.begin(9600);
  PIOC->PIO_PER = msk;
  PIOC->PIO_OER = msk;
  PIOC->PIO_OWDR = ~msk;

  PMC->PMC_PCER1 = PMC_PCER1_PID41;
  TRNG->TRNG_CR = TRNG_CR_ENABLE | TRNG_CR_KEY(TRNG_KEY);
  TRNG->TRNG_IER = 1 << 0;
}

void loop()
{
  if (TRNG->TRNG_ISR == 1) {
  PIOC->PIO_ODSR = lut[REG_TRNG_ODATA % 10];
  }
  delay(500);
}

The code above works. However, when I tried to switch to internal interrupt:
#define TRNG_KEY  0x524E47
uint8_t lut[10] = {0xF6, 0x12, 0xAE, 0xEC, 0xD8, 0x7C, 0x7E, 0xE0, 0xFE, 0xFC};
uint32_t msk = 0x1FE;

void setup()
{
  Serial.begin(9600);
  PIOC->PIO_PER = msk;
  PIOC->PIO_OER = msk;
  PIOC->PIO_OWDR = ~msk;

  PMC->PMC_PCER1 = PMC_PCER1_PID41;
  TRNG->TRNG_CR = TRNG_CR_ENABLE | TRNG_CR_KEY(TRNG_KEY);
  TRNG->TRNG_IER = 1 << 0;

  NVIC_EnableIRQ(TRNG_IRQn);
}

void loop()
{

}

void TRNG_Handler(void) {
  PIOC->PIO_ODSR = lut[REG_TRNG_ODATA % 10];
}

The code only spit out one random number and then freezes, indicating TRNG_Handler(void) was only executed once. I cannot figure out why.
Thanks in Advance !


texts: Flash "sketch" hex over ISP, without bootloader - possible?

texts:
I'm wondering if it's possible to flash the arduino sketch into a AVR, without using a bootloader - over ISP. I'd use the BSD programmer, which is basically parallel port with some resistors.

Let's say I use the Arduino IDE, try to upload with "verbose" (no actual arduino is attached) - it shows path to the hex in the verbose output, and I "steal" the file.

Now I'd flash it using avrdude onto a blank 328 via ISP - would that work?

I assume there needs to be a 16Mhz crystal, is that it? Any other pitfalls I have to be careful about?


texts: How is a long int stored in an 8 bit Arduino register

texts:
Assume the following code in C:

long int a = 262143;

which in binary will be 111111111111111111 (18 bits).
If an atmega328p register can hold 8 bits, how is the above represented in the register?

Compiled Assembly:

    .file   "a.c"
__SP_H__ = 0x3e
__SP_L__ = 0x3d
__SREG__ = 0x3f
__tmp_reg__ = 0
__zero_reg__ = 1
    .text
.global main
    .type   main, @function
main:
    push r28
    push r29
    rcall .
    rcall .
    in r28,__SP_L__
    in r29,__SP_H__
/* prologue: function */
/* frame size = 4 */
/* stack size = 6 */
.L__stack_usage = 6
    ldi r24,lo8(-1)
    ldi r25,lo8(-1)
    ldi r26,lo8(3)
    ldi r27,0
    std Y+1,r24
    std Y+2,r25
    std Y+3,r26
    std Y+4,r27
    ldi r24,0
    ldi r25,0
/* epilogue start */
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop r29
    pop r28
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 8.2.0"


texts: Two data outputs to be displayed on one 16x1 lcd display

texts: Before pursuing this very far, I would like to know if I can get two different data outputs (one on the left 8 and the other data on the right 8).  And if so, are there any requirements on the display or any other thing that might be needed.  I'm thinking that as far as the proper Arduino platform being the Mega 2560.  My idea is to put together an FSX navigation radio for my flight simulator.


texts:
I am trying to reduce the power of my Arduino Nano IoT. I would like to run it using a battery over a longer time period. I thought this would be possible when putting it to sleep most of the time. However, at the moment I can only reduce the power consumption to 10mA by

disabling wifi using the WiFiNINA library
putting the arduino to sleep using the ArduinoLowPower library
removing both LEDs
powering it through a 4,5V battery

Is there anything else I can do to further reduce power consumption? If not, is there another, more suitable device I can use instead for this project? It has to support wifi and use very low power during sleep.


texts: Using Multiple Serial Ports with arduino nano

texts: I am using a arduino nano to control a adafruit ultimate gps and a xbee wireless controller. However I recently ran into a problem using both at the same time (before I was using each separately until now) and read that I cannot listen to 2 software serials at the same time with a arduino. The biggest problem I see is that since I can only listen to one at a time, if I open a port, will cached data from the xbee and/or gps instantly start transferring in? Or or it more luck based that I will catch it as it comes? How should I go about coding around this? Should I just close and reopen the ports as needed(assuming there is no luck factor involved)? Any help is greatly appreciated. I will explain more if necessary.


texts:
I'm a really passionate beginner with arduino and electronics and I've built a Keypad lock for my room's door (inside the house).

I've used an arduino that activates a motor using a transistor to open the door if the correct pin is entered.

I want to add wifi control to my project. I have a few transistors, relays and ESP01s lying around for the upgrade. I want to use the blynk app and use the ESP01 independently without disturbing or modifying the arduino code. I'll program the ESP01 directly.

These are my requirements:

-A failsafe so I can open the lock via blynk if I forget the pin

-A kill switch that will turn off the arduino if I suspect somebody knows my PIN.

These are my ideas:

-Can I directly connect an ESP GPIO pin to the base of the transistor where the arduino is connected? By doing this can I control the transistor to switch the motor via both the arduino and the ESP 01?

-Can I put a relay module between the arduino and the battery pack and connect it to the ESP? I will connect the relay so that it will disconnect power to the arduino only when powered on. Is this a viable solution for a kill switch?

Any suggestions and ideas about how to go about this will be highly appreciated.


texts: Make device based on CH340G working as keyboard

texts:
There is small board with gyroscope. Controller - Atmega 8a, com-usb chip is CH340G. Board is handmade but not by me so I don't sure is it Arduino clone or not. It works with "ch341ser" driver on the computer and is used in small video game writed on java. This game is ran by .bat file where I specify COM port number, game listen this port in code.

I need to do anything to make computer understand gyro tilt as arrow keyboard buttons commands. In other words I need to write a driver or smth else to make computer understand device as USB HID keyboard. Is it possible to do it programmatically and how to do that?


texts: How can I use a variable to choose which Serial port to interact with?

texts:
In my use case I have multiple devices connected to the serial ports of an arduino. Currently I write to them using Serial1.write(), Serial2.write(), etc.

How can I choose the port programmatically, for example:

for(int i = 0; i < numDevices; i++){
  Serial[i].write();
}


texts: Uploading Marlin Firmware To Melzi-ATmega1284p

texts:
I'm trying to flash the Marlin Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. Melzi is a variation of Sanguino, and Sanguino is a variation of the Arduino.

The problem is that the version I'm using of Marlin (this one, development branch) only works with Arduino Mega. I saw that the file pins_RAMPS_13.h says the following (line 15-17):

#if !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__)
   #error Oops!  Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu.
#endif

So I tried to make this part to look like this:

#if !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(__AVR_Melzi_ATmega1284p16mhz__)
   #error Oops!  Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu.
#endif

Does anybody know if there's another repository made for the Melzi board?
Or if I should use another firmware, like Repetier (I tried, fail)?
Thanks for any help.


texts: I have an Arduino micro http://arduino.cc/en/Main/arduinoBoardMicro I was looking to know which is the lowest version of the IDE that support it. Actually on the IDE 0023 is not present in Tools > Board.


texts: Why is my real time clock getting the wrong time from my PC?

texts:
I want my real-time clock to set its time as the time on my PC. However, when I run the following sketch, the real-time clock reports the time as being 32-33 seconds earlier than my PC says the time is.

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

RTC_DS1307 RTC;

void setup () {
  Serial.begin(57600);
  Wire.begin();
  RTC.begin();

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
// uncomment it & upload to set the time, date and start run the RTC!
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop () {
  DateTime now = RTC.now();
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
}

I have also tried manually setting the time on the RTC, but I end up with the same problem: the RTC is always 32-33 seconds behind what I set it to. The lag happens as soon as I run the sketch. It seems very odd to me that no matter how I try to set the time, I end up with exactly the same error. I can tell the Arduino to report the time as being 33 seconds after what the RTC says it is, but this solution seems kind of sketchy, and I am worried that something is fundamentally wrong with my RTC or the way I am using it.

I am using an Arduino Uno with an Assembled Data Logging Shield from Adafruit. The data logging shield uses a DS1307 RTC. Has anyone had this problem before, or have any ideas about what could be causing it? Any help would be much appreciated.


texts: Data transfer to and from Arduino to Raspberry Pi

texts:
I am trying to transmit MPU6050 accelerometer data + data from 3 potentiometers from Arduino to Raspberry Pi. I do post processing here (on Raspberry Pi) and then transfer the data back to Arduino to move actuators. However my problem is that when I try to write the processed data back to Arduino, I see that even the stream of incoming data from Arduino starts getting corrupted and everything becomes really slow . Even If I just read serial data from Arduino, things are slower if than if I do the processing on Arduino directly. Also, the accelerometer data seems to become unresponsive i.e. its value doesn't change if I move the accelerometer. Everything just works fine if all the processing is done on Arduino. I don't know what is going wrong. Below are my Arduino and Python functions / codes.

Arduino Code:

void send_rec_data(){

    Serial.print(Kp);
    Serial.print(",");
    Serial.print(Kd);
    Serial.print(",");
    Serial.print(Ki);
    Serial.print(",");
    Serial.println(Theta_x);

    delay(20);

  if (Serial.available()>0){ // Read data sent by Raspberry Pi / Piserial

    str_data = Serial.readString();

    int firstCommaIndex = str_data.indexOf(',');

    cmd = str_data.substring(0, firstCommaIndex); // This stores the Scaled output from the Raspberry Pi

    param1 = str_data.substring(firstCommaIndex+1); // This stores the error from the Raspberry Pi to decide motor roattion direction

    Output = cmd.toFloat(); my_error = param1.toFloat(); // Change the outputs from string to float

    blink_led(); // Blink LEDS if data is received from Raspberry Pi

  }

}

Python Code:

while 1:

    data = cont.get_serial_data(arduino)

    time.sleep(0.02)

    if data is not None:

        Kp, Kd, Ki, Theta_x = data

        print(" \n Arduino sent Kp = ", Kp , "Kd = ",Kd , "Ki = ", Ki, "Theta_x = ", Theta_x)

        cont.set_tunings(Kp, Kd, 0)

        Output_scaled = cont.Compute_PID_Output(Input = Theta_x) # Compute the output of PID Algorithm

        ff = str(Output_scaled)+','+str(cont.error)

        arduino.write(ff.encode())

        print("\n Computed data sent TO ARDUINO Output_scaled = ", Output_scaled, "Error = ", cont.error)

arduino.close()

I have spent quiet sometime to resolve the issue byputting delays, flushing buffer but nothing has worked so far. Can someone please help.

Thanks.


texts: Arduino AT not working (Arduino UNO and HC-06)

texts:
Recently had issues with HC-06 AND Arduino UNO. Turned out that the last module was not working, this module keeps flashing and it appeared in the Bluetooth list.
I'm trying to work with some AT commands but for some reason this doesn't work. This module is brand new (ZS-040).

#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 3); // RX, TX
/*
 * Connect pin 2 Arduino to pin TX HC-06
 * Connect pin 3 Arduino to pin RX HC-06
 */
void setup() {

Serial.begin(9600);

Serial.println("Enter AT commands:");

btSerial.begin(9600);

}

void loop()

{

if (btSerial.available())

Serial.write(btSerial.read());

if (Serial.available())

btSerial.write(Serial.read());

}

I uploaded the code, went into Serial Monitor. When I type a command, I get no reply. I opened "Arduino Bluetooth" app,connected to my phone and when I type something in the terminal on my phone I see the text on my PC's Serial Monitor screen.
Any ideas what I should do next? Could it be something to do with the RX pin? Should I use voltage divider? I have 1k and 2k Ohm resistors, how should I connect them if that's the solution?


texts: Burn bootloader on custom ATmega 2560 board

texts:
I have developed and produced a custom board with a ATmega 2560 on it and a FT232RL for USB communication. I want to burn an Arduino bootloader onto the board without using an external Arduino as ISP. I can't seem to figure out how.
When I just click "burn bootloader" from the arduino software it says:

avrdude: stk500_recv(): programmer not responding

What am I doing wrong and how can I correctly burn the bootloader?


texts:
I am a novice in Arduino. I am working on a temperature controller for a hot plate. I have a PT100 as sensor which is being driven by a 1mA constant current source. As the resulting output voltage is quite low, I am using an OpAmp for a gain of 11. The output of the OpAmp is connected to pin A4 of the Arduino.

The desired temperature is set by means of a potentiometer, the output of which (0-5V) is connected to pin A1 on the Arduino.

The PWM output for the heater is from Pin 9 and is fed to an opto-isolator (the output of which is  connected to a Triac, which in turn controls the power to the heater element).

All this works quite well, except for a bug that I have not been able to find:
On switching on, the PWM output is zero. It activates only when the potentiometer setting is brought quite low. After that, the setting can be changed as desired and everything works well. For example, if the potentiometer setting is for say, 150 degrees, the system will work just fine as long as it is not switched off (or if the power is not disrupted). In case of switching off (or power failure), followed by a subsequent switching on, the PWM output remains zero. It is only on bringing the potentiometer to a relatively lower setting that the PWM output gets reactivated. Once it does, then the potentiometer can safely be brought back to the original (or any other desired setting) and everything works just fine.
Can anyone help me in finding the bug? I want that on switching on, the system should start working right away and control the heater (PWM) so as to attain the temperature as set by the potentiometer.

My sketch is as below:

// Heater Controller

int heatingInPin = A1;// Heating pot slider connects here
int sensorPin = A4;// Temp Sensor output (amplified) connects here
int heaterPin = 9;// PWM heater output is available here
int tempDiff;

int sensorCount;// this holds the value of the Temperature Sensor after amplification
int heatSetCount;// this holds the value of the Temperature Control Pot
int pulseWidth;

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

void loop()
{
    sensorCount = analogRead(sensorPin);
    sensorCount = (sensorCount - 247);// apply offsetvalue
    heatSetCount = analogRead(heatingInPin);

    heatSetCount = map(heatSetCount, 31,1023,0,440);// This gives a maximum temp of 400 degrees

    if (sensorCount >= heatSetCount)
    {
        analogWrite(heaterPin,0);
    }
    else
    {
        tempDiff = (heatSetCount - sensorCount);

        if (tempDiff >= 25)
        {
            pulseWidth == 255;// heater is full ON
        }
        else
        {
            pulseWidth = (10 * tempDiff);
        }
        analogWrite (heaterPin,pulseWidth);
    }
    delay (10);
}


texts: Ethernet shield not have MAC address sticker

texts: Hi everyone I recently bought an Arduino Mega and Arduino Ethernet Shield. There are lots of forum posts that say the shield should have a MAC address that is written on the back side of shield, but I don't have any sticker which has the MAC address. Does anyone know how I can get my MAC address or configure it with a new MAC address? Thanks


texts: Reading consecutive two pulse periods continuously

texts:
I'm controlling the DC motor/fan speed by PWM through varying analog input. Using Uno or Nano.

The loop is as follows:

void loop()
{
  val = analogRead(analogPin0);  // read the analog input pin
  analogWrite(pwmPin9, map(val, 0, 1024, 0 , 255));
}

Above analogPin0 value is varied by a poti.

But I also want to output the rpm on an LCD. To do that I need to measure the period between two consecutive pulses as shown below:

How could I measure continuously "period between two consecutive pulses"? Should I use interrupt? Does anybody have any experience with that?


texts:
I have two servos connected to an Arduino, They work fine if i write to them one by one so the wiring is all correct. I have seen a lot of examples here but none are facing the same issue. I have a simple for loop with Servo.write() on two servos (Facing each other) one going clockwise and the other going counterclockwise. I just want them to rotate at the same time and i cannot connect them to the same signal line since their movement is opposite.
My Code Is:

 for(int pos = 0; pos < 90; pos += 2)
 {
     delay(200);
     int pos7 = 90-pos;
     pos7 = pos7*(-1);
     myservo6.write(pos);
     myservo7.write(pos7);
 }

What Is Happening
Both the servos go to the "same position" (if one is at 90 the other is at 0 etc.. ) Yet one goes there slow and the other goes super fast(not affected by delay). Even though my delay should affect both servos.

If i remove the delay they both go to the same position yet very fast. What i need is for them to move together slowly to the position.


texts: Arduino and 2 Adafruit Fingerprint modules working together

texts: I want to do a project with fingerprint access control. But my client wants one on both sides of the door (inside and outside). Now I am using this product Adafruit Fingerprint module but I don't want to enroll each person on each fingerprint module. I want to look at enrolling each employee on 1 of these modules and then via arduino "SYNC" the fingerprint models between each other. Is this possible? Can someone maybe point me in the right direction or am I just insane HAHAHA. Look I can do the route of programming/enrolling each person on each module. But we life in a real world and at some point the fingerprint model/id's are not going to match up. And then there is going to come a problem with my online software. As well sorry for my bad lanuage  :)


texts:
I'm running Arduino IDE 1.6.10 on Mac OS X 10.12.1.
I read on the Arduino official sote that the IDE should create function prototypes for me, and it always did. But now I'm writing a 1500 lines program, with dozens of functions, and this tool wold be quite useful (although I obviously don't really need it)... and it doesn't work.
Is that a known issue?


texts: Sending a text message through a arduino wifi shield

texts: I am using an Arduino uno and need to send text messages and email messages from the device based on certain events occurring.  I have the logic figured out of when to send the text message or email but don't know what shield I need to send these messages.


texts: Can I use custom ethernet shield with standard libraries?

texts:
I would like to make a custom ethernet card that uses the enc28j60 like this:
DIY Ethernet card

but first I would like to know if I can use the standard libraries which can be used with the ethernet card which is in the market like this:
ENC28J60 ethernet module


texts:
I had used Arduino Uno & RFID but now i want to run same code in Esp8266MOD.
i have installed all the drivers and everything else to run esp8266 in Arduino IDE but i dont know how to connect rfid in esp8266. Can someone please compare which arduino pin & esp8266 pin are similar

 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             ?
 * SPI SS      SDA(SS)      10            ?
 * SPI MOSI    MOSI         11 / ICSP-4   ?
 * SPI MISO    MISO         12 / ICSP-1   ?
 * SPI SCK     SCK          13 / ICSP-3   ?


texts: Making pushbutton behave as a toggle switch with ezButton - do I have to use ledstate with =! operator

texts:
I'm using ezbutton to make a pushbutton act like a toggle switch, first press doing permanent on, second press doing permanent off. I'm just trying to understand the basic coding. This project is just a testbed for what I'm planning to do later - wiring vehicle toggle switches to Arduino and feeding the output signal to mosfet that will control the load state. So I'm trying to get the code as nice and tidy as I possible can. In the code below, I would like to know if ledState will be applicable when this sketch will control a mosfet instead of a test led, and I've seen comments saying "ledState = !ledState;" is not optimal - but being a beginner I'm not sure what this means, and is there a better more sound way to address it. Thanks!
#include <ezButton.h>

// ---
// Declaration
// ---

const int button1  = 9;
const int led1     = 4;
int ledState = LOW;

ezButton button(button1);

// ---
// Setup
// ---

void setup()
{

  pinMode(led1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  button.setDebounceTime(50);

}

// ***
// Main Loop
// ***
void loop()
{

  button.loop();

  if (button.isPressed()) {
    ledState = !ledState;
    digitalWrite(led1, ledState);
  }

}


texts: How do I set a 25 kHz PWM signal on an ESP-WROOM-32?

texts:
I want to control a single pin of an ESP-WROOM-32 to have a 25 kHz PWM signal. How do I do that in Arduino Studio? I compiled a "hello world" program for such a device successfully in Arduino Studio, now what steps do I need to take? (Other libraries? Source Code?)

FYI: I'd like to do quite the same as provided in Set PWM frequency to 25 kHz but not on an AVM micro-controller but an ESP32. There are tons of explanations for original Arduinos and ESP8266s using bit banging in various forms. But how do I do that on an ESP-WROOM-32 using no bit banging but built in PWM?

Background: I'd like to control a standard 12V PWM fan with this signal. As far as I learned I just can connect a pin with the PWM input of the fan. I just don't seem to be able to figure out how to produce such high frequent PWM signals on an ESP32 :-/ Please help!


texts: Algorithm to detect motion using ultrasonic sensor

texts:
I have a PIR sensor which sometimes give false readings and I have added a ultrasonic sensor to compensate for that. I think my algorithm can work, however currently it is very prone to give false positives.

Algorithm theory

My idea is to have an arduino which will obtain six samples and wait 25 milliseconds between each sample and then calculate the variance. If the variance exceeds a specific threshold, which I have set to a thousnad, it will send an motion event over the serial bus.

Problem with the algorithm

Ultrasonic sensors can give faulty responds which usually isn't hard to detect. My HC-SR04 sensor can only accurately read the distance between 2 cm and 400 cm. All the faulty readings are usually way over 400 cm or lower than 2 cm, therefore if is not within these boundaries a new try will be made to get a value within the boundaries, if it fails for three times it will assume the distance is exactly 400 cm.

It is redundant to wait for more than 23280 µs because 400*29.1*2 is the corresponding microseconds it would take for the distance to be 400 cm. pulseIn has a timeout value which can be used for this.

In theory this sounds great to me but very often this algorithm will erroneously send motion events. My belief for this is that when the ultrasonic sensor transmitts a wave and wait for it come back, pulseIn will timeout and retry and yet again ask the sensor to send a wave. This happens before the first wave has come back thus the distance will be incorrect and vary from time to time making the variance higher than my threshold.

If the distance is much lower than 4 metres my algorithm works very well.

What I tried

I figured I might be able to block for some time until the echo pin on the ultrasonic sensor turns low or a time of 100ms has passed. The code hanged and I couldn't communicate with my arduino any more. I can't see the problem with my code to obtain the distance pursuant to the ultrasonic sensor.

for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      continue;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
}
return 400.0f;

This just blocks my program indefinently and I had to upload a new program removing that code for my arduino to respond again.

So my question boils down to: how can I resolve this issue where my algorithm very frequently sends motion events erroneously? Is there a better way to detect motion with an ultrasonic sensor?

(EDIT: I was really tired when I wrote the code above and Majenko corrected me, I changed the code for this

for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(PINB & 0b00000010) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      goto retry;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
  retry:
  continue;
}
return 400.0f;


texts: Read a String from serial to debug the AT commands sent to my GPS shield

texts:
I want to extract an AT command's response (via serial port) to find out if the GPS shield is working as it should be.

I used:

  if(Serial.available()>1){
     String response = Serial.read();
     Serial.println(response);
  }

Normally the response to AT is OK but it keeps telling me that it cannot convert int to String .... can someone help?


texts: Are there any advantages to Wifi shields as opposed to a Yun?

texts:
I have an Arduino Uno and I have a remote sensing project for which I need Wifi connectivity. After doing research, I've found that I have 2 options:

Buy a WiFi shield for my existing Uno
Buy an Arduino Yun with built-in WiFi

Looking at costs, I found that a WiFi shield costs more than double what it costs to buy a Yun, so it would seem to me that the best option is the Yun as I'd save some cash and get a more capable board. However, I can't help but think I'm missing something.

What are the advantages of an Uno plus Wifi shield as opposed to a Yun?


texts: How to display information from a web API on an LCD (2x16) in real time?

texts:
How can I display information from a web API on an LCD (2x16)?

This is an example of the data returned by the API for train times.

The information that I want to display on the LCD is time information (2 min, 5 min, etc., ...)


texts: Problem when using PROGMEM on array holding notes for speaker on Arduino

texts:
The problem I've been having is a little weird. I'm trying to set up audio for my Arduino project and have been playing around with the example included in the IDE. The problem is whenever I try to make the array of notes go into PROGMEM, it makes the outputted note higher than the one I put in. I don't want it to do that.
In case it is relevant, the code I have is as follows:

    #define tuneSize 2
    // notes in the melody:
    const int melody[tuneSize] PROGMEM /*This is what's screwing it up*/= {
      NOTE_AS3, 0
    };

    // note durations: 4 = quarter note, 8 = eighth note, etc.:
    int noteDurations[tuneSize] = {
      6, 16
    };

    void setup() {
      // no need to repeat the melody.
      // iterate over the notes of the melody:
      for (int thisNote = 0; thisNote < tuneSize; thisNote++) {

        // to calculate the note duration, take one second
        // divided by the note type.
        //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(8, melody[thisNote], noteDuration);

        // to distinguish the notes, set a minimum time between them.
        // the note's duration + 30% seems to work well:
        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);
        // stop the tone playing:
        noTone(8);
    }
}

(Pitch.h can be found in the Arduino example tab under digital)

My circuit has an 8 ohm resistor on pin 8. That's it.

The only thing I can think is that since the PROGMEM is slower, the data doesn't get to the speakers as fast thus making the output weird. Does anyone know how to fix this issue? Also, just having it on SRAM is not ideal because I'm working with a display and the lib it uses uses a lot of SRAM.


texts: Is it possible that function will get a parameter that can be int OR char?

texts:
I'm trying to create a function that enters a key/value into a JSON file.

But, since value can be an int or char, I don't want to create 2 functions for each type.

Is there a way ?

void setValue(char *key, char* value){
        StaticJsonDocument<512> tempJDOC;
        tempJDOC[key]=value;
}

EDIT1

#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (char *key);

template <class T>
void setValue(const char *key, T value);
//void setValue(const char *key, char *value);

};
#endif

EDIT2

#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

#define LOG_LENGTH 4
#define DOC_SIZE 512

template <class T> // . <---- line added
class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (const char *key);
void removeValue(const char *key);
// void setValue(const char *key, char *value); <--- comment out
void updateArray(char* array_key, int val);
void printFile();
void setValue(const char *key, T value); <---- Added

};
#endif

and in .cpp file :

void myJSON::setValue(const char *key, T value){
        StaticJsonDocument<512> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
        myJSON::PrettyprintJSON(tempJDOC);
}


texts: Hello I am using the U8glib library and a Nokia 5110 screen to draw graphics and text. That all works but I want to draw a 'fake' graph. It would be cool if it was animated randomly. How can I draw a graph or a curved line that looks like a graph and have it update every few seconds? Thanks.


texts: Unable to tell if error is from receiving or transmitting end

texts:
so I am having trouble sending data using software serial's write function.

TX Code:

#include <SoftwareSerial.h>

SoftwareSerial TX(2,3);

void setup() {
  // put your setup code here, to run once:
  TX.begin(1200);
}

void loop() {
    TX.write(60);
}

Is the delay necessary?

RX Code:

#include <SoftwareSerial.h>
SoftwareSerial RX(2,3); //(rx pin, tx pin)
const unsigned int bufferSize = 100;

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

}

void printBuffer(const uint8_t *serialBuffer)
{
  //print contents of buffer
  for (int i = 0; i<100; i++)
    Serial.println(serialBuffer[i], BIN);
}

void processBytes(const uint8_t value)
{
  static uint8_t serialBuffer[bufferSize]; //buffer to hold values
  static unsigned int startPosition=0;

  if(startPosition < bufferSize)
    serialBuffer[startPosition++] = value;

  else
  {
    printBuffer(serialBuffer);
    startPosition = 0;
  }

}//end of processBytes
void loop() {

  //check if data is available in serial buffer
  while(RX.available())
  {
    //process data
    processBytes(RX.read());
  }
}

If i transmit the number 60, it prints 226 constantly for 2-3 seconds, then prints 60 for a short while, then goes back to printing 226. Am I doing something wrong with my code?

FIRST QUESTION: In the case when startPosition (in the process function) equals 100, it will call print. Print will then print 100 integers. Now, when doing that, there could still be data being transmitted from the transmitter. But the read function won't be executed until printBuffer returns, process returns, and the while loop iterates again. So during that time, couldn't some transmitted values potentially not be read?

SECOND QUESTION How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? How does this get resolved? I looked at the software serial library, but I am not able to find out why. Any guidance here?

THIRD QUESTION Other than getting the startbit syncing right, are there other ways to sync the data? I was reading of NRZ encoding, manchester encoding, etc. Can any of these be implemented here? Also, would it be wise to alter the softwareSerial library to have more than one startbit?

Any guidance would be very appreciated! Thank you so much!
This is all being done with wireless RF modules.


texts: How do I make a proper long string scanner to detect specific tags in a stream of characters?

texts:
Here's my code:

#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX, TX

void setup() {
    Serial.begin(9600);
    BTserial.begin(9600);
    Serial.println("Communication with HC-05 successfully started.");
}

bool is_uploading_book = false;
char c = ' ';
String recv_scanner = "";
void loop(){
    if (BTserial.available()) {
        c = BTserial.read();
        recv_scanner += c;
        if(recv_scanner.length() >= 50) {
          recv_scanner.remove(0, 1);
        }
        // I believe there's something wrong with the recv_scanner.
        if(is_uploading_book) {
          Serial.write(c);
        } else {
          if(recv_scanner.indexOf("(__BOOK_UPLOAD_START__)") >= 0) {
            is_uploading_book = true;
          }
        }
        Serial.println("\n\n" + recv_scanner + "\n\n");
    }
}

I'm sending a book (long text) in the form of characters one by one from my phone to my HC-05 module (and the Arduino).
My goal is to spot the tag "(_BOOK_UPLOAD_START_)" in the incoming characters.
Arduino allows me to receive the characters of the book one by one on each loop.
I'm storing those characters in a string called recv_scanner where I allow it's maximum size to be 50 characters and once it reaches those 50 characters, I start to remove the first character and add a new one on each loop (so it can only see 50 characters at a time because maximum String length is 200 and for my purposes, 50 is enough).
The thing is, it doesn't work properly.
When I Serial.println the recv_scanner on every loop (so I see how it progresses) it starts to look like this:

⸮qsnieq⸮cn .laslvanm.⸮⸮⸮d⸮alvuv⸮⸮urosqiam tr⸮⸮⸮

(It starts normally and then slowly progresses into this)
I have no idea what that is.
As far as my predictions go, it should show 50 characters and they should be parts of the books.
Is there something fundamental about Strings that I don't know of?
I'm doing this so I'm able to detect a tag (_BOOK_UPLOAD_END_) at the end of the book and finish uploading.
Feel free to ask my questions if something is unclear.


texts: XH-M131 Photoresistor Relay Module NC position

texts:
I have purchased XH-M131 Photoresistor Relay Module to automatically light my outdoor yard at sunset and turn it off at sunrise. I'ts working as it is supposed to, However, if I power off the relay, the light goes off.
I want this to be a closed circuit in such way if the relay malfunction or loose power, the outdoor light stays on which I can manually switch off if I want to.
BTW, I tried connecting the light wires to the otherside, but the whole thing reversed, light goes on when light detected which defies the purpose. Any suggestion or modifications.


texts: How can an Arduino-Quadcopter be stabilized?

texts:
I have built an arduino quad-copter and I am using an MPU6050 to read the rotational position and velocity of the aircraft. The problem is that I cannot get the thing to stabilize. Watch this video here to get an idea of what I mean.

So as you can see from the footage (and you did watch it, right?), I'm not even getting steady oscillations, it's just random. What I don't understand is how people get their quad-copters to oscillate very quickly (maybe 10 times per second) and then trim up their PID gains to smooth it out, whereas if I raise my p-gain high enough for it to adjust that quickly, the quad-copter just goes berserk and tries to kill me.

And, speaking of p-gains, here's the PID I wrote:

float KrP = 0.002000;
float KrI = 0.000001;
float KrD = 0.200000;

void adjustRoll(float currentRoll, int newRoll) {
  if (thrust <= 1200){
    inAutoRoll = false;
    NWPower = thrust;
    NEPower = thrust;        //PID not ready to turn on yet? Just set motor powers
    SWPower = thrust;        //equal to the throttle.
    SEPower = thrust;

    I_roll = 0;              // Reset the integral.
    return;                  // Don't do anything else
  }

  float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
                                                                       // adjust, based on the error.

  if (newRate > 50)newRate = 50;        // Don't adjust too fast!
  else if (newRate < -50)newRate = -50;

  float offset = newRate - rollRate;

  I_roll += KrI * offset;

  if(!inAutoRoll) {        // Is the PID just now turning on? (Throttle requirement met).
    lastRollRateOffset = offset;  //Smooth transition.
    inAutoRoll = true;
  }

  float adjust = (KrP * offset) + (KrI * I_roll) + (KrD * (offset - lastRollRateOffset));

  NWPower += adjust;
  NEPower -= adjust;
  SWPower += adjust;
  SEPower -= adjust;

  if (NWPower > maxOut) NWPower = maxOut;
   else if (NWPower < minOut) NWPower = minOut;

  if (NEPower > maxOut) NEPower = maxOut;
   else if (NEPower < minOut) NEPower = minOut;

  if (SWPower > maxOut) SWPower = maxOut;
   else if (SWPower < minOut) SWPower = minOut;

  if (SEPower > maxOut) SEPower = maxOut;
   else if (SEPower < minOut) SEPower = minOut;

  lastRollRateOffset = offset;
}

And in case you were wondering... yes, I do know about integral windup. The reason I have not dealt with that in my code is because the quadcopter is no where near stable, so I'm not worrying about perfection just yet. Also, I have my I-gain set to 0.000001, so it doesn't matter. The reason I have done this is because (as far as I know) a quadcopter can fly with only P and D, and with the way mine is behaving, I think a larger I-gain would only make things worse.

More detail about my PID: The PID corrects for the rotational velocity of the quad-copter, which, as I understand it, is the best way to control a quadcopter. The correction-rotation-rate is determined by multiplying the error (in degrees) by two. Why two? I dunno. I experimented with some other multipliers and two seems to be okay. Its also a prime number, so, yeah...

So anyways! What do I need to do to make the quad-copter stable? I have seen amazingly perfect quad-copters using the same arduino and the same MPU6050, but mine just tilts all over the place.

Some possible problems off the top of my head:

Bad algorithm for calculating the needed rotational velocity based on error.
Bad PID algorithm.
Bad PID gains.
I didn't balance my props, but seriously, would a couple of pieces of electrical tape stuck to the props really fix this? It doesn't seem like it would.

Thanks for any help you have to offer!


texts: Sending more than BUFFER_LENGTH(32) bytes in slave answer I2C

texts:
I need to send 259 bytes as answer to I2C master read request. AFAIK there is a buffer limit of 32 bytes in Wire.h and in HW (Arduino Nano). Is there a way sending 259 byte answer, or I have to choose another HW?

The code is:

void serveInitCommunication() {
  Serial.println("serveInitCommunication()");
  static unsigned int counter = 0;
  auto answer = findInitAnswer(counter);

  uint8_t buffer[260]; //maximum size from dataLengths[] in comm_init_data.h
  memcpy_P(buffer, answer.dataPtrProgmem, answer.dataSize);

  Serial.print(" dataSize:");
  Serial.print(answer.dataSize);
  Serial.print(" data:");
  Serial.println(int(buffer[answer.dataSize - 1]));

  auto bytesToWrite = answer.dataSize;
  uint16_t bytesWritten{0};

  while (bytesToWrite > BUFFER_LENGTH) {
    Serial.println("Write part");
    Wire.write(buffer + bytesWritten, BUFFER_LENGTH);
    bytesToWrite -= BUFFER_LENGTH;
    bytesWritten += BUFFER_LENGTH;
  }
  Serial.print("Bytes written:");
  Serial.print(bytesWritten);
  Serial.print(" Bytes yet to write:");
  Serial.println(bytesToWrite);
  Wire.write(buffer + bytesWritten, bytesToWrite);

  counter++;
}

And called is it:

void requestHandler() {
  char buff[100];
  sprintf(buff, "requestHandler addr:0x%x counter:%d", readAddress, msgReadCounter);
  Serial.println(buff);

  if (readAddress == INIT_MSG_ADDRESS) {
    serveInitCommunication();
  }
}

I've tried moving the serveInitCommunication() into void loop() and setting a just a flag in requestHandler() but without success. Sending up to 32 bytes works fine. Tnx

update: uint8_t twi_transmit(const uint8_t*, uint8_t); so twi library self limit data to 255 bytes

update2: there is a hacker way doing it, by replacing the twi.c twi_txBuffer and twi_txBufferLength with buffer from the sketch


texts:
I'm looking to use a simple IR sensor out in bright sunlight, which means hell lot of distortion. Is there any way I can modulate it using my Arduino UNO so that it isn't affected by sunlight and other ambient light sources?

The IR sensor is just like this one.


texts: Trying to read the current position of a flex sensor and store it as a variable? NANO ATmega328p

texts:
I am trying to write a code to read the current position of a flex sensor when a button is pushed and use that data to pulse a piezo. I set it up to read the flex sensor and to alarm when it gets 100 or below, that works! So what I want to do is integrate a button where you push it to set the current state of the flex sensor and then when its moved and is less than the number logged when the button was pressed then it alarms. I used to write in Basic and quick basic and am now (many years later in life) trying to learn C and am struggling. I'm using a NANO ATmega328p - here is my code so far:

int flexSensorPin = A0;//analog pin 7= tiny2=A1
const int Piezo = 3; //digital pin 3 = tiny0
const int inPin = 2; // Push Button to set current Bend Status
void setup() {
  pinMode (Piezo, OUTPUT);
  pinMode(inPin, INPUT);    // declare pushbutton as input
  Serial.begin(9600);
}
void loop() {
  int val = 0;
  val = digitalRead(inPin);
  int flexSensorReading = analogRead(flexSensorPin);
  Serial.println(flexSensorReading);
  if (flexSensorReading < 100) {
    Serial.println("Alarm! Set Angle Exceeded");
    digitalWrite(Piezo, HIGH);
    delay(100);
    digitalWrite(Piezo, LOW);

  }
  delay(250);
}


texts:
I'm trying to connect 16x2 LCD screen to clone Arduino UNO via PF8574T backpack. 4 cables are connected to +5V, GND, SDA and SDL pins.

When I tried this I2C scanner code from arduino.cc. It returned strange characters in serial monitor at first couple of tries. And now, when I try computer hangs.

When I use A4 A5 pins on the Arduino instead of SDA and SDL, i2c reported the device is on 0x27. It is ok. But if i keep LCD connected to Arduino, my iMac shutdowns after for a while. In error log i see there was a problem regarding USB serial device. I assume it as a power problem.

I'm on OS X Yosemite. Why this can be happening and how can I fix?

Note: Computer is hanging as soon as the Arduino usb cable connected.


texts: I2C communication between 2 Arduinos with updated wire library

texts:
I would like to enable communication between two Arduino 101. From what I have read, the best method is to use I2C using the wire library. However, it seems as though the newest Arduino IDE has an updated version of the Wire library that no longer includes the begin(int) and onRequest functions.

All of the tutorials for I2C communication use these methods, so I am unable to follow and use them. It looks like when I change the board to Arduino Uno these functions are found, but as soon as I change the board to Arduino 101 the following errors appear no matching function for call to TwoWire::begin(int).

When I try replacing my wire library with the older version, I get other errors for missing libraries and if I replace everything it is unable to compile on Arduino 101.

Can someone please help me or direct me to a I2C tutorial that uses the most updated version of the Wire library?


texts: Connecting 5V arduino logic with 12V car logic

texts:
I need to connect arduino to K-Line in my car's OBDII port.
I used an L7805 to power the atmega but how can I interface 12V car logic with 5V arduino logic?
The problem is, the connection has to be bidirectional- sometimes the arduino will pull the line high/low and sometimes the car will - the purpose of this connection is to get throttle, rpm etc. data.
This would be easy if the connection was one directional - I could use a transistor to steer 12V to going IN the K-Line and voltage divider if I wanted to do the reverse. But how to do both?


texts: I'm working on a project where my arduino is receiving a voltage 0-5V, I need the output to be 10V always. Is there a way to do that?


texts:
I made some arduino code for leds that blink down a row and then back again, but when the program is run, there is an approximately 2 second delay in between the first for loop and the second. This is my code in the loop function:

int leds[] = {13, 12, 11};
int i;

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

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

void loop() {
    for (i = 0; i < sizeof(leds); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i; i > 0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

It really makes the program look weird when the LEDs are blinking on a breadboard. Keep in mind that this only happens after the first for loop, the second is continuous back to the first. Any idea why this might be and how to fix it?


texts: How do I use PlatformIO to flash ESP-12F (ESP8266MOD)

texts:
In PlatformIO while creating a project , in the board selection there is no ESP-12F in the boards. While there is ESP-12E. I can flash ESP-12F while choosing ESP-12E from the boards without any flashing issue. But there are some runtime issues, the one that I noticed is the LED doesn't blink when flashed from PlatformIO , but works fine, when flashed using Arduino IDE using the same code.
So there may be some difference in the configurations.

  C:\Users\USER\.platformio\platforms\espressif8266\boards

In this directory I found the esp-12e board which is a JSON format.

{
  "build": {
    "core": "esp8266",
    "extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP12",
    "f_cpu": "80000000L",
    "f_flash": "40000000L",
    "flash_mode": "dio",
    "ldscript": "eagle.flash.4m1m.ld",
    "mcu": "esp8266",
    "variant": "nodemcu"
  },
  "connectivity": [
    "wifi"
  ],
  "frameworks": [
    "arduino",
    "simba",
    "esp8266-rtos-sdk",
    "esp8266-nonos-sdk"
  ],
  "name": "Espressif ESP8266 ESP-12E",
  "upload": {
    "maximum_ram_size": 81920,
    "maximum_size": 4194304,
    "require_upload_port": true,
    "resetmethod": "nodemcu",
    "speed": 115200
  },
  "url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
  "vendor": "Espressif"
}

How do I add ESP-12F to the PlatformIO boards and flashing without any issue.


texts:
I have an ESP8266-12E, I used it previously and it worked fine (approx 2 years ago)

I can't seem to get it to detect WiFi networks or appear as an Access Point

I can upload the blink sketch and the onboard LED will work correctly and the serial monitor will show output from the ESP8266, but there appears to be no WiFi functionality

I have tried using previous versions of the ESP core board definition via the Arduino board manager

I have tried using an external power supply (wall plug) rather than the powering from a USB port

I have tried erasing the flash using esptool.py

I have checked that the WiFi router I am trying to connect to is operating at 2.4Ghz (also there are other WiFi networks around and I set up a second router to make sure)

I have tried connecting to the Access Point using the SSID (with and without a password) despite it not appearing

I have tried getting it to connect to an Access Point even though none are found

Is there something I am missing or should I order a new module?

Any other suggestions please!

Output when uploading a sketch

    esptool.py v2.6
    Serial port /dev/cu.SLAB_USBtoUART
    Connecting........_
    Chip is ESP8266EX
    Features: WiFi
    MAC: a0:20:a6:12:51:46
    Uploading stub...
    Running stub...
    Stub running...
    Erasing flash (this may take a while)...
    Chip erase completed successfully in 9.0s
    Hard resetting via RTS pin...
    esptool.py v2.6
    Serial port /dev/cu.SLAB_USBtoUART
    Connecting........_
    Chip is ESP8266EX
    Features: WiFi
    MAC: a0:20:a6:12:54:54
    Uploading stub...
    Running stub...
    Stub running...
    Configuring flash size...
    Auto-detected Flash size: 4MB
    Compressed 293920 bytes to 210833...

    Writing at 0x00000000... (7 %)
    Writing at 0x00004000... (15 %)
    Writing at 0x00008000... (23 %)
    Writing at 0x0000c000... (30 %)
    Writing at 0x00010000... (38 %)
    Writing at 0x00014000... (46 %)
    Writing at 0x00018000... (53 %)
    Writing at 0x0001c000... (61 %)
    Writing at 0x00020000... (69 %)
    Writing at 0x00024000... (76 %)
    Writing at 0x00028000... (84 %)
    Writing at 0x0002c000... (92 %)
    Writing at 0x00030000... (100 %)
    Wrote 293920 bytes (210833 compressed) at 0x00000000 in 18.6 seconds (effective 126.4 kbit/s)...
    Hash of data verified.

    Leaving...
    Hard resetting via RTS pin...


texts: Get value from protected member of class

texts:
i'm really new to Arduino.
I have Arduino Mega, a USB host shield and a barcode scanner. I'm using this library >> link and modified it example so barcode scanner worked (Got it from here) to read what barcode scanner scanned and it worked just fine.

#include <usbhid.h>
#include <usbhub.h>
#include <hiduniversal.h>
#include <hidboot.h>
#include <SPI.h>

class MyParser : public HIDReportParser {
  public:
    MyParser();
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
    uint8_t getValue();
  protected:
    uint8_t KeyToAscii(bool upper, uint8_t mod, uint8_t key);
    virtual void OnKeyScanned(bool upper, uint8_t mod, uint8_t key);
    virtual void OnScanFinished();
};

MyParser::MyParser() {}

void MyParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
  // If error or empty, return
  if (buf[2] == 1 || buf[2] == 0) return;

  for (uint8_t i = 7; i >= 2; i--) {
    // If empty, skip
    if (buf[i] == 0) continue;

    // If enter signal emitted, scan finished
    if (buf[i] == UHS_HID_BOOT_KEY_ENTER) {
      OnScanFinished();
    }

    // If not, continue normally
    else {
      // If bit position not in 2, it's uppercase words
      OnKeyScanned(i > 2, buf, buf[i]);
    }

    return;
  }
}

uint8_t MyParser::getValue() {
  uint8_t getAscii;
  bool upper; uint8_t mod; uint8_t key;
  getAscii = KeyToAscii(upper, mod, key);
  return getAscii;
}

uint8_t MyParser::KeyToAscii(bool upper, uint8_t mod, uint8_t key) {
  // Letters
  if (VALUE_WITHIN(key, 0x04, 0x1d)) {
    if (upper) return (key - 4 + 'A');
    else return (key - 4 + 'a');
  }

  // Numbers
  else if (VALUE_WITHIN(key, 0x1e, 0x27)) {
    return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1');
  }

  return 0;
}

void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
  uint8_t ascii = KeyToAscii(upper, mod, key);
  Serial.print((char)ascii);
}

void MyParser::OnScanFinished() {
  Serial.println(" - Finished");
}

USB          Usb;
USBHub       Hub(&Usb);
HIDUniversal Hid(&Usb);
MyParser     Parser;

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

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

  delay( 200 );

  Hid.SetReportParser(0, &Parser);
}

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

So, I want to get the value from (char)ascii, store to char on loop and run it.

void MyParser::OnKeyScanned(bool upper, uint8_t mod, uint8_t key) {
  uint8_t ascii = KeyToAscii(upper, mod, key);
  Serial.print((char)ascii);
}

I tried created function that return the value but still no luck.

uint8_t MyParser::getValue() {
  uint8_t getAscii;
  bool upper; uint8_t mod; uint8_t key;
  getAscii = KeyToAscii(upper, mod, key);
  return getAscii;
}

Called it on loop:

void loop() {
  Usb.Task();
  uint8_t abcd = Parser.getValue();
  char c = (char)abcd;
  Serial.print(c);
}

What am I missing? Thank you.


texts: Use Arduino's PWM to control motor direction?

texts:
I'm looking for a way to allow Arduino to control a motor using PWM.

So far what I have gathered is that using Arduino's PWM sets the digital value of 255 to 5v and 0 to 0v.

However what I am looking to do is to set the motors to stop at 2.5v, move forward as it approaches 5v and move backwards as it approaches 0v.

Any suggestion on how I would go about accomplishing this will be highly appreciated.


texts: How can i connect 4 stepper motors and 3 sensors to an Anduino?

texts:
I have an Arduino AT MEGA 2560 circuit. I want to buy 1 Nema-17 bipolar stepper motors, 3 M49SP-2K stepper motors, 3 KY-032 sensors to do my project but i dont know how to connect them to my Arduino.
Is there any Arduino shield for my purpose? Can I use Ramps 1.4 Arduino shield?


texts: Arduino FIFO queue for with potentiometer values and 7 segment display

texts:
As of now I have code that takes a value from a potentiometer and maps it from 0-9. Based on this mapped value a number will be displayed on the seven segment display.

Currently, if I quickly turn the pot completely then back to zero it will show everything very quickly and then show 0 until I change the pot value again. What I am trying to do is make it so if it's quickly turned completely then back to 0, after a second it will display all the number from 0-9 then back down to 0, each for a second.

I was given a hint to use arrays to create a FIFO queue but I am not sure how to go about doing this and I have been stuck on this for a while. Here's my code:

// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
int pinA = 2;
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;
int pinF = 7;
int pinG = 8;
int i;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pins as outputs.
  pinMode(pinA, OUTPUT);
  pinMode(pinB, OUTPUT);
  pinMode(pinC, OUTPUT);
  pinMode(pinD, OUTPUT);
  pinMode(pinE, OUTPUT);
  pinMode(pinF, OUTPUT);
  pinMode(pinG, OUTPUT);
}

void loop() {
  potval=map(analogRead(A0),0,921,0,9);
  if (potval==0){
    //0
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, HIGH);
  }
  if (potval==1){
    //1
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==2){
    //2
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, HIGH);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==3){
    //3
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==4){
    //4
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==5){
    //5
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==6){
    //6
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==7){
    //7
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==8){
    //8
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==9){
    //9
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
}


texts:
I don't know if this is the right place to ask, but I'm an arduino newbie and I'm seeking some suggestions.
For my Robotics subject at University, I'm going to build a robot that should be able to move some objects (dragging them on the ground, not lifting them) from one place to another. I was looking around the web for the necessary components when I stumbled on a doubt: are 3-6V motors powerful enough for the wheels? Or do I need something more powerful like the 12V motors?
I'm not sure of what to choose between step motors or servo motors either, what do you suggest?
Oh and last thing, I opted for a L293D bridge driver for the motors, is this a good idea?

Thanks in advance!


texts: Brushless Motor and Electronic Speed Controller Initialisation Issues

texts:
I have been trying to make a brushless motor, working in synergy with an electronic speed controller, to work, however, all I have been achieving is the motor vibrating at a specific potentiometer/throttle position.

The following is a description of my components, circuit setup, code and calibration approaches.

Circuit Schematic

In the code image, it should say pin 8 instead of pin 9.

One problem may be that the ESC is of a lower current and voltage level to that of the motor. I have been reading online that the ESC should have a current at about 10-20% higher than that of the motor, and a voltage of similar levels. However, to my understanding, this is to prevent any burnouts if operating at full voltage. In my case, the motor will be operating at 22V as full power (36V) is not required. I expected it to at least be turning, at a low speed, when 22V are supplied, which it is not.

Another issue I thought was that the initialization process I am undergoing is not correct, however, upon checking online and cross referencing to the instructions specified in the Hobbyking booklet they appear to be similar, so I do not think is an issue either.

Any advise or guidance would be highly valued.

Thank you!

The links in the screenshots are as follows,

1) https://www.ebay.co.uk/itm/Brushless-300w-6-5-Wheel-Tyre-Motor-Hoverboard-Swegway-Board-Replacement-Part-/292465000149

2) https://hobbyking.com/en_us/hobbyking-40a-esc-4a-ubec.html?___store=en_us&gclid=EAIaIQobChMIkvb39sq54AIVy53tCh3AhwPBEAAYASAAEgJ0RfD_BwE&gclsrc=aw.ds

3)https://cdn-global-hk.hobbyking.com/media/file/378561453X16958X28.pdf

4)https://docs-emea.rs-online.com/webdocs/13cc/0900766b813cc9bb.pdf


texts:
I have a task where I should do SPI transactions in interrupt mode. Means I have to handle data in IRQ handler (both for tx and rx bytes). How should I approach?
I have a arduino board (2560) and a CAN shield (seeed studio) with SPI interface.
Edit:
From the website: https://www.arduino.cc/en/reference/SPI

With most SPI devices, after SPI.beginTransaction(), you will write
the slave select pin LOW, call SPI.transfer() any number of times to
transfer data, then write the SS pin HIGH, and finally call
SPI.endTransaction()

My question is - the function SPI.transfer() is handled in what way?
Are the bytes transfered/received in interrupt handler or by polling?


texts:
I am trying to generate a square pulse with a fixed delay of 5 second between pulses and varying width of the pulse. The code I wrote so far generates a sequence of pulses every 5 seconds. Is it possible to generate one pulse (with varying width) every 5 seconds instead? Could you please help me with it?

const int pin =  11;

int i  = 0;

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

void loop() {
    i = random(0 , 255);
    analogWrite(pin, i); // turn on LED
    delay(5000);
}


texts: Water flow sensor unable to get readings

texts:
I connected my "arduino(nano)" to "water flow sensor" and wrote a code which simply prints the readings like 0-1023 and tested it. First i got the readings but now i'm not getting it.

My code looks something like this.

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

void loop(){
 int vla=analogRead(2);
 Serial.println(vla);
 delay(1500);
}

and my connection.

  Sensor to Supply module
  Vcc -->  5v
  Gnd -->  Gnd

  Sensor to Arduino(Nano)
  Sig --> D2


texts:
I'm completely new to this world, so probably my question would sound noobish, but here it is:

I'm trying to make a led blinking just for 5 times by calling a "for" cycle inside void loop(). The confirmation of the successful cycle would come from the Serial Monitor which will print "let's star over", and at the end of each blinking cycle, it will print the text "cycle done".

The point is that my code doesn't work, the led remain switched ON and the serial monitor blank. What is wrong with it?

int ledred = 3;
int count = 5;

void setup() {
  digitalWrite(ledred, LOW);
  pinMode(ledred, OUTPUT);

}

void loop() {

    blinkingred(ledred, count);
    Serial.println("let's start over")

}

void blinkingred(int ledred, int count)
{
  for(byte i=0; i == count; i++)
  {
        digitalWrite(ledred, HIGH);
        delay(1000);
        digitalWrite(ledred, LOW);
        delay(1000);
        Serial.println("Cycle done !");
  }
}


texts: Include Git tag (or SVN revision) in Arduino sketch?

texts:
Is there any way to get the current Git tag/commit identifier into an Arduino sketch binary?

For normal desktop program development, you can pull some tricks with the Makefile (as pointed out in this StackExchange answer). However, there is no Makefile for an Arduino sketch. Right?

I could make a batch file that I run before every compile, but there is the very real possibility I will forget to run it, and incorrect version information is worse than no version information.

At the moment, I am using the preprocessor macros __DATE__ and __TIME__ to try and identify what version is running on the board. This works, but tracking backwards from a compile date/time to a source control commit is more guesswork than anything.


texts:
I came across a dev board around the Atmel Xmega controller. This an AVR like used on Arduino, but with a lot of extras.

I was surprised to see that the board is hardly more expensive than an Arduino, despite:

  384kB of Flash (versus 32kB for Arduino)
  DMA
  Xmega can run at 32 MHz (16 MHz for Arduino)
  on-board OLED display
  on-board light and temperature sensors
  on-board microSD socket

For all these on-board features you'd need a shield or breakout board for Arduino. I seems to me that for a lower price than Arduino you could build a much more powerful system, which is Arduino-compatible.
How hard would it be to port Arduino to the Xmega?

see also http://www.element14.com/community/docs/DOC-71436


texts:
Using ArduinoJson I have assigned a value such as;

const char* id = root["id"];

in the original JSON id was "1"

if (strcmp(id, "1") == 0) {
    // this executes
}

I have an array of structs that I wish to compare the id against. The struct looks like;

typedef struct  {
   char id[2];
   ....
} Device;

I assign an id (1-9) into the struct id by

_cmd.id[0] = '0' + (++DevicesPtr);
_cmd.id[1] = '\0';
Devices[DevicesPtr-1] = _cmd;

where _cmd is of type Device. Devices is an array with up to 8 entries
Now I try to find a match in the devices using the JSON id

for (byte i = 0; i < DevicesPtr; i++) {
    if (strcmp(Devices[i].id, id) == 0) {
       // This code does not execute
    }
}

I can't seem to get a match I have also tried (Devices[i].id == id)


texts: Use Arduino Uno as 5V Power Source for Sensors Connected to ESP32 Microcontrollers

texts: I am using an ESP32 WROVER B based microcontroller, which has 3.3V and 5V outputs. Due to poor soldering of the header and attempted removal of the solder (permanently damaged PCB etching electrical contacts around the 5V pin), the 5V pin doesn't output any current, so only the 3.3V works (e.g. lights up a LED). Some of my modules require 5V to work properly (according to their specification) e.g. sensors. Can I provide a 5V power source from another component (e.g. arduino uno 5V output, USB to TTL converter 5V power output or USB power supply) for these or use a GPIO output (I believe these are 3.3 volts only) on the ESP32 device itself, perhaps with level shifting? The ESP32 is powered via USB and no issues there (serial monitor shows it boots up okay).


texts: Is it possible to print all RFID chips in range instead of printing one by one?

texts:
I'm currently using an MFRC522 RFID Scanner on my Arduino UNO board. It's possible to scan for all the chips in range, but I can only print them one by one...

Is it possible to call a function that returns ALL the chips in range instead of one by one?


texts: Is there a way to remove the 8.3 filename limitation on the SD.h library?

texts: I need to be able to create text files on my SD card that are with names longer than 8 characters (which is what the SD.h currently limits me to). A choice would be to move to the SDFat library but before considering that option, is there a way to just remove the limit on the SD.h (because my code already implements the good-old SD.h)? What would be the best way to go about this issue?


texts: How would I go about measuring an analog signal on my arduino mega that has both positive and negative voltages

texts:
I have a signal that fluctuates between -70mV and 50mV. How would I get the arduino to read this.. Ultimately I am trying to graph the data in real time so it looks like this.

https://imgur.com/a/mZYnErY


texts: How do i send data from a Master to another Master?

texts:
I am using an ESP32 to receive data from web.
However in an I2C communication, the EPS32 does not work as a Slave and i already have an Atmega as the Master.

i have seen sites saying Master-Master I2C Connection is possible however, how do i do this? or are there other solutions to have the ESP32 communicate to the ATMega?


texts:
I am looking to setup a system where I have a master Arduino polling a number of sensors.

The way I am thinking is hooking the master TX line to the sensors RX line(and the opposite for the other line)

Questions

How long can the lines be?
Can the lines branch?


texts:
Scenario
I've plugged 6 pins from my RC receiver into my Arduino in order to read the incoming values.
Problem
I'm using Digital PWM~ pins 2-6. Oddly the Arduino only reads odd channels:
1480, 0, 1175, 0, 991, 0

I've that if I physically reverse the cables (2-7, 3-6, 4-5) going into the Arduino I get ALL values:
988, 983, 1511, 1174, 1490, 1487

I've found that if I go back to my initial pin setup and merely flip neighbors (2-3, 4-5, 6-7) that works as well.
Question
What could possibly be causing this?
Code
Here is the current code I've written

int ch1, ch2, ch3, ch4, ch5, ch6;
int ch1Pin = 2;
int ch2Pin = 3;
int ch3Pin = 4;
int ch4Pin = 5;
int ch5Pin = 6;
int ch6Pin = 7;

void setup() {
  pinMode(ch1Pin, INPUT);
  pinMode(ch2Pin, INPUT);
  pinMode(ch3Pin, INPUT);
  pinMode(ch4Pin, INPUT);
  pinMode(ch5Pin, INPUT);
  pinMode(ch6Pin, INPUT);

  Serial.begin(9600);
}

void loop() {
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);

  String p = (String)ch1;
  p += ", " + (String)ch2;
  p += ", " + (String)ch3;
  p += ", " + (String)ch4;
  p += ", " + (String)ch5;
  p += ", " + (String)ch6;
  Serial.println(p);

//  delay(100);
}

Photo

EDIT
Since posting this question I've found that reversing the chXpin values accomplishes the same effect as reversing the physical pins. This makes me thing it's a software issue so I'm digging in further.
TEMPORARY SOLUTION
I'm not sure why this works but flipping the neighbor order of pulseIn fixed the issue:
  /* OLD
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  */

  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);

Why did that work? It makes no sense to me.


texts: Arduino autorestarts when powered externally

texts:
I'm trying to finish  building an alarm system with relays, leds  and bluetooth. I finally made it working but when externally powered (12v source) after about 10 seconds it starts to reboot continuously.
This issue comes with no pc connection.


texts: How to get sound from analog pin of arduino play it through other pin using speaker

texts:
I am working on a small project on sound detection of lungs.
I want to get the sound using a sound sensor and play it on a speaker in real-time using Arduino.
Please suggest to me a good sound sensor that can detect the sound of the lungs.
I have read on google that the best frequency for lungs is 100 to 600 Hz.
By the way, I am using Electret Microphone Amplifier - MAX4466 with Adjustable Gain
But it is not getting the values. I think I need a preamplifier.
Thank you for your help.


texts: character on 16X2 LCD is not visible properly

texts:
i am using 16x2 LCD with arduino nano for my project.

when i connect arduino nano with usb power supply from pc or any mobile changer adapter then all the character on LCD is visible properly. But when i connect it with 5V regulated power to arduino nano than character on LCD is not visible properly (characters are visible and project is running fine but pixel which needs to be hidden are also little darker so it characters aren’t visible properly)

i have connected Vee pin of LCD with ground for maximum brightness.


texts:
I'm just starting off with using the Arduino and was learning about PWM
(http://arduino.cc/en/Tutorial/PWM).
Below is what my circuit looks like.

Below is the very simple code.

const int pinNine = 9;    // LED connected to digital pin 9

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
  // set the digital pins as outputs
  pinMode(pinNine,OUTPUT);
}

void loop() {
  analogWrite(pinNine, 0);
}

I was expecting my LED to not be lighted as its a 0% duty cycle. I even change the pinNine outputValue to (64, 127, etc) but for some reason the LED is always lighted. Any ideas?


texts: Why are my if statements acting like the condition is always true?

texts:
Here is my code. My issue is is that the keys are getting "pressed" even though there is nothing jumping any of the pins on the Arduino.

// UNO-HIDKeyboard-Library - Version: Latest
// This program has been created by pcs3rd.
// Please do not change this line.
#include <HIDKeyboard.h>
HIDKeyboard keyboard;   // Initiate keyboard
// Pin deffanitions and variables...
int key0 = 2;   // Button 0 (Unused but optional)
int key1 = 3;   // Button 1
int key2 = 4;   // Button 2
int key3 = 5;   // Button 3
int key4 = 6;   // Button 4
int key5 = 7;   // Button 5
int key6 = 8;   // Button 6
int key7 = 9;   // Button 7
int key8 = 10;  // Button 8
int led0 = 13;  // Indicator light.
int state0 = 0; // Button 0
int state1 = 0; // Button 1
int state2 = 0; // Button 2
int state3 = 0; // Button 3
int state4 = 0; // Button 4
int state5 = 0; // Button 5
int state6 = 0; // Button 6
int state7 = 0; // Button 7
int state8 = 0; // Button 8

void setup() {
   keyboard.begin();    // Start keyboard emulation
   Serial.begin(9600);  // Start Serial Output
   delay(300);          // Wait to be recognized be PC.
   pinMode(key1, INPUT_PULLUP); // set pin mode
   pinMode(key2, INPUT_PULLUP); // set pin mode
   pinMode(key3, INPUT_PULLUP); // set pin mode
   pinMode(key4, INPUT_PULLUP); // set pin mode
   pinMode(key5, INPUT_PULLUP); // set pin mode
   pinMode(key6, INPUT_PULLUP); // set pin mode
   pinMode(key7, INPUT_PULLUP); // set pin mode
   pinMode(key8, INPUT_PULLUP); // set pin mode
   pinMode(led0, OUTPUT);       // set pin mode
   Serial.println("Startup Completed!");
}

void loop() {
   // write state info to vars
   state0 = digitalRead(key0); // Button 0
   state1 = digitalRead(key1); // Button 1
   state2 = digitalRead(key2); // Button 2
   state3 = digitalRead(key3); // Button 3
   state4 = digitalRead(key4); // Button 4
   state5 = digitalRead(key5); // Button 5
   state6 = digitalRead(key6); // Button 6
   state7 = digitalRead(key7); // Button 7
   state8 = digitalRead(key8); // Button 8
   if (state0 == HIGH) {       // Button 0
     digitalWrite(led0, HIGH);
     // keyboard.pressSpecialKey(0x68); (You can enter a scancode instead of 0x68,)
     Serial.println("state0");
     delay(30);
   }
   if (state1 == HIGH) { // Button 1
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x68);
     Serial.println("state1");
     delay(30);
   }
   if (state2 == HIGH) { // Button 2
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x69);
     Serial.println("state2");
     delay(30);
   }
   if (state3 == HIGH) { // Button 3
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6A);
     Serial.println("state3");
     delay(30);
   }
   if (state4 == HIGH) { // Button 4
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6B);
     Serial.println("state4");
     delay(30);
   }
   if (state5 == HIGH) { // Button 5
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6C);
     Serial.println("state5");
     delay(30);
   }
   if (state6 == HIGH) { // Button 6
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6D);
     Serial.println("state6");
     delay(30);
   }
   if (state7 == HIGH) { // Button 7
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6E);
     Serial.println("state7");
     delay(30);
   }
   if (state8 == HIGH) { // Button 8
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x0F);
     Serial.println("state8");
     delay(30);
   }
   digitalWrite(led0, LOW);
   Serial.println("scan");
   delay(30);
}

Yet, even though I have 'if' statements, the code still gets executed, as shown in my monitor:

Startup Completed!

state0
hstate1
istate2
jstate3
kstate4
lstate5
mstate6
nstate7
state8
scan
state0
hstate1
istate2
jstate3
kstate4
lstate5
mstate6
nstate7
state8
scan

Are there any hints to what could be going on? I reformatted the code for readability, but it is pretty much the same as before. Also, I am not using pin 0 or one. I am using 13 for onboard LED.


texts: Why does pulse sensor shows gaps when I move it?

texts:
I modified the serial code in this way and I don't think the gap is produced by my edit even because it made it even before:

//////////
/////////  All Serial Handling Code,
/////////  It's Changeable with the 'serialVisual' variable
/////////  Set it to 'true' or 'false' when it's declared at start of code.
/////////

void serialOutput(){   // Decide How To Output Serial.
 if (serialVisual == true){
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
 } else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
 }
}

//  Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){
 if (serialVisual == true){            //  Code to Make the Serial Monitor Visualizer Work
    //ASCII Art Madness
    Serial.print(BPM);
    Serial.println("");

 } else{
        sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
        sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
 }
}

//  Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
void sendDataToSerial(char symbol, int data ){
    Serial.print(symbol);

    Serial.println(data);
  }

//  Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 1024;    // sensor maximum, discovered through experiment

  int sensorReading = data;
  // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // do something different depending on the
  // range value:
  switch (range) {
  case 0:
    Serial.println("");

  }
}

63

63
63
63
63
62
62
62
62
62
62
62
63
62
63
64
63
63
64
64
65
65

65
68
74
78
86
95
105
112
123
141
167
154
136
128
123
125
123
127
132
104
93
92
92
89
83
77
73
69
65
70
70
71

You can find all the code here:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

In the code I posted there is some code I don'f find useful but I can't delete it for reason linked to variables used for other functions I don't know I'm using.
You can also see huge changes in the heart rate that surely don't reflect the reality.


texts: I keep getting this error exit status 1 expected ';' before 'DigiKeyboard'

texts:
\ here is my code
include "DigiKeyboard.h"
void setup() {
DigiKeyboard.sendKeyStroke(0);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT);
DigiKeyboard.delay(100);
DigiKeyboard.print("Camera")
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
DigiKeyboard.delay(100);
DigiKeyboard.print("cmd")
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.print("REDACTED")
for(;;){ /empty/ }
}


texts: Using L298N bridge to control smart lock

texts:
I want to use L298N bridge to power up and control simple smart lock. It requires 12V power supply, so I've used L298N bridge to power this smart lock.

I removed jumper from enA pin and connected enA 12V to Arduino Nano D8 pin.

I sent value 255 through this pin but smart lock did nothing. Any suggestions?

I'm using BLE controller to send turn on/off signal from Android App (but its not relevant in this case, because analogWrite is called).

Lock:
https://www.aliexpress.com/item/32949292074.html

Here is code:

#define enA 8

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

void loop() {
 String msg = bluetooth.read(); //using BLE controller to get message from Android app.

 if(msg == "ON"){
   analogWrite(enA, 255);
 } else if(msg == "OFF"){
   analogWrite(enA, 0);
 }

}

Here is setup:


texts: Serial Communication between Node-MCU and Arduino Mega

texts: Sir mane ardunio mega 2560 my programing k hy jo k different sensor k value lake display karty hy aur sir ab my us value ko server jo k thingspeak hy aus p bajna chahta ho sir aus k leye mane esp8266 node-mcu use kar raha ho to sir ab my chahta ho k arduino value lake node-mcu ko send kary aur node mcu phr server p sir in k leye serial communication chahyae between two arduino sir is k leye koi refrence or any help


texts: Convert comma-delimited Arduino String of hex values to array of bytes

texts:
My apologies if this is a naive question. How do I convert a String which has hex values to a byte array that has those hex values?
This:
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

Needs to be converted to this:
char test[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

I used the following procedure. It does convert it, however, each character is saved as a character as opposed to hex value:
unsigned int str_len = s.length() + 1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

Any help will be appreciated. Thank you!


texts: Sensor to detect whether string is in tension?

texts:
I need a sensor to detect whether there is tension on a string or not. I do not need an accurate measurement of the amount of tension- just whether the string is being pulled on or is taut.

Alternatively, if there is some homemade hack of this sensor, please let me know. I'd love to give it a shot!


texts: Does Arduino C++ support dynamic arrays of objects

texts:
My C++ is seriously out-of-date, and I'm working on a project that will be juggling multiple timed actions at the same time, with a menu system to manage the interface and control those timed actions (A multi-channel power outlet controller.)

To do the control I'm planning to have an array of objects that get serviced every time through the event loop. I'm currently using a static C array of objects, but I'd like to use a dynamic C++ array where I can add and remove objects as needed.

I know that some features of the C++ standard library are not supported on Arduino. I think C++ calls smart arrays vectors, and believe vectors are part of the standard library, which isn't supported/fully supported on Arduino. Is there some sort of dynamic array class available?


texts: Locking ATmega328 from reading back the hex file

texts:
I want to completely block the access to an ATmega328. How do I do this?

I have Atmel ICE, AVR studio 7 and Arduino.

Bootloader - optiboot_atmega328
Fuses(without lock) - 0x05, 0xDE, 0xFF

Steps I am executing:

Program fresh ATmega328 with bootloader using Atmel Studio.
Burn the fuses as mentioned above.
Go to Arduino and program the code.
Come back to Atmel Studio >> lock bits >> enable no further programming and verification.>> Fuse bits>> disable reset.

Is the above way OK? Or should I add something to the above?

I have programmed the fuse bit with "Further programming and verification disabled". I read out the hex file and it does not match even I programmed the same hex into a different micro and it didn't work. This seems to be fine. But will high Voltage programmer brick this wall?

Note: When I program the above fuse bit. I am unable to disable the RESET or SPI. It says one or more register differ

I want avoid a readback via high voltage programmer too.

I have too many people to steal my code I want to avoid it. Kindly help

Siddharth


texts: Using both a stepper motor and a DC motor with Arduino motor shield R3

texts:
We are trying to reprogram a remote control car with an Arduino Uno. This car runs the power with a DC motor, and it controls steering using a stepper motor.

We have the Motor Shield R3 attached to the Arduino, but it has just now occurred to us that we can't support both motors with the motor shield (as the motor shield only allows for two DC motors or one stepper motor). Is there a way to somehow work around this? Or is it possible that we would need to replace the stepper motor with DC?


texts: how to send argument to ESP8266WebServer objects on function

texts:
this probably simple thing to do however I can't think of a way to pass argument to function call

ESP8266WebServer server ( 80 );

void toggleRelayOne() {
  char temp[400];
  String msg = "";
  if (relay1 == 0) {
    relay1 = 1;
    msg = "Light is turned on";
  }
  else {
    relay1 = 0;
    msg = "Light is turned off";
  }

  digitalWrite (5, relay1); //GPIO 5 // Relay 1
  snprintf ( temp, 400,
             "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU DHT11 Sensor and Relay Board</title>\
    <meta http-equiv='refresh' content='0; url=../'>\
    </head>\
  <body>\
  %d .</body>\
  </html>"
             , 1);
  server.send ( 200, "text/html", temp );
}

void setup ( void ) {

  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );
  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( host ) ) {
    Serial.println ( "MDNS responder started" );
  }
  MDNS.addService("http", "tcp", 80);
  server.on ( "/", handleRoot );
  server.on("/relay1", toggleRelayOne);
  server.begin();
  Serial.println ( "HTTP server started" );
}

in the above function where I am calling toggleRelayOne using server.on("/relay1", toggleRelayOne); I want to be able to pass relay id so I can use same function to toggle multiple relays.


texts: Convert string into char array in Arduino?

texts:
I am not that great at Arduino and C++ yet, but I'll give this a shot:

I have a char array that looks like this:

char PROGMEM bitmap[] = {0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE};

However, I receive this char array from a string, which is basically:

String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE";

How do I turn my input variable with a comma separated char array into the actual array? I need it to be fast and not use a lot of memory. I haven't been able to find a use case like this, because it's very unique.

I feel like this should be super simple to do, but I can't wrap my head around it.

Things I've tried and didn't understand that much:

1:

char delimiter[] = ",";

char* ptr = strtok_r(text, delimiter);

while (ptr != NULL) {
  Serial.println(ptr);
  ptr = strtok_r(NULL, delimiter);
}

  cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'

2:

char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
int i = 0;
char bitmap[115];
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = str;
  i++;
}
Serial.println(bitmap);

(the total length of my characters are 4799 and the total length of hexadecimals are 114, so I'm just trying something here)

Error: Apparently you can't use  =?

3:

char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  Serial.println(str);
}

This actually prints the strings to the console, but trying to add them to a char array is still a mystery I am trying to solve right as I write this.

4:

char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
char *ptr;
char bitmap[115];
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, &ptr, 16);
  i++;
}

Serial.println(bitmap);

I'm getting a lot closer now. strtol(str, &ptr, 16) actually gives me the right integers I need, but it seems like my Arduino crashes when I run this code. It simply reboots it. Error:

  assertion "heap != NULL && "free() target pointer is outside heap areas"" failed: file "/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/heap/./heap_caps.c", line 171, function: heap_caps_free
  abort() was called at PC 0x4011c173 on core 1


texts: Nothing received from function returning array of strings

texts:
My read function returns an array of strings. i.e ssid and password

String* configuration::read() {
    String rw_ssid = "";
    String rw_pswd = "";
    const int keys = 2;
    String read_ssid_pswd [keys];
    if (EEPROM.read(0) != 0) {

      for (int i = 0; i < 32; ++i) {
        rw_ssid += char(EEPROM.read(i));
      }
      for (int i = 32; i < 96; ++i) {
        rw_pswd += char(EEPROM.read(i));
      }
      Serial.print("rPASSWORD: ");
      Serial.println(rw_pswd);
      read_ssid_pswd[0] = rw_ssid;
      read_ssid_pswd[1] = rw_pswd;
      Serial.print("Sending ssid:");
      Serial.print(read_ssid_pswd[0]);
      Serial.print(" Pswd: ");
      Serial.println(read_ssid_pswd[1]);
      return read_ssid_pswd;
    } else {
      Serial.println("Data wifi not found!");
      return read_ssid_pswd;
    }
}

I can see the print in the serial monitor.

Sending ssid:SSID Pswd: password

but where this function is called from I have set it up like this:

void setup() {
  Serial.begin(115200);
  Eeprom::configuration::initialize();
  String* ssid_password = Eeprom::configuration::read();
  Serial.print(">SSID: ");
  Serial.println(ssid_password[0]);
  Serial.print(">Password: ");
  Serial.println(ssid_password[1]);
  Funcs::connection::connectWifi(ssid_password[0], ssid_password[1]);
}

and I get thing in the prints  I thought its not giving any error at compile time so it should be correct.


texts:
I have an ATmega328P monitoring room temperature and humidity. It is enough for me to monitor every 8 seconds. In these 8 seconds, I am putting my Atmega to sleep.

Now , I want to know : Does shutting down the DHT11 for these 8 seconds affect the performance of the sensor in any way or is it advisable to keep it running (stand by) for these 8 seconds ?

[Shutting down means connecting the Vcc of the sensor to GND by means of digitalWrite(Sensor_pin,LOW);]

Also , (The below question is applicable only if your answer to the above question is to keep it in Stand-by) :-

I want to modify the above project such that Temp & Humidity is measured as and when only an input button is pressed.
In this case too, should I keep the DHT11 running?

Is a running DHT11 sensor more accurate than a instantly powered on DHT11 ?

[And in case you are speculating , yeah,I want to save the 50 micro-amps Standby current of the sensor.(but of course without sacrificing accuracy of the sensor)]


texts: Send AND Receive through i2c / set Arduino as master AND slave

texts:
For a project I'm using 2 Arduino Uno's, where Arduino#1 (master) sends raw data to Arduino#2 (slave). The slave should receive and encrypt the data and afterwards send the encrypted data back to the master. I'm building my project from the sketch found at arduino.cc.

How can I make the slave send back data, if he's the only one listening on incoming data, should both arduinos be listening to each other, and how to achieve this?


texts: Error: avrdude: stk500v2_ReceiveMessage(): timeout avrdude: stk500v2_ReceiveMessage(): timeout

texts: New to Arduino Mega 2560. Using PC with Windows 10. In the Arduino IDE the only USB port I get is COM1. When I try to get board info I get is the message of 'Native serial port, can't obtain info". When I try and upload program I get the error message: "avrdude: stk500v2_ReceiveMessage(): timeout avrdude: stk500v2_ReceiveMessage(): timeout. The TX and RX leds are not flashing. Is there a driver missing?


texts: What is the default setting for a digital output pin

texts: With digitalWrite(pin_number,value), we can set an output pin as HIGH or LOW. But if only coding pinMode (pin_number, OUTPUT), what is the default state for the pin pin_number, LOW or HIGH? It is noted that: Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. Does that mean the pin will be in the state LOW?


texts: How to use FTDI to program Lilypad Arduino?

texts:
I am trying to upload a basic Blink code from my computer to Arduino Lilypad contains Atmega 328. While my Blink codes are uploading, FTDI 1402-C CN480661 FT232RL module is not responding to the Arduino IDE at the end of the process. So I couldn't upload any codes with this uploading method, I mean using FTDI modules directly.

This is how I do the connections:

This is my Blink code:

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

void loop() {
  digitalWrite(13, HIGH);     delay(1000);
  digitalWrite(13, LOW);      delay(1000);
}

I chose AVRISP mkII as a programmer. ATmega328 as a processor. Arduino Lilypad as a board on Arduino IDE v1.6.6

At this point, I got this error:

  avrdude: ser_open(): can't open device "\.\COM4": Access is denied

Windows's device manager says: USB Serial Port is attached to COM4, also Arduino IDE saw that.

I downloaded FTDI driver for Windows, but still, I can't upload any code into my Lilypad Arduino.

How can I use FTDI to program my Lilypad Arduino?


texts: Interrupt fires a random number of multiple times for one pulse

texts:
This is my first time posting on this forum. I have tried to format this question properly, but let me know if I need to correct anything. I searched to see if someone else had a similar problem, but let me know if someone has already answered this question.

Overview: I am sending pulses to my Arduino, but sometimes one single pulse is interpreted as anywhere from 2 to 30 pulses. But after looking at the pulse on an oscilloscope (see Fig. 1) I am not sure why. When I use a really long wire the ratio of false pulses to legit pulses is about 1 to 1. I shortened the length of the wire and improved the situation, so that only 1 in about every 2,000 pulses is registered as a false pulse.

For one test, I added a capacitor to the short wire situation, but that increased the rise time and made the problem worse. I am currently using attachinterrupt and have tested the situation with using both a rising and falling edge. Right now, I mainly want to understand how interrupts work on the Arduino in light of my current problem, although I welcome general advice.

When I set the interrupt to the falling edge, why does the Arduino still sometimes count 1 pulse as several? The falling edge in the photo, which is for the really long wire case, lasts about 40 microseconds and appears to have a clean break. The pulse remains low for about 80 milliseconds. Could the falling interrupt trigger during the rise time based off the oscillatory behavior shown in Fig. 1? I smoothed out the signal by adding in a 1 nF capacitor, but the Arduino still counted false pulses. So could the rise time period have anything to do with it? I also have a 10k Ohm pullup resistor connected to the Arduino's 5 V for the pulse path.

I have the relevant code attached below. I have much more code as well, but it deals with saving pulseCounts to the SD Card and uploading electricity consumption files through the cell network.

Cheers.

//Global Variables
unsigned long pulse_time = 0;
unsigned long last_pulse_time = 0;
byte code = 1; //code let's me see if a false pulse was reported for each
//SD file

void setup() {
  attachInterrupt(digitalPinToInterrupt(3), onPulse, RISING);
}

void onPulse() {
  pulse_time = millis();
  if ((pulse_time - last_pulse_time) > 50 ) {
    Serial.println("Good Pulse");
    pulseCount++;
    last_pulse_time = pulse_time;
  } else {
    Serial.println("Bad Pulse");
    pulseCount++;
    code = 2;
  }
}


texts: What are the Arduino hardware options for experimenting with IoT?

texts:
Just starting to learn about Arduino and IoT. I'd like to know what the Arduino hardware options are to try the following:

Use FreeRTOS as SO
WI-FI and BLE connectivity
Solderless board
Test OTA features
Experiment integration with different IoT Cloud platforms e.g. Azure IoT Hub
Build custom IoT devices


texts: Is it possible to hookup two ultrasonic sensors to one Arduino Uno unit?

texts: I found a couple of projects using Ultrasonic Distance sensor with Arduino Uno. Is there a way to connect two or more sensors on the same Arduino Uno?