Arduino serial monitor lagging and cant get it to work - c++

I wrote this program to check some things m but for me it is not working
` #define outputA 7
#define outputB 3
int counter = 0;
int aState;
int aLastState;
int StateAreTheSamePrinted = 0;
int StatePrinted = 0;
void setup() {
// put your setup code here, to run once:
pinMode(outputA, INPUT);
pinMode(3, INPUT);
Serial.begin(115200);
aLastState = digitalRead(outputA);
Serial.print("Arduino started");
}
void loop() {
// put your main code here, to run repeatedly:
aState = digitalRead(outputA);
if(StatePrinted == 0)
{
Serial.print(aState);
StatePrinted = 1;
}
if(aState == aLastState && StateAreTheSamePrinted == 0)
{
Serial.print("States are the same");
StateAreTheSamePrinted = 1;
}
if(aState != aLastState)
{
if(aState == 1){
Serial.print("A is high \n");
}
else
{
Serial.print("A is low \n");
}
StateAreTheSamePrinted = 0;
StatePrinted = 0;
}
aLastState = aState;
}
It always prints once arduino started, 1 (state of input), and states are the same, when I wire 5v from arduino into port 7, sometimes it react once, sometimes n ot, after few minutes it start priting output like 50-100 lines of messages and stops and lags again. Does anyone got into this problem?
`
I was expecting that after giving power into arduino 7 port it would print A is high or A is low and toggle between them

Sounds like you need to "debounce" after the state changes. When you hook 5v into the pin, it might not make a stable connection right away so it changes state very quickly a few times. A simple fix is to put a ~10ms delay after it detects a state change.

Related

Serial.write(5) not able to send decimal?

I am trying, as a test to Serial.write the int value: 5, to serial monitor, and if received, i want to print the the text "SUCCESS!" to the serial monitor.
But when writing Serial.write((int)5); All i get in the serial monitor is:
I have tried using Serial.println(5); which works fine, but then i am not able to read it.
My code:
enum read_states {
Modtag_Adresse,
Modtag_Bit_Position_I_Adresse,
Modtag_Bit_Position_Vaerdi
};
enum read_states state;
void setup() {
state = Modtag_Adresse;
Serial.begin(9600);
}
void loop() {
if(state == Modtag_Adresse) {
Serial.write((int)5);
delay(1000);
if(Serial.available() > 0) {
int serialReceived = Serial.read();
if(serialReceived >= 0) {
// Receive value 5
Serial.print("SUCCESS!!");
}
}
}
else if(state == Modtag_Bit_Position_I_Adresse) {
//
}
else if(state == Modtag_Bit_Position_Vaerdi) {
//
}
else {
// Failure.
}
}
Serial.write(5) sends the byte 5 to the computer. It appears as a square, because it's not an ASCII code of a letter or number or symbol.
Serial.print(5) sends the ASCII code for 5 (which is 53).
The reason you can't read what you wrote is because Serial.write sends data to the computer and Serial.read returns data received from the computer. If it read data from the Arduino program, it would be pointless because you don't need to use serial for that.

ESP32 Simple button hold for 3 seconds example. Output doesn't seem to make sense?

