texts: Nextion Display not getting updated data

texts:
I am using an Arduino Mega to display the readings of 4 pots on a Nextion Display as well as store it in an SD Card with the time stamp. I keep getting:
recvRetCommandFinished err
on the serial monitor and the display does not update with time.
I have attached my code below:
#include "Nextion.h"
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;
char daysOfTheWeek[7][12] = {"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

// Declare your Nextion objects - Example (page id = 0, component id = 1, component name = "b0")
NexText tDate = NexText(0, 1, "tDate");
NexText tPot1 = NexText(0, 6, "tPot1");
NexText tPot2 = NexText(0,7, "tPot2");
NexText tPot3 = NexText(0, 8, "tPot3");
NexText tPot4 = NexText(0, 9, "tPot4");

File myFile;

void setup(void) {
  Serial1.begin(9600);
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    //rtc.adjust(DateTime(2016, 11, 19, 19, 45, 0));   // <----------------------SET TIME AND DATE: YYYY,MM,DD,HH,MM,SS
  }

  delay(100);

  // You might need to change NexConfig.h file in your ITEADLIB_Arduino_Nextion folder
  // Set the baudrate which is for debug and communicate with Nextion screen
  nexInit();

  SPI.begin();

  int pot1 = 0;
  int pot2 = 0;
  int pot3 = 0;
  int pot4 = 0;

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

  Serial.print("Initializing SD card...");
  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
}

void loop(void) {
  myFile = SD.open("testpot1.csv", FILE_WRITE);
  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to testpot1.txt...");

    while(1) {
      DateTime now = rtc.now();
      myFile = SD.open("testpot1.csv ", FILE_WRITE);
      int pot1 = analogRead(A0);
      int pot2 = analogRead(A1);
      int pot3 = analogRead(A2);
      int pot4 = analogRead(A3);
      myFile.print(now.hour());
      myFile.print(":");
      myFile.print(now.minute());
      myFile.print(",");

      myFile.println(pot1);
      myFile.println(",");
      tPot1.setText(pot1);

      myFile.println(pot2);
      myFile.println(",");
      tPot2.setText(pot2);

      myFile.println(pot3);
      myFile.println(",");
      tPot3.setText(pot3);

      myFile.println(pot4);
      myFile.println(",");
      tPot4.setText(pot4);

      Serial.print(pot1);
      Serial.print(",");
      Serial.print(pot2);
      Serial.print(",");
      Serial.print(pot3);
      Serial.print(",");
      Serial.print(pot4);
      Serial.print(",");

      delay(2000);
      myFile.close();
    }
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

How do I get the pot values on my display? Any help or tips would be helpful!


texts: I'm using 4.7kOhm resistor as pullups for GPIOs 2,0,2,16, CH_PD and RESET, and also 4.7kOhm pulldown for GPIO 15. The ESP8266 boots and works fine. Would it be okay for a long shot? Should I use 10kOhm instead of 4.7kOhm?


texts: [Solved]How to make my stepper motor run clockwise and counterclockwise?

texts:
I'm relatively new to Arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

I am using AccelStepper Library

Here is my code:

#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
}

I have tried to add delay and counterclockwise code but its not working.

#include <AccelStepper.h>
//Define stepper motor connections
#define dirPin 4
#define stepPin 14
//Create stepper object
AccelStepper stepper(1,stepPin,dirPin); //motor interface type must be set to 1 when using a driver.
void setup()
{
  stepper.setMaxSpeed(1200); //maximum steps per second
}
void loop()
{
  Serial.println("clockwise");
  stepper.setSpeed(1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
  Serial.println("counterclockwise");
  stepper.setSpeed(-1200); //steps per second
  stepper.runSpeed(); //step the motor with constant speed as set by setSpeed()
  delay(1000);
}


texts:
this is the code i am working on for controlling leds

#include <WiFi.h>                                                // esp32 library
#include <IOXhop_FirebaseESP32.h>                                             // firebase library
#define FIREBASE_HOST "mmmmm"                         // the project name address from firebase id
#define FIREBASE_AUTH "mmmmmmm"                    // the secret key generated from firebase
#define WIFI_SSID "mmmmm"                                          // input your home or public wifi name
#define WIFI_PASSWORD "mmmmmm"                                    //password of wifi ssid

String fireStatus ;
String fireStatus1 ;
String fireStatus3 ;
String fireStatus4 ; // led status received from firebase
int relay1 = 15;
int relay2 = 2;
int relay3 = 4;
int relay4 = 5;

void setup() {

Serial.begin(115200);

pinMode(15, OUTPUT);
pinMode(2, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);                                      //try to connect with wifi
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
      Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
  Serial.print("IP Address is : ");
  Serial.println(WiFi.localIP());                                                      //print local IP address
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                                       // connect to firebase

}
void loop() {

  {
    fireStatus =  Firebase.getString("S1");

    Serial.println("Switch1 Turned ON/OFF");
    digitalWrite(15,fireStatus );
    fireStatus1 =  Firebase.getString("S2");
     Serial.println("Switch2 Turned ON/OFF");
    digitalWrite(2,fireStatus1 );

     fireStatus3 =  Firebase.getString("S3");
     Serial.println("Switch3 Turned ON/OFF");
    digitalWrite(4,fireStatus3));

     fireStatus4 =  Firebase.getString("S4");

     Serial.println("Switch4 Turned ON/OFF");
    digitalWrite(5,fireStatus4 );

}
}


texts:
I am connected with my ESP-12 through a programmer and all the AT functions work correctly. However I do not get a connection when connecting to the ESP8266 module.

I have done the following:

Set the mode both: AT+CWMODE=3

Connect to an Access Point: AT+CWJAP="<name>","<password>" (Responds with WIFI Connected and WIFI Got IP)

Set the Access Point: AT+CWSAP = "<other_name>","<password>",<channel>,<password_security>

So at this time it should be connected to my local network and I can connect to it through wifi on my laptop. However when I connect to it, it says 'Connected, No Internet' (The network the esp8266 module is connected to, has internet).

When I troubleshoot problems it says DNS is not responding.

Does anyone have a clue what to do next? Or what I might do wrong?


texts: How to change IIC (I2C) clock rate on MKR1000

texts:
The IIC clock defaults to 100kb, need to increase it to ~200kb.

I've tried:

changing the constant TWI_CLOCK and rebuilding Wire.cpp
calling initMasterWIRE(200000) after Wire.begin().

I'm using a scope to verify the change, and thus far can't seen a change in the clock width.

I believe the pull resistors are 10k?  Might need to decrease a bit to.

Looking for a very short example!
TIA.


texts:
We are students of Pragati Engineering College -AP. We are currently working on Automatic Street Light  project selected in Smart India Hackathon 2017 under ministry of steel. For this project  We are using Arduino nano to control street lights in industries. Now we are requiring some general following  information about arduino nano.

What is the life span of Arduino nano?
We need a micro-controller with on analog input pin to read analog voltage and four digital pins for output. The program that we are dumping include  serial communication with Java UI in PC. The program occupies 6750 bytes, 318 bytes for global variables and 1730 bytes for local variables. We would like to know which arduino board is best suitable for our project?


texts:
We are currently deploying units with the ATMEGA328 chip. Currently, all ICs have been flashed using the Arduino IDE. Upon release, we would like to offer updating of firmware in some cases, but obviously we would not want to send them the source code and let them download the arduino IDE.

We would like to send a firmware file, and an .exe file like a firmware upgrader, as most companies do. How would I start to go about this?


texts: Can I program a 3.3v chip on a 5v board?

texts:
I bought a Gertboard a while ago, and one of the features it has on-board is an ATMega328 (DIP). However, since the Gertboard is designed for use with the Raspberry Pi, it only operates at 3.3v, so the clock speed is limited to ~12MHz.

Programming it via the Raspberry Pi is quite cumbersome though. Instead, I'd like to transfer the chip to an Arduino Uno board so I can upload sketches from my desktop PC. I would then transfer it back to the Gertboard for normal operation.

The problem is that my Uno operates at the more typical 5v / 16MHz.

Is it safe to attempt this? Do I need to make any configuration changes in the IDE to tell it to account for a different clock speed?


texts: Communicating to arduino as fast as real-time

texts:
I'm trying to control some pneumatic cylinders with arduino. I want to do the calculations on pc and then send the command to arduino to control the air flow to pneumatic cylinders. It's very important that arduino receive these commands super fast (in real time if it's possible) so that I can control air flow in millisecond precision.

What is the fastest way to communicate to arduino (Read and write). I tested serial communication and it's very slow in compare to real-time. Is there any specific settings for serial communications that i need to do to increase it's speed? Should I use LAN connection? Or maybe I should use for example Arduino YUN with an OS?


texts: Generating a PWM frequency greater than 125 kHz using Arduino Uno

texts:
I need to obtain a PWM frequency of at least 125 kHz. I plan to drive a pair of MOSFETs using this PWM as the driver signal. The below code gives a 1 kHz frequency. Can I just change the delay values to obtain a lower time period, and thereby a higher frequency?

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

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);  // Can I change the delay to 1 and 9 for a totaL T=10 µsec and hence f = 100 kHz?
  delayMicroseconds(900);
}

Update

On looking up the answers provided, I stumbled across a few tutorials. I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation). But the code was supposed to provide 250 kHz and 8 MHz.

My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.

Second sketch:

// A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
// 6-bit resolution PWM with varying duty cycle (changes every 5µs
// or about every period.

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  pinMode(3, OUTPUT); // Output pin for OCR2B
  pinMode(5, OUTPUT); // Output pin for OCR0B

  // Set up the 250 kHz output (but cro measures only 125 kHz)
   TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
   TCCR2B = _BV(WGM22) | _BV(CS20);
   OCR2A = 63;
   OCR2B = 0;

  // Set up the 8 MHz output
   TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
   TCCR0B = _BV(WGM02) | _BV(CS00);
   OCR0A = 1;
   OCR0B = 0;

  // Make the 250 kHz rolling
  while (1) {
    _delay_us(5);
    if (OCR2B < 63)
      OCR2B += 5;
    else
      OCR2B = 0;
  }
}


texts: Multiple peripherals using SPI with a Mega

