Microchip C18 send data to Terminal as numeric - microchip

I am working on a project on which i need to send data over USART to terminal.
I need to display the data as the numeric value (0-255) of the char (which collected from the EEPROM
i have managed to send the char as is to the terminal (using Putty or TerMite)
My problem starts where the value of the char is non-printable
That's why i will need to convert the value of the char to numeric
Example: when the data acquired from the EEPROM is 0x31 my routine will send '1' but i will need to send '049' or '49' to the terminal
void SendToSer(void) {
unsigned char Looper;
for (Looper=EEPROM_START;Looper<EEPROM_END;Looper++){
ReadEEPROM(Looper); //returns ReadResult
Write1USART((char) ReadResult); //Sends the ASCII
ClrWdt();
}
}
Thanks,

The sprintf as jolati suggested can be a good work horse in some situations or, even better, snprintf if it is available for your version of C18. Both routines follow the standard printf formatting (ex. https://en.wikipedia.org/wiki/Printf_format_string).
#include "stdio.h"
void main() {
char buffer[80];
unsigned char len, number = 152;
// Write at most 80 bytes to our buffer
len = snprintf(buffer, 80, "sprintf string, heres a number: %d", number);
// buffer now contains our string, len is the number of bytes written
// or
len = printf(buffer, "... %d",number);
}

Thanks , I've decided to take it the long way......
Here's what i've done is:
Manipulated the int value of the char to 3 new char
(i.e.) 243 became 3 chars - 50,52,51 (the ASCII of the digits)
(maybe its long and lame but it works like a charm)
heres the script....
void ConvertToNumeric(unsigned char IsValue, unsigned int LineNumber){
unsigned int SourceInt;
ClrWdt();
if (IsValue == 1){
SourceInt = (int) ReadResult;
}else{
SourceInt = (int) LineNumber;
LineNumber++;
}
ClrWdt();
switch (SourceInt/100){
case 2 : FirstChar = 50; SourceInt = SourceInt - 200; break;
case 1 : FirstChar = 49; SourceInt = SourceInt - 100; break;
case 0: FirstChar = 48; break;
}
switch (SourceInt/10){
case 9 :SecondChar = 57; SourceInt = SourceInt - 90; break;
case 8 :SecondChar = 56; SourceInt = SourceInt - 80; break;
case 7 :SecondChar = 55; SourceInt = SourceInt - 70; break;
case 6 :SecondChar = 54; SourceInt = SourceInt - 60; break;
case 5 :SecondChar = 53; SourceInt = SourceInt - 50; break;
case 4 :SecondChar = 52; SourceInt = SourceInt - 40; break;
case 3 :SecondChar = 51; SourceInt = SourceInt - 30; break;
case 2 :SecondChar = 50; SourceInt = SourceInt - 20; break;
case 1 :SecondChar = 49; SourceInt = SourceInt - 10; break;
case 0 :SecondChar = 48; break;
}
switch (SourceInt){
case 9: ThirdChar= 57; break;
case 8: ThirdChar= 56; break;
case 7: ThirdChar= 55; break;
case 6: ThirdChar= 54; break;
case 5: ThirdChar= 53; break;
case 4: ThirdChar= 52; break;
case 3: ThirdChar= 51; break;
case 2: ThirdChar= 50; break;
case 1: ThirdChar= 49; break;
case 0: ThirdChar= 48; break;
}
ResultInChars[0] = FirstChar;
ResultInChars[1] = SecondChar;
ResultInChars[2] = ThirdChar;
ResultInChars[3] = ' ';
ResultInChars[4] = NULL;
ResultInChars[5] = NULL;
ResultInChars[6] = NULL;
}
later i have used puts1USART with an array containing 3 above chars (FirstChar, SecondChar & ThirdChar)
i've also added a "lineNumber" before every 4 values and CrLf after the forth value
and it has resulted an output looks like that.....
output to terminal in Putty over Serial port
and its working......
thanks for your help
I would apriciate your suggestions,
Guy

Related

ESP32 Task watchdog got triggered using ESP IDF

We need to read ADC module over I2C continuously 20 times to get stable values of ADC.
We have created a task for it, but code stop working in couple of min showing below error.
E (1925655) task_wdt: Task watchdog got triggered. The following tasks did not r
eset the watchdog in time:
E (1925655) task_wdt: - IDLE (CPU 0)
E (1925655) task_wdt: Tasks currently running:
E (1925655) task_wdt: CPU 0: esp_timer
We are not getting any exact solution for our error. Below is the task espfor reference.
void Hal_Read_Average_Voltage_For_TLA202x (void *pvParameters)
{
float read_value = 0, bigger_value = 0, voltage = 0;
while(1)
{
Hal_TLA2024_Re_Initialize ();
{
for (int count1 = 0; count1 < 20; count1++)
{
voltage = readVoltage (); //Performs I2C register read
if (voltage > bigger_value)
{
bigger_value = voltage;
}
vTaskDelay (1);
}
read_value += bigger_value;
bigger_value = 0;
}
ESP_LOGE(TAG, "ADC Highest Value = %f\n", (read_value));
read_value = 0;
bigger_value = 0;
voltage = 0;
vTaskDelay (300 / portTICK_PERIOD_MS);
}
}
float readVoltage (void)
{
int16_t raw_voltage;
uint16_t u16TempRead = 0;
uint8_t u8TempRead[2] = { 0, 0 };
uint8_t u8TempAddress = TLA202x_DATA_REG;
Hal_I2C_Read_Register (TLA202x_I2CADDR_DEFAULT, u8TempAddress, u8TempRead, 2, 1);
u16TempRead = u8TempRead[1] | (u8TempRead[0] << 8);
raw_voltage = u16TempRead;
// this will read the sign bit correctly, but shifting will move the bit out
// of the msbit
if (raw_voltage & 0x8000)
{
raw_voltage >>= 4;
raw_voltage |= 0x8000;
}
else
{
raw_voltage >>= 4;
}
switch (current_range)
{
case TLA202x_RANGE_6_144_V:
voltage = raw_voltage *= 3;
break;
case TLA202x_RANGE_4_096_V:
voltage = raw_voltage *= 2;
break;
case TLA202x_RANGE_2_048_V:
voltage = raw_voltage *= 1;
break;
case TLA202x_RANGE_1_024_V:
voltage = raw_voltage *= 0.5;
break;
case TLA202x_RANGE_0_512_V:
voltage = raw_voltage *= 0.25;
break;
case TLA202x_RANGE_0_256_V:
voltage = raw_voltage *= 0.125;
break;
}
voltage /= 1000.0; // mV =>V
return voltage;
}
void Hal_I2C_Read_Register (uint32_t slave_address, int register_address, uint8_t read_data_buffer[],
uint8_t read_buffer_length, uint8_t write_buffer_length)
{
i2c_cmd_handle_t cmd;
DATA_READ: cmd = i2c_cmd_link_create ();
i2c_master_start (cmd);
if (register_address != -1)
{
i2c_master_write_byte (cmd, slave_address << 1 | I2C_MASTER_WRITE,
ACK_CHECK_EN);
i2c_master_write_byte (cmd, register_address, ACK_CHECK_EN);
i2c_master_start (cmd);
}
i2c_master_write_byte (cmd, slave_address << 1 | I2C_MASTER_READ,
ACK_CHECK_EN);
if (read_buffer_length > 1)
{
i2c_master_read (cmd, read_data_buffer, read_buffer_length - 1, ACK_VAL);
}
i2c_master_read_byte (cmd, read_data_buffer + read_buffer_length - 1,
NACK_VAL);
i2c_master_stop (cmd);
esp_err_t ret = i2c_master_cmd_begin (I2C_NUM_0, cmd, 1000/ portTICK_RATE_MS);
i2c_cmd_link_delete (cmd);
if (ret == ESP_OK)
{
}
else if (ret == ESP_ERR_TIMEOUT)
{
// ESP_LOGW(TAG, "Bus is busy");
}
else
{
ESP_LOGW(TAG, "Read failed %d", ret);
goto DATA_READ;
}
}
We are having 2 more thread running on same priority.
If we remove the for loop in the above thread then there is no WDT error.
Updated ESP-IDF version to 4.4 and it solved this issue.

First led of WS2812B starts to light when the code enters the for loop

I'am working on this project, it should be a light for a carport. There are two ways to turn the light on, via motion sensor or via a switch. The Led strip starts to turn on one led after another. It will stay on for a period of time and then a reversed animation starts and turns all LEDs to black. I'am using a for loop for this animation (it's the same one FastLed uses in the first light example). The error is only when the motion sensor is activate and while the for loop is running. I'am sorry for the bad integer names, could be confusing.
Thanks a lot!
Here is the Code:
(If you can't understand German,
- Bewegungsmelder = Motion sensor
- Schalter = Switch
// für die Leds
#define NUMfront_LEDS 150 //150 Leds
#define NUMinner_LEDS 35 //35 Leds
#define rightPIN 6 //Pin 6
#define leftPIN 5
#define innerrightPIN 8
#define innerleftPIN 7
#define CLOCK_PIN 13
// für die Schalter
#define schalter 2 //Pin 2
#define Bewegungsmelder 4 //Pin 4
int schalterval = 0;
int Bewegungsval = 0;
long Time = 0;
long Wait = 900000;
int On = 0;
CRGB leftLeds[NUMfront_LEDS];
CRGB rightLeds[NUMfront_LEDS];
CRGB innerleftLeds[NUMinner_LEDS];
CRGB innerrightLeds[NUMinner_LEDS];
void setup() {
// sanity check delay - allows reprogramming if accidently blowing power w/leds
Serial.begin(115200);
delay(2000);
FastLED.addLeds<WS2812B, rightPIN, RGB>(rightLeds, NUMfront_LEDS); // GRB ordering is typical
FastLED.addLeds<WS2812B, leftPIN, RGB>(leftLeds, NUMfront_LEDS);
FastLED.addLeds<WS2812B, innerrightPIN, RGB>(innerrightLeds, NUMinner_LEDS);
FastLED.addLeds<WS2812B, innerleftPIN, RGB>(innerleftLeds, NUMinner_LEDS);
Time = millis();
}
void loop() {
Serial.println("----------------------------------------------");
Serial.print(Wait);
Serial.print("----");
Serial.print(millis());
Bewegungsval = digitalRead(Bewegungsmelder);
schalterval = digitalRead(schalter);
Serial.println(Bewegungsval);
Serial.println(schalterval);
Serial.println("Space");
Schalter:
if (digitalRead(schalter) == 1) {
On = 0;
for (int blackLed = NUMfront_LEDS; blackLed > -1; blackLed = blackLed - 1) {
leftLeds[blackLed] = CRGB::White;
rightLeds[blackLed] = CRGB::White;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::White);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::White);
//Leds aus
//Carport aussen
while (digitalRead(schalter) == 1) {
}
for (int whiteLed = 0; whiteLed < NUMfront_LEDS; whiteLed = whiteLed + 1) {
leftLeds[whiteLed] = CRGB::Black;
rightLeds[whiteLed] = CRGB::Black;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::Black);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::Black);
FastLED.show();
}
else if (Bewegungsval == 1) {
//Carport aussen
if (On == 1) {
goto Skip;
}
for (int blackLed = NUMfront_LEDS; blackLed > -1; blackLed = blackLed - 1) {
leftLeds[blackLed] = CRGB::White;
rightLeds[blackLed] = CRGB::White;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::White);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::White);
FastLED.show();
//Leds aus
On = 1;
Skip:
Time = millis();
Wait = Time + 10000; // + 5min. 300000
Bewegungsval = digitalRead(Bewegungsmelder);
goto Schalter;
}
Time = millis();
if (Time >= Wait) {
On = 0;
for (int whiteLed = 0; whiteLed < NUMfront_LEDS; whiteLed = whiteLed + 1) {
leftLeds[whiteLed] = CRGB::Black;
rightLeds[whiteLed] = CRGB::Black;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::Black);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::Black);
}
}```
Although fluent in German the program structure is alittle chaotic. Since we are in C++
you should not use goto
Since to my understanding the light routines for switch and IR are the same this code should only exist once
Your routine for measuring time is not rollover safe see blinkwithoutdelay example how todo
So clean the code up by using the following structure:
unsigned long startTime = 0;
unsigned long myTimer = 10000;// 10 sec
bool lightIsOn = false;
setup(){....}
loop(){
....
// We check wether switch or IR are triggerd AND we are not already in a light sequence
if ((digitalRead(schalter) == 1 || Bewegungsval == 1) && lightIsOn == false) {
lightIsOn = true; // change state so we know that a light sequence is running
startTime = millis(); // reset the timer
}
// this part runs as long lighIsOn == true and time is not up
if(millis() - startTime <= myTimer && lighIsOn == true){
// Carport aussen
your light sequence .....
}
// Here we run the time is up sequence
if(millis() - startTime > myTimer && lighIsOn == true) { // rollover safe
light sequence for time is up
........
lightIsOn = false; // change state so we know that a light sequence is over
}
}
This technique is called finite state machine there is no "jumping around" via goto.
If you need more states you just expand the sequence - there is no else because eg in the last two combined if statements we check for lightIsON == true ==> else would mean lightIsON == false in the second which makes no sense here as we only differentiate these to states by time.
Please never use goto in object oriented programming it makes your code unreadable and untraceable. Rewrite the program and if there are "new" problems edit here or open a new question

Unable to execute interrupt function

Using Mplab ide 5.10 and xc8 compiler for the pic18f4550 I am unable to get the code to get into the interrupt function the goal is to get J to count up in the background until something trigger it to output a value in the lcd. Currently only the lcd display the first message and using ICD 3 the value of J does not change and does not look like the program runs the interrupt function at all
#define _XTAL_FREQ 48000000
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include "lcd.h"
unsigned char j, output = 0, i, outchar;
char buffer[2] = " ";
char Message[ ] = "Hands Position ";
void interrupt timer0_isr();
void lcd_write_cmd(unsigned char cmd);
void lcd_write_data(unsigned char data);
void lcd_strobe(void); // Generate the E pulse
void lcd_init(void);
void interrupt timer0_ISR() // Timer0 Interrupt Service Routine (ISR)
{
if (INTCONbits.TMR0IF) // TMR0IF:- Timer0 Overflow Interrupt Flag Bit
{
TMR0H = 0x48; // Timer0 start value = 0x48E5 for 1 second
TMR0L = 0xE5;
PORTCbits.RC1 = !PORTCbits.RC1; /* external timing check - toggle every 1ms */
if (j <= 4) { //limit up to 7
j++; // Increase count by 1
PORTB = j; // Output to Demultiplexer
} else {
j = 0; // Reset count aftwr it hit 7
PORTB = j; // Output to Demultiplexer
}
INTCONbits.TMR0IF = 0; // Reset TMR0IF at interrupt end
}
}
void main(void) // Main Function
{
ADCON1 = 0x0F;
CMCON = 0x07;
RCONbits.IPEN = 1; // Bit7 Interrupt Priority Enable Bit
INTCONbits.GIEH = 1; // Bit7 Global Interrupt Enable bit
INTCONbits.GIEL = 0; /* turn on low & high interrupts */
T0CONbits.TMR0ON = 1; // Turn on timer
T0CON = 0b00000111; // bit7:0 Stop Timer0
// bit6:0 Timer0 as 16 bit timer
// bit5:0 Clock source is internal
// bit4:0 Increment on lo to hi transition on TOCKI pin
// bit3:0 Prescaler output is assigned to Timer0
// bit2-bit0:111 1:256 prescaler
INTCON2 = 0b10000100; // bit7 :PORTB Pull-Up Enable bit
// 1 All PORTB pull-ups are disabled
// bit2 :TMR0 Overflow Int Priority Bit
// 1 High Priority
TMR0H = 0x48; // Initialising TMR0H
TMR0L = 0xE5; // Initialising TMR0L for 1 second interrupt
INTCONbits.TMR0IE = 1; // bit5 TMR0 Overflow Int Enable bit
INTCONbits.TMR0IF = 0; // bit2 TMR0 Overflow Int Flag bit
// 0 TMR0 register did not overflow
TRISC = 0; /* all outputs */
TRISAbits.TRISA5 = 1; // RA5 is the check for signal from input Multiplexer.
TRISAbits.TRISA0 = 0; // RA0, RA1 & RA2 output to arduino
TRISAbits.TRISA1 = 0;
TRISAbits.TRISA2 = 0;
TRISD = 0x00; // PortD connects to Demultiplexer
TRISB = 0;
lcd_init(); // LCD init
lcd_write_cmd(0x80); // Cursor set at line 1 positon 1
for (i = 0; i < 16; i++) {
outchar = Message[i]; // Store Message in outchar
lcd_write_data(outchar); // Display Message
}
__delay_ms(100);
PORTD = 0x00; // Clear PortD
PORTB = 0;
j = 0; // Start count from 0
while (1) // Main Process
{
if (PORTAbits.RA5 == 1) { // If RA3 detect a signal
switch (j) { // Switch case to determine hand position & output to RA0, RA1 & RA2 to transmit to arduino
case(0):
output = 10;
PORTAbits.RA0 = 0;
PORTAbits.RA1 = 0;
PORTAbits.RA2 = 0;
break;
case(1):
output = 20;
PORTAbits.RA0 = 1;
PORTAbits.RA1 = 0;
PORTAbits.RA2 = 0;
break;
case(2):
output = 30;
PORTAbits.RA0 = 0;
PORTAbits.RA1 = 1;
PORTAbits.RA2 = 0;
break;
case(3):
output = 40;
PORTAbits.RA0 = 1;
PORTAbits.RA1 = 1;
PORTAbits.RA2 = 0;
break;
case(4):
output = 50;
PORTAbits.RA0 = 0;
PORTAbits.RA1 = 0;
PORTAbits.RA2 = 1;
break;
}
lcd_write_cmd(0xC0); // Cursor set at line 2 positon 1
sprintf(buffer, "%d", output); // Convert numbers to character
for (i = 0; i < 2; i++)
lcd_write_data(buffer[i]); // Display Hand Position
}
}
}

'set' not declared? Adruino

I have zero experience with programming adruino but I have to test these robots for my job. I was told this code drives the robots foreword. When I run this code I get the error that 'set' is not declared in this scope. Help? Or let me know if this isn't even the right question to ask. Those libraries at the top are also with me, but I'm unsure if I need to post them to solve this particular problem.
#include <Lobotank.h>
#include <tank_Cwrap.h>
int temp_R=0;
int temp_L=0;
int c15=0;
void setup()
{
enableDebug();
//test sensors(1000);
set speed(125);
}
void loop()
{
update sensors();
int pattern = 0;
long rndm = random(0,10);
serial.println(rndm);
//serial.println(temp_L);
//serial.println(lf_left);
//serial.println(lf_mleft);
//serial.println(lf_mright);
//serial.println(lf_right);
if (lf_left>= 500)
pattern += 8;
if (lf_mleft >= 500)
pattern += 4;
if (lf_mright >= 500)
pattern += 2;
if (lf_right >= 500)
pattern += 1;
switch (pattern)
{
case 0:
if (temp_R ==1)
turnRight_hard();
else
turnAround_left()
break;
case 1:
turnRight_slight();
temp_R = 1;
break;
case 2:
turnRight_slight();
temp_R = 1;
break;
case 3:
delay(25);
turnRight_slight();
break;
case 6:
forward();
temp_R = 0;
c15 = 0;
break;
case 7: //turn right
turnRight_hard();
temp_R = 1;
break;
case 8:
turnleft_slight();
temp_R = 0;
break;
case 12:
delay(15);
turnLeft_slight();
break;
case 14: //turn left
turnLeft_hard();
break;
case 15:
delay(25);
if (rndm <= 5 && c15 <= 3)
turnleft_hard();
else
{
if (rndm >= 6 && c15 <= 3)
turnRight_hard();
else
{
if (c15 >= 5)
turnRight_hard();
else
{
if (c15>= 10)
stop();
}
}
}
c15++;
break;
}
This doesn't look like valid syntax:
set speed(125);
This looks like a function call, but functions can't have spaces in them. Maybe you meant one of these:
setspeed(125);
setSpeed(125);
set_speed(125);
Look in those .h files for a function similar to these, and make sure you call it with the correct name.

Trouble having terminal run program through bash for loop

#!/bin/bash
for i in {10..11}
do
./duffing -a 1 -b -1 -u 0.25 -w -1 -A 0.4 -t $i | ./stroboscopic > $i.data
done
The $i doesn't seem to work in the program parameter line but I get the data files. This is the error
error converting i to a double for max-time:
leftover characters: i
Bad input data
error converting i to a double for max-time:
leftover characters: i
Bad input data
This is where I parse arguments in duffing program :
void parse_args(int argc, char **argv, state_t *state, system_t *system,
simulation_t *simulation, int *read_initial, int *print_final)
{
int ch;
duffing_state_t *duffing = (duffing_state_t *)system->dx_dt_state;
double dtemp;
size_t i;
while (1) {
ch = getopt_long(argc, argv, short_options, long_options, NULL);
if (ch == -1)
break;
switch(ch) {
case 'd':
simulation->dt = safe_strtod(optarg, "time-step");
break;
case 't':
simulation->t_max = safe_strtod(optarg, "max-time");
break;
case 'T':
duffing->T = safe_strtod(optarg, "transient-time");
break;
case 'x':
state->x[0] = safe_strtod(optarg, "x0");
break;
case 'v':
state->x[1] = safe_strtod(optarg, "v0");
break;
case 'm':
system->m = safe_strtod(optarg, "mass");
break;
case 'a':
duffing->a = safe_strtod(optarg, "alpha");
break;
case 'b':
duffing->b = safe_strtod(optarg, "beta");
break;
case 'u':
duffing->u = safe_strtod(optarg, "mu");
break;
case 'w':
duffing->w = safe_strtod(optarg, "omega");
break;
case 'A':
duffing->A = safe_strtod(optarg, "amplitude");
break;
case 'E':
simulation->step_fn = &euler_step;
break;
case 'M':
simulation->step_fn = &midpoint_step;
break;
case 'R':
simulation->step_fn = &rk4_step;
break;
case 'i':
*read_initial = 1;
break;
case 'f':
*print_final = 1;
break;
case '?':
exit(EXIT_FAILURE);
default:
fprintf(stderr, "?? getopt returned character code 0%o ??\n", ch);
}
}
/* convert input from periods to seconds */
simulation->t_max *= 2*M_PI / duffing->w;
duffing->T *= 2*M_PI / duffing->w;
return;
}
I have ran the program straight from the terminal with the -t 10 so I'm pretty confused why the program is refusing to accept the input from the script.

Resources