Hoping someone can see what I'm missing as it's gotta be right there staring at me in the face..
I've got this code (below) set up on an ESP32 to spawn a thread that simply monitors the state of a pin connected to a switch. Essentially this code is supposed to wait for the button to be held for 3 seconds and then do something important. The actual input seems to read fine, but for some reason once I've pressed the button, the button state is stuck for like 15 seconds after un-pressing the switch.
For example,
Press the switch, the actualBtnState reads 1, buttonState reads 1 (after 50us),and btnPressTime increments as expected.
Release switch, actualBtnState reads 0, btnState reads 1, and btnPressTime stops incrementing.
After 50us, expecting to see btnState read 0 and then trigger the else or elseif blocks (depending on how long the button was held). Actual results continue to read btnState = 1 and btnPressTime = [whatever the last held time was] for a solid 15 seconds or more. actuyalBtnState reads correctly at 0 this entire time and for some reason lastDebounceTime keeps incrementing?
I should note that this is part of a much larger project, hence the threading. I also can't seem to print anything within the resetBtnCB function as I immediately get a "guru mediation error kernel panic whatever-the-error-is" error and the esp reboots.
Code:
#include <Arduino.h>
#define BUTTON_PIN 27
// Variables will change:
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
unsigned long buttonPressTime = 0; //Amount of time the button has been held down
unsigned long actualBtnState = 0; //The actual reading from the pin without noise filtering
void resetBtnCB(void *pvParameters)
{
pinMode(BUTTON_PIN, INPUT);
while (true)
{
// read the state of the switch into a local variable:
int reading = digitalRead(BUTTON_PIN);
actualBtnState = reading;
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState)
{
// reset the debouncing timer
lastDebounceTime = millis();
}
unsigned long timeSinceDebounce = millis() - lastDebounceTime;
if (timeSinceDebounce > debounceDelay)
{
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
buttonState = reading;
if (buttonState == HIGH)
{
buttonPressTime += timeSinceDebounce;
}
else if (buttonPressTime > 300)
{
buttonPressTime = 0;
// SUCCESS! Do something important here as we've held the button for x seconds
}
else
{
buttonPressTime = 0;
}
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
vTaskDelay(10);
}
}
void setup()
{
Serial.begin(115200);
xTaskCreate(resetBtnCB, "reset_button", 1024, NULL, 10, NULL);
}
void loop()
{
char debug[512];
sprintf(debug, "button state %u, lastD %u, buttonPressTime %u, actualBtnState %u, lastBtnState %u", buttonState, lastDebounceTime, buttonPressTime, actualBtnState, lastButtonState);
Serial.println(debug);
delay(50);
yield();
}

How to make an arduino serial loop (receive numbers continuously)

New to coding! I am trying to get text on my LED Matrix through serial data that is being sent in from processing.
My code works but the only problem is that though the serial data on processing is constant, the arduino code only reads the number once. This makes it so that the text will not scroll all the way through. How do I loop a serial read on arduino?
Here is the relevant portion of my code:
void loop()
{
if (Serial.available() > 0)
{
int matrixPinState = Serial.read();
// stage = Serial.read();
// analogWrite(matrixPin, stage);
if (matrixPinState == 1)
{
matrix.fillScreen(0);
matrix.setCursor(x, 0);
matrix.print(F("Im kind"));
if (--x < -30)
{
x = matrix.width();
if (++pass >= 8) pass = 0;
matrix.setTextColor(colors[pass]);
}
matrix.show();
delay(30);
}
}
}
When a byte(or you call it character, a data that is 8 bit long) is fetched by uart block(the hardware), it is buffered to input buffer so that programmer can read and process it.
In your case, when you send a character, it is fetched and put to the buffer and when you read it there is no more byte available to read unless you send to new one.
In short, read the pin state once. You can do something like:
int matrixPinState = 0
void setup() {
// do all your setup settings first
while (Serial.available() < 0) {
// wait here for the input
delay(30);
}
// got your input, read it
matrixPinState = Serial.read();
}
void loop()
{
if (matrixPinState == 1)
{
matrix.fillScreen(0);
matrix.setCursor(x, 0);
matrix.print(F("Im kind"));
if (--x < -30)
{
x = matrix.width();
if (++pass >= 8) pass = 0;
matrix.setTextColor(colors[pass]);
}
matrix.show();
delay(30);
}
}

why does my serial print twice on Arduino IDE via Serial Monitor?