texts:
I am using a Mega 2560 and 2 x AD9833 programmable waveform generators.
The AD9833's use a SPI protocol and I have used vwlowen's code as a jumping off point (I'm not usng the display just the generators). I added a channel variable to select the slave device.
It all works fine until I try to add a second AD9833. I saw this post about more than 1 peripheral using SPI & a Mega, that says I can use any pin for slave selection (SS) but the following code only ever works if I use pin 53. The upshot if which is that I can send the same data to both i.e. both share the same SS pin as long as that pin is 53. Any other SS pin selection is ignored by the devices. I tried pin 49 for both & no change, I''ve tried 53 & 49 yet only the device on 53 changes.
So what's going on here? What's so special about pin 53 that it cant be replicated by another output pin?
/*
Amended code for AD9833 Waveform Module originally from vwlowen.co.uk
Common SPI terminology & pinout on AD9833
MOSI - DATA
SCLK - CLK
SS   - FSYNC
MISO - not implemented i.e. ther is no MISO pin on the AS9833
*/

#include <SPI.h>

const int SINE     = 0x2000;                // Define AD9833's waveform register value.
const int SQUARE   = 0x2028;                // When we update the frequency, we need to
const int TRIANGLE = 0x2002;                // define the waveform when we end writing.

const float refFreq = 25000000.0;           // On-board crystal reference frequency

const int FSYNCA = 53;                       // Standard SPI pins for the AD9833 waveform generator.
//const int FSYNCB = 49;
const int CLK    = 52;                       // CLK and DATA pins.
const int DATA   = 51;

unsigned long freq = 1000;                   // Set initial frequency.

void setup() {

  pinMode(FSYNCA, OUTPUT);
  // pinMode(FSYNCB, OUTPUT);

  SPI.begin();
  SPI.setDataMode(SPI_MODE2);
  delay(50);

  AD9833reset();                                   // Reset AD9833 module after power-up.
  delay(50);
  AD9833setFrequency(freq, SQUARE, FSYNCA);        // Set the frequency and Sine Wave output
 // AD9833setFrequency(freq, SINE, FSYNCB);

}

void loop() {

// TODO: PC control via USB

}

// AD9833 documentation advises a 'Reset' on first applying power.
void AD9833reset() {
  WriteRegister(0x100, FSYNCA);   // Write '1' to AD9833 Control register bit D8.
  delay(10);
 // WriteRegister(0x100, FSYNCB);
 // delay(10);
}

// Set the frequency and waveform registers in the AD9833.
void AD9833setFrequency(long frequency, int Waveform, int channel) {

  long FreqWord = (frequency * pow(2, 28)) / refFreq;

  int MSB = (int)((FreqWord & 0xFFFC000) >> 14);    //Only lower 14 bits are used for data
  int LSB = (int)(FreqWord & 0x3FFF);

  //Set control bits 15 ande 14 to 0 and 1, respectively, for frequency register 0
  LSB |= 0x4000;
  MSB |= 0x4000;

  WriteRegister(0x2100, channel);
  WriteRegister(LSB, channel);                  // Write lower 16 bits to AD9833 registers
  WriteRegister(MSB, channel);                  // Write upper 16 bits to AD9833 registers.
  WriteRegister(0xC000, channel);               // Phase register
  WriteRegister(Waveform, channel);             // Exit & Reset to SINE, SQUARE or TRIANGLE

}

void WriteRegister(int dat, int channel) {

  digitalWrite(channel, LOW);         // Set FSYNC low before writing to AD9833 registers
  delayMicroseconds(10);              // Give AD9833 time to get ready to receive data.

  SPI.transfer(highByte(dat));        // Each AD9833 register is 32 bits wide and each 16
  SPI.transfer(lowByte(dat));         // bits has to be transferred as 2 x 8-bit bytes.

  digitalWrite(channel, HIGH);        //Write done. Set FSYNC high
}


texts: How to Store the Value of A Sr04 Ultrasonic distance sensor (ping)?

texts: I am using a Sr04 Ultrasonic distance sensor with Uno clone for making a Alarm. The basic idea behind this project is that In Setup, Read the distance And store it in a varibale as Threshold. And in Loop, Check the distance readings regularly and if the Reading anytime is not equal to The threshold (that means someone interrupted in front of ultrasonic sensor), then a led flashes. I Know that is system is not enough good because the real world is a bit noisy. My problem is I am storing the theshold distance in "int" variable. The compiling error is "Cant convert Long Unsigned char to Int" something like this. Please tell me how can I store the reading of my sr04 sensor in a variable. I am using NewPing Library.


texts: IR signal: different libs, different bit/byte ordering?

texts:
For IR sender at Nano Every (ATMega4809-based) I am using infrared4arduino to send simple remote control codes. I am double-checking those with a Nano-based receiver with IRrecvDumpV2 example from IRremote library but I am receiving something else what I am sending (I think):

The sender has the following code using Infrared4Arduino:

   IrSignal* sig=Nec1Renderer::newIrSignal(0,0x906f); // cmd 0x90
   IrSenderPwm::getInstance(true)->sendIrSignal(*sig,1);

but the receiver dumps (besides some garbage like 0-bit JVC and SANYO frames):

Encoding  : NEC
Code      : FFF609 (32 bits)
unsigned int  data = 0xFFF609;

0x00 and 0xff (first 2 bytes of the "packet") are device and its logical complement, those are fine.

The command sent as 0x90 (followed by its logical complement 0x6f) is decoded as 0xF6 (plus its logical complement 0x09). Why? Is it an accident that 906f is f609 backwards?

What's going on here?

I will try to run both sender and receiver with the same lib (IRremote is not ported to Nano Every) but before I go ahead, better ask. Perhaps I am only doing some IR-beginner's mistake.


texts:
I am broadcasting a fixed value float over a HC-12 radio which is then received by another HC-12 radio. I am then trying to convert that String to a Float which requires 6 decimal places. However, when I print the String value out and then the Float value out, I get two different answers.
Code:
    String lat=getValue(_msg, '|', 6); // Function to get lat value from incoming message
    Serial.println(lat);
    Serial.println(lat.toFloat(), 6);

This then results in the following values being displayed to the user:
51.507401
51.507396

The value 51.507401 is the correct value, so I would ideally like the float value to be the same.


texts: Using Arduino, how can I detect that the switch is on? I have access to the wire within the red rectangle only. That's because the switch is closely connected to the car body (ground). When the handbrake is up, the switch is pushed by a coil to touch car body and close the circuit. And when the handbrake is down, the switch go away from the car body and the circuit is open.


texts: How to control one Mosfet with another mosfet

texts: I've got 4x 12V 6a peltiers and some 3d printer mosfet controllers to drive them using PWM with my arduino. But I've found the mosfets need ~7V to switch on, so I'm now wanting to control them with some logic level ones I had around. I could just use the logic ones directly to the peltiers, but am finding it difficult to make my stripboard capable of handling 24A (this page seems to say I need tracks/wire of 2.3+mm diameter which I don't have). Hence I'm trying to make a circuit for the arduino to use the logic mosfets to control the 3d printer mosfets but can't quite get my head around how to do it. I think I'm missing a power source for the first mosfet - do I need to have a whole separate DC power supply for this to the peltiers? Very grateful for a bit of help please!


texts:
I'm developing a bridge, or man in the middle for touch controller and a system board connected with I2C.  The connection is:

Touch Controller(slave)---I2C---(master)STM32(slave)---I2C---(master)ARM Board

The original i2c cable is cut in half and STM32 is sitting in the middle.

The point it letting common communication through and just sometimes after an external trigger injecting a click event. (It's for automated testing.) The TC is the only I2C device on the bus.

Have someone done something similar?

The protocol is simple. The ARM board writes two bytes address.Then reads several(3-259) bytes.

I'm trying to request data from TC after receiveEvent() from master, but I don't know how many bytes shall I request. It also takes time for the answer.

Any ideas?


texts: Reading Reveive Hold Register from USART in SPI Mode on Arduino Due

texts:
Sending with this function here works fine:

uint16_t usart0spiTransfer16(uint16_t spiMessage16) {
    uint16_t sdo = 0;
    byte firstByte = spiMessage16;
    byte secondByte = (spiMessage16 >> 8);
    while (((USART0->US_CSR  >> 1) & 1) == 0);
    digitalWrite(SS, LOW);
    USART0->US_THR = secondByte;                //write to USARTO Transmit Hold Register

    //this byte is returned twice
    secondByte = USART0->US_RHR;                //read from USART0 Receive Hold Register
    while (((USART0->US_CSR  >> 1) & 1) == 0);  //TXRDY: Transmitter Ready
    USART0->US_THR = firstByte;

    //trying to read a second time gives me the same value as before
    firstByte = USART0->US_RHR;

    while (((USART0->US_CSR  >> 9) & 1) == 0);
    digitalWrite(SS, HIGH);

    sdo = (firstByte << 8 ) | (secondByte & 0xFF);
    return sdo;
}

and when i wait for RXRDY after secondByte = USART0->US_RHR; with while (((USART0->US_CSR  >> 0) & 1) == 0); i will stay there forever since it does not change

how do i read the registers value for the second time?


texts: Communication between arduino nano and MCP3424 over I2c pt. 2

texts:
I'm am completing a project of mine that uses an MCP3424 i2c 18bit ADC and an arduino nano to measure temperature with an NTC thermistor but am having trouble with the arduino wire library. This is my first project using i2c so I'm not very knowledgeable about the subject but I have rigorously read the datasheet of the MCP3424 that can be found at (http://ww1.microchip.com/downloads/en/devicedoc/22088b.pdf) and tried many different ways to get it working. Also I'm new to posting on this stackexchange so pardon me if my syntax and what not is not right(I'm doing my best). Here is the code I have so far that is on my arduino.

#include<Wire.h>
//#include<LiquidCrystal.h>
//LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

#define MCP 0x6E //Device will output conversion data (7 bits, device address. 1 bit, Read/Write mode)
#define CH1 0x8c //PGA = 1, SPS = 3.75, One-Shot mode, channel 1, initiate new conversion.
#define CH2 0xac //channel 2
#define CH3 0xcc //channel 3
#define CH4 0xec //channel 4

void setup() {
  Serial.begin(9600);//Initiate Connection to computer
  //lcd.begin(16, 2); not used yet
  Wire.begin();//Initiate Wire library
}

void loop() {
  // Read data from
  int pins[] = {CH1, CH2, CH3, CH4};
  long results[] = {0, 0, 0, 0};
  for (int i = 0; i < 4 ; i++) {
    results[i] = ReadMCP(pins[i]);
    Serial.print(i+1);
    Serial.print(": ");
    Serial.print(ReadMCP(pins[i]));
    Serial.print(" ");
    delay(500);
  }
  Serial.print("\n");

}
long ReadMCP(int channel){
  //conversion takes the three bytes and converts to number between 0 and 131071
  int x, y, z;
  long result = 0;

  Wire.beginTransmission(MCP);//begin transmission with ADC in Write mode
  Wire.write(channel);//configure the ADC with settings found in either CH1, 2, 3 or 4
  Wire.endTransmission();
  //delay(500);
  Wire.requestFrom(MCP, 3);//request 6 Bytes of information from MCP3424
  x = Wire.read();//read bytes
  y = Wire.read();
  z = Wire.read();

  if (x>1) {
    if (x%2){
      result += (1 * 65536L);//x * 65536 = x * 2^16
      result += (y * 256L);//y * 256 = y * 2^8
      result += z;
      result = -131072 + result;
    }else{
      result += (y * 256L);//y * 256 = y * 2^8
      result += z;
      result = -131072 + result;
    }

  } else {
    result += (x * 65536L);//x * 65536 = x * 2^16
    result += (y * 256L);//y * 256 = y * 2^8
    result += z;
  }
  return result;
}

My program reads the measurements from each of the 4 channels of the ADC and prints them in the serial monitor.

The issue I am having is that when this code is run without the "delay(500);" function in the ReadMCP() function my measurements from each channel of the MCP3424 are in the wrong place. It prints the measurement from channel 1 as channel 2, the measurement from channel 4 as channel 1 and etc. However, with the delay between endTransmission() and requestFrom() the values are in the correct place. I have looked all over the datasheet and experimented a lot with the issue but cannot see what is causing it. Does anyone know why?

For reference when I have something to measure attached to channel 2 the output without the delay is

1: 131071 2: 131071 3: 66891 4: 131071

and with the delay is

1: 131071 2: 66843 3: 131071 4: 131071


texts:
I'm trying to track down a clearly/simply articulated piece of code to take a reading from the ACS712 current sensor (link to download PDF data sheet).

I understand that these sensors are noisy, and that reading AC current is quite different to DC current.

After looking at a range of examples in a variety of forums etc., I've based the following on http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/

void ac_read() {
  int rVal = 0;
  int maxVal = 0;
  int minVal = 1023;
  int sampleDuration = 100; // 100ms

  uint32_t startTime = millis();
  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0);
    if (rVal > maxVal)
      maxVal = rVal;

    if (rVal < minVal)
      minVal = rVal;
  }

  // Subtract min from max to determine the peak to peak range
  // 1023 = the max value we'll get on the input (1024, zero indexed)
  // 5.0 = 5v total on adc input
  double volt = ((maxVal - minVal) * (5.0/1023.0));

  // div by 2 is to calculate RMS from peak to peak
  // 0.35355 is factor to calculate RMS from peak to peak
  // see http://www.learningaboutelectronics.com/Articles/Voltage-rms-calculator.php
  double voltRMS = volt * 0.35355;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = voltRMS
  double ampsRMS = (voltRMS * 1000)/100;
  Serial.println(ampsRMS);
}

