texts: Arduino Pro micro Serial communication problem with Node MCU

texts:
I recently bought an ATmega32U4 based Arduino Pro micro. I am using the Keyboard library and interfacing with my PC via USB.
I am trying to create a serial communication between the Arduino Pro micro and a NodeMCU via Rx, Tx pins (0, 1), but it isn't working i.e. not giving any output with the code below on the Pro micro:
#include <Keyboard.h>

int incomingByte;
unsigned long lastTime;

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

void loop() {
  if (Serial.available() > 0) {
    lastTime = millis();
    String payload = "";

    while (1) {
      if (millis() - lastTime > 1000)
        break;

      incomingByte = Serial.read();
      Serial.println(incomingByte);
    }
  }

On the NodeMCU there is a simple script flashed which only writes on serial some characters in a delayed loop.
When using the SoftwareSerial library with the Pro micro, it is working fine i.e. I can read data sent by the NodeMCU on custom Rx, Tx pins (9, 10). I tried this because I thought since Pro micro is communicating with a PC, the original Rx and Tx pins are busy. But after some research I got to know that unlike other Arduino boards like the UNO, the Pro micro doesn't use those for communication over USB.
Although custom serial using SoftwareSerial library is working, it is too slow and unreliable i.e. it takes 2-3 seconds to pass a string of length 10. Also its unreliable because on sending bigger length strings, the strings arrive incomplete or sometimes the data gets corrupted (characters shuffle).
Again this is not my main concern, if I can use original Rx, Tx pins as usual on any other Arduino boards, it solves my issue.
This is my circuit diagram:


texts: Do I need to run an expand drive sketch if I update the Yun Firmware subsequent to expanding?

texts:
I have a Geeetech Iduino Yun shield, that initially had Geetech's System image (v2.02, 2015) on it. I then ran a USB storage expander sketch to take advantage of the space on a flash drive. I then installed a number of packages (such as vim). I subsequently flashed/updated the firmware with Dragino v2 yun-4.1.2 sysupgrade firmware, only to find that vim and other packages have disappeared, as well as my Python code.

Has the update undone the expansion and is the Linux system now confined to what's provided by the firmware? Do I need to run an expansion sketch and install packages again?


texts:
I have this callback function in my Firmata sketch. It receives a string as a character array and does something with it. The problem is, that the string is being sent to the Arduino in T\0h\0i\0s\0 form - after each character there is a \0 terminator. As you can see, my function is switching the d13 LED on if the string incoming is COMMAND. I had tried to use several comparison methods:

strcmp(myString, "COMMAND") == 1;
myString == "COMMAND";
strcmp(myString, "COMMAND\0") == 1;
myString == "COMMAND\0";
strcmp(myString, "C\0O\0M\0 M\0A\0N\0D\0") == 1;
myString == "C\0O\0M\0 M\0A\0N\0D\0";
== with saving the COMMAND to a char array variable;
strcmp with saving the COMMAND to a char array variable;
last two things with converting both the incoming and the needed to a String instance;
comparing a String instance with a directly stated "COMMAND"...

Nothing works. How can I compare the strings workably?
Full Arduino sketch:
#include <Firmata.h>

void stringCallback(char *myString)
{
  if (strcmp(myString, "COMMAND") == 1) {
    digitalWrite(13, HIGH);
  }
  Firmata.sendString(myString);
}

void sysexCallback(byte command, byte argc, byte *argv)
{
  Firmata.sendSysex(command, argc, argv);
}

void setup()
{
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(STRING_DATA, stringCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.begin(57600);
  pinMode(13, INPUT);
}

void loop()
{
  while (Firmata.available()) {
    Firmata.processInput();
  }
}

Full code of the desktop program:
import pyfirmata, time

class CustomArduino(pyfirmata.Arduino):
    def __init__(self, port: str):
        pyfirmata.Arduino.__init__(self, port)
        self.iterator = pyfirmata.util.Iterator(self)
        self.iterator.start()

        self.add_cmd_handler(0x71, self.receiveString)

    def receiveString(self, *args, **kwargs):
        print(f'Raw: {args}\n'
              f'Received: {pyfirmata.util.two_byte_iter_to_str(args)}')

    def sendString(self, data):
        self.send_sysex(0x71, pyfirmata.util.str_to_two_byte_iter(data))

    def send_sysex(self, sysex_cmd, data=[]):
        """
        Sends a SysEx msg.
        :arg sysex_cmd: A sysex command byte
        : arg data: a bytearray of 7-bit bytes of arbitrary data
        """
        msg = bytearray([pyfirmata.pyfirmata.START_SYSEX, sysex_cmd])
        msg.extend(data)
        msg.append(pyfirmata.pyfirmata.END_SYSEX)
        self.sp.write(msg)

print('STRING TESTER\nPlease input your COM port: ', end = '')
myCom = str(input())
device = CustomArduino(myCom)

while True:
    device.sendString(input('Send: '))
    time.sleep(1)

Strange detail: my Arduino is on the COM6 COM-port. If I connect it via my program and send com6 to the arduino, the D13 LED turns on!


texts:
I have an Arduino project to do, which requires a countdown timer(which I've already done). I connected a push button, and when I press that button I need it to increase my countdown timer by +10 seconds.

Can anyone help me with adding the code for this button?

Here is the code so far(I declared the button, but I don't know if it's any good):

#include <LiquidCrystal.h>

int buttonPin = 7;
int buttonState = 0;
int seconds = 30; // count seconds
int minutes = 0; // count minutes
int hours = 0; // count hours
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
//initialize the library with the numbers of the interface pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // pins connected to LCD

void setup()
{
  lcd.begin(16, 2); //set up the LCD's number of columns and rows
  pinMode(buttonPin, INPUT);
}
void loop()
{
  buttonState = digitalRead(buttonPin);
  lcd.setCursor(1, 0);
  lcd.print ("Sosire in:");
  lcd.setCursor(6, 1);
  lcd.print(":");
  lcd.setCursor(9, 1);
  lcd.print(":");

  seconds--;
  delay(1000);

 if (seconds < 0)
  {
    minutes--;
    seconds = 59;
  }
 if (minutes < 0)
  {
    hours--;
    minutes = 59;
  }
 if (hours < 0)
  {
    hours = 0;
    minutes = 0;
    seconds = 30;
  }
 if (minutes > 9)
  {
    lcd.setCursor(7, 1);
    lcd.print(minutes);
  }
 else
  {
    lcd.setCursor(7, 1);
    lcd.print("0");
    lcd.setCursor(8, 1);
    lcd.print(minutes);
    lcd.setCursor(9, 1);
    lcd.print(":");
  }

 if (seconds > 9)
  {
    lcd.setCursor(10, 1);
    lcd.print(seconds);
  }
 else
  {
    lcd.setCursor(10, 1);
    lcd.print("0");
    lcd.setCursor(11, 1);
    lcd.print(seconds);
    lcd.setCursor(12, 1);
    lcd.print(" ");
  }

 if (hours > 9)
  {
    lcd.setCursor(4, 1);
    lcd.print(hours);
  }
 else
  {
    lcd.setCursor(4, 1);
    lcd.print("0");
    lcd.setCursor(5, 1);
    lcd.print(hours);
    lcd.setCursor(6, 1);
    lcd.print(":");
  }
 if (seconds == 0)
  {
    lcd.clear();
    lcd.print("Este in statie");
    delay(5000);
    lcd.clear();
  }

}


texts: What happens when I exceed amp limit on Arduino 5v pin?

texts:
I'm using an Arduino Uno to power some rgb LEDs.

Each LED takes 20mA (on average).
I have a strand of 400 LEDs.
This should be drawing ~8,000mA.

Arduino Uno has a limit on its 5v pin of 500mA.

**So how many amps is my Arduino outputting? My 8A worth of LEDs are illuminated, just dimly.

Edit:
My Arduino still runs, and the 8,000mA LEDs illuminate, just dimly. I’ve left the setup on for 12 hours, and it all still works.

So it appears the behavior of the Arduino Uno is to limit the amp output of its 5v pin. It does not burn out.

Any explanations for this observed behavior?

Edit 2:
I know how to wire up this setup correctly using power injection. I’m just curious why my Arduino is not burning out as we all expect it to.


texts: Could someone explain this code that sets up the software serial port data rate?

texts:
I understand most of it. The part I don't understand is the is the code in for void loop. How does that set the data rate for the software serial port? I thought mySerial.begin(9600) did that? Please help.

#include <SoftwareSerial.h>

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

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

    Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    // set master
    mySerial.print("AT+ROLE1");
    delay(10000);

}

void loop() // run over and over
{

    // set the data rate for the SoftwareSerial port
    mySerial.print("test I am master  ");
    delay(10000);
    ***if (mySerial.available())
    Serial.write(mySerial.read());
    if (Serial.available())
    mySerial.write(Serial.read());***
}


texts: Sending AT commands to a gprs shield using serial port

texts:
I have a GPRS shield connected to an arduino uno board, i want to use the shield to send sms and do phone calls, from a C# Wpf application, the arduino is connected to the application using the serial port,

In order to do that I've upload the following sketch to the arduino board:

#include <SoftwareSerial.h>

SoftwareSerial GPRS(7, 8);
unsigned char buffer[64]; // buffer array for data recieve over serial port
int count=0;     // counter for buffer array
void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);             // the Serial port of Arduino baud rate.
}

void loop()
{
  if (GPRS.available())              // if date is comming from softwareserial port ==> data is comming from gprs shield
  {
    while(GPRS.available())          // reading data into char array
    {
      buffer[count++]=GPRS.read();
      if(count == 64)break;
    }
    Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
    clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
    count = 0;                       // set counter of while loop to zero
  }
  if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
    GPRS.write(Serial.read());       // write it to the GPRS shield
}
void clearBufferArray()              // function to clear buffer array
{
  for (int i=0; i<count;i++)
    { buffer[i]=NULL;}
}

every thing works perfectly when sending AT commands to the shield using the Serial Monitor, for example to dial a call this is all what i need to do

this works perfectly, but when trying to do the same thing from c# application, nothing happened !
here how i send the AT command from the code :

private readonly SerialPort _serialPort;
public void Callphone(string number)
{
    _serialPort.Open();
    _serialPort.Write("ATD + +" + number +";");
    Thread.Sleep(100);
    _serialPort.Close();
}

PS: sending sms works fine from the serial port, using the same way :

 public void SendSms(string number, string message)
    {
        _serialPort.Open();
        _serialPort.Write("AT+CMGF=1\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write("AT+CSCA=\"" + MessageCenterNumber + "\"\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write("AT+CMGS=\"" + number + "\"\r");
        Thread.Sleep(SleepTimeStamp);
        _serialPort.Write(message + "\x1A");

        Thread.Sleep(SleepTimeStamp);
        _serialPort.Close();
    }

Am i missing something ?