I have only put in one 'print command' however I get two print reads.
The programme drives two stepper motors.
The moveSteps value = 48
The motor stops briefly and print's '48' when the programme starts to run and then '48' again when the if is triggered, just before the programme ends.
Only one '48' should be printed. Any ideas why this happens?
/*
Precise movement with stop
Moves the robot 20mm forwards and 20mm backwards
Rob Miles (edited by Dileepa Ranawake)
April 2017
Version 1.0
*/
int motorDelay;
byte left1,left2,left3,left4;
byte right1,right2,right3,right4;
float wheelDiameter = 68.5;
float stepsPerRevolution = 512;
float mmsPerStep = (wheelDiameter * 3.1416) / stepsPerRevolution;
int moveCount;
int moveSteps; // number of steps the motor is to move
void leftForwards()
{
left1=7; left2=6; left3=5; left4=4;
}
void leftReverse()
{
left1=4; left2=5; left3=6; left4=7;
}
void rightForwards()
{
right1=8; right2=9; right3=10; right4=11;
}
void rightReverse()
{
right1=11; right2=10; right3=9; right4=8;
}
int calculateDistanceSteps(float distanceInMM)
{
return distanceInMM / mmsPerStep + 0.5;
}
void setup() {
leftForwards();
rightForwards();
pinMode(left1,OUTPUT);
pinMode(left2,OUTPUT);
pinMode(left3,OUTPUT);
pinMode(left4,OUTPUT);
digitalWrite(left1,HIGH);
pinMode(right1,OUTPUT);
pinMode(right2,OUTPUT);
pinMode(right3,OUTPUT);
pinMode(right4,OUTPUT);
digitalWrite(right1,HIGH);
motorDelay=1200;
moveCount=0;
moveSteps = calculateDistanceSteps(20);
Serial.begin(9800);
}
void loop() {
moveCount = moveCount + 1;
if (moveCount==moveSteps)
{
digitalWrite(left1,LOW);
digitalWrite(right1,LOW);
Serial.println(moveCount);
exit(0);
}
digitalWrite(left2,HIGH);
digitalWrite(right2,HIGH);
delayMicroseconds(motorDelay);
digitalWrite(left1,LOW);
digitalWrite(right1,LOW);
delayMicroseconds(motorDelay);
digitalWrite(left3,HIGH);
digitalWrite(right3,HIGH);
delayMicroseconds(motorDelay);
digitalWrite(left2,LOW);
digitalWrite(right2,LOW);
delayMicroseconds(motorDelay);
digitalWrite(left4,HIGH);
digitalWrite(right4,HIGH);
delayMicroseconds(motorDelay);
digitalWrite(left3,LOW);
digitalWrite(right3,LOW);
delayMicroseconds(motorDelay);
digitalWrite(left1,HIGH);
digitalWrite(right1,HIGH);
delayMicroseconds(motorDelay);
digitalWrite(left4,LOW);
digitalWrite(right4,LOW);
delayMicroseconds(motorDelay);
}
Serial Monitor prints out 4848
I have also noticed that just opening serial monitor makes the stepper motor move!
Using exit() with an Arduino is not standard. It basically disables all interrupts and enters an infinite loop. You could restructure your loop() like this to avoid it:
void loop()
{
// Still moving?
if (moveCount < moveSteps) {
moveCount = moveCount + 1;
// Move complete
if (moveCount == moveSteps)
{
digitalWrite(left1,LOW);
digitalWrite(right1,LOW);
Serial.println(moveCount);
}
else {
digitalWrite(left2,HIGH);
digitalWrite(right2,HIGH);
//etc.....
}
}
}
Also, your loop delays 1200µs 8x. That's only 1200 × 8 = 9600 µs = 9.6 ms. If moveSteps = 48 then the entire loop will only take 460.8 ms. The program is running once before you open the serial monitor then a second time after. What happens if you push the reset button after you've opened the Serial Monitor?
Have you considered using the Arduino's built in Stepper Library?
Lastly, in the future, consider posting questions like this at [arduino.se].

Microcontroller - Button 'holding down' listener

I am working with a Texas Instruments LauncherPad MSP432 P401R and Energia.
I am trying to write a small program that counts the times I press button2 while I keep button1 pressed down.
int push1_listener = -1;
int push2_listener = -1;
int digit = 0;
void setup() {
Serial.begin(9600);
pinMode(PUSH1, INPUT_PULLUP);
pinMode(PUSH2, INPUT_PULLUP);
}
void loop() {
push1_listener = digitalRead(PUSH1);
push2_listener = digitalRead(PUSH2);
while(push1_listener == 0) {
if(push2_listener == 0) {
digit++;
delay(200);
Serial.print("btn2");
}
Serial.print("btn1");
}
}
The program goes into the while loop, I can see the "btn1" in the Serial console. However the program does not go into the if case.
Can somebody help me?
Your code reads the status of both push buttons once before entering the while loop. Then it never reads the push button status within the while loop. So the value of the push button variables will never change within the while loop. You need to re-read the push button status repeatedly within the while loop.
Maybe something like this:
while ((push1_listener = digitalRead(PUSH1)) == 0) {
push2_listener = digitalRead(PUSH2);
if (push2_listener == 0) {
...
}
...
}