I unfortunately don't have sufficient test equipment at present to validate this, but I'm getting a value of around 8.9 for a 2300W device, which afaict is roughly accurate (based on this calculator http://www.rapidtables.com/calc/electric/Watt_to_Amp_Calculator.htm).

Is anyone able to confirm the above makes sense/is logical/sane?  Is there anything obviously incorrect?


texts: Why can't I use Jeelib Sleepy on the Teensy 2 along with Serial

texts:
I have been using the Jeelib Sleepy functionality for several years now to achieve low power states on the Arduino ATmega328/1280/2560 boards, specifically the LoseSomeTime functionality.

I want to get my Teensy 2 to go into a similar low power state, so I tried a very simple sketch that simply put the device to sleep, flashed an LED, and posted some Serial messages. I did need to comment out a few lines in Jeelib:

// adjust the milli ticks, since we will have missed several
#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny85__) || defined (__AVR_ATtiny44__) || defined (__AVR_ATtiny45__)
    extern volatile unsigned long millis_timer_millis;
    millis_timer_millis += msecs - msleft;
#else
    extern volatile unsigned long timer0_millis;
    timer0_millis += msecs - msleft;
#endif

This had to be done as the delay() and millis() functions on the Teensy use different variable names for the adjustment, and it was the quickest way of solving the problem. LoseSomeTime works on the ATmega328 hardware with this change.

I found that although the LoseSomeTime function did sleep for a period, the Serial functionality stopped working entirely - no messages were being printed at all. I have encountered this before on ATmega328 hardware because the microcontroller has gone to sleep before the serial buffer was flushed. I added a number of delay()s after the Serial.writes and also tried using Serial.flush() to make sure the buffer was empty.

LoseSomeTime requires setting an interrupt on the watchdog timer, but I can't see how this would impact Serial operation.


texts:
I have a standard 16x2 LCD screen and I have it hooked up to my Arduino UNO via a I2C backpack (4-bit mode).

Since I want to learn about the lcd at a lower level I’ve decided not to use the LCD library and instead use the Wire library.

I have writing to the LCD working fine so now I want to understand how to read from it. I thought trying to read the busy flag was a good start.  (I currently delay() after to the LCD which seems to be the most popular solution).

According to the LCD documentation it requires that the RS bit be set to 0 and RW bit to 1. I have a attached the code below.  For some reason it always reads 0x2.

I also read the busy flag right after writing to the screen and it always screws up every other letter.  E.g. if I write 'k' twice to the screen, the first 'k' shows up fine, but the second time it becomes a 'f'.  I am suspecting writing to the LCD before reading is screwing up the data processing.  If I don't attempt to read the flag, all the characters show up correctly.

Here is the code.  Any help would be appreciated.  Thank you!

#define ENABLE (1 << 2)
#define BACKLIGHT (1 << 3)

#define READ (1 << 1)

byte readReq = BACKLIGHT | ENABLE | READ;
Wire.beginTransmission(0x3F);
Wire.write(readReq);
Wire.write(readReq & ~ENABLE);// write 1st nibble
Wire.write(readReq);
Wire.write(readReq & ~ENABLE); //write 2nd nibble

Wire.endTransmission();

Wire.requestFrom(0x3F, 2);

while (Wire.available() < 2) {}

byte firstNibble = Wire.read(); //always reads 0x2
byte secondNibble = Wire.read(); //always reads 0x2
Serial.println(firstNibble, HEX);
Serial.println(secondNibble, HEX);


texts:
I want to introduce a boolean that is the first iteration of loop and then false
every subsequent iteration. I want it invisible, so I have to modify loop in some way. Is that possible?


texts:
So I recently purchased:

DFRobot Wheel Encoders

DFRobot 3PA and 4WD Rovers (2pk)

Romeo V2 Arduino Controller

I was doing a bit of research online and I'm trying to figure out how to use the encoders to control the PWM applied to the motors which will make precise turns. This seems like a popular method to use. Here is some of my code. I have nothing for the encoders yet. I only have the sensors working the PWM control for the motors. All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn. Does anyone have some sample code or tips on how to do this? Thanks in advanced!

  void stop(void)
    {
      digitalWrite(5,LOW);
      digitalWrite(6,LOW);

    }
    void forward(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,HIGH);
      analogWrite(6,b);
      digitalWrite(7,HIGH);

    }
    void back(char a,char b)
    {
      analogWrite(5,a);
      digitalWrite(4,LOW);
      analogWrite(6,b);
      digitalWrite(7,LOW);

    }
    void Left(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,LOW);
      analogWrite (6,b);
      digitalWrite(7,HIGH);

    }
    void Right(char a,char b)
    {
      analogWrite (5,a);
      digitalWrite(4,HIGH);
      analogWrite (6,b);
      digitalWrite(7,LOW);

    }
    void setup(void)
    {

      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);
      for(int i =4;i<=7;i++)
        pinMode(i, OUTPUT);
      pinMode(LED_BUILTIN, OUTPUT);
     forward(100,100);

      Serial.begin(9600);

    }
void GetSensor()
{

  Sen_Val_B = SenAvg(Sensor_Back);
  Sen_Val_F = SenAvg(Sensor_Front);
  Sen_Val_R = SenAvg(Sensor_Right);
  Sen_Val_L = SenAvg(Sensor_Left);

}

int SenAvg(int SensorNumber)
{

  Arr[100]= 0;
  avg = 0;

  for(int i = 0; i<100; i++)
  {
    Arr[i] = analogRead(SensorNumber);
    avg = avg + Arr[i];
  }
    avg = avg/100;
    return avg;
}
void loop(void)
{

   GetSensor();
  if(Sen_Val_F > 200)
  {
   stop();
  }

}


texts: I want to use a Catalex Micro SD Card Adapter in Combination with my Arduino MKR GSM 1400. The problem is, that the Arduino uses 3.3V to operate but the SD Adapter needs 5V (or at least 4.5V) to operate properly. Can I just use the 5V output of my Arduino to power the adapter, or will a higher voltage destroy the arduino when using it over a longer period of time? And if so, how can I use my MKR GSM 1400 with a SD-module? Maybe by unsing a step up/down converter in my circuit or just switch to a module that uses 3.3V?


texts:
I have an ESP8266 module attached to an Arduino Uno that is connected to my local network. On the network, at address 192.168.1.13, I have a nodejs/express server running on port 3000. How would I go about posting an eight digit number from the Arduino to the webserver? In my current attempts the server console isn't receiving any data when using AT+CIPSEND while connected to it.

EDIT: My Code is as follows:

     #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
  Serial.println("Sending an AT command...");
  ESP8266.println("AT+CWMODE=1");
  delay(1000);
  ESP8266.println("AT+CWJAP=\"username\",\"pass\"");
  delay(10000);
  ESP8266.println("AT+CIPMODE=1");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");
  delay(1000);
  GetData();

}
void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}
void GetData(){
  ESP8266.println("AT+CIPSEND=4");
  ESP8266.print("test");
}

and My output is this

  Sending an AT command...
Got reponse from ESP8266: AT+CWMODE=1

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CWJAP="surveillancevan4","7073199495"

Got reponse from ESP8266: AT+CIPSEND=4

Got reponse from ESP8266: testI

EDIT 2: I modified my code to this

    #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266
// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  ESP8266.println("AT");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\",3000");
  delay(20000);
  String request = "POST /test HTTP/1.0 \r\n";
  ESP8266.println("AT+CIPSEND=19");
  delay(5000);
  ESP8266.println(request);

}

void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

and now my output claims it posted successfully, but I'm still not seeing any data in my nodejs server. Here is the output:
Got reponse from ESP8266:

AT

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CIPSTART="TCP","192.168.1.13",3000

Got reponse from ESP8266: CONNECT

Got reponse from ESP8266:

Got reponse from ESP8266: O

Got reponse from ESP8266: busy sytes

Got reponse from ESP8266:

Got reponse from ESP8266: SEND OK

I can confirm that it is connecting to my web app because when I run the code on the module without the server running it returns an error.


texts: attiny85 and arduino - analogRead + pwmOut

texts:
I am using the Arduino IDE to program the attiny85. I want to take an incoming analog reading, then based on that reading, output a specific PWM value. Here's my circuit:

and here's my code:

// to run on attiny85

const byte pwmPin = 0;
const byte analogInPin = A2;

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

void loop() {
  int analogIn = analogRead(analogInPin);
  analogWrite(pwmPin, analogIn);
}

should be very simple- I have no problems uploading code to the attiny85, and no problems with simple tests like outputting a specific PWM value (not based on the analog read). but when I try to combine the two- read, then write that value, I can't seem to get things to work. In this circuit for example- I get a reading of 1023 (5v) on the arduino micro- instead of a reading of ~ 790 (3.85v) which is what I should expect. I've used a multimeter to verify the voltages in this circuit- so I think I must either be doing something wrong with my expectations of how to wire up or program the attiny85.


texts:
I need some code to pause the Arduino code until a button is pressed. I have a long program and at point I need a condition that if a Button on pin A2 is pressed then go forward, otherwise wait.