texts: Is there any way to separate this short code into its own function? (webserver, trying to use client.print outside of main loop)

texts:
I have an arduino webserver that uses the following code:

client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println();
client.println(F(""));
...
if (fan1Toggle == 0)
    client.print(F("Fan1&#8226;On
"));
else
    client.print(F("Fan1&#8226;Off
"));

if (fan2Toggle == 0)
    client.print(F("Fan2&#8226;On
"));
else
    client.print(F("Fan2&#8226;Off
"));
...

The page is pretty long, allowing the user to toggle over a dozen different switches. Some of the code checks to see the state of a certain switch, and then displays a green or red bullet ("&#8226", like •) on the page if the switch is on or off.

Since the code for the colored bullet is repeating, I wanted to make a function for it. Then I would just call (for example) "displayBullet(fan1Toggle);", and it would determine if fan1 was on or off, and display the correct color depending on the state.

I tried to create the following function:

void displayBullet(int toggle) {
if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("&#8226;"));
else    //switch is on, so display green bullet
    client.print(F("&#8226;"));
}

But then I got an error saying that "'client' is not declared in this scope".

Is there any way to work around that error, so that I can get the displayBullet() function I want? Or is this something that can't be shortened like this, because the "client" function has to be inside the main loop?

Thanks!


texts:
How do I figure out how to connect to my arduino using ethernet shield?

It prints the IP in the serial monitor, but it doesn't work, and adding the port doesn't make a difference.

The client example works, so it's not broken or anything.

I'm using Arduino 1.6.5 IDE on a Mega 2560. I'm trying to run the Examples/Ethernet/WebServer example.


texts: SoftwareSerial response is semi-gibberish using ESP8266

texts:
I have a working SoftwareSerial connection to my ESP8266 module on my Arduino UNO board. However, the response I get from the ESP8266 using the SoftwareSerial library is semi-gibberish.

So I do get the correct response, but some characters are changed.
For example when I ask the IP of the module, it sometimes returns the right IP, but most of the times just alters the IP, for example 092.168/123.5.

So what am I doing wrong?

This is the code I'm currently using:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Started");
}

void loop() {
  if (esp8266.available()) {
    Serial.println(esp8266.readStringUntil("\n"));
  }
  if (Serial.available()) {
    esp8266.write(Serial.read());
  }
}

When I send the AT command, I sometimes get OK□ or some other extra random characters.

So how do I make the SoftwareSerial show (or receive) the correct response?


texts: On/off button for Arduino Mega for 5V input pin- hardware based auto on/off arduino(PUSHBUTTON NOT AS INTERRUPT)

texts:
I am working on Arduino Mega project where I want to add a PUSHBUTTON (Any other can be suggested) that will be programmed in my arduino code, such that if I would press the button arduino code should stop working and when I will press the button back the code should resume from the moment where it stopped.
Button will be attached to 5v pin so that will turn off/on the arduino.


texts: WDT & Software RESET in ESP8266 + Arduino IDE

texts:
I am working on ESP8266 in Arduino IDE. I want to know how to Software RESET the ESP8266. Any sketch/example would be useful. Moreover, how to initialise WDT in ESP8266.

Kindly help!


texts: Can I use the setup() function inside the loop() function

texts:
In the normal case the setup() function will be run once automatically and and then the loop() function will run many times.

I want to initialize several modules in the setup() function and then in the loop() I want to read values from them periodically. But if the period between usage is long I want to power off the modules. After defined time the modules will be powered on again and need to be initialized. Can I use the already existing setup() function inside the loop() to initialize the modules or I have to write another similar function? Is there any other better way to power off/on sensors and modules during the execution of code.


texts: TimeAlarms stops working when using setSyncProvider(RTC.get) DS1307

texts:
Been working on this project for some time now, like title states when I un-comment setSyncProvider(RTC.get) in the setup the program fails to get any of the Alarm.timerOnce to run.

I have been stuck for a while and couldn't find anything while just googling so I thought I might enlist the minds of stack.

#include <Wire.h>
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

//#define DS1307_I2C_ADDRESS 0x68 // the I2C address of Tiny RTC
//byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

int curPin = 7, //  Current sense (middle terminal) connected to analog pin A7
  prePin = 6,     //  Pressure sense (green terminal) connected to analog pin A6
  ignPin = 7,     //  Igniter output pin D7
  solPin = 8,     //  Solenoid output pin D8
  genPin = 9,     //  Generator output pin D9
  tonePin = 11,   //  Tone output pin D11
  ligPin = 3,     //  Light sense pin A3
  intPin = 3,     //  Interupt pin D3 runs double bang

  runTime = 20,   //  minutes to run for

  state = 0;      //  state of operation

bool operate = false, // True if within operating time
   timeIsSet = false; // true if time till next opperation is set
double cur;

void setup() {
  Wire.begin();
  pinMode(13,OUTPUT);
  pinMode(ignPin, OUTPUT);
  pinMode(solPin, OUTPUT);
  pinMode(genPin, OUTPUT);
  Serial.begin(9600);
  //setSyncProvider(RTC.get);  //******************************************
  Alarm.alarmRepeat(dowMonday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowTuesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowWednesday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowThursday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowFriday,7,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSaturday,8,30,0,OnAlarm);
  Alarm.alarmRepeat(dowSunday,10,0,0,OnAlarm);
  Alarm.alarmRepeat(20,0,0,OffAlarm);
  tone(tonePin, 31, 1000);
  randomSeed(analogRead(0)); // nothing connected to 0 so read sees noise

  OnAlarm();
}

void loop() {
  if ((analogRead(ligPin) > 30) && operate == true)
  {
    if (timeIsSet == false)
    {
      tone(tonePin, 58, 500);
      int randm = random(27,36);
      Alarm.timerOnce(randm,operation);
      Serial.println(randm);
      timeIsSet = true;
    }
  }
  digitalClockDisplay();
  Alarm.delay(1000); // wait one second between clock display
}

void operation(){
  tone(tonePin, 100, 1000);
  Alarm.timerOnce(12,after20m);
  digitalWrite(genPin, HIGH);
}

void after20m(){
  digitalWrite(genPin, LOW);
  Alarm.timerOnce(5,after5s);
  digitalWrite(solPin, HIGH);
  tone(tonePin, 494, 1000);
  timeIsSet = false;
}

void after5s(){
  tone(tonePin, 200, 1000);
  digitalWrite(solPin, LOW);
  Alarm.timerOnce(1,after1s);
}

void after1s()
{
  digitalWrite(ignPin, HIGH);
  Alarm.delay(500);
  digitalWrite(ignPin, LOW);
}

void OnAlarm() {
  operate = true;
}

void OffAlarm() {
  operate = false;
}

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  //Serial.print(operate);
  Serial.println();
}

void printDigits(int digits) {
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}


texts: Arduino Mega 2560 + BLE HM-10 - I cannot execute AT commands

texts:
I have an Arduino Mega 2560 and a HM10 Bluetooth module (this one)
I have connected the Bluetooth according to the manufacturer's specifications:
VCC -> 5v
GND -> GND
TXD and RXD of the Bluetooth, I have tried to put them in pins of Arduino, in Serial1, in Serial2, in Serial3, with the same result.
The code I use for my tests is this:
#define BTserial Serial1

int LED_BOARD = 13;
int LED_RED = 2;
int LED_GREEN = 3;

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

    pinMode(LED_BOARD,OUTPUT);
    pinMode(LED_RED,OUTPUT);
    pinMode(LED_GREEN,OUTPUT);
}

void loop() {
    if (Serial1.available()) {
        dato = Serial1.readStringUntil('\n');

        Serial.println("DATA RECEIVED: [" + String(dato) + "]");

        if (dato.equals("1")) {
            digitalWrite(LED_BOARD, HIGH);
        }
        if (dato.equals("0")) {
            digitalWrite(LED_BOARD, LOW);
        }

        if (dato.equals("RED_ON")) {
            digitalWrite(LED_RED, HIGH);
        }
        if (dato.equals("RED_OFF")) {
            digitalWrite(LED_RED, LOW);
        }

        if (dato.equals("GREEN_ON")) {
            digitalWrite(LED_GREEN, HIGH);
        }
        if (dato.equals("GREEN_OFF")) {
            digitalWrite(LED_GREEN, LOW);
        }
    }
}

I have an Android phone, and I use the Arduino Bluetooth Controller (HM-10 Module) app.

I send the text 1, and the led of the Arduino board (pin 13) turns on.
I send the text 0, and the led of the Arduino board (pin 13) turns off.
I send RED_ON, and the led of my breadboard, connected to pin 2, turns on
I send RED_OFF, and the led of my breadboard, connected to pin 2, turns off
I send GREEN_ON, and the led of my breadboard, connected to pin 3, turns on
I send GREEN_OFF, and the led of my breadboard, connected to pin 3, turns off

So the Bluetooth works.
My problem is trying to see the list of Bluetooth commands (AT+HELP command).
I have a method that is responsible for sending AT+HELP to bluetooth, but I have no response.
This is the method, which I run in the main:
String str_ii = "";
int ii_0 = 0;
void ble_help(){
    Serial.println("ble_help");

    BTserial.println("AT+HELP"); // list all AT+ commands
    while (true){ // loop to print all AT+ commands
        char in_char = BTserial.read();
        if (int(in_char)==-1 or int(in_char)==42){
            continue;
        }
        str_ii+=in_char;
        if (in_char=='\n'){
            if (str_ii==String('\r')+String('\n')){
                if (ii_0 == 0){
                    ii_0 = 1;
                    continue;
                }
                break; // break after more than 1 empty carriage return and newline
            }
            Serial.print(str_ii);
            str_ii = "";
        }
    }
}

When executing this method, in application Arduino Bluetooth Controller (HM-10 Module) app i see the text AT+HELP, but there is no reaction / response from the bluetooh. Neither in the Arduino Bluetooth Controller (HM-10 Module) application nor in the Arduino serial monitor
What am I doing wrong?
Thank you.


texts: Digispark ATtiny 85 - not recognised as HID device

texts:
I am trying to create auto-username-writer with Digispark ATtiny 85. I have a pretty simple sketch:

#include <DigiKeyboard.h>
void setup() {
}
void loop() {
    DigiKeyboard.sendKeyStroke(0);
    DigiKeyboard.delay(100);
    DigiKeyboard.sendKeyStroke(76, MOD_ALT_RIGHT | MOD_CONTROL_LEFT); //ctrl+alt+del
    DigiKeyboard.delay(2000);
    DigiKeyboard.print("username");
    DigiKeyboard.sendKeyStroke(0x2B); //tab

    for (;;) {}
}

When I upload the code via Arduino IDE into the device (Board: Digispark (Default - 16.5MHz), it finishes successfully, it is recognised as a HID device and immediately performs all the tasks. But when I disconnect it and connect it again (to my PC or any other PC) it is recognised as Digispark Bootloader and does not do anything.

I have tried it in Arduino IDE 1.8.8 and in Arduino IDE 1.6.5 and I have no idea why it is only recognised right after upload. I have two ATtinys and both do the same behaviour.

Can someone help me, please?

EDIT:
I tried adding digitalWrite(1, HIGH); to detect, whether the sketch even runs and it turned out it does not even run (except after the upload)...


texts:
https://youtu.be/y1Bke3750WE
I’ve been trying to make an Arduino emf because no brand makes a commercial one like a board/module. I’ve tried connecting ones that work (circuits from store bought devices) and making my own but they never seem to work despite being done correctly.
In the video linked above he says you can use an Arduino without any other components except a 3.3M ohm resistor to make a emf detector and in the video his is decently responsive! I don’t have a 3.3M ohm resistor I’m was using a 1M and and before that I was using three 1M and a 3K chained together but that didn’t works. I am now using them with shorter leads and only 3M. Also I’m using tinned copper wire for the antenna but that shouldn’t matter as I sanded it off. I’m extremely pissed because I’ve been trying to find some way to integrate an EMF sensor with an Arduino for months and all the different ways that work in videos online don’t for me. I’m powering it with a 9v battery and also tried powering it from my laptop. If I touch the bare antenna the led goes on but bringing my iPhone next to it does nothing or even the soldering iron, also I’ve tried multiple antennas. I really need help I’m not sure what the problem is. Also if there is any other way that you know of to implement a good EMF sensor with an Arduino that is compact I’m all ears. Thanks in advance.


texts: Arduino Pro Mini name in CMakeList.txt in CLion

texts:
I recently try to get my Arduino Pro Mini (5v 16mhz)running in Clion.

I tried to set up the CMakeList.txt but I get the following error:

  Error:Can not find f_cpu in boards.txt for Arduino board ID (pro),
  aborting.

I used the following configuration:

set(${CMAKE_PROJECT_NAME}_BOARD pro)

In the boards text, located at C:\Program Files (x86)\Arduino\hardware\arduino\avr\boards.txt I found the following lines:

pro.name=Arduino Pro or Pro Mini

pro.upload.tool=avrdude
pro.upload.protocol=arduino

pro.bootloader.tool=avrdude
pro.bootloader.unlock_bits=0x3F
pro.bootloader.lock_bits=0x0F

pro.build.board=AVR_PRO
pro.build.core=arduino
pro.build.variant=eightanaloginputs

## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
pro.menu.cpu.16MHzatmega328.upload.speed=57600

pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

So I'm wondering what Boardname to use, to get the Pro Mini working. Thanks in advance!


texts: Firmata seems to be a popular protocol for communicating between the Arduino and host computer. However, there only seems to be C/C++ libraries for the Arduino. Most Firmata libraries for the host appear to be in Python. I've found a few C/C++ Firmata libraries for the host, but they seem incomplete and unmaintained. Is anyone aware of a full-featured C++ Firmata library designed to run on the host computer?


texts: Why is Arduino Pro Mini not powering this LED?

texts:
First off, I'm very new to Arduinos and electronics in general, so feel free to explain like I'm 5.

As a bit of background to this question, the project is simply using a Pro Mini to run a servo, with a button to turn it on and off, and an led to indicate when it's on. To make sure I was getting the button right, I built the circuit on a breadboard with just the button and LED. The button was supposed to switch the LED on and off. It did not.

I removed the button from the equation and just tried to power the LED with the Mini. No go.

It's a blue LED, so the resistor (100) was chosen assuming a forward voltage of 3.3V and current of .02A. I've tested the resistor and LED combo with JUST the battery pack, and it lights up bright like it should.

I have a 9V battery running into RAW (I've also tried a 6V pack). I had pin 2 as an output with digitalWrite(HIGH), running into the resistor, then into the LED (+, long end), and then back to a ground pin. I've tried other ground pins on the board to make sure it's not that. I've switched pin 2 to analogWrite(255), still nothing. I have tried connecting it to VCC instead. Nothing.

However, writing HIGH to the onboard LED works fine, so I can see that the sketch is indeed running.

I've verified the LED polarity. I have tried a different Pro Mini. Nothing. It's a Pro Mini 328P according to the stamp on the back, which Google says runs at 5V and 16 MHz.

Please tell me what stupid mistake I am making so I can stop wanting to rip my hair out. Thank you.


texts: Using Serial.write() to send a uint32_t send one byte x4 or send 4 bytes x1

texts:
In the IRremote library, IR signals are decoded and held in results.value.  My project uses the NEC protocol which is 32 bits, so the IR code will always be 4 bytes.

uint32_t dCodedIR;
//
//  code exists here that we can ignore
//
dCodedIR = results.value

This decoded signal is then sent out the serial port to a second MCU which will be waiting for incoming data:

while (!Serial.available())  {
}

After this, there will ideally be a complete code of 4 bytes waiting in the FIFO. I will allow for times when < 4 bytes are ready (check for more, timed out? NO:loop   YES:reset), but this should rarely happen. So I want to optimize the sending code so that the receiver has the best chance of avoiding split groups. In theory, is it better to write as single bytes and repeat 4 times, or make a 4-byte array to send once?

Serial.write(dCodedIR & 255);
Serial.write((dCodedIR >> 8) & 255);
Serial.write((dCodedIR >> 16) & 255);
Serial.write((dCodedIR >> 24) & 255);

or

byte sendBuf[4];
//
//
sendBuf[3] = (byte) dCodedIR & 255;
sendBuf[2] = (byte) (dCodedIR >> 8) & 255;
sendBuf[1] = (byte) (dCodedIR >> 16) & 255;
sendBuf[0] = (byte) (dCodedIR >> 24) & 255;
Serial.write(sendBuf, 4);

(Since there will be plenty of storage space for the code, with performance being the priority, I decided against using for loops because updating an index, testing it, and looping would seem to add overhead.)


texts:
I am looking to control an addressable LED Strip (WS2812B) mode via a Nextion display. Below is a short version of my code.
CODE
//////////////////////////////
//  LED LIGHT SHOW PRESETS  //
//////////////////////////////

int showType = 0;

void startShow(int i) {
  switch(i){
    case 0: colorWipe(strip.Color(0, 0, 0), 50);    // Black/off
            break;
    case 1: colorWipe(strip.Color(255, 0, 0), 50);  // Red
            break;
    case 2: colorWipe(strip.Color(0, 255, 0), 50);  // Green
            break;
    case 3: colorWipe(strip.Color(0, 0, 255), 50);  // Blue
            break;
    case 4: theaterChase(strip.Color(127, 127, 127), 50); // White
            break;
    case 5: theaterChase(strip.Color(127,   0,   0), 50); // Red
            break;
    case 6: theaterChase(strip.Color(  0,   0, 127), 50); // Blue
            break;
    case 7: rainbow(20);
            break;
    case 8: rainbowCycle(20);
            break;
    case 9: theaterChaseRainbow(50);
            break;
  }
}

uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

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

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

void theaterChaseRainbow(uint8_t wait) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// BUTTON CODE
void bt10PushCallback(void *ptr)
{

  if (showType < 9) {
    showType++;
    if (showType > 9)
      showType=0;
    startShow(showType);
  }

}

My Nextion display doesn't seem to be doing anything when I press the button? Please let me know if there is not enough information required to give an accurate answer.
Thanks!


texts:
I just got 4 nrf24l01+ modules with the external antennas, but I'm not able to make them work.

I'm using arduino nanos and MySensors to create a gateway and a sensor.

The funny thing is that when I put a antenna nrf as the gateway and a pcb nrf as sensor, they work just fine, but the other way doesn't.

I also tried two nrfs as gateway and sensor, but the behavior does not look good.

What could it be? Wifi router interference? Channel? Baud rate? Data rate?


texts:
I really need your help. I use VisualStudio and PlatformIo I still get this error:

  Linking .pioenvs\esp12e\firmware.elf
  .pioenvs\esp12e\src\main.cpp.o:(.data.DebugX+0x0): multiple definition of `DebugX'
  .pioenvs\esp12e\src\customFunctions.cpp.o:(.data.DebugX+0x0): first defined here
  collect2.exe: error: ld returned 1 exit status
  *** [.pioenvs\esp12e\firmware.elf] Error 1

I use header guards in my file, so I do not understand why is this part of code redeclared. I had to miss some elementary in cpp programming but I still can't get it to work.

Copy of my project:
https://bitbucket.org/fires/programingtesting/src/master/ESP8266/cpp/RedefinedError/

main.cpp

    #include <Arduino.h>;
    #include "../include/defines.h"
    //#include "../include/customFunctions.h"
    // Time
    uint32_t mTimeToSec = 0;
    uint32_t mTimeSeconds = 0;
    void setup() {
    etc. etc. etc.

customFunction.h

    #pragma once
    #ifndef CUSTOMFUNCTIONS_H
    #define CUSTOMFUNCTIONS_H
    void connectWiFi();
    void initializeOTA();
    #endif

defines.h

    #pragma once
    #ifndef DEFINES_H
    #define DEFINES_H
    #include <jled.h>
    #define BowlingLed 5
    #define StatekLed 4
    int DebugX = 1;
    #endif

Thanks for the help, I read many articles and many issues but I still do not understand why DebugX is redefined if it is in header guard.


texts: FIFO overflow - reading IMU MPU6090 and GPS uBlox NEO-6M at once

texts:
I am trying to read data from uBlox NEO-6m (I need just speed, just part of the code):

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 7, TXPin = 4;
static const uint32_t GPSBaud = 9600;

float gps_speed = 0;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup(){
ss.begin(GPSBaud);
}

void loop(){
if (ss.available())
    {
      gps.encode(ss.read());
      gps_speed = gps.speed.kmph();

    }
}

And in the same time I read data from MPU6090 using this code (gps code is integrated in it):

http://nevit.blogspot.de/2014/07/arduino-mpu-6050-pitch-roll-with-2.html

When I try to read data separately it works but together it stuck every second (probably reading of gps data) and MPU6050 serial monitor sending FIFO overflow error ..

I tried to lower MPU data rate to 20Hz from 100Hz but it didn't work. I use Arduino UNO.

I am not so much skilled.. Any idea? Is it even possible to do it like this?


texts: How to run 5 wires hibrid stepper motor with arduino uno?

texts:
I have a question. How to run stepper motor (Nema 17) that has 5 wires with arduino and stepper driver.
Here is the driver, stepper and Arduino when stepper has 4 wires.
http://jdreyer.com/projects/Arduino/ArduinoEasyDriverStepperMotorv1_Resize.png

I need help identifying the wires on my hibrid stepper motor. I will provide picture of dissasembled motor.

Questions are:

Wires identification?
How to connect it to ArduinoEasyDriver?
Code example desired.

UPDATE

  I am now thinking of making it bipolar (4 wires), because now in 5
  wires configuration motor is unipolar. I did some research and this
  motor is HIBRID. It can be driven as unipolar or bipolar. I will try
  to troubleshoot the wiring and find the common wire. Ill keep you
  informed.


texts: Does ATMega 328/2560 chips support JTAG-type programmer and hardware debugger?

texts:
As stated in www.Arduino.cc FAQ, "Can I use an Arduino board without the Arduino software? Sure. It's just an AVR development board, you can use straight AVR C or C++ (with avr-gcc and avrdude or AVR Studio) to program it."

For UNO/Pro Mini(ATMega328) and ATmega2560, does these two chips support JTAG type (some chip manufacturers may use different name) programmer / hardware-based debugger in same manner as the ST-Link/J-Link programmer/debugger where one can load code into the MCU and perform hardware break point and single stepping? Example as in  STM32 development board with ST-LINK programmer / debugger where the chip has built-in debug circuit that communicate with ST-Link.

Many thanks in advance.


texts:
I'm trying to make a program which you choose an angle, and it tells you it's respective Sin, Cos and Tan. But, I can't figure out why all of the angles I use have the same answer (Sin 0, Cos 1 and Tan 0. Can someone help me out?

#include <math.h>
double angulo;
double seno;
double cosseno;
double tangente;
double rad;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {

 Serial.println("Programa para calcular sen, cos e tg");
 delay(1000);
 Serial.println("Digite o angulo");
 angulo = Serial.parseInt();
 rad = angulo*0,0174533;
 seno = sin(rad);
 Serial.println("Seno");
 Serial.println(seno);
 cosseno = cos(rad);
 Serial.println("Cosseno");
 Serial.println(cosseno);
 tangente = tan(rad);
 Serial.println("Tangente");
 Serial.println(tangente);

}


texts:
Question: What registers do I use to access the IO on the Arduino Uno when I am using assembly for programming?

Background:  I was interested in practicing my assembly language skills on the Arduino (I thought it would be easier to turn LEDs on/off than to worry about console IO).  From doing a preliminary search, I have found that the AVR toolchain can be used to program the Arduino.  Yet, I don't quite know how to find the corresponding registers for the IO pins.


texts: Why does an Arduino MEGA 2560 have different PORTS

texts: I'm currently looking at my Arduino MEGA 2560 board and was just wondering why there are different ports to it e.g. ANALOG IN, DIGITAL, Communication? in fact I've only seen this in some microcontrollers. Not many microcontrollers have ports dedicated to certain things. Is anyone able to give me an answer as to why there is different ports to the microcontroller? is it making it easier for the chip to handle etc. A detailed but not too detailed answer would be great!


texts: The most effective way to format numbers on Arduino

texts:
I made a big search about how to Format Numbers with the Arduino. I want to format unsigned Longs into a String in this format: "23,854,972".

The most of the snippets I found work only with the standard C / C++ Libraries. They dont work on the Arduino until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.

For my Application it is very important that the solution uses the minimum Flash, SRAM and is fast.

Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is more effective in the sense of speed.

Incoming Number: 23854972
Arduino Program Output: 23,854,972


texts: invalid pure specifier (only '= 0' is allowed) before 'int'

texts:
#include <PixySPI_SS.h>
#include <Pixy.h>
#include <Adafruit_MotorShield.h>
#define X_CENTER        ((PIXY_MAX_X-PIXY_MIN_X)/2)
#define Y_CENTER        ((PIXY_MAX_Y-PIXY_MIN_Y)/2)

Pixy pixy;
 int TrackedBlock(int n) =
{
 int trackedBlock=0;
 float maxSize=0;
  for (int k=0;k<n;k++)
  {
    float newSize= pixy.blocks[k].height * pixy.blocks[k].width;
    if (newSize>maxSize)
    {
      maxSize=newSize;
      trackedBlock=k;
    }

  }
   return trackedBlock
}

For some reason the code returns the error message in the title every time I try to compile it. I can't really find any issues online that's the same as my error. Any help is appreciated!


texts:
I am currently working on an Arduino project where the Arduino will send data to a processing program via bluetooth and processing will draw the data. However, my code doesn't seem to work.

Here is my Arduino code:

#include <SoftwareSerial.h>

int bluetoothTx = 1;
int bluetoothRx = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
  Serial.println("Hello");
}

And here is my Processing code:

import processing.serial.*;
Serial myPort;

void setup() {
  myPort = new Serial(this, "COM42", 9600);
  myPort.bufferUntil('\n');
}

void serialEvent( Serial myPort) {
  String data = myPort.readStringUntil('\n');
  println(data);
}

I identified that the incoming port from the HC-05 module is "COM42" from my Bluetooth settings. I am expecting to see several "Hello" lines being printed on the processing console but this does not happen


texts: Crosses Initialization in switch case with different size of array per case

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

void loop()
{
 time_Text(2);
}

void time_Text(int PastTo_val) {
  switch (PastTo_val) {
   case 1:
   {
    int tPTT_y[] = {11, 11, 11, 11};
    int tPTT_x[] = {6, 7, 8, 9};
  }
  break;
case 2:
  {
    int tPTT_y[] = {11, 11};
    int tPTT_x[] = {10, 11};
  }
  break;
 }

 int n_tPTT = sizeof(tPTT_x) / sizeof(tPTT_x[0]);

 Serial.print(tPPT_y);
 Serial.print(" : ");
 Serial.print(tPPT_x);
 Serial.print(" : ");
 Serial.println(n_tPPT);

}

I have a case that I need to assign different kind of array value (with different size per case), and then find the size of the array, and print it. The problem is that the tPTT_y and tPTT_x is a local variable which cannot be accessed outside of the case function. I have tried to declare it before the switch function but I cannot give a size number because the size is different per case, how could I solve this?


texts: Configuring Timers to Add One More 50kHz Square Wave

texts:
I am generating two 50kHz square waves, but I would like to generate three square waves. I have problems with generating the third square wave.
Basically, I need to configure the timer bits so that I can get the third square wave.

Here is the code I need to modify for the third square wave:
// This code demonstrates how to generate two output signals
// with variable phase shift between them using an AVR Timer

// The output shows up on Arduino pin 9, 10

// More AVR Timer Tricks at http://josh.com

void setup() {
  pinMode( 9 , OUTPUT );    // Arduino Pin  9 = OCR1A
  pinMode( 10 , OUTPUT );   // Arduino Pin 10 = OCR1B

  // Both outputs in toggle mode
  TCCR1A = _BV( COM1A0 ) |_BV( COM1B0 );

  // CTC Waveform Generation Mode
  // TOP=ICR1
  // Note clock is left off for now

  TCCR1B = _BV( WGM13) | _BV( WGM12);

  OCR1A = 0;    // First output is the base, it always toggles at 0

}

// prescaler of 1 will get us 8MHz - 488Hz
// User a higher prescaler for lower freqncies

#define PRESCALER 1
#define PRESCALER_BITS 0x01

#define CLK 16000000UL    // Default clock speed is 16MHz on Arduino Uno

// Output phase shifted wave forms on Arduino Pins 9 & 10
// freq = freqnecy in Hertz (  122 < freq <8000000 )
// shift = phase shift in degrees ( 0 <= shift < 180 )

// Do do shifts 180-360 degrees, you could invert the OCR1B by doing an extra toggle using FOC

/// Note phase shifts will be rounded down to the next neared possible value so the higher the frequency, the less phase shift resolution you get. At 8Mhz, you can only have 0 or 180 degrees because there are only 2 clock ticks per cycle.

int setWaveforms( unsigned long freq , int shift ) {

  // This assumes prescaler = 1. For lower freqnecies, use a larger prescaler.

  unsigned long clocks_per_toggle = (CLK / freq) / 2;    // /2 becuase it takes 2 toggles to make a full wave

  ICR1 = clocks_per_toggle;

  unsigned long offset_clocks = (clocks_per_toggle * shift) / 180UL; // Do mult first to save precision

  OCR1B= offset_clocks;

  // Turn on timer now if is was not already on
  // Clock source = clkio/1 (no prescaling)
  // Note: you could use a prescaller here for lower freqnencies
  TCCR1B |= _BV( CS10 );

}

// Demo by cycling through some phase shifts at 50Khz

void loop() {

  setWaveforms( 50000 , 90 );

  delay(1000);

}


texts: Arduino (or clone) powered with one or two AA batteries or one CR2032, but still able to give +3.3V or +5V

texts:
Are there Arduinos (or clones) that can be powered with one or two AA batteries or one CR2032 3V battery? (it would sleep 99% of the day, and only send a few bytes per day)

If so, will they also have a +3.3V or even +5V output (produced by an internal step-up chip) that can be used by another chip?

(I know it might sound like having one's cake and eat it too, but maybe it exists?)


texts: Reducing noise and finding sampling rate

texts:
I have Arduino Due R3 (84MHz) and I am trying to find the mean of value from AnalogRead. I have to set the sampling rate of 8000 samples/second with 4 channels. I tried using for loop for this purpose.

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int i = 0;
int sensorPin = A0;
int sensorValue = 0;
int highest=0;
int lowest=0;
float mean=0;

void setup()
{
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  lcd.print("Hello");

}

void loop()
{

  for(;;)
  {
    mean=0;
    for(i=0;i<8000;i++)
    {
       sensorValue = analogRead(sensorPin);
     highest=max(highest,sensorValue);
     lowest=min(lowest,sensorValue);
     mean = mean + (highest-lowest);
    }
    mean = mean/8000;
    delay(10);
    lcd.setCursor(0, 1);
    lcd.print(mean);
  }

Will this set sampling rate to 8000 samples/sec ?

Also I was receiving  a lot of noise at A0 which often led to the lowest value to be 0. In the image : The  red wave is a constant dc voltage of 2.7 V from power supply.

How do I overcome this noise so that mean value is accurate and precise ?


texts:
I am working on project and using Arduino Pro Mini (Atmega328p running on 2xAA) to measure the time to charge a capacitor (when the volt level is high). This is the code I used while testing:

int counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while (digitalRead(7) == LOW) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

The code was working fine when the board was running at 16MHz since the loop was fast enough to give good result. ( counter =~ 28 when the test cap is charged).

However, the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) and when tested at that speed the counter only reaches 2~3 because the loop it too slow now that the cap will charge in about two to three cycles.

So I did two changes which are using byte instead of int for the counter, and reading the value of the pin directly from the PIND register:

byte counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while ((PIND & (1<<PD7)) == 0) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

Both of these changes increased the speed and now counter reads ~20 which is much better and almost close to the 16MHz.

Is there any further optimizations?

Can I use one of the general registers instead of the counter, if yes then how? and will that improve the speed?

Is there a more clever and faster way to do this loop?

Update:

I am going to follow the suggested answer and use the analog comparator, but I also wanted to add to my finding which might help others with general optimization.

Instead of incrementing the counter and comparing if it is larger than some value, it is faster to decrements and compare if it is equal to zero. The counter improved to ~23.


texts: Use Adafruit Colorsensor to distinguish between green and red

texts:
I am using the Adafruit TCS34725 to sense color. I have used the Colorview code example to set it up to sense all colors, works great. The thing I want is for it to tell me if it is seeing either green or red, I don't care about the other colors.

Can anyone suggest what I can do?


texts: library for both HardwareSerial and Serial_

texts:
many Arduino boards use the HardwareSerial class, like the AVR based boards (UNO, MEGA), ESP* and the official STM32duino. Recently seems that Arduino made a new class called Serial_ which works on the MKR boards (VIDOR4000, 1010, 1000). Other classes exist like the SoftwareSerial

I would like to make a library that accept all serial classes, I have a function in my header file like the above:

void enableDebug(HardwareSerial *debug_port);

these are the possibility I see:

defines:

#if defined (ARDUINO_SAMD_MKRVIDOR4000)
#define HardwareSerial Serial_
#endif

overload:

void enableDebug(HardwareSerial *debug_port);
void enableDebug(Serial_ *debug_port);

maybe templates? not sure if it would be possible
custom class: Passing HardwareSerial and SoftwareSerial as a Class Property

How would you achieve it? do you see other possibilities and could you point out the best way to do this?

I edited my question adding the linked solution but simpler methods would be preferred


texts:
I've never much issue importing a library to my master sketchbook location, restarting Arduino, then using the library examples. Today is a different story:

I'm loading RCLib which is part of this ArduinoLibraries family
RCLib requires PinChangeInt

So everything is in my sketchbook location right? Arduino > Preferences > Sketchbook Location

Still I'm getting compiler errors about missing libraries:

/Users/Jackson/Documents/Arduino/ArduinoLibraries-master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino:7:86: fatal error: PinChangeInt.h: No such file or directory
 #include "PinChangeInt.h"

I've even tried #include <PinChangeInt.h> Which makes more sense since this is a system library.

What is going on here?

The sketch I'm trying to run:

/**This is an example of using the RCLib with a mega and pinchangeint
 * This example isprovided as is by Jantje
 * Congratualtions, constructive feedback and I like it can be send to eclipse@baeyens.it
 **/

#define NUM_RC_CHANNELS 6 //You need to specify how many pins you want to use
#include "PinChangeInt.h"  //If you need pinchangeint you need to include this header
const uint8_t RC_Channel_Pin[NUM_RC_CHANNELS]={
  A8,A9,A10,A11,A12,A13};//Here I specify I want to listen to pins A8 to A13 of my mega

uint16_t RC_Channel_Value[NUM_RC_CHANNELS]; //This variable will contain the values read from the RC signal
#include "RCLib.h" //This include needs all declarations above. Do not try to move it up or it won't compile

Arduino v1.6.9 | OSX 10.11.4


texts: Performance tuning PORTB manipulation - mask

texts:
I have the following snippet that seems to be taking a total of 6 CPU cycles per invocation.

Can I speed this up somehow? x  is a byte with the 3 lowest bits set.

#define SET_COLOR(x) PORTB = (PORTB & ~(7)) | x


texts:
Currently practicing my programming knowledge
So,am using atmel studio to program atmega328p
I have a "for" statement that flashes an LED(led1) 5 times when button1 is pressed.
Then another "if" statement to control led2 via button2.
But while simulating the circuit on Proteus. Whenever led1 is flashing, button 2 will not be able to light up led2 until after the flash.
So, it appear as if the "for" statement is blocking the other program.
Any help will be appreciated

while (1)
{
    for (int j=1; j<=5; j++){
        If (!(PINB &(1 <<button1))){
            PORTB |= (1<<led1);
            _delay_ms (100);
            PORTB &=~(1<<led1);
            _delay_ms (100);
        }
        else {
            PORTB &=~(1<<led1);
        }

        if (!(PINB &(1 <<button2))){
            PORTB |= (1<<led2);
        }
        else {
            PORTB &=~(1<<led2);
        }
    }
}


texts: Is it possible to get which pin generated interrupt?

texts:
I wrote some code that handles rotary encoder using an interrupt, but I would like to get which pin generated the interrupt, so I'll be able to handle many interrupts in a single method.
Something like:

void ISREncoders()
{
  int pin = GetCurentInterruptPin(); // <============= this
  int dataPin = dataPins[pin];
  int data = DigitalRead(dataPin);
  if(data == HIGH)
  {
    encoders[pin] += 1;
  }
  else
  {
    encoders[pin] -= 1;
  }
}

Is it anyhow possible?

As mentioned in the answer this is not possible. Still, after peeking some encoder libraries that use interrupt found out that they do the following:
The Encoder class contains several static ISR methods hard coded.
As you create new objects it increments an internal counter and sets proper ISR method on the interrupt.
This is for sure the best solution available, but this is not at all scalable, for instance if you have an imaginary board with thousand pins that handle thousands encoders you will have to hard code each ISR method.


texts: Strange behavior from uint32_t, acting like signed int (Nano clone)

texts:
I'm having trouble with these variables. As you can see they're uint32_t type, so they should have a maximum value of 4 million or so, but they're rolling over and going negative at 32,767 like a signed int. Here's the relevant code:
byte lPin = 7;
char buff[100];
uint32_t loAvg = 0;
uint32_t hiAvg = 0;

void setup() {
  pinMode(lPin, OUTPUT);
  digitalWrite(lPin, HIGH); // Active LOW, so this is off

  Serial.begin(9600);
  // Generate high/low averages
  for(int i = 0; i < 100; i++) {
    loAvg += analogRead(A0);
  }
  loAvg /= 100;

  digitalWrite(lPin, LOW);
  delay(500);

  for(int i = 0; i < 100; i++) {
    hiAvg += analogRead(A0);
  }
  hiAvg /= 100;

  digitalWrite(lPin, HIGH);
  delay(500);

  sprintf(buff, "loAvg=%d, hiAvg=%d", loAvg, hiAvg);
  Serial.println(buff);

  Serial.println(hiAvg);
  digitalWrite(lPin, LOW);
  hiAvg = 0;
}

void loop() {
  sprintf(buff, "test=%d", hiAvg);
  Serial.println(buff);
  hiAvg+=100;
}

I removed a bunch of stuff from the code to save posting the whole (much longer) thing. If it ends up being relevant I can though, I just think I narrowed the problem down to this. Observing the serial monitor I get this on startup:
loAvg=287, hiAvg=0
933
test=0
test=100
test=200
...

The test=# repeats until 32700, then continues at -32736. I'm confused by the hiAvg=0 followed by the 933, showing that it totally is getting a high average, because that's around what it should be. Even if it's the sprintf() messing with it, in the setup function the value should only be around the 900 range so it wouldn't overflow there. Any ideas anyone?


texts: Getting the highest value from analog reading?

texts:
I am doing a project using an FSR (Force Sensitive Resistor), I'm currently reading values with no problem every 100milis. I want to output via Serial.print the highest value, I've read.

I am having a hard time doing so. The project is use to "measure" the strength some projectiles hit the sensor. I want to get the highest value.

This is the code I have until now.

int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider
void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.println(fsrReading);     // the raw analog reading

  delay(100);
}


texts:
i found following code online, to read the value of a touch sensor... i am having difficulties understanding how the 2 second timeout on the marked line works..
 if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {
touch_sensor_value is the value read from the touch input.. and the rest?? i dont see any comparison with anything in the parenthesis, i cant figure out how this if condition is working...
#define TOUCH_timeSeconds 2
uint64_t now = millis();
unsigned long lastTrigger_TOUCH = 0;
bool startTimer_TOUCH = false;
bool buttonIsPressed = false;

int touch_sensor_value = 0;
//Mux control pins
int s0 = 26;
int s1 = 27;
int s2 = 14;
int s3 = 12;
//State array
int currentState ;
//Mux in “SIG” pin
int SIG_pin = 33; //is touch sensor
void setup()
{
pinMode(s0, OUTPUT);
pinMode(s1, OUTPUT);
pinMode(s2, OUTPUT);
pinMode(s3, OUTPUT);

digitalWrite(s0, LOW);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);

Serial.begin(115200);
Serial.println(“Multiplexing 1 Touch sensor ESP32 using CD7HC4067 MUX”);

}

void loop() {

for (int i = 0; i < 16; i ++) {
currentState = readMux(i);
touch_sensor_value = touchRead(T9);

if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {    <-----!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);
buttonIsPressed = false;
startTimer_TOUCH = false;
return;
}

//

}

// delay(1000);
}

int readMux(int channel) {
int controlPin[] = {s0, s1, s2, s3};

int muxChannel[16][4] = {
{0, 0, 0, 0}, //channel 0
{1, 0, 0, 0}, //channel 1
{0, 1, 0, 0}, //channel 2
{1, 1, 0, 0}, //channel 3
{0, 0, 1, 0}, //channel 4
{1, 0, 1, 0}, //channel 5
{0, 1, 1, 0}, //channel 6
{1, 1, 1, 0}, //channel 7
{0, 0, 0, 1}, //channel 8
{1, 0, 0, 1}, //channel 9
{0, 1, 0, 1}, //channel 10
{1, 1, 0, 1}, //channel 11
{0, 0, 1, 1}, //channel 12
{1, 0, 1, 1}, //channel 13
{0, 1, 1, 1}, //channel 14
{1, 1, 1, 1} //channel 15
};

//loop through the 4 sig
for (int i = 0; i < 4; i ++) {
digitalWrite(controlPin[i], muxChannel[channel][i]);
}

//read the value at the SIG pin
int val = analogRead(SIG_pin);

//return the value
return val;
}


texts: Long freezes at the beginning of sd card transfer

texts:
I am creating an accelerometer data logger that writes data to sd card. After some sort of "warm-up" everything works perfectly for at least ~15 minutes (which is what I have tested so far).

However, during the first few seconds there are some pretty long freezes of the File.write() function (180 ms instead of 50us for normal writes!) which I can identify on an oscilloscope (see picture below, signal low after starting high indicates File.write() phases) and which I can also see in the data if I include in them a milis() timestamp.

Since RAM on the Atmega328 is limited, there is also tight limits to the amount of sensor data I can buffer (I am using an interrupt for transfer from the sensor, where I can store the data to a buffer and thus bridge the shorter sd card delays).

I stripped down my code to the absolute bare bones, just writing nonsense data instead of those from the accelerometer. What could be the reason for these freezes? The data rate is the same during the whole run. Isn't the sd card electrically or logically initialized after SD.begin()? It doesn't seem to be a problem with erasing flash memory blocks because it only occurs in the beginning. Even if I restart the application a second time (after staying electrically on all the time) it already shows no freezes anymore. Whereas if I unplug/plug power, the freezes in the beginning reappear.

And most importantly: how can I solve it?

Of course I could write the dummy data before receiving the start button. But how many? Does it depend on sd card type? Does it depend on cpu or spi clock frequency? I want a robust solution that doesn't break when I use another type of sd.

Code:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 10; // chip select of the sd card
const int pushButton = 9; // this is where the start button is (on a pulldown resistor)
const int debugPin = 1; // a line used for displaying a debug bit on the oscilloscope

const int bufferSize = 14;
byte buffer[bufferSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; // for the test just dummy values

String fileName = "accellog.raw";

void setup()
{
  pinMode(pushButton, INPUT);
  pinMode(debugPin, OUTPUT);

  if (!SD.begin(chipSelect))
  {
    // on error stop execution
    for(;;);
  }
}

void loop()
{
  // wait for the start button to be pressed
  while (digitalRead(pushButton) == HIGH);
  delay(100); // debounce delay
  while (digitalRead(pushButton) == LOW);

  // remove old file on sd card
  if (SD.exists(fileName)) SD.remove(fileName);

  File dataFile = SD.open(fileName, FILE_WRITE);

  if (dataFile)
  {
    // Debugging: indicate start of whole data transfer on an oscilloscope
    digitalWrite(debugPin, HIGH);

    int lastMillis = millis();

    for (long i=0; i<10000; i++)
    {
      // wait until millis changes in order to get SD writes at
      // whole millisecond boundaries (some cycles may get lost,
      // however, during lengthy SD writes)
      int tempMillis = millis();
      while (tempMillis == lastMillis)
      {
        tempMillis = millis();
      }
      lastMillis = tempMillis;

      // Debugging: indicate file access times by sending 0 to the DSO
      digitalWrite(debugPin, LOW);

      dataFile.write(buffer,bufferSize);

      // Debugging: indicate end of file access on DSO
      digitalWrite(debugPin, HIGH);
    }

    // Debugging: indicate end of whole data transfer
    digitalWrite(debugPin, LOW);

    dataFile.close();
  }
  else
  {
    // on error stop execution
    for (;;);
  }
}


texts: How can you switch variables recorded in memory by time?

texts:
const int KEY_LEN = 32;;
unsigned long key1 = 0x76AFDBAA;
unsigned long key2 = 0xC6E2F8F8;

const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter
unsigned long my_timer;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  my_timer = millis();
}

void loop()
{
if ((millis() - my_timer) <= 2000) //
  {
    unsigned long key = key1;
  }
if ((millis() - my_timer) > 2000 & (millis() - my_timer) < 4000)
  {
    unsigned long key = key2;
  }

    if (key & 1) delayMicroseconds(4000);
    else delayMicroseconds(2000);
  }

I have two keys and I want to switch between them every 4 seconds without any buttons. That is, when the supply voltage is applied, the keys change each other every 4 seconds. Namely, you need to load one of the keys into the key variable and then operate with this value (compare it, read it, output it to a digital pin, and so on).
The only thing that comes to my mind is to use a timer, but I can’t write it down correctly, now it doesn’t work. It is necessary that he does not stop at the last key, but switches all the time.


texts:
How would you send data wirelessly from arduino uno to a pc?

I know you can connect wifi shield / wifi breakout to arduino and use that, but what other ways are there and how practical would they be?


texts: Programming Arduino Pro mini 328 with Arduino Uno SMD

texts:
I apologize in advance, because there is a lot of tutorials out there about programming arduinos with another arduino, however I can't find really simple one I could understand.

I have Arduino Uno SMD version and Arduino Pro mini 328. I want to upload sketch to Arduino Pro mini using Arduino Uno in ISP mode (I guess).

I want to know EXACTLY which pins need to be connected and if all I need is Arduino IDE to upload my sketch to Pro mini ?

Thank you for your help.


texts: analogRead values all over the place, while measuring light

texts:
I'm trying to detect light using an led that's already attached to the circuit. I have a flashlight shining on the led.

Minimal sketch:

while( true )
{
    int photoValue = 0;
    analogReference(INTERNAL);
    photoValue = analogRead(A5);

    Serial.println(photoValue);

    delay(300);

}

While I have my multimeter attached, it reads a pretty constant value around 5mV. The serial output however swings around, as seen in this sample output:

0
0
4
4
0
16
15
22
21
25
20
36
40
34
36
24
5
0
3
6
0
0
0
0

That would translate to values between 0 and 43mV.

When I disconnect the multimeter only get 1023 printed.

I don't get how the values from the ADC and the multimeter, totally don't match.


texts: Can I work with larger numbers than an unsigned long long in Arduino?

texts: I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?


texts: How Should I Send Data to My Laptop from Multiple Arduinos?

texts:
I'm working a project which involves reading multiple RFID tags, from multiple directions, at the same time. Because of the multiple directions, I need to use multiple antennae. Because of the multiple tags, I need to use a simultaneous RFID reader.

Unfortunately, the wiring of the simultaneous RFID reader doesn't support multiple antennae, so each antenna will need its own simultaneous RFID reader. It seems likely - although I'm waiting for confirmation on this - that each RFID reader will have to have its own Arduino as well. What's the least horrible way of sending the data those antenna-reader-Arduino combinations are gathering to a laptop?

If this makes a difference, the laptop I'm going to be sending the data to will be running Ubuntu, and I'd like to collect the data using Python's pyserial package. Once I've got the data in a Python program, we're home and dry.


texts: Can you connect more sensors of the same type to a single board while not using up more pins than if you were to use a single sensor?

texts:
I'm as new as you can be at Arduino programming and specific electronics, so I don't even know if I'm asking the correct question.

I've ordered an Arduino a breadboard and some PCBs and now I'm looking for a few parts that I should buy in order to get some basic projects done.

I'd like to start with a garden automation project, a fairly simple one.
Humidity sensors, temperature sensors and a water pump.

Can I connect all (4) of the humidity sensors to a single local circuit and then connect that to the board so I can limit the number of input pins used? I'd still need to get independent readings from the sensors. Or would I need to use another board incorporating RF/Wireless/Bluetooth modules to receive the information and then send it to the board for further processing?

I'm sorry if what I just said makes no sense and I thank you for your time.
All I have is low-mid level electronic related experience. Battery checkers, Power supplies, basic light sensors, PCB making ETC.


texts:
I am completely new to programming, and I need some pointers where to look for a possible solution.

Currently I have been trying to get input from my Arduino buttons to Visual Studio to then do something with the input specifically.

There are three buttons setup and I want to use the input of these to control the answering for a quiz game in Visual Studio. Only one button can be pressed, then it will show a messagebox and advances to the next question. At the moment im having a hard time figuring out how to do this. Any pointers where to look is greatly appreciated.


texts: View Arduino M0 SD card content on a computer

texts:
Recently I bought an Arduino M0 board and I'm using it in one of my projects, which logs GPS data into an SD card.

Can an Arduino M0 be programmed as a USB SD Card reader? So that I don't have to remove the SD card from the system and use the same USB port from M0 to see the contents of the SD card directly on my computer.


texts:
I want to control my fog machine with an Arduino.  Has a simple button that is used to activate the machine.  I want to press this button using an Arduino digital output pin, but the fog machine is operating on its own electrical circuit.  How do I use the Arduino to activate this machine?

I a few other machines with buttons that I want to wire into an Arduino, so is there a generic solution?


texts:
I bought this waterproof ultrasonic sensor about 5 of them with the part number SR04M-2 Written on the PCB silkscreen Which is different from the usual SR04t-0.2, they are just not working, I don't know if its using a different communication protocol or its faulty because no output is coming out of the sensor at all.
if anyone out there has ever came across this type and was able to walk his/her way around it should help


texts: I can't receive string that I have sent through nrf correctly

texts:
I'm using arduino uno and nrf24l01. to monitor sensor data.
But this is the message that master receives:

  ⸮

this is my slave code.

void monitoring() {
    delay(10);
    radio.stopListening();
    int soilMoisture = analogRead(A5);
    int light = analogRead(A4);
    float temp = analogRead(A3);
    temp = temp * 0.48828125;
    int ltemp = int(temp);
    String message = String(soilMoisture) + "," + String(light) + "," +    String(ltemp);
    Serial.println(message);
    delay(200);
    radio.write(&message, sizeof(message));
    delay(50);
    radio.startListening();
    delay(10);
}

and here is my master code.

while (1) {
    if (radio.available()) {
      char message[32] = "";
      radio.read(&message, sizeof(message));
      delay(500);
      Serial.println(message);
}


texts: How can I control neopixels attached to a Digispark?

texts: I want to use a string of Neopixels attached to a Digispark hanging off of a RasPi3 as indicators for various situations.  For example: a motor (connected to a driver hat on the I2C bus of the RasPi) turns on or reverses direction.  Can I use Firmata, or is there something like it for the Digispark that I can use with Python?


texts:
I'm working on big Arduino project that involves lots proprietary libraries. Ergo, we need test scripts to ensure each library works. Is there a testing framework for Arduino similar to CPPUnit, JUnit, Cunit, etc.? It should preferable also have the ability to simulate an Arduino.

EDIT: By "Arduino Simulator" I only want something that allows observation of local variables, global variables, the different register values (at a minimum the INPUT/OUTPUT status of the pins, what is being inputted or outputted), and fake inputs into the various pins. This way, only the Arduino itself needs to be simulated, not the external hardware components like LEDs, buttons, real time clocks, motors etc.


texts: How can I detect the amount of water that must be filled in an arbitrary container?

texts:
So I am making a Smart Water Dispenser that must detect the amount of water that must be filled in an arbitrary shaped container. This is what I have thought:

Installing an IR LED strip to first detect the length of the container, and then fill the water upto that height; monitoring the height using Ultrasonic Sensor. But this does not seem good enough for narrow necked water bottles as the ultrasonic sensor is quite big.
I also thought of monitoring water height by directly lowering a water level measurer, into the container along with the water outlet. But the problem with this is that all the setup must be food grade since this would be drinking water.

Can anybody suggest a better method?
I do not have a vast knowledge of sensors currently. So introducing a new sensor into the play would be encouraged.


texts:
Is there a possibility to analog read on the 2.4Ghz band to just read how much activity is in the presence of your device? Not parsing the messages but just listening to how strong of a signal you are getting on a specific bandwidth?
All information is welcome.


texts: Help with button library, hold>2s doA else doB

texts:
I'm using JChristensen's Button Library to debounce my buttons and provide extra functionality.  I'm trying to use his press & hold function to do something if the button is pressed and held for greater than 2 seconds.  If it is just pressed momentarily it should do something else.  His example use switch cases, and I couldn't get it to work.  Here is my example that currently doesn't work.

    #include <Button.h>
    #include <SPI.h>
    #include <printf.h>

    // Keypress state setup
    byte clearPin = 16; // Clear pin

    #define PULLUP true
    #define INVERT true // Since the pullup resistor will keep the pin high  unless the
    #define DEBOUNCE_MS 20 // A debounce time of 20 milliseconds usually works well for tactile button switches.
    #define LONG_PRESS 2000 // We define a "long press" to be 2000 milliseconds.
    unsigned long ms; // The current time from millis()
    Button clearBtn(clearPin, PULLUP, INVERT, DEBOUNCE_MS); // Declare the button
    int score=1;

void setup ()
{
  pinMode(16, INPUT_PULLUP); // Pin for clear button
  Serial.begin(9600); // Radio Setup
}

void loop()
{
 clearScore(); // sets both home and away scores to 0 or enters settings menu
}

void clearScore()
{
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button

  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
     Serial.println("Settings Menu");
     while (clearBtn.read()!=1) {

     } // End While
   return; // Hopefully not proceed down to the next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }

}

Can anyone help please?  My serial output repeats "Settings Menu" over and over.  Once I let go of the button variable1 always gets set to 0.


texts: Driving single-character alphanumeric (16-segment) displays

texts:
I would like to drive three sixteen-segment displays (https://www.sparkfun.com/products/retired/9934) using an Arduino Micro. These displays would output an alphabetic character that a user would scroll through using rotary encoders, and constitute a subsystem of a larger project where the user enters a "combination" made from the three letters to "unlock" functionality in the larger device.

The best option, if it could be called that, is this retired product from SparkFun: https://www.sparkfun.com/products/retired/10103 that would allow me to drive the displays without a huge wiring mess, and spares me a lot of pins on the Micro to use on the rotary encoder. Unfortunately, the product is retired because the A6282 IC it was based on reached end of life, so even the schematics available on the product page aren't much use to me.

I am aware that four-character 16-segment displays are available, but for "aesthetic" reasons I am constraining myself to using single-character 16-segment displays. I do wonder how possible it would be to run three or four individual 16-seg displays from one of those LCD backpacks, but I don't think that would be trivial to do (I'd need to, probably, fabricate some sort of printed circuit board that spaced each display as far out as I need them to be, hook the pins of each display into a key matrix, and then at that point it'd be substantially easier to just get a MAX6954 (https://www.maximintegrated.com/en/app-notes/index.mvp/id/3212) and try to figure that out). It would be very clumsy to prototype.

So, I'm looking for a solid method of prototyping this "combination entry" subsystem and its 16 segment displays without needing to put each dial and alphanumeric display on its own AVR or something.


texts: Send stepper to position and back AccelStepper

texts:
At the moment I am working on a code that should send a plateau to a certain position and back. The plateau is being moved by the stepper, in my case a Nema 17 with a Polulu DRV8825 driver. Everything is hooked up correctly.
My goal is to press '4' on the keyboard and that then the stepper moves to a certain position. However, I am not succeeding in this. I am using AccelStepper and at the moment I have the following code:

#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1
int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.runSpeed();
}

Does anyone have tips or know how to achieve this?

Thanks is advance!


texts:
I have started learning about arduino and just bought a bluetooth module, HC-05. From where i bought, it says it has range of approx.10 meters. I made hc-05 connection with arduino in below described ways
I am using it as a slave with default configurations, 9600 baud rate and HC-05 name with pin 1234
GND of HC05 -> GND of `arduino`
VCC of HC05 -> 5V of `arduino`
TX of HC05 -> RX of `arduino`
RX of HC05 -> TX of `arduino` via voltage divider network 2k---|---1k

Below is my arduino code
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.

int pin = 13;
char c = ' ';

void setup()
{
 Serial.begin(9600);
 Serial.println("Arduino is ready");
 pinMode(pin,OUTPUT);

 // HC-05 default serial speed for communication mode is 9600
 BTserial.begin(9600);
 Serial.println("BTserial started at 9600");
}

void loop()
{
  if (BTserial.available()>0){
    c = BTserial.read();
    Serial.println(c);
    switch (c){
      case '1' :
        digitalWrite(pin,HIGH);
        break;
      case '2' :
        digitalWrite(pin,LOW);
        break;
      default: break;

    }
  }
}

Following things happening to me:

When I power the module I am able to discover it with my phone but only when I hold my phone very near to the module. If I move away from the HC05 module, for example 3-4 feet, I am not able to discover it.

2.After connecting with it (while holding phone near to the module), I am able to send data to it but again, if I move away , only a few steps, I am unable to send data and I disconnect from it automatically. Also if I change direction of the antenna even then no communication happens.
My purpose is to control my home's lights and TV with the help of this module and Relays. But HC05 is useless so far. I was hoping that I would code it and wire it and hang it on a wall and interact it with and andoird app.
Is it suppose to happen like this? or there's something wrong with my module's antenna
thank you.


texts: Can I power up my Arduino and MotorShield with four AA batteries?

texts:
can I power up my Arduino UNO with four AA batteries? It's about 6V, will my arduino burn? And, if I power my Arduino, I have to power my Motor Shield too or not?

I want to make line follower. I have to know what I have to power up. I dont know, how many battery holders I need. I have: Arduino UNO, motor shield, two 6V DC motors


texts:
I am trying to send a 50x50 bitmap bytearray from my python client to arduino where it should be displayed on a screen.

I need to receive 350 bytes to have the data to show the bitmap but as soon as i initialise the array with > 255 elements it does weird things (i guess because of the memory):

When initialising the array with size 254 it does the expected:

  Transmission of 350 completed in 2.805466s (arduino) Received: 253
  elements

with size 350 I only get

  "Received: 93 elements"

How can i split the bytes i receive with the available memory and then build the bitmap accordingly or what is a better way to do it? I would like to have it transmitted via serial rather than building the qrcode in arduino (as i couldn't get the libraries required working in my setup).

My python client does basically this:

for element in qrCodeBytes:
    countElementsSent+=1
    ser.write(element)
    print("Sending " + str(element))
ser.write("$".encode()) #stop char

My arduino code is based on the popular Serial input basics guide
https://forum.arduino.cc/index.php?topic=288234.0

 const byte numChars = 254;
 byte receivedChars[numChars]; // an array to store the received data

boolean newData = false;

void setup() {
 Serial.begin(114000);
 Serial.setTimeout(10000);
 Serial.println("<Arduino is ready>");
 display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
 display.clearDisplay();
 display.display();
}

void loop() {
 recvWithEndMarker();
 showNewData();
}

void recvWithEndMarker() {
 static byte ndx = 0;
 char endMarker = '$';
 char rc;

 // if (Serial.available() > 0) {
   while (Serial.available() > 0 && newData == false) {
     rc = Serial.read();
     if (rc != endMarker) {
       receivedChars[ndx] = rc;
       ndx++;
       if (ndx >= numChars) {
         ndx = numChars - 1;
       }
     }
     else {
     receivedChars[ndx] = '$'; // terminate the string
     Serial.println("Received: " + String(ndx) + " elements");
     ndx = 0;
     newData = true;
     }
   }
}

void showNewData() {
 if (newData == true) {
 Serial.println("This just in ... ");
 display.clearDisplay();
 drawBitMap(receivedChars,50,50,0);
 display.display();
 newData = false;
 }
}

void drawBitMap(unsigned char *img, int width, int height, int position){
  if (position ==0){
   display.drawBitmap(128/2-(width/2), 64/2-(height/2), img, width, height, 1);
  } else if (position == 1){
   display.drawBitmap(128-62,1, img, width, height, 1);
  } else if (position == 2){
   display.drawBitmap(0,5, img, width, height, 1);
  }
}


texts: problem serial hardware sim7600 arduino due

texts:
I am very newbie using arduino. I get a EVB SIM7600 TTL 3V and I am trying to test it using a arduino Due.
I need a help please, my simple code doesnt work.
The serial monitor only show zeros. The baudrate default for SIM7600 is 115200bps. I insert a simcard and then write AT command in serial monitor, for example ATI... I received zero

Here is my code and photo of connection.

void setup() {

  Serial.begin(115200);
  Serial.println("Testing GSM SIM7600");
  Serial1.begin(115200);
  delay(100);

}

void loop() {

  if(Serial1.available())
  {
    Serial.println(Serial1.read());
  }

  if(Serial.available())
  {
    Serial1.write(Serial.read());
  }

}


texts: I need a random code for Arduino Uno to trigger a single relay

texts:
I am trying to get a random triggering of a single relay from an Arduino Uno. I would also ultimately like to be able to adjust the speed that the random triggering happens at. How are the times between the randoms adjusted?
I have tried some codes and have the relay hooked up to pin 8 on the Uno, and would like more control. Thanks

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

void loop() {

long randnumber;
long randnumber2;
long randnumber5;
long randnumber6;

randomSeed(analogRead(A0));

randnumber = random(5, 9);
randnumber2 = random(5,9);
randnumber5 = random(3370,498);
randnumber6 = random(537,4370);

digitalWrite(randnumber, HIGH);
digitalWrite(randnumber2, LOW);
delay(randnumber5);
digitalWrite(randnumber, LOW);
digitalWrite(randnumber2, HIGH);
delay(randnumber5);
}


texts: Need help understanding how RF communication works with 2 arduinos

texts:
I have two arduinos (uno) and I would like to send the results of a key press on a 5X4 matrix pad to the other arduino. The matrix keypad works great. I can identify which key was pressed with a switch function.

switch (keypad())
//switch used to specify which button
     {
      case 0:
        Serial.print("Key A Pressed");
        Serial.print(keypad());
        messageToSend = 0;
      break;
        case 1:
        Serial.print("Key B Pressed");
        Serial.print(keypad());
        messageToSend = 1;
      break;
        case 2:
        Serial.print("Key C Pressed");
        Serial.print(keypad());
        messageToSend = 2;
      break;
       }

My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.

What is the nature of the data sent between units? I want to send
integers, possibly even text. Is that possible? Do I need to convert
to binary or something?
My understanding of "ping" and "pong" is that ping sends a message
then pong sends that same message back to ping... is this correct?
Are RF units very different? Is this one particularly difficult?
If I just want to send with one receive with the other shouldn't
this simplify the code?
What are pipes? How many can I open?
If I have 3 or more of these what changes will I need to make to the
code?

Thanks!


texts: What is the sampling-rate of the `analogRead()`?

texts:
I am about to Fourier analyse some data I've taken, but i need to know at which sampling rate the data was written to the serial monitor. I've found a lot of threads about how to increase it and such but not a single one that lays down some information about what the sampling-rate is.

My code is very simple, here it is:

      // the setup routine runs once when you press reset:
  void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
  }

  // the loop routine runs over and over again forever:
  void loop() {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
  }


texts:
I'm creating a weather station / environmental datalogger and am saving my data to a SD card Breakout. The SD card works fine but I would like to name the files I am saving on it after the date when the readings were taken.I've tryed multiple things but I can't work out how to combine the date from my RTC and put them in a file name. I've tryed this:

dataFile = SD.open(String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv",FILE_WRITE);

But this gives me an error -

char dateName[13] = {String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv"};
dataFile = SD.open(dateName,FILE_WRITE);

But this gives me this error:

 cannot convert 'StringSumHelper' to 'char' in initialization

Help! How do I do this?


texts:
I'm working on a midi device with a pro micro, it's reading as a midi device, but not outputting any notes, here's my program:
    const int button1 = 2;
    const int button2 = 3;
    const int button3 = 4;
    const int button4 = 5;
    const int button5 = 6;
    const int button6 = 7;

int note = 0;

const int c3 = 36;
const int d3 = 38;
const int e3 = 40;
const int f3 = 41;
const int g3 = 43;
const int a3 = 45;

void setup() {

  pinMode(button1,INPUT);
  pinMode(button2,INPUT);
  pinMode(button3,INPUT);
  pinMode(button4,INPUT);
  pinMode(button5,INPUT);
  pinMode(button6,INPUT);

  Serial.begin(31250);

}

void loop() {
  int button1State = digitalRead(button1);
  int button2State = digitalRead(button2);
  int button3State = digitalRead(button3);
  int button4State = digitalRead(button4);
  int button5State = digitalRead(button5);
  int button6State = digitalRead(button6);

  if (button1State == HIGH) {
    note = c3;
    noteOn(0x90, note, 0x64);
  }
  if (button1State == LOW) {
    note = c3;
    noteOn(0x90, note, 0x00);
  }

  if (button2State == HIGH) {
    note = d3;
    noteOn(0x90, note, 0x64);
  }
  if (button2State == LOW) {
    note = d3;
    noteOn(0x90, note, 0x00);
  }

  if (button3State == HIGH) {
    note = e3;
    noteOn(0x90, note, 0x64);
  }
  if (button3State == LOW ) {
    note = e3;
    noteOn(0x90, note, 0x00);
  }

  if (button4State == HIGH) {
    note = f3;
    noteOn(0x90, note, 0x64);
  }
  if (button4State == LOW) {
    note = f3;
    noteOn(0x90, note, 0x00);
  }

  if (button5State == HIGH) {
    note = g3;
    noteOn(0x90, note, 0x64);
  }
  if (button5State == LOW) {
    note = g3;
    noteOn(0x90, note, 0x00);
  }

  if (button6State == HIGH) {
    note = a3;
    noteOn(0x90, note, 0x64);
  }
  if (button6State == LOW ) {
    note = a3;
    noteOn(0x90, note, 0x00);
  }

}

void noteOn(int cmd, int pitch, int velocity) {
  Serial.write(cmd);
  Serial.write(pitch);
  Serial.write(velocity);
}


texts:
I have a project where I am using an Arduino to control a smoke machine and a strobe light using DMX (with a shield). I also use a light sensor, so that when a person pass through it, the Arduino sends a signal to activate the smoke machine.

Currently I have hardcoded both intensities in my Arduino sketch, but I want to allow the operator to control the settings of both devices, but needing to be connected to a PC.

I don't know if a potentiometer is a good option, because I would want to offer fine control to the operator (select a number in the range of 0-255).

How can I do that? What user interface system can I use?


texts:
How do I start this program???

int x=0;
int P1=A5;
int P2=A4;
int P3=A3;
int R1=3;
int G1=5;
int B1=6;
int R2=9;
int G2=10;
int B2=11;
int sValue1;
int sValue2;
int sValue3;
int oValue1;
int oValue2;
int oValue3;
int timer(1000);

void setup() {
 pinMode(P1,INPUT);
 pinMode(P2,INPUT);
 pinMode(P3,INPUT);
 pinMode(R1,OUTPUT);
 pinMode(G1,OUTPUT);
 pinMode(B1,OUTPUT);
 pinMode(R2,OUTPUT);
 pinMode(G2,OUTPUT);
 pinMode(B2,OUTPUT);

}

void loop() {

sValue1=analogRead(P1);
sValue2=analogRead(P2);
sValue3=analogRead(P3);

oValue1=map(sValue1,0,1023,0,255);
oValue2=map(sValue2,0,1023,0,255);
oValue3=map(sValue3,0,1023,0,255);

if ((sValue1=0)&&(sValue2=0)&&(sValue3=0));
{
  setColor1(0,255,255);
  delay(timer);
  setColor2(255,0,0);
}
}

void setColor1(int red1, int green1, int blue1){
  {
    analogWrite(R1,red1);
    analogWrite(G1,green1);
    analogWrite(B1,blue1);
  }
}

void setColor2(int red2, int green2, int blue2){
  {
    analogWrite(R2,red2);
    analogWrite(G2,green2);
    analogWrite(B2,blue2);

  }
}


texts: Programming AT24C16 EEPROM with Arduino Nano

texts:
I have been trying to program an AT24C16 EEPROM and have set up a circuit as per the attached image.

I have been using the following Arduino code:
#include <Wire.h>

#define disk1 0x50    //Address of 24LC256 eeprom chip

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

  unsigned int address = 10;

  writeEEPROM(disk1, address, 72);
  Serial.println(readEEPROM(disk1, address), DEC);
}

void loop(){}

void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data )
{
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(data);
  Serial.println(Wire.endTransmission());

  delay(5);
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{
  byte rdata = 0xFF;

  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Serial.println(Wire.endTransmission());

  Wire.requestFrom(deviceaddress,1);

  if (Wire.available()) rdata = Wire.read();

  return rdata;
}

Unfortunately I only ever receive '255' in the serial monitor suggesting that no data has been written.
The code was from this tutorial which explains how the wiring on pins 1-3 governs the address of the chip.


texts: Industry Standard for Single-Board Computers?

texts: Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor? I'm trying to sell management on using Arduino, but they are stuck on the question "what if Arduino goes out of business", and if I could answer "we can just switch over to using brand X because it's the same size and has the same connectors", my life would be much easier.


texts: What is the meaning of "volatile bool mpuInterrupt = false; " in Arduino Program interfacing MPU6050?


texts: Should a delay be expected to cause deadlock?

texts:
I have made a simple program using the int main() {} function. It has a delay in it. It is evident the code before the delay is running, but the delay never seems to time out and let the next instructions through. Is this by design?

If I rename the method and call it exactly once from the loop() {} function though, it does work.

Edit:

The code borrowed the 'main()' function and I suppose redefined it:

int main() {
    Forward();
    delay(3000);
    Reverse();
}

void Forward() {
    //...
}

void Reverse() {
    //...
}

I can see this redefinition of main() could cause some serious issues based on the answer below.


texts: Modbus TCP together with MQTT over same ethernet

texts:
I'm currently in a planning phase for a project.
I want to read some sensor data over Modbus TCP, do some simple calculations on the Arduino and publish the results over MQTT. Which means I have 2 RJ-45s and two different protocols.
Given a Arduino Mega with an Ethernet shield.
Does it work if I simply add a network switch and connect the sensor and an internet router to it, and use both protocols in parallel?
Or are there any problems running such a thing on only one Arduino?


texts:
I'm having problems with my setup.
I'm trying to create a wind-speed system when you send an SMS to retrieve the correct wind speed as an SMS response.
I'm using a pro mini, connected by USB via FTDI, and a SIM808 module.
The SIM808 is connected to a mains supply and the LED status suggests it is connected to the network.
The SIM808 pins are as follows:
TX > Pin 9
RX > Pin 10
VMCU V IN > Power supply +
GND (the one under VMCU) > Power supply -
GND (under Li-on) > GND on the Arduino

I've tried lots of source code examples but nothing much seems to happen, this is the latest code I'm testing (the top part of the loop at least). In the serial monitor, it reports back the "Sim808 init error" over and over.
include <DFRobot_sim808.h>
include <SoftwareSerial.h>
define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;
char MESSAGE[300];
char lat[12];
char lon[12];
char wspeed[12];

char phone[16];
char datetime[24];

define PIN_TX 9
define PIN_RX 10
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

void sendSMS(); void getGPS(); void readSMS();

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

//******** Initialize sim808 module *************
while(!sim808.init()) {
  Serial.print("Sim808 init error\r\n");
  delay(1000);
}
delay(3000);

Serial.println("SIM Init success");

I hope someone can help as I've spent ages on this and had no luck.


texts: Is AREF a stable output Ref voltage with analogReference(INTERNAL)

texts:
I'm using an analog input on a NANO board to measure the midpoint between two photo resistive (Cadmium) cells, with the two outside ends tied to GND and a source voltage. Basically a simple voltage divider. So it almost wouldn't matter what reference voltage I used in a case like that, as long as the AnalogReference() was correctly set corresponding to the reference voltage, AND the load did not pull down that voltage.

Well if I used the 5V for my source, and set AnalogReference(DEFAULT), then assuming a worst case load of 4K-ohm, the total load on the 5V regulator is still only 1.25mA. But even so, I figured I could minimize the system load even more by setting AnalogReference(INTERNAL), and using the VREF pin as a source for my voltage divider.

Well it seems to work fine, but I don't know that I've seen any actual examples of what I'm doing, which is using the AREF pin as a source output voltage for my voltage divider. Using vREF as a source, a 4K load would only draw 27.5 microamps with a 1.1V source. But I can't find any spec for the max current I should avoid exceeding, That has me worried maybe I'm not even supposed to be doing that!

So is it acceptable to use the VREF pin as an output for light loads, when using the INTERNAL AnalogReference?

Thoughts?

EDIT: After receiving a "no" answer yesterday, I did some bench checking. I configured my NANO board for Internal, and connected a fully open 100K linear pot from AREF to Ground, with a DVM in parallel. The AREF terminal output was about 1.076, with or without the 100K load. Not quite the 1.1 specified but close enough. I then slowly rotated the pot to increase load. At just under 9K the voltage dropped a somewhat insignificant amount, to 1.075. From there on there were additional small decreases, down to about 1K, at which point i measured about 1.062V. Below 1K, there was a very steep decrease.

Note that this was a "quickie" test, done while powering the NANO from a USB port. However, repeating the test with 12V on the DV input did not alter the results significantly.

Even considering the USB source, from this test I conclude:

1) There does appear to be some buffering on the VREF output. It certainly did not behave as there was a simple case of a 1.1V source in series with a high impedance.

2) Up to a load of 10K, the VREF output seems at least as stable as the 5.0V regulator output.

3) Since a 1.062 drop from an initial no-load voltage of 1.076 equates to less than a 2% difference, I have to conclude that a load on VREF (to ground) greater than 1K (lets say 2K for margin) makes VREF probably useful in cases like i described, with a worst case load of 4K.

4) I repeated my test with a second NANO board. This time the initial no-load voltage was salightly higher, 1.084. However, the response to increasing load and the K point where the slope changed dramatically were unchanged.

Again, this is an arduino NANO board, and probably a clone. Can anyone else verify or disprove my results? I'm sure someone else will need to consider using VREF as I did, and it would be good to know.