I tried using if with a condition but it failed for my purpose. I think this is because when if(...) detects that the button is not pressed, it moves to next lines (as usual). But I have a long program and I want to wait forever until the button is pressed.


texts:
In the current project I'm programming simultaneously an UNO board and a Leonardo one.

Switching back and forth between the two boards in the Tools menu takes too much time because of the other 18 boards that I do not own anyway.

Is there a way to remove those boards from the Tools menu?


texts:
#include <avr/sleep.h>
#include <avr/power.h>
//This sketch is a metronome, in which each led pin shows one beat.

const int speaker = 13;  //speaker at pin 13
int ts = 6;  //highest led pin
int count = 3;  //"beat 1 pin"
const int keyPin = 11;  //button to change time signature
const int keyPinR = 10;  //button to change rhythm
const int keySwitch = 2;  //sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;  //you do not need to know this,
//it's just a variable for the potentiometer to change the tempo

int rthm = 1;  //rhythm
volatile int pressed = 0;
long silent = p;

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

   for(int thisPin = 3;thisPin <= ts;thisPin++)
   {
      pinMode(thisPin,OUTPUT); //initialize thisPin as an output
      pinMode(8, INPUT); //potentialmeter for changing temp
      //Pin 9 to 11, along with pin 2, are all push buttons with pull-up     resistors
      for(int i = 9; i<=11; i++)
      {
         pinMode(i, INPUT);
         digitalWrite(i, HIGH);
      }
         pinMode(2, INPUT);
         digitalWrite(2,HIGH);
   }
}

void loop()
{
   turnOn();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);
    //Serial.println(switchState);
    if(switchState==LOW&&pressed==0)
    {
       sleep_enable();
       set_sleep_mode(SLEEP_MODE_PWR_DOWN);
       attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);
       sleep_cpu();
       //Serial.println(switchState);
    }
    else {
       //The beat starts at pin 3, runs in consecutive pins,
       //and ends at pin 8 at maximum
       if(buttonState==LOW)
       {  //changing time signature - up to 5 beats
           ts++;
           if(ts==8)
           {
              ts = 3;
              //8 - 3 = 5 beats max
           }
        }
        if(buttonState2==LOW)
        {  //changing rhythm - quarter note to eighth, then
          //triplets and sixteenths, back to quarter notes
          rthm++;
          if(rthm==5)
          rthm = 1;
 }

    if(silentState==LOW){//if silent key pressed, go to silence (only LED's showing)
    silent++;
  }

  //The RUN code
  for(int thisPin = 3;thisPin <= ts;thisPin++)
  //LED's blinking beats (thisPin - LED pin (beat number + 2))
 {

 for(int r = 1; r<=rthm; r++)
 {//nested loop for the rhythm
   bpm = pulseIn(8, HIGH);//pin 8 - tempo potentialmeter
   digitalWrite(thisPin,HIGH);//each LED blinks

   pinMode(13,OUTPUT); //pin 13 - speaker

   if(silent%2==0)//Press once, tone, press again, no tone
     noTone(13);
 else
 if(count == 3&&r==1). //first beat is higher
 tone(13,4400,80);
 else if(r==1). //downbeats slightly lower
 tone(13,2500,80);
 else
 tone(13,2200,60);  //off beats even lower
 delay((bpm-52)/rthm);
 digitalWrite(thisPin,LOW);  //turn each off as we proceed to the next beat (LED)
 pinMode(13,INPUT);  //speaker input
}
count++;  //beat++

if(count >ts){//go back to count
count = 3;
}

   }
  }
 }

void noSound()//silence the speaker
{
  noTone(13);
}

void interrupt()//this is where the sleep interrupt starts -               //how can i press it to wake up???
{
    sleep_disable();
    detachInterrupt(0);
    if(switchState==HIGH){
       pressed = 1;
       Serial.println(switchState);
       turnOn(); //go back to the main functional method (?????)
     }
 }

Once the keySwitch button is pressed (pin 2), the arduino goes to sleep; however, the only way to turn it on is by resetting everything. How can I just wake up the Arduino, keeping every state as before the sleep interrupt?


texts: Combining a GPS, GPRS, MCU, tilt sensor, and distance sensor

texts:
I am in my final year learning software programing and I am looking to start my own project.
I want to build a device that combine a GPS, GPRS, tilt and ultrasonic sensor.
The purpose of the device is sending the location to my database and then start measuring and sending data those measures to my DB.
The device will be placed in a remote locations (Running on batteries), it will report the distance after detecting a movement(tilt sensor).
For now I am using:

SW-520D Tilt Sensor
Sim 808 as a GPS GPRS modem
Esp8266 NodeMcu
UltraSonic sensor (works with I2C)
2x 18650 3350mah 3.6v battery (with a buck convertor)

The problem is that:

Big components
Battery drain fast (one week)

My question is what devices should I use to minimize battery consumption? Is there any device that combine a modem (GPS and GPRS) with an MCU?


texts: 3-instruction remote machine coding Arduino Atmel chip over a serial line from a tethered (host) PC

texts:
I'm trying to write a program for AVR Atmel 328 chip on Arduino Nano board that will allow me to send machine code instructions to the chip over a serial line, run/execute them on the chip, and interrogate the results by reading chip memory and sending the contents back over the serial line.  This is the genesis of the idea: 3-instruction Forth by Frank Sergeant.
The remote-store and remote-fetch instructions appear to be working fine, but I've not been able to get the remote-call instruction (XCALL() function) to work. The approach I've taken is to coerce a 16-bit address into a subroutine by casting it as a function pointer.
Below is the code that is running on the Arduino Nano (compiled in the Arduino IDE and uploaded using the USB cable via the bootloader)
Any insight would be greatly appreciated!  (I can add diassembled code, my remote instructions etc, if that helps).
Thanks in advance!
// Remote serial development platform for machine coding ArduinoNano/ATmel328, AKE, Jun 9, 2020

// global variables
unsigned char byt;                  // command token from host
unsigned char mem[255];             // memory window under programmatic control
unsigned char dat;                  // data byte from host
unsigned char adr_lo;               // address from host, low byte first
unsigned char adr_hi;
unsigned short adr;                 // combined 16-bit address
typedef void (*GeneralFunction)();  // template to call memory address (as a subroutine)

void setup() {
  Serial.begin(9600);              // Turn UART serial protocol ON for comms with host PC
  Serial.write(0xFF);              // magic number to verify transmission
  Serial.write(0xFE);
  Serial.write((int) mem);         // Informs you of the writeable address space available (LSB, MSB) for tethered memory access
  Serial.write((int) mem>>8);
}

char get_byte(void) {
    while (!(Serial.available()>0)) { delay(50); }
    return Serial.read();
}
short get_adr(void) {
    adr_lo=get_byte();
    adr_hi=get_byte();
    return ( (short)adr_hi<<8 )   |   (short)adr_lo;
}
void xstore() {             // Instruction 1 = xstore(data,adr_lo,adr_hi).  Store byte from host at indicated address in target.
    dat=get_byte();
    adr=get_adr();
    *(char *)adr=dat;
}
void xfetch() {             //  Instruction 2 = xfetch(adr_lo,adr_hi).  Read byte from target memory and return to host.
        adr=get_adr();
        dat=*(char *)adr;
        Serial.write(dat);
}
void xcall() {              //  Instruction 3 = xcall(adr_lo,adr_hi).  Execute subroutine in target memory from indicated address.
                            //  WARNING!  User must have stored RET instruction to send control back to serial monitor.
        adr=get_adr();
        GeneralFunction fGf=adr;
        fGf;
}

void loop() {
    byt = get_byte();               // user specified instruction token (1,2,3)
    if(byt == 0x01 )      { xstore(); }
    else if (byt == 0x02) { xfetch(); }
    else if (byt == 0x3 ) { xcall(); } // else ignore any other serial inputs
}


texts: Testing tri-state pin - erroneous results with internal pullup

texts:
I'm using an MPC73831 - a LiPo charging IC - in my Arduino project. It has a status pin to allow interface to a microcontroller, which uses a tri-state operation to convey three possible states of charging. I don't have the IC and battery yet, but I wanted to write a quick program to test a generic tri-state pin for HI, LO, and HiZ while I'm waiting for it to arrive.

The algorithm I wrote is very simple:

Set pinTest to input, no pullup.
Is pinTest high?
    Yes - pinTriState is HIGH, done.
Set pinTest to input with pullup.
Is pinTest high?
    Yes - pinTriState is HiZ, internal pullup causes high reading.
    No - pinTriState is LOW, 'cancelling out' internal pullup.

However, I'm not getting the expected results when using the internal pullup resistor - my board is showing correct analysis for HI and LO, but HiZ returns a mixture of HiZ and HIGH. I have tried this on an Uno, a Pro-Micro (32u4) and Uno->Micro and Micro->Uno. All give the same spurious results. I am baffled, therefore some advice would be appreciated. The full code is as below. I have left in code which randomises the time pinTriState stays at in a given state to keep pinTest guessing, but it's ultimately only an elaborate way of cycling through the three states.

#define pinTest 2
#define pinTriState 3

int state = 0;
char stateCh = '?';

int sect1;
int sect2;
int sectMax;

void setup()
{
    Serial.begin(9600);
    randomSeed(analogRead(A0));
    sect1 = random(1, 20);
    sect2 = random(sect1 + 1, random(sect1 + 2, sect1 + 20));
    sectMax = random(sect2 + 1, random(sect2 + 2, sect2 + 20));
}

void loop()
{
    // PART (1) Code to toggle three states of a tri-state pin
    if (state == 0)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, HIGH);
        stateCh = 'H';
    }
    if (state == sect1)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, LOW);
        stateCh = 'L'
    }
    if (state == sect2)
    {
        pinMode(pinTriState, INPUT);
        stateCh = 'Z';
    }

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be
    pinMode(pinTest, INPUT);
    if (digitalRead(pinTest))
        Serial.println(" - HIGH");
    else
    {
        pinMode(pinTest, INPUT_PULLUP);
        if (digitalRead(pinTest))
            Serial.println(" - HiZ");
        else
            Serial.println(" - LOW");
    }

    (state == sectMax ? state = 0 : state++);
}

The necessary pins are connected with a single wire. If I upload the code to two boards I remove PART (2) on the 'triState' board and PART (1) on the 'testing' board. In this case, stateCh has no function.

For a single-board setup, I get the following output:

H - HIGH
H - HIGH
...
L - LOW
L - LOW
...
Z - HiZ        <-- the first Z is correct 95% of the time
Z - HIGH
Z - HIGH       <-- the remaining Zs are a mixture, biased heavily towards HIGH.
Z - HiZ
...
H - HIGH       <-- H always gives HIGH
...

It makes no difference if I change the operating order of pinState. I've thrown in delay(100); between almost every other line, again to no avail.

I tried with a 22k, a 33k, and a 47k external pullup resistor. The results are perfect. However, this requires an extra Arduino pin to make sure that the pullup is only active when necessary. Part (2) becomes:

// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be
pinMode(pinTest, INPUT);
pinMode(pinPullup, INPUT);    // connected to pinTest via resistor
if (digitalRead(pinTest))
    Serial.println(" - HIGH");
else
{
    //pinMode(pinTest, INPUT_PULLUP);   <-- not anymore
    pinMode(pinPullup, OUTPUT);
    digitalWrite(pinPullup, HIGH);    // pulls pinTest to Vdd
    if (digitalRead(pinTest))
        Serial.println(" - HiZ");
    else
        Serial.println(" - LOW");
}

Using the extra pin to provide the pullup is a real pain in the ar...duino. I'm cripplingly short of spare pins and I don't see why this is not resolvable with internal pullups. Help?!


texts: Why do I get negative voltages for a PWM waveform?

texts:
I used my Arduino Uno's pin 3 to generate a PWM output. The code is:

void setup() {
  // Put your setup code here, to run once:
}

void loop() {
  analogWrite(3, 180);
}

I connected the output directly with a oscilloscope.
And the output waveform is shown below:

I found it's weird that the minimum voltage is negative! And with the duty cycle increasing, both the maximum voltage and minimum voltage decrease.
Why does it behave in such a way?


texts:
I am using the DFRobotDFPlayerMini-1.0.1 library by Angelo. I am trying to use the actual RX TX pins on a Uno R3, but it doesn't connect unless I type in an alternate digital pin number. This is no good for my application as I have a major pin shortage. I have tried typing in (0,1) but that is not being accepted.

The reason for using this library is because it provides a LOOP function that works well.

How do I use the RX TX pins with this library?
Is there another library that has a good LOOP function in it?

Thanks.

Doug


texts: Need help: Cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]

texts:
I'm trying to convert the string that I receive from the Websocket to uint8_t that I can copy to the data bytes of CAN protocol frame. I'm using an ESP32 chip and programming it on an Arduino IDE. The string that it receives from the websocket is "0322F12155555555".
#include <WiFi.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <esp32_can.h>
#include <SPI.h>
#include <string.h>

uint8_t payload1;
char payload2[100];
...
AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(1337);
...
// Callback: receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num,
                      WStype_t type,
                      uint8_t * payload,
                      size_t length) {
...
      Serial.printf("[%u] Received text: %s\n", client_num, payload);
      strcpy(payload2, (const char*)payload);
      payload1 = (uint8_t)(payload2);
...

Error:
error: cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]
       payload1 = (uint8_t)(payload2);
                                    ^

I'm segmenting the data into an array later, but I'm not confident that my cast is correct. Can someone please help with this? Thanks
-- Keith


texts: Arduino Mega Timer1 in pure C problem - doesn't work

texts:
Does somebody know what can be wrong in this, where I try to set Timer1 interrupt in Arduino Mega in C code only. I'm trying CTC Mode and the purpose is LED blinking with 1[s] Period.

I work with documentation program doesn't work completely.

 #include <avr/io.h>
 #include <avr/interrupt.h>

 void setup()
 {
   //LED -> PB7 (Digital pin 13
     DDRB |= (1<<PB7);

  //FCPU = 16MHz, Prescaler :256 | CTC
   TCCR1B |= (1<<CS12) | (1<<WGM12);
   TIMSK1 |= (1<<OCIE1A);  // Compare Match A interrupt allowing
     OCR1A = 62500;

    sei();
    }

  void loop()
  {

   }

   ISR(TIMER1_COMPA_vect)
   {
     PORTB ^= (1<<PB7);
    }


texts: Arduino as serial 'snoop' tool for 77 bits at 100k baud?

texts:
curious if a Arduino could be configured to read and serial print raw binary bits from a proprietary serial encoder used on machine tools and robots... if so, might have a lot of other possible uses.

I made up a 120 volt servo drive for manually moving big fanuc machine/robot servos, handy during rebuilding/service to be able to move a axis without a control...but the older drives read 4 gray code channels kinda like a set of halls for brushless commutation...on the serial versions, same drive could move the motor if I could decipher the commutation bits and output graycode to the drive... a tiny Arduino looks like a ideal little thing to try doing this.

Scoped out the signals long ago, kinda know where the bits are, but need to be able to actually print them out thru 90 degrees of shaft rotation to find the 12 steps for commutation required by the drive.

Arduino is new to me, but in the past few days have been quite impressed with its abilities. If anyone can suggest a way for Arduino to read a repeating 77 bit data stream at ~100K baud, I'm all ears... I think a 'serial snoop tool' with easily changed baud rates(including non-standard) and 'word length', then serial print out could be really handy. to prevent overflow in my case, could only do the serial print every X milliseconds, and I could just rotate slow enough to get a decent sample.


texts:
Im currently new on this and sucessfully made a sound-activated alarm with Arduino Uno and a microphone sensor. (If sound is detected, then it will alarm). Now, I am adding a ESP 8266 module into it so it can perform a HTTP GET or POST to IFTT Maker link.

My problem with it is how can I program the esp with arduino uno? Do I do something like this

  https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

(and add the threshold for the microphone sensor, buzzers and LEDs)??

Thanks for helping


texts: How to use variables and functions across multiple .ino files

texts:
I have 2 .ino files (2 tabs) for one Arduino project/sketch: MySketch_File1.ino and MySketch_File2.ino.

I declared in MySketch_File2 variables and functions which I want to use in MySketch_File1, but I get this error massage:

  error: 'a' was not declared in this scope

//MySketch_File1.ino
void setup(){
Serial.begin(9600);
Serial.println(String(a));
}

void loop(){

}

Second file:

//MySketch_File2.ino
int a;

How can I declare variables and functions one time in one .ino file and use it across multiple .ino files?


texts: How to add two assembly arrays in arduino

texts:
Hey guys what I'm trying to do is to sum two arrays and return a new array; for example if given
  uint8_t a[] = {2, 4, 6};
  uint8_t b[] = {1, 2, 3};

I should get { 3, 6, 9} What I'm trying to do is have a .ino file call on an assembly file that will do this in assembly and not in C and this is what I currently have in assembly:
// mimics void sumArrays(uint8_t *a, uint8_t *b, uint8_t *c, byte length){} method
    .global sumArrays
    sumArrays:
      //r18 is the byte length
      //r24 and r25 first  array 31,30
      //r23 and r22 second array 29,28
      //r21 and r20 third  array 27,26

      mov r30, r24
      mov r31, r25
      mov r28, r22
      mov r29, r23
      mov r26, r20
      mov r27, r21
      ldi r17, 0 //counter variable
      ldi r19, 1
      call printRegs
      //jmp sumLoop

      ret

    sumLoop:
      cp r17, r18
      brge endSumLoop
      ldi r16, 0
      add r16, Z+
      add r16, Y+
      st X+, r16
      add r17, r23
      jmp sumLoop:

    endSumLoop:
      ret

However, I get sketch/assignment13.S:65: Error: constant value required which is most likely from the
add r16, Z+
add r16, Y+

Lines but otherwise, how would I add it to a temporary variable while progressing the pointer?


texts: Get pin input status without using the arduino library

texts:
I am not allowed to use the Arduino Library (or any Library) for this program. How would I check the input of a pin?

I found two different functions:

In Arduino.h:

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)

Following digitalRead back to pgmspace.h:

#define __LPM_enhanced__(addr)  \
(__extension__({                \
    uint16_t __addr16 = (uint16_t)(addr); \
    uint8_t __result;           \
    __asm__ __volatile__        \
    (                           \
        "lpm %0, Z" "\n\t"      \
        : "=r" (__result)       \
        : "z" (__addr16)        \
    );                          \
    __result;                   \
}))

For the first one, I don't know where bit and value come from and I just don't understand the second one at all.


texts:
Short version: Is the NodeMCU capable of key injection in the same way that an Arduino Teensy can be programmed with Duckuino script to function as a HID?

Long version: Recently, my 7+ year old iMac suddenly stopped working and now I am unable to boot into the Mac which is a right pain. Even more of a pain is that due to the fact that the iMac has a wireless keyboard as opposed to a USB meaning that I am unable to boot into Single User mode, recovery mode, safe boot etc. This is a pain as I am currently stuck with an iMac in an unsuccessful boot loop. I understand that the best option would be to buy a USB keyboard and use this separately; however, it turns out that one of my friends has a spare NodeMCU and said he's willing to lend it to me as he is pretty sure that the Duckuino script will work on it meaning that I could use the NodeMCU as a sort of impromptu keyboard to hold down the shift key on boot, effectively removing the need for me to buy and wait for a new USB keyboard.

I had found this video here on YouTube which explains the process of turning an Arduino into a "USB Rubber Ducky" but there is no mention of this working with a NodeMCU. Assuming that I have the ESP8266 addon for the Arduino IDE and was able to put the Duckuino script onto the NodeMCU, would the NodeMCU function as intended with the Duckuino script or is the NodeMCU hardware such that this would be impossible?

Thank you for any assistance,

Kind regards,
John

P.s. This is what my NodeMCU looks like:


texts: How could I combine sensor data with custom protocol und send it with Serial?

texts:
I am very new to Arduino.
Now I am trying to send the sensor data to Computer.
The sensor data will be stored as bytes into arrays. To build  a robust transmission I'll pack the data with own defined protocol. e.g. has Header, length, Checksum ...
My question is, how to combine the sensor data with protocol frames and send it with serial in a better way.
Now I have written something like below, it works, but very simple and dirty :)
#define SOF_1 0x55
#define SOF_2 0xAA

uint8_t SensorDataByteArrA[4] = {0xc1, 0xc2, 0xc3, 0xC4};
uint8_t SensorDataByteArrB[4] = {0xe1, 0xe2, 0xe3, 0xe4};

void send_sensor_data()
{
  Serial.write(SOF_1);
  Serial.write(SOF_2);

  Serial.write(SensorDataByteArrA, 4);
  Serial.write(SensorDataByteArrB, 4);
  // ...

}

So I'd like to know how will you handle my case?


texts:
my code was working and the connection with database was fine , until I don't know what happen every time I run my code it show this error , can please someone tell me what error 33 = got packets out of order means . I'm using Arduino Uno , Iam using xampp (phpmyadmin) , connecting my Arduino to database using ethernet

#include Ethernet.h>
#include MySQL_Connection.h>
#include MySQL_Cursor.h>

IPAddress ip(10, 0, 0, 12);
EthernetServer server(80);
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(10,0,0,5);  // IP of the MySQL *server* here
char user[] = "username";              // MySQL user login username
char password[] = "amna";        // MySQL user login password

EthernetClient client;
MySQL_Connection conn((Client *)&client);

    String  pass = "AAA";

void setup() {
  Serial.begin(250000);
  Serial.println(pass);
  while (!Serial); // wait for serial port to connect
   Ethernet.begin(mac_addr, ip );
   Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
    // You would add your code here to run a query once on startup.
  }
  else
    Serial.println("Connection failed.");

}

void loop() {
char  query[] ="SELECT * FROM parkingdatabase.infotable";
//     query->setchar(1, pass.c_str());
   //char query[256];
   //sprintf(query,select,pass.c_str());
 //('" + sensorValue + "');");
// Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
   // Execute the query
  cur_mem->execute(query);
  // Fetch the columns and print them

  column_names *cols = cur_mem->get_columns();

    for (int f = 0; f < cols->num_fields; f++) {
    Serial.print(cols->fields[f]->name);
    if (f < cols->num_fields-1) {
      Serial.print(", ");

    }
  }

  Serial.println();
  // Read the rows and print them
  row_values *row = NULL;
  int r = 0;
  do {
    row = cur_mem->get_next_row();
      r=+1;
    if (row != NULL) {
      for (int f = 0; f < cols->num_fields; f++) {
        Serial.print(row->values[f]);
        if (f < cols->num_fields-1) {
          Serial.print("+  ");

        }
      }

      Serial.println();
    }
    delay(1000);

  } while (row != NULL);
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}


texts: digital pin's current limit, ohm's law and DC motor

texts: A digital pin's output voltage on an UNO board is 5V, which is equal to the output from the VCC. I read that the DC current limits of those pins are 40mA and 200mA respectively, and that a higher current could damage the board. Now, since V=RI, I expect to get the same current whether I connect a DC motor to the VCC or to a digital pin. But, the motor spins slower when connected to the digital pin. Therefore, I'm not getting the same current, and the only thing I could think of in order to explain this apparent contradiction with ohm's law is that there must be some mechanism to keep the current flowing through a digital pin inferior to 40mA. But I also read somewhere (can't find/remember the source) that there are no such mechanisms (except for a fuse concerning the USB)... So as you see, I can't understand what's going on. It will be really nice if someone could explain that to me... thanks in advance!


texts: Sleep mode and months of operation on small battery

texts:
In context of getting the MCU on Pro Mini and ATMega2560 (chip is ATmega328 and ATMega 2560) to sleep and power down modes, so as to run on one set of battery for months, appreciate idea and comment.

Initially, I looked at web postings and get the following general idea. Did I miss anything?

Is sleep mode done via ATMel factory library, Arduino-level user contributed library, or the Arduino IDE? Many web posting are along the line of getting it partially working but only at half expected current reduction, etc. That is, current do reduced, but, not enough.

Are there several such library?

How are they?

Which one is better support and more functions? (no need for easy to use, can do registers programming, when needed)

Many thanks in advance


texts: How precise can I get Arduino using rotary encoders?

texts:
Stepper motors are often pricey for a large motor. However, with a powerful, standard DC motor and a rotary encoder, you can "simulate" a stepper motor. How accurate are rotary encoders with Arduino just with a basic loop and not much other code? Is it going to "miss a pulse" and not record enough rotation often? How can I handle this with much more code? Is there a better way to do this? Would interrupts help? Is there some sort of circuit that would help with this problem?

Note: It will probably not exceed 4 rotations a second... (That may be a lot but if you're doing a lead screw type mechanism that would only be 24 inches a minute if there is 10 rotations per inch of linear motion.)


texts: How to use same sketch on two different computers in two different directories

texts: I have the same sketch one that I use at my desk and in the lab, but they are in different directories on the different computers.  This means that I have to change the paths to the includes which I have to fixup every time I transfer back and fourth.  Is there a way to put in a #ifdef that I can set at the start of the build that would include correct path.


texts: How to use the timer to generate a pulse wave of the specified frequency and duty cycle

texts: So we have the tone library, which produces a 50% duty cycle square wave of varying frequency, and analogWrite() which produces a fixed frequency wave of varying duty cycle. Is there any way to control frequency and duty cycle at the same time on an Atmega328-based board?


texts: Can I control a Z84 counter timer circuit with Arduino?

texts:
Link to pin description and to the Datasheet.

I'm thinking about connecting channel outputs to LEDs and control the clock with IO-Arduino or a 555: I would program it with a 595 register.

Can someone explain me why this is a bad idea?


texts: NRF24L01 based project freezes for no good reason

texts:
I have built and coded a low power NRF24L01 transmitter and receiver, for purposes of transmitting the temperature of the transmitter's environment. I have used an Atmega328P chip for the project. The project itself works well, but after some time, around 10 days or so, the transmitter goes silent.
During my initial troubleshooting, I have concluded that the system hangs up during NRF transmission, and since it's stuck in the transmission phase, it eats up all the battery and dies. For this, I'm also transmitting battery usage, and I have added watchdog timers in my temperature sensing and transmission phases. This has not solved my problem, and I'm stuck as of now.

Some bits of code:
My low power cycle:

 while (1) {
  wdt_reset();  //watchdog timer added for 8S. See the beginning of loop func for timer settings.
  Serial.print("Loop Start ");
  delay(50);
    //Blink only at every wakeup
    digitalWrite(redLed, HIGH);
    setTime = millis() + ( 1 );
    while ( millis() <= setTime ) {
    }
    digitalWrite(redLed, LOW);
    //Blink only at every wakeup

    Serial.println("Powerdown begins");
      delay(50);
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
    sleepCounter++;
    Serial.println("Powerdown over");
      delay(50);
     wdt_enable(WDTO_4S);     // enable the watchdog
  //Reenabling radio for test purposes

//end of radio edit
         Serial.print("Slept for ");
         Serial.println(sleepCounter);
    if ( sleepCounter >= postPeriod || sleepCounter == -1 || interruptState == true ){       ///|| true ) {
      sleepCounter = 0;
      interruptState = false;

      break;

    }

  }

  //Serial.println(micros());
  //Serial.println("DEBUG nRf Test");

  radio.begin();
//  radio.powerUp(); //power up the nRF24

  digitalWrite(redLed, HIGH);

  Set_nRFTX_Data (1);

  nRF_Send ();

In the Set_nRFTX_Data() function, I'm writing my temperature value to the buffer, as such :

   nRF_BufferTX [23] = b1;             // 24th byte the first byte of a two-byte value for precision (msb)
    nRF_BufferTX [24] = b2;              // 25th byte the second byte of a two-byte value for precision (lsb)

And in the nRF_Send() function, I'm sending it over NRF:

void nRF_Send () {

  radio.closeReadingPipe(address);
  radio.openWritingPipe(address);
  radio.stopListening();

  bool isDataTransfer;
  radio.write(nRF_BufferTX, 32);

  radio.openReadingPipe(1, address);
  radio.startListening();
}

If anyone's interested, I may share circuit specifications as well.


texts:
hi there im using arduino uno + usb host shield and i have taken the readings from the usb mouse in this line of code : x =  mi->dX;
and the x output is the speed of the mouse x coordinates
and i wanna make it thru an analog  reading from 0 to 1023 i should do a constrain and a map
then i send the data thru i2c comm and recieve them with a slave code and display them but the mouse on the screen is moving always when i give the mouse a left move the mouse moves always to left and when i gave the mouse roght it moves to the right always without stopping the cursor as if im giving it a speed direction + or - .
this is the master code :

#include<Wire.h>
#include <hidboot.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif
int x; // mouse x
int y; // mouse y
int y1;
int x1;
int l,r;
int x11,y11;
class MouseRptParser : public MouseReportParser
{
protected:
void OnMouseMove (MOUSEINFO *mi);
void OnLeftButtonUp (MOUSEINFO *mi);
void OnLeftButtonDown (MOUSEINFO *mi);
void OnRightButtonUp (MOUSEINFO *mi);
void OnRightButtonDown (MOUSEINFO *mi);
void OnMiddleButtonUp (MOUSEINFO *mi);
void OnMiddleButtonDown (MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{
x =  mi->dX;
//x = constrain(x, 0, 1023);

Serial.println(x);

y =  mi->dY;
//y = constrain(y, 0, 1023);

Serial.println(y);

};
void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
{
Serial.println("L Butt Up");
l=0;
};
void MouseRptParser::OnLeftButtonDown (MOUSEINFO *mi)
{
Serial.println("L Butt Dn");
l=1;
};
void MouseRptParser::OnRightButtonUp (MOUSEINFO *mi)
{
Serial.println("R Butt Up");
r=0;
};
void MouseRptParser::OnRightButtonDown (MOUSEINFO *mi)
{
Serial.println("R Butt Dn");
r=1;
};
void MouseRptParser::OnMiddleButtonUp (MOUSEINFO *mi)
{
Serial.println("M Butt Up");
};
void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
{
Serial.println("M Butt Dn");
x = 90;
y = 90;
};

USB Usb;
USBHub Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE> HidMouse(&Usb);

uint32_t next_time;

MouseRptParser Prs;

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

Wire.begin();       //Begins I2C communication at pin (A4,A5)

Serial.begin(115200);
#if !defined(__MIPSEL__)
while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
Serial.println("Start");

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

delay( 200 );

next_time = millis() + 5000;

HidMouse.SetReportParser(0, &Prs);
}

void loop()
{
Usb.Task();
Wire.beginTransmission(8);
Wire.write(x);
Wire.write(y);
//Wire.write(l);
//Wire.write(r);

Wire.endTransmission();
delay(10);

}

and the output is speed direction of x and y :
0
0
0
1
1
2
3
4
5
66
66
78
99
102
113
22
3
0
and this is the slave code :
#include<Wire.h>
int x,y,l,r;
#include <Mouse.h>                                                                               // Analog output of vertical joystick pin

void setup() {
Serial.begin( 115200 ); // start serial for output
Wire.begin(8);
Wire.onReceive(receiveEvent);
Mouse.begin(); //Init mouse emulation
}

void receiveEvent( int bytes )
{

x = Wire.read();
y = Wire.read();
//l = Wire.read();
//r = Wire.read();
delay(10);
}

void loop() {

Mouse.move(x, y, 0); // move mouse on y axis
delay(10);
}

anyone could help please i think the problem is i should ask the current position  and the next postion and if it was not zero move the mouse otherwise if it is 0 do not move


texts: how to stop the relay after it is getting on and let the sensor get the result

texts:
I want to provide a delay in the following iteration reading so that the sensor can read the condition after the pump starts.
void loop() {
  //-------------Fungsi Read sensor-----------
  // sensorAll();

  hasilec = (ppmcensor - inputec);
  ph = (phcensor - inputph);

  //  hasilec = random(-200, 0) / 100.0;
  //  ph = random(-200, 200) / 100.0;

  //  ph = -180/100.0;
  //  hasilec = -1.2;

  unsigned long now = millis();

  Serial.print("pH    ");
  Serial.print(ph);
  Serial.print("  ");
  Serial.print("EC ");
  Serial.print(hasilec);
  Serial.println("");
  Serial.print(ph); Serial.print(" ");
  Serial.print(hasilec); Serial.print(" ");
  Serial.println(" ");

  //  delay (500000);

  fuzzy->setInput(2, hasilec);
  fuzzy->setInput(1, ph);
  fuzzy->fuzzify();

  float pompa01 = fuzzy->defuzzify(1);//pHDOWN
  float pompa02 = fuzzy->defuzzify(2);//pHUP
  float pompa03 = fuzzy->defuzzify(3);//ABMIX

  Serial.println("Result= ");
  Serial.println("");
  Serial.print(" Pompa1 pHDOWN: ");
  Serial.println(pompa01);
  Serial.print(" pompa2 phUP  : ");
  Serial.println(pompa02);
  Serial.print(" pompa3 ABMIX : ");
  Serial.println(pompa03);
  Serial.println("");
  Serial.println("");
  Serial.println("");

  delay (2000);

  long int pompa1 = pompa01 * 1000;
  long int pompa2 = pompa02 * 1000;
  long int pompa3 = pompa03 * 1000;

  pump_periods[0] = pompa1; //PHdown
  pump_periods[1] = pompa2; //PHup
  pump_periods[2] = pompa3; //ABMIX

  for (int i = 0; i < jml_pump; i++) {
    if (now - pump_last_actuations[i] >= pump_periods[i]) {
      pump_states[i] = (pump_states[i] == LOW) ? HIGH : LOW;
      digitalWrite(pump_pins[i], pump_states[i]);
      pump_last_actuations[i] = now;
    }
  }
}

If I put the delay after millis iteration it causes the pump to only turn on based on the delay, not the timer millis. What should I do?


texts: Interrupt is activated as soon as I insert a jumper wire into the port

texts:
I have written a very simple code to test the interrupt functionality of my Arduino Uno expansion board:

const byte buttonPin3 = 3;

void setup() {
  pinMode(buttonPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin3), trigger, CHANGE);

  Serial.begin(9600);
}

void loop() {
}

void trigger(){
  Serial.println("trigger");
}

However, the Serial.println("trigger"); is activated as soon as I insert a jumper wire into pins 2 or 3. It seems like I have broken the microcontroller. I would appreciate if you could help me know if there is something wrong with my code or I need to change the microcontroller? if I have to replace the MCU can I just use any identical AVR and just place it on the DIP IC socket adaptor?

P.S. Filip Franik asked me to draw the schematics:

simulate this circuit – Schematic created using CircuitLab

P.S. I used the official Button's tutorial and now everything works just fine. I can't reproduce the issue anymore for no obvious reason!.


texts: Random characters generated by LCD during serial.read()

texts:
I am using the following codes to print characters on LCD display....

#include <LiquidCrystal.h>

const int rs = 8, en = 9, d0 = 4, d1 = 5, d2 = 6, d3 = 7;
LiquidCrystal lcd(rs, en, d0, d1, d2, d3);

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    delay(100);
    lcd.clear();
    while (Serial.available() > 0) {
      lcd.write(Serial.read());
    }
  }
}

but in the end it is generating an unwanted character also..

kindly help me with the problem


texts:
I recently bought the HC 08 Bluetooth module (link here). As the specs state, this module supports Bluetooth 4.0 which indicates that it supports BLE (Bluetooth low energy).

My goal is to be able to use something similar to the CurieBLE library: I want to code services and characteristics on my Arduino so I can discover those on LightBlue (iOS).

I searched the internet for some guidelines, but I only found code using AT commands and honestly I don't know anything about those.

Can you please recommend any source to achieve the goal?

Update

After following the connections in this link (In Spanish I guess but helpful), I was able to discover the Arduino on LightBlue. The characteristic name was Tx/Rx and I was able to write, read and subscribe to notifications (data coming in). Of course if would be better to find something that allows the definition of services and characteristics.


texts: How to add data without pre-defining variables?

texts:
I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.

What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello w, your ID number is xxx xxx xxx xxx xxx.

So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?

Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach.


texts: Leostick Receiving message from Uno using USB jumpers cables

texts:
I have a Arduino Uno which is looping over Serial.println("$testmessage"). Connected to this is a USB cable that i have cut and soldered male jumper leads to . I need to receive this message ("$testmessage") from the Uno using this USB cable without using the leosticks usb connector. After receiving the correct messgae from the Uno i plan to use Serial to send data from the leostick to my pc.

I'm stuck trying to figure out how to receive this message from the Uno.

Currently the the USB 5v and ground is connected to the leosticks 5V, GND pins. The Uno powers on and the the tx led is flashing every 100 milliseconds.

Can i just plug the green and white wires from the USB cable into D0&D1 and except it to work?

(Uno plugs into usb cable in the image)
http://imgur.com/jxiKJMa


texts: Avrdude Verification Error while flashing Arduino Mega code

texts:
I'm working with an Arduino Mega 2560 and am getting the following error at compile time:

  avrdude: verification error, first mismatch in byte 0x0000 0x14! =
  0x25 avrdude: verification error; content mismatch

I've already changed the COM port and also restarted an IDE.


texts: Can I change the pins on the communication for a Master-Slave arduino Wire transmission? I want to communicate between 2 arduinos, but on one of them A4&A5 are taken


texts: Having a bunch of global variables or calculate them on the go on an Arduino, as far as memory is concerned

texts:
So I'm new in the arduino world but I have a grasp of object oriented programming, and decided to write a little library for running games on an arduino mega using a display. My question is, I'm creating an "Entity" class (to spawn multiple enemies, players, etc) outside the setup() and the loop() functions, so they dont overwrite themselfs when the program is running (don't know if there's a better way), and I want to store position information, like xPos and yPos, but I need to calculate a lot of other stuff based on those two variables, and creating more variables makes the code more easy to read/write.
But I don't know how this would affect the memory usage or speed, because I ran into some problems earlier when I tried to create a big array, it end up using like 300% of the dynamic memory, so I guess that when I declare a global byte, for example, the arduino allocates the whole memory as if you would use the biggest byte possible.
Sorry for bad english :s


texts: Custom built Arduino is not working - double blinks

texts:
I've made a home-made Arduino based on this video. The problem is that I can't upload anything, it doesn't react, only the LED double blinks in every second. What does that mean? How to fix it? Thanks.

Update:


texts: Serial Communication between arduino and nodeMCU

texts:
I am trying to connect a nodeMCU to arduino mega using serial communication so that i can read data from firebase.

I have put the following code on the NODEMCU.

#include<SoftwareSerial.h> //Included SoftwareSerial Library
//Started SoftwareSerial at RX and TX pin of ESP8266/NodeMCU
SoftwareSerial s(3,1);

void setup() {
  //Serial S Begin at 9600 Baud
  s.begin(9600);
}

void loop() {
  //Write '123' to Serial
  s.write('h');
  delay(1000);
}

And the following on the MEGA

int data; //Initialized variable to store recieved data

void setup() {
  //Serial Begin at 9600 Baud
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  if(Serial1.available()){
  data = Serial1.read(); //Read the serial data and store it
  delay(1000);
  Serial.print(data);}
}

I have connected TX1(arduino) to RX(nodeMCU) and RX1(arduino) to TX(nodeMCU) yet when ever i upload the code it doesnt work until i press the reset button then  some random numbers are passed over then eventually 123 comes accross. I am trying to do 2 way comunication but will worry about that when i finish this.

Any help would be much appreciated as I have spent the last 15 hours trying to solve this problem but to no avail.
Cheers, Hamish


texts: WiFi.begin doesn't work with ArduinoJson's const char* output

texts:
I'm using ArduinoJson to parse a file full of JSON strings that contain the SSID and password for the registered networks. I have a little web interface that runs in soft AP mode so you can scan for networks and add them to the file. Adding networks to the file works fine, but reading them back and using them as input for WiFi.begin doesn't work. It moves to status code 1, which means it failed to find a network with that SSID.

I have compared the value of the result of const char* ssid = networks[network]["ssid"]; with const char* _ssid = "MySSID"; using strcmp and it returns 0, so I can't figure out why it's not working. It works if I replace networks[network]["ssid] with my SSID (though I need to replace the password with the string literal as well, otherwise it stays on status code 6, disconnected).

I can't figure out what it is about ArduinoJson, but it seems that the result of grabbing a string doesn't return a string that is formatted correctly for WiFi.begin, but it satisfies strcmp?

Edit:
I modified the code quite a bit in an effort to get it to work. I am no longer passing the ArduinoJson object, I'm now passing a struct with the data, and it still doesn't work. Is this the work of some advanced c++ constants/pointers stuff that I don't seem to understand?

main.cpp:

#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <ESPmDNS.h>
#include <SPIFFS.h>
#include <vector>
#include <elapsedMillis.h>

#include "config.h"
#include "restserver.h"
#include "scanwifiserver.h"

AsyncWebServer *Server = new AsyncWebServer(80);

ScanWifiServer *scanWifi;
RestServer *restServer;

struct Network {
    const char* ssid;
    const char* password;
};

std::vector<Network> readAP(fs::FS &fs) {
    //fs.remove("/ap.txt");
    File file = fs.open("/ap.txt");
    std::vector<Network> networks;
    if (!file) {
#ifdef DEBUG
        Serial.println("Failed to open file for reading");
#endif
        return networks;
    }

    while (file.available()) {
        DynamicJsonDocument n(JSON_CAPACITY);
        auto s = file.readStringUntil('\n');
        deserializeJson(n, s);
        struct Network network = {n["ssid"], n["password"]};
        networks.push_back(network);
        Serial.println(networks.back().ssid);
    }

    file.close();
    return networks;
}

void setup() {
#ifdef DEBUG
    Serial.begin(BAUDRATE);
    delay(2000);
#endif

    SPIFFS.begin();
    auto networks = readAP(SPIFFS);
    if (networks.size() > 0) {
        Serial.println("Networks:");
        int network = 0;
        Serial.println(networks.size());
        while (WiFi.status() != WL_CONNECTED && network < networks.size()) {
            const char* ssid = networks[network].ssid;
            const char* password = networks[network].password;
            Serial.printf("%s, %s\n", ssid, password);

            WiFi.begin(ssid, password);

            while (WiFi.status() != WL_CONNECTED) {
                if (WiFi.status() == WL_CONNECT_FAILED || WiFi.status() == WL_NO_SSID_AVAIL)
                    break;
                delay(500);
                Serial.print(WiFi.status());
            }
            Serial.println("");
            network++;
        }
        if (WiFi.status() == WL_CONNECTED) Serial.println("Connected");
        else networks.clear();
    }
    if (networks.size() == 0) {
        Serial.println("Starting ScanWifiServer");
        WiFi.mode(WIFI_AP);

        scanWifi = new ScanWifiServer(Server);

        Server->begin();

        MDNS.begin("grow");
        MDNS.addService("http", "tcp", 80);
    }
}

void loop() {}


texts: Powering LCD Displays without a Breadboard

texts: I hope that this is not a silly question. I may be hoplelessly optimistic in asking, but is there any way to power & display information onto a LCD Display from an Arduino Uno.... Without the breadboard? I am working on a hardware project that has very strict space constraints, and the breadboard is simply not an option.


texts: ArduinoUNO/MEGA, Is there a way to exceed 256 in analogWrite

texts:
I am using Arduino UNO/MEGA, I want to

analogWrite(pin, val);

where the value is 0-1023.

How can I make that ?

Thanks.


texts:
I am using a MCP3002 to convert an analog signal to digital data. It works fine actually, sends good data. However; After a while, when the power is turned off and on again a few times, it only returns zeros. If I Power it on the next day, it works for a while again.

I am just beginning with SPI, so I do not know 'all' the basics. Is there something I should reset when powering on or something? (Clock, Timing, etc.)

This is the code I am using (pretty straightforward):

#include <SPI.h>
SPISettings spiSettings(7280000, MSBFIRST, SPI_MODE0);
const int SPI_CS = 2;

void setup() {
    pinMode (SPI_CS, OUTPUT);
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setFrequency(7280000);
}

void loop() {
    SPI.beginTransaction(spiSettings);
    digitalWrite (SPI_CS, LOW);

    uint8_t cmd = 0b11000000;
    byte msb, lsb;
    word assembled;

    msb = SPI.transfer(cmd);
    lsb = SPI.transfer(0);

    assembled = word(msb, lsb);
    Serial.println(assembled);

    digitalWrite (SPI_CS, HIGH);
    SPI.endTransaction();
}

Is there something wrong, or should something be added to this?


texts: Determine whether Arduino Uno board is faulty or not?

texts: I'm just giving 9V supply to the Arduino Uno but along with its power led,  the transmission one is also blinking. Can anyone please tell me whether the board is faulty or not?


texts: General Question about fast Serial Communication and Arduino

texts:
I'm looking for a fast (and safe, in terms of stability) way to send sensor data from an Arduino UnoR3 in real time to a Computer (in my case a MacBook Pro) with a sample rate of at least 1kHz.

I tried following:

Sending sensor values with the related timestamp (in microseconds):
I use 7 bytes for each sample [1 Header byte, 2 bytes for the sensor value (10/(16)bit-Int), and 4 bytes for a 32-bit unsigned long (time in microseconds)] and send them right away.
On the receiving end i mainly use Processing (Im relatively new to Processing though): Reading the bytes in, converting them in integers and safe them in a file or plot them.

For sampling rates of 1sample/10ms my code runs smooth and i even can plot the data in "real-time".

For higher frequencies i ran into following problems:

If i want to plot things, my peripherals freeze and program stops after some time. I have no clue why... maybe serial buffer overflow??
If i just save the data in a text file (without plotting) it works but with a delay of around 20-30seconds on total sampling times of 10seconds (10000 samples).
Meaning that somewhere seems to be a bottleneck and i cant keep up with the sent samples from the Arduino.
Is it possible that the serial bus is the bottleneck here? How can i speed things up? (I'm working with a baudrate 115200bits/s and also 230400bits/s)

How can i improve this while still be able to process data in almost real-time (e.g plotting). Is this even possible or do you recommend logging the data in a text file first and then plot?

Will it helps to send the data in packages (10samles = 70bytes)?

I added a timestamp on each sample, since i observed some delay between the actual sensor measurement and the input on the receiving end. I thought that would allow me to plot and postprocess accurately in "real"-time (with a little delay). Any other ideas?

I would appreciate some input and advice!

Thanks in advance!


texts: Can I use an ST-Link to program an STM32F4 through the Arduino IDE?

texts: I have a bunch of boards with STM32F's on them, and they only have JTAG headers. Is there some way to program and/or debug the boards


texts: Can I use the microchip of Arduino Uno as a standalone microcontroller

texts:
I want use the ATmega328P chip of the Arduino Uno board as a standalone device.

Is that possible?
Which pins are which on the Arduino board and the ATmega328P?
Do I need any external components?


texts:
i struggle to figure out the max payload for the RF24 Network library without payload fragmentation.
It uses a NetworkHeader with the Attributes from_node, to_node, id, type and reserved.
This must be send to and lowers the amount of Bytes of the payload.

Can any one tell me how many Bytes I can write without sending two packages?


texts: Forward kinematics of a differential drive robot

texts:
I've been braking my head over this for the past few days and can't make it work.. So, I have a small robot with a rotary encoder on each wheel and i want to track its position (in x and y) on a flat plane. I know it's called forward kinematics, but i can't seem to get it working. I found a lot of great public sheets, but i think, out of all of them, this is the best one It had the equations of how to calculate the X and Y on page 74:

Vicc=L * (Din / (Dout–Din) + ½) (page 73) //Din is the inner wheel of the turn traveled distance, Dout is the outer wheel
Xtδ=Xt+Vicc*(sin(θt+θΔ) – sinθt)
Ytδ=Yt+Vicc*(cosθt - cos(θt+θΔ))
θtδ=θt+θΔ //angle measurement

Where Xtδ and Ytδ are the position of the robot (x, y); Xt/Yt/θt is the position of the robot when the counting of the position has been started; θΔ is the angle of the robot now;
. Here's The code that I tried to write using the equations. I expected it to write my coordinates in x and y, but when i moved the wheels, it sent me big, random numbers, which are fluctuating up and down, which looks like a sine wave. What am I doing wrong? Could you guide me to the right path? My end result, that I want to reach is controlling 2 both motor speeds and knowing the robots position (doesn't need to be very precise though).
Thanks in advance!
EDIT: Added code from PasteBin
#include <Encoder.h>

Encoder Left(3, 2);
Encoder Right(0, 1);

float R = 385; //mm
float r = 12.5; //Wheel diameter in mm
float L = 8; //Distance between the wheels in cm

double LeftDist = 0;
long LOldPos  = -999;
float LNewPos;
int Correction;

double RightDist = 0;
long ROldPos  = -999;
float RNewPos;

int angle= 0; // Robots current angle
unsigned long t;

int Xold= 0; //position at the start of the calculation
int Xnew= 0; //new, calculated position
int Ystart= 0; //position at the start of the calculation
int Ynew= 0;//new, calculated position
int OldAngle= 0; //angle at the start of the calculation
int NewAngle= 0;// new angle at the end of the calculation
int Vicc;

void setup() {
  Serial.begin(9600);
  t = millis();
}

void loop() {
  Encoders();
  if ((millis() - t) >= 100) {
    Xold= Ynew; //setting the new position to old
    Yold= Ynew; // setting the new position to old
    OldAngle= NewAngle; //Setting the new angle to old

    Vicc = (L * (LeftDist / (RightDist / LeftDist))) + 0.5;
    Xnew= Xold + (Vicc * (sin(OldAngle + Angle) - sin (OldAngle))); //Calculation of X
    Ynew= Yold+ (Vicc * (cos(OldAngle) - cos(OldAngle+ Angle))); //Calculation of Y
    NewAngle = OldAngle+ Angle;

    t = millis();
  }

  Serial.print(angle);
  Serial.print("        ");
  Serial.print(Xnew);
  Serial.print("        ");
  Serial.println(Ynew);
}

//0.9mm/1 deg
void Encoders() {
  LNewPos = Left.read();
  if (LNewPos != LOldPos) {
    LOldPos = LNewPos;
    LeftDist = ((LNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  //-----------------------------------------------------
  RNewPos = Right.read();
  if (RNewPos != ROldPos) {
    ROldPos = RNewPos;
    RightDist = ((RNewPos / 840) * (2 * r * 3.14)) / 10; //cm/ Rev
  }
  angle= (abs(RightDist - LeftDist) * 0.9) - Correction; //calculate the angle the robot has turned
  if (fi >= 360) Correction += 360;
  else if (fi <= -360) Correction -= 360;
}


texts: How to design an enclosure around the load cell (Beam type)?

texts: Hardware and Electronics Used: Arduino UNO, HX711 ADC Load cell amplifier, Load Cell (2Kg); Currently, I am working on a project which requires me to put load cell along with the other circuitry in an enclosure to make it water-resistant... But while doing so, the weighing platform and the base come in contact (as shown in picture 2). This messes up the readings. I 3D printed various loading styles and tried out a few different configurations but none of them seem to work. The configuration that is shown in Image1 is an ideal one that yields precise results irrespective of where you place the load on the weighing platform. The configuration in Image2 yields fluctuating readings which make no sense whatsoever. Can you suggest to me some way by which I can design a proper enclosure around the load cell and the circuitry in order to get proper readings and also keep it water-resistant?


texts: I'm trying to control a servo with a push of a button but its not working HELP

texts:
I'm new to Arduino and I'm following this tutorial: https://www.youtube.com/watch?v=T2HMJiy9b_I   but the problem is the servo just keeps moving back and forwards on it own and the button is doing nothing when pressed please help.

Code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =90;    // initial angle  for servo
int angleStep =5;
const int minAngle = 50;
const int maxAngle = 110;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Robojax Servo Button ");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }

}


texts: Can I damage an arduino by setting pins high with no load

texts: I have an Arduino project that has 15 different output pins set.  Some are currently attached to devices and others are not.  Will testing my program cause a problem / damage if it sets pints to HIGH that do not have anything connected to them?


texts: Unable to upload code to the Arduino Nano

texts:
I tried to to upload a hex file I generated for the Arduino Nano using avrdude but I keep getting the error:

avrdude: stk500_2_ReceiveMessage(): timeout

First the arduino board stops doing whatever it is programmed to do, in this case powering a vibration motor .
Then this error keeps showing up in delays of around 10 seconds.
That error is then followed by

avrdude: ser_recv(): read error: The I/O operation has been aborted because of either a thread exit or an application re
quest.

which appears to be caused by me pulling out the USB cable after waiting a while.

Thanks


texts: how to make transmitter and receiver for quad copter?

texts: I want to make a transmitter and receiver for quad copter for that I am using two arduinos(UNO and nano).I am using 4 pots for controlling the brushless motors.For that I am sending 4 integer values of the pots and with that integer value PWM signals are generated at receiver by the arduino.Now I want to know how to send that 4 integer values of the pots serially using arduino.


texts:
I have a STM32 that I programm in Windows, I connected them like this:
https://electronics.stackexchange.com/questions/515810/ftdi-and-st-link-devices-together-to-stm32
Now, I moved to Linux (Ubuntu 18.04) but the Arduino IDE cannot find the ST LINK, I got the following
      -------------------------------------------------------------------
                    STM32CubeProgrammer v2.5.0
  -------------------------------------------------------------------

libusb:warning [libusb_open] internal signalling write failed
ST-LINK error (DEV_USB_COMM_ERR)
libusb:warning [libusb_close] internal signalling write failed, closing anyway
the selected serial port libusb:warning [libusb_close] internal signalling write failed, closing anyway
does not exist or your board is not connected

Am I missing some configuration?


texts: Do some arduino pins give signals when the controller starts?

texts:
For example, on the ESP32 board there are several contacts that can issue pulses when the controller starts, which is connected with the operation of the chip itself. It is not recommended to connect devices that respond to input signals from the ESP to these contacts.

Tell me, are there any contacts on the Arduino UNO (Atmega328P) that give out any impulses at startup?

In particular, it is important for me to know about the following contacts:

PB1 (9 pin)
PD4 (4 pin)
PD5 (5 pin)

Thank you!